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
5c5ac118797daf1cc64df7b8b0f9c2c3a17b9590
9,723
hpp
C++
include/libndgpp/net/basic_ipv4_address.hpp
goodfella/libndgpp
2e3d4b993a04664905c1e257fb2af3a5faab5296
[ "MIT" ]
null
null
null
include/libndgpp/net/basic_ipv4_address.hpp
goodfella/libndgpp
2e3d4b993a04664905c1e257fb2af3a5faab5296
[ "MIT" ]
null
null
null
include/libndgpp/net/basic_ipv4_address.hpp
goodfella/libndgpp
2e3d4b993a04664905c1e257fb2af3a5faab5296
[ "MIT" ]
null
null
null
#ifndef LIBNDGPP_NET_BASIC_IPV4_ADDRESS_HPP #define LIBNDGPP_NET_BASIC_IPV4_ADDRESS_HPP #include <cstdint> #include <array> #include <ostream> #include <stdexcept> #include <string> #include <type_traits> #include <libndgpp/error.hpp> #include <libndgpp/net/ipv4_array.hpp> namespace ndgpp { namespace net { template <uint32_t Min, uint32_t Max> struct basic_ipv4_address_validator { constexpr bool operator () (uint32_t value) { if (value < Min || value > Max) { throw ndgpp_error(std::out_of_range, "supplied address out of range"); } return true; } }; template <> struct basic_ipv4_address_validator<0, 0xffffffff> { constexpr bool operator () (uint32_t value) noexcept { return true; } }; /** IPv4 address value type * * @tparam Min The minimum address value in network byte order * @tparam Max The maximum address value in network byte order * * @par Move Semantics * Move operations behave just like copy operations */ template <uint32_t Min = 0, uint32_t Max = 0xffffffff> class basic_ipv4_address final { public: using value_type = ndgpp::net::ipv4_array; /// The minimum address value in network byte order static constexpr uint32_t min = Min; /// The maximum address value in network byte order static constexpr uint32_t max = Max; using constrained_bool_type = std::conditional_t<Min == 0x0 && Max == 0xffffffff, std::false_type, std::true_type>; static constexpr bool constrained = constrained_bool_type::value; /// Constructs an address assigned to Min constexpr basic_ipv4_address() noexcept; template <uint32_t MinO, uint32_t MaxO> constexpr basic_ipv4_address(const basic_ipv4_address<MinO, MaxO> & other) noexcept(MinO >= Min && MaxO <= Max); /// Constructs an address assigned to the value provided constexpr basic_ipv4_address(const value_type value) noexcept(!constrained); /** Constructs an address from an unsigned 32 bit integer * * The parameter's value is mapped to the address octet like * so: * * address[0] = (value >> 24) & 0xff000000; * address[1] = (value >> 16) & 0x00ff0000; * address[2] = (value >> 8) & 0x0000ff00; * address[3] = value & 0x000000ff; * * @param An unsigned 32 bit integer */ explicit constexpr basic_ipv4_address(const uint32_t value) noexcept(!constrained); /** Constructs an address from a string * * @param value A string representing an IP address in dotted * quad notation. The string can be optionally * terminated by a colon. */ explicit basic_ipv4_address(const std::string & value); basic_ipv4_address & operator = (const basic_ipv4_address & value) noexcept; /// Assignes the address based on the value_type value basic_ipv4_address & operator = (const value_type value) noexcept(!constrained); /// Assignes the address based on the passed in unsigned 32 bit value basic_ipv4_address & operator = (const uint32_t value) noexcept (!constrained); /// Assignes the address based on the passed in dotted quad string value basic_ipv4_address & operator = (const std::string & value); void swap(basic_ipv4_address & other) noexcept; constexpr uint8_t operator[] (const std::size_t index) const noexcept; constexpr ndgpp::net::ipv4_array value() const noexcept; /** Returns the address as an unsigned 32 bit integer * * The address is mapped to the value like so: * * addr[0] << 24 | addr[1] << 16 | addr[2] << 8 | addr[3] */ constexpr uint32_t to_uint32() const noexcept; /// Returns the address as a dotted quad string std::string to_string() const; private: ndgpp::net::ipv4_array value_ = {ndgpp::net::make_ipv4_array(Min)}; }; template <uint32_t Min, uint32_t Max> constexpr basic_ipv4_address<Min, Max>::basic_ipv4_address() noexcept = default; template <uint32_t Min, uint32_t Max> template <uint32_t MinO, uint32_t MaxO> constexpr basic_ipv4_address<Min, Max>::basic_ipv4_address(const basic_ipv4_address<MinO, MaxO> & addr) noexcept(MinO >= Min && MaxO <= Max): value_ {addr.value()} { if (!(MinO >= Min && MaxO <= Max)) { basic_ipv4_address_validator<Min, Max> {} (this->to_uint32()); } } template <uint32_t Min, uint32_t Max> constexpr basic_ipv4_address<Min, Max>::basic_ipv4_address(const ndgpp::net::ipv4_array value) noexcept(!basic_ipv4_address::constrained): value_ {value} { basic_ipv4_address_validator<Min, Max> {} (this->to_uint32()); } template <uint32_t Min, uint32_t Max> constexpr basic_ipv4_address<Min, Max>::basic_ipv4_address(const uint32_t value) noexcept(!basic_ipv4_address::constrained): value_ {ndgpp::net::make_ipv4_array(value)} { basic_ipv4_address_validator<Min, Max> {} (value); } template <uint32_t Min, uint32_t Max> basic_ipv4_address<Min, Max>::basic_ipv4_address(const std::string & value): value_ {ndgpp::net::make_ipv4_array(value)} { basic_ipv4_address_validator<Min, Max> {} (this->to_uint32()); } template <uint32_t Min, uint32_t Max> basic_ipv4_address<Min, Max> & basic_ipv4_address<Min, Max>::operator = (const basic_ipv4_address &) noexcept = default; template <uint32_t Min, uint32_t Max> basic_ipv4_address<Min, Max> & basic_ipv4_address<Min, Max>::operator = (const ndgpp::net::ipv4_array rhs) noexcept(!basic_ipv4_address::constrained) { this->value_ = rhs; basic_ipv4_address_validator<Min, Max> {} (this->to_uint32()); return *this; } template <uint32_t Min, uint32_t Max> basic_ipv4_address<Min, Max> & basic_ipv4_address<Min, Max>::operator = (const uint32_t rhs) noexcept(!basic_ipv4_address::constrained) { this->value_ = ndgpp::net::make_ipv4_array(rhs); basic_ipv4_address_validator<Min, Max> {} (rhs); return *this; } template <uint32_t Min, uint32_t Max> basic_ipv4_address<Min, Max> & basic_ipv4_address<Min, Max>::operator = (const std::string & rhs) { this->value_ = ndgpp::net::make_ipv4_array(rhs); basic_ipv4_address_validator<Min, Max> {} (this->to_uint32()); return *this; } template <uint32_t Min, uint32_t Max> void basic_ipv4_address<Min, Max>::swap(basic_ipv4_address & other) noexcept { std::swap(this->value_, other.value_); } template <uint32_t Min, uint32_t Max> inline constexpr uint8_t basic_ipv4_address<Min, Max>::operator [] (const std::size_t index) const noexcept { return this->value_[index]; } template <uint32_t Min, uint32_t Max> inline constexpr ndgpp::net::ipv4_array basic_ipv4_address<Min, Max>::value() const noexcept { return this->value_; } template <uint32_t Min, uint32_t Max> inline constexpr uint32_t basic_ipv4_address<Min, Max>::to_uint32() const noexcept { return ndgpp::net::to_uint32(this->value_); } template <uint32_t Min, uint32_t Max> inline std::string basic_ipv4_address<Min, Max>::to_string() const { return ndgpp::net::to_string(this->value_); } template <uint32_t Min, uint32_t Max> void swap(basic_ipv4_address<Min, Max> & lhs, basic_ipv4_address<Min, Max> & rhs) { lhs.swap(rhs); } template <uint32_t Min, uint32_t Max> inline std::ostream & operator <<(std::ostream & stream, const basic_ipv4_address<Min, Max> address) { stream << static_cast<uint16_t>(address[0]); for (std::size_t i = 1; i < std::tuple_size<typename ndgpp::net::basic_ipv4_address<Min, Max>::value_type>::value; ++i) { stream.put('.'); stream << static_cast<uint16_t>(address[i]); } return stream; } template <uint32_t Min, uint32_t Max> inline bool operator ==(const basic_ipv4_address<Min, Max> lhs, const basic_ipv4_address<Min, Max> rhs) { return lhs.value() == rhs.value(); } template <uint32_t Min, uint32_t Max> inline bool operator !=(const basic_ipv4_address<Min, Max> lhs, const basic_ipv4_address<Min, Max> rhs) { return !(lhs == rhs); } template <uint32_t Min, uint32_t Max> inline bool operator <(const basic_ipv4_address<Min, Max> lhs, const basic_ipv4_address<Min, Max> rhs) { return lhs.value() < rhs.value(); } template <uint32_t Min, uint32_t Max> inline bool operator >=(const basic_ipv4_address<Min, Max> lhs, const basic_ipv4_address<Min, Max> rhs) { return !(lhs < rhs); } template <uint32_t Min, uint32_t Max> inline bool operator >(const basic_ipv4_address<Min, Max> lhs, const basic_ipv4_address<Min, Max> rhs) { return rhs < lhs; } template <uint32_t Min, uint32_t Max> inline bool operator <=(const basic_ipv4_address<Min, Max> lhs, const basic_ipv4_address<Min, Max> rhs) { return !(rhs < lhs); } }} #endif
33.297945
145
0.62851
goodfella
5c5d4896cdef7918d1b9b1b525726cbddbafd513
597
hxx
C++
code/src/Profile.hxx
Angew/AnyBak
66146b4b94e18ce7d215f1132752d33e4cddf1ed
[ "MIT" ]
null
null
null
code/src/Profile.hxx
Angew/AnyBak
66146b4b94e18ce7d215f1132752d33e4cddf1ed
[ "MIT" ]
null
null
null
code/src/Profile.hxx
Angew/AnyBak
66146b4b94e18ce7d215f1132752d33e4cddf1ed
[ "MIT" ]
null
null
null
#pragma once #include "RuleSet.hh" #include "VolumeRegistry.hh" #include "VolumeSet.hh" #include <memory> class Profile { public: const RuleSet& getRuleSet() const { return getRuleSet_impl(); } RuleSet& getRuleSet() { return getRuleSet_impl(); } const VolumeRegistry& getVolumeRegistry() const { return getVolumeRegistry_impl(); } VolumeRegistry& getVolumeRegistry() { return getVolumeRegistry_impl(); } virtual bool createVolumes(VolumeSet &volumes) const = 0; protected: virtual RuleSet& getRuleSet_impl() const = 0; virtual VolumeRegistry& getVolumeRegistry_impl() const = 0; };
22.961538
85
0.755444
Angew
5c5e6063275e112ec3c117a6c97cc9442bf36d9b
996
cpp
C++
leetcode/1014.cpp
laiyuling424/LeetCode
afb582026b4d9a4082fdb99fc65b437e55d1f64d
[ "Apache-2.0" ]
null
null
null
leetcode/1014.cpp
laiyuling424/LeetCode
afb582026b4d9a4082fdb99fc65b437e55d1f64d
[ "Apache-2.0" ]
null
null
null
leetcode/1014.cpp
laiyuling424/LeetCode
afb582026b4d9a4082fdb99fc65b437e55d1f64d
[ "Apache-2.0" ]
null
null
null
// // Created by 赖於领 on 2021/9/1. // #include <vector> #include <iostream> using namespace std; //最佳观光组合 class Solution { public: int maxScoreSightseeingPair(vector<int> &values) { // if (values.size() == 2) { // return values[0] + values[1] - 1; // } //values[i]+values[j]+i-j = int n = values.size(); vector<int> r(n, 0); vector<int> sums(n, 0); r[0] = values[0]; sums[0] = INT_MIN; for (int i = 1; i < n; i++) { r[i] = max(r[i - 1], values[i - 1]) - 1; sums[i] = max(sums[i - 1], r[i] + values[i]); cout << "i is " << i << " " << r[i] << " " << sums[i] << endl; } return sums[n - 1]; } }; //int main() { // // Solution *solution = new Solution(); //// vector<int> a = {8, 1, 5, 2, 6}; // vector<int> a = {1, 2}; //// vector<int> a = {1, 3, 5}; // cout << solution->maxScoreSightseeingPair(a) << endl; // // return 0; //}
21.191489
78
0.447791
laiyuling424
5c60f0151b28f916dc90688f5b7d0b866658f1ec
676
cpp
C++
demos/multiplatform/delay/source/main.cpp
SarahS16/SJSU-Dev2
47f9ddb7d3c3743f839b57f381bf979dd61d49ab
[ "Apache-2.0" ]
6
2020-06-20T23:56:42.000Z
2021-12-18T08:13:54.000Z
demos/multiplatform/delay/source/main.cpp
SarahS16/SJSU-Dev2
47f9ddb7d3c3743f839b57f381bf979dd61d49ab
[ "Apache-2.0" ]
153
2020-06-09T14:49:29.000Z
2022-01-31T16:39:39.000Z
demos/multiplatform/delay/source/main.cpp
SarahS16/SJSU-Dev2
47f9ddb7d3c3743f839b57f381bf979dd61d49ab
[ "Apache-2.0" ]
10
2020-08-02T00:55:38.000Z
2022-01-24T23:06:51.000Z
#include <cinttypes> #include <cstdint> #include "utility/log.hpp" #include "utility/time/time.hpp" int main() { sjsu::LogInfo("Delay Application Starting..."); sjsu::LogInfo("This demo prints a statement every second using Delay(1s)."); sjsu::LogInfo( "Notice that the uptime does not increase by 1 second but by a little " "more then that."); sjsu::LogInfo( "This is due to the fact that we delay for a whole second, but it takes " "time to print each statement."); int counter = 0; while (true) { sjsu::LogInfo( "[%d] Uptime = %" PRId64 "ns", counter++, sjsu::Uptime().count()); sjsu::Delay(1s); } return 0; }
23.310345
79
0.633136
SarahS16
5c63ad45055fc5b87ccc0f9aa9c7696d28857b5d
4,991
cc
C++
Source/BladeBase/source/graphics/RenderProperty.cc
OscarGame/blade
6987708cb011813eb38e5c262c7a83888635f002
[ "MIT" ]
146
2018-12-03T08:08:17.000Z
2022-03-21T06:04:06.000Z
Source/BladeBase/source/graphics/RenderProperty.cc
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
1
2019-01-18T03:35:49.000Z
2019-01-18T03:36:08.000Z
Source/BladeBase/source/graphics/RenderProperty.cc
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
31
2018-12-03T10:32:43.000Z
2021-10-04T06:31:44.000Z
/******************************************************************** created: 2011/12/21 filename: RenderProperty.cc author: Crazii purpose: *********************************************************************/ #include <BladePCH.h> #include <interface/public/graphics/RenderProperty.h> #include <interface/public/graphics/ITexture.h> namespace Blade { template class FixedArray<HRENDERPROPERTY,RPT_COUNT>; /************************************************************************/ /* */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// IRenderProperty* IRenderProperty::createProperty(RENDER_PROPERTY eProp) { switch(eProp) { case RPT_COLOR: return BLADE_NEW ColorProperty(); case RPT_COLORWIRTE: return BLADE_NEW ColorWriteProperty(); case RPT_FOG: return BLADE_NEW FogProperty(); case RPT_ALPHABLEND: return BLADE_NEW AlphaBlendProperty(); case RPT_DEPTH: return BLADE_NEW DepthProperty(); case RPT_STENCIL: return BLADE_NEW StencilProperty(); case RPT_SCISSOR: return BLADE_NEW ScissorProperty(); default: break; } assert(false); return NULL; } ////////////////////////////////////////////////////////////////////////// IRenderProperty* IRenderProperty::cloneProperty(IRenderProperty* prop) { if(prop == NULL) return NULL; switch(prop->getType()) { case RPT_COLOR: return BLADE_NEW ColorProperty( *static_cast<ColorProperty*>(prop) ); case RPT_COLORWIRTE: return BLADE_NEW ColorWriteProperty( *static_cast<ColorWriteProperty*>(prop) ); case RPT_FOG: return BLADE_NEW FogProperty( *static_cast<FogProperty*>(prop) ); case RPT_ALPHABLEND: return BLADE_NEW AlphaBlendProperty( *static_cast<AlphaBlendProperty*>(prop) ); case RPT_DEPTH: return BLADE_NEW DepthProperty( *static_cast<DepthProperty*>(prop) ); case RPT_STENCIL: return BLADE_NEW StencilProperty( *static_cast<StencilProperty*>(prop) ); case RPT_SCISSOR: return BLADE_NEW ScissorProperty( *static_cast<ScissorProperty*>(prop) ); default: break; } assert(false); return NULL; } /************************************************************************/ /* */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// bool RenderPropertySet::addProperty(const HRENDERPROPERTY& hProp) { if( hProp == NULL || this->hasProperty(hProp->getType())) return false; RENDER_PROPERTY eRP = hProp->getType(); if( eRP < RPT_COUNT ) { HRENDERPROPERTY& hTarget = mPropertyList[eRP]; assert(hTarget == NULL ); hTarget = hProp; mPropertyMask.raiseBitAtIndex(eRP); return true; } else return false; } ////////////////////////////////////////////////////////////////////////// bool RenderPropertySet::setProperty(const HRENDERPROPERTY& hProp) { if( hProp == NULL ) return false; RENDER_PROPERTY eRP = hProp->getType(); if( eRP < RPT_COUNT ) { mPropertyList[eRP] = hProp; mPropertyMask.raiseBitAtIndex(eRP); return true; } else return false; } ////////////////////////////////////////////////////////////////////////// bool RenderPropertySet::removeProperty(RENDER_PROPERTY eRP) { if( eRP < RPT_COUNT ) { HRENDERPROPERTY& hProp = mPropertyList[eRP]; hProp.clear(); mPropertyMask.clearBitAtIndex(eRP); return true; } else return false; } ////////////////////////////////////////////////////////////////////////// void RenderPropertySet::mergeProperties(const RenderPropertySet& mergeSource) { for(int i = RPT_BEGIN; i < RPT_COUNT; ++i) { RENDER_PROPERTY eProp = (RENDER_PROPERTY)i; if( mergeSource.hasProperty(eProp) ) this->setProperty(mergeSource.getProperty(eProp)); } //mCullMode = mergeSource.mCullMode; //FIXME: } ////////////////////////////////////////////////////////////////////////// const HRENDERPROPTYSET& RenderPropertySet::getDefaultRenderProperty() { static HRENDERPROPTYSET DEFAULT_PROPERTY; if( DEFAULT_PROPERTY == NULL ) { DEFAULT_PROPERTY.lock(); DEFAULT_PROPERTY.bind( BLADE_NEW RenderPropertySet() ); Lock::memoryBarrier(); DEFAULT_PROPERTY.unlock(); } return DEFAULT_PROPERTY; } /************************************************************************/ /* */ /************************************************************************/ const Sampler Sampler::DEFAULT; const Sampler Sampler::DEFAULT_RTT(TAM_CLAMP, TAM_CLAMP, TAM_CLAMP, TFM_LINEAR, TFM_LINEAR, TFM_LINEAR, 0.0f, 0.0f); const Sampler Sampler::DEFAULT_RTT_DEPTH(TAM_CLAMP, TAM_CLAMP, TAM_CLAMP, TFM_POINT, TFM_POINT, TFM_POINT, 0.0f, 0.0f); }//namespace Blade
31
120
0.530154
OscarGame
5c65d2b705eadf9e53f5d161593f3221b758eaa0
2,763
cpp
C++
src/ChunkHandlerSFNC.cpp
Peralex/pxgf
a4ea0ad5d2d2ff3b909782c22ef6488a0ac81662
[ "Apache-2.0" ]
1
2017-12-20T14:27:01.000Z
2017-12-20T14:27:01.000Z
src/ChunkHandlerSFNC.cpp
Peralex/pxgf
a4ea0ad5d2d2ff3b909782c22ef6488a0ac81662
[ "Apache-2.0" ]
null
null
null
src/ChunkHandlerSFNC.cpp
Peralex/pxgf
a4ea0ad5d2d2ff3b909782c22ef6488a0ac81662
[ "Apache-2.0" ]
null
null
null
// Copyright 2006 Peralex Electronics (Pty) Ltd // // 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. // LIBRARY INCLUDE FILES #include <cstring> #include "handlers/ChunkHandlerSFNC.h" #include "handlers/PxgfHandlerException.h" #include "SwapEndian.h" namespace pxgf { using namespace std; cChunkHandlerSFNC::cChunkHandlerSFNC() : m_pCallbackSFNCHandler(nullptr) { } void cChunkHandlerSFNC::registerCallbackHandler(cCallbackSFNC *pHandler) { m_pCallbackSFNCHandler = pHandler; } bool cChunkHandlerSFNC::processChunk(const vector<char> &vchData, bool bBigEndian) { // check that there is enough data for an even number of floats if(((vchData.size()) & 0x3) != 0) return false; if(m_pCallbackSFNCHandler == nullptr) { return true; } int64_t lTimestamp_ns = *(int64_t *)vchData.data(); int iLength = (vchData.size() - 8) / sizeof(float); //vector<float> vfIqData (iLength); m_vfIqData.resize(iLength); memcpy(&m_vfIqData[0], &vchData[8], iLength * sizeof(float)); if(cPXGWriterBase::getIsLocalBigEndian() != bBigEndian) { SWAP_INT64(lTimestamp_ns); for(vector<float>::iterator it = m_vfIqData.begin(); it != m_vfIqData.end(); it++) SWAP_FLOAT(*it); } m_pCallbackSFNCHandler->callbackSFNC(lTimestamp_ns, m_vfIqData); return true; } void cChunkHandlerSFNC::writeChunkSFNC(cPXGWriterBase &stream, int64_t lTimestamp_ns, const vector<float> &vfIqData) const { stream.writeChunkHeader(*this, 8 + vfIqData.size() * sizeof(float)); stream.writeInt64(lTimestamp_ns); stream.writeFloatArray(vfIqData); } void cChunkHandlerSFNC::repack(const cPackingSIQP &oInputPacking, const cPackingSIQP &oOutputPacking, const vector<float> &vfInputIQData, vector<float> &vfOutputData) { if(oInputPacking.equals(oOutputPacking)) { vfOutputData = vfInputIQData; return; } // check that there are an even number of elements if((vfInputIQData.size() & 0x1) != 0) throw cPxgfHandlerException("The length of vfInputIQData must be even."); // swap IQ data vfOutputData.resize(vfInputIQData.size()); for(unsigned uSample = 0; uSample < vfInputIQData.size(); uSample += 2) { vfOutputData[uSample] = vfInputIQData[uSample + 1]; vfOutputData[uSample + 1] = vfInputIQData[uSample]; } } }
32.892857
167
0.734347
Peralex
5c683a17d743c3a35d9e5f54c3197d497153624c
3,505
cpp
C++
Source/10.0.18362.0/ucrt/env/get_environment_from_os.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
2
2021-01-27T10:19:30.000Z
2021-02-09T06:24:30.000Z
Source/10.0.18362.0/ucrt/env/get_environment_from_os.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
null
null
null
Source/10.0.18362.0/ucrt/env/get_environment_from_os.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
1
2021-01-27T10:19:36.000Z
2021-01-27T10:19:36.000Z
// // get_environment_from_os.cpp // // Copyright (c) Microsoft Corporation. All rights reserved. // // Defines a pair of functions to get the environment strings from the operating // system. These functions copy the environment strings into a CRT-allocated // buffer and return a pointer to that buffer. The caller is responsible for // freeing the returned buffer (via _crt_free). // #include <corecrt_internal.h> #include <corecrt_internal_traits.h> #include <stdlib.h> namespace { struct environment_strings_traits { typedef wchar_t* type; static bool close(_In_ type p) throw() { FreeEnvironmentStringsW(p); return true; } static type get_invalid_value() throw() { return nullptr; } }; typedef __crt_unique_handle_t<environment_strings_traits> environment_strings_handle; } static wchar_t const* __cdecl find_end_of_double_null_terminated_sequence(wchar_t const* const first) throw() { wchar_t const* last = first; for (; *last != '\0'; last += wcslen(last) + 1) { } return last + 1; // Return the pointer one-past-the-end of the double null terminator } extern "C" wchar_t* __cdecl __dcrt_get_wide_environment_from_os() throw() { environment_strings_handle const environment(GetEnvironmentStringsW()); if (!environment) return nullptr; // Find the wchar_t const* const first = environment.get(); wchar_t const* const last = find_end_of_double_null_terminated_sequence(first); size_t const required_count = last - first; __crt_unique_heap_ptr<wchar_t> buffer(_malloc_crt_t(wchar_t, required_count)); if (!buffer) return nullptr; // Note that the multiplication here cannot overflow: memcpy(buffer.get(), environment.get(), required_count * sizeof(wchar_t)); return buffer.detach(); } extern "C" char* __cdecl __dcrt_get_narrow_environment_from_os() throw() { // Note that we call GetEnvironmentStringsW and convert to multibyte. The // GetEnvironmentStringsA function returns the environment in the OEM code // page, but we need the strings in ANSI. environment_strings_handle const environment(GetEnvironmentStringsW()); if (!environment.is_valid()) return nullptr; wchar_t const* const first = environment.get(); wchar_t const* const last = find_end_of_double_null_terminated_sequence(first); size_t const required_wide_count = last - first; #pragma warning(suppress:__WARNING_W2A_BEST_FIT) // 38021 Prefast recommends WC_NO_BEST_FIT_CHARS. size_t const required_narrow_count = static_cast<size_t>(__acrt_WideCharToMultiByte( CP_ACP, 0, environment.get(), static_cast<int>(required_wide_count), nullptr, 0, nullptr, nullptr)); if (required_narrow_count == 0) return nullptr; __crt_unique_heap_ptr<char> buffer(_malloc_crt_t(char, required_narrow_count)); if (!buffer) return nullptr; #pragma warning(suppress:__WARNING_W2A_BEST_FIT) // 38021 Prefast recommends WC_NO_BEST_FIT_CHARS. int const conversion_result = __acrt_WideCharToMultiByte( CP_ACP, 0, environment.get(), static_cast<int>(required_wide_count), buffer.get(), static_cast<int>(required_narrow_count), nullptr, nullptr); if (conversion_result == 0) return nullptr; return buffer.detach(); }
28.729508
109
0.694722
825126369
5c6fc2ea2c3eef41dd62d1afbe34ac4cbeea7a44
29,192
cpp
C++
Source/Core/BuildCommon/CDisneySceneBuildProcessor.cpp
schuttejoe/ShootyEngine
56a7fab5a479ec93d7f641bb64b8170f3b0d3095
[ "MIT" ]
81
2018-07-31T17:13:47.000Z
2022-03-03T09:24:22.000Z
Source/Core/BuildCommon/CDisneySceneBuildProcessor.cpp
schuttejoe/ShootyEngine
56a7fab5a479ec93d7f641bb64b8170f3b0d3095
[ "MIT" ]
2
2018-10-15T04:39:43.000Z
2019-12-05T03:46:50.000Z
Source/Core/BuildCommon/CDisneySceneBuildProcessor.cpp
schuttejoe/ShootyEngine
56a7fab5a479ec93d7f641bb64b8170f3b0d3095
[ "MIT" ]
9
2018-10-11T06:32:12.000Z
2020-10-01T03:46:37.000Z
//================================================================================================================================= // Joe Schutte //================================================================================================================================= #include "BuildCommon/CDisneySceneBuildProcessor.h" #include "BuildCommon/ImportMaterial.h" #include "BuildCommon/ModelBuildPipeline.h" #include "BuildCommon/BakeModel.h" #include "BuildCommon/BuildModel.h" #include "BuildCore/BuildContext.h" #include "SceneLib/SceneResource.h" #include "SceneLib/SubSceneResource.h" #include "Assets/AssetFileUtils.h" #include "UtilityLib/JsonUtilities.h" #include "UtilityLib/MurmurHash.h" #include "IoLib/Directory.h" #include "MathLib/FloatFuncs.h" #include "SystemLib/Logging.h" #include "SystemLib/MemoryAllocation.h" #include "SystemLib/CheckedCast.h" #include <rapidjson/document.h> #include <rapidjson/prettywriter.h> #include <rapidjson/stringbuffer.h> namespace Selas { #define CurveModelNameSuffix_ "_generatedcurves" struct ElementDesc { FilePathString file; int32 lightSetIndex; }; struct LightSetDesc { CArray<FilePathString> lightFiles; }; //============================================================================================================================= struct SceneFileData { CArray<FilePathString> cameraFiles; FilePathString iblFile; CArray<LightSetDesc*> lightsets; CArray<ElementDesc> elements; }; //============================================================================================================================= struct CurveSegment { uint64 startIndex; uint64 controlPointCount; }; //============================================================================================================================= struct CurveData { float widthTip; float widthRoot; float degrees; bool faceCamera; CArray<float3> controlPoints; CArray<CurveSegment> segments; Hash32 name; }; //============================================================================================================================= static FixedString256 ContentRoot(BuildProcessorContext* context) { FixedString256 root; root.Copy(context->source.name.Ascii()); char* addr = StringUtil::FindLastChar(root.Ascii(), '~'); if(addr == nullptr) { root.Clear(); } else { *(addr + 1) = '\0'; } return root; } //============================================================================================================================= static Error ParseArchiveFile(BuildProcessorContext* context, const FixedString256& root, const FilePathString& sourceId, SubsceneResourceData* subscene) { FilePathString filepath; AssetFileUtils::ContentFilePath(sourceId.Ascii(), filepath); ReturnError_(context->AddFileDependency(filepath.Ascii())); rapidjson::Document document; ReturnError_(Json::OpenJsonDocument(filepath.Ascii(), document)); uint modelCount = 0; for(const auto& objFileKV : document.GetObject()) { modelCount += objFileKV.value.GetObject().MemberCount(); } subscene->modelInstances.Reserve(subscene->modelInstances.Count() + modelCount); for(const auto& objFileKV : document.GetObject()) { cpointer objFile = objFileKV.name.GetString(); FilePathString instanceObjFile; FixedStringSprintf(instanceObjFile, "%s%s", root.Ascii(), objFile); AssetFileUtils::IndependentPathSeperators(instanceObjFile); uint meshIndex = subscene->modelNames.Add(instanceObjFile); const auto& element = objFileKV.value; for(const auto& instanceKV : element.GetObject()) { cpointer instanceName = instanceKV.name.GetString(); Instance modelInstance; modelInstance.index = meshIndex; if(Json::ReadMatrix4x4(instanceKV.value, modelInstance.localToWorld) == false) { return Error_("Failed to parse transform from instance '%s' in primfile '%s'", instanceName, filepath.Ascii()); } subscene->modelInstances.Add(modelInstance); } } return Success_; } //============================================================================================================================= static Error ParseControlPointsFile(BuildProcessorContext* context, cpointer path, CurveData* importedCurve) { FilePathString filepath; AssetFileUtils::ContentFilePath(path, filepath); ReturnError_(context->AddFileDependency(filepath.Ascii())); rapidjson::Document document; ReturnError_(Json::OpenJsonDocument(filepath.Ascii(), document)); uint totalControlPoints = 0; // -- Do a prepass to count the total number of control points uint segmentCount = document.Size(); for(const auto& curveElement : document.GetArray()) { uint controlPointCount = curveElement.Size(); totalControlPoints += controlPointCount; } importedCurve->controlPoints.Resize(totalControlPoints); importedCurve->segments.Resize(segmentCount); uint segmentIndex = 0; uint cpIndex = 0; for(const auto& curveElement : document.GetArray()) { uint controlPointCount = curveElement.Size(); importedCurve->segments[segmentIndex].startIndex = cpIndex; importedCurve->segments[segmentIndex].controlPointCount = controlPointCount; ++segmentIndex; for(const auto& controlPointElement : curveElement.GetArray()) { float3& controlPoint = importedCurve->controlPoints[cpIndex]; ++cpIndex; controlPoint.x = controlPointElement[0].GetFloat(); controlPoint.y = controlPointElement[1].GetFloat(); controlPoint.z = controlPointElement[2].GetFloat(); } } return Success_; } //============================================================================================================================= static void BuildCurveModel(CurveData* importedCurve, cpointer curveName, BuiltModel& curveModel) { uint controlPointCount = importedCurve->controlPoints.Count(); uint curveCount = importedCurve->segments.Count(); MakeInvalid(&curveModel.aaBox); uint curveIndex = 0; uint64 indexOffset = 0; curveModel.curveModelNameHash = MurmurHash3_x86_32(curveName, StringUtil::Length(curveName)); curveModel.curves.Resize(curveCount); curveModel.curveIndices.Reserve(controlPointCount + curveCount * 3); curveModel.curveVertices.Reserve(controlPointCount + curveCount * 2); float widthRoot = importedCurve->widthRoot; float widthTip = importedCurve->widthTip; for(uint segIndex = 0, segCount = importedCurve->segments.Count(); segIndex < segCount; ++segIndex) { const CurveSegment& segment = importedCurve->segments[segIndex]; CurveMetaData& curve = curveModel.curves[curveIndex++]; curve.indexOffset = CheckedCast<uint32>(curveModel.curveIndices.Count()); curve.indexCount = CheckedCast<uint32>(segment.controlPointCount - 1); for(uint cpScan = 0; cpScan < segment.controlPointCount - 1; ++cpScan) { curveModel.curveIndices.Add(CheckedCast<uint32>(indexOffset)); ++indexOffset; } indexOffset += 3; curveModel.curveVertices.Add(float4(importedCurve->controlPoints[segment.startIndex], widthRoot)); for(uint cpScan = 0; cpScan < segment.controlPointCount; ++cpScan) { float w = Lerp(widthRoot, widthTip, (float)cpScan / (float)(segment.controlPointCount - 1)); float3 cpPosition = importedCurve->controlPoints[segment.startIndex + cpScan]; IncludePosition(&curveModel.aaBox, cpPosition); curveModel.curveVertices.Add(float4(cpPosition, w)); } curveModel.curveVertices.Add(float4(importedCurve->controlPoints[segment.startIndex + segment.controlPointCount - 1], widthTip)); } } //============================================================================================================================= static Error ParseCurveElement(BuildProcessorContext* context, cpointer curveName, const FixedString256& root, const rapidjson::Value& element, SubsceneResourceData* subscene) { FilePathString curveFile; if(Json::ReadFixedString(element, "jsonFile", curveFile) == false) { return Error_("`jsonFile ` parameter missing from instanced primitives section"); } AssetFileUtils::IndependentPathSeperators(curveFile); CurveData curve; Json::ReadFloat(element, "widthTip", curve.widthTip, 1.0f); Json::ReadFloat(element, "widthRoot", curve.widthRoot, 1.0f); Json::ReadFloat(element, "degrees", curve.degrees, 1.0f); Json::ReadBool(element, "faceCamera", curve.faceCamera, false); FilePathString controlPointsFile; FixedStringSprintf(controlPointsFile, "%s%s", root.Ascii(), curveFile.Ascii()); FilePathString curveModelName; FixedStringSprintf(curveModelName, "%s%s%s", root.Ascii(), curveFile.Ascii(), CurveModelNameSuffix_); ReturnError_(ParseControlPointsFile(context, controlPointsFile.Ascii(), &curve)); BuiltModel curveModel; BuildCurveModel(&curve, curveName, curveModel); ReturnError_(BakeModel(context, curveModelName.Ascii(), curveModel)); Instance curveInstance; curveInstance.index = subscene->modelNames.Add(curveModelName); curveInstance.localToWorld = Matrix4x4::Identity(); subscene->modelInstances.Add(curveInstance); return Success_; } //============================================================================================================================= static Error ParseInstancePrimitivesSection(BuildProcessorContext* context, const FixedString256& root, const rapidjson::Value& section, SubsceneResourceData* subscene) { uint controlPointCount = 0; uint curveCount = 0; for(const auto& keyvalue : section.GetObject()) { const auto& element = keyvalue.value; FixedString32 type; if(Json::ReadFixedString(element, "type", type) == false) { return Error_("'type' parameter missing from instanced primitives section."); } if(StringUtil::Equals(type.Ascii(), "archive")) { FilePathString primFile; if(Json::ReadFixedString(element, "jsonFile", primFile) == false) { return Error_("`jsonFile ` parameter missing from instanced primitives section"); } AssetFileUtils::IndependentPathSeperators(primFile); FilePathString sourceId; FixedStringSprintf(sourceId, "%s%s", root.Ascii(), primFile.Ascii()); ReturnError_(ParseArchiveFile(context, root, sourceId, subscene)); } else if(StringUtil::Equals(type.Ascii(), "curve")) { ReturnError_(ParseCurveElement(context, keyvalue.name.GetString(), root, element, subscene)); } } return Success_; } //============================================================================================================================= static Error ParseLightsFile(BuildProcessorContext* context, cpointer lightfile, CArray<SceneLight>& lights) { if(StringUtil::Length(lightfile) == 0) { return Success_; } FilePathString filepath; AssetFileUtils::ContentFilePath(lightfile, filepath); ReturnError_(context->AddFileDependency(filepath.Ascii())); rapidjson::Document document; ReturnError_(Json::OpenJsonDocument(filepath.Ascii(), document)); uint lightCount = document.MemberCount(); lights.Reserve(lights.Count() + lightCount); for(const auto& lightElementKV : document.GetObject()) { FixedString64 type; Json::ReadFixedString(lightElementKV.value, "type", type); if(StringUtil::Equals(type.Ascii(), "quad") == false) { continue; } float4 color; float exposure; Json::ReadFloat4(lightElementKV.value, "color", color, float4::Zero_); Json::ReadFloat(lightElementKV.value, "exposure", exposure, 0.0f); float width, height; Json::ReadFloat(lightElementKV.value, "width", width, 0.0f); Json::ReadFloat(lightElementKV.value, "height", height, 0.0f); float3 rgb = color.XYZ(); float3 radiance = Math::Powf(2.0f, exposure) * Pow(rgb, 2.2f); if(Dot(radiance, float3::One_) <= 0.0f) { continue; } SceneLight& light = lights.Add(); float4x4 matrix; Json::ReadMatrix4x4(lightElementKV.value, "translationMatrix", matrix); light.position = MatrixMultiplyPoint(float3::Zero_, matrix); light.direction = MatrixMultiplyVector(-float3::ZAxis_, matrix); light.x = MatrixMultiplyVector(width * float3::XAxis_, matrix); light.z = MatrixMultiplyVector(height * float3::YAxis_, matrix); light.radiance = radiance; light.type = QuadLight; } return Success_; } //============================================================================================================================= static Error ParseLightSets(BuildProcessorContext* context, const SceneFileData& sceneFile, SceneResourceData* scene) { scene->lightSetRanges.Resize((sceneFile.lightsets.Count())); for(uint setScan = 0, setCount = sceneFile.lightsets.Count(); setScan < setCount; ++setScan) { scene->lightSetRanges[setScan].start = (uint32)scene->lights.Count(); for(uint fileScan = 0, fileCount = sceneFile.lightsets[setScan]->lightFiles.Count(); fileScan < fileCount; ++fileScan) { cpointer filename = sceneFile.lightsets[setScan]->lightFiles[fileScan].Ascii(); ReturnError_(ParseLightsFile(context, filename, scene->lights)); } scene->lightSetRanges[setScan].count = (uint32)(scene->lights.Count() - scene->lightSetRanges[setScan].start); } return Success_; } //============================================================================================================================= static Error ImportDisneyMaterials(BuildProcessorContext* context, cpointer materialPath, cpointer prefix, SubsceneResourceData* subscene) { FilePathString filepath; AssetFileUtils::ContentFilePath(materialPath, filepath); ReturnError_(context->AddFileDependency(filepath.Ascii())); CArray<FixedString64> materialNames; CArray<ImportedMaterialData> importedMaterials; ReturnError_(ImportDisneyMaterials(filepath.Ascii(), materialNames, importedMaterials)); subscene->sceneMaterialNames.Reserve(importedMaterials.Count()); subscene->sceneMaterials.Reserve(importedMaterials.Count()); for(uint scan = 0, count = importedMaterials.Count(); scan < count; ++scan) { if(importedMaterials[scan].baseColorTexture.Length() > 0) { FilePathString temp; temp.Copy(importedMaterials[scan].baseColorTexture.Ascii()); FixedStringSprintf(importedMaterials[scan].baseColorTexture, "%s%s", prefix, temp.Ascii()); } Hash32 materialNameHash = MurmurHash3_x86_32(materialNames[scan].Ascii(), (int32)materialNames[scan].Length()); subscene->sceneMaterialNames.Add(materialNameHash); MaterialResourceData& material = subscene->sceneMaterials.Add(); BuildMaterial(importedMaterials[scan], material); } return Success_; } //============================================================================================================================= static Error ParseSceneFile(BuildProcessorContext* context, SceneFileData& output) { FilePathString filepath; AssetFileUtils::ContentFilePath(context->source.name.Ascii(), filepath); context->AddFileDependency(filepath.Ascii()); rapidjson::Document document; ReturnError_(Json::OpenJsonDocument(filepath.Ascii(), document)); if(document.HasMember("elements") == false) { return Error_("'elements' member not found in Disney scene '%s'", filepath.Ascii()); } for(const auto& elementJson : document["elements"].GetArray()) { ElementDesc& element = output.elements.Add(); Json::ReadFixedString(elementJson, "element", element.file); Json::ReadInt32(elementJson, "lightset", element.lightSetIndex, 0); } if(document.HasMember("cameras")) { for(const auto& cameraElement : document["cameras"].GetArray()) { FilePathString& cameraFile = output.cameraFiles.Add(); cameraFile.Copy(cameraElement.GetString()); } } Json::ReadFixedString(document, "ibl", output.iblFile); if(document.HasMember("lightsets")) { for(const auto& lightsetElement : document["lightsets"].GetArray()) { LightSetDesc* desc = New_(LightSetDesc); for(const auto& lightfiles : lightsetElement.GetArray()) { FilePathString& lightFile = desc->lightFiles.Add(); lightFile.Copy(lightfiles.GetString()); } output.lightsets.Add(desc); } } return Success_; } //============================================================================================================================= static Error AllocateSubscene(BuildProcessorContext* context, CArray<SubsceneResourceData*>& scenes, cpointer name, int32 lightSetIndex, const FilePathString& materialFile, const FixedString256& root, SubsceneResourceData*& scene) { scene = New_(SubsceneResourceData); scene->name.Copy(name); scene->lightSetIndex = lightSetIndex; ReturnError_(ImportDisneyMaterials(context, materialFile.Ascii(), root.Ascii(), scene)); scenes.Add(scene); return Success_; } //============================================================================================================================= static Error ParseElementFile(BuildProcessorContext* context, const FixedString256& root, const FilePathString& path, int32 lightSetIndex, SceneResourceData* rootScene, CArray<SubsceneResourceData*>& scenes) { FilePathString elementFilePath; AssetFileUtils::ContentFilePath(path.Ascii(), elementFilePath); ReturnError_(context->AddFileDependency(elementFilePath.Ascii())); rapidjson::Document document; ReturnError_(Json::OpenJsonDocument(elementFilePath.Ascii(), document)); // -- Prepare the materials json file path FilePathString materialFile; FixedStringSprintf(materialFile, "%s%s", root.Ascii(), document["matFile"].GetString()); FilePathString geomSceneName; FixedStringSprintf(geomSceneName, "%s_geometry", path.Ascii()); SubsceneResourceData* elementGeometryScene; ReturnError_(AllocateSubscene(context, scenes, geomSceneName.Ascii(), lightSetIndex, materialFile, root, elementGeometryScene)); uint geometrySceneIndex = rootScene->subsceneNames.Add(geomSceneName); Instance geometrySceneInstance; geometrySceneInstance.index = geometrySceneIndex; rootScene->subsceneInstances.Add(geometrySceneInstance); // -- Add the main geometry file FilePathString geomObjFile; FixedStringSprintf(geomObjFile, "%s%s", root.Ascii(), document["geomObjFile"].GetString()); AssetFileUtils::IndependentPathSeperators(geomObjFile); uint rootModelIndex = elementGeometryScene->modelNames.Add(geomObjFile); // -- create a child scene to contain the instanced primitives uint primitivesSceneIndex = InvalidIndex64; if(document.HasMember("instancedPrimitiveJsonFiles")) { SubsceneResourceData* primitivesScene; ReturnError_(AllocateSubscene(context, scenes, path.Ascii(), lightSetIndex, materialFile, root, primitivesScene)); primitivesSceneIndex = rootScene->subsceneNames.Add(primitivesScene->name); // -- read the instanced primitives section. ReturnError_(ParseInstancePrimitivesSection(context, root, document["instancedPrimitiveJsonFiles"], primitivesScene)); } { // -- Each element file will have a transform for the 'root level' object file... Instance rootInstance; Json::ReadMatrix4x4(document["transformMatrix"], rootInstance.localToWorld); rootInstance.index = rootModelIndex; elementGeometryScene->modelInstances.Add(rootInstance); if(primitivesSceneIndex != InvalidIndex64) { rootInstance.index = primitivesSceneIndex; rootScene->subsceneInstances.Add(rootInstance); } } // -- add instanced copies if(document.HasMember("instancedCopies")) { for(const auto& instancedCopyKV : document["instancedCopies"].GetObject()) { Instance copyInstance; if(Json::ReadMatrix4x4(instancedCopyKV.value["transformMatrix"], copyInstance.localToWorld) == false) { return Error_("Failed to read `transformMatrix` from instancedCopy '%s'", instancedCopyKV.name.GetString()); } uint modelIndex = rootModelIndex; if(instancedCopyKV.value.HasMember("geomObjFile")) { FilePathString altGeomObjFile; FixedStringSprintf(altGeomObjFile, "%s%s", root.Ascii(), instancedCopyKV.value["geomObjFile"].GetString()); AssetFileUtils::IndependentPathSeperators(altGeomObjFile); modelIndex = elementGeometryScene->modelNames.Add(altGeomObjFile); } copyInstance.index = modelIndex; elementGeometryScene->modelInstances.Add(copyInstance); uint sceneIndex = primitivesSceneIndex; if(instancedCopyKV.value.HasMember("instancedPrimitiveJsonFiles") && instancedCopyKV.value["instancedPrimitiveJsonFiles"].MemberCount() > 0) { SubsceneResourceData* altScene; ReturnError_(AllocateSubscene(context, scenes, instancedCopyKV.name.GetString(), lightSetIndex, materialFile, root, altScene)); sceneIndex = rootScene->subsceneNames.Add(altScene->name); // -- read the instanced primitives section. ReturnError_(ParseInstancePrimitivesSection(context, root, instancedCopyKV.value["instancedPrimitiveJsonFiles"], altScene)); } if(sceneIndex != InvalidIndex64) { copyInstance.index = sceneIndex; rootScene->subsceneInstances.Add(copyInstance); } } } return Success_; } //============================================================================================================================= static Error ParseCameraFile(BuildProcessorContext* context, cpointer path, CameraSettings& settings) { FilePathString fullPath; AssetFileUtils::ContentFilePath(path, fullPath); ReturnError_(context->AddFileDependency(fullPath.Ascii())); cpointer lastSep = StringUtil::FindLastChar(path, PlatformIndependentPathSep_) + 1; settings.name.Copy(lastSep); StringUtil::RemoveExtension(settings.name.Ascii()); rapidjson::Document document; ReturnError_(Json::OpenJsonDocument(fullPath.Ascii(), document)); Json::ReadFloat3(document, "eye", settings.position, float3(1.0f, 0.0f, 0.0f)); Json::ReadFloat(document, "fov", settings.fovDegrees, 70.0f); Json::ReadFloat3(document, "look", settings.lookAt, float3::Zero_); Json::ReadFloat3(document, "up", settings.up, float3::YAxis_); settings.znear = 0.1f; settings.zfar = 50000.0f; return Success_; } //============================================================================================================================= Error CDisneySceneBuildProcessor::Setup() { AssetFileUtils::EnsureAssetDirectory<SceneResource>(); AssetFileUtils::EnsureAssetDirectory<SubsceneResource>(); AssetFileUtils::EnsureAssetDirectory<ModelResource>(); return Success_; } //============================================================================================================================= cpointer CDisneySceneBuildProcessor::Type() { return "disneyscene"; } //============================================================================================================================= uint64 CDisneySceneBuildProcessor::Version() { return SceneResource::kDataVersion + SubsceneResource::kDataVersion + ModelResource::kDataVersion; } //============================================================================================================================= Error CDisneySceneBuildProcessor::Process(BuildProcessorContext* context) { FixedString256 contentRoot = ContentRoot(context); SceneFileData sceneFile; ReturnError_(ParseSceneFile(context, sceneFile)); CArray<SubsceneResourceData*> allScenes; SceneResourceData* rootScene = New_(SceneResourceData); rootScene->name.Copy(context->source.name.Ascii()); rootScene->backgroundIntensity = float4::One_; rootScene->iblName.Copy(sceneFile.iblFile.Ascii()); for(uint scan = 0, count = sceneFile.cameraFiles.Count(); scan < count; ++scan) { CameraSettings& settings = rootScene->cameras.Add(); ReturnError_(ParseCameraFile(context, sceneFile.cameraFiles[scan].Ascii(), settings)); } ReturnError_(ParseLightSets(context, sceneFile, rootScene)); for(uint scan = 0, count = sceneFile.elements.Count(); scan < count; ++scan) { const FilePathString& elementName = sceneFile.elements[scan].file; int32 lightSetIndex = sceneFile.elements[scan].lightSetIndex; ReturnError_(ParseElementFile(context, contentRoot, elementName, lightSetIndex, rootScene, allScenes)); } for(uint scan = 0, count = allScenes.Count(); scan < count; ++scan) { SubsceneResourceData* scene = allScenes[scan]; for(uint scan = 0, count = scene->modelNames.Count(); scan < count; ++scan) { if(!StringUtil::EndsWithIgnoreCase(scene->modelNames[scan].Ascii(), CurveModelNameSuffix_)) { context->AddProcessDependency("model", scene->modelNames[scan].Ascii()); } } ReturnError_(context->CreateOutput(SubsceneResource::kDataType, SubsceneResource::kDataVersion, scene->name.Ascii(), *scene)); Delete_(scene); } allScenes.Shutdown(); if(StringUtil::Length(sceneFile.iblFile.Ascii()) > 0) { context->AddProcessDependency("DualIbl", sceneFile.iblFile.Ascii()); } ReturnError_(context->CreateOutput(SceneResource::kDataType, SceneResource::kDataVersion, rootScene->name.Ascii(), *rootScene)); Delete_(rootScene); for(uint scan = 0, count = sceneFile.lightsets.Count(); scan < count; ++scan) { Delete_(sceneFile.lightsets[scan]); } return Success_; } }
43.700599
141
0.571047
schuttejoe
5c7557362a73f40f51615910d3586efe130137ba
1,477
cpp
C++
DSA-450/02Matrix/10commonElements.cpp
vikkastiwari/cpp-coding-questions
020790e1a3b26c7b24991427004730b3f0785c71
[ "MIT" ]
null
null
null
DSA-450/02Matrix/10commonElements.cpp
vikkastiwari/cpp-coding-questions
020790e1a3b26c7b24991427004730b3f0785c71
[ "MIT" ]
null
null
null
DSA-450/02Matrix/10commonElements.cpp
vikkastiwari/cpp-coding-questions
020790e1a3b26c7b24991427004730b3f0785c71
[ "MIT" ]
null
null
null
// question link: https://www.geeksforgeeks.org/common-elements-in-all-rows-of-a-given-matrix/ #include <bits/stdc++.h> using namespace std; vector<int> findCommon(vector<vector<int>> &nums) { vector<int> common; unordered_map<int, int> map; // marking all row 0 elements as present for (int j = 0; j < nums[0].size(); j++) { map[nums[0][j]] = 1; } for (int i = 1; i < nums.size(); i++) { for (int j = 0; j < nums[0].size(); j++) { // we initialize first row with 1, here i=0 // then when i =1 we check in map if the count of that element is 1 // increment it by 1, now the count is 2 in map of that element // now in second row i=2 if the element is present then we compare the count of that element in map which is also now 2 with i. if (map[nums[i][j]] == i) { map[nums[i][j]] = i + 1; if ((i == nums.size() - 1) && map[nums[i][j]] == nums.size()) { common.push_back(nums[i][j]); } } } } return common; } int main() { vector<vector<int>> nums = { {1, 2, 1, 4, 8}, {3, 7, 8, 5, 1}, {8, 7, 7, 3, 1}, {8, 1, 2, 7, 9}, }; vector<int> result = findCommon(nums); for (int j = 0; j < result.size(); j++) { cout << result[j] << " "; } cout << endl; return 0; }
25.912281
139
0.477319
vikkastiwari
5c7610d0031114fd6ae16fbd1d44b0c1e1400667
622
cpp
C++
prob03/main.cpp
CSUF-CPSC120-2019F23-24/labex02-TommyLe3825
5d938242e9991e39c7138241e532475ed0705a48
[ "MIT" ]
null
null
null
prob03/main.cpp
CSUF-CPSC120-2019F23-24/labex02-TommyLe3825
5d938242e9991e39c7138241e532475ed0705a48
[ "MIT" ]
null
null
null
prob03/main.cpp
CSUF-CPSC120-2019F23-24/labex02-TommyLe3825
5d938242e9991e39c7138241e532475ed0705a48
[ "MIT" ]
null
null
null
// Name: Tommy Le // This program calculates the tax and tip on a restaurant bill. #include <iostream> int main() { double mealcost,tax,tip,totalbill; std::cout << "Welcome to the Restaurant Bill Calculator!\n"; //Input Meal Cost std::cout << "What is the total meal cost? "; std::cin >> mealcost; //Calculating Tax tax= mealcost * 0.0775; std::cout << "Tax: $" << tax << "\n"; //Calculating Tip tip= mealcost * 0.20; std::cout << "Tip: $" << tip << "\n"; //Calculating Total Bill totalbill=tip+tax+mealcost; std::cout << "Total Bill: $" << totalbill; return 0; }
22.214286
64
0.599678
CSUF-CPSC120-2019F23-24
f07f84cdd2ba1c1e88458535c89ae66d4374b2e5
12,766
cpp
C++
Flash/src/flash.cpp
MuellerA/LonganNanoTest
ed71398e63ff318695552b665b42e762b401c61e
[ "MIT" ]
15
2019-12-15T21:57:27.000Z
2022-02-22T05:28:24.000Z
Flash/src/flash.cpp
MuellerA/LonganNanoTest
ed71398e63ff318695552b665b42e762b401c61e
[ "MIT" ]
null
null
null
Flash/src/flash.cpp
MuellerA/LonganNanoTest
ed71398e63ff318695552b665b42e762b401c61e
[ "MIT" ]
3
2020-07-28T17:19:39.000Z
2021-10-01T09:01:51.000Z
//////////////////////////////////////////////////////////////////////////////// // flash.cpp //////////////////////////////////////////////////////////////////////////////// extern "C" { #include "gd32vf103.h" } #include "GD32VF103/spi.h" #include "GD32VF103/gpio.h" #include "GD32VF103/time.h" #include "Longan/lcd.h" using ::RV::GD32VF103::Spi ; using ::RV::GD32VF103::Gpio ; using ::RV::GD32VF103::TickTimer ; using ::RV::Longan::Lcd ; using ::RV::Longan::LcdArea ; Gpio &button(Gpio::gpioA8()) ; Lcd &lcd(Lcd::lcd()) ; //////////////////////////////////////////////////////////////////////////////// class Flash { private: enum class Cmd { WriteEnable = 0x06, VolatileSrWriteEnable = 0x50, WriteDisable = 0x04, ReleasePowerDownId = 0xAB, // Dummy Dummy Dummy (ID7-ID0) ManufacturerDeviceId = 0x90, // Dummy Dummy 00h (MF7-MF0) (ID7-ID0) JedecId = 0x9F, // (MF7-MF0) (ID15-ID8) (ID7-ID0) UniqueId = 0x4B, // Dummy Dummy Dummy Dummy (UID63-0) ReadData = 0x03, // A23-A16 A15-A8 A7-A0 (D7-D0) FastRead = 0x0B, // A23-A16 A15-A8 A7-A0 Dummy (D7-D0) PageProgram = 0x02, // A23-A16 A15-A8 A7-A0 D7-D0 D7-D0 SectorErase = 0x20, // ( 4KB) A23-A16 A15-A8 A7-A0 BlockErase32 = 0x52, // (32KB) A23-A16 A15-A8 A7-A0 BlockErase64 = 0xD8, // (64KB) A23-A16 A15-A8 A7-A0 ChipErase = 0xC7, // 60h ReadStatusRegister1 = 0x05, // (S7-S0) WriteStatusRegister1 = 0x01, // (S7-S0) ReadStatusRegister2 = 0x35, // (S15-S8) WriteStatusRegister2 = 0x31, // (S15-S8) ReadStatusRegister3 = 0x15, // (S23-S16) WriteStatusRegister3 = 0x11, // (S23-S16) ReadSfdpRegister = 0x5A, // 00h 00h A7–A0 Dummy (D7-D0) EraseSecurityRegister = 0x44, // A23-A16 A15-A8 A7-A0 ProgramSecurityRegister = 0x42, // A23-A16 A15-A8 A7-A0 D7-D0 D7-D0 ReadSecurityRegister = 0x48, // A23-A16 A15-A8 A7-A0 Dummy (D7-D0) GlobalBlockLock = 0x7E, GlobalBlockUnlock = 0x98, ReadBlockLock = 0x3D, // A23-A16 A15-A8 A7-A0 (L7-L0) IndividualBlockLock = 0x36, // A23-A16 A15-A8 A7-A0 IndividualBlockUnlock = 0x39, // A23-A16 A15-A8 A7-A0 EraseProgramSuspend = 0x75, EraseProgramResume = 0x7A, PowerDown = 0xB9, EnableReset = 0x66, ResetDevice = 0x99, } ; public: Flash() : _spi(Spi::spi1()), _cs(Gpio::gpioB8()) { } void setup() { _spi.setup(Spi::Psc::_2) ; // SPI1: 54MHz/2 _cs.setup(Gpio::Mode::OUT_PP) ; _cs.high() ; } void getManufacturerDeviceId(uint8_t &mfid, uint8_t &did) { uint8_t dout[] = { 0x00, 0x00, 0x00 } ; uint8_t din[2] ; xch(Cmd::ManufacturerDeviceId, dout, sizeof(dout), din, sizeof(din)) ; mfid = din[0] ; did = din[1] ; } void getJedecId(uint8_t &mfid, uint8_t &memoryType, uint8_t &capacity) { uint8_t din[3] ; xch(Cmd::JedecId, nullptr, 0, din, sizeof(din)) ; mfid = din[0] ; memoryType = din[1] ; capacity = din[2] ; } void getUniqueId(uint64_t &uid) { uint8_t dout[] = { 0x00, 0x00, 0x00, 0x00 } ; uint8_t din[8] ; xch(Cmd::UniqueId, dout, sizeof(dout), din, sizeof(din)) ; uid = din[0] ; uid <<= 8 ; uid |= din[1] ; uid <<= 8 ; uid |= din[2] ; uid <<= 8 ; uid |= din[3] ; uid <<= 8 ; uid |= din[4] ; uid <<= 8 ; uid |= din[5] ; uid <<= 8 ; uid |= din[6] ; uid <<= 8 ; uid |= din[7] ; } void read(uint32_t addr, uint8_t *data, size_t size) { uint8_t dout[3] ; uint8_t *o = (uint8_t*)&addr ; dout[0] = o[2] ; dout[1] = o[1] ; dout[2] = o[0] ; xch(Cmd::ReadData, dout, sizeof(dout), data, size) ; } void write(uint32_t addr, uint8_t *data, size_t size) { if ((size == 0) || (size > 256)) return ; xch(Cmd::WriteEnable, nullptr, 0, nullptr, 0) ; uint8_t dout[3] ; uint8_t *o = (uint8_t*)&addr ; dout[0] = o[2] ; dout[1] = o[1] ; dout[2] = o[0] ; uint8_t cc = (uint8_t)Cmd::PageProgram ; _cs.low() ; _spi.xch(&cc, 1, 1) ; _spi.xch(dout, sizeof(dout), 1) ; _spi.xch(data, size, 1) ; _cs.high() ; } void erase(uint32_t addr) { xch(Cmd::WriteEnable, nullptr, 0, nullptr, 0) ; uint8_t dout[3] ; uint8_t *o = (uint8_t*)&addr ; dout[0] = o[2] ; dout[1] = o[1] ; dout[2] = o[0] ; xch(Cmd::SectorErase, dout, sizeof(dout), nullptr, 0) ; } void waitBusy() { uint8_t dout = (uint8_t) Cmd::ReadStatusRegister1 ; _cs.low() ; _spi.xch(&dout, sizeof(dout), 1) ; uint8_t status ; while (true) { _spi.xch(&status, sizeof(status), 2) ; if (!(status & 0x01)) break ; } _cs.high() ; } void getStatus1(uint8_t &status) { xch(Cmd::ReadStatusRegister1, nullptr, 0, &status, sizeof(status)) ; } void getStatus2(uint8_t &status) { xch(Cmd::ReadStatusRegister2, nullptr, 0, &status, sizeof(status)) ; } void getStatus3(uint8_t &status) { xch(Cmd::ReadStatusRegister3, nullptr, 0, &status, sizeof(status)) ; } bool getSize(uint32_t &size) { #pragma pack(push, 1) struct SfdpHeader { uint32_t _magic ; uint8_t _minor ; uint8_t _major ; uint8_t _count ; // n = _count+1 uint8_t _unused ; } ; struct SfdpParameterHeader { uint8_t _id ; uint8_t _minor ; uint8_t _major ; uint8_t _size ; // in 32 bit uint32_t _offset ; // clear MSByte / only lower 24 Bits used } ; struct SfdpParameter0 { uint32_t _1 ; uint32_t _flashMemoryDensity ; uint32_t _3 ; uint32_t _4 ; uint32_t _5 ; uint32_t _6 ; uint32_t _7 ; uint32_t _8 ; uint32_t _9 ; } ; #pragma pack(pop) SfdpHeader sfdpHdr ; SfdpParameterHeader sfdpParamHdr ; SfdpParameter0 sfdpParam0 ; uint8_t dout[] = { 0x00, 0x00, 0x00, 0x00 } ; xch(Cmd::ReadSfdpRegister, dout, sizeof(dout), (uint8_t*)&sfdpHdr , sizeof(sfdpHdr)) ; if (sfdpHdr._magic != 'PDFS') return false ; uint32_t offset ; uint8_t *o = (uint8_t*)&offset ; offset = sizeof(SfdpHeader) ; dout[0] = o[2] ; dout[1] = o[1] ; dout[2] = o[0] ; xch(Cmd::ReadSfdpRegister, dout, sizeof(dout), (uint8_t*)&sfdpParamHdr , sizeof(sfdpParamHdr)) ; sfdpParamHdr._offset &= 0xffffff ; if (sfdpParamHdr._id != 0) return false ; if (sfdpParamHdr._size < 9) return false ; offset = sfdpParamHdr._offset ; dout[0] = o[2] ; dout[1] = o[1] ; dout[2] = o[0] ; xch(Cmd::ReadSfdpRegister, dout, sizeof(dout), (uint8_t*)&sfdpParam0 , sizeof(sfdpParam0)) ; size = sfdpParam0._flashMemoryDensity ; return true ; } private: void xch(Cmd cmd, uint8_t *txData, size_t txSize, uint8_t *rxData, size_t rxSize) { uint8_t cc = (uint8_t)cmd ; _cs.low() ; _spi.xch(&cc, 1, 1) ; if (txSize) _spi.xch(txData, txSize, 1) ; if (rxSize) _spi.xch(rxData, rxSize, 2) ; _cs.high() ; } private: Spi &_spi ; Gpio &_cs ; } ; //////////////////////////////////////////////////////////////////////////////// uint8_t buttonPressed() { struct State { State() : _value{0x00}, _tick{TickTimer::now()} {} uint8_t _value ; uint64_t _tick ; } ; static State last ; static State current ; uint64_t now = TickTimer::now() ; if ((now - current._tick) < TickTimer::usToTick(2500)) return 0 ; current._tick = now ; current._value = (current._value << 1) | button.get() ; if ((current._value == last._value) || ((current._value != 0x00) && (current._value != 0xff))) return 0 ; uint32_t ms = TickTimer::tickToMs(current._tick - last._tick) ; last = current ; if (current._value) return 0 ; return (ms < 600) ? 1 : 2 ; } //////////////////////////////////////////////////////////////////////////////// int main() { Flash flash ; button.setup(Gpio::Mode::IN_FL) ; lcd.setup() ; flash.setup() ; lcd.clear() ; lcd.txtPos(0) ; lcd.put("Flash ") ; lcd.txtPos(4) ; lcd.put("press button to continue") ; LcdArea lcdWrk(lcd, 0, 160, 16, 48) ; while (true) { { uint8_t mfid ; uint8_t did ; flash.getManufacturerDeviceId(mfid, did) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Manufacturer ID: ") ; lcdWrk.put(mfid, 2, '0', true) ; lcdWrk.txtPos(1) ; lcdWrk.put("Device ID: ") ; lcdWrk.put(did, 2, '0', true) ; } while (!buttonPressed()) ; { uint8_t mfid ; uint8_t memoryType ; uint8_t capacity ; flash.getJedecId(mfid, memoryType, capacity) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Manufacturer ID: ") ; lcdWrk.put(mfid, 2, '0', true) ; lcdWrk.txtPos(1) ; lcdWrk.put("Memory Type: ") ; lcdWrk.put(memoryType, 2, '0', true) ; lcdWrk.txtPos(2) ; lcdWrk.put("Capacity: ") ; lcdWrk.put(capacity, 2, '0', true) ; } while (!buttonPressed()) ; { uint64_t uid ; flash.getUniqueId(uid) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Unique ID: ") ; lcdWrk.txtPos(1) ; lcdWrk.put((uint32_t)(uid>>32), 8, '0', true) ; lcdWrk.put((uint32_t)(uid>> 0), 8, '0', true) ; } while (!buttonPressed()) ; { uint32_t size ; uint64_t size64 ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Size: ") ; if (flash.getSize(size)) { if (size & 0x80000000) size64 = 1LL << size ; else size64 = size + 1 ; size64 >>= 3 ; // bit to byte if (size64 > (1LL << 30)) { size64 >>= 30 ; lcdWrk.put((uint32_t)size64) ; lcdWrk.put("GByte") ; } else if (size64 > (1LL << 20)) { size64 >>= 20 ; lcdWrk.put((uint32_t)size64) ; lcdWrk.put("MByte") ; } else if (size64 > (1LL << 20)) { size64 >>= 10 ; lcdWrk.put((uint32_t)size64) ; lcdWrk.put("kByte") ; } else { lcdWrk.put((uint32_t)size64) ; lcdWrk.put("Byte") ; } } else lcdWrk.put('?') ; } while (!buttonPressed()) ; { uint8_t status1 ; uint8_t status2 ; uint8_t status3 ; flash.getStatus1(status1) ; flash.getStatus2(status2) ; flash.getStatus3(status3) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Status1: ") ; lcdWrk.put(status1, 2, '0', true) ; lcdWrk.txtPos(1) ; lcdWrk.put("Status2: ") ; lcdWrk.put(status2, 2, '0', true) ; lcdWrk.txtPos(2) ; lcdWrk.put("Status3: ") ; lcdWrk.put(status3, 2, '0', true) ; } while (!buttonPressed()) ; { uint8_t data[16] ; flash.read(0x1000, data, sizeof(data)) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Read") ; lcdWrk.txtPos(1) ; for (uint8_t b : data) { lcdWrk.put(b, 2, '0', true) ; lcdWrk.put(' ') ; } } while (!buttonPressed()) ; { const char *txt = "Hallo Welt?!" ; flash.write(0x1000, (uint8_t*)txt, 11) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Write") ; lcdWrk.txtPos(1) ; lcdWrk.put("...") ; flash.waitBusy() ; lcdWrk.put(" done") ; } while (!buttonPressed()) ; { uint8_t data[16] ; flash.read(0x1000, data, sizeof(data)) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Read") ; lcdWrk.txtPos(1) ; for (uint8_t b : data) { lcdWrk.put(b, 2, '0', true) ; lcdWrk.put(' ') ; } lcdWrk.clearEOL() ; } while (!buttonPressed()) ; { flash.erase(0x1000) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Erase") ; lcdWrk.txtPos(1) ; lcdWrk.put("...") ; flash.waitBusy() ; lcdWrk.put(" done") ; } while (!buttonPressed()) ; { uint8_t data[16] ; flash.read(0x1000, data, sizeof(data)) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Read") ; lcdWrk.txtPos(1) ; for (uint8_t b : data) { lcdWrk.put(b, 2, '0', true) ; lcdWrk.put(' ') ; } lcdWrk.clearEOL() ; } while (!buttonPressed()) ; } } //////////////////////////////////////////////////////////////////////////////// // EOF ////////////////////////////////////////////////////////////////////////////////
24.933594
100
0.513943
MuellerA
f07fddd0d7e9745b75518d3d5266c40ab673b3d0
13,076
cpp
C++
chip8/src/cpu/opcodes.cpp
bryan-pakulski/emulators
599856760529cce7cc31be43d07617983e642dae
[ "MIT" ]
null
null
null
chip8/src/cpu/opcodes.cpp
bryan-pakulski/emulators
599856760529cce7cc31be43d07617983e642dae
[ "MIT" ]
null
null
null
chip8/src/cpu/opcodes.cpp
bryan-pakulski/emulators
599856760529cce7cc31be43d07617983e642dae
[ "MIT" ]
null
null
null
#include <iostream> #include <stdexcept> #include "../globals.hpp" #include "opcodes.hpp" using namespace std; opcodes::opcodes() { std::map<unsigned short, int> optable; } opcodes::~opcodes() { } /** * Gets function from the hashtable at a given index - If the function has not yet * been added to the lookup table it is inserted here with the key of the opcode * that has called it * * @param o opcode */ func_p opcodes::get(unsigned short o) { // Check if instruction already exists in opcode lookup table // If not then decode instruction based on HPP header and add to lookup int instruction = lookup(o); if ( instruction == -1 ) { instruction = decode( o ); if ( instruction != -1 ) { cerr << "Inserting new opcode: " << std::hex << o << " with key: " << std::hex << instruction << endl; optable.insert( std::pair<unsigned short, int>(o, instruction) ); } else { throw std::runtime_error("Invalid opcode: " + to_string(o)); } } // Run instruction from opcode lookup table, passes along current opcode operation return oplist[instruction]; } /** * Checks if an instruction already exists in the optable * If not it will be decoded and added for faster lookup next time * * @param o Opcode * * @return Returns the index location of function to call */ int opcodes::lookup(unsigned short o) { // Find in optable auto search = optable.find(o); if ( search != optable.end() ) return search->second; else return -1; } /** * Decodes a given opcode and returns an index * * @param o Opcode * * @return Returns the index location lookup key of the function to call */ int opcodes::decode(unsigned short o) { cerr << "Parsing new opcode: " << std::hex << o << endl; switch( o & 0xF000) { case 0x0000: switch( o & 0x0F00 ) { case 0x0000: switch( o & 0x000F ) { case 0x0000: return 1; break; case 0x000E: return 2; break; } break; default: return 0; } break; case 0x1000: return 3; break; case 0x2000: return 4; break; case 0x3000: return 5; break; case 0x4000: return 6; break; case 0x5000: return 7; break; case 0x6000: return 8; break; case 0x7000: return 9; break; case 0x8000: switch( o & 0x000F ) { case 0x0000: return 10; break; case 0x0001: return 11; break; case 0x0002: return 12; break; case 0x0003: return 13; break; case 0x0004: return 14; break; case 0x0005: return 15; break; case 0x0006: return 16; break; case 0x0007: return 17; break; case 0x000E: return 18; break; } break; case 0x9000: return 19; break; case 0xA000: return 20; break; case 0xB000: return 21; break; case 0xC000: return 22; break; case 0xD000: return 23; break; case 0xE000: switch( o & 0x00FF ) { case 0x009E: return 24; break; case 0x00A1: return 25; break; } break; case 0xF000: switch ( o & 0x00FF ) { case 0x0007: return 26; break; case 0x000A: return 27; break; case 0x0015: return 28; break; case 0x0018: return 29; break; case 0x001E: return 30; break; case 0x0029: return 31; break; case 0x0033: return 32; break; case 0x0055: return 33; break; case 0x0065: return 34; break; } break; } cerr << "Unknown opcode encountered: " << o << endl; return -1; } /** * @brief Calls RCA 1802 program at address NNN. * Not necessary for most ROMs */ void opcodes::op0NNN(cpu* proc) { } /** * @brief Clears the screen */ void opcodes::op00E0(cpu* proc) { proc->clearScreen = true; } /** * Returns from a subroutine */ void opcodes::op00EE(cpu* proc) { proc->setPC(proc->popStack()); } /** * Jumps to address NNN */ void opcodes::op1NNN(cpu* proc) { proc->setPC( proc->getOP() & 0x0FFF ); } /** * Calls subroutine at NNN */ void opcodes::op2NNN(cpu* proc) { proc->pushStack( proc->getPC() ); proc->setPC( proc->getOP() & 0x0FFF ); } /** * Skips the next instruction if VX equals NN */ void opcodes::op3XNN(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short n = (proc->getOP() & 0x00FF); if ( proc->getV( x ) == n ) { proc->stepPC(1); } } /** * Skips the next instruction if VX doesn't equal NN */ void opcodes::op4XNN(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short n = (proc->getOP() & 0x00FF); if ( proc->getV( x ) != n ) { proc->stepPC(1); } } /** * Skips the next instruction if VX equals VY */ void opcodes::op5XY0(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; if ( proc->getV(x) == proc->getV(y) ) { proc->stepPC(1); } } /** * Sets VX to NN */ void opcodes::op6XNN(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short n = (proc->getOP() & 0x00FF); proc->setV(x, n); } /** * Adds NN to VX */ void opcodes::op7XNN(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short n = (proc->getOP() & 0x00FF); proc->setV(x, proc->getV(x) + n); } /** * Sets VX to the value of VY */ void opcodes::op8XY0(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; proc->setV( x, proc->getV( y ) ); } /** * Sets VX to VX or VY */ void opcodes::op8XY1(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; proc->setV(x, proc->getV(x) | proc->getV(y)); } /** * Sets VX to VX and VY */ void opcodes::op8XY2(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; proc->setV(x, proc->getV(x) & proc->getV(y)); } /** * Sets VX to VX xor VY */ void opcodes::op8XY3(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; proc->setV(x, proc->getV(x) ^ proc->getV(y)); } /** * Adds VY to VX. VF is set to 1 when there's a carry, * and to 0 when there isn't */ void opcodes::op8XY4(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; short sum = proc->getV(x) + proc->getV(y); if (sum > 0xFF) { proc->setV(0xF, 1); sum -= 0x100; } proc->setV(x, sum); } /** * VY is subtracted from VX. VF is set to 0 when there's a * borrow, and 1 when there isn't */ void opcodes::op8XY5(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; short diff = proc->getV(x) - proc->getV(y); proc->setV(0xF, 1); if (diff < 0) { proc->setV(0xF, 0); diff += 0x100; } proc->setV(x, diff); } /** * Shifts VX right by one. VF is set to the value * of the least significant bit of VX before the shift */ void opcodes::op8XY6(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; // Get least significant bit proc->setV(0xF, proc->getV(x) & 0x1); proc->setV(x, proc->getV(x) >> 1); } /** * Sets VX to VY minus VX. VF is set to 0 when there's a borrow, * and 1 when there isn't */ void opcodes::op8XY7(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; short diff = proc->getV(y) - proc->getV(x); proc->setV(0xF, 1); if (diff < 0) { proc->setV(0xF, 0); diff += 0x100; } proc->setV(x, diff); } /** * Shifts VX left by one.VF is set to the value of the * most significant bit of VX before the shift */ void opcodes::op8XYE(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; proc->setV(0xF, proc->getV(x) >> 7); proc->setV(x, proc->getV(x) << 1); } /** * Skips the next instruction if VX doesn't equal VY */ void opcodes::op9XY0(cpu* proc) { unsigned short x = ( proc->getOP() & 0x0F00 ) >> 8; unsigned short y = ( proc->getOP() & 0x00F0 ) >> 4; if ( proc->getV(x) != proc->getV(y) ) { proc->stepPC(1); } } /** * Sets I to the address NNN */ void opcodes::opANNN(cpu* proc) { proc->setI( proc->getOP() & 0x0FFF ); } /** * Jumps to the address NNN plus V0 */ void opcodes::opBNNN(cpu* proc) { proc->setPC( (proc->getOP() & 0x0FFF) + proc->getV(0) ); } /** * Sets VX to the result of a bitwise and * operation on a random number and NN */ void opcodes::opCXNN(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short v_nn = proc->getOP() & 0x00FF; // TODO: generate random byte in the following format int r = ((rand() % (0xF + 1 - 0x0)) + 0x0); proc->setV(x, r & v_nn); } /** * Sprites stored in memory at location in index register (I), * 8bits wide. Wraps around the screen. If when * drawn, clears a pixel, register VF is set to 1 otherwise it is * zero. All drawing is XOR drawing (i.e. it toggles the screen pixels). * Sprites are drawn starting at position VX, VY. N is the number of 8bit * rows that need to be drawn. If N is greater than 1, * second line continues at position VX, VY+1, and so on */ void opcodes::opDXYN(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; unsigned short nRows = (proc->getOP() & 0x000F); proc->setV(0xF, 0); // Normalized coordinates unsigned short xPos = proc->getV(x) % c8_display::INTERNAL_WIDTH; unsigned short yPos = proc->getV(y) % c8_display::INTERNAL_HEIGHT; // Iterate over display for (int row = 0; row < nRows; ++row) { unsigned short sprite = proc->mem->get(proc->getI() + row); for (int col = 0; col < 8; ++col) { if ((sprite & (0x80 >> col)) != 0) { unsigned short index = ((yPos + row) * c8_display::INTERNAL_WIDTH) + (xPos + col); index %= (c8_display::INTERNAL_WIDTH * c8_display::INTERNAL_HEIGHT); unsigned char gfxVal = proc->gfx->getPixel(index); if (gfxVal == 0xF) { proc->setV(0xF, 1); } gfxVal ^= 0xF; proc->gfx->setPixel(index, gfxVal); } } } proc->drawFlag = true; } /** * Skips the next instruction if the key stored in VX is pressed */ void opcodes::opEX9E(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short key = proc->getV(x); if (proc->keyPressed(key)) { proc->stepPC(1); } } /** * Skips the next instruction if the key stored in VX isn't pressed */ void opcodes::opEXA1(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short key = proc->getV(x); if (!proc->keyPressed(key)) { proc->stepPC(1); } } /** * Sets VX to the value of the delay timer */ void opcodes::opFX07(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; proc->setV(x, proc->delayTimer); } /** * A key press is awaited, and then stored in VX */ void opcodes::opFX0A(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; bool keyPressed = false; while (!keyPressed) { for (int i = 0; i < 0xF; i++) { if (proc->keyPressed(i)) { proc->setV(x, i); keyPressed = true; break; } } } } /** * Sets the delay timer to VX */ void opcodes::opFX15(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; proc->delayTimer = proc->getV(x); } /** * Sets the sound timer to VX */ void opcodes::opFX18(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; proc->soundTimer = proc->getV(x); } /** * Adds VX to I */ void opcodes::opFX1E(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; proc->setI(proc->getI() + proc->getV(x)); } /** * Sets I to the location of the sprite for the shortacter in VX. * shortacters 0-F (in hexadecimal) are represented by a 4x5 font */ void opcodes::opFX29(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; proc->setI(proc->getV(x) * 5); } /** * Stores the Binary-coded decimal representation of VX, * with the most significant of three digits at the address in I, * the middle digit at I plus 1, and the least significant digit at * I plus 2. (In other words, take the decimal representation of VX, * place the hundreds digit in memory at location in I, * the tens digit at location I+1, * and the ones digit at location I+2) */ void opcodes::opFX33(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short vx = proc->getV(x); for (int i = 2; i >= 0; i--) { proc->mem->set(proc->getI() + i, vx % 10); vx /= 10; } } /** * Stores V0 to VX in memory starting at address I */ void opcodes::opFX55(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; for (int i = 0; i <= x; ++i) { proc->mem->set( proc->getI() + i, proc->getV(i) ); } } /** * Fills V0 to VX with values from memory starting at address I */ void opcodes::opFX65(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; for (int i = 0; i <= x; ++i) { proc->setV( i, proc->mem->get(proc->getI() + i) ); } }
19.229412
106
0.601101
bryan-pakulski
f0844ff5707784bddf9aff38dcd89c3fded92da1
941
cpp
C++
Stack/postfixEvaluation.cpp
gaurav147-star/DSA-learning
52625953e2b1421fdd550004df893b970aac9308
[ "MIT" ]
1
2022-02-15T12:53:00.000Z
2022-02-15T12:53:00.000Z
Stack/postfixEvaluation.cpp
gaurav147-star/DSA-learning
52625953e2b1421fdd550004df893b970aac9308
[ "MIT" ]
null
null
null
Stack/postfixEvaluation.cpp
gaurav147-star/DSA-learning
52625953e2b1421fdd550004df893b970aac9308
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int postfixEvaluation(string s) { stack<double> st; for (int i = 0; i < s.length(); i++) { if (s[i] >= '0' && s[i] <= '9') { st.push(s[i] - '0'); } else { double op2 = st.top(); st.pop(); double op1 = st.top(); st.pop(); switch (s[i]) { case '+': st.push(op1 + op2); case '-': st.push(op1 - op2); case '*': st.push(op1 * op2); case '/': st.push(op1 / op2); break; case '^': st.push(pow(op1, op2)); break; default: break; } } } return st.top(); } int main() { cout << postfixEvaluation("46+2/5*7+") << endl; return 0; }
19.604167
51
0.336876
gaurav147-star
f084a7ccdba1a870071401028679bfbe7618d1f6
2,386
cpp
C++
phoenix/.test/test-listicons.cpp
vgmtool/vgm2pre
f4f917df35d531512292541234a5c1722b8af96f
[ "MIT" ]
21
2015-04-13T03:07:12.000Z
2021-11-20T00:27:00.000Z
phoenix/.test/test-listicons.cpp
apollolux/hello-phoenix
71510b5f329804c525a9576fb0367fe8ab2487cd
[ "MIT" ]
2
2015-10-06T14:59:48.000Z
2022-01-27T08:57:57.000Z
phoenix/.test/test-listicons.cpp
apollolux/hello-phoenix
71510b5f329804c525a9576fb0367fe8ab2487cd
[ "MIT" ]
2
2021-11-19T08:36:57.000Z
2022-03-04T16:03:16.000Z
#include "phoenix.hpp" using namespace nall; using namespace phoenix; struct TestWindow : Window { TestWindow() { setGeometry({64, 64, 480, 640}); setTitle("Test Window"); onClose = [&] { setVisible(false); }; } } *testWindow = nullptr; struct Application : Window { VerticalLayout layout; ListView listView; ListView test; ComboBox comboView; Button button; Label label; Menu file; Menu submenu; Item quit; Application() { setTitle("Main Window"); setGeometry({128, 128, 640, 480}); file.setText("File"); submenu.setText("Submenu"); submenu.setImage(image("folder.png")); quit.setText("Quit"); quit.setImage(image("image.png")); //submenu.setImage(); //quit.setImage(); setMenuVisible(); append(file); file.append(submenu); file.append(quit); listView.setHeaderText("Column 1", "Column 2", "Column 3"); listView.setHeaderVisible(); listView.setCheckable(); listView.append("A", "B", "C"); listView.append("D", "E", "F"); listView.append("G", "H", "I"); test.setHeaderText("Column 1", "Column 2"); test.setHeaderVisible(); test.append("A", "B"); test.append("C", "D"); test.append("E", "F"); listView.setImage(0, 0, image("image.png")); listView.setImage(1, 0, image("folder.png")); listView.setImage(2, 2, image("folder.png")); //listView.setImage(0, 0); //listView.setImage(1, 0); //button.setText("Hello"); button.setImage(image("image.png")); //button.setImage(); label.setText("Label"); append(layout); layout.setMargin(5); layout.append(listView, {~0, ~0}, 5); layout.append(test, {~0, ~0}, 5); layout.append(comboView, {~0, 0}, 5); layout.append(button, {~0, 0}, 5); layout.append(label, {~0, 0}); comboView.append("item1", "item2*", "item3", "item4", "item5", "item6", "item7", "item8"); button.onActivate = [&] { testWindow->setVisible(); //DialogWindow::folderSelect(*this, "c:/users/byuu/appdata/roaming/emulation"); //, "All files (*)"); //listView.remove(1); //comboView.modify(1, "item2"); //comboView.remove(2); }; setVisible(); onClose = &OS::quit; } } *application = nullptr; int main() { OS::setName("higan"); testWindow = new TestWindow; application = new Application; OS::main(); return 0; }
23.86
108
0.604359
vgmtool
f08869385b8bd0b0f20dd057ebc8fdbf6b9426c8
298
cpp
C++
AtCoder/ABC 162/C.cpp
igortakeo/Solutions-CF
d945f0ae21c691120b69db78ff3d240b7dedc0a7
[ "MIT" ]
1
2020-05-25T15:32:23.000Z
2020-05-25T15:32:23.000Z
AtCoder/ABC 162/C.cpp
igortakeo/Solutions-CF
d945f0ae21c691120b69db78ff3d240b7dedc0a7
[ "MIT" ]
null
null
null
AtCoder/ABC 162/C.cpp
igortakeo/Solutions-CF
d945f0ae21c691120b69db78ff3d240b7dedc0a7
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define ll long long using namespace std; int main(){ int k; ll sum = 0; cin >> k; for(int i=1; i<=k; i++){ for(int j=1; j<=k; j++){ int a = __gcd(i, j); for(int l=1; l<=k; l++){ sum+= __gcd(a, l); } } } cout << sum << endl; return 0; }
12.416667
27
0.47651
igortakeo
f08c2d61feb5de0e5929ee721e6e49d47a942450
53
cpp
C++
source/Allocators/DoubleStackAllocator.cpp
teemid/Capstan
35e37a41cdc4c471a4570916751e5f391693aef4
[ "MIT" ]
null
null
null
source/Allocators/DoubleStackAllocator.cpp
teemid/Capstan
35e37a41cdc4c471a4570916751e5f391693aef4
[ "MIT" ]
null
null
null
source/Allocators/DoubleStackAllocator.cpp
teemid/Capstan
35e37a41cdc4c471a4570916751e5f391693aef4
[ "MIT" ]
null
null
null
#include "Capstan/Allocators/DoubleStackAllocator.h"
26.5
52
0.849057
teemid
f0944e557457ef143775a29eda3792bb6760d37e
23,656
cpp
C++
firmware/src/Statemachine/Canopen.cpp
sprenger120/remote_control_device
c375ab12683c10fd2918ea8345bcb06a5d78b978
[ "MIT" ]
1
2021-01-27T12:23:43.000Z
2021-01-27T12:23:43.000Z
firmware/src/Statemachine/Canopen.cpp
sprenger120/remote_control_device
c375ab12683c10fd2918ea8345bcb06a5d78b978
[ "MIT" ]
null
null
null
firmware/src/Statemachine/Canopen.cpp
sprenger120/remote_control_device
c375ab12683c10fd2918ea8345bcb06a5d78b978
[ "MIT" ]
null
null
null
#include "Canopen.hpp" #include "ANSIEscapeCodes.hpp" #include "CanFestivalLocker.hpp" #include "Logging.hpp" #include "PeripheralDrivers/CanIO.hpp" #include "PeripheralDrivers/TerminalIO.hpp" #include <algorithm> namespace remote_control_device { Canopen *Canopen::_instance = nullptr; Message Canopen::RTD_StateBootupMessage = { Canopen::RPDO1_RTD_State, NOT_A_REQUEST, 1, {Canopen::RTD_State_Bootup, 0, 0, 0, 0, 0, 0, 0}}; Message Canopen::RTD_StateReadyMessage = { Canopen::RPDO1_RTD_State, NOT_A_REQUEST, 1, {Canopen::RTD_State_Ready, 0, 0, 0, 0, 0, 0, 0}}; Message Canopen::RTD_StateEmcyMessage = {Canopen::RPDO1_RTD_State, NOT_A_REQUEST, 1, {Canopen::RTD_State_Emergency, 0, 0, 0, 0, 0, 0, 0}}; Canopen::Canopen(CanIO &canio, Logging &log, bool bypass) : _canIO(canio), _log(log), _monitoredDevices{{MonitoredDevice(BusDevices::DriveMotorController), MonitoredDevice(BusDevices::BrakeActuator), MonitoredDevice(BusDevices::BrakePressureSensor), MonitoredDevice(BusDevices::SteeringActuator), MonitoredDevice(BusDevices::SteeringAngleSensor)}}, _stateControlledDevices{ {StateControlledDevice(BusDevices::DriveMotorController, CanDeviceState::Operational), StateControlledDevice(BusDevices::BrakeActuator, CanDeviceState::Operational), StateControlledDevice(BusDevices::SteeringActuator, CanDeviceState::Operational), StateControlledDevice(BusDevices::BrakePressureSensor, CanDeviceState::Operational)}}, _couplings{{Coupling(BusDevices::BrakeActuator, BrakeActuatorCoupling_IndexOD, BrakeActuatorCoupling_SubIndexOD, BrakeActuatorCoupling_EngagedValue, BrakeActuatorCoupling_DisEngagedValue), Coupling(BusDevices::SteeringActuator, SteeringActuatorCoupling_IndexOD, SteerinActuatorCoupling_SubIndexOD, SteerinActuatorCoupling_EngagedValue, SteerinActuatorCoupling_DisEngagedValue)}} { specialAssert(_instance == nullptr); _instance = this; if (bypass) { return; } { CFLocker locker; setNodeId(locker.getOD(), static_cast<UNS8>(BusDevices::RemoteControlDevice)); // fix for REPEAT_NMT_MAX_NODE_ID_TIMES not having enough repeats by default thus not // initializing the NMT table correctly which makes post_SlaveStateChange miss bootup // events for nodes with higher ids for (auto &e : locker.getOD()->NMTable) { e = Unknown_state; } // set zero values to not have canfestival send pure zeros 0 // which could cause damage setBrakeForce(0.0); setSteeringAngle(0.0); setWheelDriveTorque(0.0); setSelfState(StateId::Start); RTD_State = RTD_State_Bootup; setTPDO(TPDOIndex::SelfState, true); setActuatorPDOs(false); // setup callbacks locker.getOD()->heartbeatError = &cbHeartbeatError; locker.getOD()->post_SlaveStateChange = &cbSlaveStateChange; // avoids global reset sent out // preOperational callback is pre-programmed with // masterSendNMTstateChange (d, 0, NMT_Reset_Node) // by overwriting the callback we stop this from being sent locker.getOD()->preOperational = [](CO_Data *d) -> void {}; setState(locker.getOD(), Initialisation); setState(locker.getOD(), Operational); // RX timeout requires a timer table that can't be generated and is initialized with NULL // every time adding our own // also the stack has a bug in timeout registration (since fixed) // where it reads from the wrong memory address and uses garbage for the timeout value std::fill(_rpdoTimers.begin(), _rpdoTimers.end(), TIMER_NONE); locker.getOD()->RxPDO_EventTimers = _rpdoTimers.data(); // hack in rpdo timeout callback as it can't be registered anyhere locker.getOD()->RxPDO_EventTimers_Handler = [](CO_Data *d, UNS32 timerId) -> void { // remove reference to previously used timer // if not done, the next reception of this rpdo will clear the timer spot previously // used again even though it could be attributed to something completely different d->RxPDO_EventTimers[timerId] = TIMER_NONE; // NOLINT testHook_signalRTDTimeout(); _instance->signalRTDTimeout(); }; // when a rpdo is received, the OD entry where RTD_State resides is updated, every entry // can have a callback so we use this cb to reset the timeout flag set by the rpdo timeout RegisterSetODentryCallBack(locker.getOD(), RTD_State_ODIndex, RTD_State_ODSubIndex, [](CO_Data *d, const indextable *, UNS8 bSubindex) -> UNS32 { testHook_signalRTDRecovery(); _instance->signalRTDRecovery(); return OD_SUCCESSFUL; }); // rpdo timeout is a poorly supported feature in canopen // canfestival is also not capable to start the rpdo timeout unless at least // one message was received, so dispatch one fake message to get the timer going _canIO.addRXMessage(RTD_StateBootupMessage); } } Canopen::~Canopen() { _instance = nullptr; CFLocker locker; locker.getOD()->RxPDO_EventTimers = nullptr; } bool Canopen::isDeviceOnline(const BusDevices device) const { for (auto &dev : _monitoredDevices) { if (dev.device == device) { return !dev.disconnected; } } return false; } void Canopen::drawUIDevicesPart(TerminalIO &term) { term.write(ANSIEscapeCodes::ColorSection_WhiteText_GrayBackground); term.write("\r\nMonitored Devices:\r\n"); term.write(ANSIEscapeCodes::ColorSection_End); auto printMonitoredDevice = [&](const MonitoredDevice &dev) -> void { if (dev.disconnected) { term.write(ANSIEscapeCodes::ColorSection_WhiteText_RedBackground); } term.write(getBusDeviceName(dev.device)); if (dev.disconnected) { term.write(": Offline"); term.write(ANSIEscapeCodes::ColorSection_End); } else { term.write(": Online"); } term.write("\r\n"); }; for (auto &dev : _monitoredDevices) { printMonitoredDevice(dev); } MonitoredDevice rtd(BusDevices::RealTimeDevice); rtd.disconnected = _rtdTimeout; printMonitoredDevice(rtd); term.write(ANSIEscapeCodes::ColorSection_WhiteText_GrayBackground); term.write("\r\nState Controlled Devices:\r\n"); term.write(ANSIEscapeCodes::ColorSection_End); for (auto &scd : _stateControlledDevices) { if (scd.targetState != scd.currentState) { term.write(ANSIEscapeCodes::ColorSection_BlackText_YellowBackground); } term.write(getBusDeviceName(scd.device)); term.write(": "); term.write(getCanDeviceStateName(scd.currentState)); term.write(" (Target: "); term.write(getCanDeviceStateName(scd.targetState)); term.write(")"); if (scd.targetState != scd.currentState) { term.write(ANSIEscapeCodes::ColorSection_End); } term.write("\r\n"); } } void Canopen::kickstartPDOTranmission() { // setState(operational) calls sendPDOEvent which // causes the stack to register event timers for continous sending for all // enabled PDOs. As only self state is enabled by default // All other pdos get left behind and will not start transmitting // on their own until sendPDOEvent is called again. // Also: The stack has an oversight within pdo transmission in where there is no easy way // to force it to transmit a pdo with the same data continously. Every time a pdo tries to get // sent it is compared against the last one and if it is the same the function aborts. In this // case the event timers are not re-registered and the pdo is functionally broken You could do // something like this here below after every pdo transmission /*lock.getOD()->PDO_status[static_cast<size_t>(TPDOIndex::SelfState)].last_message.cob_id = 0; lock.getOD()->PDO_status[static_cast<size_t>(TPDOIndex::BrakeForce)].last_message.cob_id = 0; lock.getOD()->PDO_status[static_cast<size_t>(TPDOIndex::SteeringAngle)].last_message.cob_id = 0; lock.getOD()->PDO_status[static_cast<size_t>(TPDOIndex::MotorTorque)].last_message.cob_id = 0; lock.getOD()->PDO_status[static_cast<size_t>(TPDOIndex::TargetValues)].last_message.cob_id = 0;*/ // bus this is tedious as there is no callback to hook into after a pdo has fired. // So to avoid all this b.s. pdo.c was modified in line 539 to not compare at all. CFLocker lock; sendPDOevent(lock.getOD()); } void Canopen::setSelfState(const StateId state) { { CFLocker locker; SelfState = static_cast<UNS8>(state); } } void Canopen::setBrakeForce(float force) { { CFLocker locker; BrakeTargetForce = mapValue<float, INTEGER16>(0.0f, 1.0f, BrakeForceRaw_Min, BrakeForceRaw_Max, force); } } void Canopen::setWheelDriveTorque(float torque) { { CFLocker locker; WheelTargetTorque = mapValue<float, INTEGER16>(-1.0f, 1.0f, WheelDriveTorqueRaw_Min, WheelDriveTorqueRaw_Max, torque); } } void Canopen::setSteeringAngle(float angle) { // inverted due to hardware gearing angle *= -1.0f; { CFLocker locker; SteeringTargetAngle = mapValue<float, INTEGER32>(-1.0f, 1.0f, SteeringAngleRaw_Min, SteeringAngleRaw_Max, angle); } } void Canopen::setCouplingStates(bool brake, bool steering) { { CFLocker locker; _setCouplingState(_couplings[CouplingIndex_Brake], steering); _setCouplingState(_couplings[CouplingIndex_Steering], brake); } } void Canopen::setTPDO(const TPDOIndex index, bool enable) { { CFLocker locker; if (enable) { PDOEnable(locker.getOD(), static_cast<UNS8>(index)); } else { PDODisable(locker.getOD(), static_cast<UNS8>(index)); } } } void Canopen::setActuatorPDOs(bool enable) { setTPDO(TPDOIndex::BrakeForce, enable); setTPDO(TPDOIndex::SteeringAngle, enable); setTPDO(TPDOIndex::MotorTorque, enable); setTPDO(TPDOIndex::TargetValues, enable); if (enable) { kickstartPDOTranmission(); } } void Canopen::update(BusDevicesState &target) { { CFLocker locker; target.rtdEmergency = RTD_State == RTD_State_Emergency; target.rtdBootedUp = RTD_State != RTD_State_Bootup; } target.timeout = false; for (auto &e : _monitoredDevices) { target.timeout = target.timeout || e.disconnected; } target.timeout = target.timeout || _rtdTimeout; } void Canopen::cbSlaveStateChange(CO_Data *d, UNS8 heartbeatID, e_nodeState state) { const auto dev = static_cast<BusDevices>(heartbeatID); // state controlled devices int8_t index{0}; if ((index = _instance->findInStateControlledList(dev)) != -1) { { CFLocker lock; // interpret node state to check if device is in correct state CanDeviceState convertedState = CanDeviceState::Unknown; switch (state) { case e_nodeState::Operational: convertedState = CanDeviceState::Operational; break; case e_nodeState::Pre_operational: convertedState = CanDeviceState::Preoperational; break; case e_nodeState::Initialisation: /* fall through */ case e_nodeState::Disconnected: /* fall through */ case e_nodeState::Connecting: /* fall through */ // case Preparing: has same value as connecting /* fall through */ case e_nodeState::Stopped: /* fall through */ case e_nodeState::Unknown_state: /* fall through */ default: break; } _instance->_stateControlledDevices[index].currentState = convertedState; _instance->_log.logInfo(Logging::Origin::BusDevices, "%s changed state to %s", getBusDeviceName(dev), getCanDeviceStateName(convertedState)); if (convertedState != _instance->_stateControlledDevices[index].targetState) { _instance->setDeviceState( dev, _instance->_stateControlledDevices[index].targetState); } } } // reset disconnected state for (MonitoredDevice &e : _instance->_monitoredDevices) { if (e.device == dev && e.disconnected) { _instance->_log.logInfo(Logging::Origin::BusDevices, "%s is online", getBusDeviceName(dev)); e.disconnected = false; return; } } } void Canopen::cbHeartbeatError(CO_Data *d, UNS8 heartbeatID) { // Called when a node registered in the heartbeat consumer od index // didn't send a heartbeat within the timeout range // after timeout the node's state is changed to disconnected internally // when the timed out node recovers, slave state change callback is called const auto dev = static_cast<BusDevices>(heartbeatID); _instance->_log.logInfo(Logging::Origin::BusDevices, "%s timed out", getBusDeviceName(dev)); // Reset internal current state when device is state monitored // so UI doesn't show wrong information int8_t index = 0; if ((index = _instance->findInStateControlledList(dev)) != -1) { _instance->_stateControlledDevices[index].currentState = CanDeviceState::Unknown; } for (MonitoredDevice &e : _instance->_monitoredDevices) { if (e.device == dev) { e.disconnected = true; return; } } _instance->_log.logWarning(Logging::Origin::BusDevices, "Received heartbeat error callback for nodeId %d but it isn't registered as a " "monitored device", heartbeatID); } void Canopen::cbSDO(CO_Data *d, UNS8 nodeId) { // search for coupling with nodeid Coupling *coupling = nullptr; for (Coupling &e : _instance->_couplings) { if (e.device == static_cast<BusDevices>(nodeId)) { coupling = &e; break; } } if (coupling == nullptr) { _instance->_log.logDebug(Logging::Origin::BusDevices, "Unexpected SDO received from nodeId %d", nodeId); return; } bool restart = false; uint32_t abortCode = 0; if (getWriteResultNetworkDict(d, nodeId, &abortCode) != SDO_FINISHED) { // transfer failed // abortCode is 0 for timeout which isn't correct // but flow errors in the stack cause this to be 0 if (abortCode == 0) { // timeout, try again restart = true; } else { // serious error, most likely ill configured node // not attempting new transmission as these errors are more likely // to come from an active node which answers quickly (like we do) // causing risk of flooding _instance->_log.logWarning(Logging::Origin::BusDevices, "SDO to nodeId %d failed (%s)", nodeId, abortCodeToString(abortCode)); restart = false; } } else { // sucess but check if target changed mid request processing if (coupling->stateForThisRequest != coupling->targetState) { _instance->_log.logDebug(Logging::Origin::BusDevices, "SDO finished successfully but state changed mid transmission"); restart = true; } else { _instance->_log.logDebug(Logging::Origin::BusDevices, "SDO finished successfully"); } } // closing isn't necessary when the transfer is finished but this isn't always the case closeSDOtransfer(d, nodeId, SDO_CLIENT); if (restart) { // logDebug(Logging::Origin::BusDevices, "Repeating transmission"); _instance->_setCouplingState(*coupling, coupling->targetState); } } const char *Canopen::abortCodeToString(uint32_t abortCode) { switch (abortCode) { /* case OD_SUCCESSFUL: return "OD_SUCCESSFUL"; case OD_READ_NOT_ALLOWED: return "OD_READ_NOT_ALLOWED"; case OD_WRITE_NOT_ALLOWED: return "OD_WRITE_NOT_ALLOWED"; case OD_NO_SUCH_OBJECT: return "OD_NO_SUCH_OBJECT"; case OD_NOT_MAPPABLE: return "OD_NOT_MAPPABLE"; case OD_ACCES_FAILED: return "OD_ACCES_FAILED"; case OD_LENGTH_DATA_INVALID: return "OD_LENGTH_DATA_INVALID"; case OD_NO_SUCH_SUBINDEX: return "OD_NO_SUCH_SUBINDEX"; case OD_VALUE_RANGE_EXCEEDED: return "OD_VALUE_RANGE_EXCEEDED"; case OD_VALUE_TOO_LOW: return "OD_VALUE_TOO_LOW"; case OD_VALUE_TOO_HIGH: return "OD_VALUE_TOO_HIGH"; case SDOABT_TOGGLE_NOT_ALTERNED: return "SDOABT_TOGGLE_NOT_ALTERNED"; case SDOABT_TIMED_OUT: return "SDOABT_TIMED_OUT"; case SDOABT_CS_NOT_VALID: return "SDOABT_CS_NOT_VALID"; case SDOABT_INVALID_BLOCK_SIZE: return "SDOABT_INVALID_BLOCK_SIZE"; case SDOABT_OUT_OF_MEMORY: return "SDOABT_OUT_OF_MEMORY"; case SDOABT_GENERAL_ERROR: return "SDOABT_GENERAL_ERROR"; case SDOABT_LOCAL_CTRL_ERROR: return "SDOABT_LOCAL_CTRL_ERROR";*/ default: return "Error Unknown"; } } int8_t Canopen::findInStateControlledList(const BusDevices device) { for (uint8_t i = 0; i < _stateControlledDevices.size(); ++i) { if (_stateControlledDevices[i].device == device) { return i; } } return -1; } void Canopen::setDeviceState(const BusDevices device, CanDeviceState state) { // check if allowed to change state int8_t index = findInStateControlledList(device); if (index == -1) { _instance->_log.logWarning(Logging::Origin::BusDevices, "Denied request to change state of unlisted device with nodeId %d", static_cast<uint8_t>(device)); return; } uint8_t nmtCommand = 0; switch (state) { case CanDeviceState::Operational: nmtCommand = NMT_Start_Node; break; case CanDeviceState::Preoperational: nmtCommand = NMT_Enter_PreOperational; break; case CanDeviceState::Unknown: /* fall through */ default: return; } _instance->_log.logInfo(Logging::Origin::BusDevices, "Requesting %s to change status to %s", getBusDeviceName(device), getCanDeviceStateName(state)); _stateControlledDevices[index].targetState = state; { CFLocker locker; masterSendNMTstateChange(locker.getOD(), static_cast<uint8_t>(_stateControlledDevices[index].device), nmtCommand); // masterSendNMTstateChange is just blindly transmitting the state change request // when a node doesn't switch it isn't noticed as proceedNODE_GUARD which processes incoming // heartbeats compares the old state with the unchanged newly received one and finds no // difference // invalidating the local state of a node will force the change state callback to be fired // which allows confirming the state change or retrying locker.getOD()->NMTable[static_cast<UNS8>(_stateControlledDevices[index].device)] = Disconnected; } } const char *Canopen::getBusDeviceName(const BusDevices dev) { switch (dev) { case BusDevices::DriveMotorController: return "Drive Motor Controller (10h)"; case BusDevices::BrakeActuator: return "Brake Actuator (20h)"; case BusDevices::SteeringActuator: return "Steering Actuator (30h)"; case BusDevices::RemoteControlDevice: return "Remote Control Device (1h)"; case BusDevices::RealTimeDevice: return "Real Time Device (2h)"; case BusDevices::WheelSpeedSensor: return "Wheel Speed Sensor (11h)"; case BusDevices::BrakePressureSensor: return "Brake Pressure Sensor (21h)"; case BusDevices::SteeringAngleSensor: return "Steering Angle Sensor (31h)"; default: return "Unamed device"; } } Canopen::Coupling::Coupling(BusDevices device, uint16_t odIndex, uint8_t odSubIndex, uint32_t engagedValue, uint32_t disengagedValue) : device(device), odIndex(odIndex), odSubIndex(odSubIndex), engagedValue(engagedValue), disengagedValue(disengagedValue) { } void Canopen::_setCouplingState(Coupling &coupling, bool state) { coupling.targetState = state; // check if sdo is still in porgress { CFLocker locker; UNS32 abortCode = 0; if (getWriteResultNetworkDict(locker.getOD(), static_cast<UNS8>(coupling.device), &abortCode) == SDO_ABORTED_INTERNAL) { // nothing in progress, start write request coupling.stateForThisRequest = coupling.targetState; uint32_t couplingState = coupling.stateForThisRequest ? coupling.engagedValue : coupling.disengagedValue; writeNetworkDictCallBack(locker.getOD(), static_cast<UNS8>(coupling.device), coupling.odIndex, coupling.odSubIndex, 4, uint32, &couplingState, &Canopen::cbSDO, false); } else { _instance->_log.logInfo(Logging::Origin::BusDevices, "SDO transfer already in progress, repeating after this one finished"); } } } std::array<Canopen::BusDevices, Canopen::MonitoredDeviceCount> Canopen::getMonitoredDevices() const { std::array<Canopen::BusDevices, Canopen::MonitoredDeviceCount> list; for (uint8_t i = 0; i < _monitoredDevices.size(); ++i) { list[i] = _monitoredDevices[i].device; } return list; } std::array<Canopen::BusDevices, Canopen::StateControlledDeviceCount> Canopen::getStateControlledDevices() const { std::array<Canopen::BusDevices, Canopen::StateControlledDeviceCount> list; for (uint8_t i = 0; i < _stateControlledDevices.size(); ++i) { list[i] = _stateControlledDevices[i].device; } return list; } } // namespace remote_control_device
36.337942
113
0.625592
sprenger120
f09853d57b96f656cd589da1c25a2f02cc1897ea
1,524
hpp
C++
include/codegen/include/RootMotion/FinalIK/EditorIK.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/RootMotion/FinalIK/EditorIK.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/RootMotion/FinalIK/EditorIK.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:09:17 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes // Including type: UnityEngine.MonoBehaviour #include "UnityEngine/MonoBehaviour.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: RootMotion::FinalIK namespace RootMotion::FinalIK { // Forward declaring type: IK class IK; } // Completed forward declares // Type namespace: RootMotion.FinalIK namespace RootMotion::FinalIK { // Autogenerated type: RootMotion.FinalIK.EditorIK class EditorIK : public UnityEngine::MonoBehaviour { public: // private RootMotion.FinalIK.IK ik // Offset: 0x18 RootMotion::FinalIK::IK* ik; // private System.Void Start() // Offset: 0x1395670 void Start(); // private System.Void Update() // Offset: 0x1395718 void Update(); // public System.Void .ctor() // Offset: 0x13957E8 // Implemented from: UnityEngine.MonoBehaviour // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() static EditorIK* New_ctor(); }; // RootMotion.FinalIK.EditorIK } DEFINE_IL2CPP_ARG_TYPE(RootMotion::FinalIK::EditorIK*, "RootMotion.FinalIK", "EditorIK"); #pragma pack(pop)
33.866667
89
0.672572
Futuremappermydud
f098e60a5ec2af63aaac74f9d576e9cfb39f56f5
11,089
cc
C++
parser/pub/tools/tools.cc
smartdata-x/MarketSys
b4f999fb80b8f2357b75694c2ca94d46190a55f7
[ "Apache-2.0" ]
null
null
null
parser/pub/tools/tools.cc
smartdata-x/MarketSys
b4f999fb80b8f2357b75694c2ca94d46190a55f7
[ "Apache-2.0" ]
null
null
null
parser/pub/tools/tools.cc
smartdata-x/MarketSys
b4f999fb80b8f2357b75694c2ca94d46190a55f7
[ "Apache-2.0" ]
3
2016-10-25T01:56:17.000Z
2019-06-24T04:45:06.000Z
// Copyright (c) 2015-2015 The restful Authors. All rights reserved. // Created on: 2015/11/24 Author: jiaoyongqing #include<malloc.h> #include<stdlib.h> #include<memory.h> #include <string> #include <sstream> #include <map> #include <list> #include <vector> #include "tools/tools.h" #include "tea/tea.h" #include "net/typedef.h" #include "base/logic/logic_comm.h" #include "db/db_comm.h" #include "logic/logic_unit.h" namespace tools { std::string GetTimeKey(int64 time) { struct tm timeTm; int64 s = time; localtime_r(&s, &timeTm); char s_char[32]; memset(s_char, '\0', sizeof(s_char)); snprintf(s_char, sizeof(s_char), "%4d-%02d-%02d %02d", timeTm.tm_year+1900, timeTm.tm_mon+1, timeTm.tm_mday, timeTm.tm_hour); std::string str_time = s_char; return str_time; } std::string GetProvinceString(int province) { switch (province) { case 1 : return "jsdx:"; case 2: return "shdx:"; case 3: return "zjdx:"; } return ""; } int64 StrToTime(const char *Data) { struct tm* tmp_time = (struct tm*)malloc(sizeof( struct tm )); strptime(Data, "%Y-%m-%d %H", tmp_time); tmp_time->tm_min = 0; tmp_time->tm_sec = 0; time_t t = mktime(tmp_time); free(tmp_time); return t; } int64 TodayStartTime() { return time(NULL) - (time(NULL) + 28800) % 86400; } int64 CurrentTime() { return time(NULL); } // 集合的形式为:a,b,c,d, std::string MergeSet(const std::string &set_one, \ const std::string &set_two, \ char separator) { if (set_one == "") return set_two; if (set_two == "") return set_one; std::string ret(set_two); if (ret[ret.length() - 1] != separator) { ret = ret + std::string(1, separator); } std::list<std::string> set_one_list; SeparatorStr(set_one, ',', &set_one_list); std::list<std::string>::iterator it = set_one_list.begin(); for (; it != set_one_list.end(); ++it) { if (set_two.find((*it).c_str()) == std::string::npos) { ret += *it; ret += std::string(","); } } return ret; } void ListGroup(const ContainerStr &l, \ int group_size, \ char separator, \ ContainerStr *const out) { ContainerStr::const_iterator it = l.begin(); int i = 0; std::string value(""); for (; it != l.end(); ++it) { value += *it; value += std::string(1, separator); ++i; if (i == group_size) { out->push_back(value); value = ""; i = 0; } } if (value != "") { out->push_back(value); } } bool IfSetOneIsInSetTwo(const std::string &set_one, \ const std::string &set_two, \ char separator) { if (set_one == "") return true; if (set_two == "") return false; std::list<std::string> set_one_list; SeparatorStr(set_one, ',', &set_one_list); std::list<std::string>::iterator it = set_one_list.begin(); for (; it != set_one_list.end(); ++it) { if (set_two.find((*it).c_str()) == std::string::npos) { return false; } } return true; } std::string DeleteSet(const std::string &set_one, \ const std::string &set_two, \ char separator) { if (set_one == "" || set_two == "") return set_two; std::string ret(""); std::list<std::string> set_two_list; SeparatorStr(set_two, ',', &set_two_list); std::list<std::string>::iterator it = set_two_list.begin(); for (; it != set_two_list.end(); ++it) { if (set_one.find((*it).c_str()) == std::string::npos) { ret += *it; ret += std::string(","); } } return ret; } std::string::size_type FindNth(const std::string &str, \ std::string::size_type start, \ int len, \ char ch, \ int num) { if (num == 0) return -1; std::string::size_type end = str.find(ch, start); int count = 0; int cur_len = end + 1 - start; while (true) { if (end == std::string::npos) break; if (cur_len > len) break; ++count; if (cur_len == len) break; if (count == num )break; start = end + 1; end = str.find(ch, start); cur_len = end + 1 - start; } if (count < num) { return -1; } return end; } void NumToChar(void *d, size_t l, std::string &token) { std::stringstream os; char *p = reinterpret_cast<char *>(d); int temp; for (int i = 0; i < l; ++i) { temp = p[i]; os << temp << ","; } token = os.str(); } size_t CharToNum(void **d, std::string &token) { ContainerStr out; tools::SeparatorStr<ContainerStr>(token, ',', &out, true); *d = reinterpret_cast<void *>(malloc(out.size())); char *p = reinterpret_cast<char*>(*d); for (int i = 0; i < out.size(); ++i) { p[i] = atoi(out[i].c_str()); } return out.size(); } std::string TeaEncode(const std::string src) { LOG_DEBUG2("encode before: %s", src.c_str()); int src_len = src.length(); int len = ((src.length() - 1) / 8 + 1) * 8; char *in = reinterpret_cast<char*>(malloc(len)); memset(in, 0, len); strcpy(in, src.c_str()); struct tea_data td; td.d = reinterpret_cast<void *>(in); td.l = len; StrEn(&td); std::string des; NumToChar(td.d, td.l, des); free(in); LOG_DEBUG2("encode after:%s", des.c_str()); return des; } std::string TeaDecode(const std::string src) { struct tea_data td; std::string temp_src(src); td.l = CharToNum(&td.d, temp_src); StrDe(&td); std::string temp(""); for (int i = 0; i < td.l; ++i) { temp.append(1, (reinterpret_cast<char*>(td.d))[i]); } temp.append(1, '\0'); LOG_DEBUG2("decode after:%s", temp.c_str()); free(td.d); return temp; } std::string GetToken(int64 user_id, std::string &token) { std::stringstream os; std::string cur_token; std::string temp; os.str(""); os << user_id; os << ","; os << time(NULL); cur_token = os.str(); LOG_DEBUG2("\n\norigin token: %s\n\n", cur_token.c_str()); int len = ((cur_token.length() - 1) / 8 + 1) * 8; char *in = reinterpret_cast<char*>(malloc(len)); memset(in, 0, len); strcpy(in, cur_token.c_str()); in[cur_token.length()] = 0; struct tea_data td; td.d = reinterpret_cast<void *>(in); td.l = len; StrEn(&td); NumToChar(td.d, td.l, token); free(in); return token; } bool CheckToken(int64 user_id, std::string &token) { struct tea_data td; td.l = CharToNum(&td.d, token); StrDe(&td); std::string origin_token(""); for (int i = 0; i < td.l; ++i) { origin_token.append(1, (reinterpret_cast<char*>(td.d))[i]); } origin_token.append(1, '\0'); std::string::size_type separator_pos = origin_token.find(',', 0); std::string origin_id = origin_token.substr(0, separator_pos); std::stringstream os; os.str(""); os << origin_token.substr(separator_pos + 1, origin_token.length()); int64 origin_time; os >> origin_time; os.str(""); os << user_id; std::string current_id = os.str(); LOG_DEBUG2("\n\norigin token: %s,%d\n\n", origin_id.c_str(), origin_time); int64 current_time = time(NULL); const int TOKEN_SURVIVE_TIME = 86400; if (origin_id == current_id && (current_time - origin_time <= 86400)) { return true; } return false; } void MapAdd(std::map<std::string, int64> *map, \ const std::string &key, int64 value) { std::map<std::string, int64>::iterator it; it = map->find(key); if (it == map->end()) { (*map)[key] = value; } else { (*map)[key] += value; } } std::string TimeFormat(int64 time, const char* format) { struct tm timeTm; localtime_r(&time, &timeTm); char s_char[32]; memset(s_char, '\0', sizeof(s_char)); snprintf(s_char, sizeof(s_char), format, timeTm.tm_year+1900, timeTm.tm_mon+1, timeTm.tm_mday, timeTm.tm_hour); std::string str_time = s_char; return str_time; } std::vector<std::string> Split(std::string str, std::string pattern) { std::string::size_type pos; std::vector<std::string> result; str += pattern; int size = str.size(); for (int i = 0; i < size; i++) { pos = str.find(pattern, i); if (pos < size) { std::string s = str.substr(i , pos - i); result.push_back(s); i = pos + pattern.size() - 1; } } return result; } void replace_all(std::string *str, \ const std::string &old_value, \ const std::string &new_value) { while (true) { std::string::size_type pos(0); if ((pos = str->find(old_value)) != std::string::npos) str->replace(pos, old_value.length(), new_value); else break; } } void replace_all_distinct(std::string *str, \ const std::string &old_value, \ const std::string &new_value) { for (std::string::size_type pos(0); \ pos != std::string::npos; pos += new_value.length()) { if ((pos = str->find(old_value, pos)) != std::string::npos) str->replace(pos, old_value.length(), new_value); else break; } } void ReplaceBlank(std::string *str) { // 去除空格 replace_all_distinct(str, " ", ""); // 去除\t replace_all_distinct(str, "\t", ""); // 去除\n replace_all_distinct(str, "\n", ""); } bool check_userid_if_in_sql(NetBase* value,const int socket) { bool r = false; bool flag = false; int64 user_id = 0; int error_code = 0; r = value->GetBigInteger(L"user_id", static_cast<int64*>(&user_id)); if (false == r) error_code = STRUCT_ERROR; if (user_id > 0) { db::DbSql sql; flag = sql.CheckUseridIfInSql(user_id); error_code = sql.get_error_info(); LOG_DEBUG2("\n\DbSql::check_id_token-------error_code: %d\n\n",error_code); if (error_code != 0) { send_error(error_code, socket); return false; } if (flag == false) { error_code = USER_ID_ISNOT_IN_SQL; LOG_DEBUG2("\n\DbSql::check_id_token-------error_code1: %d\n\n",error_code); send_error(error_code, socket); return false; LOG_DEBUG2("\n\DbSql::check_id_token-------error_code2: %d\n\n",error_code); } } return true; } bool check_id_token(NetBase* value,const int socket) { bool r = false; bool flag = false; int error_code = 0; std::string token = ""; int64 user_id = 0; r = value->GetString(L"token", &token); if (false == r) error_code = STRUCT_ERROR; r = value->GetBigInteger(L"user_id", static_cast<int64*>(&user_id)); if (false == r) error_code = STRUCT_ERROR; /*LOG_DEBUG2("\n\DbSql::check_id_token-------user_id: %d\n\n",user_id);*/ if (CheckToken(user_id, token)) { return true; } else { error_code = USER_ACCESS_NOT_ENOUGH; send_error(error_code, socket); return false; } return false; } bool CheckUserIdAndToken(NetBase* value,const int socket) { if (!tools::check_userid_if_in_sql(value, socket)) { return false; } if (!tools::check_id_token(value, socket)) { return false; } return true; } } // namespace tools
24.533186
93
0.584994
smartdata-x
f09924a80a0e716a64c7699e1ed64931e559b292
228
hpp
C++
Rimfrost/src/Rimfrost/EventSystem/EventObserver.hpp
Cgunnar/Rimfrost
924f8bab51e42e6b0790eb46cc1064b6920333cf
[ "MIT" ]
null
null
null
Rimfrost/src/Rimfrost/EventSystem/EventObserver.hpp
Cgunnar/Rimfrost
924f8bab51e42e6b0790eb46cc1064b6920333cf
[ "MIT" ]
null
null
null
Rimfrost/src/Rimfrost/EventSystem/EventObserver.hpp
Cgunnar/Rimfrost
924f8bab51e42e6b0790eb46cc1064b6920333cf
[ "MIT" ]
null
null
null
#pragma once #include "Rimfrost\EventSystem\Event.hpp" namespace Rimfrost { class EventObserver { public: EventObserver() = default; virtual ~EventObserver() = default; virtual void onEvent(const Event& e) = 0; }; }
15.2
43
0.710526
Cgunnar
f09a60960c8157f4cce0993e7a96946606567a9c
129
cpp
C++
dependencies/physx-4.1/source/geomutils/src/pcm/GuPCMContactPlaneConvex.cpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
dependencies/physx-4.1/source/geomutils/src/pcm/GuPCMContactPlaneConvex.cpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
dependencies/physx-4.1/source/geomutils/src/pcm/GuPCMContactPlaneConvex.cpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:943d9f005beb984bd9d29ed487bf6adf30882f9fa79903c6092cbd91ecee3e90 size 6381
32.25
75
0.883721
realtehcman
f0a3986dff053570d226301f52321899ed5ba9bd
8,948
cpp
C++
example-ExtendsSprite/src/DocumentRoot.cpp
selflash/ofxSelflash
087a263b2d4de970edd75ecab2c2a48b7b58e62d
[ "MIT" ]
19
2015-05-14T09:57:38.000Z
2022-01-10T23:32:28.000Z
example-ExtendsSprite/src/DocumentRoot.cpp
selflash/ofxSelflash
087a263b2d4de970edd75ecab2c2a48b7b58e62d
[ "MIT" ]
3
2015-08-04T09:07:26.000Z
2018-01-18T07:14:35.000Z
example-ExtendsSprite/src/DocumentRoot.cpp
selflash/ofxSelflash
087a263b2d4de970edd75ecab2c2a48b7b58e62d
[ "MIT" ]
1
2015-08-04T09:05:22.000Z
2015-08-04T09:05:22.000Z
#include "DocumentRoot.h" //static const double pi = std::acos(-1.0); // お手軽に π を得る。 //============================================================== // Constructor / Destructor //============================================================== //-------------------------------------------------------------- // //-------------------------------------------------------------- DocumentRoot::DocumentRoot() { cout << "[DocumentRoot]DocumentRoot()" << endl; _target = this; name("DocumentRoot"); useHandCursor(true); } //-------------------------------------------------------------- // //-------------------------------------------------------------- DocumentRoot::~DocumentRoot() { cout << "[DocumentRoot]~DocumentRoot()" << endl; } //============================================================== // Setup / Update / Draw //============================================================== //-------------------------------------------------------------- // //-------------------------------------------------------------- void DocumentRoot::_setup() { cout << "[DocumentRoot]_setup()" << endl; //-------------------------------------- //ステージに追加された時にキーボードイベントを監視する addEventListener(flEvent::ADDED_TO_STAGE, this, &DocumentRoot::_eventHandler); addEventListener(flMouseEvent::MOUSE_DOWN, this, &DocumentRoot::_mouseEventHandler); addEventListener(flMouseEvent::MOUSE_UP, this, &DocumentRoot::_mouseEventHandler); flGraphics* g; g = graphics(); g->clear(); g->beginFill(0x888888, 0.1); g->drawRect(0, 0, ofGetWidth(), ofGetHeight()); g->endFill(); //----------------------------------- //----------------------------------- //copy from examples/graphics/graphicsExample //graphicsExampleのコードを書き写し counter = 0; ofSetCircleResolution(50); ofBackground(255,255,255); bSmooth = false; // ofSetWindowTitle("graphics example"); ofSetFrameRate(60); // if vertical sync is off, we can go a bit fast... this caps the framerate at 60fps. //----------------------------------- } //-------------------------------------------------------------- void DocumentRoot::_update() { //-------------------------------------- if(!isMouseDown()){ _forceX *= 0.95; _forceY *= 0.95; float temp; temp = x(); temp += _forceX; x(temp); temp = y(); temp += _forceY; y(temp); } else { _preX = x(); _preY = y(); } //-------------------------------------- //-------------------------------------- flGraphics* g; g = graphics(); g->clear(); //背景色 g->beginFill(0x888888, 0.1); g->drawRect(0, 0, ofGetWidth(), ofGetHeight()); g->endFill(); //透明のヒットエリア g->beginFill(0x0000cc, 0); g->drawRect(-x(), -y(), ofGetWidth(), ofGetHeight()); g->endFill(); //-------------------------------------- //----------------------------------- //copy from examples/graphics/graphicsExample //graphicsExampleのコードを書き写し counter = counter + 0.033f; //----------------------------------- } //-------------------------------------------------------------- void DocumentRoot::_draw() { //----------------------------------- //copy from examples/graphics/graphicsExample //graphicsExampleのコードを書き写し //--------------------------- circles //let's draw a circle: ofSetColor(255,130,0); float radius = 50 + 10 * sin(counter); ofFill(); // draw "filled shapes" ofDrawCircle(100,400,radius); // now just an outline ofNoFill(); ofSetHexColor(0xCCCCCC); ofDrawCircle(100,400,80); // use the bitMap type // note, this can be slow on some graphics cards // because it is using glDrawPixels which varies in // speed from system to system. try using ofTrueTypeFont // if this bitMap type slows you down. ofSetHexColor(0x000000); ofDrawBitmapString("circle", 75,500); //--------------------------- rectangles ofFill(); for (int i = 0; i < 200; i++){ ofSetColor((int)ofRandom(0,255),(int)ofRandom(0,255),(int)ofRandom(0,255)); ofDrawRectangle(ofRandom(250,350),ofRandom(350,450),ofRandom(10,20),ofRandom(10,20)); } ofSetHexColor(0x000000); ofDrawBitmapString("rectangles", 275,500); //--------------------------- transparency ofSetHexColor(0x00FF33); ofDrawRectangle(400,350,100,100); // alpha is usually turned off - for speed puposes. let's turn it on! ofEnableAlphaBlending(); ofSetColor(255,0,0,127); // red, 50% transparent ofDrawRectangle(450,430,100,33); ofSetColor(255,0,0,(int)(counter * 10.0f) % 255); // red, variable transparent ofDrawRectangle(450,370,100,33); ofDisableAlphaBlending(); ofSetHexColor(0x000000); ofDrawBitmapString("transparency", 410,500); //--------------------------- lines // a bunch of red lines, make them smooth if the flag is set ofSetHexColor(0xFF0000); for (int i = 0; i < 20; i++){ ofDrawLine(600,300 + (i*5),800, 250 + (i*10)); } ofSetHexColor(0x000000); ofDrawBitmapString("lines\npress 's' to toggle smoothness", 600,500); //----------------------------------- } //============================================================== // Public Method //============================================================== //============================================================== // Protected / Private Method //============================================================== //============================================================== // Private Event Handler //============================================================== //-------------------------------------------------------------- void DocumentRoot::_eventHandler(flEvent& event) { cout << "[DocumentRoot]_eventHandler(" + event.type() + ")"; if(event.type() == flEvent::ADDED_TO_STAGE) { removeEventListener(flEvent::ADDED_TO_STAGE, this, &DocumentRoot::_eventHandler); stage()->addEventListener(flKeyboardEvent::KEY_PRESS, this, &DocumentRoot::_keyboardEventHandler); stage()->addEventListener(flKeyboardEvent::KEY_RELEASE, this, &DocumentRoot::_keyboardEventHandler); } } //-------------------------------------------------------------- void DocumentRoot::_keyboardEventHandler(flEvent& event) { // cout << "[DocumentRoot]_keyboardEventHandler(" + event.type() + ")"; flKeyboardEvent* keyboardEvent = dynamic_cast<flKeyboardEvent*>(&event); int key = keyboardEvent->keyCode(); if(event.type() == flKeyboardEvent::KEY_PRESS) { //----------------------------------- //copy from examples/graphics/graphicsExample //graphicsExampleのコードを書き写し if (key == 's') { bSmooth = !bSmooth; if (bSmooth){ ofEnableAntiAliasing(); }else{ ofDisableAntiAliasing(); } } //----------------------------------- } if(event.type() == flKeyboardEvent::KEY_RELEASE) { } } //-------------------------------------------------------------- void DocumentRoot::_moveEventHandler(flEvent& event) { //cout << "[DocumentRoot]_moveEventHandler(" << event.type() << ")" << endl; // cout << "mouse is moving" << endl; } //-------------------------------------------------------------- void DocumentRoot::_mouseEventHandler(flEvent& event) { // cout << "[DocumentRoot]_mouseEventHandler(" << event.type() << ")" << endl; // cout << "[PrentBox]this = " << this << endl; // cout << "[ParetBox]currentTarget = " << event.currentTarget() << endl; // cout << "[ParetBox]target = " << event.target() << endl; if(event.type() == flMouseEvent::MOUSE_OVER) { if(event.target() == this) { } } if(event.type() == flMouseEvent::MOUSE_OUT) { if(event.target() == this) { } } if(event.type() == flMouseEvent::MOUSE_DOWN) { if(event.target() == this) { startDrag(); stage()->addEventListener(flMouseEvent::MOUSE_UP, this, &DocumentRoot::_mouseEventHandler); stage()->addEventListener(flMouseEvent::MOUSE_MOVE, this, &DocumentRoot::_moveEventHandler); } } if(event.type() == flMouseEvent::MOUSE_UP) { if(event.currentTarget() == stage()) { stopDrag(); stage()->removeEventListener(flMouseEvent::MOUSE_UP, this, &DocumentRoot::_mouseEventHandler); stage()->removeEventListener(flMouseEvent::MOUSE_MOVE, this, &DocumentRoot::_moveEventHandler); _forceX = (x() - _preX) * 0.5; _forceY = (y() - _preY) * 0.5; } } }
34.022814
109
0.456638
selflash
f0a6282ef467cbb597f6376aa9e36c7f9759eb46
3,508
cpp
C++
src/SQLite.cpp
nianfh/beebox
a2c68847a442f1d4bcb80d9eefb7c0c7682f748a
[ "MIT" ]
1
2018-07-11T03:47:41.000Z
2018-07-11T03:47:41.000Z
src/SQLite.cpp
nianfh/beebox
a2c68847a442f1d4bcb80d9eefb7c0c7682f748a
[ "MIT" ]
null
null
null
src/SQLite.cpp
nianfh/beebox
a2c68847a442f1d4bcb80d9eefb7c0c7682f748a
[ "MIT" ]
null
null
null
#include "SQLite.h" #include <sqlite3/sqlite3.h> #include <stdio.h> #include <vector> namespace beebox { CSQLite::CSQLite() { m_db = NULL; } CSQLite::~CSQLite() { close(); } bool CSQLite::open(string filePath) { if (m_db) { close(); } return sqlite3_open_v2(filePath.c_str(), &m_db, SQLITE_OPEN_READWRITE, NULL) == SQLITE_OK ? true : false; } void CSQLite::close() { sqlite3_close(m_db); } bool CSQLite::create(string filePath) { return sqlite3_open_v2(filePath.c_str(), &m_db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL) == SQLITE_OK ? true : false; } bool CSQLite::select(string sql, string& recordInJson) { sqlite3_stmt* res = NULL; const char* unused = NULL; recordInJson.clear(); int rc = sqlite3_prepare_v2(m_db, sql.c_str(), sql.size(), &res, &unused); if (rc != SQLITE_OK) { return false; } int columnCount = sqlite3_column_count(res); vector<string> fieldNameList; for (int i=0; i<columnCount; ++i) { const char* name = sqlite3_column_name(res, i); string _name = "\"" ; _name += name; _name += "\":"; fieldNameList.push_back(_name); } recordInJson += "["; rc = sqlite3_step(res); while(rc == SQLITE_ROW) { for(int i=0; i<columnCount; i++) { if (i == 0) { recordInJson += "{"; } string val = getValue(res, i); recordInJson += fieldNameList[i]; recordInJson += val.empty() ? "null" : val; if (i < columnCount - 1) { recordInJson += ","; } else { recordInJson += "}"; } } rc = sqlite3_step(res); if (rc == SQLITE_ROW) { recordInJson += ","; } } recordInJson += "]"; sqlite3_finalize(res); if (recordInJson.size() < 3) { recordInJson.clear(); } return true; } bool CSQLite::execute(string sql) { printf("########## sql: %s\n", sql.c_str()); char* errMsg = NULL; int rc = sqlite3_exec(m_db, sql.c_str(), 0, 0, &errMsg); if (rc != SQLITE_OK) { printf("SQL error:%s\n", errMsg); return false; } else { printf("SQL Execute OK!\n"); } return true; } string CSQLite::getError() { return sqlite3_errmsg(m_db); } string CSQLite::getValue(sqlite3_stmt* res, int columnIndex) { const unsigned char* pStr = NULL; int type = sqlite3_column_type(res, columnIndex); string out; char buffer[256] = {0}; switch(type) { case SQLITE_INTEGER: sprintf(buffer, "%d", sqlite3_column_int(res, columnIndex)); out = buffer; break; case SQLITE_FLOAT: sprintf(buffer, "%f", sqlite3_column_double(res, columnIndex)); out = buffer; break; case SQLITE3_TEXT: pStr = sqlite3_column_text(res, columnIndex); if (pStr) { out = "\""; out += (char*)pStr; out += "\""; } break; case SQLITE_BLOB: //sqlite3_column_bytes(res, 0); //(void*) sqlite3_column_blob(res, 0); out = "blob"; break; case SQLITE_NULL: out = ""; break; default: out = ""; break; }; return out; } } // namespace beebox
19.381215
80
0.517104
nianfh
f0ae115e5186c11bf9fd48e719659cc0cace4643
8,946
cpp
C++
Source/Gui3D-master/examples/build/EnvironmentDemo.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
3
2019-04-12T15:22:53.000Z
2022-01-05T02:59:56.000Z
Source/Gui3D-master/examples/build/EnvironmentDemo.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
null
null
null
Source/Gui3D-master/examples/build/EnvironmentDemo.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
2
2019-04-10T22:46:21.000Z
2020-05-27T16:21:37.000Z
#include <iostream> #include <sstream> #include <vector> #include <OGRE/Ogre.h> #include <OIS/OIS.h> #include "Gui3D.h" #include "Gui3DPanel.h" #include "MyEnvironmentDemoPanelColors.h" typedef struct PanelAndDirection { Gui3D::Panel* panel; Ogre::Vector3 cameraDirection; int yaw; } PanelAndDirection; class EnvironmentDemo : public Ogre::FrameListener, public OIS::KeyListener, public OIS::MouseListener { public: // Gui3D main object Gui3D::Gui3D* mGui3D; // Keep track of some captions to modify their contents on callback Gui3D::Caption* captionButton; Gui3D::Caption* captionChecked; Gui3D::Caption* captionCombobox; Ogre::SceneNode* tvNode; Ogre::Vector3 originalTvNodePos; Ogre::Entity* entSinbad; Ogre::AnimationState* a, *a2; Gui3D::Panel* mPanel; MyEnvironmentDemoPanelColors mMyEnvironmentDemoPanelColors; EnvironmentDemo() { originalTvNodePos = Ogre::Vector3(0, 1, 10); _makeOgre(); _makeOIS(); _makeScene(); mGui3D = new Gui3D::Gui3D(&mMyEnvironmentDemoPanelColors); mGui3D->createScreen(mViewport, "environmentDemo", "mainScreen"); mPanel = _createPanel(Ogre::Vector3(0, 5.3, -2.5), 180); mCamera->setPosition(0, 6.f, -8); mCamera->setDirection(Ogre::Vector3(0, 0, 1)); } Gui3D::Panel* _createPanel(Ogre::Vector3 pos, int yaw) { Gui3D::Panel* panel = new Gui3D::Panel( mGui3D, mSceneMgr, Ogre::Vector2(400, 400), 15, "environmentDemo", "kikoo"); panel->mNode->setPosition(pos); panel->mNode->yaw(Ogre::Degree(yaw)); panel->makeCaption(10, 10, 380, 30, "Move the TV please...", Gorilla::TextAlign_Centre); panel->makeCaption(10, 100, 90, 100, "Left", Gorilla::TextAlign_Centre, Gorilla::VerticalAlign_Middle); panel->makeCaption(310, 100, 90, 100, "Right", Gorilla::TextAlign_Centre, Gorilla::VerticalAlign_Middle); Gui3D::ScrollBar* s = panel->makeScrollBar(100, 100, 200, 100, 0, 15); s->setValueChangedCallback(this, &EnvironmentDemo::decalValueChanged); s->setStep(0.1); s->setDisplayedPrecision(0, false); s->setCallCallbackOnSelectingValue(true); s->setDisplayValue(false); return panel; } bool decalValueChanged(Gui3D::PanelElement* e) { Ogre::Vector3 pos = originalTvNodePos; pos.x -= ((Gui3D::ScrollBar*)e)->getValue(); tvNode->setPosition(pos); return true; } ~EnvironmentDemo() { delete mGui3D; std::ostringstream s; s << "\n** Average FPS (with FSAA to 1) is " << mWindow->getAverageFPS() << "\n\n"; Ogre::LogManager::getSingleton().logMessage(s.str()); delete mRoot; } bool frameStarted(const Ogre::FrameEvent& evt) { if (mWindow->isClosed()) return false; Ogre::Vector3 trans(0,0,0); if (mKeyboard->isKeyDown(OIS::KC_W)) trans.z = -1; else if (mKeyboard->isKeyDown(OIS::KC_S)) trans.z = 1; if (mKeyboard->isKeyDown(OIS::KC_A)) trans.x = -1; else if (mKeyboard->isKeyDown(OIS::KC_D)) trans.x = 1; if (trans.isZeroLength() == false) { Ogre::Vector3 pos = mCamera->getPosition(); pos += mCamera->getOrientation() * (trans * 10.0f) * evt.timeSinceLastFrame; pos.y = 6.0f; mCamera->setPosition(pos); } a->addTime(evt.timeSinceLastFrame); a2->addTime(evt.timeSinceLastFrame); mPanel->injectMouseMoved(mCamera->getCameraToViewportRay(0.5f, 0.5f)); mPanel->injectTime(evt.timeSinceLastFrame); mMouse->capture(); // Quit on ESCAPE Keyboard mKeyboard->capture(); if (mKeyboard->isKeyDown(OIS::KC_ESCAPE)) return false; return true; } bool keyPressed(const OIS::KeyEvent &e) { mPanel->injectKeyPressed(e); return true; } bool keyReleased(const OIS::KeyEvent &e) { mPanel->injectKeyReleased(e); return true; } bool mousePressed(const OIS::MouseEvent &evt, OIS::MouseButtonID id) { mPanel->injectMousePressed(evt, id); return true; } bool mouseReleased(const OIS::MouseEvent &evt, OIS::MouseButtonID id) { mPanel->injectMouseReleased(evt, id); return true; } bool mouseMoved(const OIS::MouseEvent &arg) { Ogre::Real pitch = Ogre::Real(arg.state.Y.rel) * -0.005f; Ogre::Real yaw = Ogre::Real(arg.state.X.rel) * -0.005f; mCamera->pitch(Ogre::Radian(pitch)); mCamera->yaw(Ogre::Radian(yaw)); return true; } void _makeOgre() { mRoot = new Ogre::Root("", ""); mRoot->addFrameListener(this); #if OGRE_PLATFORM == OGRE_PLATFORM_LINUX mRoot->loadPlugin(OGRE_RENDERER); #else #if 1 #ifdef _DEBUG mRoot->loadPlugin("RenderSystem_Direct3D9_d"); #else mRoot->loadPlugin("RenderSystem_Direct3D9"); #endif #else #ifdef _DEBUG mRoot->loadPlugin("RenderSystem_GL_d.dll"); #else mRoot->loadPlugin("RenderSystem_GL.dll"); #endif #endif #endif mRoot->setRenderSystem(mRoot->getAvailableRenderers()[0]); Ogre::ResourceGroupManager* rgm = Ogre::ResourceGroupManager::getSingletonPtr(); rgm->addResourceLocation(".", "FileSystem"); rgm->addResourceLocation("sinbad.zip", "Zip"); mRoot->initialise(false); Ogre::NameValuePairList misc; misc["FSAA"] = "1"; mWindow = mRoot->createRenderWindow("Gorilla", 800, 600, false, &misc); mSceneMgr = mRoot->createSceneManager(Ogre::ST_EXTERIOR_CLOSE); mCamera = mSceneMgr->createCamera("Camera"); mViewport = mWindow->addViewport(mCamera); mViewport->setBackgroundColour(Ogre::ColourValue(0./255, 80./255, 160./255, .5f)); rgm->initialiseAllResourceGroups(); tvNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); tvNode->setPosition(originalTvNodePos); tvNode->setScale(2, 2, 2); Ogre::Entity* entTV = mSceneMgr->createEntity("TV.mesh"); tvNode->attachObject(entTV); Ogre::SceneNode* sinbadNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); sinbadNode->setPosition(0, 2, -2.2); sinbadNode->setScale(0.4, 0.4, 0.4); sinbadNode->yaw(Ogre::Degree(180)); entSinbad = mSceneMgr->createEntity("sinbad.mesh"); sinbadNode->attachObject(entSinbad); entSinbad->getSkeleton()->setBlendMode(Ogre::ANIMBLEND_CUMULATIVE); a = entSinbad->getAnimationState("IdleBase"); a->setEnabled(true); a->setLoop(true); a2 = entSinbad->getAnimationState("IdleTop"); a2->setEnabled(true); a2->setLoop(true); //mCameraNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); //mCameraNode->attachObject(mCamera); mCamera->setNearClipDistance(0.05f); mCamera->setFarClipDistance(1000); } void _makeOIS() { // Initialise OIS OIS::ParamList pl; size_t windowHnd = 0; std::ostringstream windowHndStr; mWindow->getCustomAttribute("WINDOW", &windowHnd); windowHndStr << windowHnd; pl.insert(std::make_pair(Ogre::String("WINDOW"), windowHndStr.str())); mInputManager = OIS::InputManager::createInputSystem(pl); mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject(OIS::OISKeyboard, true)); mKeyboard->setEventCallback(this); mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject(OIS::OISMouse, true)); mMouse->setEventCallback(this); mMouse->getMouseState().width = mViewport->getActualWidth(); mMouse->getMouseState().height = mViewport->getActualHeight(); } void _makeScene() { Ogre::Plane plane(Ogre::Vector3::UNIT_Y, 0); Ogre::MeshManager::getSingleton().createPlane("ground", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, plane, 1500, 1500, 20, 20, true, 1, 150, 150, Ogre::Vector3::UNIT_Z); Ogre::Entity* entGround = mSceneMgr->createEntity("GroundEntity", "ground"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(entGround); entGround->setMaterialName("Gui3DExample/Ground"); entGround->setCastShadows(false); } Ogre::Root* mRoot; Ogre::RenderWindow* mWindow; Ogre::Viewport* mViewport; Ogre::SceneManager* mSceneMgr; Ogre::Camera* mCamera; OIS::InputManager* mInputManager; OIS::Keyboard* mKeyboard; OIS::Mouse* mMouse; }; int main() { EnvironmentDemo* demo = new EnvironmentDemo(); demo->mRoot->startRendering(); delete demo; return 0; }
30.848276
120
0.625755
shanefarris
f0ae79a162cee6343a9cc5bdc989da19c7e0c60c
1,923
cpp
C++
scripts/project_euler/euler_problem_37.cpp
cannontwo/cannon
4be79f3a6200d1a3cd26c28c8f2250dbdf08f267
[ "MIT" ]
null
null
null
scripts/project_euler/euler_problem_37.cpp
cannontwo/cannon
4be79f3a6200d1a3cd26c28c8f2250dbdf08f267
[ "MIT" ]
46
2021-01-12T23:03:52.000Z
2021-10-01T17:29:01.000Z
scripts/project_euler/euler_problem_37.cpp
cannontwo/cannon
4be79f3a6200d1a3cd26c28c8f2250dbdf08f267
[ "MIT" ]
null
null
null
#include <iostream> #include <cassert> #include <cmath> #include <algorithm> #include <cannon/log/registry.hpp> #include <cannon/math/primes.hpp> #include <cannon/math/digits.hpp> using namespace cannon::log; using namespace cannon::math; /*! * The number 3797 has an interesting property. Being prime itself, it is * possible to continuously remove digits from left o right, and remain prime at * each stage: 3797, 797, 97, and 7. Similarly, we can work from right to left: * 3797, 379, 37, and 3. * * Find the sum of the only eleven primes that are both truncatable from left to * right and right to left. * * Note: 2, 3, 5, and 7 are not considered to be truncatable primes. */ bool is_right_truncatable(unsigned int x) { if (!is_prime(x)) return false; while (x != 0) { if (!is_prime(x)) return false; x /= 10; } return true; } bool is_left_truncatable(unsigned int x) { while (x != 0) { if (!is_prime(x)) return false; unsigned int first_digit_pow = std::floor(std::log10(x)); unsigned int first_digit = x / std::pow(10, first_digit_pow); x -= first_digit * std::pow(10, first_digit_pow); } return true; } bool is_truncatable(unsigned int x) { return is_left_truncatable(x) && is_right_truncatable(x); } unsigned int compute_truncatable_primes_sum() { unsigned int sum = 0; unsigned int num_truncatable = 0; unsigned int upper = 1000; auto primes = get_primes_up_to(upper); // Skipping 2-7 unsigned int i = 4; while (num_truncatable < 11) { for (; i < primes.size(); ++i) { if (is_truncatable(primes[i])) { log_info("Found truncatable prime:", primes[i]); sum += primes[i]; ++num_truncatable; } } upper *= 2; primes = get_primes_up_to(upper); } return sum; } int main(int argc, char** argv) { std::cout << compute_truncatable_primes_sum() << std::endl; }
22.360465
80
0.656786
cannontwo
f0af743f6522a91956e542645b9de037882c3874
1,901
cpp
C++
src/main.cpp
vieiraa/ray_tracer
75665fd5b15f486ad52f3c5b61521fb394d40fe1
[ "MIT" ]
null
null
null
src/main.cpp
vieiraa/ray_tracer
75665fd5b15f486ad52f3c5b61521fb394d40fe1
[ "MIT" ]
null
null
null
src/main.cpp
vieiraa/ray_tracer
75665fd5b15f486ad52f3c5b61521fb394d40fe1
[ "MIT" ]
null
null
null
#include <chrono> #include <glm/geometric.hpp> #include "camera.h" #include "orthographic_camera.h" #include "pinhole_camera.h" #include "scene.h" #include "buffer.h" #include "raytracer.h" #include "path_tracer.h" #include "bvh.h" int main() { unsigned int width = 256; unsigned int height = 256; PinholeCamera camera(-2.5f, 2.5f, -2.5f, 2.5f, 5.0f, glm::ivec2(width, height), glm::vec3(0.0f, 0.0f, 6.0f), // position glm::vec3(0.0f, -1.0f, 0.0f), // up glm::vec3(0.0f, 0.0f, -1.0f)); // look at Scene scene; scene.load(); //Primitives number std::cout << "\nNumber of primitives: " << scene.primitives_.size(); // acceleration structure construction time auto start1 = std::chrono::high_resolution_clock::now(); scene.acc_ = std::make_unique<BVH_SAH>(scene.primitives_); auto duration1 = std::chrono:: duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock::now() - start1); std::cout << "\nBVH construction time: " << duration1.count() << "s" << std::endl; Buffer rendering_buffer(width, height); glm::vec3 background_color(1.0f, 1.0f, 1.0f); // Set up the renderer. PathTracer rt(camera, scene, background_color, rendering_buffer); auto start2 = std::chrono::high_resolution_clock::now(); rt.integrate(); // Renders the final image. auto duration2 = std::chrono:: duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock::now() - start2); std::cout << "\nElapsed time: " << duration2.count() << "s" << std::endl; // Save the rendered image to a .ppm file. rendering_buffer.save("teste.ppm"); return 0; }
30.174603
89
0.571804
vieiraa
f0af752401c2358f7c738dff258fa6e5bb7e7176
2,477
hpp
C++
include/clotho/utility/linear_bit_block_iterator.hpp
putnampp/clotho
6dbfd82ef37b4265381cd78888cd6da8c61c68c2
[ "ECL-2.0", "Apache-2.0" ]
3
2015-06-16T21:27:57.000Z
2022-01-25T23:26:54.000Z
include/clotho/utility/linear_bit_block_iterator.hpp
putnampp/clotho
6dbfd82ef37b4265381cd78888cd6da8c61c68c2
[ "ECL-2.0", "Apache-2.0" ]
3
2015-06-16T21:12:42.000Z
2015-06-23T12:41:00.000Z
include/clotho/utility/linear_bit_block_iterator.hpp
putnampp/clotho
6dbfd82ef37b4265381cd78888cd6da8c61c68c2
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// Copyright 2015 Patrick Putnam // // 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 LINEAR_BIT_BLOCK_ITERATOR_HPP_ #define LINEAR_BIT_BLOCK_ITERATOR_HPP_ #include "clotho/utility/bit_block_iterator_def.hpp" namespace clotho { namespace utility { namespace tag { struct linear_iterator_tag {}; } // namespace tag } // namespace utility } // namespace clotho namespace clotho { namespace utility { template < class Block > class bit_block_iterator < Block, clotho::utility::tag::linear_iterator_tag, typename std::enable_if< std::is_integral< Block >::value >::type > { public: typedef bit_block_iterator< Block, clotho::utility::tag::linear_iterator_tag, void > self_type; typedef Block block_type; bit_block_iterator( block_type b = (block_type)0) : m_val(b) , m_index(0) { if( (m_val & (block_type)1) == 0) next(); } bit_block_iterator( const self_type & rhs ) : m_val( rhs.m_val ) , m_index( rhs.m_index ) { } bit_block_iterator & operator++() { if( m_val ) next(); return *this; } bit_block_iterator operator++(int) { bit_block_iterator res(*this); this->operator++(); return res; } inline bool done() const { return (m_val == 0); } unsigned int operator*() const { return m_index; } bool operator==( const self_type & rhs ) const { return (this->m_val == rhs.m_val); } bool operator!=(const self_type & rhs ) const { return (this->m_val != rhs.m_val); } virtual ~bit_block_iterator() {} protected: inline void next() { do { m_val >>= 1; ++m_index; } while( (m_val != 0) && (m_val & (block_type)1) == 0 ); } block_type m_val; unsigned int m_index; }; } // namespace utility { } // namespace clotho { #endif // LINEAR_BIT_BLOCK_ITERATOR_HPP_
25.802083
146
0.634639
putnampp
f0b0a5d96d62348b136ca0edc7e881fd7b6cea60
7,451
cpp
C++
SuperBigNum.cpp
W-YXN/MyNOIPProjects
0269a8385a6c8d87511236146f374f39dcdd2b82
[ "Apache-2.0" ]
null
null
null
SuperBigNum.cpp
W-YXN/MyNOIPProjects
0269a8385a6c8d87511236146f374f39dcdd2b82
[ "Apache-2.0" ]
null
null
null
SuperBigNum.cpp
W-YXN/MyNOIPProjects
0269a8385a6c8d87511236146f374f39dcdd2b82
[ "Apache-2.0" ]
1
2019-01-19T01:05:07.000Z
2019-01-19T01:05:07.000Z
#define max(a, b) a > b ? a : b #define min(a, b) a < b ? a : b class bign { public: int len, s[MAX_L]; bign(); bign(const char *); bign(int); bool sign; string toStr() const; friend istream &operator>>(istream &, bign &); friend ostream &operator<<(ostream &, bign &); bign operator=(const char *); bign operator=(int); bign operator=(const string); bool operator>(const bign &) const; bool operator>=(const bign &) const; bool operator<(const bign &) const; bool operator<=(const bign &) const; bool operator==(const bign &) const; bool operator!=(const bign &) const; bign operator+(const bign &) const; bign operator++(); bign operator++(int); bign operator+=(const bign &); bign operator-(const bign &) const; bign operator--(); bign operator--(int); bign operator-=(const bign &); bign operator*(const bign &)const; bign operator*(const int num) const; bign operator*=(const bign &); bign operator/(const bign &) const; bign operator/=(const bign &); bign operator%(const bign &) const; bign bign::operator%=(const bign &); bign factorial() const; bign Sqrt() const; bign pow(const bign &) const; void clean(); ~bign(); }; bign::bign() { memset(s, 0, sizeof(s)); len = 1; sign = 1; } bign::bign(const char *num) { *this = num; } bign::bign(int num) { *this = num; } string bign::toStr() const { string res; res = ""; for (int i = 0; i < len; i++) res = (char)(s[i] + '0') + res; if (res == "") res = "0"; if (!sign && res != "0") res = "-" + res; return res; } istream &operator>>(istream &in, bign &num) { string str; in >> str; num = str; return in; } ostream &operator<<(ostream &out, bign &num) { out << num.toStr(); return out; } bign bign::operator=(const char *num) { memset(s, 0, sizeof(s)); char a[MAX_L] = ""; if (num[0] != '-') strcpy(a, num); else for (int i = 1; i < strlen(num); i++) a[i - 1] = num[i]; sign = !(num[0] == '-'); len = strlen(a); for (int i = 0; i < strlen(a); i++) s[i] = a[len - i - 1] - 48; return *this; } bign bign::operator=(int num) { char temp[MAX_L]; sprintf(temp, "%d", num); *this = temp; return *this; } bign bign::operator=(const string num) { const char *tmp; tmp = num.c_str(); *this = tmp; return *this; } bool bign::operator<(const bign &num) const { if (sign ^ num.sign) return num.sign; if (len != num.len) return len < num.len; for (int i = len - 1; i >= 0; i--) if (s[i] != num.s[i]) return sign ? (s[i] < num.s[i]) : (!(s[i] < num.s[i])); return !sign; } bool bign::operator>(const bign &num) const { return num < *this; } bool bign::operator<=(const bign &num) const { return !(*this > num); } bool bign::operator>=(const bign &num) const { return !(*this < num); } bool bign::operator!=(const bign &num) const { return *this > num || *this < num; } bool bign::operator==(const bign &num) const { return !(num != *this); } bign bign::operator+(const bign &num) const { if (sign ^ num.sign) { bign tmp = sign ? num : *this; tmp.sign = 1; return sign ? *this - tmp : num - tmp; } bign result; result.len = 0; int temp = 0; for (int i = 0; temp || i < (max(len, num.len)); i++) { int t = s[i] + num.s[i] + temp; result.s[result.len++] = t % 10; temp = t / 10; } result.sign = sign; return result; } bign bign::operator++() { *this = *this + 1; return *this; } bign bign::operator++(int) { bign old = *this; ++(*this); return old; } bign bign::operator+=(const bign &num) { *this = *this + num; return *this; } bign bign::operator-(const bign &num) const { bign b = num, a = *this; if (!num.sign && !sign) { b.sign = 1; a.sign = 1; return b - a; } if (!b.sign) { b.sign = 1; return a + b; } if (!a.sign) { a.sign = 1; b = bign(0) - (a + b); return b; } if (a < b) { bign c = (b - a); c.sign = false; return c; } bign result; result.len = 0; for (int i = 0, g = 0; i < a.len; i++) { int x = a.s[i] - g; if (i < b.len) x -= b.s[i]; if (x >= 0) g = 0; else { g = 1; x += 10; } result.s[result.len++] = x; } result.clean(); return result; } bign bign::operator*(const bign &num) const { bign result; result.len = len + num.len; for (int i = 0; i < len; i++) for (int j = 0; j < num.len; j++) result.s[i + j] += s[i] * num.s[j]; for (int i = 0; i < result.len; i++) { result.s[i + 1] += result.s[i] / 10; result.s[i] %= 10; } result.clean(); result.sign = !(sign ^ num.sign); return result; } bign bign::operator*(const int num) const { bign x = num; bign z = *this; return x * z; } bign bign::operator*=(const bign &num) { *this = *this * num; return *this; } bign bign::operator/(const bign &num) const { bign ans; ans.len = len - num.len + 1; if (ans.len < 0) { ans.len = 1; return ans; } bign divisor = *this, divid = num; divisor.sign = divid.sign = 1; int k = ans.len - 1; int j = len - 1; while (k >= 0) { while (divisor.s[j] == 0) j--; if (k > j) k = j; char z[MAX_L]; memset(z, 0, sizeof(z)); for (int i = j; i >= k; i--) z[j - i] = divisor.s[i] + '0'; bign dividend = z; if (dividend < divid) { k--; continue; } int key = 0; while (divid * key <= dividend) key++; key--; ans.s[k] = key; bign temp = divid * key; for (int i = 0; i < k; i++) temp = temp * 10; divisor = divisor - temp; k--; } ans.clean(); ans.sign = !(sign ^ num.sign); return ans; } bign bign::operator/=(const bign &num) { *this = *this / num; return *this; } bign bign::operator%(const bign &num) const { bign a = *this, b = num; a.sign = b.sign = 1; bign result, temp = a / b * b; result = a - temp; result.sign = sign; return result; } bign bign::operator%=(const bign &num) { *this = *this % num; return *this; } bign bign::pow(const bign &num) const { bign result = 1; for (bign i = 0; i < num; i++) result = result * (*this); return result; } bign bign::factorial() const { bign result = 1; for (bign i = 1; i <= *this; i++) result *= i; return result; } void bign::clean() { if (len == 0) len++; while (len > 1 && s[len - 1] == '\0') len--; } bign bign::Sqrt() const { if (*this < 0) return -1; if (*this <= 1) return *this; bign l = 0, r = *this, mid; while (r - l > 1) { mid = (l + r) / 2; if (mid * mid > *this) r = mid; else l = mid; } return l; } bign::~bign() { //Nothing to do. }
18.911168
67
0.476715
W-YXN
f0b193b1898fab2aabee86a2b7a9cf98b7551b35
14,729
cpp
C++
source/smoothmethod.cpp
TianSHH/Picop
200fffde41eaf3fa5e041eaface306053f291056
[ "BSD-3-Clause" ]
1
2019-11-22T12:03:44.000Z
2019-11-22T12:03:44.000Z
source/smoothmethod.cpp
TianSHH/Picop
200fffde41eaf3fa5e041eaface306053f291056
[ "BSD-3-Clause" ]
null
null
null
source/smoothmethod.cpp
TianSHH/Picop
200fffde41eaf3fa5e041eaface306053f291056
[ "BSD-3-Clause" ]
null
null
null
#include "smoothmethod.h" SmoothMethod::SmoothMethod() { } SmoothMethod::~SmoothMethod() { } QImage SmoothMethod::averageFiltering(QImage *originImage) { bool ok; int filterRadius = QInputDialog::getInt(nullptr, QObject::tr("均值滤波"), "输入滤波器大小(1~30)", 3, 1, 30, 1, &ok); if (ok) { if (filterRadius % 2 == 0) filterRadius += 1; qDebug().noquote() << "[Debug]" << QDateTime::currentDateTimeUtc().toString("yyyy-MM-dd hh:mm:ss.zzz") << ":" << "图像平滑, 方式, 均值滤波" << "滤波器大小" << filterRadius; int kernel[filterRadius][filterRadius]; for (int i = 0; i < filterRadius; i++) for (int j = 0; j < filterRadius; j++) kernel[i][j] = 1; int len = filterRadius / 2; int originWidth = originImage->width(); int originHeight = originImage->height(); QImage targetImage = QImage(originWidth + 2 * len, originHeight + 2 * len, QImage::Format_RGB32); // 添加边框 for (int i = 0; i < targetImage.width(); i++) for (int j = 0; j < targetImage.height(); j++) if (i >= len && i < targetImage.width() - len && j >= len && j < targetImage.height() - len) { // 不在边框中 QColor originImageColor = QColor(originImage->pixel(i - len, j - len)); targetImage.setPixelColor(i, j, originImageColor); } else // 在边框中 targetImage.setPixel(i, j, Qt::white); // 将边框中颜色设置为白色 for (int i = len; i < targetImage.width() - len; i++) for (int j = len; j < targetImage.height() - len; j++) { int r = 0; int g = 0; int b = 0; for (int p = -len; p <= len; p++) for (int q = -len; q <= len; q++) { r = targetImage.pixelColor(i + p, j + q).red() * kernel[len + p][len + q] + r; g = targetImage.pixelColor(i + p, j + q).green() * kernel[len + p][len + q] + g; b = targetImage.pixelColor(i + p, j + q).blue() * kernel[len + p][len + q] + b; } r /= (filterRadius * filterRadius); g /= (filterRadius * filterRadius); b /= (filterRadius * filterRadius); if (((i - len) >= 0) && ((i - len) < originWidth) && ((j - len) >= 0) && ((j - len) < originHeight)) originImage->setPixel(i - len, j - len, qRgb(r, g, b)); } } return (*originImage); } // averageFiltering QImage SmoothMethod::medianFiltering(QImage *originImage) { // originImage 格式为 Format_RGB32 bool ok; int filterRadius = QInputDialog::getInt(nullptr, QObject::tr("中值滤波"), "输入滤波器大小(1~30)", 3, 1, 30, 1, &ok); if (ok) { if (filterRadius % 2 == 0) filterRadius += 1; qDebug().noquote() << "[Debug]" << QDateTime::currentDateTimeUtc().toString("yyyy-MM-dd hh:mm:ss.zzz") << ":" << "图像平滑, 方式, 中值滤波" << "滤波器大小" << filterRadius; int len = filterRadius / 2; int threshold = filterRadius * filterRadius / 2 + 1; int originWidth = originImage->width(); int originHeight = originImage->height(); QImage middleImage = QImage(originWidth + 2 * len, originHeight + 2 * len, QImage::Format_RGB32); QImage targetImage = QImage(originWidth, originHeight, QImage::Format_RGB32); // 初始化 middleImage for (int i = 0; i < middleImage.width(); i++) { for (int j = 0; j < middleImage.height(); j++) { if ((i >= len) && (i < (middleImage.width() - len)) && (j >= len) && (j < (middleImage.height() - len))) { // 像素点不在边框中 middleImage.setPixelColor(i, j, QColor(originImage->pixel(i - len, j - len))); } else { // 像素点在边框中 middleImage.setPixelColor(i, j, Qt::white); } } } // 使用直方图记录窗口中出现的像素的出现次数 int redHist[256] = {0}; int greenHist[256] = {0}; int blueHist[256] = {0}; int grayHist[256] = {0}; for (int i = len; i < middleImage.width() - len; i++) { for (int j = len; j < middleImage.height() - len; j++) { // 设置窗口 if (j == len) { // 每到新的一列, 初始化直方图 memset(redHist, 0, sizeof(redHist)); memset(greenHist, 0, sizeof(greenHist)); memset(blueHist, 0, sizeof(blueHist)); memset(grayHist, 0, sizeof(grayHist)); for (int p = -len; p <= len; p++) { for (int q = -len; q <= len; q++) { int red = qRed(middleImage.pixel(i + p, j + q)); int green = qGreen(middleImage.pixel(i + p, j + q)); int blue = qBlue(middleImage.pixel(i + p, j + q)); int gray = qGray(middleImage.pixel(i + p, j + q)); redHist[red]++; greenHist[green]++; blueHist[blue]++; grayHist[gray]++; } } } else { // 列数增加, 窗口按列向下移动, 为窗口新添加一行像素值, 并删去一行像素值 int oldWindowStartCol = j - len - 1; int newWindowEndCol = j + len; for (int p = -len; p <= len; p++) { // 要减去的列的像素值, 从窗口上到窗口下, 即 [j-len,j+len] int red = qRed(middleImage.pixel(i + p, oldWindowStartCol)); int green = qGreen(middleImage.pixel(i + p, oldWindowStartCol)); int blue = qBlue(middleImage.pixel(i + p, oldWindowStartCol)); int gray = qGray(middleImage.pixel(i + p, oldWindowStartCol)); redHist[red]--; greenHist[green]--; blueHist[blue]--; grayHist[gray]--; red = qRed(middleImage.pixel(i + p, newWindowEndCol)); green = qGreen(middleImage.pixel(i + p, newWindowEndCol)); blue = qBlue(middleImage.pixel(i + p, newWindowEndCol)); gray = qGray(middleImage.pixel(i + p, newWindowEndCol)); redHist[red]++; greenHist[green]++; blueHist[blue]++; grayHist[gray]++; } } // 获取窗口内像素中值 int r = getMedianValue(redHist, threshold); int g = getMedianValue(greenHist, threshold); int b = getMedianValue(blueHist, threshold); targetImage.setPixel(i - len, j - len, qRgb(r, g, b)); } } return targetImage; } } // medianFiltering // 获取窗口中像素的中值 int SmoothMethod::getMedianValue(const int *histogram, int threshold) { int sum = 0; for (int i = 0; i < 256; i++) { sum += histogram[i]; if (sum >= threshold) return i; } return 255; } // getMedianValue QImage SmoothMethod::KNNF(QImage originImage) { bool ok1; bool ok2; int filterRadius = QInputDialog::getInt(nullptr, QObject::tr("K近邻均值滤波"), "输入滤波器大小(1~30)", 3, 1, 30, 1, &ok1); int K = QInputDialog::getInt(nullptr, QObject::tr("K近邻均值平滑"), "输入K值", 1, 1, 30, 1, &ok2); if (ok1 & ok2) { if (filterRadius % 2 == 0) filterRadius += 1; qDebug().noquote().nospace() << "[Debug] " << QDateTime::currentDateTimeUtc().toString("yyyy-MM-dd hh:mm:ss.zzz") << ": " << "图像平滑, 方式, K近邻均值滤波, " << "滤波器大小, " << filterRadius << ", " << "K值, " << K; // int kernel[filterRadius][filterRadius]; // for (int i = 0; i < filterRadius; i++) // for (int j = 0; j < filterRadius; j++) // kernel[i][j] = 1; int len = filterRadius / 2; int originWidth = originImage.width(); int originHeight = originImage.height(); QImage middleImage = QImage(originWidth + 2 * len, originHeight + 2 * len, QImage::Format_RGB32); QImage targetImage = QImage(originWidth, originHeight, QImage::Format_RGB32); // 添加边框 for (int i = 0; i < middleImage.width(); i++) for (int j = 0; j < middleImage.height(); j++) if (i >= len && i < middleImage.width() - len && j >= len && j < middleImage.height() - len) { // 不在边框中 middleImage.setPixelColor(i, j, QColor(originImage.pixel(i - len, j - len))); } else { // 在边框中 middleImage.setPixel(i, j, Qt::white); // 将边框中颜色设置为白色 } int redHist[256] = {0}; int greenHist[256] = {0}; int blueHist[256] = {0}; for (int i = len; i < middleImage.width() - len; i++) for (int j = len; j < middleImage.height() - len; j++) { // 设置窗口 if (j == len) { // 每到新的一列, 初始化直方图 memset(redHist, 0, sizeof(redHist)); memset(greenHist, 0, sizeof(greenHist)); memset(blueHist, 0, sizeof(blueHist)); for (int p = -len; p <= len; p++) { for (int q = -len; q <= len; q++) { int red = qRed(middleImage.pixel(i + p, j + q)); int green = qGreen(middleImage.pixel(i + p, j + q)); int blue = qBlue(middleImage.pixel(i + p, j + q)); redHist[red]++; greenHist[green]++; blueHist[blue]++; } } } else { // 列数增加, 窗口按列向下移动, 为窗口新添加一行像素值, 并删去一行像素值 int oldWindowStartCol = j - len - 1; int newWindowEndCol = j + len; for (int p = -len; p <= len; p++) { // 要减去的列的像素值, 从窗口上到窗口下, 即 [j-len,j+len] int red = qRed(middleImage.pixel(i + p, oldWindowStartCol)); int green = qGreen(middleImage.pixel(i + p, oldWindowStartCol)); int blue = qBlue(middleImage.pixel(i + p, oldWindowStartCol)); redHist[red]--; greenHist[green]--; blueHist[blue]--; red = qRed(middleImage.pixel(i + p, newWindowEndCol)); green = qGreen(middleImage.pixel(i + p, newWindowEndCol)); blue = qBlue(middleImage.pixel(i + p, newWindowEndCol)); redHist[red]++; greenHist[green]++; blueHist[blue]++; } } int r = getKValue(redHist, qRed(middleImage.pixel(i, j)), K); int g = getKValue(greenHist, qGreen(middleImage.pixel(i, j)), K); int b = getKValue(blueHist, qBlue(middleImage.pixel(i, j)), K); // int r = getAverage(rKNNValue); // int g = getAverage(gKNNValue); // int b = getAverage(bKNNValue); targetImage.setPixel(i - len, j - len, qRgb(r, g, b)); } return targetImage; } return originImage; } // KNNF int SmoothMethod::getKValue(const int *histogram, int key, int K) { // 计算距离 key 的 K 近邻的方法也是桶排序 // 记录各点到 key 距离的数组长度不超过 255-key // bucket[255-key][0] => 像素值大于 key 的点其像素值与 key 的差值 // bucket[255-key][1] => 像素值小于 key 的点其像素值与 key 的差值 int bucket[255][2]; for (int i = 0; i <= 255; i++) { bucket[i][0] = 0; bucket[i][1] = 0; } for (int i = 0; i <= 255; i++) { if (histogram[i] > 0) { if (i - key >= 0) { bucket[i - key][0] = histogram[i]; } else { bucket[key - i][1] = histogram[i]; } } } int max = K + 1; int KNNValue[max] = {0}; K = K - 1; // 所有的 K 近邻点中 key 本身是第一个 KNNValue[0] = key; bucket[0][0]--; if (K <= 0) return key; // j 是 KNNValue 索引 for (int i = 0, j = 1; i <= 255; i++) { if (bucket[i][0] > 0) { // TODO 可优化 // 大于 key 的像素值 qDebug() << ">"; if (bucket[i][0] >= K) { for (int k = 0; k < K; j++, k++) { KNNValue[j] = i + key; } K = 0; } else { for (int k = 0; k < bucket[i][0]; j++, k++) { // 将所有像素值为 i 的点全部加入 KNNValue[j] = i + key; // 还原原始像素值 } K -= bucket[i][0]; } } if (K <= 0) break; if (bucket[i][1] > 0) { // 小于 key 的像素值 qDebug() << "<"; if (bucket[i][1] >= K) { for (int k = 0; k < K; j++, k++) { KNNValue[j] = key - i; } K = 0; } else { for (int k = 0; k < bucket[i][1]; j++, k++) { // 将所有像素值为 i 的点全部加入 KNNValue[j] = key - i; // 还原原始像素值 } K -= bucket[i][1]; } } if (K <= 0) break; } for (int i = 0; i < max - 1; i++) qDebug() << KNNValue[i]; // return KNNValue; int res = getAverage(KNNValue, max - 1); return res; } // getKValue int SmoothMethod::getAverage(const int *arr, int len) { int average = 0; for (int i = 0; i < len; i++) average += arr[i]; int res = average / len; return res; } // getAverage
34.494145
129
0.42345
TianSHH
f0b19e8ef7819f07395c7199e2a6c9f000b5a0ec
2,548
cpp
C++
gen_desc/kitti_gen.cpp
lilin-hitcrt/RINet
0e28c26e015c50385816b2cbe6549583486fd486
[ "MIT" ]
5
2022-03-01T13:56:47.000Z
2022-03-09T02:57:15.000Z
gen_desc/kitti_gen.cpp
lilin-hitcrt/RINet
0e28c26e015c50385816b2cbe6549583486fd486
[ "MIT" ]
null
null
null
gen_desc/kitti_gen.cpp
lilin-hitcrt/RINet
0e28c26e015c50385816b2cbe6549583486fd486
[ "MIT" ]
1
2022-03-06T07:59:51.000Z
2022-03-06T07:59:51.000Z
#include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/visualization/cloud_viewer.h> #include <opencv2/opencv.hpp> #include "semanticConf.hpp" #include "genData.hpp" int main(int argc,char** argv){ if(argc<4){ std::cout<<"Usage: ./kitti_gen cloud_folder label_folder output_file"<<std::endl; exit(0); } std::string cloud_path=argv[1]; std::string label_path=argv[2]; bool label_valid[20]={0,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1}; bool use_min[20]={1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1}; int label_map[20]={-1,0,-1,-1,-1,-1,-1,-1,-1,1,2,3,4,5,6,7,8,9,10,11}; std::shared_ptr<semConf> semconf(new semConf("../conf/sem_config.yaml")); genData gener(cloud_path,label_path, semconf); CloudLPtr cloud(new CloudL); int totaldata = gener.totaldata; int num=0; pcl::visualization::CloudViewer viewer("cloud"); std::ofstream fout(argv[3],ios::binary); while (gener.getData(cloud)){ std::cout<<num<<"/"<<totaldata<<std::endl; CloudLPtr cloud_out(new CloudL); std::vector<float> dis_list; cloud_out->resize((label_map[19]+1)*360); dis_list.resize(cloud_out->size(),0.f); for(auto p:cloud->points){ if(label_valid[p.label]){ int angle=std::floor((std::atan2(p.y,p.x)+M_PI)*180./M_PI); if(angle<0||angle>359){ continue; } float dis=std::sqrt(p.x*p.x+p.y*p.y); if(dis>50){ continue; } auto& q=cloud_out->at(360*label_map[p.label]+angle); if(q.label>0){ float dis_temp=std::sqrt(q.x*q.x+q.y*q.y); if(use_min[p.label]){ if(dis<dis_temp){ q=p; dis_list[360*label_map[p.label]+angle]=dis; } }else{ if(dis>dis_temp){ q=p; dis_list[360*label_map[p.label]+angle]=dis; } } }else{ q=p; dis_list[360*label_map[p.label]+angle]=dis; } } } for(auto dis:dis_list){ fout.write((char*)(&dis),sizeof(dis)); } auto ccloud=semconf->getColorCloud(cloud_out); viewer.showCloud(ccloud); ++num; } fout.close(); return 0; }
36.4
89
0.494505
lilin-hitcrt
f0b9afdee429081c137cbabb2df8b2a312396ec3
1,221
cpp
C++
BAC_2nd/ch5/UVa12096.cpp
Anyrainel/aoapc-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
3
2017-08-15T06:00:01.000Z
2018-12-10T09:05:53.000Z
BAC_2nd/ch5/UVa12096.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
null
null
null
BAC_2nd/ch5/UVa12096.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
2
2017-09-16T18:46:27.000Z
2018-05-22T05:42:03.000Z
// UVa12096 The SetStack Computer // Rujia Liu #include<iostream> #include<string> #include<set> #include<map> #include<stack> #include<vector> #include<algorithm> using namespace std; #define ALL(x) x.begin(),x.end() #define INS(x) inserter(x,x.begin()) typedef set<int> Set; map<Set,int> IDcache; // 把集合映射成ID vector<Set> Setcache; // 根据ID取集合 // 查找给定集合x的ID。如果找不到,分配一个新ID int ID (Set x) { if (IDcache.count(x)) return IDcache[x]; Setcache.push_back(x); // 添加新集合 return IDcache[x] = Setcache.size() - 1; } int main () { int T; cin >> T; while(T--) { stack<int> s; // 题目中的栈 int n; cin >> n; for(int i = 0; i < n; i++) { string op; cin >> op; if (op[0] == 'P') s.push(ID(Set())); else if (op[0] == 'D') s.push(s.top()); else { Set x1 = Setcache[s.top()]; s.pop(); Set x2 = Setcache[s.top()]; s.pop(); Set x; if (op[0] == 'U') set_union (ALL(x1), ALL(x2), INS(x)); if (op[0] == 'I') set_intersection (ALL(x1), ALL(x2), INS(x)); if (op[0] == 'A') { x = x2; x.insert(ID(x1)); } s.push(ID(x)); } cout << Setcache[s.top()].size() << endl; } cout << "***" << endl; } return 0; }
23.037736
70
0.527437
Anyrainel
f0c266afdbbcaeb1c0628f623cfc342ab307f85c
5,958
hh
C++
Kaskade/fem/diffops/mooneyRivlin.hh
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
3
2019-07-03T14:03:31.000Z
2021-12-19T10:18:49.000Z
Kaskade/fem/diffops/mooneyRivlin.hh
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
6
2020-02-17T12:01:30.000Z
2021-12-09T22:02:33.000Z
Kaskade/fem/diffops/mooneyRivlin.hh
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
2
2020-12-03T04:41:18.000Z
2021-01-11T21:44:42.000Z
#ifndef MOONEY_RIVLIN_HH #define MOONEY_RIVLIN_HH #include "linalg/invariants.hh" #include "utilities/functionTools.hh" namespace Kaskade { template <int dim, class VolumetricPenalty = void, Invariant i = Invariant::Principal, class Direction = void> class MooneyRivlin; /** * \param lambda first Lame constant * \param mu second Lame constant */ template <class VolumetricPenalty, int dim, Invariant i = Invariant::Principal, class Direction = void> MooneyRivlin<dim,VolumetricPenalty,i,Direction> createMooneyRivlinFromLameConstants(double lambda, double mu) { static_assert(!std::is_same<VolumetricPenalty,void>::value,"not implemented"); VolumetricPenalty g; // std::cout << "g': " << g.d1(1) << ", g'': " << g.d2(1) << std::endl; //double c = (lambda + 2*mu)/(g.d2(1)-g.d1(1)); //double b = -0.5*mu - 0.5*c*g.d1(1); //double a = mu + 0.5*c*g.d1(1); double rho = g.d1(1)/(-g.d2(1)+g.d1(1)); double d = (lambda+2.0*mu)/(g.d2(1)-g.d1(1)); double c = (0.5*rho-0.25)*mu+0.25*rho*lambda; if(c > 0.25*mu) c = (rho-0.75)*mu+0.5*rho*lambda; double b = -mu + rho*(lambda+2.*mu)-2.*c; double a = b + mu; double alpha = 0.5*a - b; double beta = 0.5*b; // std::cout << "alpha: " << alpha << ", beta: " << beta << ", c: " << c << ", d: " << d << std::endl; if(a<0 || b<0 || c<0) { std::cout << "computed parameters: " << a << ", " << b << ", " << c << ", " << d << std::endl; std::cout << "alpha=" << alpha << ", beta=" << beta << std::endl; std::cout << "material law is not polyconvex" << std::endl; exit(1); } return MooneyRivlin<dim,VolumetricPenalty,i,Direction>(alpha,beta,c,d); } /** * \param E Young's modulus * \param nu Poisson ratio */ template <class VolumetricPenalty, int dim, Invariant i = Invariant::Principal, class Direction = void> MooneyRivlin<dim,VolumetricPenalty,i,Direction> createMooneyRivlinFromMaterialConstants(double E, double nu) { static_assert(!std::is_same<VolumetricPenalty,void>::value,"not implemented"); double lambda = E*nu/((1+nu)*(1-2*nu)); double mu = E/(2*(1+nu)); return createMooneyRivlinFromLameConstants<VolumetricPenalty,dim,i,Direction>(lambda,mu); } template <int dim, class VolumetricPenalty, Invariant i, class Direction> class MooneyRivlin : public StrainBase<double,dim>, public Sum<Scaled<ShiftedInvariant<typename ChooseInvariant<1,dim,i,CauchyGreenTensor<double,dim>,Direction>::type> >, Scaled<ShiftedInvariant<typename ChooseInvariant<2,dim,i,CauchyGreenTensor<double,dim>,Direction>::type> >, MatrixToScalarFunction<VolumetricPenalty,Determinant<dim> > > { typedef typename ChooseInvariant<1,dim,i,CauchyGreenTensor<double,dim>,Direction>::type Inv1; typedef ShiftedInvariant<Inv1> SInv1; typedef typename ChooseInvariant<2,dim,i,CauchyGreenTensor<double,dim>,Direction>::type Inv2; typedef ShiftedInvariant<Inv2> SInv2; typedef Determinant<dim> Det; typedef MatrixToScalarFunction<VolumetricPenalty,Det>Penalty; typedef Sum<Scaled<SInv1>,Scaled<SInv2>,Penalty> Base; using StrainBase<double,dim>::F; using StrainBase<double,dim>::S; public: typedef double Scalar; MooneyRivlin(double lambda, double mu) : MooneyRivlin(createMooneyRivlinFromLameConstants<VolumetricPenalty,dim>(lambda,mu)) {} // template <class Scalar, class enable = typename std::enable_if<std::is_same<Scalar,double>::value && std::is_same<Direction,void>::value,void>::type> MooneyRivlin(double c0, double c1, double c2, double c3) : StrainBase<double,dim>(), Base(Scaled<SInv1>(c0,SInv1(Inv1(S),dim)), Scaled<SInv2>(c1,SInv2(Inv2(S),dim)), Penalty(Det(F),VolumetricPenalty(c2,c3))) { assert(c0>0 && c1>0 && c2>0); } template <class Dir, class enable = typename std::enable_if< std::is_same<Direction,Dir>::value && !std::is_same<void,Direction>::value,void>::type> MooneyRivlin(double c0, double c1, double c2, double c3, Dir d) : StrainBase<double,dim>(), Base(Scaled<SInv1>(c0,SInv1(Inv1(S,d),dim)), Scaled<SInv2>(c1,SInv2(Inv2(S,d),dim)), Penalty(Det(F),VolumetricPenalty(c2,c3))) { assert(c0>0 && c1>0 && c2>0); } MooneyRivlin(MooneyRivlin const&) = default; MooneyRivlin& operator=(MooneyRivlin const&) = default; }; template <int dim, Invariant i,class Direction> class MooneyRivlin<dim,void,i,Direction> : public StrainBase<double,dim>, public Sum<Scaled<ShiftedInvariant<typename ChooseInvariant<1,dim,i,CauchyGreenTensor<double,dim>,Direction>::type> >, Scaled<ShiftedInvariant<typename ChooseInvariant<2,dim,i,CauchyGreenTensor<double,dim>,Direction>::type> > > { typedef typename ChooseInvariant<1,dim,i,CauchyGreenTensor<double,dim>,Direction>::type Inv1; typedef typename ChooseInvariant<2,dim,i,CauchyGreenTensor<double,dim>,Direction>::type Inv2; typedef ShiftedInvariant<Inv1> SInv1; typedef ShiftedInvariant<Inv2> SInv2; typedef Sum<Scaled<SInv1>,Scaled<SInv2> > Base; using StrainBase<double,dim>::S; public: typedef double Scalar; template <class Scalar, class enable = typename std::enable_if<std::is_same<Scalar,double>::value && std::is_same<Direction,void>::value,void>::type> MooneyRivlin(double c0, double c1) : StrainBase<double,dim>(), Base(Scaled<SInv1>(c0,SInv1(Inv1(S),dim)),Scaled<SInv2>(c1,SInv2(Inv2(S),dim))) { assert(c0>0 && c1>0); } template <class Scalar, class enable = typename std::enable_if<std::is_same<Scalar,double>::value && !std::is_same<Direction,void>::value,void>::type> MooneyRivlin(double c0, double c1, Direction const& d) : StrainBase<double,dim>(), Base(Scaled<SInv1>(c0,SInv1(Inv1(S,d),dim)),Scaled<SInv2>(c1,SInv2(Inv2(S,d),dim))) { assert(c0>0 && c1>0); } MooneyRivlin(MooneyRivlin const&) = default; MooneyRivlin& operator=(MooneyRivlin const&) = default; }; } #endif
46.546875
158
0.678583
chenzongxiong
f0c422605b8c43b5b392f5f57e418a229c356f8d
970
hpp
C++
include/defines.hpp
Yao-Chung/Sokoban-Agent
7135a51ee8a912fe8a636ccfeecbcd3551e6720c
[ "BSD-3-Clause" ]
null
null
null
include/defines.hpp
Yao-Chung/Sokoban-Agent
7135a51ee8a912fe8a636ccfeecbcd3551e6720c
[ "BSD-3-Clause" ]
null
null
null
include/defines.hpp
Yao-Chung/Sokoban-Agent
7135a51ee8a912fe8a636ccfeecbcd3551e6720c
[ "BSD-3-Clause" ]
null
null
null
#ifndef SOKOBAN_AGENT_DEFINES #define SOKOBAN_AGENT_DEFINES #include <vector> #include <string> #include <iostream> enum MoveDirection{ Left = 0, Right = 1, Up = 2, Down = 3, Unspecified = -1, }; using Map = std::vector<std::string>; using Position = std::pair<int, int>; using Decimal = float; std::string getKey(const Map map); std::string getKey(const Position manPos, const std::vector<Position> boxPos); std::pair< Position, std::vector<Position> > getPositions(const Map map); Map move(const Map& map, const MoveDirection direction, const Map& level); void write_solution(const std::string filename, const Map& map, const std::vector<MoveDirection>& policy); std::vector< std::pair<Map, std::vector<MoveDirection>> > read_solutions(std::string filename); Map readMap(std::istream &stream); std::vector< std::pair<Map, std::vector<MoveDirection>> > clean_solutions(std::vector< std::pair<Map, std::vector<MoveDirection>> > solutions); #endif
34.642857
143
0.727835
Yao-Chung
f0c9ea61afd241f3c72bd16e62d22587e4d0f3d9
53,605
hh
C++
apps/rosetta/rif_dock_test.hh
willsheffler/rifdock
291d05112d52318bb07d499ce6da3e0fb9fbf9cf
[ "Apache-2.0" ]
2
2020-01-28T07:59:26.000Z
2020-09-17T06:32:14.000Z
apps/rosetta/rif_dock_test.hh
willsheffler/rifdock
291d05112d52318bb07d499ce6da3e0fb9fbf9cf
[ "Apache-2.0" ]
null
null
null
apps/rosetta/rif_dock_test.hh
willsheffler/rifdock
291d05112d52318bb07d499ce6da3e0fb9fbf9cf
[ "Apache-2.0" ]
null
null
null
#include <basic/options/option_macros.hh> #include <basic/options/keys/corrections.OptionKeys.gen.hh> #include <riflib/scaffold/nineA_util.hh> #include <vector> #ifdef GLOBAL_VARIABLES_ARE_BAD #ifndef INCLUDED_rif_dock_test_hh_1 #define INCLUDED_rif_dock_test_hh_1 OPT_1GRP_KEY( StringVector , rif_dock, scaffolds ) OPT_1GRP_KEY( StringVector, rif_dock, scaffold_res ) OPT_1GRP_KEY( StringVector, rif_dock, scaffold_res_fixed ) OPT_1GRP_KEY( Boolean , rif_dock, scaffold_res_use_best_guess ) OPT_1GRP_KEY( Boolean , rif_dock, scaffold_to_ala ) OPT_1GRP_KEY( Boolean , rif_dock, scaffold_to_ala_selonly ) OPT_1GRP_KEY( Boolean , rif_dock, replace_orig_scaffold_res ) OPT_1GRP_KEY( Boolean , rif_dock, replace_all_with_ala_1bre ) OPT_1GRP_KEY( Boolean , rif_dock, random_perturb_scaffold ) OPT_1GRP_KEY( StringVector, rif_dock, target_bounding_xmaps ) OPT_1GRP_KEY( String , rif_dock, target_pdb ) OPT_1GRP_KEY( String , rif_dock, target_res ) OPT_1GRP_KEY( String , rif_dock, target_rif ) OPT_1GRP_KEY( Real , rif_dock, target_rf_resl ) OPT_1GRP_KEY( Integer , rif_dock, target_rf_oversample ) OPT_1GRP_KEY( String , rif_dock, target_rf_cache ) OPT_1GRP_KEY( String , rif_dock, target_donors ) OPT_1GRP_KEY( String , rif_dock, target_acceptors ) OPT_1GRP_KEY( Boolean , rif_dock, only_load_highest_resl ) OPT_1GRP_KEY( Boolean , rif_dock, use_rosetta_grid_energies ) OPT_1GRP_KEY( Boolean , rif_dock, soft_rosetta_grid_energies ) OPT_1GRP_KEY( StringVector, rif_dock, data_cache_dir ) OPT_1GRP_KEY( Real , rif_dock, beam_size_M ) OPT_1GRP_KEY( Real , rif_dock, max_beam_multiplier ) OPT_1GRP_KEY( Boolean , rif_dock, multiply_beam_by_seeding_positions ) OPT_1GRP_KEY( Boolean , rif_dock, multiply_beam_by_scaffolds ) OPT_1GRP_KEY( Real , rif_dock, search_diameter ) OPT_1GRP_KEY( Real , rif_dock, hsearch_scale_factor ) OPT_1GRP_KEY( Real , rif_dock, max_rf_bounding_ratio ) OPT_1GRP_KEY( Boolean , rif_dock, make_bounding_plot_data ) OPT_1GRP_KEY( Boolean , rif_dock, align_output_to_scaffold ) OPT_1GRP_KEY( Boolean , rif_dock, output_scaffold_only ) OPT_1GRP_KEY( Boolean , rif_dock, output_full_scaffold_only ) OPT_1GRP_KEY( Boolean , rif_dock, output_full_scaffold ) OPT_1GRP_KEY( Integer , rif_dock, n_pdb_out ) OPT_1GRP_KEY( Real , rif_dock, rf_resl ) OPT_1GRP_KEY( Integer , rif_dock, rf_oversample ) OPT_1GRP_KEY( Boolean , rif_dock, downscale_atr_by_hierarchy ) OPT_1GRP_KEY( Real , rif_dock, favorable_1body_multiplier ) OPT_1GRP_KEY( Real , rif_dock, favorable_1body_multiplier_cutoff ) OPT_1GRP_KEY( Real , rif_dock, favorable_2body_multiplier ) OPT_1GRP_KEY( Integer , rif_dock, rotrf_oversample ) OPT_1GRP_KEY( Real , rif_dock, rotrf_resl ) OPT_1GRP_KEY( Real , rif_dock, rotrf_spread ) OPT_1GRP_KEY( Real , rif_dock, rotrf_scale_atr ) OPT_1GRP_KEY( String , rif_dock, rotrf_cache_dir ) OPT_1GRP_KEY( Boolean , rif_dock, hack_pack ) OPT_1GRP_KEY( Boolean , rif_dock, hack_pack_during_hsearch ) OPT_1GRP_KEY( Real , rif_dock, hack_pack_frac ) OPT_1GRP_KEY( Real , rif_dock, pack_iter_mult ) OPT_1GRP_KEY( Integer , rif_dock, pack_n_iters ) OPT_1GRP_KEY( Real , rif_dock, hbond_weight ) OPT_1GRP_KEY( Real , rif_dock, upweight_multi_hbond ) OPT_1GRP_KEY( Real , rif_dock, min_hb_quality_for_satisfaction ) OPT_1GRP_KEY( Real , rif_dock, long_hbond_fudge_distance ) OPT_1GRP_KEY( Real , rif_dock, global_score_cut ) OPT_1GRP_KEY( Real , rif_dock, redundancy_filter_mag ) OPT_1GRP_KEY( Boolean , rif_dock, filter_seeding_positions_separately ) OPT_1GRP_KEY( Boolean , rif_dock, filter_scaffolds_separately ) OPT_1GRP_KEY( Real , rif_dock, force_output_if_close_to_input ) OPT_1GRP_KEY( Integer , rif_dock, force_output_if_close_to_input_num ) OPT_1GRP_KEY( Real , rif_dock, upweight_iface ) OPT_1GRP_KEY( Boolean , rif_dock, use_scaffold_bounding_grids ) OPT_1GRP_KEY( Boolean , rif_dock, restrict_to_native_scaffold_res ) OPT_1GRP_KEY( Real , rif_dock, bonus_to_native_scaffold_res ) OPT_1GRP_KEY( Boolean , rif_dock, add_native_scaffold_rots_when_packing ) OPT_1GRP_KEY( Boolean , rif_dock, dump_all_rif_rots ) OPT_1GRP_KEY( Boolean , rif_dock, dump_all_rif_rots_into_output ) OPT_1GRP_KEY( Boolean , rif_dock, rif_rots_as_chains ) OPT_1GRP_KEY( String , rif_dock, dump_rifgen_near_pdb ) OPT_1GRP_KEY( Real , rif_dock, dump_rifgen_near_pdb_dist ) OPT_1GRP_KEY( Real , rif_dock, dump_rifgen_near_pdb_frac ) OPT_1GRP_KEY( Boolean , rif_dock, dump_rifgen_text ) OPT_1GRP_KEY( String , rif_dock, score_this_pdb ) OPT_1GRP_KEY( String , rif_dock, dump_pdb_at_bin_center ) OPT_1GRP_KEY( String , rif_dock, dokfile ) OPT_1GRP_KEY( String , rif_dock, outdir ) OPT_1GRP_KEY( String , rif_dock, output_tag ) OPT_1GRP_KEY( Boolean , rif_dock, dont_use_scaffold_loops ) OPT_1GRP_KEY( Boolean , rif_dock, dump_resfile ) OPT_1GRP_KEY( Boolean , rif_dock, pdb_info_pikaa ) OPT_1GRP_KEY( Boolean , rif_dock, cache_scaffold_data ) OPT_1GRP_KEY( Real , rif_dock, tether_to_input_position ) OPT_1GRP_KEY( Boolean , rif_dock, lowres_sterics_cbonly ) OPT_1GRP_KEY( Integer , rif_dock, require_satisfaction ) OPT_1GRP_KEY( Integer , rif_dock, num_hotspots ) OPT_1GRP_KEY( Integer , rif_dock, require_n_rifres ) OPT_1GRP_KEY( Boolean , rif_dock, use_dl_mix_bb ) OPT_1GRP_KEY( Real , rif_dock, rosetta_score_fraction ) OPT_1GRP_KEY( Real , rif_dock, rosetta_score_then_min_below_thresh ) OPT_1GRP_KEY( Integer , rif_dock, rosetta_score_at_least ) OPT_1GRP_KEY( Integer , rif_dock, rosetta_score_at_most ) OPT_1GRP_KEY( Real , rif_dock, rosetta_min_fraction ) OPT_1GRP_KEY( Integer , rif_dock, rosetta_min_at_least ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_min_fix_target ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_min_targetbb ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_min_scaffoldbb ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_min_allbb ) OPT_1GRP_KEY( Real , rif_dock, rosetta_score_cut ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_hard_min ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_score_total ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_score_ddg_only ) OPT_1GRP_KEY( Real , rif_dock, rosetta_score_rifres_rifres_weight ) OPT_1GRP_KEY( Real , rif_dock, rosetta_score_rifres_scaffold_weight ) OPT_1GRP_KEY( String , rif_dock, rosetta_soft_score ) OPT_1GRP_KEY( String , rif_dock, rosetta_hard_score ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_filter_before ) OPT_1GRP_KEY( Integer , rif_dock, rosetta_filter_n_per_scaffold ) OPT_1GRP_KEY( Real , rif_dock, rosetta_filter_redundancy_mag ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_filter_even_if_no_score ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_debug_dump_scores ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_score_select_random ) OPT_1GRP_KEY( Boolean , rif_dock, extra_rotamers ) OPT_1GRP_KEY( Boolean , rif_dock, extra_rif_rotamers ) OPT_1GRP_KEY( Integer , rif_dock, always_available_rotamers_level ) OPT_1GRP_KEY( Boolean , rif_dock, packing_use_rif_rotamers ) OPT_1GRP_KEY( Integer , rif_dock, nfold_symmetry ) OPT_1GRP_KEY( RealVector , rif_dock, symmetry_axis ) OPT_1GRP_KEY( Real , rif_dock, user_rotamer_bonus_constant ) OPT_1GRP_KEY( Real , rif_dock, user_rotamer_bonus_per_chi ) OPT_1GRP_KEY( Real , rif_dock, resl0 ) OPT_1GRP_KEY( Integer , rif_dock, dump_x_frames_per_resl ) OPT_1GRP_KEY( Boolean , rif_dock, dump_only_best_frames ) OPT_1GRP_KEY( Integer , rif_dock, dump_only_best_stride ) OPT_1GRP_KEY( String , rif_dock, dump_prefix ) OPT_1GRP_KEY( String , rif_dock, scaff_search_mode ) OPT_1GRP_KEY( String , rif_dock, nineA_cluster_path ) OPT_1GRP_KEY( String , rif_dock, nineA_baseline_range ) OPT_1GRP_KEY( Integer , rif_dock, low_cut_site ) OPT_1GRP_KEY( Integer , rif_dock, high_cut_site ) OPT_1GRP_KEY( Integer , rif_dock, max_insertion ) OPT_1GRP_KEY( Integer , rif_dock, max_deletion ) OPT_1GRP_KEY( Real , rif_dock, fragment_cluster_tolerance ) OPT_1GRP_KEY( Real , rif_dock, fragment_max_rmsd ) OPT_1GRP_KEY( Integer , rif_dock, max_fragments ) OPT_1GRP_KEY( StringVector, rif_dock, morph_rules_files ) OPT_1GRP_KEY( String , rif_dock, morph_silent_file ) OPT_1GRP_KEY( String , rif_dock, morph_silent_archetype ) OPT_1GRP_KEY( Real , rif_dock, morph_silent_max_structures ) OPT_1GRP_KEY( Boolean , rif_dock, morph_silent_random_selection ) OPT_1GRP_KEY( Real , rif_dock, morph_silent_cluster_use_frac ) OPT_1GRP_KEY( Boolean , rif_dock, include_parent ) OPT_1GRP_KEY( Boolean , rif_dock, use_parent_body_energies ) OPT_1GRP_KEY( Integer , rif_dock, dive_resl ) OPT_1GRP_KEY( Integer , rif_dock, pop_resl ) OPT_1GRP_KEY( String , rif_dock, match_this_pdb ) OPT_1GRP_KEY( Real , rif_dock, match_this_rmsd ) OPT_1GRP_KEY( String , rif_dock, rot_spec_fname ) // constrain file OPT_1GRP_KEY( StringVector, rif_dock, cst_files ) OPT_1GRP_KEY( StringVector, rif_dock, seed_with_these_pdbs ) OPT_1GRP_KEY( Boolean , rif_dock, seed_include_input ) OPT_1GRP_KEY( StringVector, rif_dock, seeding_pos ) OPT_1GRP_KEY( Boolean , rif_dock, seeding_by_patchdock ) OPT_1GRP_KEY( String , rif_dock, xform_pos ) OPT_1GRP_KEY( Integer , rif_dock, rosetta_score_each_seeding_at_least ) OPT_1GRP_KEY( Real , rif_dock, cluster_score_cut ) OPT_1GRP_KEY( Real , rif_dock, keep_top_clusters_frac ) OPT_1GRP_KEY( Real , rif_dock, unsat_orbital_penalty ) OPT_1GRP_KEY( Real , rif_dock, neighbor_distance_cutoff ) OPT_1GRP_KEY( Integer , rif_dock, unsat_neighbor_cutoff ) OPT_1GRP_KEY( Boolean , rif_dock, unsat_debug ) OPT_1GRP_KEY( Boolean , rif_dock, test_hackpack ) OPT_1GRP_KEY( String , rif_dock, unsat_helper ) OPT_1GRP_KEY( Real , rif_dock, unsat_score_offset ) OPT_1GRP_KEY( Integer , rif_dock, unsat_require_burial ) OPT_1GRP_KEY( Boolean , rif_dock, report_common_unsats ) OPT_1GRP_KEY( Boolean , rif_dock, dump_presatisfied_donors_acceptors ) OPT_1GRP_KEY( IntegerVector, rif_dock, requirements ) void register_options() { using namespace basic::options; using namespace basic::options::OptionKeys; NEW_OPT( rif_dock::scaffolds, "" , utility::vector1<std::string>() ); NEW_OPT( rif_dock::scaffold_res, "" , utility::vector1<std::string>() ); NEW_OPT( rif_dock::scaffold_res_fixed, "" , utility::vector1<std::string>() ); NEW_OPT( rif_dock::scaffold_res_use_best_guess, "" , false ); NEW_OPT( rif_dock::scaffold_to_ala, "" , false ); NEW_OPT( rif_dock::scaffold_to_ala_selonly, "" , true ); NEW_OPT( rif_dock::replace_orig_scaffold_res, "", true ); NEW_OPT( rif_dock::replace_all_with_ala_1bre, "" , false ); NEW_OPT( rif_dock::random_perturb_scaffold, "" , false ); NEW_OPT( rif_dock::target_bounding_xmaps, "" , utility::vector1<std::string>() ); NEW_OPT( rif_dock::target_pdb, "" , "" ); NEW_OPT( rif_dock::target_res, "" , "" ); NEW_OPT( rif_dock::target_rif, "" , "" ); NEW_OPT( rif_dock::target_rf_resl, "" , 0.25 ); NEW_OPT( rif_dock::target_rf_oversample, "" , 2 ); NEW_OPT( rif_dock::downscale_atr_by_hierarchy, "" , true ); NEW_OPT( rif_dock::favorable_1body_multiplier, "Anything with a one-body energy less than favorable_1body_cutoff gets multiplied by this", 1 ); NEW_OPT( rif_dock::favorable_1body_multiplier_cutoff, "Anything with a one-body energy less than this gets multiplied by favorable_1body_multiplier", 0 ); NEW_OPT( rif_dock::favorable_2body_multiplier, "Anything with a two-body energy less than 0 gets multiplied by this", 1 ); NEW_OPT( rif_dock::target_rf_cache, "" , "NO_CACHE_SPECIFIED_ON_COMMAND_LINE" ); NEW_OPT( rif_dock::target_donors, "", "" ); NEW_OPT( rif_dock::target_acceptors, "", "" ); NEW_OPT( rif_dock::only_load_highest_resl, "Only read in the highest resolution rif", false ); NEW_OPT( rif_dock::use_rosetta_grid_energies, "Use Frank's grid energies for scoring", false ); NEW_OPT( rif_dock::soft_rosetta_grid_energies, "Use soft option for grid energies", false ); NEW_OPT( rif_dock::data_cache_dir, "" , utility::vector1<std::string>(1,"./") ); NEW_OPT( rif_dock::beam_size_M, "" , 10.000000 ); NEW_OPT( rif_dock::max_beam_multiplier, "Maximum beam multiplier", 1 ); NEW_OPT( rif_dock::multiply_beam_by_seeding_positions, "Multiply beam size by number of seeding positions", false); NEW_OPT( rif_dock::multiply_beam_by_scaffolds, "Multiply beam size by number of scaffolds", true); NEW_OPT( rif_dock::max_rf_bounding_ratio, "" , 4 ); NEW_OPT( rif_dock::make_bounding_plot_data, "" , false ); NEW_OPT( rif_dock::align_output_to_scaffold, "" , false ); NEW_OPT( rif_dock::output_scaffold_only, "" , false ); NEW_OPT( rif_dock::output_full_scaffold_only, "" , false ); NEW_OPT( rif_dock::output_full_scaffold, "", false ); NEW_OPT( rif_dock::n_pdb_out, "" , 10 ); NEW_OPT( rif_dock::rf_resl, "" , 0.25 ); NEW_OPT( rif_dock::rf_oversample, "" , 2 ); NEW_OPT( rif_dock::rotrf_oversample, "" , 2 ); NEW_OPT( rif_dock::rotrf_resl, "" , 0.3 ); NEW_OPT( rif_dock::rotrf_spread, "" , 0.0 ); NEW_OPT( rif_dock::rotrf_scale_atr, "" , 1.0 ); NEW_OPT( rif_dock::rotrf_cache_dir, "" , "./" ); NEW_OPT( rif_dock::hack_pack, "" , true ); NEW_OPT( rif_dock::hack_pack_during_hsearch, "hackpack during hsearch", false ); NEW_OPT( rif_dock::hack_pack_frac, "" , 0.2 ); NEW_OPT( rif_dock::pack_iter_mult, "" , 2.0 ); NEW_OPT( rif_dock::pack_n_iters, "" , 1 ); NEW_OPT( rif_dock::hbond_weight, "" , 2.0 ); NEW_OPT( rif_dock::upweight_multi_hbond, "" , 0.0 ); NEW_OPT( rif_dock::min_hb_quality_for_satisfaction, "Minimum fraction of total hbond energy required for satisfaction. Scale -1 to 0", -0.6 ); NEW_OPT( rif_dock::long_hbond_fudge_distance, "Any hbond longer than 2A gets moved closer to 2A by this amount for scoring", 0.0 ); NEW_OPT( rif_dock::global_score_cut, "" , 0.0 ); NEW_OPT( rif_dock::redundancy_filter_mag, "" , 1.0 ); NEW_OPT( rif_dock::filter_seeding_positions_separately, "Redundancy filter each seeding position separately", true ); NEW_OPT( rif_dock::filter_scaffolds_separately, "Redundancy filter each scaffold separately", true ); NEW_OPT( rif_dock::force_output_if_close_to_input, "" , 1.0 ); NEW_OPT( rif_dock::force_output_if_close_to_input_num, "" , 0 ); NEW_OPT( rif_dock::upweight_iface, "", 1.2 ); NEW_OPT( rif_dock::use_scaffold_bounding_grids, "", false ); NEW_OPT( rif_dock::search_diameter, "", 150.0 ); NEW_OPT( rif_dock::hsearch_scale_factor, "global scaling of rotation/translation search grid", 1.0 ); NEW_OPT( rif_dock::restrict_to_native_scaffold_res, "aka structure prediction CHEAT", false ); NEW_OPT( rif_dock::bonus_to_native_scaffold_res, "aka favor native CHEAT", -0.3 ); NEW_OPT( rif_dock::add_native_scaffold_rots_when_packing, "CHEAT", false ); NEW_OPT( rif_dock::dump_all_rif_rots, "", false ); NEW_OPT( rif_dock::dump_all_rif_rots_into_output, "dump all rif rots into output", false); NEW_OPT( rif_dock::rif_rots_as_chains, "dump rif rots as chains instead of models, loses resnum if true", false ); NEW_OPT( rif_dock::dump_rifgen_near_pdb, "dump rifgen rotamers with same AA type near this single residue", ""); NEW_OPT( rif_dock::dump_rifgen_near_pdb_dist, "", 1 ); NEW_OPT( rif_dock::dump_rifgen_near_pdb_frac, "", 1 ); NEW_OPT( rif_dock::dump_rifgen_text, "Dump the rifgen tables within dump_rifgen_near_pdb_dist", false ); NEW_OPT( rif_dock::score_this_pdb, "Score every residue of this pdb using the rif scoring machinery", "" ); NEW_OPT( rif_dock::dump_pdb_at_bin_center, "Dump each residue of this pdb at the rotamer's bin center", "" ); NEW_OPT( rif_dock::dokfile, "", "default.dok" ); NEW_OPT( rif_dock::outdir, "", "./" ); NEW_OPT( rif_dock::output_tag, "", "" ); NEW_OPT( rif_dock::dont_use_scaffold_loops, "", false ); NEW_OPT( rif_dock::dump_resfile, "", false ); NEW_OPT( rif_dock::pdb_info_pikaa, "", false ); NEW_OPT( rif_dock::cache_scaffold_data, "", false ); NEW_OPT( rif_dock::tether_to_input_position, "", -1.0 ); NEW_OPT( rif_dock::lowres_sterics_cbonly, "", true ); NEW_OPT( rif_dock::require_satisfaction, "", 0 ); NEW_OPT( rif_dock::num_hotspots, "Number of hotspots found in Rifdock hotspots. If in doubt, set this to 1000", 0 ); NEW_OPT( rif_dock::require_n_rifres, "This doesn't work during HackPack", 0 ); NEW_OPT( rif_dock::use_dl_mix_bb, "use phi to decide where d is allow", false ); NEW_OPT( rif_dock::rosetta_score_fraction , "", 0.00 ); NEW_OPT( rif_dock::rosetta_score_then_min_below_thresh, "", -9e9 ); NEW_OPT( rif_dock::rosetta_score_at_least, "", -1 ); NEW_OPT( rif_dock::rosetta_score_at_most, "", 999999999 ); NEW_OPT( rif_dock::rosetta_min_fraction , "", 0.1 ); NEW_OPT( rif_dock::rosetta_min_at_least, "", -1 ); NEW_OPT( rif_dock::rosetta_min_targetbb , "", false ); NEW_OPT( rif_dock::rosetta_min_scaffoldbb , "", false ); NEW_OPT( rif_dock::rosetta_min_allbb , "", false ); NEW_OPT( rif_dock::rosetta_min_fix_target, "", false ); NEW_OPT( rif_dock::rosetta_score_cut , "", -10.0 ); NEW_OPT( rif_dock::rosetta_hard_min , "", false ); NEW_OPT( rif_dock::rosetta_score_total , "", false ); NEW_OPT( rif_dock::rosetta_score_ddg_only , "", false ); NEW_OPT( rif_dock::rosetta_score_rifres_rifres_weight, "", 0.75 ); NEW_OPT( rif_dock::rosetta_score_rifres_scaffold_weight, "", 0.5 ); NEW_OPT( rif_dock::rosetta_soft_score, "", "beta_soft" ); NEW_OPT( rif_dock::rosetta_hard_score, "", "beta" ); NEW_OPT( rif_dock::rosetta_filter_before, "redundancy filter results before rosetta score", false ); NEW_OPT( rif_dock::rosetta_filter_n_per_scaffold, "use with rosetta_filter_before, num to save per scaffold", 300); NEW_OPT( rif_dock::rosetta_filter_redundancy_mag, "use with rosetta_filter_before, redundancy mag on the clustering", 0.5); NEW_OPT( rif_dock::rosetta_filter_even_if_no_score, "Do the filtering for rosetta score and min even if you don't actually score/min", false ); NEW_OPT( rif_dock::rosetta_debug_dump_scores, "dump lists of scores around the rosetta score and min", false); NEW_OPT( rif_dock::rosetta_score_select_random, "Select random positions to score rather than best", false); NEW_OPT( rif_dock::extra_rotamers, "", true ); NEW_OPT( rif_dock::extra_rif_rotamers, "", true ); NEW_OPT( rif_dock::always_available_rotamers_level, "", 0 ); NEW_OPT( rif_dock::packing_use_rif_rotamers, "", true ); NEW_OPT( rif_dock::nfold_symmetry, "", 1 ); NEW_OPT( rif_dock::symmetry_axis, "", utility::vector1<double>() ); NEW_OPT( rif_dock::user_rotamer_bonus_constant, "", 0 ); NEW_OPT( rif_dock::user_rotamer_bonus_per_chi, "", 0 ); NEW_OPT( rif_dock::resl0, "", 16 ); NEW_OPT( rif_dock::dump_x_frames_per_resl, "Use this to make a movie", 0 ); NEW_OPT( rif_dock::dump_only_best_frames, "Only dump the best frames for the movie", false ); NEW_OPT( rif_dock::dump_only_best_stride, "When doing dump_only_best_frames, dump every Xth element of the best", 1 ); NEW_OPT( rif_dock::dump_prefix, "Convince Brian to make this autocreate the folder", "hsearch" ); NEW_OPT( rif_dock::scaff_search_mode, "Which scaffold mode and HSearch do you want? Options: default, morph_dive_pop, nineA_baseline", "default"); NEW_OPT( rif_dock::nineA_cluster_path, "Path to cluster database for nineA_baseline.", "" ); NEW_OPT( rif_dock::nineA_baseline_range, "format cdindex:low-high (python range style)", ""); NEW_OPT( rif_dock::low_cut_site, "The low cut point for fragment insertion, this res and the previous get minimized.", 0 ); NEW_OPT( rif_dock::high_cut_site, "The high cut point for fragment insertion, this res and the next get minimized.", 0 ); NEW_OPT( rif_dock::max_insertion, "Maximum number of residues to lengthen protein by.", 0 ); NEW_OPT( rif_dock::max_deletion, "Maximum number of residues to shorten protein by.", 0 ); NEW_OPT( rif_dock::fragment_cluster_tolerance, "RMSD cluster tolerance for fragments.", 0.5 ); NEW_OPT( rif_dock::fragment_max_rmsd , "Max RMSD to starting fragment.", 10000 ); NEW_OPT( rif_dock::max_fragments, "Maximum number of fragments to find.", 10000000 ); NEW_OPT( rif_dock::morph_rules_files, "List of files for each scaffold to specify morph regions", utility::vector1<std::string>() ); NEW_OPT( rif_dock::morph_silent_file, "Silent file containing pre-morphed structures. Overrides other options", "" ); NEW_OPT( rif_dock::morph_silent_archetype, "PDB to calculate transform difference between input position and silent file", "" ); NEW_OPT( rif_dock::morph_silent_max_structures, "Cluster silent file into this many cluster centers", 1000000000 ); NEW_OPT( rif_dock::morph_silent_random_selection, "Use random picks instead of clustering to limit silent file", false ); NEW_OPT( rif_dock::morph_silent_cluster_use_frac, "Cluster and take the top clusters that make up this frac of total", 1 ); NEW_OPT( rif_dock::include_parent, "Include parent fragment in diversified scaffolds.", false ); NEW_OPT( rif_dock::use_parent_body_energies, "Don't recalculate 1-/2-body energies for fragment insertions", false ); NEW_OPT( rif_dock::dive_resl , "Dive to this depth before diversifying", 5 ); NEW_OPT( rif_dock::pop_resl , "Return to this depth after diversifying", 4 ); NEW_OPT( rif_dock::match_this_pdb, "Like tether to input position but applied at diversification time.", "" ); NEW_OPT( rif_dock::match_this_rmsd, "RMSD for match_this_pdb", 7 ); NEW_OPT( rif_dock::rot_spec_fname,"rot_spec_fname","NOT SPECIFIED"); // constrain file names NEW_OPT( rif_dock::cst_files, "" , utility::vector1<std::string>() ); NEW_OPT( rif_dock::seed_with_these_pdbs, "Use these pdbs as seeding positions, use this with tether_to_input_position", utility::vector1<std::string>() ); NEW_OPT( rif_dock::seed_include_input, "Include the input scaffold as a seeding position in seed_with_these_pdbs", true ); NEW_OPT( rif_dock::seeding_pos, "" , utility::vector1<std::string>() ); NEW_OPT( rif_dock::seeding_by_patchdock, "The format of seeding file can be either Rosetta Xform or raw patchdock outputs", true ); NEW_OPT( rif_dock::xform_pos, "" , "" ); NEW_OPT( rif_dock::rosetta_score_each_seeding_at_least, "", -1 ); NEW_OPT( rif_dock::cluster_score_cut, "", 0); NEW_OPT( rif_dock::keep_top_clusters_frac, "", 0.5); NEW_OPT( rif_dock::unsat_orbital_penalty, "temp", 0 ); NEW_OPT( rif_dock::neighbor_distance_cutoff, "temp", 6.0 ); NEW_OPT( rif_dock::unsat_neighbor_cutoff, "temp", 6 ); NEW_OPT( rif_dock::unsat_debug, "Dump debug info from unsat calculations", false ); NEW_OPT( rif_dock::test_hackpack, "Test the packing objective in the original position too", false ); NEW_OPT( rif_dock::unsat_helper, "Helper file for use with unsats", "" ); NEW_OPT( rif_dock::unsat_score_offset, "This gets added to the score of all designs", 0.0 ); NEW_OPT( rif_dock::unsat_require_burial, "Require at least this many polar atoms be buried", 0 ); NEW_OPT( rif_dock::report_common_unsats, "Show probability of burying every unsat", false ); NEW_OPT( rif_dock::dump_presatisfied_donors_acceptors, "Dump the presatisifed donors and acceptors", false ); NEW_OPT( rif_dock::requirements, "which rif residue should be in the final output", utility::vector1< int >()); } #endif #endif #ifndef INCLUDED_rif_dock_test_hh_3 #define INCLUDED_rif_dock_test_hh_3 struct RifDockOpt { std::vector<std::string> scaffold_fnames; std::vector<std::string> scaffold_res_fnames; std::vector<std::string> data_cache_path; std::vector<std::string> rif_files; bool VERBOSE ; double resl0 ; int64_t DIM ; int64_t DIMPOW2 ; int64_t beam_size ; float max_beam_multiplier ; bool multiply_beam_by_seeding_positions ; bool multiply_beam_by_scaffolds ; bool replace_all_with_ala_1bre ; bool lowres_sterics_cbonly ; float tether_to_input_position_cut ; bool tether_to_input_position ; float global_score_cut ; std::string target_pdb ; std::string outdir ; std::string output_tag ; std::string dokfile_fname ; bool dump_all_rif_rots ; bool dump_all_rif_rots_into_output ; bool rif_rots_as_chains ; std::string dump_rifgen_near_pdb ; float dump_rifgen_near_pdb_dist ; float dump_rifgen_near_pdb_frac ; bool dump_rifgen_text ; std::string score_this_pdb ; std::string dump_pdb_at_bin_center ; bool add_native_scaffold_rots_when_packing; bool restrict_to_native_scaffold_res ; float bonus_to_native_scaffold_res ; float hack_pack_frac ; float hsearch_scale_factor ; float search_diameter ; bool use_scaffold_bounding_grids ; bool scaffold_res_use_best_guess ; bool scaff2ala ; bool scaff2alaselonly ; bool replace_orig_scaffold_res ; int require_satisfaction ; int num_hotspots ; int require_n_rifres ; bool use_dl_mix_bb ; float target_rf_resl ; bool align_to_scaffold ; bool output_scaffold_only ; bool output_full_scaffold_only ; bool output_full_scaffold ; bool pdb_info_pikaa ; bool dump_resfile ; std::string target_res_fname ; int target_rf_oversample ; float max_rf_bounding_ratio ; std::string target_rf_cache ; std::string target_donors ; std::string target_acceptors ; bool only_load_highest_resl ; bool use_rosetta_grid_energies ; bool soft_rosetta_grid_energies ; bool downscale_atr_by_hierarchy ; float favorable_1body_multiplier ; float favorable_1body_multiplier_cutoff ; float favorable_2body_multiplier ; bool random_perturb_scaffold ; bool dont_use_scaffold_loops ; bool cache_scaffold_data ; float rf_resl ; bool hack_pack ; bool hack_pack_during_hsearch ; int rf_oversample ; int rotrf_oversample ; float rotrf_resl ; float rotrf_spread ; std::string rotrf_cache_dir ; float rotrf_scale_atr ; float pack_iter_mult ; int pack_n_iters ; float hbond_weight ; float upweight_iface ; float upweight_multi_hbond ; float min_hb_quality_for_satisfaction ; float long_hbond_fudge_distance ; float redundancy_filter_mag ; bool filter_seeding_positions_separately ; bool filter_scaffolds_separately ; int force_output_if_close_to_input_num ; float force_output_if_close_to_input ; int n_pdb_out ; bool extra_rotamers ; bool extra_rif_rotamers ; int always_available_rotamers_level ; int packing_use_rif_rotamers ; float rosetta_score_fraction ; float rosetta_score_then_min_below_thresh ; float rosetta_score_at_least ; float rosetta_score_at_most ; float rosetta_min_fraction ; int rosetta_min_at_least ; bool rosetta_min_fix_target ; bool rosetta_min_targetbb ; bool rosetta_min_scaffoldbb ; bool rosetta_min_allbb ; float rosetta_score_cut ; float rosetta_hard_min ; bool rosetta_score_total ; bool rosetta_score_ddg_only ; float rosetta_score_rifres_rifres_weight ; float rosetta_score_rifres_scaffold_weight ; bool rosetta_beta ; std::string rosetta_soft_score ; std::string rosetta_hard_score ; bool rosetta_filter_before ; int rosetta_filter_n_per_scaffold ; float rosetta_filter_redundancy_mag ; bool rosetta_filter_even_if_no_score ; bool rosetta_debug_dump_scores ; bool rosetta_score_select_random ; int nfold_symmetry ; std::vector<float> symmetry_axis ; float user_rotamer_bonus_constant ; float user_rotamer_bonus_per_chi ; int dump_x_frames_per_resl ; bool dump_only_best_frames ; int dump_only_best_stride ; std::string dump_prefix ; std::string scaff_search_mode ; std::string nineA_cluster_path ; std::string nineA_baseline_range ; int low_cut_site ; int high_cut_site ; int max_insertion ; int max_deletion ; float fragment_cluster_tolerance ; float fragment_max_rmsd ; int max_fragments ; std::vector<std::string> morph_rules_fnames ; std::string morph_silent_file ; std::string morph_silent_archetype ; int morph_silent_max_structures ; bool morph_silent_random_selection ; float morph_silent_cluster_use_frac ; bool include_parent ; bool use_parent_body_energies ; int dive_resl ; int pop_resl ; std::string match_this_pdb ; float match_this_rmsd ; std::string rot_spec_fname ; // constrain file names std::vector<std::string> cst_fnames ; std::vector<std::string> seed_with_these_pdbs ; bool seed_include_input ; std::vector<std::string> seeding_fnames ; std::string xform_fname ; float rosetta_score_each_seeding_at_least ; float cluster_score_cut ; float keep_top_clusters_frac ; bool seeding_by_patchdock ; float unsat_orbital_penalty ; float neighbor_distance_cutoff ; int unsat_neighbor_cutoff ; bool unsat_debug ; bool test_hackpack ; std::string unsat_helper ; float unsat_score_offset ; int unsat_require_burial ; bool report_common_unsats ; bool dump_presatisfied_donors_acceptors ; std::vector<int> requirements; void init_from_cli(); }; #endif #ifdef GLOBAL_VARIABLES_ARE_BAD #ifndef INCLUDED_rif_dock_test_hh_4 #define INCLUDED_rif_dock_test_hh_4 void RifDockOpt::init_from_cli() { using basic::options::option; using namespace basic::options::OptionKeys; runtime_assert( option[rif_dock::target_rif].user() ); VERBOSE = false; resl0 = option[rif_dock::resl0 ](); DIM = 6; DIMPOW2 = 1<<DIM; beam_size = int64_t( option[rif_dock::beam_size_M]() * 1000000.0 / DIMPOW2 ) * DIMPOW2; max_beam_multiplier = option[rif_dock::max_beam_multiplier ](); multiply_beam_by_seeding_positions = option[rif_dock::multiply_beam_by_seeding_positions ](); multiply_beam_by_scaffolds = option[rif_dock::multiply_beam_by_scaffolds ](); replace_all_with_ala_1bre = option[rif_dock::replace_all_with_ala_1bre ](); target_pdb = option[rif_dock::target_pdb ](); lowres_sterics_cbonly = option[rif_dock::lowres_sterics_cbonly ](); tether_to_input_position_cut = option[rif_dock::tether_to_input_position ](); tether_to_input_position = tether_to_input_position_cut > 0.0; global_score_cut = option[rif_dock::global_score_cut ](); outdir = option[rif_dock::outdir ](); output_tag = option[rif_dock::output_tag ](); dokfile_fname = outdir + "/" + option[rif_dock::dokfile ](); dump_all_rif_rots = option[rif_dock::dump_all_rif_rots ](); dump_all_rif_rots_into_output = option[rif_dock::dump_all_rif_rots_into_output ](); rif_rots_as_chains = option[rif_dock::rif_rots_as_chains ](); dump_rifgen_near_pdb = option[rif_dock::dump_rifgen_near_pdb ](); dump_rifgen_near_pdb_dist = option[rif_dock::dump_rifgen_near_pdb_dist ](); dump_rifgen_near_pdb_frac = option[rif_dock::dump_rifgen_near_pdb_frac ](); dump_rifgen_text = option[rif_dock::dump_rifgen_text ](); score_this_pdb = option[rif_dock::score_this_pdb ](); dump_pdb_at_bin_center = option[rif_dock::dump_pdb_at_bin_center ](); add_native_scaffold_rots_when_packing = option[rif_dock::add_native_scaffold_rots_when_packing ](); restrict_to_native_scaffold_res = option[rif_dock::restrict_to_native_scaffold_res ](); bonus_to_native_scaffold_res = option[rif_dock::bonus_to_native_scaffold_res ](); hack_pack_frac = option[rif_dock::hack_pack_frac ](); hsearch_scale_factor = option[rif_dock::hsearch_scale_factor ](); search_diameter = option[rif_dock::search_diameter ](); use_scaffold_bounding_grids = option[rif_dock::use_scaffold_bounding_grids ](); scaffold_res_use_best_guess = option[rif_dock::scaffold_res_use_best_guess ](); scaff2ala = option[rif_dock::scaffold_to_ala ](); scaff2alaselonly = option[rif_dock::scaffold_to_ala_selonly ](); replace_orig_scaffold_res = option[rif_dock::replace_orig_scaffold_res ](); require_satisfaction = option[rif_dock::require_satisfaction ](); num_hotspots = option[rif_dock::num_hotspots ](); require_n_rifres = option[rif_dock::require_n_rifres ](); use_dl_mix_bb = option[rif_dock::use_dl_mix_bb ](); target_rf_resl = option[rif_dock::target_rf_resl ](); align_to_scaffold = option[rif_dock::align_output_to_scaffold ](); output_scaffold_only = option[rif_dock::output_scaffold_only ](); output_full_scaffold_only = option[rif_dock::output_full_scaffold_only ](); output_full_scaffold = option[rif_dock::output_full_scaffold ](); pdb_info_pikaa = option[rif_dock::pdb_info_pikaa ](); dump_resfile = option[rif_dock::dump_resfile ](); target_res_fname = option[rif_dock::target_res ](); target_rf_oversample = option[rif_dock::target_rf_oversample ](); max_rf_bounding_ratio = option[rif_dock::max_rf_bounding_ratio ](); target_rf_cache = option[rif_dock::target_rf_cache ](); target_donors = option[rif_dock::target_donors ](); target_acceptors = option[rif_dock::target_acceptors ](); only_load_highest_resl = option[rif_dock::only_load_highest_resl ](); use_rosetta_grid_energies = option[rif_dock::use_rosetta_grid_energies ](); soft_rosetta_grid_energies = option[rif_dock::soft_rosetta_grid_energies ](); downscale_atr_by_hierarchy = option[rif_dock::downscale_atr_by_hierarchy ](); favorable_1body_multiplier = option[rif_dock::favorable_1body_multiplier ](); favorable_1body_multiplier_cutoff = option[rif_dock::favorable_1body_multiplier_cutoff ](); favorable_2body_multiplier = option[rif_dock::favorable_2body_multiplier ](); random_perturb_scaffold = option[rif_dock::random_perturb_scaffold ](); dont_use_scaffold_loops = option[rif_dock::dont_use_scaffold_loops ](); cache_scaffold_data = option[rif_dock::cache_scaffold_data ](); rf_resl = option[rif_dock::rf_resl ](); hack_pack = option[rif_dock::hack_pack ](); hack_pack_during_hsearch = option[rif_dock::hack_pack_during_hsearch ](); rf_oversample = option[rif_dock::rf_oversample ](); redundancy_filter_mag = option[rif_dock::redundancy_filter_mag ](); filter_seeding_positions_separately = option[rif_dock::filter_seeding_positions_separately ](); filter_scaffolds_separately = option[rif_dock::filter_scaffolds_separately ](); rotrf_oversample = option[rif_dock::rotrf_oversample ](); rotrf_resl = option[rif_dock::rotrf_resl ](); rotrf_spread = option[rif_dock::rotrf_spread ](); rotrf_cache_dir = option[rif_dock::rotrf_cache_dir ](); rotrf_scale_atr = option[rif_dock::rotrf_scale_atr ](); pack_iter_mult = option[rif_dock::pack_iter_mult ](); pack_n_iters = option[rif_dock::pack_n_iters ](); hbond_weight = option[rif_dock::hbond_weight ](); upweight_iface = option[rif_dock::upweight_iface ](); upweight_multi_hbond = option[rif_dock::upweight_multi_hbond ](); min_hb_quality_for_satisfaction = option[rif_dock::min_hb_quality_for_satisfaction ](); long_hbond_fudge_distance = option[rif_dock::long_hbond_fudge_distance ](); redundancy_filter_mag = option[rif_dock::redundancy_filter_mag ](); force_output_if_close_to_input_num = option[rif_dock::force_output_if_close_to_input_num ](); force_output_if_close_to_input = option[rif_dock::force_output_if_close_to_input ](); n_pdb_out = option[rif_dock::n_pdb_out ](); extra_rotamers = option[rif_dock::extra_rotamers ](); extra_rif_rotamers = option[rif_dock::extra_rif_rotamers ](); always_available_rotamers_level = option[rif_dock::always_available_rotamers_level ](); packing_use_rif_rotamers = option[rif_dock::packing_use_rif_rotamers ](); rosetta_score_fraction = option[rif_dock::rosetta_score_fraction ](); rosetta_score_then_min_below_thresh = option[rif_dock::rosetta_score_then_min_below_thresh ](); rosetta_score_at_least = option[rif_dock::rosetta_score_at_least ](); rosetta_score_at_most = option[rif_dock::rosetta_score_at_most ](); rosetta_min_fraction = option[rif_dock::rosetta_min_fraction ](); rosetta_min_at_least = option[rif_dock::rosetta_min_at_least ](); rosetta_min_fix_target = option[rif_dock::rosetta_min_fix_target ](); rosetta_min_targetbb = option[rif_dock::rosetta_min_targetbb ](); rosetta_min_scaffoldbb = option[rif_dock::rosetta_min_scaffoldbb ](); rosetta_min_allbb = option[rif_dock::rosetta_min_allbb ](); rosetta_score_cut = option[rif_dock::rosetta_score_cut ](); rosetta_hard_min = option[rif_dock::rosetta_hard_min ](); rosetta_score_total = option[rif_dock::rosetta_score_total ](); rosetta_score_ddg_only = option[rif_dock::rosetta_score_ddg_only ](); rosetta_score_rifres_rifres_weight = option[rif_dock::rosetta_score_rifres_rifres_weight ](); rosetta_score_rifres_scaffold_weight = option[rif_dock::rosetta_score_rifres_scaffold_weight ](); rosetta_soft_score = option[rif_dock::rosetta_soft_score ](); rosetta_hard_score = option[rif_dock::rosetta_hard_score ](); rosetta_beta = option[corrections::beta ](); rosetta_filter_before = option[rif_dock::rosetta_filter_before ](); rosetta_filter_n_per_scaffold = option[rif_dock::rosetta_filter_n_per_scaffold ](); rosetta_filter_redundancy_mag = option[rif_dock::rosetta_filter_redundancy_mag ](); rosetta_filter_even_if_no_score = option[rif_dock::rosetta_filter_even_if_no_score ](); user_rotamer_bonus_constant = option[rif_dock::user_rotamer_bonus_constant ](); user_rotamer_bonus_per_chi = option[rif_dock::user_rotamer_bonus_per_chi ](); rosetta_debug_dump_scores = option[rif_dock::rosetta_debug_dump_scores ](); rosetta_score_select_random = option[rif_dock::rosetta_score_select_random ](); dump_x_frames_per_resl = option[rif_dock::dump_x_frames_per_resl ](); dump_only_best_frames = option[rif_dock::dump_only_best_frames ](); dump_only_best_stride = option[rif_dock::dump_only_best_stride ](); dump_prefix = option[rif_dock::dump_prefix ](); scaff_search_mode = option[rif_dock::scaff_search_mode ](); nineA_cluster_path = option[rif_dock::nineA_cluster_path ](); nineA_baseline_range = option[rif_dock::nineA_baseline_range ](); low_cut_site = option[rif_dock::low_cut_site ](); high_cut_site = option[rif_dock::high_cut_site ](); max_insertion = option[rif_dock::max_insertion ](); max_deletion = option[rif_dock::max_deletion ](); fragment_cluster_tolerance = option[rif_dock::fragment_cluster_tolerance ](); fragment_max_rmsd = option[rif_dock::fragment_max_rmsd ](); max_fragments = option[rif_dock::max_fragments ](); morph_silent_file = option[rif_dock::morph_silent_file ](); morph_silent_archetype = option[rif_dock::morph_silent_archetype ](); morph_silent_max_structures = option[rif_dock::morph_silent_max_structures ](); morph_silent_random_selection = option[rif_dock::morph_silent_random_selection ](); morph_silent_cluster_use_frac = option[rif_dock::morph_silent_cluster_use_frac ](); include_parent = option[rif_dock::include_parent ](); use_parent_body_energies = option[rif_dock::use_parent_body_energies ](); dive_resl = option[rif_dock::dive_resl ](); pop_resl = option[rif_dock::pop_resl ](); match_this_pdb = option[rif_dock::match_this_pdb ](); match_this_rmsd = option[rif_dock::match_this_rmsd ](); rot_spec_fname = option[rif_dock::rot_spec_fname ](); seed_include_input = option[rif_dock::seed_include_input ](); seeding_by_patchdock = option[rif_dock::seeding_by_patchdock ](); xform_fname = option[rif_dock::xform_pos ](); rosetta_score_each_seeding_at_least = option[rif_dock::rosetta_score_each_seeding_at_least ](); cluster_score_cut = option[rif_dock::cluster_score_cut ](); keep_top_clusters_frac = option[rif_dock::keep_top_clusters_frac ](); unsat_orbital_penalty = option[rif_dock::unsat_orbital_penalty ](); neighbor_distance_cutoff = option[rif_dock::neighbor_distance_cutoff ](); unsat_neighbor_cutoff = option[rif_dock::unsat_neighbor_cutoff ](); unsat_debug = option[rif_dock::unsat_debug ](); test_hackpack = option[rif_dock::test_hackpack ](); unsat_helper = option[rif_dock::unsat_helper ](); unsat_score_offset = option[rif_dock::unsat_score_offset ](); unsat_require_burial = option[rif_dock::unsat_require_burial ](); report_common_unsats = option[rif_dock::report_common_unsats ](); dump_presatisfied_donors_acceptors = option[rif_dock::dump_presatisfied_donors_acceptors ](); for( std::string s : option[rif_dock::scaffolds ]() ) scaffold_fnames.push_back(s); for( std::string s : option[rif_dock::scaffold_res ]() ) scaffold_res_fnames.push_back(s); for( std::string s : option[rif_dock::data_cache_dir]() ) data_cache_path.push_back(s); for( std::string fn : option[rif_dock::target_bounding_xmaps]() ) rif_files.push_back(fn); rif_files.push_back( option[rif_dock::target_rif]() ); if( scaff2ala && scaff2alaselonly && option[rif_dock::scaffold_to_ala_selonly].user() ){ std::cout << "WARNING: -scaffold_to_ala overrides -scaffold_to_ala_selonly!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl; } if( rosetta_score_total && rosetta_score_ddg_only ){ std::cout << "WARNING: rosetta_score_total overrives rosetta_score_ddg_only" << std::endl; rosetta_score_ddg_only = false; } runtime_assert_msg( min_hb_quality_for_satisfaction < 0 && min_hb_quality_for_satisfaction > -1, "-min_hb_quality_for_satisfaction must be between -1 and 0"); nfold_symmetry = option[rif_dock::nfold_symmetry](); symmetry_axis.clear(); if( option[rif_dock::symmetry_axis]().size() == 3 ){ symmetry_axis.push_back( option[rif_dock::symmetry_axis]()[1] ); symmetry_axis.push_back( option[rif_dock::symmetry_axis]()[2] ); symmetry_axis.push_back( option[rif_dock::symmetry_axis]()[3] ); } else if( option[rif_dock::symmetry_axis]().size() == 0 ){ symmetry_axis.push_back(0); symmetry_axis.push_back(0); symmetry_axis.push_back(1); } else { std::cout << "bad rif_dock::symmetry_axis option" << std::endl; std::exit(-1); } // Brian if (option[rif_dock::use_scaffold_bounding_grids]()) { std::cout << "ERROR: use_scaffold_bounding_grids no longer supported. Email bcov@uw.edu" << std::endl; std::exit(-1); } if (option[rif_dock::nfold_symmetry]() > 1) { std::cout << "ERROR: nfold_symmetry not currently supported. Email bcov@uw.edu" << std::endl; std::exit(-1); } if ( scaff_search_mode == "nineA_baseline" ) { if ( scaffold_fnames.size() > 0 ) { std::cout << "ERROR: can't use -scaffolds with nineA_baseline." << std::endl; std::exit(-1); } std::vector<uint64_t> cdindex_then_clusts = devel::scheme::parse_nineA_baseline_range( nineA_baseline_range ); uint64_t num_scaffolds = cdindex_then_clusts.size() - 1; runtime_assert( num_scaffolds > 0 ); scaffold_fnames.resize(num_scaffolds); } for( std::string s : option[rif_dock::morph_rules_files ]() ) morph_rules_fnames.push_back(s); // constrain file names for( std::string s : option[rif_dock::cst_files ]() ) cst_fnames.push_back(s); for( std::string s : option[rif_dock::seed_with_these_pdbs ]() ) seed_with_these_pdbs.push_back(s); for( std::string s : option[rif_dock::seeding_pos ]() ) seeding_fnames.push_back(s); for( int req : option[rif_dock::requirements]() ) requirements.push_back(req); } #endif #endif
58.648796
158
0.612406
willsheffler
f0cb289aca4dd19d69e868efc9e4137c98d0b056
1,771
cpp
C++
matlab/panoContext_code/Toolbox/segmentation/segmentGraphMex_edge.cpp
imamik/LayoutNet
f68eb214e793b9786f2582f9244bac4f8f98a816
[ "MIT" ]
380
2018-02-23T02:58:35.000Z
2022-03-21T06:34:33.000Z
matlab/panoContext_code/Toolbox/segmentation/segmentGraphMex_edge.cpp
imamik/LayoutNet
f68eb214e793b9786f2582f9244bac4f8f98a816
[ "MIT" ]
36
2018-04-11T03:49:42.000Z
2021-01-21T01:25:47.000Z
matlab/panoContext_code/Toolbox/segmentation/segmentGraphMex_edge.cpp
imamik/LayoutNet
f68eb214e793b9786f2582f9244bac4f8f98a816
[ "MIT" ]
94
2018-02-25T05:23:51.000Z
2022-02-11T02:00:47.000Z
#include <cstdio> #include <cstdlib> #include <image.h> #include <misc.h> #include <pnmfile.h> #include "mex.h" #include "segment-image.h" void mexFunction(int nlhs,mxArray* plhs[],int nrhs,const mxArray* prhs[]) { // check arguments if (nrhs != 5) { mexPrintf("Usage: [seg] = segmentGraphMex_edge(maxID, numEdge, edges, threshold, minSize);\n"); return; } // convert edges memory from matlab to c++ int maxID = (int)mxGetScalar(prhs[0]); int numEdge = (int)mxGetScalar(prhs[1]); double* edgeMat = (double*)mxGetData(prhs[2]); double c = mxGetScalar(prhs[3]); int min_size = (int)mxGetScalar(prhs[4]); printf("maxID: %d, numEdge: %d, c: %f, min_size: %d\n", maxID, numEdge, c, min_size); edge *edges = new edge[numEdge]; for( int i = 0; i<numEdge; i++) { edges[i].a = edgeMat[i*3+0]; edges[i].b = edgeMat[i*3+1]; edges[i].w = edgeMat[i*3+2]; } printf("a: %d, b: %d, w: %f\n", edges[0].a, edges[0].b, edges[0].w); printf("Loading finished!\n"); universe *u = segment_graph( maxID, numEdge, edges, c); printf("get out of segment_graph\n"); // post process for (int i = 0; i < numEdge; i++) { int a = u->find(edges[i].a); int b = u->find(edges[i].b); if ((a != b) && ((u->size(a) < min_size) || (u->size(b) < min_size))) u->join(a, b); } printf("finish post process\n"); // pass result to matlab plhs[0] = mxCreateNumericMatrix((mwSize)maxID, 1, mxDOUBLE_CLASS, mxREAL); double* output = (double *)mxGetData(plhs[0]); for (int i = 0; i<maxID; i++) { output[i] = (double)(u->find(i+1)); } printf("packed up output\n"); delete[] edges; printf("delete edges\n"); //delete u; printf("memory released\n"); }
29.516667
98
0.585545
imamik
f0cd16803c3887c2e9fc46e5b45ea987f4b0c6b2
8,806
cpp
C++
src/main.cpp
russellklenk/gwbase
eb4094b4cea29cd24612e88298efbdfbec1d59aa
[ "Unlicense" ]
3
2018-03-24T12:28:05.000Z
2021-07-29T02:00:16.000Z
src/main.cpp
russellklenk/gwbase
eb4094b4cea29cd24612e88298efbdfbec1d59aa
[ "Unlicense" ]
null
null
null
src/main.cpp
russellklenk/gwbase
eb4094b4cea29cd24612e88298efbdfbec1d59aa
[ "Unlicense" ]
1
2018-05-13T12:59:01.000Z
2018-05-13T12:59:01.000Z
/*///////////////////////////////////////////////////////////////////////////// /// @summary Implements the entry point of the application. This handles the /// setup of our third party libraries and the creation of our main window and /// rendering context, along with implementing the game loop. /// @author Russell Klenk (contact@russellklenk.com) ///////////////////////////////////////////////////////////////////////////80*/ /*//////////////// // Includes // ////////////////*/ #include <stdio.h> #include <stdlib.h> #include "math.hpp" #include "input.hpp" #include "display.hpp" #include "entity.hpp" #include "player.hpp" #include "ll_sprite.hpp" #include "ll_shader.hpp" /*///////////////// // Constants // /////////////////*/ #define GW_WINDOW_WIDTH 800 #define GW_WINDOW_HEIGHT 600 #define GW_WINDOW_TITLE "Geometry Wars" #define GW_MIN_TIMESTEP 0.000001 #define GW_MAX_TIMESTEP 0.25 #define GW_SIM_TIMESTEP 1.0 / 120.0 /*/////////////// // Globals // ///////////////*/ static EntityManager *gEntityManager = NULL; static DisplayManager *gDisplayManager = NULL; static InputManager *gInputManager = NULL; /*/////////////////////// // Local Functions // ///////////////////////*/ /// @summary Callback to handle a GLFW error. Prints the error information to stderr. /// @param error_code The internal GLFW error code. /// @param error_desc A textual description of the error. static void glfw_error(int error_code, char const *error_desc) { fprintf(stderr, "ERROR: (GLFW code 0x%08X): %s\n", error_code, error_desc); } #if GL_DEBUG_ENABLE /// @summary Callback to handle output from the GL_ARB_debug_output extension, /// which is of course not supported on OSX as of 10.9. /// @param source /// @param type /// @param id /// @param severity /// @param length /// @param message /// @param context static void gl_arb_debug( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, char const *message, void *context) { UNUSED_ARG(source); UNUSED_ARG(type); UNUSED_ARG(id); UNUSED_ARG(severity); UNUSED_ARG(length); UNUSED_ARG(context); fprintf(stdout, "ARB_debug: %s\n", message); } #endif /// @summary Executes all of the logic associated with game user input. This /// is also where we would run user interface logic. Runs once per application tick. /// @param currentTime The current absolute time, in seconds. This represents /// the time at which the current tick started. /// @param elapsedTime The time elapsed since the previous tick, in seconds. static void input(double currentTime, double elapsedTime) { gInputManager->Update(currentTime, elapsedTime); gEntityManager->Input(currentTime, elapsedTime, gInputManager); } /// @summary Executes a single game simulation tick to move all game entities. /// Runs zero or more times per application tick at a fixed timestep. /// @param currentTime The current absolute simulation time, in seconds. This /// represents the time at which the current simulation tick started. /// @param elapsedTime The time elapsed since the previous tick, in seconds. static void simulate(double currentTime, double elapsedTime) { gEntityManager->Update(currentTime, elapsedTime); } /// @summary Submits a single frame to the GPU for rendering. Runs once per /// application tick at a variable timestep. /// @param currentTime The current absolute time, in seconds. This represents /// the time at which the current tick started. /// @param elapsedTime The time elapsed since the previous tick, in seconds. /// @param t A value in [0, 1] indicating how far into the current simulation /// step we are at the time the frame is generated. /// @param width The width of the default framebuffer, in pixels. /// @param height The height of the default framebuffer, in pixels. static void render(double currentTime, double elapsedTime, double t, int width, int height) { UNUSED_ARG(currentTime); UNUSED_ARG(elapsedTime); UNUSED_ARG(t); DisplayManager *dm = gDisplayManager; SpriteBatch *batch = dm->GetBatch(); SpriteFont *font = dm->GetFont(); float rgba[]= {1.0f, 0.0f, 0.0f, 1.0f}; dm->SetViewport(width, height); dm->Clear(0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0); dm->BeginFrame(); batch->SetBlendModeAlpha(); font->Draw("Hello, world!", 0, 0, 1, rgba, 5.0f, 5.0f, batch); gEntityManager->Draw(currentTime, elapsedTime, dm); dm->EndFrame(); } /*/////////////////////// // Public Functions // ///////////////////////*/ int main(int argc, char **argv) { GLFWwindow *window = NULL; UNUSED_ARG(argc); UNUSED_ARG(argv); // initialize GLFW, our platform abstraction library. glfwSetErrorCallback(glfw_error); if (!glfwInit()) { exit(EXIT_FAILURE); } glfwWindowHint(GLFW_VISIBLE, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #if GL_DEBUG_ENABLE glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); #endif // create the main application window and OpenGL context. window = glfwCreateWindow(GW_WINDOW_WIDTH, GW_WINDOW_HEIGHT, GW_WINDOW_TITLE, NULL, NULL); if (window == NULL) { fprintf(stderr, "ERROR: Cannot create primary GLFW window.\n"); glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); // now that we have an OpenGL context, load extensions provided by the platform. // note that glewExperimental is defined by the GLEW library and is required on // OSX or the glGenVertexArrays() call will cause a fault. glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { fprintf(stderr, "ERROR: Cannot initialize GLEW for the primary context.\n"); glfwTerminate(); exit(EXIT_FAILURE); } // clear any OpenGL error status and configure debug output. glGetError(); #if GL_DEBUG_ENABLE if (GLEW_ARB_debug_output) { glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); glDebugMessageCallbackARB(gl_arb_debug, NULL); } #endif // initialize global managers: gDisplayManager = new DisplayManager(); gDisplayManager->Init(window); gInputManager = new InputManager(); gInputManager->Init(window); Player *player = new Player(0); player->Init(gDisplayManager); gEntityManager = new EntityManager(); gEntityManager->AddEntity(player); // game loop setup and run: const double Step = GW_SIM_TIMESTEP; double previousTime = glfwGetTime(); double currentTime = previousTime; double elapsedTime = 0.0; double accumulator = 0.0; double simTime = 0.0; double t = 0.0; int width = 0; int height = 0; while (!glfwWindowShouldClose(window)) { // retrieve the current framebuffer size, which // may be different from the current window size. glfwGetFramebufferSize(window, &width, &height); // update the main game clock. previousTime = currentTime; currentTime = glfwGetTime(); elapsedTime = currentTime - previousTime; if (elapsedTime > GW_MAX_TIMESTEP) { elapsedTime = GW_MAX_TIMESTEP; } if (elapsedTime < GW_MIN_TIMESTEP) { elapsedTime = GW_MIN_TIMESTEP; } accumulator += elapsedTime; // process user input at the start of the frame. input(currentTime, elapsedTime); // execute the simulation zero or more times per-frame. // the simulation runs at a fixed timestep. while (accumulator >= Step) { // @todo: swap game state buffers here. // pass the current game state to simulate. simulate(simTime, Step); accumulator -= Step; simTime += Step; } // interpolate display state. t = accumulator / Step; // state = currentState * t + previousState * (1.0 - t); render(currentTime, elapsedTime, t, width, height); // now present the current frame and process OS events. glfwSwapBuffers(window); glfwPollEvents(); } // teardown global managers. delete gEntityManager; delete gDisplayManager; delete gInputManager; // perform any top-level cleanup. glfwTerminate(); exit(EXIT_SUCCESS); }
33.356061
94
0.650693
russellklenk
f0da524a8ee5f41b5b255973c45add652ae74843
473
cc
C++
src/core/logging_event.cc
pragkent/logbox
15274be0726cd3f0d71266a0ce4755106c8bdd1f
[ "MIT" ]
2
2015-02-14T04:24:07.000Z
2015-02-28T11:23:48.000Z
src/core/logging_event.cc
pragkent/logbox
15274be0726cd3f0d71266a0ce4755106c8bdd1f
[ "MIT" ]
null
null
null
src/core/logging_event.cc
pragkent/logbox
15274be0726cd3f0d71266a0ce4755106c8bdd1f
[ "MIT" ]
null
null
null
#include "core/logging_event.h" #include <errno.h> #include "util/environment.h" namespace logbox { LoggingEvent::LoggingEvent( LogSeverity severity, const char* file, int line, const char* function) : severity_(severity), file_fullname_(file), file_basename_(Environment::GetBasename(file)), line_no_(line), function_(function), preserved_errno_(errno), timestamp_(Environment::Now()) { } } // namespace logbox
20.565217
53
0.676533
pragkent
f0da74da343d1e48921fbefea6fe4b456427bae7
1,197
cpp
C++
Code/System/Core/Time/Time.cpp
JuanluMorales/KRG
f3a11de469586a4ef0db835af4bc4589e6b70779
[ "MIT" ]
419
2022-01-27T19:37:43.000Z
2022-03-31T06:14:22.000Z
Code/System/Core/Time/Time.cpp
jagt/KRG
ba20cd8798997b0450491b0cc04dc817c4a4bc76
[ "MIT" ]
2
2022-01-28T20:35:33.000Z
2022-03-13T17:42:52.000Z
Code/System/Core/Time/Time.cpp
jagt/KRG
ba20cd8798997b0450491b0cc04dc817c4a4bc76
[ "MIT" ]
20
2022-01-27T20:41:02.000Z
2022-03-26T16:16:57.000Z
#include "Time.h" #include <chrono> //------------------------------------------------------------------------- namespace KRG { KRG::Nanoseconds EngineClock::CurrentTime = 0; //------------------------------------------------------------------------- Nanoseconds::operator Microseconds() const { auto const duration = std::chrono::duration<uint64, std::chrono::steady_clock::period>( m_value ); uint64 const numMicroseconds = std::chrono::duration_cast<std::chrono::microseconds>( duration ).count(); return float( numMicroseconds ); } //------------------------------------------------------------------------- Nanoseconds PlatformClock::GetTime() { auto const time = std::chrono::high_resolution_clock::now(); uint64 const numNanosecondsSinceEpoch = time.time_since_epoch().count(); return Nanoseconds( numNanosecondsSinceEpoch ); } //------------------------------------------------------------------------- void EngineClock::Update( Milliseconds deltaTime ) { KRG_ASSERT( deltaTime >= 0 ); CurrentTime += deltaTime.ToNanoseconds(); } }
34.2
114
0.472013
JuanluMorales
f0db14785a36f33ca7d2e246eff7183b9b3bb82d
215
cpp
C++
src/sysGCU/appThread.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
33
2021-12-08T11:10:59.000Z
2022-03-26T19:59:37.000Z
src/sysGCU/appThread.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
6
2021-12-22T17:54:31.000Z
2022-01-07T21:43:18.000Z
src/sysGCU/appThread.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
2
2022-01-04T06:00:49.000Z
2022-01-26T07:27:28.000Z
#include "types.h" #include "AppThread.h" /* * --INFO-- * Address: 80424E18 * Size: 00003C */ AppThread::AppThread(u32 stackSize, int msgCount, int priority) : JKRThread(stackSize, msgCount, priority) { }
15.357143
63
0.674419
projectPiki
f0ddf37d5a08322fefec7ff12c8b80b255fc02f5
370
cpp
C++
LeetCode/Problems/Algorithms/#762_PrimeNumberOfSetBitsInBinaryRepresentation_sol1_builtin_popcount_and_unordered_set_O(R-L)_time_O(1)_extra_space_40ms_6.5MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#762_PrimeNumberOfSetBitsInBinaryRepresentation_sol1_builtin_popcount_and_unordered_set_O(R-L)_time_O(1)_extra_space_40ms_6.5MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#762_PrimeNumberOfSetBitsInBinaryRepresentation_sol1_builtin_popcount_and_unordered_set_O(R-L)_time_O(1)_extra_space_40ms_6.5MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { public: int countPrimeSetBits(int L, int R) { const unordered_set<int> PRIMES = {2,3,5,7,11,13,17,19}; int answer = 0; for(int num = L; num <= R; ++num){ int setBitsCnt = __builtin_popcount(num); answer += (PRIMES.find(setBitsCnt) != PRIMES.end()); } return answer; } };
30.833333
65
0.524324
Tudor67
f0e719c6ea86f83338f9e8745890360cae78d634
6,370
cpp
C++
texture.cpp
CaptainDreamcast/prism
a6b0f5c3e86d7b37d14c9139862775e7768998ce
[ "MIT" ]
7
2018-04-08T15:01:59.000Z
2022-02-27T12:13:19.000Z
texture.cpp
CaptainDreamcast/prism
a6b0f5c3e86d7b37d14c9139862775e7768998ce
[ "MIT" ]
1
2017-04-23T15:27:37.000Z
2017-04-24T05:38:18.000Z
texture.cpp
CaptainDreamcast/libtari
a6b0f5c3e86d7b37d14c9139862775e7768998ce
[ "MIT" ]
1
2020-04-24T04:21:00.000Z
2020-04-24T04:21:00.000Z
#include "prism/texture.h" #include<algorithm> #ifdef DREAMCAST #include <png/png.h> #else #include <png.h> #endif #include "prism/file.h" #include "prism/log.h" #include "prism/system.h" #include "prism/math.h" using namespace std; #define FONT_CHARACTER_AMOUNT 91 static int isFontDataLoaded; static TextureData gFont; static FontCharacterData gFontCharacterData[FONT_CHARACTER_AMOUNT]; void unloadFont() { if (!isFontDataLoaded) return; unloadTexture(gFont); memset(gFontCharacterData, 0, sizeof gFontCharacterData); isFontDataLoaded = 0; } static void loadFontHeader(const char* tFileDir) { FileHandler file; file = fileOpen(tFileDir, O_RDONLY); if (file == FILEHND_INVALID) { logError("Cannot open font header."); logErrorString(tFileDir); recoverFromError(); } fileSeek(file, 0, 0); int i; for (i = 0; i < FONT_CHARACTER_AMOUNT; i++) { fileRead(file, &gFontCharacterData[i], sizeof gFontCharacterData[i]); } fileClose(file); } static void loadFontTexture(const char* tFileDir) { gFont = loadTexturePKG(tFileDir); } void setFont(const char* tFileDirHeader, const char* tFileDirTexture) { if (isFontDataLoaded) { unloadFont(); } if (!isFile(tFileDirHeader)) { return; } loadFontHeader(tFileDirHeader); loadFontTexture(tFileDirTexture); isFontDataLoaded = 1; } void loadConsecutiveTextures(TextureData * tDst, const char * tBaseFileDir, int tAmount) { int i; for (i = 0; i < tAmount; i++) { char path[1024]; getPathWithNumberAffixedFromAssetPath(path, tBaseFileDir, i); tDst[i] = loadTexture(path); } } TextureData getFontTexture() { return gFont; } FontCharacterData getFontCharacterData(char tChar) { int i; if (tChar < ' ' || tChar > 'z') i = 0; else i = tChar - ' '; return gFontCharacterData[i]; } TextureSize makeTextureSize(int x, int y) { TextureSize ret; ret.x = x; ret.y = y; return ret; } TextureData createWhiteTexture() { int length = 16 * 16 * 4; uint8_t* data = (uint8_t*)allocMemory(length); memset(data, 0xFF, length); TextureData ret = loadTextureFromARGB32Buffer(makeBuffer(data, length), 16, 16); freeMemory(data); return ret; } TextureData createWhiteCircleTexture() { int length = 16 * 16 * 4; uint8_t* data = (uint8_t*)allocMemory(length); memset(data, 0xFF, length); const std::vector<int> LINE_EMPTY_AMOUNT = {5, 3, 2, 1, 1}; for (size_t y = 0; y < LINE_EMPTY_AMOUNT.size(); y++) { const auto width = LINE_EMPTY_AMOUNT[y]; for (int x = 0; x < width; x++) { data[(y * 16 + x) * 4 + 3] = 0; data[(y * 16 + (15 - x)) * 4 + 3] = 0; data[((15 - y) * 16 + x) * 4 + 3] = 0; data[((15 - y) * 16 + (15 - x)) * 4 + 3] = 0; } } TextureData ret = loadTextureFromARGB32Buffer(makeBuffer(data, length), 16, 16); freeMemory(data); return ret; } Buffer turnARGB32BufferIntoARGB16Buffer(const Buffer& tSrc) { int dstSize = tSrc.mLength / 2; char* dst = (char*)allocMemory(dstSize); char* src = (char*)tSrc.mData; int n = dstSize / 2; int i; for(i = 0; i < n; i++) { int srcPos = 4*i; int dstPos = 2*i; uint8_t a = ((uint8_t)src[srcPos + 3]) >> 4; uint8_t r = ((uint8_t)src[srcPos + 2]) >> 4; uint8_t g = ((uint8_t)src[srcPos + 1]) >> 4; uint8_t b = ((uint8_t)src[srcPos + 0]) >> 4; dst[dstPos + 0] = (g << 4) | b; dst[dstPos + 1] = (a << 4) | r; } return makeBufferOwned(dst, dstSize); } /* Linear/iterative twiddling algorithm from Marcus' tatest */ #define TWIDTAB(x) ( (x&1)|((x&2)<<1)|((x&4)<<2)|((x&8)<<3)|((x&16)<<4)| \ ((x&32)<<5)|((x&64)<<6)|((x&128)<<7)|((x&256)<<8)|((x&512)<<9) ) #define TWIDOUT(x, y) ( TWIDTAB((y)) | (TWIDTAB((x)) << 1) ) #define MIN(a, b) ( (a)<(b)? (a):(b) ) /* This twiddling code is copied from pvr_texture.c, and the original algorithm was written by Vincent Penne. */ Buffer twiddleTextureBuffer8(const Buffer& tBuffer, int tWidth, int tHeight) { int w = tWidth; int h = tHeight; int mini = min(w, h); int mask = mini - 1; uint8_t * pixels = (uint8_t *)tBuffer.mData; uint8_t * vtex = (uint8_t*)allocMemory(tBuffer.mLength); int x, y, yout; for(y = 0; y < h; y++) { yout = y; for(x = 0; x < w; x++) { vtex[TWIDOUT(x & mask, yout & mask) + (x / mini + yout / mini)*mini * mini] = pixels[y * w + x]; } } return makeBufferOwned(vtex, tBuffer.mLength); } Buffer twiddleTextureBuffer16(const Buffer& tBuffer, int tWidth, int tHeight) { int w = tWidth; int h = tHeight; int mini = min(w, h); int mask = mini - 1; uint16_t * pixels = (uint16_t *)tBuffer.mData; uint16_t * vtex = (uint16_t*)allocMemory(tBuffer.mLength); int x, y, yout; for (y = 0; y < h; y++) { yout = y; for (x = 0; x < w; x++) { vtex[TWIDOUT(x & mask, yout & mask) + (x / mini + yout / mini)*mini * mini] = pixels[y * w + x]; } } return makeBufferOwned(vtex, tBuffer.mLength); } #ifdef DREAMCAST #pragma GCC diagnostic ignored "-Wclobbered" #endif #ifdef _WIN32 #pragma warning(push) #pragma warning(disable: 4611) #endif void saveRGB32ToPNG(const Buffer& b, int tWidth, int tHeight, const char* tFileDir) { char fullPath[1024]; getFullPath(fullPath, tFileDir); FILE *fp = fopen(fullPath, "wb"); if (!fp) { logErrorFormat("Unable to open file %s", tFileDir); return; } auto png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { logError("Unable to create png struct."); return; } auto info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { logError("Unable to create png info struct."); return; } if (setjmp(png_jmpbuf(png_ptr))) { logError("Exception writing png."); return; } png_init_io(png_ptr, fp); if (setjmp(png_jmpbuf(png_ptr))) { logError("Exception writing png."); return; } png_set_IHDR(png_ptr, info_ptr, tWidth, tHeight, 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(png_ptr, info_ptr); if (setjmp(png_jmpbuf(png_ptr))) { logError("Exception writing png."); return; } for (int y = tHeight - 1; y >= 0; y--) { png_bytep bytes = ((png_bytep)b.mData) + tWidth * 3 * y; png_write_rows(png_ptr, &bytes, 1); } if (setjmp(png_jmpbuf(png_ptr))) { logError("Exception writing png."); return; } png_write_end(png_ptr, NULL); fclose(fp); } #ifdef _WIN32 #pragma warning(pop) #endif
22.75
88
0.649137
CaptainDreamcast
f0e933ed100092fe5cf143ddcb9558b9fc32c21d
267
hpp
C++
pythran/pythonic/include/__builtin__/ReferenceError.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
1
2018-03-24T00:33:03.000Z
2018-03-24T00:33:03.000Z
pythran/pythonic/include/__builtin__/ReferenceError.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/include/__builtin__/ReferenceError.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
#ifndef PYTHONIC_INCLUDE_BUILTIN_REFERENCEERROR_HPP #define PYTHONIC_INCLUDE_BUILTIN_REFERENCEERROR_HPP #include "pythonic/include/types/exceptions.hpp" PYTHONIC_NS_BEGIN namespace __builtin__ { PYTHONIC_EXCEPTION_DECL(ReferenceError) } PYTHONIC_NS_END #endif
16.6875
51
0.868914
SylvainCorlay
f0ea469a07225cc24c6b92a7cb30c43024a6108f
5,692
cpp
C++
c++/src/corelib/ncbi_safe_static.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
31
2016-12-09T04:56:59.000Z
2021-12-31T17:19:10.000Z
c++/src/corelib/ncbi_safe_static.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
6
2017-03-10T17:25:13.000Z
2021-09-22T15:49:49.000Z
c++/src/corelib/ncbi_safe_static.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
20
2015-01-04T02:15:17.000Z
2021-12-03T02:31:43.000Z
/* $Id: ncbi_safe_static.cpp 177027 2009-11-24 19:19:28Z grichenk $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Aleksey Grichenko * * File Description: * Static variables safety - create on demand, destroy on termination * * CSafeStaticGuard:: -- guarantee for CSafePtr<> and CSafeRef<> * destruction and cleanup * */ #include <ncbi_pch.hpp> #include <corelib/ncbi_safe_static.hpp> #include <corelib/ncbistd.hpp> #include <corelib/ncbithr.hpp> #include <corelib/ncbimtx.hpp> #include <corelib/error_codes.hpp> #include <memory> #include <assert.h> #define NCBI_USE_ERRCODE_X Corelib_Static BEGIN_NCBI_SCOPE CSafeStaticLifeSpan::CSafeStaticLifeSpan(ELifeSpan span, int adjust) : m_LifeSpan(int(span) + adjust) { if (span == eLifeSpan_Min) { m_LifeSpan = int(span); // ignore adjustments adjust = 0; } if (adjust >= 5000 || adjust <= -5000) { ERR_POST_X(1, Warning << "CSafeStaticLifeSpan level adjustment out of range: " << adjust); } _ASSERT(adjust > -5000 && adjust < 5000); } CSafeStaticLifeSpan& CSafeStaticLifeSpan::GetDefault(void) { static CSafeStaticLifeSpan s_DefaultSpan(eLifeSpan_Min); return s_DefaultSpan; } ///////////////////////////////////////////////////////////////////////////// // // CSafeStaticPtr_Base:: // // Protective mutex and the owner thread ID to avoid // multiple initializations and deadlocks DEFINE_STATIC_MUTEX(s_Mutex); static CThreadSystemID s_MutexOwner; // true if s_MutexOwner has been set (while the mutex is locked) static bool s_MutexLocked; bool CSafeStaticPtr_Base::Init_Lock(bool* mutex_locked) { // Check if already locked by the same thread to avoid deadlock // in case of nested calls to Get() by T constructor // Lock only if unlocked or locked by another thread // to prevent initialization by another thread CThreadSystemID id = CThreadSystemID::GetCurrent(); if (!s_MutexLocked || s_MutexOwner != id) { s_Mutex.Lock(); s_MutexLocked = true; *mutex_locked = true; s_MutexOwner = id; } return m_Ptr == 0; } void CSafeStaticPtr_Base::Init_Unlock(bool mutex_locked) { // Unlock the mutex only if it was locked by the same call to Get() if ( mutex_locked ) { s_MutexLocked = false; s_Mutex.Unlock(); } } int CSafeStaticPtr_Base::x_GetCreationOrder(void) { static CAtomicCounter s_CreationOrder; return s_CreationOrder.Add(1); } CSafeStaticPtr_Base::~CSafeStaticPtr_Base(void) { bool mutex_locked = false; if ( x_IsStdStatic() && !Init_Lock(&mutex_locked) ) { x_Cleanup(); } Init_Unlock(mutex_locked); } ///////////////////////////////////////////////////////////////////////////// // // CSafeStaticGuard:: // // Cleanup stack to keep all on-demand variables CSafeStaticGuard::TStack* CSafeStaticGuard::sm_Stack; // CSafeStaticGuard reference counter int CSafeStaticGuard::sm_RefCount; CSafeStaticGuard::CSafeStaticGuard(void) { // Initialize the guard only once if (sm_RefCount == 0) { CSafeStaticGuard::sm_Stack = new CSafeStaticGuard::TStack; } sm_RefCount++; } static CSafeStaticGuard* sh_CleanupGuard; CSafeStaticGuard::~CSafeStaticGuard(void) { CMutexGuard guard(s_Mutex); // Protect CSafeStaticGuard destruction if ( sh_CleanupGuard ) { CSafeStaticGuard* tmp = sh_CleanupGuard; sh_CleanupGuard = 0; delete tmp; } // If this is not the last reference, then do not destroy stack if (--sm_RefCount > 0) { return; } assert(sm_RefCount == 0); // Call Cleanup() for all variables registered NON_CONST_ITERATE(TStack, it, *sm_Stack) { (*it)->x_Cleanup(); } delete sm_Stack; sm_Stack = 0; } // Global guard - to prevent premature destruction by e.g. GNU compiler // (it destroys all local static variables before any global one) static CSafeStaticGuard sg_CleanupGuard; // Initialization of the guard CSafeStaticGuard* CSafeStaticGuard::x_Get(void) { // Local static variable - to initialize the guard // as soon as the function is called (global static // variable may be still uninitialized at this moment) static CSafeStaticGuard sl_CleanupGuard; if ( !sh_CleanupGuard ) sh_CleanupGuard = new CSafeStaticGuard; return &sl_CleanupGuard; } END_NCBI_SCOPE
27.765854
78
0.655657
OpenHero
f0ed6acb33e0b41499306ec4590b306a0280924d
5,808
cpp
C++
libs/geometry/src/matrix.cpp
blagodarin/yttrium
534289c3082355e5537a03c0b5855b60f0c344ad
[ "Apache-2.0" ]
null
null
null
libs/geometry/src/matrix.cpp
blagodarin/yttrium
534289c3082355e5537a03c0b5855b60f0c344ad
[ "Apache-2.0" ]
null
null
null
libs/geometry/src/matrix.cpp
blagodarin/yttrium
534289c3082355e5537a03c0b5855b60f0c344ad
[ "Apache-2.0" ]
null
null
null
// This file is part of the Yttrium toolkit. // Copyright (C) Sergei Blagodarin. // SPDX-License-Identifier: Apache-2.0 #include <yttrium/geometry/matrix.h> #include <yttrium/geometry/euler.h> #include <yttrium/geometry/size.h> #include <cmath> #include <numbers> namespace Yt { Matrix4::Matrix4(const Euler& e) noexcept { const auto yaw = e._yaw / 180 * std::numbers::pi_v<float>; const auto pitch = e._pitch / 180 * std::numbers::pi_v<float>; const auto roll = e._roll / 180 * std::numbers::pi_v<float>; const auto cy = std::cos(yaw); const auto sy = std::sin(yaw); const auto cp = std::cos(pitch); const auto sp = std::sin(pitch); const auto cr = std::cos(roll); const auto sr = std::sin(roll); x = { sy * sp * sr + cy * cr, cy * sp * sr - sy * cr, -cp * sr, 0 }; y = { sy * cp, cy * cp, sp, 0 }; z = { cy * sr - sy * sp * cr, -cy * sp * cr - sy * sr, cp * cr, 0 }; t = { 0, 0, 0, 1 }; } Matrix4 Matrix4::camera(const Vector3& position, const Euler& orientation) noexcept { const Matrix4 r{ orientation }; return { r.x.x, r.x.y, r.x.z, -dot_product(position, { r.x.x, r.x.y, r.x.z }), r.y.x, r.y.y, r.y.z, -dot_product(position, { r.y.x, r.y.y, r.y.z }), r.z.x, r.z.y, r.z.z, -dot_product(position, { r.z.x, r.z.y, r.z.z }), 0, 0, 0, 1 }; } Matrix4 Matrix4::perspective(const SizeF& size, float vertical_fov, float near_plane, float far_plane) noexcept { const auto aspect = size._width / size._height; const auto f = 1 / std::tan(vertical_fov / 360 * std::numbers::pi_v<float>); const auto xx = f / aspect; const auto yy = f; const auto zz = (near_plane + far_plane) / (near_plane - far_plane); const auto tz = 2 * near_plane * far_plane / (near_plane - far_plane); const auto zw = -1.f; return { xx, 0, 0, 0, 0, yy, 0, 0, 0, 0, zz, tz, 0, 0, zw, 0 }; } Matrix4 Matrix4::projection_2d(const SizeF& size, float near_plane, float far_plane) noexcept { const auto xx = 2 / size._width; const auto yy = -2 / size._height; const auto zz = -2 / (far_plane - near_plane); const auto tx = -1.f; const auto ty = 1.f; const auto tz = (far_plane + near_plane) / (far_plane - near_plane); return { xx, 0, 0, tx, 0, yy, 0, ty, 0, 0, zz, tz, 0, 0, 0, 1 }; } Matrix4 Matrix4::rotation(float degrees, const Vector3& axis) noexcept { const auto v = normalize(axis); const auto radians = degrees / 180 * std::numbers::pi_v<float>; const auto c = std::cos(radians); const auto s = std::sin(radians); return { v.x * v.x * (1 - c) + c, v.y * v.x * (1 - c) - s * v.z, v.z * v.x * (1 - c) + s * v.y, 0, v.x * v.y * (1 - c) + s * v.z, v.y * v.y * (1 - c) + c, v.z * v.y * (1 - c) - s * v.x, 0, v.x * v.z * (1 - c) - s * v.y, v.y * v.z * (1 - c) + s * v.x, v.z * v.z * (1 - c) + c, 0, 0, 0, 0, 1 }; } float det(const Matrix4& m) noexcept { const auto xy = m.x.z * m.y.w - m.x.w * m.y.z; const auto xz = m.x.z * m.z.w - m.x.w * m.z.z; const auto xt = m.x.z * m.t.w - m.x.w * m.t.z; const auto yz = m.y.z * m.z.w - m.y.w * m.z.z; const auto yt = m.y.z * m.t.w - m.y.w * m.t.z; const auto zt = m.z.z * m.t.w - m.z.w * m.t.z; const auto yzt = m.y.y * zt - m.z.y * yt + m.t.y * yz; const auto xzt = m.x.y * zt - m.z.y * xt + m.t.y * xz; const auto xyt = m.x.y * yt - m.y.y * xt + m.t.y * xy; const auto xyz = m.x.y * yz - m.y.y * xz + m.z.y * xy; return m.x.x * yzt - m.y.x * xzt + m.z.x * xyt - m.t.x * xyz; } Matrix4 inverse(const Matrix4& m) noexcept { // Z and W rows. auto det01 = m.x.z * m.y.w - m.x.w * m.y.z; auto det02 = m.x.z * m.z.w - m.x.w * m.z.z; auto det03 = m.x.z * m.t.w - m.x.w * m.t.z; auto det12 = m.y.z * m.z.w - m.y.w * m.z.z; auto det13 = m.y.z * m.t.w - m.y.w * m.t.z; auto det23 = m.z.z * m.t.w - m.z.w * m.t.z; // Y, Z and W rows. const auto det123 = m.y.y * det23 - m.z.y * det13 + m.t.y * det12; const auto det023 = m.x.y * det23 - m.z.y * det03 + m.t.y * det02; const auto det013 = m.x.y * det13 - m.y.y * det03 + m.t.y * det01; const auto det012 = m.x.y * det12 - m.y.y * det02 + m.z.y * det01; const auto d = 1 / (m.x.x * det123 - m.y.x * det023 + m.z.x * det013 - m.t.x * det012); const auto xx = d * det123; const auto xy = d * -det023; const auto xz = d * det013; const auto xw = d * -det012; const auto yx = d * -(m.y.x * det23 - m.z.x * det13 + m.t.x * det12); const auto yy = d * (m.x.x * det23 - m.z.x * det03 + m.t.x * det02); const auto yz = d * -(m.x.x * det13 - m.y.x * det03 + m.t.x * det01); const auto yw = d * (m.x.x * det12 - m.y.x * det02 + m.z.x * det01); // Y and W rows. det01 = m.x.y * m.y.w - m.y.y * m.x.w; det02 = m.x.y * m.z.w - m.z.y * m.x.w; det03 = m.x.y * m.t.w - m.t.y * m.x.w; det12 = m.y.y * m.z.w - m.z.y * m.y.w; det13 = m.y.y * m.t.w - m.t.y * m.y.w; det23 = m.z.y * m.t.w - m.t.y * m.z.w; const auto zx = d * (m.y.x * det23 - m.z.x * det13 + m.t.x * det12); const auto zy = d * -(m.x.x * det23 - m.z.x * det03 + m.t.x * det02); const auto zz = d * (m.x.x * det13 - m.y.x * det03 + m.t.x * det01); const auto zw = d * -(m.x.x * det12 - m.y.x * det02 + m.z.x * det01); // Y and Z rows. det01 = m.y.z * m.x.y - m.x.z * m.y.y; det02 = m.z.z * m.x.y - m.x.z * m.z.y; det03 = m.t.z * m.x.y - m.x.z * m.t.y; det12 = m.z.z * m.y.y - m.y.z * m.z.y; det13 = m.t.z * m.y.y - m.y.z * m.t.y; det23 = m.t.z * m.z.y - m.z.z * m.t.y; const auto tx = d * -(m.y.x * det23 - m.z.x * det13 + m.t.x * det12); const auto ty = d * (m.x.x * det23 - m.z.x * det03 + m.t.x * det02); const auto tz = d * -(m.x.x * det13 - m.y.x * det03 + m.t.x * det01); const auto tw = d * (m.x.x * det12 - m.y.x * det02 + m.z.x * det01); return { xx, yx, zx, tx, xy, yy, zy, ty, xz, yz, zz, tz, xw, yw, zw, tw }; } }
34.366864
112
0.532369
blagodarin
f0ef45f838db55c49ad28fb6f393909025c8e1d6
7,054
hpp
C++
packages/Search/src/details/DTK_DetailsTreeTraversal.hpp
flyingcat007/DTK_Test
ef8e0e791b76f138045354715a8ce23436ea0edf
[ "BSD-3-Clause" ]
null
null
null
packages/Search/src/details/DTK_DetailsTreeTraversal.hpp
flyingcat007/DTK_Test
ef8e0e791b76f138045354715a8ce23436ea0edf
[ "BSD-3-Clause" ]
null
null
null
packages/Search/src/details/DTK_DetailsTreeTraversal.hpp
flyingcat007/DTK_Test
ef8e0e791b76f138045354715a8ce23436ea0edf
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** * Copyright (c) 2012-2017 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * ****************************************************************************/ #ifndef DTK_DETAILS_TREE_TRAVERSAL_HPP #define DTK_DETAILS_TREE_TRAVERSAL_HPP #include <DTK_DBC.hpp> #include <DTK_DetailsAlgorithms.hpp> #include <DTK_DetailsNode.hpp> #include <DTK_DetailsPredicate.hpp> #include <DTK_DetailsPriorityQueue.hpp> #include <DTK_DetailsStack.hpp> namespace DataTransferKit { template <typename DeviceType> class BVH; namespace Details { template <typename DeviceType> struct TreeTraversal { public: using ExecutionSpace = typename DeviceType::execution_space; template <typename Predicate, typename Insert> KOKKOS_INLINE_FUNCTION static int query( BVH<DeviceType> const bvh, Predicate const &pred, Insert const &insert ) { using Tag = typename Predicate::Tag; return queryDispatch( bvh, pred, insert, Tag{} ); } /** * Return true if the node is a leaf. */ KOKKOS_INLINE_FUNCTION static bool isLeaf( BVH<DeviceType> bvh, Node const *node ) { // COMMENT: could also check that pointer is in the range [leaf_nodes, // leaf_nodes+n] (void)bvh; return ( node->children.first == nullptr ) && ( node->children.second == nullptr ); } /** * Return the index of the leaf node. */ KOKKOS_INLINE_FUNCTION static int getIndex( BVH<DeviceType> bvh, Node const *leaf ) { return bvh._indices[leaf - bvh._leaf_nodes.data()]; } /** * Return the root node of the BVH. */ KOKKOS_INLINE_FUNCTION static Node const *getRoot( BVH<DeviceType> bvh ) { if ( bvh.empty() ) return nullptr; return ( bvh.size() > 1 ? bvh._internal_nodes : bvh._leaf_nodes ) .data(); } }; // There are two (related) families of search: one using a spatial predicate and // one using nearest neighbours query (see boost::geometry::queries // documentation). template <typename DeviceType, typename Predicate, typename Insert> KOKKOS_FUNCTION int spatial_query( BVH<DeviceType> const bvh, Predicate const &predicate, Insert const &insert ) { if ( bvh.empty() ) return 0; if ( bvh.size() == 1 ) { Node const *leaf = TreeTraversal<DeviceType>::getRoot( bvh ); if ( predicate( leaf ) ) { int const leaf_index = TreeTraversal<DeviceType>::getIndex( bvh, leaf ); insert( leaf_index ); return 1; } else return 0; } Stack<Node const *> stack; Node const *root = TreeTraversal<DeviceType>::getRoot( bvh ); stack.push( root ); int count = 0; while ( !stack.empty() ) { Node const *node = stack.top(); stack.pop(); if ( TreeTraversal<DeviceType>::isLeaf( bvh, node ) ) { insert( TreeTraversal<DeviceType>::getIndex( bvh, node ) ); count++; } else { for ( Node const *child : {node->children.first, node->children.second} ) { if ( predicate( child ) ) { stack.push( child ); } } } } return count; } // query k nearest neighbours template <typename DeviceType, typename Insert> KOKKOS_FUNCTION int nearestQuery( BVH<DeviceType> const bvh, Point const &query_point, int k, Insert const &insert ) { if ( bvh.empty() || k < 1 ) return 0; if ( bvh.size() == 1 ) { Node const *leaf = TreeTraversal<DeviceType>::getRoot( bvh ); int const leaf_index = TreeTraversal<DeviceType>::getIndex( bvh, leaf ); double const leaf_distance = distance( query_point, leaf->bounding_box ); insert( leaf_index, leaf_distance ); return 1; } using PairNodePtrDistance = Kokkos::pair<Node const *, double>; struct CompareDistance { KOKKOS_INLINE_FUNCTION bool operator()( PairNodePtrDistance const &lhs, PairNodePtrDistance const &rhs ) { // reverse order (larger distance means lower priority) return lhs.second > rhs.second; } }; PriorityQueue<PairNodePtrDistance, CompareDistance> queue; // priority does not matter for the root since the node will be // processed directly and removed from the priority queue we don't even // bother computing the distance to it. Node const *root = TreeTraversal<DeviceType>::getRoot( bvh ); queue.push( root, 0. ); int count = 0; while ( !queue.empty() && count < k ) { // get the node that is on top of the priority list (i.e. is the // closest to the query point) Node const *node = queue.top().first; double const node_distance = queue.top().second; // NOTE: it would be nice to be able to do something like // tie( node, node_distance = queue.top(); queue.pop(); if ( TreeTraversal<DeviceType>::isLeaf( bvh, node ) ) { insert( TreeTraversal<DeviceType>::getIndex( bvh, node ), node_distance ); count++; } else { // insert children of the node in the priority list for ( Node const *child : {node->children.first, node->children.second} ) { double child_distance = distance( query_point, child->bounding_box ); queue.push( child, child_distance ); } } } return count; } template <typename DeviceType, typename Predicate, typename Insert> KOKKOS_INLINE_FUNCTION int queryDispatch( BVH<DeviceType> const bvh, Predicate const &pred, Insert const &insert, SpatialPredicateTag ) { return spatial_query( bvh, pred, insert ); } template <typename DeviceType, typename Predicate, typename Insert> KOKKOS_INLINE_FUNCTION int queryDispatch( BVH<DeviceType> const bvh, Predicate const &pred, Insert const &insert, NearestPredicateTag ) { return nearestQuery( bvh, pred._query_point, pred._k, insert ); } } // end namespace Details } // end namespace DataTransferKit #endif
31.632287
80
0.561242
flyingcat007
f0f058c70d3c3c2b34e72acbf78be9b844e025bb
788
cpp
C++
client/include/game/CColDisk.cpp
MayconFelipeA/sampvoiceatt
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
[ "MIT" ]
368
2015-01-01T21:42:00.000Z
2022-03-29T06:22:22.000Z
client/include/game/CColDisk.cpp
MayconFelipeA/sampvoiceatt
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
[ "MIT" ]
92
2019-01-23T23:02:31.000Z
2022-03-23T19:59:40.000Z
client/include/game/CColDisk.cpp
MayconFelipeA/sampvoiceatt
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
[ "MIT" ]
179
2015-02-03T23:41:17.000Z
2022-03-26T08:27:16.000Z
/* Plugin-SDK (Grand Theft Auto San Andreas) source file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #include "CColDisk.h" // Converted from thiscall void CColDisk::Set(float startRadius,CVector const&start,CVector const&end,float endRadius,uchar material,uchar pieceType,uchar lighting) 0x40FD50 void CColDisk::Set(float startRadius, CVector const& start, CVector const& end, float endRadius, unsigned char material, unsigned char pieceType, unsigned char lighting) { plugin::CallMethod<0x40FD50, CColDisk *, float, CVector const&, CVector const&, float, unsigned char, unsigned char, unsigned char>(this, startRadius, start, end, endRadius, material, pieceType, lighting); }
65.666667
209
0.769036
MayconFelipeA
f0f3e273807c03960248ad61cc8e678f24cf06dc
78
hpp
C++
include/Pulsejet/Pulsejet.hpp
logicomacorp/pulsejet
ec73d19ccb71ff05b2122e258fe4b7b16e55fb53
[ "MIT" ]
30
2021-06-07T20:25:48.000Z
2022-03-30T00:52:38.000Z
include/Pulsejet/Pulsejet.hpp
going-digital/pulsejet
8452a0311645867d64c038cef7fdf751b26717ee
[ "MIT" ]
null
null
null
include/Pulsejet/Pulsejet.hpp
going-digital/pulsejet
8452a0311645867d64c038cef7fdf751b26717ee
[ "MIT" ]
1
2021-09-21T11:17:45.000Z
2021-09-21T11:17:45.000Z
#pragma once #include "Decode.hpp" #include "Encode.hpp" #include "Meta.hpp"
13
21
0.717949
logicomacorp
e7c8958dc2beaffff8a59eb2d4072ef8b2a3bd22
1,114
cpp
C++
silk_engine/src/gfx/buffers/index_buffer.cpp
GeorgeAzma/VulkanEngine
0c2279682f526f428b44eae2a82be6933c74320d
[ "MIT" ]
1
2022-02-11T12:49:49.000Z
2022-02-11T12:49:49.000Z
silk_engine/src/gfx/buffers/index_buffer.cpp
GeorgeAzma/VulkanEngine
0c2279682f526f428b44eae2a82be6933c74320d
[ "MIT" ]
null
null
null
silk_engine/src/gfx/buffers/index_buffer.cpp
GeorgeAzma/VulkanEngine
0c2279682f526f428b44eae2a82be6933c74320d
[ "MIT" ]
null
null
null
#include "index_buffer.h" #include "staging_buffer.h" #include "gfx/graphics.h" #include "gfx/buffers/command_buffer.h" IndexBuffer::IndexBuffer(const void* data, VkDeviceSize count, IndexType index_type, VmaMemoryUsage memory_usage) : Buffer(count * indexTypeSize(index_type), VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, memory_usage), index_type(index_type) { setData(data, count * indexTypeSize(index_type)); } void IndexBuffer::bind(VkDeviceSize offset) { Graphics::getActiveCommandBuffer().bindIndexBuffer(buffer, offset, indexType(index_type)); } VkIndexType IndexBuffer::indexType(IndexType index_type) { switch (index_type) { case IndexType::UINT16: return VK_INDEX_TYPE_UINT16; case IndexType::UINT32: return VK_INDEX_TYPE_UINT32; } SK_ERROR("Unsupported index type specified: {0}.", index_type); return VkIndexType(0); } size_t IndexBuffer::indexTypeSize(IndexType index_type) { switch (index_type) { case IndexType::UINT16: return 2; case IndexType::UINT32: return 4; } SK_ERROR("Unsoppurted index type specified: {0}.", index_type); return 0; }
26.52381
113
0.777379
GeorgeAzma
e7cb1b6abec8324c260fbf8ecc7489fc23aa1f9f
780
cpp
C++
Snipets/08_Strings/CharacterCounting.cpp
Gabroide/Learning-C
63a89b9b6b84e410756e70e346173d475a1802a6
[ "Apache-2.0" ]
null
null
null
Snipets/08_Strings/CharacterCounting.cpp
Gabroide/Learning-C
63a89b9b6b84e410756e70e346173d475a1802a6
[ "Apache-2.0" ]
null
null
null
Snipets/08_Strings/CharacterCounting.cpp
Gabroide/Learning-C
63a89b9b6b84e410756e70e346173d475a1802a6
[ "Apache-2.0" ]
null
null
null
// CharacterCounting.cpp // Programa para contar los caracteres contenidos en un string #include <iostream> #include <stdlib.h> #include <stdio.h> #include <string.h> int main() { char str[100]; int i, j, n, k, o; i=0; j=0; k=0; o=0; puts("Introduce una frase"); gets(str); n=strlen(str); while(str[i]!='\0') { if((str[i]>=65) &&(str[i]<97)) j++; if((str[i]>=97) &&(str[i]<122)) k++; if(str[i]==' ') o++; i++; } std::cout << "El numero total de letras es: " << n << std::endl; std::cout << "El numero de letras mayusculas es: " << j << std::endl; std::cout << "El numero de letras minusculas es: " << k << std::endl; std::cout << "El numero de espacios en blanco es: " << o << std::endl; system("pause"); return 0; }
16.595745
71
0.553846
Gabroide
e7d5a48fc6a783714974803c80fcd00436f6473c
3,002
cpp
C++
source/src/gui/qrsystemtray.cpp
Qters/QrChaos
accc5b9efe5469377a09170ecd92e4674d177f9f
[ "MIT" ]
1
2016-10-21T08:14:26.000Z
2016-10-21T08:14:26.000Z
source/src/gui/qrsystemtray.cpp
Qters/QrChaos
accc5b9efe5469377a09170ecd92e4674d177f9f
[ "MIT" ]
null
null
null
source/src/gui/qrsystemtray.cpp
Qters/QrChaos
accc5b9efe5469377a09170ecd92e4674d177f9f
[ "MIT" ]
null
null
null
#include "gui/qrsystemtray.h" #include <QtCore/qdebug.h> #include <QtCore/qmap.h> #include <QtWidgets/qsystemtrayicon.h> #include <QtWidgets/qaction.h> #include <QtWidgets/qmenu.h> #include <QtWidgets/qapplication.h> #include "db/qrtblsystemtray.h" #include "db/qrtblframeconfig.h" NS_CHAOS_BASE_BEGIN class QrSystemTrayPrivate{ QR_DECLARE_PUBLIC(QrSystemTray) public: static QrSystemTrayPrivate *dInstance(); public: QrSystemTrayPrivate(QWidget* parent); ~QrSystemTrayPrivate(); bool initTray(); QAction *getAction(const QString& key); public: QWidget* parent; QMenu trayMenu; QSystemTrayIcon systemTray; QMap<QString, QAction*> actions; public: static QrSystemTray* qInstance; }; QrSystemTray* QrSystemTrayPrivate::qInstance = nullptr; QrSystemTrayPrivate *QrSystemTrayPrivate::dInstance(){ Q_ASSERT(nullptr != QrSystemTrayPrivate::qInstance); return QrSystemTrayPrivate::qInstance->d_func(); } QrSystemTrayPrivate::QrSystemTrayPrivate(QWidget *parent) : parent(parent) {} QrSystemTrayPrivate::~QrSystemTrayPrivate() {} QAction *QrSystemTrayPrivate::getAction(const QString &key) { Q_ASSERT(actions.contains(key)); return actions[key]; } bool QrSystemTrayPrivate::initTray() { QVector<QrSystemlTrayData> trayDatas; if (! QrTbSystemlTrayHelper::getTrayList(&trayDatas)) { return false; } QMap<QString, QString> systemtrayValues; if (! Qters::QrFrame::QrTblFrameConfigHelper::getKeyValuesByType("systemtray", &systemtrayValues)) { return false; } if ("false" == systemtrayValues["use"]) { qDebug() << "database config deside not use system tray"; return false; } systemTray.setIcon(QIcon(systemtrayValues["icon"])); systemTray.setToolTip(systemtrayValues["tooltip"]); trayMenu.clear(); Q_FOREACH(QrSystemlTrayData data, trayDatas) { auto action = new QAction(data.text, parent); action->setIcon(QIcon(data.icon)); if (! data.visible) { action->setVisible(false); } trayMenu.addAction(action); actions[data.key] = action; if (data.separator) { trayMenu.addSeparator(); } } systemTray.setContextMenu(&trayMenu); systemTray.show(); QObject::connect( qApp, &QApplication::aboutToQuit, [this](){ systemTray.hide(); }); return true; } NS_CHAOS_BASE_END USING_NS_CHAOS_BASE; QrSystemTray::QrSystemTray(QWidget* parent) :d_ptr(new QrSystemTrayPrivate(parent)) { QrSystemTrayPrivate::qInstance = this; d_ptr->initTray(); } bool QrSystemTray::qrconnect(const QString &key, const QObject *receiver, const char *member) { auto action = QrSystemTrayPrivate::dInstance()->getAction(key); if (nullptr == action) { return false; } QObject::connect(action, SIGNAL(triggered(bool)), receiver, member); return true; }
24.606557
104
0.675217
Qters
e7d68cfba12d0c5cc12915b0739af0e174083928
6,140
cpp
C++
PG/physics/PhysicsWorld.cpp
mcdreamer/PG
a047615d9eae7f2229a203a262f239106cf7f39c
[ "MIT" ]
2
2018-01-14T17:47:22.000Z
2021-11-15T10:34:24.000Z
PG/physics/PhysicsWorld.cpp
mcdreamer/PG
a047615d9eae7f2229a203a262f239106cf7f39c
[ "MIT" ]
23
2017-07-31T19:43:00.000Z
2018-11-11T18:51:28.000Z
PG/physics/PhysicsWorld.cpp
mcdreamer/PG
a047615d9eae7f2229a203a262f239106cf7f39c
[ "MIT" ]
null
null
null
#include "PG/physics/PhysicsWorld.h" #include "PG/physics/PhysicsBody.h" #include "PG/app/GameConstants.h" #include "PG/entities/TilePositionCalculator.h" #include "PG/core/RectUtils.h" #include "PG/core/PointUtils.h" #include "PG/core/SizeUtils.h" #include "PG/core/MathsUtils.h" #include <array> namespace PG { namespace { const size_t kNumCoordsToTest = 9; using TileCoordsToTest = std::array<TileCoord, kNumCoordsToTest>; //-------------------------------------------------------- TileCoordsToTest getCollisionTestCoords(const TileCoord& bodyTileCoord) { TileCoordsToTest coordsToTest; for (auto& coordToTest : coordsToTest) { coordToTest = bodyTileCoord; } auto coordToTestIt = coordsToTest.begin(); // Aligned points ++coordToTestIt; coordToTestIt->y -= 1; ++coordToTestIt; coordToTestIt->y += 1; ++coordToTestIt; coordToTestIt->x -= 1; ++coordToTestIt; coordToTestIt->x += 1; // Diagonal points ++coordToTestIt; coordToTestIt->x -= 1; coordToTestIt->y += 1; ++coordToTestIt; coordToTestIt->x += 1; coordToTestIt->y += 1; ++coordToTestIt; coordToTestIt->x -= 1; coordToTestIt->y -= 1; ++coordToTestIt; coordToTestIt->x += 1; coordToTestIt->y -= 1; return coordsToTest; } // Don't allow passing through tiles // Better detection of whether collision is above/below or left/right? //-------------------------------------------------------- void findIntersectionAndResolveForBody(PhysicsBody& body, const Rect& geometryRect) { const Rect desiredRect(body.desiredPosition, body.bounds.size); const auto intersection = RectUtils::getIntersection(desiredRect, geometryRect); if (!RectUtils::isEmpty(intersection)) { Point removeIntersectionPt; Point adjustedVelocity; if (intersection.size.height < intersection.size.width) { const bool collisionBelow = (desiredRect.origin.y <= geometryRect.origin.y); if (collisionBelow) { body.hasHitGround(); } const int dir = collisionBelow ? -1 : 1; removeIntersectionPt = Point(0, dir * intersection.size.height); adjustedVelocity = Point(body.velocity.x, 0); } else { const int dir = (desiredRect.origin.x < geometryRect.origin.x) ? -1 : 1; removeIntersectionPt = Point(dir * intersection.size.width, 0); adjustedVelocity = Point(0, body.velocity.y); } body.velocity = adjustedVelocity; body.desiredPosition = PointUtils::addPoints(body.desiredPosition, removeIntersectionPt); } } //-------------------------------------------------------- void resolveCollisionAtCoord(const TileCoord& coordToTest, const DataGrid<bool>& levelGeometry, PhysicsBody& body) { if (coordToTest.x < 0 || coordToTest.x >= levelGeometry.getWidth() || coordToTest.y < 0 || coordToTest.y >= levelGeometry.getHeight() || !levelGeometry.at(coordToTest.x, coordToTest.y)) { return; } TilePositionCalculator tilePosCalc; const Rect tileRect(tilePosCalc.calculatePoint(coordToTest), Size(GameConstants::tileSize(), GameConstants::tileSize())); findIntersectionAndResolveForBody(body, tileRect); } //-------------------------------------------------------- void applyForcesToBody(PhysicsBody& body, const PhysicsWorldParams& params, float dt) { const auto gravityStep = SizeUtils::scaleSize(params.gravity, dt); const auto forwardStep = PointUtils::scalePoint(params.forward, dt); // Gravity and X friction followed by movement if (!body.isFreeMoving) { body.velocity = PointUtils::addToPoint(body.velocity, gravityStep); body.velocity = Point(body.velocity.x * params.friction, body.velocity.y); if (body.jumpToConsume && body.onGround) { body.velocity = PointUtils::addPoints(body.velocity, params.jumpForce); body.jumpToConsume = false; body.onGround = false; } } else { body.velocity = Point(body.velocity.x * params.friction, body.velocity.y * params.friction); if (body.movingUp) { body.velocity = PointUtils::subtractPoints(body.velocity, PointUtils::swapValues(forwardStep)); } if (body.movingDown) { body.velocity = PointUtils::addPoints(body.velocity, PointUtils::swapValues(forwardStep)); } } // Horizontal movement always the same if (body.movingRight) { body.velocity = PointUtils::addPoints(body.velocity, forwardStep); } if (body.movingLeft) { body.velocity = PointUtils::subtractPoints(body.velocity, forwardStep); } // Clamp velocity auto clampedVelX = MathsUtils::clamp(body.velocity.x, params.minMovement.x, params.maxMovement.x); auto clampedVelY = MathsUtils::clamp(body.velocity.y, params.minMovement.y, params.maxMovement.y); body.velocity = Point(clampedVelX, clampedVelY); // Apply velocity auto velocityStep = PointUtils::scalePoint(body.velocity, dt); body.desiredPosition = PointUtils::addPoints(body.bounds.origin, velocityStep); } } //-------------------------------------------------------- void PhysicsWorld::applyPhysicsForBody(PhysicsBody& body, const DataGrid<bool>& levelGeometry, float dt) const { applyForcesToBody(body, m_Params, dt); TilePositionCalculator tilePosCalc; const auto bodyTileCoord = tilePosCalc.calculateTileCoord(body.desiredPosition); // Collision detection const auto coordsToTest = getCollisionTestCoords(bodyTileCoord); for (size_t i = 0; i < coordsToTest.size(); ++i) { resolveCollisionAtCoord(coordsToTest[i], levelGeometry, body); } // Apply updated desired position body.setPosition(body.desiredPosition); } //-------------------------------------------------------- void PhysicsWorld::findCollisionsWithBody(const PhysicsBody& body, const std::vector<PhysicsBody>& bodiesToCheck, PhysicsWorldCallback& callback) const { for (size_t nthBody = 0; nthBody < bodiesToCheck.size(); ++nthBody) { if (!RectUtils::isEmpty(RectUtils::getIntersection(body.bounds, bodiesToCheck[nthBody].bounds))) { callback.bodiesDidCollide(body, bodiesToCheck[nthBody], (int)nthBody); } } } }
29.238095
123
0.669055
mcdreamer
e7d6cb36c09282359e3ab5b7cc06ba1989389fd0
1,269
cxx
C++
src/sqlite/connection.cxx
slurps-mad-rips/apex
8d88e6167e460a74e2c42a4d11d7f8e70adb5102
[ "Apache-2.0" ]
4
2020-12-14T18:07:28.000Z
2021-04-21T18:10:26.000Z
src/sqlite/connection.cxx
slurps-mad-rips/apex
8d88e6167e460a74e2c42a4d11d7f8e70adb5102
[ "Apache-2.0" ]
11
2020-07-21T03:27:10.000Z
2021-03-22T20:24:44.000Z
src/sqlite/connection.cxx
slurps-mad-rips/apex
8d88e6167e460a74e2c42a4d11d7f8e70adb5102
[ "Apache-2.0" ]
3
2020-12-14T17:40:07.000Z
2022-03-18T15:43:10.000Z
#include <apex/sqlite/connection.hpp> #include <apex/sqlite/memory.hpp> #include <apex/sqlite/table.hpp> #include <apex/sqlite/error.hpp> #include <apex/core/memory.hpp> #include <apex/memory/out.hpp> #include <sqlite3.h> namespace apex::sqlite { void default_delete<sqlite3>::operator () (sqlite3* ptr) noexcept { sqlite3_close_v2(ptr); } //connection::connection (::std::filesystem::path const& path) noexcept(false) : // resource_type { } //{ // sqlite3_open_v2(path.c_str(), out_ptr(static_cast<resource_type&>(*this)), SQLITE_OPEN_READONLY, nullptr); // throw ::std::runtime_error("Not yet implemented"); //} void plugin (connection& conn, std::string_view name, std::shared_ptr<table> item) noexcept(false) { auto destructor = [] (void* ptr) noexcept { auto pointer = static_cast<std::shared_ptr<table>*>(ptr); apex::destroy_at(pointer); deallocate(pointer); }; auto db = conn.get(); auto module = item->module(); auto aux = ::new (allocate(sizeof(item))) std::shared_ptr<table>(item); if (not aux) { throw std::system_error(error::not_enough_memory); } auto result = sqlite3_create_module_v2(db, name.data(), module, aux, destructor); if (result) { throw std::system_error(error(result)); } } } /* namespace apex::sqlite */
34.297297
110
0.704492
slurps-mad-rips
e7dab0aec55c610adbe8dc2f3a51df4ee13a9827
17,150
cpp
C++
test/tf/t_tf_tree.cpp
Robotics-BUT/Robotic-Template-Library
a93b31f5a8f5b12fbbd5fa134a714ea0f82c1578
[ "MIT" ]
8
2020-04-22T09:46:14.000Z
2022-03-17T00:09:38.000Z
test/tf/t_tf_tree.cpp
Robotics-BUT/Robotic-Template-Library
a93b31f5a8f5b12fbbd5fa134a714ea0f82c1578
[ "MIT" ]
1
2020-08-11T07:24:14.000Z
2020-10-05T12:47:05.000Z
test/tf/t_tf_tree.cpp
Robotics-BUT/Robotic-Template-Library
a93b31f5a8f5b12fbbd5fa134a714ea0f82c1578
[ "MIT" ]
null
null
null
// This file is part of the Robotic Template Library (RTL), a C++ // template library for usage in robotic research and applications // under the MIT licence: // // Copyright 2020 Brno University of Technology // // 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. // // Contact person: Ales Jelinek <Ales.Jelinek@ceitec.vutbr.cz> #include <gtest/gtest.h> #include <rtl/Transformation.h> #include <rtl/Test.h> #include <vector> #include <typeinfo> #include <iostream> #include <chrono> #include "tf_test/key_generator.h" #include "tf_test/tf_comparison.h" #include "rtl/io/StdLib.h" TEST(t_tf_tree, key_generator) { rtl::test::Types<TestKeyGenerator, TYPES> keyGenTest(static_cast<size_t>(10)); } ////////////////////////// /// Tests ////////////////////////// template<int N, typename dtype, typename T> struct TestInit { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); tree.clear(); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); } }; TEST(t_tf_tree, init) { [[maybe_unused]]auto keyGenTest = rtl::test::RangeTypesTypes<TestInit, 2, 4, float, double>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct TestConstructors { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree_copy(origin); ASSERT_EQ(tree_copy.empty(), false); ASSERT_EQ(tree_copy.size(), 1); auto tree_copy_root_address = &tree_copy.root(); ASSERT_TRUE(&tree.root() != tree_copy_root_address); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree_move(rtl::TfTree<T, rtl::RigidTfND<N, dtype>>{origin}); ASSERT_EQ(tree_move.empty(), false); ASSERT_EQ(tree_move.size(), 1); } }; TEST(t_tf_tree, constructors) { [[maybe_unused]]auto constructorTests = rtl::test::RangeTypesTypes<TestConstructors, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> void fill_tree_insert(rtl::TfTree<T, rtl::RigidTfND<N, dtype>>& tree, std::vector<T> keys) { auto generator = rtl::test::Random::uniformCallable<double>(-1.0, 1.0); for (size_t i = 1 ; i < keys.size() ; i++) { auto tf = rtl::RigidTfND<N, dtype>::random(generator); tree.insert(keys.at(i), tf, keys.at(i-1)); auto tf2 = tree.at(keys.at(i)).tf(); bool res = CompareTfsEqual<N, dtype>(tf, tf2); ASSERT_EQ(res, true); } } template<int N, typename dtype, typename T> struct TestInsert { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); fill_tree_insert(tree, keys); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), keys.size()); } }; TEST(t_tf_tree, insert) { [[maybe_unused]]auto insertTest = rtl::test::RangeTypesTypes<TestInsert, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct TestClear { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); fill_tree_insert(tree, keys); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), keys.size()); tree.clear(); // root should stay ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); fill_tree_insert(tree, keys); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), keys.size()); } }; TEST(t_tf_tree, clear) { [[maybe_unused]]auto clearTest = rtl::test::RangeTypesTypes<TestClear, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct TestContains { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); for (size_t i = 1 ; i < keys.size() ; i++) { ASSERT_EQ(tree.contains(keys.at(i)), false); } fill_tree_insert(tree, keys); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), keys.size()); for (const auto& key : keys) { ASSERT_EQ(tree.contains(key), true); } } }; TEST(t_tf_tree, contains) { [[maybe_unused]]auto containsTest = rtl::test::RangeTypesTypes<TestContains, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct TestErase { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); for (typename std::vector<T>::iterator it = keys.end() - 1; it > keys.begin(); it--) { tree.erase(*it); } ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); fill_tree_insert(tree, keys); { size_t i = 0; for (typename std::vector<T>::iterator it = keys.end() - 1; it > keys.begin(); it--) { ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), keys.size() - i); tree.erase(*it); for (typename std::vector<T>::iterator it2 = (keys.end() - 1); it2 > keys.begin(); it2--) { if (it2 >= it){ ASSERT_EQ(tree.contains(*it2), false); } else { ASSERT_EQ(tree.contains(*it2), true); } } i++; } } } }; TEST(t_tf_tree, erase) { [[maybe_unused]]auto eraseTest = rtl::test::RangeTypesTypes<TestErase, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct TestErase2 { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); fill_tree_insert(tree, keys); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), keys.size()); tree.erase(keys.at(1)); for (size_t i = 0 ; i < keys.size() ; i++) { if (i > 0) { ASSERT_EQ(tree.contains(keys.at(i)), false); } else { ASSERT_EQ(tree.contains(keys.at(i)), true); } } } }; TEST(t_tf_tree, erase_2) { [[maybe_unused]]auto erase2Test = rtl::test::RangeTypesTypes<TestErase2, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct RootTest { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); ASSERT_EQ(tree.root().key(), origin); ASSERT_EQ(tree.root().children().size(), 0); ASSERT_EQ(tree.root().depth(), 0); ASSERT_EQ(tree.root().key() , tree.root().parent()->key()); } }; TEST(t_tf_tree, root) { [[maybe_unused]]auto rootTest = rtl::test::RangeTypesTypes<RootTest, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct AtTest { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); fill_tree_insert(tree, keys); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), keys.size()); for (const auto& key : keys) { ASSERT_EQ(tree.at(key).key(), key); ASSERT_EQ(tree[key].key(), key); ASSERT_EQ( &tree[key], &tree.at(key)); } } }; TEST(t_tf_tree, at) { [[maybe_unused]]auto atTest = rtl::test::RangeTypesTypes<AtTest, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct TreeStructureTest { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); fill_tree_insert(tree, keys); for (size_t i = 0 ; i < keys.size() ; i++) { auto& node1 = tree.at(keys.at(i)); auto& node2 = tree[keys.at(i)]; ASSERT_EQ( &node1, &node2); ASSERT_EQ( node1.depth(), i); if(i > 0) { const auto& parent = tree[keys.at(i-1)]; auto node_parent = node1.parent(); ASSERT_EQ( node_parent, &parent); } } } }; TEST(t_tf_tree, tree_structure) { [[maybe_unused]]auto treeStructureTest = rtl::test::RangeTypesTypes<TreeStructureTest, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct TestTfFromTo { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); auto generator = rtl::test::Random::uniformCallable<double>(-1.0, 1.0); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); auto tf1 = rtl::RigidTfND<N, dtype>::random(generator); auto tf2 = rtl::RigidTfND<N, dtype>::random(generator); auto tf3 = rtl::RigidTfND<N, dtype>::random(generator); auto tf4 = rtl::RigidTfND<N, dtype>::random(generator); auto tf5 = rtl::RigidTfND<N, dtype>::random(generator); auto tf6 = rtl::RigidTfND<N, dtype>::random(generator); auto tf7 = rtl::RigidTfND<N, dtype>::random(generator); auto tf8 = rtl::RigidTfND<N, dtype>::random(generator); auto tf9 = rtl::RigidTfND<N, dtype>::random(generator); /* * * / tf2 - tf5 - tf9 * / \ tf6 * origin * \ * \ tf1 - tf3 - tf7 * \ \ tf8 * \ tf4 */ tree.insert(key_1, tf1, origin); tree.insert(key_2, tf2, origin); tree.insert(key_3, tf3, key_1); tree.insert(key_4, tf4, key_1); tree.insert(key_5, tf5, key_2); tree.insert(key_6, tf6, key_2); tree.insert(key_7, tf7, key_3); tree.insert(key_8, tf8, key_3); tree.insert(key_9, tf9, key_5); auto identity = rtl::RigidTfND<N, dtype>::identity(); auto tfChain = tree.tf(key_8, key_9); std::cout << tf1 << std::endl; auto cumulated = tfChain(identity); auto cumulated2 = tf9(tf5(tf2(tf1.inverted()(tf3.inverted()(tf8.inverted()))))); ASSERT_EQ(CompareTfsEqual(cumulated, cumulated2), true); } }; TEST(t_tf_tree, tree_tf_from_to) { [[maybe_unused]]auto tfFromToTest = rtl::test::RangeTypesTypes<TestTfFromTo, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename T> struct APITest { static void testFunction() { auto keyGen = KeysGenerator<T>{keyN}; auto keys = keyGen.generateKyes(); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree(origin); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree_copy(tree); rtl::TfTree<T, rtl::RigidTfND<N, dtype>> tree_move(rtl::TfTree<T, rtl::RigidTfND<N, dtype>>{origin}); ASSERT_EQ(tree.empty(), false); ASSERT_EQ(tree.size(), 1); ASSERT_EQ(tree_copy.empty(), false); ASSERT_EQ(tree_copy.size(), 1); ASSERT_EQ(tree_move.empty(), false); ASSERT_EQ(tree_move.size(), 1); tree_copy.clear(); tree_move.clear(); ASSERT_EQ(tree_copy.empty(), false); ASSERT_EQ(tree_copy.size(), 1); ASSERT_EQ(tree_move.empty(), false); ASSERT_EQ(tree_move.size(), 1); tree_copy = tree; tree_move = rtl::TfTree<T, rtl::RigidTfND<N, dtype>>(origin); ASSERT_EQ(tree.contains(key_1), false); tree.insert(key_1, rtl::RigidTfND<N, dtype>::identity(), origin); ASSERT_EQ(tree.contains(key_1), true); tree.erase(key_1); ASSERT_EQ(tree.contains(key_1), false); ASSERT_EQ(tree.root().key(), origin); auto new_tf = rtl::RigidTfND<N, dtype>::identity(); tree[origin].tf() = new_tf; tree.at(origin).tf() = new_tf; auto rootNode_1 = tree[origin]; auto rootNode_2 = tree[origin]; auto rootNode_3 = tree.at(origin); auto rootNode_4 = tree.at(origin); tree.clear(); ASSERT_EQ(tree.root().key(), origin); } }; TEST(t_tf_tree, api_test) { [[maybe_unused]]auto apiTest = rtl::test::RangeTypesTypes<APITest, RANGE_AND_DTYPES>::with<TYPES>{}; } template<int N, typename dtype, typename K> struct GeneralTFTest { static void testFunction() { auto keyGen = KeysGenerator<K>{keyN}; auto keys = keyGen.generateKyes(); auto generator = rtl::test::Random::uniformCallable<double>(-1.0, 1.0); using General3DTf = rtl::GeneralTf<rtl::RigidTfND<3,double>, rtl::TranslationND<3, double>, rtl::RotationND<3, double>>; rtl::TfTree<std::string, General3DTf> generalTree{origin}; auto rigid = rtl::RigidTfND<3, double>::random(generator); auto rot = rtl::RotationND<3, double>::random(generator); auto trans = rtl::TranslationND<3, double>::random(generator); /* origin / \ trans rot / \ 1 2 / rigidTf / 3 */ generalTree.insert(key_1, trans, origin); generalTree.insert(key_2, rot, origin); generalTree.insert(key_3, rigid, key_1); auto chain_3_2 = generalTree.tf(key_3, key_2); auto tf_3_2 = rot(trans.inverted()(rigid.inverted())); ASSERT_EQ(CompareTfsEqual((rtl::RigidTfND<3, double>) chain_3_2.squash(), tf_3_2 ), true); } }; TEST(t_tf_tree, generalTfTest) { [[maybe_unused]]auto generalTfTests = rtl::test::RangeTypesTypes<GeneralTFTest, RANGE_AND_DTYPES>::with<std::string>{}; } TEST(t_tf_tree, str_cmp_vs_stc_hash) { auto keyGen = KeysGenerator<std::string>{2}; auto keys = keyGen.generateKyes(); auto a = origin; auto b = key_1; auto t1 = std::chrono::high_resolution_clock::now(); for(size_t i = 0 ; i < 10000000 ; i++) { if( a == b ) {} } auto t2 = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count(); std::cout << "Str cmp duration: " << duration << " ms" << std::endl; auto hasher = std::hash<std::string>{}; t1 = std::chrono::high_resolution_clock::now(); for(size_t i = 0 ; i < 10000000 ; i++) { auto ha = hasher(a); auto hb = hasher(b); if( ha == hb ) {} } t2 = std::chrono::high_resolution_clock::now(); duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count(); std::cout << "Str hash and int cmp duration: " << duration << " ms" << std::endl;; } int main(int argc, char **argv){ testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
31.181818
128
0.593703
Robotics-BUT
e7dd038a07f541672ecdbee54894256ccb613089
2,899
cpp
C++
387/387.cpp
bsamseth/project-euler
60d70b117960f37411935bc18eab5bb2fca220e2
[ "MIT" ]
null
null
null
387/387.cpp
bsamseth/project-euler
60d70b117960f37411935bc18eab5bb2fca220e2
[ "MIT" ]
null
null
null
387/387.cpp
bsamseth/project-euler
60d70b117960f37411935bc18eab5bb2fca220e2
[ "MIT" ]
null
null
null
/* A Harshad or Niven number is a number that is divisible by the sum of its digits. 201 is a Harshad number because it is divisible by 3 (the sum of its digits.) When we truncate the last digit from 201, we get 20, which is a Harshad number. When we truncate the last digit from 20, we get 2, which is also a Harshad number. Let's call a Harshad number that, while recursively truncating the last digit, always results in a Harshad number a right truncatable Harshad number. Also: 201/3=67 which is prime. Let's call a Harshad number that, when divided by the sum of its digits, results in a prime a strong Harshad number. Now take the number 2011 which is prime. When we truncate the last digit from it we get 201, a strong Harshad number that is also right truncatable. Let's call such primes strong, right truncatable Harshad primes. You are given that the sum of the strong, right truncatable Harshad primes less than 10000 is 90619. Find the sum of the strong, right truncatable Harshad primes less than 1014. Solution comment: Quite fast, <100 ms. Hard to optimize further. Starting with all single digit numbers, which are Harshads, we can add digits that produces new Harshads. If adding a digit does not give a new Harshad, then it is either because we just hit a boring number, or it could be that we hit a prime. If this prime, without its last digit added happens to be a strong Harshad (and also truncatable by design) then the prime is a strong right truncatable Harshad prime. This problem really put the eulertools to the test, showing overflow issues in pow_mod, which is used in the Miller-Rabbin primality test. I don't think this is solvable without that test btw., as the numbers are way to big to test by trial division. Now there should be no overflow issues left, as handling of it is explicitly done when needed. I really don't agree with the 10% difficulty of this one, clearly much harder than many other problems in the 30-40% range. */ #include <iostream> #include "timing.hpp" #include "primes.hpp" using euler::primes::is_prime; using Int = uint64_t; Int sum = 0; void build_strong_Harshad_prime(Int base, Int base_digit_sum, int depth) { if (depth < 1) return; bool base_is_strong = is_prime(base / base_digit_sum); for (Int digit = 0; digit <= 9; ++digit) { Int x = base * 10 + digit; Int digit_sum = base_digit_sum + digit; if (x % digit_sum != 0) { if ( base_is_strong and is_prime(x)) { sum += x; } continue; } build_strong_Harshad_prime(x, digit_sum, depth - 1); } } int main() { euler::Timer timer {}; constexpr Int digits = 14; for (Int base = 1; base <= 9; ++base) { build_strong_Harshad_prime(base, base, digits - 1); } std::cout << "Answer: " << sum << std::endl; timer.stop(); }
34.511905
79
0.709555
bsamseth
e7e04f2e48b35efebb79ea7a8852920c557ecd42
1,921
cpp
C++
Game/src/game/Kamikaze.cpp
franticsoftware/vlad-heavy-strike
a4da4df617e9ccd6ebd9819ad166d892924638ce
[ "MIT" ]
3
2019-10-04T19:44:44.000Z
2021-07-27T15:59:39.000Z
Game/src/game/Kamikaze.cpp
franticsoftware/vlad-heavy-strike
a4da4df617e9ccd6ebd9819ad166d892924638ce
[ "MIT" ]
1
2019-07-20T05:36:31.000Z
2019-07-20T22:22:49.000Z
Game/src/game/Kamikaze.cpp
aminere/vlad-heavy-strike
a4da4df617e9ccd6ebd9819ad166d892924638ce
[ "MIT" ]
null
null
null
/* Amine Rehioui Created: November 05th 2011 */ #include "ShootTest.h" #include "Kamikaze.h" namespace shoot { DEFINE_OBJECT(Kamikaze); DEFINE_OBJECT(KamikazeSettings); //! constructor KamikazeSettings::KamikazeSettings() : m_fDuration(1.5f) { } //! serializes the entity to/from a PropertyStream void KamikazeSettings::Serialize(PropertyStream& stream) { super::Serialize(stream); stream.Serialize(PT_Float, "Duration", &m_fDuration); } //! constructor Kamikaze::Kamikaze() : m_vDirection(Vector3::Create(0.0f, -1.0f, 0.0f)) , m_fTimer(1.5f) { } //! called during the initialization of the entity void Kamikaze::Init() { super::Init(); if(Player* pPlayer = Player::Instance()) { Vector3 vPosition = pPlayer->GetPosition() + GetSpawningPoint(); SetAbsolutePosition(vPosition); } if(KamikazeSettings* pSettings = static_cast<KamikazeSettings*>(m_Settings.Get())) { m_fTimer = pSettings->m_fDuration; } } //! called during the update of the entity void Kamikaze::Update() { super::Update(); if(m_HitPoints < 0) { return; } KamikazeSettings* pSettings = static_cast<KamikazeSettings*>(m_Settings.Get()); if(m_fTimer > 0.0f) { Vector3 vPosition = GetTransformationMatrix().GetTranslation(); Vector3 vPlayerMeshPos = Player::Instance()->GetMeshEntity()->GetTransformationMatrix().GetTranslation(); f32 fInterpolator = pSettings->m_fHomingFactor*g_fDeltaTime; fInterpolator = Math::Clamp(fInterpolator, 0.0f, 1.0f); Vector3 vDirectionToPlayer = (vPlayerMeshPos-vPosition).Normalize(); m_vDirection = ((vDirectionToPlayer-m_vDirection)*fInterpolator + m_vDirection).Normalize(); f32 fAngle = Math::ATan2(-m_vDirection.X, -m_vDirection.Y)*Math::RadToDegFactor; SetRotation(Vector3::Create(0.0f, 0.0f, fAngle)); m_fTimer -= g_fDeltaTime; } Translate(m_vDirection*pSettings->m_fSpeed*g_fDeltaTime); } }
22.337209
108
0.71317
franticsoftware
e7e43276a194c619ccf2813db3479e093ae732c5
7,324
cpp
C++
msfs2020/GaugeConnect/GaugeConnect.cpp
brion/simpanel
5ac172006889cbbf92e2b7f86bab3f709072ff12
[ "MIT" ]
1
2021-07-21T03:19:55.000Z
2021-07-21T03:19:55.000Z
msfs2020/GaugeConnect/GaugeConnect.cpp
brion/simpanel
5ac172006889cbbf92e2b7f86bab3f709072ff12
[ "MIT" ]
null
null
null
msfs2020/GaugeConnect/GaugeConnect.cpp
brion/simpanel
5ac172006889cbbf92e2b7f86bab3f709072ff12
[ "MIT" ]
1
2021-07-21T03:20:01.000Z
2021-07-21T03:20:01.000Z
// GaugeConnect.cpp #include <MSFS/MSFS.h> #include <MSFS/MSFS_WindowsTypes.h> #include <MSFS/Legacy/gauges.h> #include <SimConnect.h> #include <cstring> #include "GaugeConnect.h" struct Expression { bool valid; double value; char* expression; UINT32 expr_len; Expression(void) : valid(false), expression(0), expr_len(0) { }; ~Expression() { remove(); }; void remove(void) { if (valid && expression) delete[] expression; valid = false; expression = 0; }; }; Expression* exprs = 0; size_t num_exprs = 0; enum GaugeInputCommands { GISetExpr, GIEvaluate, }; enum GaugeOutputResults { GIError, GIOk, GIMore, GIComplete, }; struct GaugeInputStruct { UINT32 sequence; UINT16 command; UINT16 param; char data[248]; }; struct GaugeOutputStruct { UINT32 sequence; UINT16 result; UINT16 count; struct { INT16 index; INT16 valid; FLOAT64 value; } values[20]; }; enum Event : DWORD { GaugeInput, GaugeOutput, }; enum SCData : DWORD { GaugeInputData, GaugeOutputData, }; enum SCRequest : DWORD { GaugeInputReq, GaugeInputCD, GaugeOutputReq, GaugeOutputCD, }; enum SCGroup : DWORD { GaugeConnectGroup, }; HANDLE sim = 0; ID gvar; template<typename T> void sim_recv(T* ev, DWORD data, void* ctx) { fprintf(stderr, "[GaugeConnect] unhandled RECV type %ld\n", ev->dwID); fflush(stderr); } #define RECV(tn) case SIMCONNECT_RECV_ID_##tn: sim_recv(static_cast<SIMCONNECT_RECV_##tn*>(recv), data, ctx); return #define RECV_FUNC(tn) template<> void sim_recv(SIMCONNECT_RECV_##tn* ev, DWORD data, void* ctx) RECV_FUNC(EXCEPTION) { fprintf(stderr, "[GaugeConnect] SimConnect exception %ld\n", ev->dwException); fflush(stderr); } RECV_FUNC(OPEN) { printf("[GaugeConnect] Open (%s)\n", ev->szApplicationName);; } RECV_FUNC(CLIENT_DATA) { switch (ev->dwRequestID) { case GaugeInputReq: { const GaugeInputStruct& inp = *reinterpret_cast<GaugeInputStruct*>(&ev->dwData); GaugeOutputStruct out; out.sequence = inp.sequence; out.result = GIError; switch (inp.command) { case GISetExpr: { if (inp.param >= num_exprs) { size_t nn = (inp.param+256) & ~255; Expression* ne = new Expression[nn]; if(ne) { if (exprs) { std::memcpy(ne, exprs, num_exprs*sizeof(Expression)); std::memset(exprs, 0, num_exprs*sizeof(Expression)); delete[] exprs; } exprs = ne; num_exprs = nn; } } if (exprs && inp.param < num_exprs) { Expression& e = exprs[inp.param]; e.remove(); if ((e.expression = new char[strlen(inp.data)+1])) { strcpy(e.expression, inp.data); e.valid = true; out.result = GIOk; // printf("[GaugeConnect] expression %d registered (%s)\n", int(inp.param), inp.data); // fflush(stdout); } else e.valid = false; } } break; case GIEvaluate: { out.result = GIMore; out.count = 0; for (int i = 0; i < inp.param; i++) { UINT16 index = reinterpret_cast<const UINT16*>(inp.data + inp.param * sizeof(FLOAT64))[i]; FLOAT64 value = reinterpret_cast<const FLOAT64*>(inp.data)[i]; if (index < num_exprs && exprs[index].valid) { auto& v = out.values[out.count++]; char* str = 0; int vi; v.index = index; set_named_variable_value(gvar, value); v.valid = execute_calculator_code(exprs[index].expression, &v.value, (SINT32*)0, (PCSTRINGZ * )0); // printf("[GaugeConnect] eval '%s': returns %g ('%s')\n", exprs[index].expression, v.value, str ? str : "<no string>"); // fflush(stdout); } if (out.count == 20) { SimConnect_SetClientData(sim, GaugeOutputCD, GaugeOutputData, 0, 0, sizeof(GaugeOutputStruct), &out); out.count = 0; } } out.result = GIComplete; } break; } SimConnect_SetClientData(sim, GaugeOutputCD, GaugeOutputData, 0, 0, sizeof(GaugeOutputStruct), &out); break; } } } RECV_FUNC(SYSTEM_STATE) { printf("[GaugeConnect] System state: %g '%s'\n", ev->fFloat, ev->szString); fflush(stdout); } RECV_FUNC(QUIT) { } RECV_FUNC(EVENT_FILENAME) { switch (ev->uEventID) { default: fprintf(stderr, "[GaugeConnect] unhandled event %ld (filename)\n", ev->uEventID); fflush(stderr); break; } } RECV_FUNC(EVENT) { switch (ev->uEventID) { default: fprintf(stderr, "[GaugeConnect] unhandled event %ld\n", ev->uEventID); fflush(stderr); break; } } void CALLBACK sim_recv(SIMCONNECT_RECV* recv, DWORD data, void* ctx) { switch (recv->dwID) { RECV(EVENT_FRAME); RECV(EVENT_FILENAME); RECV(EVENT); RECV(EXCEPTION); RECV(CLIENT_DATA); RECV(SYSTEM_STATE); RECV(SIMOBJECT_DATA); RECV(OPEN); RECV(QUIT); default: fprintf(stderr, "[GaugeConnect] unknown recv? (%ld)\n", recv->dwID); fflush(stderr); break; } } extern "C" MSFS_CALLBACK void module_init(void) { gvar = register_named_variable("GCVAL"); if (SimConnect_Open(&sim, "GaugeConnect Module", 0, 0, 0, 0) != S_OK) { fprintf(stderr, "[GaugeConnect] Unable to open SimConnect.\n"); return; } if (SimConnect_MapClientDataNameToID(sim, "org.uberbox.gauge.input", GaugeInputCD) != S_OK) fprintf(stderr, "[GaugeConnect] MapClientDataNameToID(org.uberbox.gauge.input) failed\n"); if(SimConnect_CreateClientData(sim, GaugeInputCD, sizeof(GaugeInputStruct), 0) != S_OK) fprintf(stderr, "[GaugeConnect] CreateClientData(org.uberbox.gauge.input) failed\n"); if (SimConnect_MapClientDataNameToID(sim, "org.uberbox.gauge.output", GaugeOutputCD) != S_OK) fprintf(stderr, "[GaugeConnect] MapClientDataNameToID(org.uberbox.gauge.output) failed\n"); if(SimConnect_CreateClientData(sim, GaugeOutputCD, sizeof(GaugeOutputStruct), SIMCONNECT_CREATE_CLIENT_DATA_FLAG_READ_ONLY) != S_OK) fprintf(stderr, "[GaugeConnect] CreateClientData(org.uberbox.gauge.output) failed\n"); SimConnect_MapClientEventToSimEvent(sim, GaugeInput, "org.uberbox.gauge.input"); SimConnect_MapClientEventToSimEvent(sim, GaugeOutput, "org.uberbox.gauge.output"); SimConnect_AddToClientDataDefinition(sim, GaugeInputData, 0, SIMCONNECT_CLIENTDATATYPE_INT32); SimConnect_AddToClientDataDefinition(sim, GaugeInputData, 4, SIMCONNECT_CLIENTDATATYPE_INT16); SimConnect_AddToClientDataDefinition(sim, GaugeInputData, 6, SIMCONNECT_CLIENTDATATYPE_INT16); SimConnect_AddToClientDataDefinition(sim, GaugeInputData, 8, 248); SimConnect_AddToClientDataDefinition(sim, GaugeOutputData, 0, SIMCONNECT_CLIENTDATATYPE_INT32); SimConnect_AddToClientDataDefinition(sim, GaugeOutputData, 4, SIMCONNECT_CLIENTDATATYPE_INT16); SimConnect_AddToClientDataDefinition(sim, GaugeOutputData, 6, SIMCONNECT_CLIENTDATATYPE_INT16); SimConnect_AddToClientDataDefinition(sim, GaugeOutputData, 8, sizeof(GaugeOutputStruct)-8); SimConnect_CallDispatch(sim, sim_recv, NULL); SimConnect_RequestClientData(sim, GaugeInputCD, GaugeInputReq, GaugeInputData, SIMCONNECT_CLIENT_DATA_PERIOD_ON_SET, SIMCONNECT_CLIENT_DATA_REQUEST_FLAG_DEFAULT); fflush(stderr); printf("[GaugeConnect] Module started!\n"); } extern "C" MSFS_CALLBACK void module_deinit(void) { printf("[GaugeConnect] Module going away. :-(\n"); if (!sim) return; SimConnect_Close(sim); }
28.061303
164
0.685554
brion
e7e8f43ab3bc37214f81a307791266a6fffe32ef
341
cpp
C++
UB/Scripting/EntTeleportAction.cpp
Mr-1337/CAGE
e99082676e83cc069ebf0859fcb34e5b96712725
[ "MIT" ]
null
null
null
UB/Scripting/EntTeleportAction.cpp
Mr-1337/CAGE
e99082676e83cc069ebf0859fcb34e5b96712725
[ "MIT" ]
null
null
null
UB/Scripting/EntTeleportAction.cpp
Mr-1337/CAGE
e99082676e83cc069ebf0859fcb34e5b96712725
[ "MIT" ]
1
2019-06-16T19:00:31.000Z
2019-06-16T19:00:31.000Z
#include "EntTeleportAction.hpp" namespace ub { EntTeleportAction::EntTeleportAction(World* world, glm::vec2 destination) : ScriptAction(world), m_destination(destination) { } void EntTeleportAction::Initialize() { } void EntTeleportAction::Update(float dt) { m_world->MoveEnt(1, m_destination); m_complete = true; } }
15.5
77
0.727273
Mr-1337
e7eddc82f37df2a9dd86f8058ebcf131a0bf6f69
2,142
hpp
C++
kernel/lib/elf.hpp
ethan4984/rock
751b9af1009b622bedf384c1f80970b333c436c3
[ "BSD-2-Clause" ]
207
2020-05-27T21:57:28.000Z
2022-02-26T15:17:27.000Z
kernel/lib/elf.hpp
ethan4984/crepOS
751b9af1009b622bedf384c1f80970b333c436c3
[ "BSD-2-Clause" ]
3
2020-07-26T18:14:05.000Z
2020-12-09T05:32:07.000Z
kernel/lib/elf.hpp
ethan4984/rock
751b9af1009b622bedf384c1f80970b333c436c3
[ "BSD-2-Clause" ]
17
2020-07-05T19:08:48.000Z
2021-10-13T12:30:13.000Z
#ifndef ELF_HPP_ #define ELF_HPP_ #include <mm/vmm.hpp> #include <string.hpp> #include <fs/fd.hpp> namespace elf { constexpr size_t elf_signature = 0x464C457F; constexpr size_t elf64 = 0x2; constexpr size_t ei_class = 0x4; constexpr size_t ei_data = 0x5; constexpr size_t ei_version = 0x6; constexpr size_t ei_osabi = 0x7; constexpr size_t abi_system_v = 0x0; constexpr size_t abi_linux = 0x3; constexpr size_t little_endian = 0x1; constexpr size_t mach_x86_64 = 0x3e; struct aux { uint64_t at_entry; uint64_t at_phdr; uint64_t at_phent; uint64_t at_phnum; }; constexpr size_t at_entry = 10; constexpr size_t at_phdr = 20; constexpr size_t at_phent = 21; constexpr size_t at_phnum = 22; struct elf64_phdr { uint32_t p_type; uint32_t p_flags; uint64_t p_offset; uint64_t p_vaddr; uint64_t p_paddr; uint64_t p_filesz; uint64_t p_memsz; uint64_t p_align; }; constexpr size_t pt_null = 0x0; constexpr size_t pt_load = 0x1; constexpr size_t pt_dynamic = 0x2; constexpr size_t pt_interp = 0x3; constexpr size_t pt_note = 0x4; constexpr size_t pt_shlib = 0x5; constexpr size_t pt_phdr = 0x6; constexpr size_t pt_lts = 0x7; constexpr size_t pt_loos = 0x60000000; constexpr size_t pt_hois = 0x6fffffff; constexpr size_t pt_loproc = 0x70000000; constexpr size_t pt_hiproc = 0x7fffffff; struct elf64_shdr { uint32_t sh_name; uint32_t sh_type; uint64_t sh_flags; uint64_t sh_addr; uint64_t sh_offset; uint64_t sh_size; uint32_t sh_link; uint32_t sh_info; uint64_t sh_addr_align; uint64_t sh_entsize; }; struct file { file(vmm::pmlx_table *page_map, aux *aux_cur, fs::fd &file, uint64_t base, lib::string **ld_path); struct [[gnu::packed]] { uint8_t ident[16]; uint16_t type; uint16_t machine; uint32_t version; uint64_t entry; uint64_t phoff; uint64_t shoff; uint32_t flags; uint16_t hdr_size; uint16_t phdr_size; uint16_t ph_num; uint16_t shdr_size; uint16_t sh_num; uint16_t shstrndx; } hdr; size_t status; }; }; #endif
21.636364
102
0.704949
ethan4984
e7f00603063bc356ee35f2dd4e5a891475b981ee
387
cpp
C++
01_Week_Programming_Basics/FishTank/FishTank.cpp
kostadinmarkov99/SoftUni_Exercises_PB_Jan_2022
70e619d7c19b6676f509f2509fe102ecbc7669bc
[ "MIT" ]
null
null
null
01_Week_Programming_Basics/FishTank/FishTank.cpp
kostadinmarkov99/SoftUni_Exercises_PB_Jan_2022
70e619d7c19b6676f509f2509fe102ecbc7669bc
[ "MIT" ]
null
null
null
01_Week_Programming_Basics/FishTank/FishTank.cpp
kostadinmarkov99/SoftUni_Exercises_PB_Jan_2022
70e619d7c19b6676f509f2509fe102ecbc7669bc
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int length, width, height; double percetage; cin >> length >> width >> height >> percetage; double volumeInSM = length * width * height; double liters = volumeInSM / 1000; double unusedLiters = liters * percetage / 100.0; double usedLiters = liters - unusedLiters; cout << usedLiters << endl; }
19.35
53
0.648579
kostadinmarkov99
e7f4315c365569ee6ce9a3393bc227c62b6a2fc9
9,001
cpp
C++
Client/src/UIGuildBankForm.cpp
ruuuubi/corsairs-client
ddbcd293d6ef3f58ff02290c02382cbb7e0939a2
[ "Apache-2.0" ]
1
2021-06-14T09:34:08.000Z
2021-06-14T09:34:08.000Z
Client/src/UIGuildBankForm.cpp
ruuuubi/corsairs-client
ddbcd293d6ef3f58ff02290c02382cbb7e0939a2
[ "Apache-2.0" ]
null
null
null
Client/src/UIGuildBankForm.cpp
ruuuubi/corsairs-client
ddbcd293d6ef3f58ff02290c02382cbb7e0939a2
[ "Apache-2.0" ]
null
null
null
#include "StdAfx.h" #include "UIGuildBankForm.h" #include "uiform.h" #include "uilabel.h" #include "uiformmgr.h" #include "uigoodsgrid.h" #include "NetProtocol.h" #include "uiboxform.h" #include "uiEquipForm.h" #include "UIGoodsGrid.h" #include "uiItemCommand.h" #include "uiform.h" #include "uiBoatForm.h" #include "packetcmd.h" #include "Character.h" #include "GameApp.h" #include "StringLib.h" namespace GUI { //======================================================================= // CGuildBankMgr 's Members //======================================================================= bool CGuildBankMgr::Init() //用户银行信息初始化 { CFormMgr &mgr = CFormMgr::s_Mgr; frmBank = mgr.Find("frmManage");// 查找NPC银行存储表单 if ( !frmBank) { LG("gui", g_oLangRec.GetString(438)); return false; } grdBank = dynamic_cast<CGoodsGrid*>(frmBank->Find("guildBank")); labGuildMoney = dynamic_cast<CLabel*>(frmBank->Find("labGuildMoney")); btnGoldTake = dynamic_cast<CTextButton*>(frmBank->Find("btngoldtake")); btnGoldPut = dynamic_cast<CTextButton*>(frmBank->Find("btngoldput")); grdBank->evtBeforeAccept = CUIInterface::_evtDragToGoodsEvent; grdBank->evtSwapItem = _evtBankToBank; btnGoldPut->evtMouseClick=_OnClickGoldPut; btnGoldTake->evtMouseClick=_OnClickGoldTake; return true; } void CGuildBankMgr::UpdateGuildGold(const char* value){ labGuildMoney->SetCaption(StringSplitNum(value)); } void CGuildBankMgr::_OnClickGoldPut(CGuiData *pSender, int x, int y, DWORD key){ g_stUIBox.ShowNumberBox(_EnterGoldPut, g_stUIBoat.GetHuman()->getGameAttr()->get(ATTR_GD), "Enter Gold", false); } void CGuildBankMgr::_EnterGoldPut(CCompent *pSender, int nMsgType, int x, int y, DWORD dwKey){ if( nMsgType!=CForm::mrYes ) { return; } stNumBox* kItemPriceBox = (stNumBox*)pSender->GetForm()->GetPointer(); if (!kItemPriceBox) return; int value = kItemPriceBox->GetNumber(); if( value<=0 ) { g_pGameApp->MsgBox( g_oLangRec.GetString(451) ); return; } CS_GuildBankGiveGold(value); } void CGuildBankMgr::_OnClickGoldTake(CGuiData *pSender, int x, int y, DWORD key){ g_stUIBox.ShowNumberBox(_EnterGoldTake, 2000000000-(g_stUIBoat.GetHuman()->getGameAttr()->get(ATTR_GD)), "Enter Gold", false); } void CGuildBankMgr::_EnterGoldTake(CCompent *pSender, int nMsgType, int x, int y, DWORD dwKey){ if( nMsgType!=CForm::mrYes ) { return; } stNumBox* kItemPriceBox = (stNumBox*)pSender->GetForm()->GetPointer(); if (!kItemPriceBox) return; int value = kItemPriceBox->GetNumber(); if( value<=0 ) { g_pGameApp->MsgBox( g_oLangRec.GetString(451) ); return; } CS_GuildBankTakeGold(value); } void CGuildBankMgr::_evtOnClose( CForm* pForm, bool& IsClose ) // 关闭用户银行 { CS_BeginAction(g_stUIBoat.GetHuman(), enumACTION_CLOSE_BANK, NULL); CFormMgr::s_Mgr.SetEnableHotKey(HOTKEY_BANK, true); // 西门文档修改 } //------------------------------------------------------------------------- void CGuildBankMgr::ShowBank() // 显示物品 { // 保存服务器传来的物品 if (!g_stUIBoat.GetHuman()) // 找人物 return; char szBuf[32]; sprintf(szBuf, "%s%s", g_stUIBoat.GetHuman()->getName(), g_oLangRec.GetString(440));//显示人物名及专用 //labCharName->SetCaption(szBuf);//设置标题名字 frmBank->Show(); // 打开玩家的物品栏 if (!g_stUIEquip.GetItemForm()->GetIsShow()) { int nLeft, nTop; nLeft = frmBank->GetX2(); nTop = frmBank->GetY(); g_stUIEquip.GetItemForm()->SetPos(nLeft, nTop); //物品放置位置 g_stUIEquip.GetItemForm()->Refresh(); //更新物品栏 g_stUIEquip.GetItemForm()->Show(); //保存在物品栏 } CFormMgr::s_Mgr.SetEnableHotKey(HOTKEY_BANK, false); // 西门文档修改 } //------------------------------------------------------------------------- bool CGuildBankMgr::PushToBank(CGoodsGrid& rkDrag, CGoodsGrid& rkSelf, int nGridID, CCommandObj& rkItem) { #define EQUIP_TYPE 0 #define BANK_TYPE 1 // 设置发送拖动物品的服务器信息 m_kNetBank.chSrcType = EQUIP_TYPE; m_kNetBank.sSrcID = rkDrag.GetDragIndex(); //m_kNetBank.sSrcNum = ; 数量在回调函数中设置 m_kNetBank.chTarType = BANK_TYPE; m_kNetBank.sTarID = nGridID; // 判断物品是否是可重叠的物品 CItemCommand* pkItemCmd = dynamic_cast<CItemCommand*>(&rkItem); if (!pkItemCmd) return false; CItemRecord* pkItemRecord = pkItemCmd->GetItemInfo(); if (!pkItemRecord) return false; //if(pkItemRecord->sType == 59 && m_kNetBank.sSrcID == 1) //{ // g_pGameApp->MsgBox("您的精灵正在使用中\n请更换到其它位置才可放入仓库"); // return false; // 第二格的精灵不允许拖入银行 //} // if(pkItemRecord->lID == 2520 || pkItemRecord->lID == 2521) if( pkItemRecord->lID == 2520 || pkItemRecord->lID == 2521 || pkItemRecord->lID == 6341 || pkItemRecord->lID == 6343 || pkItemRecord->lID == 6347 || pkItemRecord->lID == 6359 || pkItemRecord->lID == 6370 || pkItemRecord->lID == 6371 || pkItemRecord->lID == 6373 || pkItemRecord->lID >= 6376 && pkItemRecord->lID <= 6378 || pkItemRecord->lID >= 6383 && pkItemRecord->lID <= 6385 )// modify by ning.yan 20080820 策划绵羊、李恒等提需求,增加一些道具不准存银行 { //g_pGameApp->MsgBox(g_oLangRec.GetString(958)); // "该道具不允许存入银行!请重新选择" g_pGameApp->MsgBox(g_oLangRec.GetString(958)); // "该道具不允许存入银行!请重新选择" return false; } if ( pkItemCmd->GetItemInfo()->GetIsPile() && pkItemCmd->GetTotalNum() > 1 ) { /*存放多个物品*/ m_pkNumberBox = g_stUIBox.ShowNumberBox(_MoveItemsEvent, pkItemCmd->GetTotalNum(), g_oLangRec.GetString(441), false); if (m_pkNumberBox->GetNumber() < pkItemCmd->GetTotalNum()) return false; else return true; } else { /*存放单个物品*/ g_stUIGuildBank.m_kNetBank.sSrcNum = 1; //CS_BeginAction(g_stUIBoat.GetHuman(), enumACTION_GUILDBANK, (void*)&(g_stUIGuildBank.m_kNetBank)); CS_GuildBankOper(&g_stUIGuildBank.m_kNetBank); return true; //char buf[256] = { 0 }; //sprintf(buf, "您确认放入银行\n[%s]?", pkItemCmd->GetName()); //g_stUIBox.ShowSelectBox(_MoveAItemEvent, buf, true); //return true; } } //------------------------------------------------------------------------- bool CGuildBankMgr::PopFromBank(CGoodsGrid& rkDrag, CGoodsGrid& rkSelf, int nGridID, CCommandObj& rkItem) { // 设置发送拖动物品的服务器信息 m_kNetBank.chSrcType = BANK_TYPE ; m_kNetBank.sSrcID = rkDrag.GetDragIndex(); //m_kNetBank.sSrcNum = ; 数量在回掉函数中设置 m_kNetBank.chTarType = EQUIP_TYPE; m_kNetBank.sTarID = nGridID; // 判断物品是否是可重叠的物品 CItemCommand* pkItemCmd = dynamic_cast<CItemCommand*>(&rkItem); if (!pkItemCmd) return false; if ( pkItemCmd->GetItemInfo()->GetIsPile() && pkItemCmd->GetTotalNum() > 1 ) { /*取出多个物品*/ m_pkNumberBox = g_stUIBox.ShowNumberBox( _MoveItemsEvent, pkItemCmd->GetTotalNum(), g_oLangRec.GetString(442), false); if (m_pkNumberBox->GetNumber() < pkItemCmd->GetTotalNum()) return false; else return true; } else { /*存放单个物品*/ g_stUIGuildBank.m_kNetBank.sSrcNum = 1; //CS_BeginAction(g_stUIBoat.GetHuman(), enumACTION_GUILDBANK, (void*)&(g_stUIGuildBank.m_kNetBank)); CS_GuildBankOper(&g_stUIGuildBank.m_kNetBank); return true; //char buf[256] = { 0 }; //sprintf(buf, "您确认取出\n[%s]?", pkItemCmd->GetName()); //g_stUIBox.ShowSelectBox(_MoveAItemEvent, buf, true); //return true; } } //------------------------------------------------------------------------- void CGuildBankMgr::_MoveItemsEvent(CCompent *pSender, int nMsgType, int x, int y, DWORD dwKey) // 多个物品移动 { if(nMsgType != CForm::mrYes) // 玩家是否同意拖动 return; int num = g_stUIGuildBank.m_pkNumberBox->GetNumber();// 拖动物品数 if ( num > 0 ) { g_stUIGuildBank.m_kNetBank.sSrcNum = num; //CS_BeginAction(g_stUIBoat.GetHuman(), enumACTION_GUILDBANK, (void*)&(g_stUIGuildBank.m_kNetBank)); CS_GuildBankOper(&g_stUIGuildBank.m_kNetBank); } } //------------------------------------------------------------------------- void CGuildBankMgr::_MoveAItemEvent(CCompent *pSender, int nMsgType, int x, int y, DWORD dwKey) // 单个道具移动 { if(nMsgType != CForm::mrYes) return; g_stUIGuildBank.m_kNetBank.sSrcNum = 1; //CS_BeginAction(g_stUIBoat.GetHuman(), enumACTION_GUILDBANK, (void*)&(g_stUIGuildBank.m_kNetBank));//更新银行信息 CS_GuildBankOper(&g_stUIGuildBank.m_kNetBank); } //------------------------------------------------------------------------- void CGuildBankMgr::CloseForm() // 关闭道具栏表单 { if (frmBank->GetIsShow()) { frmBank->Close(); g_stUIEquip.GetItemForm()->Close(); } } //------------------------------------------------------------------------- void CGuildBankMgr::_evtBankToBank(CGuiData *pSender,int nFirst, int nSecond, bool& isSwap) // 用于用户银行表单中道具互换 { isSwap = false; if( !g_stUIBoat.GetHuman() ) return; g_stUIGuildBank.m_kNetBank.chSrcType = BANK_TYPE ; g_stUIGuildBank.m_kNetBank.sSrcID = nSecond; g_stUIGuildBank.m_kNetBank.sSrcNum = 0; g_stUIGuildBank.m_kNetBank.chTarType = BANK_TYPE; g_stUIGuildBank.m_kNetBank.sTarID = nFirst; //CS_BeginAction(g_stUIBoat.GetHuman(), enumACTION_GUILDBANK, (void*)&(g_stUIGuildBank.m_kNetBank)); CS_GuildBankOper(&g_stUIGuildBank.m_kNetBank); } } // end of namespace GUI
31.582456
128
0.651039
ruuuubi
e7f603ac6f13bee4c23a336e65ebf2c1e5f4ece4
4,597
hpp
C++
ASch/include/ASch_System.hpp
JuhoL/ASch
757c7edacb1aabce5577acc3df0560548975df49
[ "MIT" ]
2
2018-08-20T08:56:11.000Z
2019-07-09T07:27:45.000Z
ASch/include/ASch_System.hpp
JuhoL/ASch
757c7edacb1aabce5577acc3df0560548975df49
[ "MIT" ]
null
null
null
ASch/include/ASch_System.hpp
JuhoL/ASch
757c7edacb1aabce5577acc3df0560548975df49
[ "MIT" ]
null
null
null
//----------------------------------------------------------------------------------------------------------------------------- // Copyright (c) 2018 Juho Lepistö // // 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. //----------------------------------------------------------------------------------------------------------------------------- //! @file ASch_System.hpp //! @author Juho Lepistö <juho.lepisto(a)gmail.com> //! @date 20 Aug 2018 //! //! @class System //! @brief Generic system control class for ASch. //! //! This class implements system control functions and handles generic system level events like ticks and system errors. #ifndef ASCH_SYSTEM_HPP_ #define ASCH_SYSTEM_HPP_ //----------------------------------------------------------------------------------------------------------------------------- // 1. Include Dependencies //----------------------------------------------------------------------------------------------------------------------------- #include <Utils_Types.hpp> #include <Hal_System.hpp> //----------------------------------------------------------------------------------------------------------------------------- // 2. Typedefs, Structs, Enums and Constants //----------------------------------------------------------------------------------------------------------------------------- namespace ASch { /// @brief This is a system error enum. enum class SysError { invalidParameters = 0, //!< A function was called with invalid parameters. bufferOverflow, //!< A buffer has overflown. insufficientResources, //!< System resources (e.g. task quota) has ran out. accessNotPermitted, //!< An attempt to access blocked resource has occurred. assertFailure, //!< A debug assert has failed. unknownError //!< An unknown error. Should never occur. }; } //----------------------------------------------------------------------------------------------------------------------------- // 3. Inline Functions //----------------------------------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------------------------- // 4. Global Function Prototypes //----------------------------------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------------------------- // 5. Class Declaration //----------------------------------------------------------------------------------------------------------------------------- namespace ASch { //! @class System //! @brief Generic system control class for ASch. //! This class implements system control functions and handles generic system level events like ticks and system errors. class System { public: explicit System(void) {}; /// @brief This fuction raises a system error. /// @param error - Error type. static void Error(SysError error); /// @brief This function enables reset on error. static void EnableResetOnSystemError(void); /// @brief This fuction initialises the system, e.f. clocks and other base peripherals. static void Init(void); /// @brief This function runs pre-start configuration functions. static void PreStartConfig(void); private: static bool resetOnError; }; } // namespace ASch #endif // ASCH_SYSTEM_HPP_
45.068627
127
0.474005
JuhoL
e7f60c2f38799f660ad85b4e9de2bbd6da832a41
1,843
cpp
C++
src/Ledger.cpp
LAHumphreys/LedgerJRI
0c015ed328a71d624791bc6fb6c03e65709c7b13
[ "MIT" ]
null
null
null
src/Ledger.cpp
LAHumphreys/LedgerJRI
0c015ed328a71d624791bc6fb6c03e65709c7b13
[ "MIT" ]
null
null
null
src/Ledger.cpp
LAHumphreys/LedgerJRI
0c015ed328a71d624791bc6fb6c03e65709c7b13
[ "MIT" ]
null
null
null
#include <Ledger.h> #include <LedgerSessionData.h> #include <LedgerSession.h> #include <LedgerCommands.h> Ledger::Ledger() { // libLedger one-time setup? } std::unique_ptr<LedgerSession> Ledger::LoadJournal(const std::string& fname) { std::unique_ptr<LedgerSession> sess; WithInstance([&] (Ledger& instance) { sess = std::make_unique<LedgerSession>(instance); instance.SwitchToSession(*sess); const char ** env = const_cast<const char**>(environ); sess->Data().sess.set_flush_on_next_data_file(true); ledger::process_environment(env, "LEDGER_", sess->Data().report); sess->Data().sess.set_flush_on_next_data_file(true); bool initialised = false; try { sess->Data().sess.read_journal(fname); initialised = true; } catch (ledger::error_count& ec) { sess->BadJournal(instance, ec.what()); } catch (const std::runtime_error& err) { sess->BadJournal(instance, err.what()); } if (initialised) { sess->SessionInitialised(instance); } }); return sess; } void Ledger::WithInstance(const std::function<void(Ledger &instance)> &cb) { static Ledger instance; std::unique_lock<std::mutex> lock(instance.globalLock); cb(instance); } void Ledger::SwitchToSession(LedgerSession&sess) { ledger::set_session_context(&sess.Data().sess); ledger::scope_t::default_scope = &sess.Data().report; ledger::scope_t::empty_scope = &sess.Data().emptyScope; } void Ledger::WithSession(LedgerSession &sess, const std::function<void(LedgerCommands &)>& task) { WithInstance([&] (Ledger& instance) { instance.SwitchToSession(sess); LedgerCommands cmdHandler(instance, sess); task(cmdHandler); }); }
29.253968
78
0.637005
LAHumphreys
e7f789f835be45fa51b41edcbf3a38b3802995b0
3,746
cpp
C++
code/silverlib/game_hooks.cpp
adm244/f4silver
564ecc80991266ae8b3238f553b76d75506f9fbf
[ "Unlicense" ]
6
2018-11-07T19:31:30.000Z
2021-07-29T02:58:33.000Z
code/silverlib/game_hooks.cpp
adm244/f4silver
564ecc80991266ae8b3238f553b76d75506f9fbf
[ "Unlicense" ]
2
2018-06-01T23:27:46.000Z
2018-09-11T23:35:58.000Z
code/silverlib/game_hooks.cpp
adm244/f4silver
564ecc80991266ae8b3238f553b76d75506f9fbf
[ "Unlicense" ]
3
2019-12-29T14:45:55.000Z
2020-05-12T16:34:23.000Z
/* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. */ //IMPORTANT(adm244): SCRATCH VERSION JUST TO GET IT UP WORKING #ifndef _SILVERLIB_GAME_HOOKS_CPP_ #define _SILVERLIB_GAME_HOOKS_CPP_ extern "C" void GameLoop() { if( gGameState.IsGameLoaded ) { if (gGameState.IsPlayerDead != IsActorDead((TESActor *)TES_GetPlayer())) { gGameState.IsPlayerDead = !gGameState.IsPlayerDead; if (gGameState.IsPlayerDead) { //TODO(adm244): place into a separate function call? INPUT input = {0}; input.type = INPUT_KEYBOARD; input.ki.wVk = Keys.DeathEvent; input.ki.dwExtraInfo = GetMessageExtraInfo(); SendInput(1, &input, sizeof(INPUT)); } } if (!IsActivationPaused()) { if( gGameState.IsInterior != IsPlayerInInterior() ) { gGameState.IsInterior = !gGameState.IsInterior; if( gGameState.IsInterior ) { ProcessQueue(&gQueues.InteriorPendingQueue, false); } else { ProcessQueue(&gQueues.ExteriorPendingQueue, false); } } ProcessQueue(&gQueues.PrimaryQueue, true); } } } extern "C" void LoadGameBegin(char *filename) { gGameState.IsGameLoaded = false; } extern "C" void LoadGameEnd() { gGameState.IsGameLoaded = true; } extern "C" void HackingPrepare() { //TESConsolePrint("Terminal Hacking Entered"); ExtraDataList *extrasList = (*gActiveTerminalREFR)->extraDataList; assert(extrasList != 0); ExtraLockData *lockData = ExtraDataList_GetExtraLockData(extrasList); assert(lockData != 0); //BSReadWriteLock_Lock(&extrasList->lock); //NOTE(adm244): unused flag, should be safe if (lockData->flags & 0x80) { //NOTE(adm244): using padding here, should be safe uint8 savedTries = lockData->pad01[0]; if (savedTries == 0) { lockData->flags &= 0x7F; } else { *gTerminalTryCount = (int32)savedTries; } } //BSReadWriteLock_Unlock(&extrasList->lock); } extern "C" void HackingQuit() { //TESConsolePrint("Terminal Hacking Quitted"); ExtraDataList *extrasList = (*gActiveTerminalREFR)->extraDataList; assert(extrasList != 0); ExtraLockData *lockData = ExtraDataList_GetExtraLockData(extrasList); assert(lockData != 0); //FIX(adm244): locks game sometimes? //BSReadWriteLock_Lock(&extrasList->lock); lockData->flags |= 0x80; lockData->pad01[0] = (uint8)(*gTerminalTryCount); //BSReadWriteLock_Unlock(&extrasList->lock); } //NOTE(adm244): returns true if VATS is allowed to activate, false otherwise extern "C" bool VATSActivate() { return IsPlayerInCombat(); } #endif
29.730159
78
0.70929
adm244
e7feb77a0e6a3e4807d2f203b96c6ff3cb432fb3
1,002
hpp
C++
coroutine/OverridingList.hpp
bxtx999/pmembench
9577a15bc7934a681f23b3096f2cd25e09f66874
[ "MIT", "Unlicense" ]
10
2021-02-09T21:07:12.000Z
2022-02-10T17:37:06.000Z
coroutine/OverridingList.hpp
bxtx999/pmembench
9577a15bc7934a681f23b3096f2cd25e09f66874
[ "MIT", "Unlicense" ]
null
null
null
coroutine/OverridingList.hpp
bxtx999/pmembench
9577a15bc7934a681f23b3096f2cd25e09f66874
[ "MIT", "Unlicense" ]
4
2021-04-12T08:13:09.000Z
2022-01-05T02:54:45.000Z
#pragma once // ------------------------------------------------------------------------------------- #include <type_traits> #include <cassert> // ------------------------------------------------------------------------------------- template<typename Value> class OverridingList { public: OverridingList() : head(nullptr) {} void Push(Value ptr) { Entry *entry = reinterpret_cast<Entry *>(ptr); entry->next = head; head = ptr; } Value Pop() { assert(!Empty()); Value result = head; head = reinterpret_cast<Entry *>(head)->next; return result; } Value Top() { assert(!Empty()); return head; } bool Empty() const { return head == nullptr; } private: static_assert(std::is_pointer<Value>::value, "InPlaceList can not work on values."); struct Entry { Value next; }; Value head; }; // -------------------------------------------------------------------------------------
20.875
88
0.422156
bxtx999
f001aa502b6b916c44ef754284d4953e994763a6
2,085
hh
C++
Include/Zion/GameMode.hh
ZionMP/Zion
7266cc5df81644e54c2744fca7f31b24873b31e7
[ "BSD-2-Clause" ]
1
2021-10-14T05:25:47.000Z
2021-10-14T05:25:47.000Z
Include/Zion/GameMode.hh
ZionMP/Zion
7266cc5df81644e54c2744fca7f31b24873b31e7
[ "BSD-2-Clause" ]
null
null
null
Include/Zion/GameMode.hh
ZionMP/Zion
7266cc5df81644e54c2744fca7f31b24873b31e7
[ "BSD-2-Clause" ]
null
null
null
#pragma once #include "Base.hh" #include "Player.hh" #include "Vehicle.hh" #include "Util.hh" #include "TextDraw.hh" #include "Pickup.hh" namespace Zion { class GameMode { public: virtual void OnPlayerInteriorChange(Player *player, int newInterior, int oldInterior) {} virtual void OnDialogResponse(Player *player, int dialogId, int buttonId, int listItem, const char *inputText) {} virtual void OnPlayerClickMap(Player *player, Vector3 position) {} virtual void OnPlayerCommandText(Player *player, const char *command) {} virtual void OnClientMessage(Player *player, const char *message) {} virtual void OnPlayerDeath(Player *player, Player *killer, int reason) {} virtual void OnPlayerSpawn(Player *player) {} virtual bool OnPlayerRequestSpawn(Player *player) { return true; } virtual bool OnPlayerRequestClass(Player *player, int classId) { return true; } virtual void OnPlayerConnect(Player *player) {} virtual void OnPlayerDisconnect(Player *player, int reason) {} virtual void OnPlayerUpdate(Player *player) {} virtual void OnPlayerEnterCheckpoint(Player *player) {} virtual void OnPlayerLeaveCheckpoint(Player *player) {} virtual void OnPlayerEnterRaceCheckpoint(Player *player) {} virtual void OnPlayerLeaveRaceCheckpoint(Player *player) {} virtual void OnPlayerStateChange(Player *player, int newState, int oldState) {} virtual void OnPlayerEnterVehicle(Player *player, Vehicle *vehicle, bool ispassenger) {} virtual void OnPlayerExitVehicle(Player *player, Vehicle *vehicle) {} virtual void OnVehicleDamageStatusUpdate(Vehicle *vehicle, Player *player) {} virtual void OnGameModeInit() {} virtual void OnGameModeExit() {} virtual void OnPlayerClickTextDraw(Player *player, TextDraw *textDraw) {} virtual void OnPlayerPickUpPickup(Player *player, Pickup *pickup) {} }; };
56.351351
125
0.67482
ZionMP
f005369c1ccf2e02974208beb2f1ab22db4f5cfb
2,025
hpp
C++
zen/lexgen/nodes.hpp
ZenLibraries/ZenLibraries
ae189b5080c75412cbd4f33cf6cfb51e15f6ee66
[ "Apache-2.0" ]
null
null
null
zen/lexgen/nodes.hpp
ZenLibraries/ZenLibraries
ae189b5080c75412cbd4f33cf6cfb51e15f6ee66
[ "Apache-2.0" ]
2
2020-02-06T17:01:39.000Z
2020-02-12T17:50:14.000Z
zen/lexgen/nodes.hpp
ZenLibraries/ZenLibraries
ae189b5080c75412cbd4f33cf6cfb51e15f6ee66
[ "Apache-2.0" ]
null
null
null
#ifndef ZEN_LEXGEN_NODES_HPP #define ZEN_LEXGEN_NODES_HPP #include <list> #include <memory> #include "zen/string.hpp" #include "zen/dllist.hpp" namespace zen { namespace lexgen { template<typename T> using SPtr = std::shared_ptr<T>; enum class NodeType { rule, ref_expr, char_expr, string_expr, choice_expr, seq_expr, }; class Node { NodeType type; public: inline Node(NodeType type): type(type) {} Node* parent_node = nullptr; inline NodeType get_type() const { return type; } template<typename DerivedT> inline DerivedT& as() { return *static_cast<DerivedT*>(this); } }; class Expr; class Rule : public Node { String name; SPtr<Expr> expr; public: inline Rule(String name): Node(NodeType::rule), name(name) {} string_view get_name() const { return name; } }; class Expr : public Node { public: inline Expr(NodeType type): Node(type) {} }; class CharExpr : public Expr { Glyph ch; public: inline CharExpr(Glyph ch): Expr(NodeType::char_expr), ch(ch) {} inline Glyph get_ch() const { return ch; } }; class ChoiceExpr : public Expr { using Elements = DLList<SPtr<Expr>>; Elements elements; public: template<typename RangeT> inline ChoiceExpr(RangeT range): Expr(NodeType::choice_expr), elements(range.begin(), range.end()) {} Elements::Range get_elements() { return elements.range(); } }; class SeqExpr : public Expr { using Elements = DLList<SPtr<Expr>>; Elements elements; public: inline SeqExpr(): Expr(NodeType::seq_expr) {} template<typename RangeT> inline SeqExpr(RangeT range): Expr(NodeType::seq_expr), elements(range) {} }; } } #endif // of #ifndef ZEN_LEXGEN_NODES_HPP
15.944882
76
0.576296
ZenLibraries
f00812be6bc41c86a6dcd549186c57d6f57ce8d3
2,301
hpp
C++
CookieEngine/include/Gameplay/CGPWorker.hpp
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
CookieEngine/include/Gameplay/CGPWorker.hpp
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
CookieEngine/include/Gameplay/CGPWorker.hpp
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
#ifndef _CGP_WORKER_HPP__ #define _CGP_WORKER_HPP__ #include "ComponentTransform.hpp" #include "Map.hpp" #include "Gameplay/CGPResource.hpp" #include "Gameplay/Income.hpp" #include <vector> namespace Cookie { namespace ECS { class Coordinator; } namespace Resources { class Prefab; class Map; } namespace Gameplay { #define TIME_TO_HARVEST 2 #define PRIMARY_PER_HARVEST 5 #define SECONDARY_PER_HARVEST 4 class CGPWorker { public: //will be replace by the CPGMove with flying later on float moveSpeed {5}; //Harvest Income* income {nullptr}; Core::Math::Vec3* posBase {nullptr}; Core::Math::Vec3* posResource {nullptr}; CGPResource* resource {nullptr}; float harvestCountdown {0}; bool isCarryingResource {false}; //Building std::vector<Resources::Prefab*> possibleBuildings; std::vector<std::string> possibleBuildingsAtLoad; Resources::Prefab* BuildingInConstruction {nullptr}; Core::Math::Vec3 posBuilding {0, 0, 0}; // = mousePos when start construction bool needTostartBuilding {false}; float constructionCountdown {0}; std::vector<Resources::Tile*> occupiedTiles; //get at start of building, then set in building CGPWorker() {} ~CGPWorker() {} inline void ToDefault() noexcept { income = nullptr; posBase = nullptr; posResource = nullptr; resource = nullptr; harvestCountdown = 0; isCarryingResource = false; possibleBuildings.clear(); possibleBuildingsAtLoad.clear(); BuildingInConstruction = nullptr; posBuilding = {0, 0, 0}; needTostartBuilding = false; constructionCountdown = 0; for (int i = 0; i < occupiedTiles.size(); ++i) occupiedTiles[i]->isObstacle = false; occupiedTiles.clear(); } void Update(Resources::Map& map, ECS::Coordinator& coordinator, int selfId); void SetResource(Core::Math::Vec3& resourcePos, CGPResource& resourceCGP); bool StartBuilding(Resources::Map& map, Core::Math::Vec3& _posBuilding, int indexInPossibleBuildings); }; } } #endif // !_CGP_WORKER_HPP__
26.755814
105
0.633638
qbleuse
f00a35b5915426f9c5ddcecaebf999755c2cc7e7
192
cpp
C++
bytecode/interpreter/src/BytecodeInterpreter/Units/InterpreterCommandMov.cpp
Scorbutics/skalang
c8d1869a2f0c7857ee05ef45bd3aa4e537d39558
[ "MIT" ]
3
2019-04-08T17:34:19.000Z
2020-01-03T04:47:06.000Z
bytecode/interpreter/src/BytecodeInterpreter/Units/InterpreterCommandMov.cpp
Scorbutics/skalang
c8d1869a2f0c7857ee05ef45bd3aa4e537d39558
[ "MIT" ]
4
2020-04-19T22:09:06.000Z
2020-11-06T15:47:08.000Z
bytecode/interpreter/src/BytecodeInterpreter/Units/InterpreterCommandMov.cpp
Scorbutics/skalang
c8d1869a2f0c7857ee05ef45bd3aa4e537d39558
[ "MIT" ]
null
null
null
#include "InterpreterCommandMov.h" SKALANG_BYTECODE_INTERPRETER_COMMAND_DECLARE(MOV)(ExecutionContext& context, const Operand& left, const Operand& right) { return context.getCell(left); }
32
121
0.8125
Scorbutics
f00dbdb3d7bef7604daa1335487649f287667bd0
5,221
cpp
C++
libvast/src/system/read_query.cpp
rdettai/vast
0b3cf41011df5fe8a4e8430fa6a1d6f1c50a18fa
[ "BSD-3-Clause" ]
249
2019-08-26T01:44:45.000Z
2022-03-26T14:12:32.000Z
libvast/src/system/read_query.cpp
rdettai/vast
0b3cf41011df5fe8a4e8430fa6a1d6f1c50a18fa
[ "BSD-3-Clause" ]
586
2019-08-06T13:10:36.000Z
2022-03-31T08:31:00.000Z
libvast/src/system/read_query.cpp
rdettai/vast
0b3cf41011df5fe8a4e8430fa6a1d6f1c50a18fa
[ "BSD-3-Clause" ]
37
2019-08-16T02:01:14.000Z
2022-02-21T16:13:59.000Z
// _ _____ __________ // | | / / _ | / __/_ __/ Visibility // | |/ / __ |_\ \ / / Across // |___/_/ |_/___/ /_/ Space and Time // // SPDX-FileCopyrightText: (c) 2019 The VAST Contributors // SPDX-License-Identifier: BSD-3-Clause #include "vast/system/read_query.hpp" #include "vast/fwd.hpp" #include "vast/concept/parseable/to.hpp" #include "vast/concept/parseable/vast/expression.hpp" #include "vast/defaults.hpp" #include "vast/error.hpp" #include "vast/logger.hpp" #include "vast/scope_linked.hpp" #include "vast/system/signal_monitor.hpp" #include "vast/system/spawn_or_connect_to_node.hpp" #include <caf/actor.hpp> #include <caf/event_based_actor.hpp> #include <caf/scoped_actor.hpp> #include <caf/settings.hpp> #include <caf/stateful_actor.hpp> #include <sys/stat.h> #include <chrono> #include <cstdio> #include <fstream> #include <iostream> #include <unistd.h> using namespace caf; using namespace std::chrono_literals; namespace vast::system { namespace { caf::expected<std::string> read_query(const std::vector<std::string>& args, size_t offset) { if (args.size() > offset + 1) return caf::make_error(ec::invalid_argument, "spreading a query over " "multiple arguments is not " "allowed; please pass it as a " "single string instead."); return args[offset]; } caf::expected<std::string> read_query(std::istream& in) { auto result = std::string{}; result.assign(std::istreambuf_iterator<char>{in}, std::istreambuf_iterator<char>{}); return result; } caf::expected<std::string> read_query(const std::string& path) { std::ifstream f{path}; if (!f) return caf::make_error(ec::no_such_file, fmt::format("unable to read from '{}'", path)); return read_query(f); } std::string make_all_query() { VAST_VERBOSE("not providing a query causes everything to be exported; please " "be aware that this operation may be very expensive."); return R"__(#type != "this expression matches everything")__"; } } // namespace caf::expected<std::string> read_query(const invocation& inv, std::string_view file_option, enum must_provide_query must_provide_query, size_t argument_offset) { VAST_TRACE_SCOPE("{} {}", inv, file_option); // The below logic matches the following behavior: // vast export <format> <query> // takes the query from the command line // vast export -r - <format> // reads the query from stdin. // echo "query" | vast export <format> // reads the query from stdin // vast <query.txt export <format> // reads the query from `query.txt` // vast export <format> // export everything // Specifying any two conflicting ways of reading the query // results in an error. const auto fname = caf::get_if<std::string>(&inv.options, file_option); const bool has_query_cli = inv.arguments.size() > argument_offset; bool has_query_stdin = [] { struct stat stats = {}; if (::fstat(::fileno(stdin), &stats) != 0) return false; return S_ISFIFO(stats.st_mode) || S_ISREG(stats.st_mode); }(); if (fname) { if (has_query_cli) return caf::make_error( ec::invalid_argument, fmt::format("got query '{}' on the command line and query file" " '{}' specified via '--read' option", read_query(inv.arguments, argument_offset), *fname)); if (*fname == "-") return read_query(std::cin); if (has_query_stdin) return caf::make_error(ec::invalid_argument, fmt::format("stdin is connected to a pipe or " "regular file and query file '{}'", " specified via '--read' option", *fname)); return read_query(*fname); } // As a special case we ignore stdin unless we get an actual query // from it, since empirically this is often connected to the remnants // of a long-forgotten file descriptor by some distant parent process // when running in any kind of automated environment like a CI runner. std::string cin_query; if (has_query_stdin) { auto query = read_query(std::cin); if (!query || query->empty()) has_query_stdin = false; else cin_query = *query; } if (has_query_stdin && has_query_cli) return caf::make_error( ec::invalid_argument, fmt::format("got query '{}' on the command line and '{}' via stdin", read_query(inv.arguments, argument_offset), cin_query)); if (has_query_cli) return read_query(inv.arguments, argument_offset); if (has_query_stdin) return cin_query; if (must_provide_query == must_provide_query::yes) return caf::make_error(ec::invalid_argument, "no query provided, but " "command requires a query " "argument"); // No query provided, make a query that finds everything. return make_all_query(); } } // namespace vast::system
35.517007
80
0.622103
rdettai
f00f829e36cab5051a674b7c0f5f57955c333623
4,000
hpp
C++
include/ashespp/RenderPass/RenderPass.hpp
DragonJoker/Ashes
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
[ "MIT" ]
227
2018-09-17T16:03:35.000Z
2022-03-19T02:02:45.000Z
include/ashespp/RenderPass/RenderPass.hpp
DragonJoker/RendererLib
0f8ad8edec1b0929ebd10247d3dd0a9ee8f8c91a
[ "MIT" ]
39
2018-02-06T22:22:24.000Z
2018-08-29T07:11:06.000Z
include/ashespp/RenderPass/RenderPass.hpp
DragonJoker/Ashes
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
[ "MIT" ]
8
2019-05-04T10:33:32.000Z
2021-04-05T13:19:27.000Z
/* This file belongs to Ashes. See LICENSE file in root folder. */ #ifndef ___AshesPP_RenderPass_HPP___ #define ___AshesPP_RenderPass_HPP___ #pragma once #include "RenderPassCreateInfo.hpp" namespace ashes { /** *\brief * Describes a render pass (which can contain one or more render subpasses). */ class RenderPass : public VkObject { public: /** *\brief * Constructor. *\param[in] device * The logical device. *\param[in] createInfo * The creation informations. */ RenderPass( Device const & device , RenderPassCreateInfo createInfo ); /** *\brief * Constructor. *\param[in] device * The logical device. *\param[in] createInfo * The creation informations. */ RenderPass( Device const & device , std::string const & debugName , RenderPassCreateInfo createInfo ); /** *\brief * Destructor. */ ~RenderPass(); /** *\brief * Creates a frame buffer compatible with this render pass. *\remarks * If the compatibility between wanted views and the render pass' formats * is not possible, a std::runtime_error will be thrown. *\param[in] dimensions * The frame buffer's dimensions. *\param[in] views * The views for the frame buffer to create. *\param[in] layers * The layers count for the frame buffer to create. *\return * The created frame buffer. */ FrameBufferPtr createFrameBuffer( VkFramebufferCreateInfo info )const; /** *\brief * Creates a frame buffer compatible with this render pass. *\remarks * If the compatibility between wanted views and the render pass' formats * is not possible, a std::runtime_error will be thrown. *\param[in] dimensions * The frame buffer's dimensions. *\param[in] views * The views for the frame buffer to create. *\param[in] layers * The layers count for the frame buffer to create. *\return * The created frame buffer. */ FrameBufferPtr createFrameBuffer( std::string const & debugName , VkFramebufferCreateInfo info )const; /** *\brief * Creates a frame buffer compatible with this render pass. *\remarks * If the compatibility between wanted views and the render pass' formats * is not possible, a std::runtime_error will be thrown. *\param[in] dimensions * The frame buffer's dimensions. *\param[in] views * The views for the frame buffer to create. *\param[in] layers * The layers count for the frame buffer to create. *\return * The created frame buffer. */ FrameBufferPtr createFrameBuffer( VkExtent2D const & dimensions , ImageViewCRefArray views , uint32_t layers = 1u )const; /** *\brief * Creates a frame buffer compatible with this render pass. *\remarks * If the compatibility between wanted views and the render pass' formats * is not possible, a std::runtime_error will be thrown. *\param[in] dimensions * The frame buffer's dimensions. *\param[in] views * The views for the frame buffer to create. *\param[in] layers * The layers count for the frame buffer to create. *\return * The created frame buffer. */ FrameBufferPtr createFrameBuffer( std::string const & debugName , VkExtent2D const & dimensions , ImageViewCRefArray views , uint32_t layers = 1u )const; /** *name * Getters. */ /**@{*/ inline size_t getAttachmentCount()const { return m_createInfo.attachments.size(); } inline VkAttachmentDescriptionArray const & getAttachments()const { return m_createInfo.attachments; } inline Device const & getDevice()const { return m_device; } inline size_t getSubpassCount()const { return m_createInfo.subpasses.size(); } inline SubpassDescriptionArray const & getSubpasses()const { return m_createInfo.subpasses; } /**@}*/ /** *\brief * VkRenderPass implicit cast operator. */ inline operator VkRenderPass const & ()const { return m_internal; } private: Device const & m_device; RenderPassCreateInfo m_createInfo; VkRenderPass m_internal{}; }; } #endif
24.390244
76
0.70075
DragonJoker
f0140c4ac96027b009016a32e66fd6ff5f3e6fc1
14,176
cpp
C++
Immortal/Platform/D3D12/RenderContext.cpp
QSXW/Immortal
32adcc8609b318752dd97f1c14dc7368b47d47d1
[ "Apache-2.0" ]
6
2021-09-15T08:56:28.000Z
2022-03-29T15:55:02.000Z
Immortal/Platform/D3D12/RenderContext.cpp
DaShi-Git/Immortal
e3345b4ff2a2b9d215c682db2b4530e24cc3b203
[ "Apache-2.0" ]
null
null
null
Immortal/Platform/D3D12/RenderContext.cpp
DaShi-Git/Immortal
e3345b4ff2a2b9d215c682db2b4530e24cc3b203
[ "Apache-2.0" ]
4
2021-12-05T17:28:57.000Z
2022-03-29T15:55:05.000Z
#include "impch.h" #include "RenderContext.h" #include "Framework/Utils.h" #include "Descriptor.h" namespace Immortal { namespace D3D12 { Device *RenderContext::UnlimitedDevice = nullptr; DescriptorAllocator RenderContext::shaderVisibleDescriptorAllocator{ DescriptorPool::Type::ShaderResourceView, DescriptorPool::Flag::ShaderVisible }; DescriptorAllocator RenderContext::descriptorAllocators[U32(DescriptorPool::Type::Quantity)] = { DescriptorPool::Type::ShaderResourceView, DescriptorPool::Type::Sampler, DescriptorPool::Type::RenderTargetView, DescriptorPool::Type::DepthStencilView }; RenderContext::RenderContext(Description &descrition) : desc{ descrition } { Setup(); } RenderContext::RenderContext(const void *handle) { Setup(); } RenderContext::~RenderContext() { IfNotNullThen<FreeLibrary>(hModule); } void RenderContext::Setup() { desc.FrameCount = Swapchain::SWAP_CHAIN_BUFFER_COUNT; uint32_t dxgiFactoryFlags = 0; #if SLDEBUG ComPtr<ID3D12Debug> debugController; if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugController)))) { debugController->EnableDebugLayer(); dxgiFactoryFlags |= DXGI_CREATE_FACTORY_DEBUG; LOG::INFO("Enable Debug Layer: {0}", rcast<void*>(debugController.Get())); } #endif Check(CreateDXGIFactory2(dxgiFactoryFlags, IID_PPV_ARGS(&dxgiFactory)), "Failed to create DXGI Factory"); device = std::make_unique<Device>(dxgiFactory); UnlimitedDevice = device.get(); for (size_t i = 0; i < SL_ARRAY_LENGTH(descriptorAllocators); i++) { descriptorAllocators[i].Init(device.get()); } shaderVisibleDescriptorAllocator.Init(device.get()); auto adaptorDesc = device->AdaptorDesc(); Super::UpdateMeta( Utils::ws2s(adaptorDesc.Description).c_str(), nullptr, nullptr ); auto hWnd = rcast<HWND>(desc.WindowHandle->Primitive()); { Queue::Description queueDesc{}; queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; queue = device->CreateQueue(queueDesc); } { Swapchain::Description swapchainDesc{}; CleanUpObject(&swapchainDesc); swapchainDesc.BufferCount = desc.FrameCount; swapchainDesc.Width = desc.Width; swapchainDesc.Height = desc.Height; swapchainDesc.Format = NORMALIZE(desc.format); swapchainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapchainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; swapchainDesc.SampleDesc.Count = 1; swapchainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; // swapchainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT; swapchain = std::make_unique<Swapchain>(dxgiFactory, queue->Handle(), hWnd, swapchainDesc); // swapchain->SetMaximumFrameLatency(desc.FrameCount); // swapchainWritableObject = swapchain->FrameLatencyWaitableObject(); } Check(dxgiFactory->MakeWindowAssociation(hWnd, DXGI_MWA_NO_ALT_ENTER)); { CheckDisplayHDRSupport(); color.enableST2084 = color.hdrSupport; EnsureSwapChainColorSpace(color.bitDepth, color.enableST2084); /* SetHDRMetaData( HDRMetaDataPool[color.hdrMetaDataPoolIdx][0], HDRMetaDataPool[color.hdrMetaDataPoolIdx][1], HDRMetaDataPool[color.hdrMetaDataPoolIdx][2], HDRMetaDataPool[color.hdrMetaDataPoolIdx][3] ); */ } { DescriptorPool::Description renderTargetViewDesc = { DescriptorPool::Type::RenderTargetView, desc.FrameCount, DescriptorPool::Flag::None, 1 }; renderTargetViewDescriptorHeap = std::make_unique<DescriptorPool>( device->Handle(), &renderTargetViewDesc ); renderTargetViewDescriptorSize = device->DescriptorHandleIncrementSize( renderTargetViewDesc.Type ); } CreateRenderTarget(); for (int i{0}; i < desc.FrameCount; i++) { commandAllocator[i] = queue->RequestCommandAllocator(); } commandList = std::make_unique<CommandList>( device.get(), CommandList::Type::Direct, commandAllocator[0] ); commandList->Close(); queue->Handle()->ExecuteCommandLists(1, (ID3D12CommandList **)commandList->AddressOf()); // Create synchronization objects and wait until assets have been uploaded to the GPU. { frameIndex = swapchain->AcquireCurrentBackBufferIndex(); device->CreateFence(&fence, fenceValues[frameIndex], D3D12_FENCE_FLAG_NONE); fenceValues[frameIndex]++; // Create an event handle to use for frame synchronization. fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); if (!fenceEvent) { Check(HRESULT_FROM_WIN32(GetLastError())); return; } const uint64_t fenceToWaitFor = fenceValues[frameIndex]; queue->Signal(fence, fenceToWaitFor); fenceValues[frameIndex]++; Check(fence->SetEventOnCompletion(fenceToWaitFor, fenceEvent)); WaitForSingleObject(fenceEvent, INFINITE); } #ifdef SLDEBUG device->Set("RenderContext::Device"); #endif } void RenderContext::CreateRenderTarget() { CPUDescriptor renderTargetViewDescriptor { renderTargetViewDescriptorHeap->StartOfCPU() }; for (UINT i = 0; i < desc.FrameCount; i++) { swapchain->AccessBackBuffer(i, &renderTargets[i]); device->CreateView(renderTargets[i], rcast<D3D12_RENDER_TARGET_VIEW_DESC *>(nullptr), renderTargetViewDescriptor); renderTargetViewDescriptor.Offset(1, renderTargetViewDescriptorSize); renderTargets[i]->SetName((std::wstring(L"Render Target{") + std::to_wstring(i) + std::wstring(L"}")).c_str()); } } inline int ComputeIntersectionArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { // (ax1, ay1) = left-top coordinates of A; (ax2, ay2) = right-bottom coordinates of A // (bx1, by1) = left-top coordinates of B; (bx2, by2) = right-bottom coordinates of B return std::max(0, std::min(ax2, bx2) - std::max(ax1, bx1)) * std::max(0, std::min(ay2, by2) - std::max(ay1, by1)); } void RenderContext::EnsureSwapChainColorSpace(Swapchain::BitDepth bitDepth, bool enableST2084) { DXGI_COLOR_SPACE_TYPE colorSpace = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709; switch (bitDepth) { case Swapchain::BitDepth::_8: color.rootConstants[DisplayCurve] = sRGB; break; case Swapchain::BitDepth::_10: colorSpace = enableST2084 ? DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020 : DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709; color.rootConstants[DisplayCurve] = enableST2084 ? ST2084 : sRGB; break; case Swapchain::BitDepth::_16: colorSpace = DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709; color.rootConstants[DisplayCurve] = None; break; default: break; } if (color.currentColorSpace != colorSpace) { UINT colorSpaceSupport = 0; if (swapchain->CheckColorSpaceSupport(colorSpace, &colorSpaceSupport) && ((colorSpaceSupport & DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG_PRESENT) == DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG_PRESENT)) { swapchain->Set(colorSpace); color.currentColorSpace = colorSpace; } } } void RenderContext::CheckDisplayHDRSupport() { if (dxgiFactory->IsCurrent() == false) { Check(CreateDXGIFactory2(0, IID_PPV_ARGS(&dxgiFactory))); } ComPtr<IDXGIAdapter1> dxgiAdapter; Check(dxgiFactory->EnumAdapters1(0, &dxgiAdapter)); UINT i = 0; ComPtr<IDXGIOutput> currentOutput; ComPtr<IDXGIOutput> bestOutput; float bestIntersectArea = -1; while (dxgiAdapter->EnumOutputs(i, &currentOutput) != DXGI_ERROR_NOT_FOUND) { int ax1 = windowBounds.left; int ay1 = windowBounds.top; int ax2 = windowBounds.right; int ay2 = windowBounds.bottom; DXGI_OUTPUT_DESC desc{}; Check(currentOutput->GetDesc(&desc)); RECT rect = desc.DesktopCoordinates; int bx1 = rect.left; int by1 = rect.top; int bx2 = rect.right; int by2 = rect.bottom; int intersectArea = ComputeIntersectionArea(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2); if (intersectArea > bestIntersectArea) { bestOutput = currentOutput; bestIntersectArea = ncast<float>(intersectArea); } i++; } ComPtr<IDXGIOutput6> output6; Check(bestOutput.As(&output6)); DXGI_OUTPUT_DESC1 desc1; Check(output6->GetDesc1(&desc1)); color.hdrSupport = (desc1.ColorSpace == DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020); } void RenderContext::SetHDRMetaData(float maxOutputNits, float minOutputNits, float maxCLL, float maxFALL) { if (!swapchain) { return; } if (!color.hdrSupport) { swapchain->Set(DXGI_HDR_METADATA_TYPE_NONE, 0, nullptr); return; } static const DisplayChromaticities displayChromaticityList[] = { { 0.64000f, 0.33000f, 0.30000f, 0.60000f, 0.15000f, 0.06000f, 0.31270f, 0.32900f }, // Display Gamut Rec709 { 0.70800f, 0.29200f, 0.17000f, 0.79700f, 0.13100f, 0.04600f, 0.31270f, 0.32900f }, // Display Gamut Rec2020 }; int selectedChroma{ 0 }; if (color.bitDepth == Swapchain::BitDepth::_16 && color.currentColorSpace == DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709) { selectedChroma = 0; } else if (color.bitDepth == Swapchain::BitDepth::_10 && color.currentColorSpace == DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020) { selectedChroma = 1; } else { swapchain->Set(DXGI_HDR_METADATA_TYPE_NONE, 0, nullptr); } const DisplayChromaticities &chroma = displayChromaticityList[selectedChroma]; DXGI_HDR_METADATA_HDR10 metaData{}; metaData.RedPrimary[0] = ncast<UINT16>(chroma.RedX * 50000.0f); metaData.RedPrimary[0] = ncast<UINT16>(chroma.RedX * 50000.0f); metaData.RedPrimary[1] = ncast<UINT16>(chroma.RedY * 50000.0f); metaData.GreenPrimary[0] = ncast<UINT16>(chroma.GreenX * 50000.0f); metaData.GreenPrimary[1] = ncast<UINT16>(chroma.GreenY * 50000.0f); metaData.BluePrimary[0] = ncast<UINT16>(chroma.BlueX * 50000.0f); metaData.BluePrimary[1] = ncast<UINT16>(chroma.BlueY * 50000.0f); metaData.WhitePoint[0] = ncast<UINT16>(chroma.WhiteX * 50000.0f); metaData.WhitePoint[1] = ncast<UINT16>(chroma.WhiteY * 50000.0f); metaData.MaxMasteringLuminance = ncast<UINT>(maxOutputNits * 10000.0f); metaData.MinMasteringLuminance = ncast<UINT>(minOutputNits * 10000.0f); metaData.MaxContentLightLevel = ncast<UINT16>(maxCLL); metaData.MaxFrameAverageLightLevel = ncast<UINT16>(maxFALL); swapchain->Set(DXGI_HDR_METADATA_TYPE_HDR10, sizeof(metaData), &metaData); } void RenderContext::CleanUpRenderTarget() { for (UINT i = 0; i < desc.FrameCount; i++) { if (renderTargets[i]) { renderTargets[i]->Release(); renderTargets[i] = nullptr; } } } void RenderContext::WaitForGPU() { // Schedule a Signal command in the queue. queue->Signal(fence, fenceValues[frameIndex]); // Wait until the fence has been processed. fence->SetEventOnCompletion(fenceValues[frameIndex], fenceEvent); WaitForSingleObjectEx(fenceEvent, INFINITE, FALSE); // Increment the fence value for the current frame. fenceValues[frameIndex]++; } UINT RenderContext::WaitForPreviousFrame() { // Schedule a Signal command in the queue. const UINT64 currentFenceValue = fenceValues[frameIndex]; queue->Signal(fence, currentFenceValue); // Update the frame index. frameIndex = swapchain->AcquireCurrentBackBufferIndex(); // If the next frame is not ready to be rendered yet, wait until it is ready. auto completedValue = fence->GetCompletedValue(); if (completedValue < fenceValues[frameIndex]) { Check(fence->SetEventOnCompletion(fenceValues[frameIndex], fenceEvent)); WaitForSingleObjectEx(fenceEvent, INFINITE, FALSE); } // Set the fence value for the next frame. fenceValues[frameIndex] = currentFenceValue + 1; return frameIndex; } void RenderContext::UpdateSwapchain(UINT width, UINT height) { if (!swapchain) { return; } WaitForGPU(); CleanUpRenderTarget(); DXGI_SWAP_CHAIN_DESC1 swapchainDesc{}; swapchain->Desc(&swapchainDesc); swapchain->ResizeBuffers( width, height, DXGI_FORMAT_UNKNOWN, swapchainDesc.Flags, desc.FrameCount ); EnsureSwapChainColorSpace(color.bitDepth, color.enableST2084); CreateRenderTarget(); } void RenderContext::WaitForNextFrameResources() { frameIndex = swapchain->AcquireCurrentBackBufferIndex(); HANDLE waitableObjects[] = { swapchainWritableObject, NULL }; DWORD numWaitableObjects = 1; UINT64 fenceValue = fenceValues[frameIndex]; if (fenceValue != 0) // means no fence was signaled { fenceValues[frameIndex] = 0; fence->SetEventOnCompletion(fenceValue, fenceEvent); waitableObjects[1] = fenceEvent; numWaitableObjects = 2; } WaitForMultipleObjects(numWaitableObjects, waitableObjects, TRUE, INFINITE); } void RenderContext::CopyDescriptorHeapToShaderVisible() { auto srcDescriptorAllocator = descriptorAllocators[U32(DescriptorPool::Type::ShaderResourceView)]; device->CopyDescriptors( srcDescriptorAllocator.CountOfDescriptor(), shaderVisibleDescriptorAllocator.FreeStartOfHeap(), srcDescriptorAllocator.StartOfHeap(), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ); } } }
31.572383
137
0.670076
QSXW
f015cd8f7d4f76500819b27551d6ae929fb9f087
11,675
cpp
C++
models/processor/zesto/ZCOMPS-bpred/bpred-tage.cpp
Basseuph/manifold
99779998911ed7e8b8ff6adacc7f93080409a5fe
[ "BSD-3-Clause" ]
8
2016-01-22T18:28:48.000Z
2021-05-07T02:27:21.000Z
models/processor/zesto/ZCOMPS-bpred/bpred-tage.cpp
Basseuph/manifold
99779998911ed7e8b8ff6adacc7f93080409a5fe
[ "BSD-3-Clause" ]
3
2016-04-15T02:58:58.000Z
2017-01-19T17:07:34.000Z
models/processor/zesto/ZCOMPS-bpred/bpred-tage.cpp
Basseuph/manifold
99779998911ed7e8b8ff6adacc7f93080409a5fe
[ "BSD-3-Clause" ]
10
2015-12-11T04:16:55.000Z
2019-05-25T20:58:13.000Z
/* bpred-tage.cpp: TAgged GEometric-history length predictor [Seznec and Michaud, JILP 2006] */ /* * __COPYRIGHT__ GT */ #define COMPONENT_NAME "tage" #ifdef BPRED_PARSE_ARGS if(!strcasecmp(COMPONENT_NAME,type)) { int num_tables; int bim_size; int table_size; int tag_width; int first_length; int last_length; if(sscanf(opt_string,"%*[^:]:%[^:]:%d:%d:%d:%d:%d:%d",name,&num_tables,&bim_size,&table_size,&tag_width,&first_length,&last_length) != 7) fatal("bad bpred options string %s (should be \"tage:name:num-tables:bim-size:table-size:tag-width:first-hist-length:last-hist-length\")",opt_string); return new bpred_tage_t(name,num_tables,bim_size,table_size,tag_width,first_length,last_length); } #else #include <math.h> class bpred_tage_t:public bpred_dir_t { #define TAGE_MAX_HIST 512 #define TAGE_MAX_TABLES 16 typedef qword_t bpred_tage_hist_t[8]; /* Max length: 8 * 64 = 512 */ struct bpred_tage_ent_t { int tag; char ctr; char u; }; class bpred_tage_sc_t:public bpred_sc_t { public: my2bc_t * current_ctr; bpred_tage_hist_t lookup_bhr; int index[TAGE_MAX_TABLES]; int provider; int provpred; int alt; int altpred; int used_alt; int provnew; }; private: inline void bpred_tage_hist_update(bpred_tage_hist_t H, int outcome) { H[7] <<= 1; H[7] |= (H[6]>>63)&1; H[6] <<= 1; H[6] |= (H[5]>>63)&1; H[5] <<= 1; H[5] |= (H[4]>>63)&1; H[4] <<= 1; H[4] |= (H[3]>>63)&1; H[3] <<= 1; H[3] |= (H[2]>>63)&1; H[2] <<= 1; H[2] |= (H[1]>>63)&1; H[1] <<= 1; H[1] |= (H[0]>>63)&1; H[0] <<= 1; H[0] |= outcome&1; } inline void bpred_tage_hist_copy(bpred_tage_hist_t D /*dest*/, bpred_tage_hist_t S /*src*/) { D[0] = S[0]; D[1] = S[1]; D[2] = S[2]; D[3] = S[3]; D[4] = S[4]; D[5] = S[5]; D[6] = S[6]; D[7] = S[7]; } int bpred_tage_hist_hash(bpred_tage_hist_t H, int hist_length, int hash_length) { int result = 0; int i; int mask = (1<<hash_length)-1; int row=0; int pos=0; for(i=0;i<hist_length/hash_length;i++) { result ^= (H[row]>>pos) & mask; if(pos+hash_length > 64) /* wrap past end of current qword_t */ { row++; pos = (pos+hash_length)&63; result ^= (H[row]<<(hash_length-pos))&mask; } else /* includes when pos+HL is exactly 64 */ { pos = pos+hash_length; if(pos > 63) { pos &=63; row++; } } } return result; } protected: int num_tables; int table_size; int log_size; int table_mask; int tag_width; int tag_mask; int bim_size; int bim_mask; int alpha; int * Hlen; /* array of history lengths */ struct bpred_tage_ent_t **T; int pwin; zcounter_t * Tuses; bpred_tage_hist_t bhr; public: /* CREATE */ bpred_tage_t(char * const arg_name, const int arg_num_tables, const int arg_bim_size, const int arg_table_size, const int arg_tag_width, const int arg_first_length, const int arg_last_length ) { init(); int i; /* verify arguments are valid */ CHECK_PPOW2(arg_bim_size); CHECK_PPOW2(arg_table_size); CHECK_POS(arg_num_tables); CHECK_POS(arg_tag_width); CHECK_POS(arg_first_length); CHECK_POS(arg_last_length); CHECK_POS_GT(arg_last_length,arg_first_length); CHECK_POS_LT(arg_num_tables,TAGE_MAX_TABLES); CHECK_POS_LEQ(arg_last_length,TAGE_MAX_HIST); for(i=0;i<8;i++) bhr[i] = 0; name = strdup(arg_name); if(!name) fatal("couldn't malloc tage name (strdup)"); type = strdup(COMPONENT_NAME); if(!type) fatal("couldn't malloc tage type (strdup)"); num_tables = arg_num_tables; table_size = arg_table_size; table_mask = arg_table_size-1; log_size = log_base2(arg_table_size); bim_size = arg_bim_size; bim_mask = arg_bim_size-1; double logA = (log(arg_last_length) - log(arg_first_length)) / ((double)arg_num_tables - 2.0); alpha = (int) exp(logA); Hlen = (int*) calloc(arg_num_tables,sizeof(*Hlen)); if(!Hlen) fatal("couldn't calloc Hlen array"); /* Hlen[0] = 0; set by calloc, for 2bc */ for(i=1;i<num_tables-1;i++) Hlen[i] = (int)floor(arg_first_length * pow(alpha,i-1) + 0.5); Hlen[i] = arg_last_length; T = (struct bpred_tage_ent_t**) calloc(num_tables,sizeof(*T)); if(!T) fatal("couldn't calloc tage T array"); tag_width = arg_tag_width; tag_mask = (1<<arg_tag_width)-1; for(i=0;i<num_tables;i++) { if(i>0) { T[i] = (struct bpred_tage_ent_t*) calloc(table_size,sizeof(**T)); if(!T[i]) fatal("couldn't calloc tage T[%d]",i); for(int j=0;j<table_size;j++) { T[i][j].tag = 0; T[i][j].ctr = 4; /* weakly taken */ } } else /* T0 */ { T[i] = (struct bpred_tage_ent_t*) calloc(bim_size,sizeof(**T)); if(!T[i]) fatal("couldn't calloc tage T[%d]",i); for(int j=0;j<bim_size;j++) T[i][j].ctr = MY2BC_WEAKLY_TAKEN; /* weakly taken */ } } Tuses = (zcounter_t*) calloc(num_tables,sizeof(*Tuses)); if(!Tuses) fatal("failed to calloc Tuses"); pwin = 15; bits = bim_size*2 /*2bc*/ + (num_tables-1)*(2/*u*/+3/*ctr*/+tag_width)*table_size + arg_last_length + 4/*use altpred?*/; } /* DESTROY */ ~bpred_tage_t() { free(Tuses); Tuses = NULL; for(int i=0;i<num_tables;i++) { free(T[i]); T[i] = NULL; } free(T); T = NULL; free(Hlen); Hlen = NULL; } /* LOOKUP */ BPRED_LOOKUP_HEADER { class bpred_tage_sc_t * sc = (class bpred_tage_sc_t*) scvp; for(int i=0;i<num_tables;i++) { if(i==0) sc->index[i] = PC; else sc->index[i] = PC^bpred_tage_hist_hash(bhr,Hlen[i],log_size); } sc->provider = 0; sc->provpred = 0; sc->altpred = 0; sc->provnew = false; int hit = false; int pwin_hit = false; for(int i=num_tables-1;i>0;i--) { struct bpred_tage_ent_t * ent = &T[i][sc->index[i]&table_mask]; if(((unsigned)ent->tag) == (PC&tag_mask)) { sc->provnew = !ent->u && ((ent->ctr==4) || (ent->ctr==3)); if((pwin < 8) || !sc->provnew) pwin_hit = true; sc->provpred = (ent->ctr >= 4); hit = true; sc->provider = i; break; } } sc->alt = -1; if(hit) { for(int i=sc->provider-1;i>0;i--) { struct bpred_tage_ent_t * ent = &T[i][sc->index[i]&table_mask]; if((unsigned)ent->tag == (PC&tag_mask)) { sc->altpred = (ent->ctr >= 4); sc->alt = i; break; } } } if(sc->alt == -1) { sc->altpred = MY2BC_DIR(T[0][sc->index[0]&bim_mask].ctr); sc->alt = 0; } sc->updated = false; BPRED_STAT(lookups++;) bpred_tage_hist_copy(sc->lookup_bhr,bhr); if(!pwin_hit) { sc->used_alt = true; return sc->altpred; } else { sc->used_alt = false; return sc->provpred; } } /* UPDATE */ BPRED_UPDATE_HEADER { class bpred_tage_sc_t * sc = (class bpred_tage_sc_t*) scvp; if(!sc->updated) { BPRED_STAT(updates++;) BPRED_STAT(num_hits += our_pred == outcome;) if(sc->used_alt) Tuses[sc->alt]++; else { assert(sc->provider); Tuses[sc->provider]++; } if(sc->provnew) { if(sc->altpred != sc->provpred) { if(sc->altpred == outcome) { if(pwin < 15) pwin++; } else { if(pwin > 0) pwin--; } } } /* Allocate new entry if needed */ if(our_pred != outcome) /* mispred */ { if(sc->provider < (num_tables-1)) /* not already using longest history */ { int allocated = 0; int allocated2 = 0; for(int i=sc->provider+1;i<num_tables;i++) { if(T[i][sc->index[i]&table_mask].u == 0) { if(!allocated) allocated = i; else { allocated2 = i; break; } } } if(allocated) { if(allocated2) /* more than one choice */ { if((random() & 0xffff) > 21845) /* choose allocated over allocated2 with 2:1 probability */ allocated = allocated2; } struct bpred_tage_ent_t * ent = &T[allocated][sc->index[allocated]&table_mask]; ent->u = 0; ent->ctr = 3+outcome; ent->tag = PC & tag_mask; } else { for(int i=sc->provider+1;i<num_tables;i++) if(T[i][sc->index[i]&table_mask].u > 0) T[i][sc->index[i]&table_mask].u --; } } } /* perioidic reset of ubits */ if((updates & ((1<<18)-1)) == 0) { int mask = ~1; if(updates & (1<<18)) /* alternate reset msb and lsb */ mask = ~2; for(int i=1;i<num_tables;i++) { for(int j=0;j<table_size;j++) T[i][j].u &= mask; } } /* update provider component */ if((sc->provider == 0) || ((sc->alt == 0) && (sc->used_alt))) MY2BC_UPDATE(T[0][sc->index[0]&bim_mask].ctr,outcome); else { if(outcome) { if(T[sc->provider][sc->index[sc->provider]&table_mask].ctr < 7) T[sc->provider][sc->index[sc->provider]&table_mask].ctr ++; } else { if(T[sc->provider][sc->index[sc->provider]&table_mask].ctr > 0) T[sc->provider][sc->index[sc->provider]&table_mask].ctr --; } } /* update u counter: inc if correct and different than altpred */ if(sc->provpred != sc->altpred) { if(sc->provpred == outcome) { if(T[sc->provider][sc->index[sc->provider]&table_mask].u < 3) T[sc->provider][sc->index[sc->provider]&table_mask].u ++; } else { if(T[sc->provider][sc->index[sc->provider]&table_mask].u > 0) T[sc->provider][sc->index[sc->provider]&table_mask].u --; } } sc->updated = true; } } /* SPEC UPDATE */ BPRED_SPEC_UPDATE_HEADER { BPRED_STAT(spec_updates++;) bpred_tage_hist_update(bhr,our_pred); } BPRED_RECOVER_HEADER { class bpred_tage_sc_t * sc = (class bpred_tage_sc_t*) scvp; bpred_tage_hist_copy(bhr,sc->lookup_bhr); bpred_tage_hist_update(bhr,outcome); } BPRED_FLUSH_HEADER { class bpred_tage_sc_t * sc = (class bpred_tage_sc_t*) scvp; bpred_tage_hist_copy(bhr,sc->lookup_bhr); } /* REG_STATS */ BPRED_REG_STATS_HEADER { bpred_dir_t::reg_stats(sdb,core); int id = core?core->current_thread->id:0; for(int i=0;i<num_tables;i++) { char buf[256]; char buf2[256]; sprintf(buf,"c%d.%s.uses%d",id,name,i); sprintf(buf2,"predictions made with %s's T[%d]",name,i); stat_reg_counter(sdb, true, buf, buf2, &Tuses[i], 0, NULL); } } /* GETCACHE */ BPRED_GET_CACHE_HEADER { class bpred_tage_sc_t * sc = new bpred_tage_sc_t(); if(!sc) fatal("couldn't malloc tage State Cache"); return sc; } }; #endif /* BPRED_PARSE_ARGS */ #undef COMPONENT_NAME
23.92418
154
0.53439
Basseuph
f01900af12de7167295f7738f8636d6c75b1ce11
8,180
cc
C++
src/server/DataBase.cc
ryan-rao/LTFS-Data-Management
041960282d20aeefb8da20eabf04367a164a5903
[ "Apache-2.0" ]
19
2018-06-28T03:53:41.000Z
2022-03-15T16:17:33.000Z
src/server/DataBase.cc
ryan-rao/LTFS-Data-Management
041960282d20aeefb8da20eabf04367a164a5903
[ "Apache-2.0" ]
13
2018-04-25T15:40:14.000Z
2021-01-18T11:03:27.000Z
src/server/DataBase.cc
ryan-rao/LTFS-Data-Management
041960282d20aeefb8da20eabf04367a164a5903
[ "Apache-2.0" ]
8
2018-08-08T05:40:31.000Z
2022-03-22T16:21:06.000Z
/******************************************************************************* * Copyright 2018 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. * *******************************************************************************/ #include "ServerIncludes.h" DataBase DB; std::mutex DataBase::trans_mutex; DataBase::~DataBase() { if (dbNeedsClosed) sqlite3_close(db); sqlite3_shutdown(); } void DataBase::cleanup() { unlink(Const::DB_FILE.c_str()); unlink((Const::DB_FILE + "-journal").c_str()); } void DataBase::fits(sqlite3_context *ctx, int argc, sqlite3_value **argv) { assert(argc == 5); unsigned long size = sqlite3_value_int64(argv[1]); unsigned long *free = (unsigned long *) sqlite3_value_int64(argv[2]); unsigned long *num_found = (unsigned long *) sqlite3_value_int64(argv[3]); unsigned long *total = (unsigned long *) sqlite3_value_int64(argv[4]); if (*free >= size) { *free -= size; (*total)++; (*num_found)++; sqlite3_result_int(ctx, 1); } else { (*total)++; sqlite3_result_int(ctx, 0); } } void DataBase::open(bool dbUseMemory) { int rc; std::string sql; std::string uri; if (dbUseMemory) uri = "file::memory:"; else uri = std::string("file:") + Const::DB_FILE; rc = sqlite3_config(SQLITE_CONFIG_URI, 1); if (rc != SQLITE_OK) { TRACE(Trace::error, rc); errno = rc; THROW(Error::GENERAL_ERROR, uri, rc); } rc = sqlite3_initialize(); if (rc != SQLITE_OK) { TRACE(Trace::error, rc); errno = rc; THROW(Error::GENERAL_ERROR, rc); } rc = sqlite3_open_v2(uri.c_str(), &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_SHAREDCACHE | SQLITE_OPEN_EXCLUSIVE, NULL); if (rc != SQLITE_OK) { TRACE(Trace::error, rc, uri); errno = rc; THROW(Error::GENERAL_ERROR, uri, rc); } rc = sqlite3_extended_result_codes(db, 1); if (rc != SQLITE_OK) { TRACE(Trace::error, rc); errno = rc; THROW(Error::GENERAL_ERROR, rc); } dbNeedsClosed = true; sqlite3_create_function(db, "FITS", 5, SQLITE_UTF8, NULL, &DataBase::fits, NULL, NULL); } void DataBase::createTables() { SQLStatement stmt; stmt(DataBase::CREATE_JOB_QUEUE); stmt.doall(); stmt(DataBase::CREATE_REQUEST_QUEUE); stmt.doall(); } std::string DataBase::opStr(DataBase::operation op) { switch (op) { case MOUNT: return ltfsdm_messages[LTFSDMX0078I]; case UNMOUNT: return ltfsdm_messages[LTFSDMX0079I]; case TRARECALL: return ltfsdm_messages[LTFSDMX0015I]; case SELRECALL: return ltfsdm_messages[LTFSDMX0014I]; case MIGRATION: return ltfsdm_messages[LTFSDMX0013I]; case FORMAT: return ltfsdm_messages[LTFSDMX0081I]; case CHECK: return ltfsdm_messages[LTFSDMX0082I]; case MOVE: return ltfsdm_messages[LTFSDMX0087I]; default: return ""; } } std::string DataBase::reqStateStr(DataBase::req_state reqs) { switch (reqs) { case REQ_NEW: return ltfsdm_messages[LTFSDMX0016I]; case REQ_INPROGRESS: return ltfsdm_messages[LTFSDMX0017I]; case REQ_COMPLETED: return ltfsdm_messages[LTFSDMX0018I]; default: return ""; } } int DataBase::lastUpdates() { return sqlite3_changes(db); } SQLStatement& SQLStatement::operator()(std::string _fmtstr) { fmtstr = _fmtstr; try { fmt = boost::format(fmtstr); } catch (const std::exception& e) { MSG(LTFSDMS0102E); THROW(Error::GENERAL_ERROR, e.what(), fmtstr); } return *this; } void SQLStatement::prepare() { int rc; rc = sqlite3_prepare_v2(DB.getDB(), fmt.str().c_str(), -1, &stmt, NULL); if (rc != SQLITE_OK) { TRACE(Trace::error, fmt.str(), rc); errno = rc; THROW(Error::GENERAL_ERROR, rc); } } std::string SQLStatement::encode(std::string s) { std::string enc; for (char c : s) { switch (c) { case 0047: enc += "\\0047"; break; case 0134: enc += "\\0134"; break; default: enc += c; } } return enc; } std::string SQLStatement::decode(std::string s) { unsigned long pos = s.size(); while ((pos = s.rfind("\\", pos)) != std::string::npos) { if (s.compare(pos, 5, "\\0047") == 0) { s.replace(pos, 5, std::string(1, 0047)); } else if (s.compare(pos, 5, "\\0134") == 0) { s.replace(pos, 5, std::string(1, 0134)); } else { THROW(Error::GENERAL_ERROR, s); } pos--; } return s; } void SQLStatement::getColumn(int *result, int column) { *result = sqlite3_column_int(stmt, column); } void SQLStatement::getColumn(unsigned int *result, int column) { *result = static_cast<unsigned int>(sqlite3_column_int(stmt, column)); } void SQLStatement::getColumn(DataBase::operation *result, int column) { *result = static_cast<DataBase::operation>(sqlite3_column_int(stmt, column)); } void SQLStatement::getColumn(DataBase::req_state *result, int column) { *result = static_cast<DataBase::req_state>(sqlite3_column_int(stmt, column)); } void SQLStatement::getColumn(FsObj::file_state *result, int column) { *result = static_cast<FsObj::file_state>(sqlite3_column_int(stmt, column)); } void SQLStatement::getColumn(long *result, int column) { *result = sqlite3_column_int64(stmt, column); } void SQLStatement::getColumn(unsigned long *result, int column) { *result = static_cast<unsigned long>(sqlite3_column_int64(stmt, column)); } void SQLStatement::getColumn(unsigned long long *result, int column) { *result = static_cast<unsigned long long>(sqlite3_column_int64(stmt, column)); } void SQLStatement::getColumn(std::string *result, int column) { const char *column_ctr = reinterpret_cast<const char*>(sqlite3_column_text( stmt, column)); if (column_ctr != NULL) *result = decode(std::string(column_ctr)); else *result = ""; } std::string SQLStatement::str() { std::string str; try { str = fmt.str(); } catch (const std::exception& e) { MSG(LTFSDMS0102E); THROW(Error::GENERAL_ERROR, e.what(), fmtstr); } return str; } void SQLStatement::bind(int num, int value) { int rc; if ((rc = sqlite3_bind_int(stmt, num, value)) != SQLITE_OK) { TRACE(Trace::error, rc); errno = rc; THROW(Error::GENERAL_ERROR, rc); } } void SQLStatement::bind(int num, std::string value) { int rc; if ((rc = sqlite3_bind_text(stmt, num, value.c_str(), value.size(), 0)) != SQLITE_OK) { TRACE(Trace::error, rc); errno = rc; THROW(Error::GENERAL_ERROR, rc); } } void SQLStatement::finalize() { if (stmt_rc != SQLITE_ROW && stmt_rc != SQLITE_DONE) { TRACE(Trace::error, fmt.str(), stmt_rc); errno = stmt_rc; THROW(Error::GENERAL_ERROR, stmt_rc); } int rc = sqlite3_finalize(stmt); if (rc != SQLITE_OK) { TRACE(Trace::error, fmt.str(), rc); errno = rc; THROW(Error::GENERAL_ERROR, rc); } } void SQLStatement::doall() { prepare(); step(); finalize(); }
22.349727
81
0.590098
ryan-rao
f01e5468ec34fc81f5bfb7f0da1d4d62e9107d7c
387
cpp
C++
leetcode/two-pointer/11.container-with-most-water.cpp
saurabhraj042/dsaPrep
0973a03bc565a2850003c7e48d99b97ff83b1d01
[ "MIT" ]
23
2021-10-30T04:11:52.000Z
2021-11-27T09:16:18.000Z
leetcode/two-pointer/11.container-with-most-water.cpp
Pawanupadhyay10/placement-prep
0449fa7cbc56e7933e6b090936ab7c15ca5f290f
[ "MIT" ]
null
null
null
leetcode/two-pointer/11.container-with-most-water.cpp
Pawanupadhyay10/placement-prep
0449fa7cbc56e7933e6b090936ab7c15ca5f290f
[ "MIT" ]
4
2021-10-30T03:26:05.000Z
2021-11-14T12:15:04.000Z
// saurabhraj042 class Solution { public: int maxArea(vector<int>& A) { int i = 0,j = A.size()-1; int mx = j * min( A[i],A[j] ); while( i < j ) { if( (j-i) * min( A[j],A[i] ) > mx) mx=(j-i)*min(A[j],A[i]); if( A[i] < A[j]) i++; else j--; } return mx; } };
19.35
46
0.330749
saurabhraj042
f01f9b2b18a3d97fdf502b9b2fde13cba6e1418a
849
cpp
C++
Source/PluginPostEffects_Core1/Exports.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
3
2019-04-12T15:22:53.000Z
2022-01-05T02:59:56.000Z
Source/PluginPostEffects_Core1/Exports.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
null
null
null
Source/PluginPostEffects_Core1/Exports.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
2
2019-04-10T22:46:21.000Z
2020-05-27T16:21:37.000Z
#define DLL_EXPORT #include "Exports.h" #include "Plugins/IPostEffectFactory.h" #include "Factories.h" namespace Core { namespace Plugin { CPostEffectFactory_Bloom* Bloom = nullptr; CPostEffectFactory_Hdr* Hdr = nullptr; CPostEffectFactory_MotionBlur* MotionBlur = nullptr; CPostEffectFactory_SSAO* Ssao = nullptr; extern "C" { DECLDIR void GetFactories(Vector<IPostEffectFactory*>& list) { Bloom = new CPostEffectFactory_Bloom(); if(Bloom) list.push_back(Bloom); Hdr = new CPostEffectFactory_Hdr(); if(Hdr) list.push_back(Hdr); MotionBlur = new CPostEffectFactory_MotionBlur(); if(MotionBlur) list.push_back(MotionBlur); Ssao = new CPostEffectFactory_SSAO(); if(Ssao) list.push_back(Ssao); } DECLDIR E_PLUGIN GetPluginType(void) { return Core::Plugin::EP_POSTEFFECT; } } } }
19.295455
62
0.720848
shanefarris
f020af42a32e14a0c8a88f5f7986e92a282436ca
376
cpp
C++
moosh/src/msg_handler.cpp
mujido/moove
380fd0ea2eb2ad59b62a27bb86079ecb8c5b783b
[ "Apache-2.0" ]
null
null
null
moosh/src/msg_handler.cpp
mujido/moove
380fd0ea2eb2ad59b62a27bb86079ecb8c5b783b
[ "Apache-2.0" ]
null
null
null
moosh/src/msg_handler.cpp
mujido/moove
380fd0ea2eb2ad59b62a27bb86079ecb8c5b783b
[ "Apache-2.0" ]
null
null
null
#include "msg_handler.hpp" #include <iostream> void MessageHandler::error(const std::string& msg, unsigned lineNum) { std::cerr << "Error, line " << lineNum + m_lineOffset << ": " << msg << std::endl; } void MessageHandler::warning(const std::string& msg, unsigned lineNum) { std::cerr << "Warning, line " << lineNum + m_lineOffset << ": " << msg << std::endl; }
25.066667
87
0.638298
mujido
f0226c78fa7c6e4f85aedf840418a5f8df8a9b15
10,309
cpp
C++
HaloTAS/TASDLL/tas_hooks.cpp
s3anyboy/HaloTAS
9584786f19e1475399298fda2d5783d47623cccd
[ "MIT" ]
6
2019-09-10T19:47:04.000Z
2020-11-26T08:32:36.000Z
HaloTAS/TASDLL/tas_hooks.cpp
s3anyboy/HaloTAS
9584786f19e1475399298fda2d5783d47623cccd
[ "MIT" ]
13
2018-11-24T09:37:49.000Z
2021-10-22T02:29:11.000Z
HaloTAS/TASDLL/tas_hooks.cpp
s3anyboy/HaloTAS
9584786f19e1475399298fda2d5783d47623cccd
[ "MIT" ]
3
2020-07-28T09:19:14.000Z
2020-09-02T04:48:49.000Z
#include "tas_hooks.h" #include "tas_logger.h" #include "tas_input_handler.h" #include "randomizer.h" #include "halo_engine.h" #include "render_d3d9.h" // Function Defs typedef HRESULT(__stdcall* GetDeviceState_t)(LPDIRECTINPUTDEVICE*, DWORD, LPVOID*); typedef HRESULT(__stdcall* GetDeviceData_t)(LPDIRECTINPUTDEVICE*, DWORD, LPDIDEVICEOBJECTDATA, LPDWORD, DWORD); typedef void(__cdecl* SimulateTick_t)(int); typedef char(__cdecl* AdvanceFrame_t)(float); typedef int(__cdecl* BeginLoop_t)(); typedef void(__cdecl* GetMouseKeyboardGamepadInput_t)(); typedef void(__cdecl* AdvanceEffectsTimer_t)(float); typedef HRESULT(__stdcall* D3D9BeginScene_t)(IDirect3DDevice9* pDevice); typedef HRESULT(__stdcall* D3D9EndScene_t)(IDirect3DDevice9* pDevice); typedef HRESULT(__stdcall* D3D9Present_t)(IDirect3DDevice9* pDevice, const RECT*, const RECT*, HWND, RGNDATA*); // Declarations HRESULT __stdcall hkGetDeviceState(LPDIRECTINPUTDEVICE* pDevice, DWORD cbData, LPVOID* lpvData); HRESULT __stdcall hkGetDeviceData(LPDIRECTINPUTDEVICE* pDevice, DWORD cbObjectData, LPDIDEVICEOBJECTDATA rgdod, LPDWORD pdwInOut, DWORD dwFlags); void __cdecl hkSimulateTick(int); char __cdecl hkAdvanceFrame(float); int __cdecl hkBeginLoop(); void __cdecl hkGetMouseKeyboardGamepadInput(); void __cdecl hkAdvanceEffectsTimer(float); HRESULT __stdcall hkD3D9EndScene(IDirect3DDevice9* pDevice); HRESULT __stdcall hkD3D9BeginScene(IDirect3DDevice9* pDevice); HRESULT __stdcall hkD3D9Present(IDirect3DDevice9* pDevice, const RECT* pSourceRect, const RECT* pDestRect, HWND hDestWindowOverride, RGNDATA* pDirtyRegion); // Store original pointers to old functions GetDeviceState_t originalGetDeviceState; GetDeviceData_t originalGetDeviceData; SimulateTick_t originalSimulateTick = (SimulateTick_t)(0x45B780); AdvanceFrame_t originalAdvanceFrame = (AdvanceFrame_t)(0x470BF0); BeginLoop_t originalBeginLoop = (BeginLoop_t)(0x4C6E80); AdvanceEffectsTimer_t originalAdvanceEffectsTimer = (AdvanceEffectsTimer_t)(0x45b4f0); GetMouseKeyboardGamepadInput_t originalGetMouseKeyboardGamepadInput = (GetMouseKeyboardGamepadInput_t)(0x490760); D3D9EndScene_t originalD3D9EndScene; D3D9BeginScene_t originalD3D9BeginScene; D3D9Present_t originalD3D9Present; void tas_hooks::detours_error(LONG detourResult) { if (detourResult != NO_ERROR) { throw; } } void tas_hooks::hook_function(PVOID* originalFunc, PVOID replacementFunc) { DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); detours_error(DetourAttach(originalFunc, replacementFunc)); detours_error(DetourTransactionCommit()); } void tas_hooks::unhook_function(PVOID* originalFunc, PVOID replacementFunc) { DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourDetach(originalFunc, replacementFunc); DetourTransactionCommit(); } void tas_hooks::hook_dinput8() { // DIRECTINPUT8 LPDIRECTINPUT8 pDI8; DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&pDI8, NULL); if (!pDI8) { tas_logger::fatal("Couldn't get dinput8 handle."); exit(1); } LPDIRECTINPUTDEVICE8 pDI8Dev = nullptr; pDI8->CreateDevice(GUID_SysKeyboard, &pDI8Dev, NULL); if (!pDI8Dev) { pDI8->Release(); tas_logger::fatal("Couldn't create dinput8 device."); exit(1); } void** dinputVTable = *reinterpret_cast<void***>(pDI8Dev); originalGetDeviceState = (GetDeviceState_t)(dinputVTable[9]); originalGetDeviceData = (GetDeviceData_t)(dinputVTable[10]); pDI8Dev->Release(); pDI8->Release(); hook_function(&(PVOID&)originalGetDeviceState, hkGetDeviceState); hook_function(&(PVOID&)originalGetDeviceData, hkGetDeviceData); } void tas_hooks::hook_d3d9() { IDirect3D9* pD3D = Direct3DCreate9(D3D_SDK_VERSION); if (!pD3D) { tas_logger::fatal("Couldn't get d3d9 handle."); exit(1); } int mainMonitorX = GetSystemMetrics(SM_CXSCREEN); int mainMonitorY = GetSystemMetrics(SM_CYSCREEN); D3DPRESENT_PARAMETERS d3dpp = { 0 }; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.hDeviceWindow = GetForegroundWindow(); d3dpp.Windowed = TRUE; d3dpp.BackBufferCount = 1; d3dpp.BackBufferWidth = std::clamp(mainMonitorX, 800, 8000); d3dpp.BackBufferHeight = std::clamp(mainMonitorY, 600, 8000); IDirect3DDevice9* dummyD3D9Device = nullptr; pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, d3dpp.hDeviceWindow, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &dummyD3D9Device); if (!dummyD3D9Device) { pD3D->Release(); tas_logger::fatal("Couldn't create dummy d3d9 device."); exit(1); } void** d3d9VTable = *reinterpret_cast<void***>(dummyD3D9Device); #if _DEBUG // Breakpoint to find additional D3D functions if needed // Make sure symbols are loaded for (int i = 0; i < 180; i++) { auto funcPtr = d3d9VTable[i]; } #endif originalD3D9BeginScene = (D3D9BeginScene_t)(d3d9VTable[41]); hook_function(&(PVOID&)originalD3D9BeginScene, hkD3D9BeginScene); originalD3D9EndScene = (D3D9EndScene_t)(d3d9VTable[42]); hook_function(&(PVOID&)originalD3D9EndScene, hkD3D9EndScene); originalD3D9Present = (D3D9Present_t)(d3d9VTable[17]); hook_function(&(PVOID&)originalD3D9Present, hkD3D9Present); dummyD3D9Device->Release(); pD3D->Release(); } void tas_hooks::hook_halo_engine() { hook_function(&(PVOID&)originalSimulateTick, hkSimulateTick); hook_function(&(PVOID&)originalAdvanceFrame, hkAdvanceFrame); hook_function(&(PVOID&)originalBeginLoop, hkBeginLoop); hook_function(&(PVOID&)originalGetMouseKeyboardGamepadInput, hkGetMouseKeyboardGamepadInput); hook_function(&(PVOID&)originalAdvanceEffectsTimer, hkAdvanceEffectsTimer); } void tas_hooks::attach_all() { hook_dinput8(); hook_d3d9(); hook_halo_engine(); } void tas_hooks::detach_all() { unhook_function(&(PVOID&)originalGetDeviceState, hkGetDeviceState); unhook_function(&(PVOID&)originalGetDeviceData, hkGetDeviceData); unhook_function(&(PVOID&)originalSimulateTick, hkSimulateTick); unhook_function(&(PVOID&)originalAdvanceFrame, hkAdvanceFrame); unhook_function(&(PVOID&)originalBeginLoop, hkBeginLoop); unhook_function(&(PVOID&)originalGetMouseKeyboardGamepadInput, hkGetMouseKeyboardGamepadInput); unhook_function(&(PVOID&)originalAdvanceEffectsTimer, hkAdvanceEffectsTimer); unhook_function(&(PVOID&)originalD3D9EndScene, hkD3D9EndScene); unhook_function(&(PVOID&)originalD3D9BeginScene, hkD3D9BeginScene); unhook_function(&(PVOID&)originalD3D9Present, hkD3D9Present); } /* HOOKED FUNCTIONS */ static int32_t pressedMouseTick = 0; static bool btn_down[3] = { false, false, false }; static bool btn_queued[3] = { false, false, false }; HRESULT __stdcall hkGetDeviceState(LPDIRECTINPUTDEVICE* lpDevice, DWORD cbData, LPVOID* lpvData) // Mouse { HRESULT hResult = DI_OK; hResult = originalGetDeviceState(lpDevice, cbData, lpvData); return hResult; } static bool tab_down = false; static bool enter_down = false; static bool g_down = false; static DWORD lastsequence = 0; static int32_t pressedTick = 0; static bool enterPreviousFrame = false; static int32_t enterPressedFrame = 0; static bool queuedEnter = false; static bool queuedTab = false; static bool queuedG = false; HRESULT __stdcall hkGetDeviceData(LPDIRECTINPUTDEVICE* pDevice, DWORD cbObjectData, LPDIDEVICEOBJECTDATA rgdod, LPDWORD pdwInOut, DWORD dwFlags) // Keyboard { HRESULT hResult = DI_OK; auto& inputHandler = tas_input_handler::get(); if (inputHandler.this_tick_enter() && pressedTick != inputHandler.get_current_playback_tick()) { queuedEnter = true; } if (inputHandler.this_tick_tab() && pressedTick != inputHandler.get_current_playback_tick()) { queuedTab = true; } if (inputHandler.this_tick_g() && pressedTick != inputHandler.get_current_playback_tick()) { queuedG = true; } pressedTick = inputHandler.get_current_playback_tick(); if (queuedEnter) { if (enter_down) { rgdod->dwData = 0x80; } else { rgdod->dwData = 0x00; queuedEnter = false; } rgdod->dwOfs = DIK_RETURN; rgdod->dwTimeStamp = GetTickCount(); rgdod->dwSequence = ++lastsequence; enter_down = !enter_down; return hResult; } if (queuedTab) { if (tab_down) { rgdod->dwData = 0x80; } else { rgdod->dwData = 0x00; queuedTab = false; } rgdod->dwOfs = DIK_TAB; rgdod->dwTimeStamp = GetTickCount(); rgdod->dwSequence = ++lastsequence; tab_down = !tab_down; return hResult; } if (queuedG) { if (g_down) { rgdod->dwData = 0x80; } else { rgdod->dwData = 0x00; queuedG = false; } rgdod->dwOfs = DIK_G; rgdod->dwTimeStamp = GetTickCount(); rgdod->dwSequence = ++lastsequence; g_down = !g_down; return hResult; } hResult = originalGetDeviceData(pDevice, cbObjectData, rgdod, pdwInOut, dwFlags); return hResult; } void hkSimulateTick(int ticksAfterThis) { auto& gInputHandler = tas_input_handler::get(); auto& gRandomizer = randomizer::get(); auto& gEngine = halo_engine::get(); gRandomizer.pre_tick(); gInputHandler.pre_tick(); originalSimulateTick(ticksAfterThis); gInputHandler.post_tick(); gEngine.post_tick(); } char hkAdvanceFrame(float deltaTime) { auto& gInputHandler = tas_input_handler::get(); auto& gEngine = halo_engine::get(); gEngine.pre_frame(); gInputHandler.pre_frame(); char c = originalAdvanceFrame(deltaTime); gInputHandler.post_frame(); return c; } int __cdecl hkBeginLoop() { auto& gInputHandler = tas_input_handler::get(); auto& gRandomizer = randomizer::get(); auto& gEngine = halo_engine::get(); gRandomizer.pre_loop(); gInputHandler.pre_loop(); auto ret = originalBeginLoop(); gInputHandler.post_loop(); return ret; } void __cdecl hkGetMouseKeyboardGamepadInput() { originalGetMouseKeyboardGamepadInput(); } void __cdecl hkAdvanceEffectsTimer(float dt) { originalAdvanceEffectsTimer(dt); } HRESULT __stdcall hkD3D9BeginScene(IDirect3DDevice9* pDevice) { return originalD3D9BeginScene(pDevice); } HRESULT __stdcall hkD3D9Present(IDirect3DDevice9* pDevice, const RECT* pSourceRect, const RECT* pDestRect, HWND hDestWindowOverride, RGNDATA* pDirtyRegion) { auto& gEngine = halo_engine::get(); if (gEngine.is_present_enabled()) { return originalD3D9Present(pDevice, pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion); } return D3D_OK; } HRESULT __stdcall hkD3D9EndScene(IDirect3DDevice9* pDevice) { auto& d3d9 = render_d3d9::get(); d3d9.render(pDevice); return originalD3D9EndScene(pDevice); }
30.957958
156
0.776409
s3anyboy
f02732e925b9bd7a3d1071c0ebc55a73fc0c1d0d
418
hpp
C++
pythran/pythonic/include/numpy/isscalar.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/include/numpy/isscalar.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/include/numpy/isscalar.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
null
null
null
#ifndef PYTHONIC_INCLUDE_NUMPY_ISSCALAR_HPP #define PYTHONIC_INCLUDE_NUMPY_ISSCALAR_HPP #include "pythonic/include/utils/functor.hpp" #include "pythonic/include/types/traits.hpp" #include "pythonic/include/types/str.hpp" #include <type_traits> namespace pythonic { namespace numpy { template <class E> constexpr bool isscalar(E const &); DECLARE_FUNCTOR(pythonic::numpy, isscalar); } } #endif
17.416667
47
0.763158
xmar
f02e4a207cb97f3d4edb73883357be6961ea0058
1,583
cpp
C++
src/network/uber-profile-requestor.cpp
ghosalmartin/harbour-uber
b8d906f4050cfea8817aaebe1ade5c3466662109
[ "MIT" ]
2
2018-03-16T10:31:20.000Z
2018-10-02T15:50:56.000Z
src/network/uber-profile-requestor.cpp
ghosalmartin/harbour-uber
b8d906f4050cfea8817aaebe1ade5c3466662109
[ "MIT" ]
null
null
null
src/network/uber-profile-requestor.cpp
ghosalmartin/harbour-uber
b8d906f4050cfea8817aaebe1ade5c3466662109
[ "MIT" ]
null
null
null
#include "uber-profile-requestor.h" UberProfileRequestor::UberProfileRequestor(QObject *parent) : UberRequestor(parent){ connect(this, SIGNAL(profileChanged(Profile*)), this, SLOT(setProfile(Profile*))); } void UberProfileRequestor::fetchProfileFromNetwork(){ makeNetworkCall( UBER_ME_ENDPOINT, QNetworkAccessManager::Operation::GetOperation); } void UberProfileRequestor::setProfile(Profile *profile){ if(this->m_profile != profile){ this->m_profile = profile; emit profileChanged(profile); } } Profile* UberProfileRequestor::getProfile(){ return this->m_profile; } void UberProfileRequestor::deserialize(QByteArray data) { QString stringReply = (QString) data; QJsonDocument jsonResponse = QJsonDocument::fromJson(stringReply.toUtf8()); QJsonObject jsonObject = jsonResponse.object(); Profile *profile = new Profile(jsonObject["picture"].toString(), jsonObject["first_name"].toString(), jsonObject["last_name"].toString(), jsonObject["uuid"].toString(), jsonObject["rider_id"].toString(), jsonObject["email"].toString(), jsonObject["mobile_verified"].toString(), jsonObject["promo_code"].toString()); setProfile(profile); } void UberProfileRequestor::onError(QString errorString){ qDebug() << errorString; }
33.680851
76
0.602021
ghosalmartin
f0345cefb360a8d7f49255d1ecb9b909df56d97e
244
hpp
C++
include/PrimeGenerator.hpp
sigalor/prime-plot
53bfa9e5f4d89d717d616620045a7c21c7cfe733
[ "Apache-2.0" ]
9
2018-04-10T09:38:16.000Z
2021-02-02T22:46:30.000Z
include/PrimeGenerator.hpp
sigalor/prime-plot
53bfa9e5f4d89d717d616620045a7c21c7cfe733
[ "Apache-2.0" ]
null
null
null
include/PrimeGenerator.hpp
sigalor/prime-plot
53bfa9e5f4d89d717d616620045a7c21c7cfe733
[ "Apache-2.0" ]
2
2018-07-31T04:31:10.000Z
2019-12-21T22:47:50.000Z
#pragma once #include <iostream> #include <vector> //#include <thread> namespace PrimeGenerator { long integerSqrt(long num); std::vector<long> findPrimes(long start, std::size_t num, long* lastCurrLimit, long end=-1); }
15.25
99
0.67623
sigalor
f03624c4db456ba229b7c38e968a48cfa94cb403
7,796
cpp
C++
Beon/src/main.cpp
Riordan-DC/B-on
174390c08eddcdfbd0ae7441fc440a32641bcf28
[ "MIT" ]
null
null
null
Beon/src/main.cpp
Riordan-DC/B-on
174390c08eddcdfbd0ae7441fc440a32641bcf28
[ "MIT" ]
null
null
null
Beon/src/main.cpp
Riordan-DC/B-on
174390c08eddcdfbd0ae7441fc440a32641bcf28
[ "MIT" ]
null
null
null
#include "Beon.hpp" // Window parameters int windowWidth = 1980; int windowHeight = 1080; static bool running = true; //Get a handle on our light //GLuint LightID = glGetUniformLocation(mShader.ID, "LightPosition_worldspace"); // Forward declaration of functions void cleanup(); // Create window manager WindowManager* Manager = WindowManager::getInstance(); int main(int argc, char* argv[]) { if (Manager->initWindow("Beon", windowWidth, windowHeight) == -1) { std::cout << "Window failed to initialize." << std::endl; return -1; }; // Get window from window manager GLFWwindow* window = Manager->getWindow(); // Set GLFW call backs setBasicGLFWCallbacks(window); // Initalise camera controls CameraController controlled_cam(window, glm::vec3(0,10,10)); // Create render view with camera Renderer MainView(controlled_cam.camera, windowWidth, windowHeight); // Initalise Gui GUI::InitGui(window); // Load shaders Shader core_shader = Shader("../Beon/shaders/TransformVertexShader.vert", "../Beon/shaders/TextureFragmentShader.frag"); //Shader crysis_shader = Shader("../Beon/shaders/Toon.vert", "../Beon/shaders/Toon.frag"); Shader mCubmap = Shader("../Beon/shaders/CubeMap.vert", "../Beon/shaders/CubeMap.frag" ); // Load models //Model monkey_model(GetCurrentWorkingDir()+"/../Beon/assets/models/suzanne/suzanne.obj", false); //Model man_model(GetCurrentWorkingDir() + "/../Beon/assets/models/people/Male_Casual.obj", false); //Model crysis_model(GetCurrentWorkingDir() + "/../Beon/assets/models/nanosuit/nanosuit.obj", false); Model cube_model(GetCurrentWorkingDir() + "/../Beon/assets/models/cube/cube.obj", false); Model skybox; skybox.LoadSkyBox(GetCurrentWorkingDir()+"/../Beon/assets/skybox"); mCubmap.use(); mCubmap.setInt("skybox", 0); Object* crysis = new Object(cube_model, 0); crysis->AddShader("texture", core_shader); Object* monkey = new Object(cube_model, 1); monkey->AddShader("basic", core_shader); Object* man = new Object(cube_model, 562); man->AddShader("material", core_shader); Object* floor = new Object(cube_model, 30000); floor->AddShader("material", core_shader); //crysis_shader.use(); //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); BulletSystem bulletSystem = StartBulletPhysics(); bulletSystem.dynamicsWorld->setGravity(btVector3(0,-5.1,0)); crysis->mass = 1.0; crysis->InitPhysics(bulletSystem.dynamicsWorld); crysis->SetPosition(glm::vec3(0.0,40.0,0.0)); man->mass = 1.0; man->InitPhysics(bulletSystem.dynamicsWorld); man->SetPosition(glm::vec3(0.0, 70.0,0.0)); monkey->mass = 1.0; monkey->InitPhysics(bulletSystem.dynamicsWorld); monkey->SetPosition(glm::vec3(0.f, 90.0, 0.0)); floor->mass = 0.0; floor->InitPhysics(bulletSystem.dynamicsWorld); floor->SetPosition(glm::vec3(0.0, 0.0, 0.0)); floor->SetScale(glm::vec3(1,10,10)); double lastTime = glfwGetTime(); // Game Loop // while (glfwWindowShouldClose(window) == false && running) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); getDeltaTime(); // UPDATE bulletSystem.dynamicsWorld->stepSimulation( deltaTime, // Time since last step 7, // Mas substep count btScalar(1.) / btScalar(60.)); // Fixed time step crysis->Update(deltaTime); man->Update(deltaTime); monkey->Update(deltaTime); floor->Update(deltaTime); // RENDER GUI::getFrame(); glClearColor(GUI::backgroundColor.x, GUI::backgroundColor.y, GUI::backgroundColor.z, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); MainView.Update(); MainView.UpdateShader(core_shader); core_shader.setBool("dirLight.On", true); core_shader.setVec3("dirLight.direction", glm::vec3(GUI::DirLightDirection.x, GUI::DirLightDirection.y, GUI::DirLightDirection.z)); core_shader.setVec3("dirLight.ambient", glm::vec3(GUI::DirLightAmbientColor.x, GUI::DirLightAmbientColor.y, GUI::DirLightAmbientColor.z)); core_shader.setVec3("dirLight.diffuse", glm::vec3(GUI::DirLightDiffuse, GUI::DirLightDiffuse, GUI::DirLightDiffuse)); core_shader.setVec3("dirLight.specular", glm::vec3(GUI::DirLightSpecular, GUI::DirLightSpecular, GUI::DirLightSpecular)); core_shader.setFloat("dirLight.shininess", GUI::DirLightShininess); core_shader.setBool("pointLights[0].On", false); core_shader.setVec3("pointLights[0].position", controlled_cam.camera->Position); core_shader.setVec3("pointLights[0].ambient", glm::vec3(GUI::DirLightAmbientColor.x, GUI::DirLightAmbientColor.y, GUI::DirLightAmbientColor.z)); core_shader.setVec3("pointLights[0].specular", glm::vec3(GUI::DirLightSpecular, GUI::DirLightSpecular, GUI::DirLightSpecular)); core_shader.setVec3("pointLights[0].diffuse", glm::vec3(GUI::DirLightDiffuse, GUI::DirLightDiffuse, GUI::DirLightDiffuse)); core_shader.setFloat("pointLights[0].quadratic", 0.032f); core_shader.setFloat("pointLights[0].linear", 0.09f); core_shader.setFloat("pointLights[0].constant", 3.0f); crysis->RenderObject(MainView); man->RenderObject(MainView); monkey->RenderObject(MainView); floor->RenderObject(MainView); if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT)) { glm::vec3 out_origin; glm::vec3 out_direction; double xpos, ypos; if (controlled_cam.trackMouse) { xpos = windowWidth / 2; ypos = windowHeight / 2; } else { glfwGetCursorPos(window, &xpos, &ypos); ypos = windowHeight - ypos; } ScreenPosToWorldRay( (int)xpos, (int)ypos, windowWidth, windowHeight, controlled_cam.camera->ViewMatrix, controlled_cam.camera->ProjectionMatrix, out_origin, out_direction ); glm::vec3 out_end = out_origin + out_direction * 1000.0f; btCollisionWorld::ClosestRayResultCallback RayCallback(btVector3(out_origin.x, out_origin.y, out_origin.z), btVector3(out_end.x, out_end.y, out_end.z)); bulletSystem.dynamicsWorld->rayTest(btVector3(out_origin.x, out_origin.y, out_origin.z), btVector3(out_end.x, out_end.y, out_end.z), RayCallback); if (RayCallback.hasHit()) { if (GUI::selected_object) { GUI::selected_object->Selected(false); } GUI::selected_object = (Object*)RayCallback.m_collisionObject->getUserPointer(); GUI::selected_object->Selected(true); //std::cout << "mesh " << GUI::selected_object->entity_tag << std::endl; } else { if (GUI::selected_object) { GUI::selected_object->Selected(false); } //std::cout << "background" << std::endl;; } } if (glfwGetKey(window, GLFW_KEY_TAB) == GLFW_PRESS) { // Escape camera mode GUI::fly_camera = false; } controlled_cam.Update(deltaTime); controlled_cam.trackMouse = GUI::fly_camera; glDepthFunc(GL_LEQUAL); MainView.UpdateShader(mCubmap); //skybox.DrawSkyBox(crysis_shader); skybox.DrawSkyBox(mCubmap); // Render GUI GUI::renderGui(); // In time left over, poll events again. while (glfwGetTime() < lastTime + (1.0 / 60.0)) { // Do nothing continue; } lastTime += (1.0 / 60.0); // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) glfwSwapBuffers(window); glfwPollEvents(); } // de-allocate all resources once they've outlived their purpose: delete man; delete monkey; delete floor; delete crysis; GUI::killGui(); DestroyBulletPhysics(&bulletSystem); cleanup(); return 0; } void cleanup() { // Close OpenGL window and terminate GLFW glfwTerminate(); delete Manager; }
34.043668
156
0.685993
Riordan-DC
f036d2b4c7e72d0bc013732246952863da7336c2
1,773
cpp
C++
roo_material_icons/sharp/18/home.cpp
dejwk/roo_material_icons
f559ce25b6ee2fdf67ed4f8b0bedfce2aaefb885
[ "MIT" ]
null
null
null
roo_material_icons/sharp/18/home.cpp
dejwk/roo_material_icons
f559ce25b6ee2fdf67ed4f8b0bedfce2aaefb885
[ "MIT" ]
null
null
null
roo_material_icons/sharp/18/home.cpp
dejwk/roo_material_icons
f559ce25b6ee2fdf67ed4f8b0bedfce2aaefb885
[ "MIT" ]
null
null
null
#include "home.h" using namespace roo_display; // Image file ic_sharp_18_home_sensor_door 18x18, 4-bit Alpha, RLE, 60 bytes. static const uint8_t ic_sharp_18_home_sensor_door_data[] PROGMEM = { 0x80, 0xC3, 0x00, 0x18, 0x06, 0x30, 0x16, 0x06, 0xFB, 0x06, 0x60, 0x6F, 0xB0, 0x66, 0x06, 0xFB, 0x06, 0x60, 0x6F, 0xB0, 0x66, 0x06, 0xFB, 0x06, 0x60, 0x6E, 0x83, 0xE3, 0xAF, 0x66, 0x06, 0xE8, 0x3E, 0x3A, 0xF6, 0x60, 0x6F, 0xB0, 0x66, 0x06, 0xFB, 0x06, 0x60, 0x6F, 0xB0, 0x66, 0x06, 0xFB, 0x06, 0x60, 0x6F, 0xB0, 0x66, 0x01, 0x80, 0x63, 0x01, 0x80, 0xC3, 0x00, }; const RleImage4bppxBiased<Alpha4, PrgMemResource>& ic_sharp_18_home_sensor_door() { static RleImage4bppxBiased<Alpha4, PrgMemResource> value( 18, 18, ic_sharp_18_home_sensor_door_data, Alpha4(color::Black)); return value; } // Image file ic_sharp_18_home_sensor_window 18x18, 4-bit Alpha, RLE, 94 bytes. static const uint8_t ic_sharp_18_home_sensor_window_data[] PROGMEM = { 0x80, 0xC3, 0x00, 0x18, 0x06, 0x30, 0x16, 0x06, 0x0C, 0x80, 0x49, 0x0C, 0x06, 0x68, 0x16, 0x74, 0x80, 0x27, 0x81, 0x47, 0x66, 0x81, 0x67, 0x9E, 0x81, 0x97, 0x66, 0x81, 0x67, 0x9E, 0x81, 0x97, 0x66, 0x89, 0x26, 0x79, 0xFB, 0x33, 0xBF, 0x97, 0x66, 0x06, 0x07, 0x0F, 0x12, 0x0F, 0x10, 0x70, 0x66, 0x81, 0x67, 0x9E, 0x81, 0x97, 0x66, 0x81, 0x67, 0x9E, 0x81, 0x97, 0x66, 0x81, 0x67, 0x9E, 0x81, 0x97, 0x66, 0x81, 0x67, 0x9E, 0x81, 0x97, 0x66, 0x81, 0x67, 0x48, 0x02, 0x78, 0x14, 0x76, 0x60, 0x60, 0xC8, 0x04, 0x90, 0xC0, 0x66, 0x01, 0x80, 0x63, 0x01, 0x80, 0xC3, 0x00, }; const RleImage4bppxBiased<Alpha4, PrgMemResource>& ic_sharp_18_home_sensor_window() { static RleImage4bppxBiased<Alpha4, PrgMemResource> value( 18, 18, ic_sharp_18_home_sensor_window_data, Alpha4(color::Black)); return value; }
53.727273
97
0.716864
dejwk
f0377dc35798653f437c55858a0ab0ae28426d9a
4,645
cc
C++
util/fuchsia/koid_utilities.cc
rbxeyl/crashpad
95b4e6276836283a91e18382fb258598bd77f8aa
[ "Apache-2.0" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
util/fuchsia/koid_utilities.cc
rbxeyl/crashpad
95b4e6276836283a91e18382fb258598bd77f8aa
[ "Apache-2.0" ]
113
2019-12-14T04:28:04.000Z
2021-09-26T18:40:27.000Z
util/fuchsia/koid_utilities.cc
rbxeyl/crashpad
95b4e6276836283a91e18382fb258598bd77f8aa
[ "Apache-2.0" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2018 The Crashpad Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "util/fuchsia/koid_utilities.h" #include <lib/fdio/fdio.h> #include <lib/zx/channel.h> #include <lib/zx/job.h> #include <lib/zx/process.h> #include <vector> #include "base/files/file_path.h" #include "base/fuchsia/fuchsia_logging.h" #include "util/file/file_io.h" namespace crashpad { namespace { // Casts |handle| into a container of type T, returning a null handle if the // actual handle type does not match that of T. template <typename T> T CastHandle(zx::handle handle) { zx_info_handle_basic_t actual = {}; zx_status_t status = handle.get_info( ZX_INFO_HANDLE_BASIC, &actual, sizeof(actual), nullptr, nullptr); if (status != ZX_OK) { ZX_LOG(ERROR, status) << "zx_object_get_info"; return T(); } if (actual.type != T::TYPE) { LOG(ERROR) << "Wrong type: " << actual.type << ", expected " << T::TYPE; return T(); } return T(std::move(handle)); } // Returns null handle if |koid| is not found or an error occurs. If |was_found| // is non-null then it will be set, to distinguish not-found from other errors. template <typename T, typename U> T GetChildHandleByKoid(const U& parent, zx_koid_t child_koid, bool* was_found) { zx::handle handle; zx_status_t status = parent.get_child(child_koid, ZX_RIGHT_SAME_RIGHTS, &handle); if (was_found) *was_found = (status != ZX_ERR_NOT_FOUND); if (status != ZX_OK) { ZX_LOG(ERROR, status) << "zx_object_get_child"; return T(); } return CastHandle<T>(std::move(handle)); } } // namespace std::vector<zx_koid_t> GetChildKoids(const zx::object_base& parent_object, zx_object_info_topic_t child_kind) { size_t actual = 0; size_t available = 0; std::vector<zx_koid_t> result(100); zx::unowned_handle parent(parent_object.get()); // This is inherently racy. Better if the process is suspended, but there's // still no guarantee that a thread isn't externally created. As a result, // must be in a retry loop. for (;;) { zx_status_t status = parent->get_info(child_kind, result.data(), result.size() * sizeof(zx_koid_t), &actual, &available); // If the buffer is too small (even zero), the result is still ZX_OK, not // ZX_ERR_BUFFER_TOO_SMALL. if (status != ZX_OK) { ZX_LOG(ERROR, status) << "zx_object_get_info"; break; } if (actual == available) { break; } // Resize to the expected number next time, with a bit of slop to handle the // race between here and the next request. result.resize(available + 10); } result.resize(actual); return result; } std::vector<zx::thread> GetThreadHandles(const zx::process& parent) { auto koids = GetChildKoids(parent, ZX_INFO_PROCESS_THREADS); return GetHandlesForThreadKoids(parent, koids); } std::vector<zx::thread> GetHandlesForThreadKoids( const zx::process& parent, const std::vector<zx_koid_t>& koids) { std::vector<zx::thread> result; result.reserve(koids.size()); for (zx_koid_t koid : koids) { result.emplace_back(GetThreadHandleByKoid(parent, koid)); } return result; } zx::thread GetThreadHandleByKoid(const zx::process& parent, zx_koid_t child_koid) { return GetChildHandleByKoid<zx::thread>(parent, child_koid, nullptr); } zx_koid_t GetKoidForHandle(const zx::object_base& object) { zx_info_handle_basic_t info; zx_status_t status = zx_object_get_info(object.get(), ZX_INFO_HANDLE_BASIC, &info, sizeof(info), nullptr, nullptr); if (status != ZX_OK) { ZX_LOG(ERROR, status) << "zx_object_get_info"; return ZX_KOID_INVALID; } return info.koid; } } // namespace crashpad
32.711268
80
0.639182
rbxeyl
f040c8b9ee2c07b5d508dcc6f6c41cd4e4cd3511
8,596
hpp
C++
include/codegen/include/Zenject/FactoryFromBinder1Extensions.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/Zenject/FactoryFromBinder1Extensions.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/Zenject/FactoryFromBinder1Extensions.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:42 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Object #include "System/Object.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: Zenject namespace Zenject { // Forward declaring type: ArgConditionCopyNonLazyBinder class ArgConditionCopyNonLazyBinder; // Forward declaring type: FactoryFromBinder`2<TParam1, TContract> template<typename TParam1, typename TContract> class FactoryFromBinder_2; // Forward declaring type: ConcreteBinderGeneric`1<TContract> template<typename TContract> class ConcreteBinderGeneric_1; // Forward declaring type: IFactory`2<TValue, TParam1> template<typename TValue, typename TParam1> class IFactory_2; // Forward declaring type: IPoolable`2<TParam1, TParam2> template<typename TParam1, typename TParam2> class IPoolable_2; // Forward declaring type: IMemoryPool class IMemoryPool; // Forward declaring type: MemoryPoolInitialSizeMaxSizeBinder`1<TContract> template<typename TContract> class MemoryPoolInitialSizeMaxSizeBinder_1; // Forward declaring type: MemoryPool`3<TValue, TParam1, TParam2> template<typename TValue, typename TParam1, typename TParam2> class MemoryPool_3; } // Forward declaring namespace: System namespace System { // Forward declaring type: Action`1<T> template<typename T> class Action_1; // Forward declaring type: Action`1<T> template<typename T> class Action_1; } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: Component class Component; } // Completed forward declares // Type namespace: Zenject namespace Zenject { // Autogenerated type: Zenject.FactoryFromBinder1Extensions class FactoryFromBinder1Extensions : public ::Il2CppObject { public: // Nested type: Zenject::FactoryFromBinder1Extensions::$$c__DisplayClass0_0_2<TParam1, TContract> template<typename TParam1, typename TContract> class $$c__DisplayClass0_0_2; // Nested type: Zenject::FactoryFromBinder1Extensions::$$c__1_2<TParam1, TContract> template<typename TParam1, typename TContract> class $$c__1_2; // Nested type: Zenject::FactoryFromBinder1Extensions::$$c__3_2<TParam1, TContract> template<typename TParam1, typename TContract> class $$c__3_2; // Nested type: Zenject::FactoryFromBinder1Extensions::$$c__5_3<TParam1, TContract, TMemoryPool> template<typename TParam1, typename TContract, typename TMemoryPool> class $$c__5_3; // Nested type: Zenject::FactoryFromBinder1Extensions::$$c__DisplayClass6_0_3<TParam1, TContract, TMemoryPool> template<typename TParam1, typename TContract, typename TMemoryPool> class $$c__DisplayClass6_0_3; // static public Zenject.ArgConditionCopyNonLazyBinder FromIFactory(Zenject.FactoryFromBinder`2<TParam1,TContract> fromBinder, System.Action`1<Zenject.ConcreteBinderGeneric`1<Zenject.IFactory`2<TParam1,TContract>>> factoryBindGenerator) // Offset: 0x13D1270 template<class TParam1, class TContract> static Zenject::ArgConditionCopyNonLazyBinder* FromIFactory(Zenject::FactoryFromBinder_2<TParam1, TContract>* fromBinder, System::Action_1<Zenject::ConcreteBinderGeneric_1<Zenject::IFactory_2<TParam1, TContract>*>*>* factoryBindGenerator) { return CRASH_UNLESS(il2cpp_utils::RunGenericMethod<Zenject::ArgConditionCopyNonLazyBinder*>("Zenject", "FactoryFromBinder1Extensions", "FromIFactory", {il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TParam1>::get(), il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TContract>::get()}, fromBinder, factoryBindGenerator)); } // static public Zenject.ArgConditionCopyNonLazyBinder FromPoolableMemoryPool(Zenject.FactoryFromBinder`2<TParam1,TContract> fromBinder) // Offset: 0x13D18B4 template<class TParam1, class TContract> static Zenject::ArgConditionCopyNonLazyBinder* FromPoolableMemoryPool(Zenject::FactoryFromBinder_2<TParam1, TContract>* fromBinder) { static_assert(std::is_convertible_v<TContract, Zenject::IPoolable_2<TParam1, Zenject::IMemoryPool*>*>); return CRASH_UNLESS(il2cpp_utils::RunGenericMethod<Zenject::ArgConditionCopyNonLazyBinder*>("Zenject", "FactoryFromBinder1Extensions", "FromPoolableMemoryPool", {il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TParam1>::get(), il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TContract>::get()}, fromBinder)); } // static public Zenject.ArgConditionCopyNonLazyBinder FromPoolableMemoryPool(Zenject.FactoryFromBinder`2<TParam1,TContract> fromBinder, System.Action`1<Zenject.MemoryPoolInitialSizeMaxSizeBinder`1<TContract>> poolBindGenerator) // Offset: 0x13D1A60 template<class TParam1, class TContract> static Zenject::ArgConditionCopyNonLazyBinder* FromPoolableMemoryPool(Zenject::FactoryFromBinder_2<TParam1, TContract>* fromBinder, System::Action_1<Zenject::MemoryPoolInitialSizeMaxSizeBinder_1<TContract>*>* poolBindGenerator) { static_assert(std::is_convertible_v<TContract, Zenject::IPoolable_2<TParam1, Zenject::IMemoryPool*>*>); return CRASH_UNLESS(il2cpp_utils::RunGenericMethod<Zenject::ArgConditionCopyNonLazyBinder*>("Zenject", "FactoryFromBinder1Extensions", "FromPoolableMemoryPool", {il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TParam1>::get(), il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TContract>::get()}, fromBinder, poolBindGenerator)); } // static public Zenject.ArgConditionCopyNonLazyBinder FromMonoPoolableMemoryPool(Zenject.FactoryFromBinder`2<TParam1,TContract> fromBinder) // Offset: 0x13D139C template<class TParam1, class TContract> static Zenject::ArgConditionCopyNonLazyBinder* FromMonoPoolableMemoryPool(Zenject::FactoryFromBinder_2<TParam1, TContract>* fromBinder) { static_assert(std::is_convertible_v<TContract, UnityEngine::Component*> && std::is_convertible_v<TContract, Zenject::IPoolable_2<TParam1, Zenject::IMemoryPool*>*>); return CRASH_UNLESS(il2cpp_utils::RunGenericMethod<Zenject::ArgConditionCopyNonLazyBinder*>("Zenject", "FactoryFromBinder1Extensions", "FromMonoPoolableMemoryPool", {il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TParam1>::get(), il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TContract>::get()}, fromBinder)); } // static public Zenject.ArgConditionCopyNonLazyBinder FromMonoPoolableMemoryPool(Zenject.FactoryFromBinder`2<TParam1,TContract> fromBinder, System.Action`1<Zenject.MemoryPoolInitialSizeMaxSizeBinder`1<TContract>> poolBindGenerator) // Offset: 0x13D1548 template<class TParam1, class TContract> static Zenject::ArgConditionCopyNonLazyBinder* FromMonoPoolableMemoryPool(Zenject::FactoryFromBinder_2<TParam1, TContract>* fromBinder, System::Action_1<Zenject::MemoryPoolInitialSizeMaxSizeBinder_1<TContract>*>* poolBindGenerator) { static_assert(std::is_convertible_v<TContract, UnityEngine::Component*> && std::is_convertible_v<TContract, Zenject::IPoolable_2<TParam1, Zenject::IMemoryPool*>*>); return CRASH_UNLESS(il2cpp_utils::RunGenericMethod<Zenject::ArgConditionCopyNonLazyBinder*>("Zenject", "FactoryFromBinder1Extensions", "FromMonoPoolableMemoryPool", {il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TParam1>::get(), il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TContract>::get()}, fromBinder, poolBindGenerator)); } // static public Zenject.ArgConditionCopyNonLazyBinder FromPoolableMemoryPool(Zenject.FactoryFromBinder`2<TParam1,TContract> fromBinder) // Offset: 0x13D1558 // ABORTED: conflicts with another method. static Zenject::ArgConditionCopyNonLazyBinder* FromPoolableMemoryPool(Zenject::FactoryFromBinder_2<TParam1, TContract>* fromBinder) // static public Zenject.ArgConditionCopyNonLazyBinder FromPoolableMemoryPool(Zenject.FactoryFromBinder`2<TParam1,TContract> fromBinder, System.Action`1<Zenject.MemoryPoolInitialSizeMaxSizeBinder`1<TContract>> poolBindGenerator) // Offset: 0x13D1704 // ABORTED: conflicts with another method. static Zenject::ArgConditionCopyNonLazyBinder* FromPoolableMemoryPool(Zenject::FactoryFromBinder_2<TParam1, TContract>* fromBinder, System::Action_1<Zenject::MemoryPoolInitialSizeMaxSizeBinder_1<TContract>*>* poolBindGenerator) }; // Zenject.FactoryFromBinder1Extensions } DEFINE_IL2CPP_ARG_TYPE(Zenject::FactoryFromBinder1Extensions*, "Zenject", "FactoryFromBinder1Extensions"); #pragma pack(pop)
73.470085
347
0.79665
Futuremappermydud
f04378c7ee5b0e8ee964c93bb89f07a6b122379e
680
hpp
C++
include/jln/mp/functional/if.hpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
9
2020-07-04T16:46:13.000Z
2022-01-09T21:59:31.000Z
include/jln/mp/functional/if.hpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
null
null
null
include/jln/mp/functional/if.hpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
1
2021-05-23T13:37:40.000Z
2021-05-23T13:37:40.000Z
#pragma once #include <jln/mp/utility/conditional.hpp> #include <jln/mp/utility/always.hpp> #include <jln/mp/number/number.hpp> #include <jln/mp/functional/call.hpp> namespace jln::mp { /// \ingroup functional /// A conditional expression. /// \treturn \value template<class Pred, class TC, class FC = always<false_>> struct if_ { template<class... xs> using f = typename mp::conditional_c<bool(call<Pred, xs...>::value)> ::template f<TC, FC> ::template f<xs...>; }; namespace emp { template<class Pred, class TC, class FC, class... xs> using if_ = typename conditional<call<Pred, xs...>, TC, FC> ::template f<xs...>; } }
22.666667
72
0.636765
jonathanpoelen
f043b2b0fde76b34dd159a94d2ffaa47995915cd
7,135
cpp
C++
src/zxing/zxing/oned/rss/expanded/decoders/FieldParser.cpp
favoritas37/qzxing
6ea2b31e26db9d43db027ba207f5c73dc9d759fc
[ "Apache-2.0" ]
608
2015-02-21T22:31:37.000Z
2022-03-31T05:05:36.000Z
src/zxing/zxing/oned/rss/expanded/decoders/FieldParser.cpp
favoritas37/qzxing
6ea2b31e26db9d43db027ba207f5c73dc9d759fc
[ "Apache-2.0" ]
512
2015-01-06T17:59:31.000Z
2022-03-31T13:21:49.000Z
src/zxing/zxing/oned/rss/expanded/decoders/FieldParser.cpp
favoritas37/qzxing
6ea2b31e26db9d43db027ba207f5c73dc9d759fc
[ "Apache-2.0" ]
281
2016-09-15T08:42:26.000Z
2022-03-21T17:55:00.000Z
#include "FieldParser.h" #include <algorithm> namespace zxing { namespace oned { namespace rss { static const int VARIABLE_LENGTH = 99999; struct DigitData { std::string digit; int variableLength; int length; }; static const DigitData TWO_DIGIT_DATA_LENGTH[] { // "DIGITS", new Integer(LENGTH) // or // "DIGITS", VARIABLE_LENGTH, new Integer(MAX_SIZE) { "00", 18, 0}, { "01", 14, 0}, { "02", 14, 0}, { "10", VARIABLE_LENGTH, 20}, { "11", 6, 0}, { "12", 6, 0}, { "13", 6, 0}, { "15", 6, 0}, { "17", 6, 0}, { "20", 2, 0}, { "21", VARIABLE_LENGTH, 20}, { "22", VARIABLE_LENGTH, 29}, { "30", VARIABLE_LENGTH, 8}, { "37", VARIABLE_LENGTH, 8}, //internal company codes { "90", VARIABLE_LENGTH, 30}, { "91", VARIABLE_LENGTH, 30}, { "92", VARIABLE_LENGTH, 30}, { "93", VARIABLE_LENGTH, 30}, { "94", VARIABLE_LENGTH, 30}, { "95", VARIABLE_LENGTH, 30}, { "96", VARIABLE_LENGTH, 30}, { "97", VARIABLE_LENGTH, 30}, { "98", VARIABLE_LENGTH, 30}, { "99", VARIABLE_LENGTH, 30}, }; static const DigitData THREE_DIGIT_DATA_LENGTH[] { // Same format as above { "240", VARIABLE_LENGTH, 30}, { "241", VARIABLE_LENGTH, 30}, { "242", VARIABLE_LENGTH, 6}, { "250", VARIABLE_LENGTH, 30}, { "251", VARIABLE_LENGTH, 30}, { "253", VARIABLE_LENGTH, 17}, { "254", VARIABLE_LENGTH, 20}, { "400", VARIABLE_LENGTH, 30}, { "401", VARIABLE_LENGTH, 30}, { "402", 17, 0}, { "403", VARIABLE_LENGTH, 30}, { "410", 13, 0}, { "411", 13, 0}, { "412", 13, 0}, { "413", 13, 0}, { "414", 13, 0}, { "420", VARIABLE_LENGTH, 20}, { "421", VARIABLE_LENGTH, 15}, { "422", 3, 0}, { "423", VARIABLE_LENGTH, 15}, { "424", 3, 0}, { "425", 3, 0}, { "426", 3, 0}, }; static const DigitData THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH[] { // Same format as above { "310", 6, 0}, { "311", 6, 0}, { "312", 6, 0}, { "313", 6, 0}, { "314", 6, 0}, { "315", 6, 0}, { "316", 6, 0}, { "320", 6, 0}, { "321", 6, 0}, { "322", 6, 0}, { "323", 6, 0}, { "324", 6, 0}, { "325", 6, 0}, { "326", 6, 0}, { "327", 6, 0}, { "328", 6, 0}, { "329", 6, 0}, { "330", 6, 0}, { "331", 6, 0}, { "332", 6, 0}, { "333", 6, 0}, { "334", 6, 0}, { "335", 6, 0}, { "336", 6, 0}, { "340", 6, 0}, { "341", 6, 0}, { "342", 6, 0}, { "343", 6, 0}, { "344", 6, 0}, { "345", 6, 0}, { "346", 6, 0}, { "347", 6, 0}, { "348", 6, 0}, { "349", 6, 0}, { "350", 6, 0}, { "351", 6, 0}, { "352", 6, 0}, { "353", 6, 0}, { "354", 6, 0}, { "355", 6, 0}, { "356", 6, 0}, { "357", 6, 0}, { "360", 6, 0}, { "361", 6, 0}, { "362", 6, 0}, { "363", 6, 0}, { "364", 6, 0}, { "365", 6, 0}, { "366", 6, 0}, { "367", 6, 0}, { "368", 6, 0}, { "369", 6, 0}, { "390", VARIABLE_LENGTH, 15}, { "391", VARIABLE_LENGTH, 18}, { "392", VARIABLE_LENGTH, 15}, { "393", VARIABLE_LENGTH, 18}, { "703", VARIABLE_LENGTH, 30}, }; static const DigitData FOUR_DIGIT_DATA_LENGTH[] { // Same format as above { "7001", 13, 0}, { "7002", VARIABLE_LENGTH, 30}, { "7003", 10, 0}, { "8001", 14, 0}, { "8002", VARIABLE_LENGTH, 20}, { "8003", VARIABLE_LENGTH, 30}, { "8004", VARIABLE_LENGTH, 30}, { "8005", 6, 0}, { "8006", 18, 0}, { "8007", VARIABLE_LENGTH, 30}, { "8008", VARIABLE_LENGTH, 12}, { "8018", 18, 0}, { "8020", VARIABLE_LENGTH, 25}, { "8100", 6, 0}, { "8101", 10, 0}, { "8102", 2, 0}, { "8110", VARIABLE_LENGTH, 70}, { "8200", VARIABLE_LENGTH, 70}, }; String FieldParser::parseFieldsInGeneralPurpose(String rawInformation) { if (rawInformation.getText().empty()) { return String(""); } // Processing 2-digit AIs if (rawInformation.length() < 2) { throw NotFoundException(); } String firstTwoDigits(rawInformation.substring(0, 2)->getText()); for (DigitData dataLength : TWO_DIGIT_DATA_LENGTH) { if (dataLength.digit == firstTwoDigits.getText()) { if (dataLength.variableLength == VARIABLE_LENGTH) { return processVariableAI(2, dataLength.length, rawInformation); } return processFixedAI(2, dataLength.variableLength, rawInformation); } } if (rawInformation.length() < 3) { throw NotFoundException(); } String firstThreeDigits(rawInformation.substring(0, 3)->getText()); for (DigitData dataLength : THREE_DIGIT_DATA_LENGTH) { if (dataLength.digit == firstThreeDigits.getText()) { if (dataLength.variableLength == VARIABLE_LENGTH) { return processVariableAI(3, dataLength.length, rawInformation); } return processFixedAI(3, dataLength.variableLength, rawInformation); } } for (DigitData dataLength : THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH) { if (dataLength.digit == firstThreeDigits.getText()) { if (dataLength.variableLength == VARIABLE_LENGTH) { return processVariableAI(4, dataLength.length, rawInformation); } return processFixedAI(4, dataLength.variableLength, rawInformation); } } if (rawInformation.length() < 4) { throw NotFoundException(); } String firstFourDigits(rawInformation.substring(0, 4)->getText()); for (DigitData dataLength : FOUR_DIGIT_DATA_LENGTH) { if (dataLength.digit == firstFourDigits.getText()) { if (dataLength.variableLength == VARIABLE_LENGTH) { return processVariableAI(4, dataLength.length, rawInformation); } return processFixedAI(4, dataLength.variableLength, rawInformation); } } throw NotFoundException(); } String FieldParser::processFixedAI(int aiSize, int fieldSize, String rawInformation) { if (rawInformation.length() < aiSize) { throw NotFoundException(); } String ai(rawInformation.substring(0, aiSize)->getText()); if (rawInformation.length() < aiSize + fieldSize) { throw NotFoundException(); } String field(rawInformation.substring(aiSize, /*aiSize +*/ fieldSize)->getText()); String remaining(rawInformation.substring(aiSize + fieldSize)->getText()); String result('(' + ai.getText() + ')' + field.getText()); String parsedAI = parseFieldsInGeneralPurpose(remaining); if (parsedAI.getText() == "") { return result; } else { result.append(parsedAI.getText()); return result; } } String FieldParser::processVariableAI(int aiSize, int variableFieldSize, String rawInformation) { String ai(rawInformation.substring(0, aiSize)->getText()); int maxSize = std::min(rawInformation.length(), aiSize + variableFieldSize); String field(rawInformation.substring(aiSize, maxSize - aiSize)->getText()); String remaining(rawInformation.substring(maxSize)->getText()); String result('(' + ai.getText() + ')' + field.getText()); String parsedAI = parseFieldsInGeneralPurpose(remaining); if (parsedAI.getText() == "") { return result; } else { result.append(parsedAI.getText()); return result; } } } } }
25.758123
95
0.571829
favoritas37
f045c323aed5df511f3059cb6ecfa62ee27afcee
1,198
hh
C++
GameLogic/Engine/piecefactory.hh
saarioka/Saaripeli
28145e49b4708e22fb7cb051c1ccddfa4a6a24f9
[ "MIT" ]
null
null
null
GameLogic/Engine/piecefactory.hh
saarioka/Saaripeli
28145e49b4708e22fb7cb051c1ccddfa4a6a24f9
[ "MIT" ]
null
null
null
GameLogic/Engine/piecefactory.hh
saarioka/Saaripeli
28145e49b4708e22fb7cb051c1ccddfa4a6a24f9
[ "MIT" ]
null
null
null
#ifndef PIECEFACTORY_HH #define PIECEFACTORY_HH #include <QJsonObject> #include <string> #include <vector> /** * @file * @brief Singleton class that creates pieces. */ namespace Logic { /** * @brief Singleton class for creating pieces. * * The factory is requested to read JSON file, after which it will requested to * return a data structure, which containts the read pieces. */ class PieceFactory { public: /** * @return A reference to the factory. */ static PieceFactory& getInstance(); /** * @brief readJSON reads pieces a JSON file. * @exception IOException Could not open the file Assets/pieces.json for reading. * @exception FormatException Format of the file Assets/pieces.json is invalid. * @post Exception quarantee: basic */ void readJSON(); /** * @brief Gets the pieces used in the game * @return The pieces read from the JSON file. If the file is not read, or the actors did not exist, will return an empty vector. * @post Exception quarantee: basic */ std::vector<std::pair<std::string,int>> getGamePieces() const; private: PieceFactory(); QJsonObject _json; }; } #endif
21.392857
133
0.673623
saarioka
f04c4f700ec089a967ffa9bfa9b5e02c7dfa42ff
1,413
hpp
C++
lib/include/interlinck/Core/Syntax/IWithSimplifiedWidthAndPosition.hpp
henrikfroehling/polyglot
955fb37c2f54ebbaf933c16bf9e0e4bcca8a4142
[ "MIT" ]
null
null
null
lib/include/interlinck/Core/Syntax/IWithSimplifiedWidthAndPosition.hpp
henrikfroehling/polyglot
955fb37c2f54ebbaf933c16bf9e0e4bcca8a4142
[ "MIT" ]
50
2021-06-30T20:01:50.000Z
2021-11-28T16:21:26.000Z
lib/include/interlinck/Core/Syntax/IWithSimplifiedWidthAndPosition.hpp
henrikfroehling/polyglot
955fb37c2f54ebbaf933c16bf9e0e4bcca8a4142
[ "MIT" ]
null
null
null
#ifndef INTERLINCK_CORE_SYNTAX_IWITHSIMPLIFIEDWIDTHANDPOSITION_H #define INTERLINCK_CORE_SYNTAX_IWITHSIMPLIFIEDWIDTHANDPOSITION_H #include "interlinck/interlinck_global.hpp" #include "interlinck/Core/Text/TextSpan.hpp" #include "interlinck/Core/Types.hpp" namespace interlinck::Core::Syntax { /** * @brief Interface providing functions regarding positions and widths of syntax elements without trivia. */ class INTERLINCK_API IWithSimplifiedWidthAndPosition { public: virtual ~IWithSimplifiedWidthAndPosition() noexcept = default; /** * @brief Returns the width of the syntax elements. * @return The width of the syntax elements. */ virtual il_size width() const noexcept = 0; /** * @brief Returns the position of the syntax element. * @return The position of the syntax element. */ virtual il_size position() const noexcept = 0; /** * @brief Returns the position at which the syntax element ends. * @return The position at which the syntax element ends. */ virtual il_size endPosition() const noexcept = 0; /** * @brief Returns the <code>TextSpan</code> for the syntax element. * @return The <code>TextSpan</code> for the syntax element. */ virtual Text::TextSpan span() const noexcept = 0; }; } // end namespace interlinck::Core::Syntax #endif // INTERLINCK_CORE_SYNTAX_IWITHSIMPLIFIEDWIDTHANDPOSITION_H
30.06383
105
0.726115
henrikfroehling
f0536743f2f27114eb1aa65d2d52739f363aad92
1,111
cpp
C++
UVA/11582/17163602_AC_970ms_0kB.cpp
BakaErii/ACM_Collection
d368b15c7f1c84472424d5e61e5ebc667f589025
[ "WTFPL" ]
null
null
null
UVA/11582/17163602_AC_970ms_0kB.cpp
BakaErii/ACM_Collection
d368b15c7f1c84472424d5e61e5ebc667f589025
[ "WTFPL" ]
null
null
null
UVA/11582/17163602_AC_970ms_0kB.cpp
BakaErii/ACM_Collection
d368b15c7f1c84472424d5e61e5ebc667f589025
[ "WTFPL" ]
null
null
null
/** * @author Moe_Sakiya sakiya@tun.moe * @date 2018-11-24 14:58:37 * */ #include <iostream> #include <string> #include <algorithm> #include <set> #include <map> #include <vector> #include <stack> #include <queue> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> using namespace std; const int maxN = 10005; unsigned long long int fac[maxN]; unsigned long long int pm(unsigned long long int a, unsigned long long int b, unsigned long long int c) { unsigned long long int tmp = 1 % c; a = a % c; while (b > 0) { if (b % 2 == 1) tmp = (tmp * a) % c; b /= 2; a = (a * a) % c; } return tmp; } int main(void) { unsigned long long int t, n, mod = 0; unsigned long long int x, y; cin >> t; while (t--) { cin >> x >> y >> n; fac[0] = 0; fac[1] = 1 % n; for (int i = 2; i < maxN; i++) fac[i] = (fac[i - 1] + fac[i - 2]) % n; for (int i = 4; i < maxN - 10; i++) if (fac[1] == fac[i] && fac[2] == fac[i + 1] && fac[3] == fac[i + 2] && fac[4] == fac[i + 3]){ mod = i; break; } mod--; cout << fac[pm(x, y, mod)] << endl; } return 0; }
19.155172
105
0.545455
BakaErii
f0573ae4797675834357ceed30a2b0960325ab6e
1,281
hpp
C++
src/memory/Array.hpp
LU15W1R7H/lwirth-lib
f51cfb56b801790c200cea64d226730449d68f53
[ "MIT" ]
2
2018-04-04T17:26:32.000Z
2020-06-26T09:22:49.000Z
src/memory/Array.hpp
LU15W1R7H/lwirth-lib
f51cfb56b801790c200cea64d226730449d68f53
[ "MIT" ]
1
2018-08-27T14:35:45.000Z
2018-08-27T19:00:12.000Z
src/memory/Array.hpp
LU15W1R7H/lwirth-lib
f51cfb56b801790c200cea64d226730449d68f53
[ "MIT" ]
null
null
null
#pragma once #include "../Standard.hpp" #include <utility> #include <initializer_list> namespace lw { template<class T, size_t SIZE> class Array { private: T m_pData[SIZE]; public: constexpr Array() : m_pData{} { } constexpr Array(const std::initializer_list<T>& il) { static_assert(il.end() - il.begin() == SIZE, "Wrong length"); size_t i = 0; for (auto iter = 0; iter != il.end(); iter++) { m_pData[i] = *iter; i++; } } Array(Array<T, SIZE> const& other) { std::copy(other.m_pData, other.m_pData + SIZE, m_pData); } Array(Array<T, SIZE>&& other) { for (size_t i = 0; i < SIZE; i++) { m_pData[i] = std::move(other.m_pData[i]); } } Array& operator=(Array<T, SIZE> const& other) { std::copy(other.m_pData, other.m_pData + LENGTH, m_pData); return *this; } Array& operator=(Array<T, LENGTH>&& other) { for (size_t i = 0; i < LENGTH; i++) { m_pData[i] = std::move(other.m_pData[i]); } return *this; } ~Array() { } T& operator[](u32 index) { return m_pData[index]; } T const& operator[](u32 index) const { return m_pData[index]; } constexpr u32 size() const { return LENGTH; } T* raw() const { return m_pData; } }; }
14.233333
64
0.569087
LU15W1R7H
f05afcaf3ed05ba253818a720fa5abcfd082bd35
261
cc
C++
test/mocks/grpc/mocks.cc
htuch/envoy
f466a86e4bba81c18f5b59f0c56ea36aa663e174
[ "Apache-2.0" ]
2
2017-07-31T15:03:19.000Z
2018-02-20T16:18:49.000Z
test/mocks/grpc/mocks.cc
htuch/envoy
f466a86e4bba81c18f5b59f0c56ea36aa663e174
[ "Apache-2.0" ]
null
null
null
test/mocks/grpc/mocks.cc
htuch/envoy
f466a86e4bba81c18f5b59f0c56ea36aa663e174
[ "Apache-2.0" ]
null
null
null
#include "mocks.h" namespace Envoy { namespace Grpc { MockRpcChannelCallbacks::MockRpcChannelCallbacks() {} MockRpcChannelCallbacks::~MockRpcChannelCallbacks() {} MockRpcChannel::MockRpcChannel() {} MockRpcChannel::~MockRpcChannel() {} } // Grpc } // Envoy
18.642857
54
0.754789
htuch
f05e815d93655bacfc70fe1ce478ee32625984dd
881
cpp
C++
src/functions.cpp
cbries/tetrisgl
a40f22140d05c2cf6116946459a99a0477c1569a
[ "MIT" ]
1
2015-02-23T19:06:04.000Z
2015-02-23T19:06:04.000Z
src/functions.cpp
cbries/tetrisgl
a40f22140d05c2cf6116946459a99a0477c1569a
[ "MIT" ]
null
null
null
src/functions.cpp
cbries/tetrisgl
a40f22140d05c2cf6116946459a99a0477c1569a
[ "MIT" ]
null
null
null
/* * Copyright (c) 2008 Christian Benjamin Ries * License: MIT * Website: https://github.com/cbries/tetrisgl */ #include "functions.h" #include <GL/gl.h> void Enter2DMode( int startx, int starty, int width, int height ) { glPushAttrib(GL_ENABLE_BIT); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glViewport(startx, starty, width, height); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho((GLdouble)startx, (GLdouble)width, (GLdouble)starty, (GLdouble)height, -1.0, 1.0); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); } void Leave2DMode() { glMatrixMode(GL_MODELVIEW); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glPopAttrib(); }
21.487805
92
0.702611
cbries
f0661040e34c42c182ca269d08eafe3d14b1291c
1,350
hpp
C++
include/onepass/trackable.hpp
inql/OnePass
6e24d6bd6bcb70fdac4de5e4a155fcea68ea85ef
[ "Unlicense" ]
4
2021-10-20T17:40:33.000Z
2022-02-14T09:39:46.000Z
include/onepass/trackable.hpp
inql/OnePass
6e24d6bd6bcb70fdac4de5e4a155fcea68ea85ef
[ "Unlicense" ]
null
null
null
include/onepass/trackable.hpp
inql/OnePass
6e24d6bd6bcb70fdac4de5e4a155fcea68ea85ef
[ "Unlicense" ]
null
null
null
#ifndef TRACKABLE_HPP #define TRACKABLE_HPP namespace onepass { namespace core { template<class T> class Trackable { private: unsigned id_; time_t created_; time_t accessed_; friend class boost::serialization::access; public: T val_; Trackable() : id_(0) { } Trackable(unsigned i) : id_(i) { initialize(); } Trackable(unsigned i, T tracked) : id_(i), val_(tracked) { initialize(); } template<typename Archive> void serialize(Archive &ar, const unsigned int) { ar &id_; ar &created_; ar &accessed_; ar &val_; } unsigned getId() const { return id_; } time_t getCreated() const { return created_; } time_t getAccessed() const { return accessed_; } void initialize() { created_ = accessed_ = time(0); } void seen() { accessed_ = time(0); } std::string toString(time_t t) { char buffer[32]; std::tm *pmt = std::localtime(&t); std::strftime(buffer, 32, "%Y-%m-%d %H:%M:%S", pmt); return std::string{ buffer }; } }; } // namespace core } // namespace onepass #endif // TRACKABLE_HPP
19.285714
62
0.508889
inql
f06c0f25f37e1f31691505bc5a0f838dd83c8a8e
48,489
cpp
C++
Temp/il2cppOutput/il2cppOutput/Il2CppCompilerCalculateTypeValues_19Table.cpp
408794550/871AR
3f903d01ae05522413f7be7abb286d1944d00bbb
[ "Apache-2.0" ]
1
2018-08-16T10:43:30.000Z
2018-08-16T10:43:30.000Z
Temp/il2cppOutput/il2cppOutput/Il2CppCompilerCalculateTypeValues_19Table.cpp
408794550/871AR
3f903d01ae05522413f7be7abb286d1944d00bbb
[ "Apache-2.0" ]
null
null
null
Temp/il2cppOutput/il2cppOutput/Il2CppCompilerCalculateTypeValues_19Table.cpp
408794550/871AR
3f903d01ae05522413f7be7abb286d1944d00bbb
[ "Apache-2.0" ]
null
null
null
#include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <cstring> #include <string.h> #include <stdio.h> #include <cmath> #include <limits> #include <assert.h> #include "class-internals.h" #include "codegen/il2cpp-codegen.h" #include "UnityEngine_UI_UnityEngine_UI_PositionAsUV11102546563.h" #include "UnityEngine_UI_UnityEngine_UI_Shadow4269599528.h" #include "UnityEngine_UI_U3CPrivateImplementationDetailsU3E1486305137.h" #include "UnityEngine_UI_U3CPrivateImplementationDetailsU3E_1568637717.h" #include "DOTween43_U3CModuleU3E3783534214.h" #include "DOTween43_DG_Tweening_ShortcutExtensions43301896125.h" #include "DOTween43_DG_Tweening_ShortcutExtensions43_U3CU3Ec_426334720.h" #include "DOTween43_DG_Tweening_ShortcutExtensions43_U3CU3Ec_426334751.h" #include "DOTween43_DG_Tweening_ShortcutExtensions43_U3CU3Ec_426334817.h" #include "DOTween43_DG_Tweening_ShortcutExtensions43_U3CU3Ec_426334918.h" #include "DOTween46_U3CModuleU3E3783534214.h" #include "DOTween46_DG_Tweening_DOTweenUtils461550156519.h" #include "DOTween46_DG_Tweening_ShortcutExtensions46705180652.h" #include "DOTween46_DG_Tweening_ShortcutExtensions46_U3CU3Ec3371939845.h" #include "DOTween46_DG_Tweening_ShortcutExtensions46_U3CU3Ec3371939942.h" #include "DOTween46_DG_Tweening_ShortcutExtensions46_U3CU3Ec3371939977.h" #include "DOTween46_DG_Tweening_ShortcutExtensions46_U3CU3Ec3017480080.h" #include "DOTween46_DG_Tweening_ShortcutExtensions46_U3CU3Ec3582130305.h" #include "DOTween46_DG_Tweening_ShortcutExtensions46_U3CU3Ec_591124924.h" #include "DOTween46_DG_Tweening_ShortcutExtensions46_U3CU3Ec4039117214.h" #include "DOTween46_DG_Tweening_ShortcutExtensions46_U3CU3Ec_308799891.h" #include "DOTween46_DG_Tweening_ShortcutExtensions46_U3CU3Ec3582130274.h" #include "DOTween46_DG_Tweening_ShortcutExtensions46_U3CU3Ec_591124893.h" #include "DOTweenPro_U3CModuleU3E3783534214.h" #include "DOTweenPro_DG_Tweening_DOTweenVisualManager2945673405.h" #include "DOTweenPro_DG_Tweening_HandlesDrawMode3273484032.h" #include "DOTweenPro_DG_Tweening_HandlesType3201532857.h" #include "DOTweenPro_DG_Tweening_DOTweenInspectorMode2739551672.h" #include "DOTweenPro_DG_Tweening_DOTweenPath1397145371.h" #include "DOTweenPro_DG_Tweening_Core_ABSAnimationComponent2205594551.h" #include "DOTweenPro_DG_Tweening_Core_DOTweenAnimationType119935370.h" #include "DOTweenPro_DG_Tweening_Core_OnDisableBehaviour125315118.h" #include "DOTweenPro_DG_Tweening_Core_OnEnableBehaviour285142911.h" #include "DOTweenPro_DG_Tweening_Core_TargetType2706200073.h" #include "DOTweenPro_DG_Tweening_Core_VisualManagerPreset4087939440.h" #include "LitJson_U3CModuleU3E3783534214.h" #include "LitJson_LitJson_JsonType3145703806.h" #include "LitJson_LitJson_JsonData269267574.h" #include "LitJson_LitJson_OrderedDictionaryEnumerator3437478891.h" #include "LitJson_LitJson_JsonException613047007.h" #include "LitJson_LitJson_PropertyMetadata3693826136.h" #include "LitJson_LitJson_ArrayMetadata2008834462.h" #include "LitJson_LitJson_ObjectMetadata3995922398.h" #include "LitJson_LitJson_JsonMapper800426905.h" #include "LitJson_LitJson_JsonToken2852816099.h" #include "LitJson_LitJson_JsonReader1077921503.h" #include "LitJson_LitJson_Condition1980525237.h" #include "LitJson_LitJson_WriterContext4137194742.h" #include "LitJson_LitJson_JsonWriter1927598499.h" #include "LitJson_LitJson_FsmContext1296252303.h" #include "LitJson_LitJson_Lexer186508296.h" #include "LitJson_LitJson_Lexer_StateHandler387387051.h" #include "LitJson_LitJson_ParserToken1554180950.h" #include "LitJson_LitJson_ExporterFunc408878057.h" #include "LitJson_LitJson_ImporterFunc2977850894.h" #include "LitJson_LitJson_WrapperFactory2219329745.h" #include "LitJson_U3CPrivateImplementationDetailsU3E1486305137.h" #include "LitJson_U3CPrivateImplementationDetailsU3E_U24Arra4007721333.h" #include "Vuforia_UnityExtensions_U3CModuleU3E3783534214.h" #include "Vuforia_UnityExtensions_Vuforia_ARController2638793709.h" #include "Vuforia_UnityExtensions_Vuforia_ARController_U3CU32604000414.h" #include "Vuforia_UnityExtensions_Vuforia_DigitalEyewearARCo1398758191.h" #include "Vuforia_UnityExtensions_Vuforia_DigitalEyewearARCo2121820252.h" #include "Vuforia_UnityExtensions_Vuforia_DigitalEyewearARCo3746630162.h" #include "Vuforia_UnityExtensions_Vuforia_DigitalEyewearARCon342269456.h" #include "Vuforia_UnityExtensions_Vuforia_DigitalEyewearARCo2750347603.h" #include "Vuforia_UnityExtensions_Vuforia_EyewearDevice1202635122.h" #include "Vuforia_UnityExtensions_Vuforia_EyewearDevice_EyeID642957731.h" #include "Vuforia_UnityExtensions_Vuforia_EyewearDevice_Eyew1521251591.h" #include "Vuforia_UnityExtensions_Vuforia_NullHoloLensApiAbs1386933393.h" #include "Vuforia_UnityExtensions_Vuforia_DeviceTracker2183873360.h" #include "Vuforia_UnityExtensions_Vuforia_DeviceTrackerARCon3939888793.h" #include "Vuforia_UnityExtensions_Vuforia_DistortionRenderin3766399464.h" #include "Vuforia_UnityExtensions_Vuforia_DistortionRenderin2945034146.h" #include "Vuforia_UnityExtensions_Vuforia_DelegateHelper1202011487.h" #include "Vuforia_UnityExtensions_Vuforia_PlayModeEyewearUser117253723.h" #include "Vuforia_UnityExtensions_Vuforia_PlayModeEyewearCal3632467967.h" #include "Vuforia_UnityExtensions_Vuforia_PlayModeEyewearDev2977282393.h" #include "Vuforia_UnityExtensions_Vuforia_DedicatedEyewearDevi22891981.h" #include "Vuforia_UnityExtensions_Vuforia_CameraConfiguratio3904398347.h" #include "Vuforia_UnityExtensions_Vuforia_BaseCameraConfigurat38459502.h" #include "Vuforia_UnityExtensions_Vuforia_BaseStereoViewerCa1102239676.h" #include "Vuforia_UnityExtensions_Vuforia_StereoViewerCamera3365023487.h" #include "Vuforia_UnityExtensions_Vuforia_HoloLensExtendedTr3502001541.h" #include "Vuforia_UnityExtensions_Vuforia_HoloLensExtendedTr1161658011.h" #include "Vuforia_UnityExtensions_Vuforia_HoloLensExtendedTr3432166560.h" #include "Vuforia_UnityExtensions_Vuforia_VuforiaExtendedTra2074328369.h" #include "Vuforia_UnityExtensions_Vuforia_VuMarkManagerImpl1660847547.h" #include "Vuforia_UnityExtensions_Vuforia_InstanceIdImpl3955455590.h" #include "Vuforia_UnityExtensions_Vuforia_VuMarkTargetImpl2700679413.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1900 = { sizeof (PositionAsUV1_t1102546563), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1901 = { sizeof (Shadow_t4269599528), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1901[4] = { Shadow_t4269599528::get_offset_of_m_EffectColor_3(), Shadow_t4269599528::get_offset_of_m_EffectDistance_4(), Shadow_t4269599528::get_offset_of_m_UseGraphicAlpha_5(), 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1902 = { sizeof (U3CPrivateImplementationDetailsU3E_t1486305142), -1, sizeof(U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1902[1] = { U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields::get_offset_of_U24fieldU2D7BBE37982E6C057ED87163CAFC7FD6E5E42EEA46_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1903 = { sizeof (U24ArrayTypeU3D12_t1568637717)+ sizeof (Il2CppObject), sizeof(U24ArrayTypeU3D12_t1568637717 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1904 = { sizeof (U3CModuleU3E_t3783534221), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1905 = { sizeof (ShortcutExtensions43_t301896125), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1906 = { sizeof (U3CU3Ec__DisplayClass2_0_t426334720), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1906[1] = { U3CU3Ec__DisplayClass2_0_t426334720::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1907 = { sizeof (U3CU3Ec__DisplayClass3_0_t426334751), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1907[1] = { U3CU3Ec__DisplayClass3_0_t426334751::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1908 = { sizeof (U3CU3Ec__DisplayClass5_0_t426334817), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1908[1] = { U3CU3Ec__DisplayClass5_0_t426334817::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1909 = { sizeof (U3CU3Ec__DisplayClass8_0_t426334918), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1909[1] = { U3CU3Ec__DisplayClass8_0_t426334918::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1910 = { sizeof (U3CModuleU3E_t3783534222), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1911 = { sizeof (DOTweenUtils46_t1550156519), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1912 = { sizeof (ShortcutExtensions46_t705180652), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1913 = { sizeof (U3CU3Ec__DisplayClass0_0_t3371939845), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1913[1] = { U3CU3Ec__DisplayClass0_0_t3371939845::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1914 = { sizeof (U3CU3Ec__DisplayClass3_0_t3371939942), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1914[1] = { U3CU3Ec__DisplayClass3_0_t3371939942::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1915 = { sizeof (U3CU3Ec__DisplayClass4_0_t3371939977), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1915[1] = { U3CU3Ec__DisplayClass4_0_t3371939977::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1916 = { sizeof (U3CU3Ec__DisplayClass16_0_t3017480080), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1916[1] = { U3CU3Ec__DisplayClass16_0_t3017480080::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1917 = { sizeof (U3CU3Ec__DisplayClass22_0_t3582130305), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1917[1] = { U3CU3Ec__DisplayClass22_0_t3582130305::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1918 = { sizeof (U3CU3Ec__DisplayClass23_0_t591124924), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1918[1] = { U3CU3Ec__DisplayClass23_0_t591124924::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1919 = { sizeof (U3CU3Ec__DisplayClass25_0_t4039117214), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1919[1] = { U3CU3Ec__DisplayClass25_0_t4039117214::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1920 = { sizeof (U3CU3Ec__DisplayClass31_0_t308799891), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1920[1] = { U3CU3Ec__DisplayClass31_0_t308799891::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1921 = { sizeof (U3CU3Ec__DisplayClass32_0_t3582130274), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1921[1] = { U3CU3Ec__DisplayClass32_0_t3582130274::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1922 = { sizeof (U3CU3Ec__DisplayClass33_0_t591124893), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1922[1] = { U3CU3Ec__DisplayClass33_0_t591124893::get_offset_of_target_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1923 = { sizeof (U3CModuleU3E_t3783534223), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1924 = { sizeof (DOTweenVisualManager_t2945673405), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1924[4] = { DOTweenVisualManager_t2945673405::get_offset_of_preset_2(), DOTweenVisualManager_t2945673405::get_offset_of_onEnableBehaviour_3(), DOTweenVisualManager_t2945673405::get_offset_of_onDisableBehaviour_4(), DOTweenVisualManager_t2945673405::get_offset_of__requiresRestartFromSpawnPoint_5(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1925 = { sizeof (HandlesDrawMode_t3273484032)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1925[3] = { HandlesDrawMode_t3273484032::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1926 = { sizeof (HandlesType_t3201532857)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1926[3] = { HandlesType_t3201532857::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1927 = { sizeof (DOTweenInspectorMode_t2739551672)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1927[3] = { DOTweenInspectorMode_t2739551672::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1928 = { sizeof (DOTweenPath_t1397145371), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1928[36] = { DOTweenPath_t1397145371::get_offset_of_delay_17(), DOTweenPath_t1397145371::get_offset_of_duration_18(), DOTweenPath_t1397145371::get_offset_of_easeType_19(), DOTweenPath_t1397145371::get_offset_of_easeCurve_20(), DOTweenPath_t1397145371::get_offset_of_loops_21(), DOTweenPath_t1397145371::get_offset_of_id_22(), DOTweenPath_t1397145371::get_offset_of_loopType_23(), DOTweenPath_t1397145371::get_offset_of_orientType_24(), DOTweenPath_t1397145371::get_offset_of_lookAtTransform_25(), DOTweenPath_t1397145371::get_offset_of_lookAtPosition_26(), DOTweenPath_t1397145371::get_offset_of_lookAhead_27(), DOTweenPath_t1397145371::get_offset_of_autoPlay_28(), DOTweenPath_t1397145371::get_offset_of_autoKill_29(), DOTweenPath_t1397145371::get_offset_of_relative_30(), DOTweenPath_t1397145371::get_offset_of_isLocal_31(), DOTweenPath_t1397145371::get_offset_of_isClosedPath_32(), DOTweenPath_t1397145371::get_offset_of_pathResolution_33(), DOTweenPath_t1397145371::get_offset_of_pathMode_34(), DOTweenPath_t1397145371::get_offset_of_lockRotation_35(), DOTweenPath_t1397145371::get_offset_of_assignForwardAndUp_36(), DOTweenPath_t1397145371::get_offset_of_forwardDirection_37(), DOTweenPath_t1397145371::get_offset_of_upDirection_38(), DOTweenPath_t1397145371::get_offset_of_wps_39(), DOTweenPath_t1397145371::get_offset_of_fullWps_40(), DOTweenPath_t1397145371::get_offset_of_path_41(), DOTweenPath_t1397145371::get_offset_of_inspectorMode_42(), DOTweenPath_t1397145371::get_offset_of_pathType_43(), DOTweenPath_t1397145371::get_offset_of_handlesType_44(), DOTweenPath_t1397145371::get_offset_of_livePreview_45(), DOTweenPath_t1397145371::get_offset_of_handlesDrawMode_46(), DOTweenPath_t1397145371::get_offset_of_perspectiveHandleSize_47(), DOTweenPath_t1397145371::get_offset_of_showIndexes_48(), DOTweenPath_t1397145371::get_offset_of_showWpLength_49(), DOTweenPath_t1397145371::get_offset_of_pathColor_50(), DOTweenPath_t1397145371::get_offset_of_lastSrcPosition_51(), DOTweenPath_t1397145371::get_offset_of_wpsDropdown_52(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1929 = { sizeof (ABSAnimationComponent_t2205594551), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1929[15] = { ABSAnimationComponent_t2205594551::get_offset_of_updateType_2(), ABSAnimationComponent_t2205594551::get_offset_of_isSpeedBased_3(), ABSAnimationComponent_t2205594551::get_offset_of_hasOnStart_4(), ABSAnimationComponent_t2205594551::get_offset_of_hasOnPlay_5(), ABSAnimationComponent_t2205594551::get_offset_of_hasOnUpdate_6(), ABSAnimationComponent_t2205594551::get_offset_of_hasOnStepComplete_7(), ABSAnimationComponent_t2205594551::get_offset_of_hasOnComplete_8(), ABSAnimationComponent_t2205594551::get_offset_of_hasOnTweenCreated_9(), ABSAnimationComponent_t2205594551::get_offset_of_onStart_10(), ABSAnimationComponent_t2205594551::get_offset_of_onPlay_11(), ABSAnimationComponent_t2205594551::get_offset_of_onUpdate_12(), ABSAnimationComponent_t2205594551::get_offset_of_onStepComplete_13(), ABSAnimationComponent_t2205594551::get_offset_of_onComplete_14(), ABSAnimationComponent_t2205594551::get_offset_of_onTweenCreated_15(), ABSAnimationComponent_t2205594551::get_offset_of_tween_16(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1930 = { sizeof (DOTweenAnimationType_t119935370)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1930[23] = { DOTweenAnimationType_t119935370::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1931 = { sizeof (OnDisableBehaviour_t125315118)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1931[7] = { OnDisableBehaviour_t125315118::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1932 = { sizeof (OnEnableBehaviour_t285142911)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1932[5] = { OnEnableBehaviour_t285142911::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1933 = { sizeof (TargetType_t2706200073)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1933[17] = { TargetType_t2706200073::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1934 = { sizeof (VisualManagerPreset_t4087939440)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1934[3] = { VisualManagerPreset_t4087939440::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1935 = { sizeof (U3CModuleU3E_t3783534224), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1936 = { sizeof (JsonType_t3145703806)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1936[9] = { JsonType_t3145703806::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1937 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1938 = { sizeof (JsonData_t269267574), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1938[10] = { JsonData_t269267574::get_offset_of_inst_array_0(), JsonData_t269267574::get_offset_of_inst_boolean_1(), JsonData_t269267574::get_offset_of_inst_double_2(), JsonData_t269267574::get_offset_of_inst_int_3(), JsonData_t269267574::get_offset_of_inst_long_4(), JsonData_t269267574::get_offset_of_inst_object_5(), JsonData_t269267574::get_offset_of_inst_string_6(), JsonData_t269267574::get_offset_of_json_7(), JsonData_t269267574::get_offset_of_type_8(), JsonData_t269267574::get_offset_of_object_list_9(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1939 = { sizeof (OrderedDictionaryEnumerator_t3437478891), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1939[1] = { OrderedDictionaryEnumerator_t3437478891::get_offset_of_list_enumerator_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1940 = { sizeof (JsonException_t613047007), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1941 = { sizeof (PropertyMetadata_t3693826136)+ sizeof (Il2CppObject), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1941[3] = { PropertyMetadata_t3693826136::get_offset_of_Info_0() + static_cast<int32_t>(sizeof(Il2CppObject)), PropertyMetadata_t3693826136::get_offset_of_IsField_1() + static_cast<int32_t>(sizeof(Il2CppObject)), PropertyMetadata_t3693826136::get_offset_of_Type_2() + static_cast<int32_t>(sizeof(Il2CppObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1942 = { sizeof (ArrayMetadata_t2008834462)+ sizeof (Il2CppObject), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1942[3] = { ArrayMetadata_t2008834462::get_offset_of_element_type_0() + static_cast<int32_t>(sizeof(Il2CppObject)), ArrayMetadata_t2008834462::get_offset_of_is_array_1() + static_cast<int32_t>(sizeof(Il2CppObject)), ArrayMetadata_t2008834462::get_offset_of_is_list_2() + static_cast<int32_t>(sizeof(Il2CppObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1943 = { sizeof (ObjectMetadata_t3995922398)+ sizeof (Il2CppObject), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1943[3] = { ObjectMetadata_t3995922398::get_offset_of_element_type_0() + static_cast<int32_t>(sizeof(Il2CppObject)), ObjectMetadata_t3995922398::get_offset_of_is_dictionary_1() + static_cast<int32_t>(sizeof(Il2CppObject)), ObjectMetadata_t3995922398::get_offset_of_properties_2() + static_cast<int32_t>(sizeof(Il2CppObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1944 = { sizeof (JsonMapper_t800426905), -1, sizeof(JsonMapper_t800426905_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1944[38] = { JsonMapper_t800426905_StaticFields::get_offset_of_max_nesting_depth_0(), JsonMapper_t800426905_StaticFields::get_offset_of_datetime_format_1(), JsonMapper_t800426905_StaticFields::get_offset_of_base_exporters_table_2(), JsonMapper_t800426905_StaticFields::get_offset_of_custom_exporters_table_3(), JsonMapper_t800426905_StaticFields::get_offset_of_base_importers_table_4(), JsonMapper_t800426905_StaticFields::get_offset_of_custom_importers_table_5(), JsonMapper_t800426905_StaticFields::get_offset_of_array_metadata_6(), JsonMapper_t800426905_StaticFields::get_offset_of_array_metadata_lock_7(), JsonMapper_t800426905_StaticFields::get_offset_of_conv_ops_8(), JsonMapper_t800426905_StaticFields::get_offset_of_conv_ops_lock_9(), JsonMapper_t800426905_StaticFields::get_offset_of_object_metadata_10(), JsonMapper_t800426905_StaticFields::get_offset_of_object_metadata_lock_11(), JsonMapper_t800426905_StaticFields::get_offset_of_type_properties_12(), JsonMapper_t800426905_StaticFields::get_offset_of_type_properties_lock_13(), JsonMapper_t800426905_StaticFields::get_offset_of_static_writer_14(), JsonMapper_t800426905_StaticFields::get_offset_of_static_writer_lock_15(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache10_16(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache11_17(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache12_18(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache13_19(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache14_20(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache15_21(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache16_22(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache17_23(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache18_24(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache19_25(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache1A_26(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache1B_27(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache1C_28(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache1D_29(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache1E_30(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache1F_31(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache20_32(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache21_33(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache22_34(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache23_35(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache24_36(), JsonMapper_t800426905_StaticFields::get_offset_of_U3CU3Ef__amU24cache27_37(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1945 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable1945[1] = { 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1946 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable1946[1] = { 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1947 = { sizeof (JsonToken_t2852816099)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1947[13] = { JsonToken_t2852816099::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1948 = { sizeof (JsonReader_t1077921503), -1, sizeof(JsonReader_t1077921503_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1948[14] = { JsonReader_t1077921503_StaticFields::get_offset_of_parse_table_0(), JsonReader_t1077921503::get_offset_of_automaton_stack_1(), JsonReader_t1077921503::get_offset_of_current_input_2(), JsonReader_t1077921503::get_offset_of_current_symbol_3(), JsonReader_t1077921503::get_offset_of_end_of_json_4(), JsonReader_t1077921503::get_offset_of_end_of_input_5(), JsonReader_t1077921503::get_offset_of_lexer_6(), JsonReader_t1077921503::get_offset_of_parser_in_string_7(), JsonReader_t1077921503::get_offset_of_parser_return_8(), JsonReader_t1077921503::get_offset_of_read_started_9(), JsonReader_t1077921503::get_offset_of_reader_10(), JsonReader_t1077921503::get_offset_of_reader_is_owned_11(), JsonReader_t1077921503::get_offset_of_token_value_12(), JsonReader_t1077921503::get_offset_of_token_13(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1949 = { sizeof (Condition_t1980525237)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1949[6] = { Condition_t1980525237::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1950 = { sizeof (WriterContext_t4137194742), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1950[5] = { WriterContext_t4137194742::get_offset_of_Count_0(), WriterContext_t4137194742::get_offset_of_InArray_1(), WriterContext_t4137194742::get_offset_of_InObject_2(), WriterContext_t4137194742::get_offset_of_ExpectingValue_3(), WriterContext_t4137194742::get_offset_of_Padding_4(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1951 = { sizeof (JsonWriter_t1927598499), -1, sizeof(JsonWriter_t1927598499_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1951[11] = { JsonWriter_t1927598499_StaticFields::get_offset_of_number_format_0(), JsonWriter_t1927598499::get_offset_of_context_1(), JsonWriter_t1927598499::get_offset_of_ctx_stack_2(), JsonWriter_t1927598499::get_offset_of_has_reached_end_3(), JsonWriter_t1927598499::get_offset_of_hex_seq_4(), JsonWriter_t1927598499::get_offset_of_indentation_5(), JsonWriter_t1927598499::get_offset_of_indent_value_6(), JsonWriter_t1927598499::get_offset_of_inst_string_builder_7(), JsonWriter_t1927598499::get_offset_of_pretty_print_8(), JsonWriter_t1927598499::get_offset_of_validate_9(), JsonWriter_t1927598499::get_offset_of_writer_10(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1952 = { sizeof (FsmContext_t1296252303), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1952[4] = { FsmContext_t1296252303::get_offset_of_Return_0(), FsmContext_t1296252303::get_offset_of_NextState_1(), FsmContext_t1296252303::get_offset_of_L_2(), FsmContext_t1296252303::get_offset_of_StateStack_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1953 = { sizeof (Lexer_t186508296), -1, sizeof(Lexer_t186508296_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1953[14] = { Lexer_t186508296_StaticFields::get_offset_of_fsm_return_table_0(), Lexer_t186508296_StaticFields::get_offset_of_fsm_handler_table_1(), Lexer_t186508296::get_offset_of_allow_comments_2(), Lexer_t186508296::get_offset_of_allow_single_quoted_strings_3(), Lexer_t186508296::get_offset_of_end_of_input_4(), Lexer_t186508296::get_offset_of_fsm_context_5(), Lexer_t186508296::get_offset_of_input_buffer_6(), Lexer_t186508296::get_offset_of_input_char_7(), Lexer_t186508296::get_offset_of_reader_8(), Lexer_t186508296::get_offset_of_state_9(), Lexer_t186508296::get_offset_of_string_buffer_10(), Lexer_t186508296::get_offset_of_string_value_11(), Lexer_t186508296::get_offset_of_token_12(), Lexer_t186508296::get_offset_of_unichar_13(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1954 = { sizeof (StateHandler_t387387051), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1955 = { sizeof (ParserToken_t1554180950)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1955[20] = { ParserToken_t1554180950::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1956 = { sizeof (ExporterFunc_t408878057), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1957 = { 0, 0, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1958 = { sizeof (ImporterFunc_t2977850894), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1959 = { 0, 0, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1960 = { sizeof (WrapperFactory_t2219329745), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1961 = { sizeof (U3CPrivateImplementationDetailsU3E_t1486305143), -1, sizeof(U3CPrivateImplementationDetailsU3E_t1486305143_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1961[1] = { U3CPrivateImplementationDetailsU3E_t1486305143_StaticFields::get_offset_of_U24U24fieldU2D0_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1962 = { sizeof (U24ArrayTypeU24112_t4007721333)+ sizeof (Il2CppObject), sizeof(U24ArrayTypeU24112_t4007721333 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1963 = { sizeof (U3CModuleU3E_t3783534225), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1964 = { sizeof (ARController_t2638793709), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1964[1] = { ARController_t2638793709::get_offset_of_mVuforiaBehaviour_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1965 = { sizeof (U3CU3Ec__DisplayClass11_0_t2604000414), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1965[1] = { U3CU3Ec__DisplayClass11_0_t2604000414::get_offset_of_controller_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1966 = { sizeof (DigitalEyewearARController_t1398758191), -1, sizeof(DigitalEyewearARController_t1398758191_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1966[28] = { 0, 0, 0, 0, 0, 0, DigitalEyewearARController_t1398758191::get_offset_of_mCameraOffset_7(), DigitalEyewearARController_t1398758191::get_offset_of_mDistortionRenderingMode_8(), DigitalEyewearARController_t1398758191::get_offset_of_mDistortionRenderingLayer_9(), DigitalEyewearARController_t1398758191::get_offset_of_mEyewearType_10(), DigitalEyewearARController_t1398758191::get_offset_of_mStereoFramework_11(), DigitalEyewearARController_t1398758191::get_offset_of_mSeeThroughConfiguration_12(), DigitalEyewearARController_t1398758191::get_offset_of_mViewerName_13(), DigitalEyewearARController_t1398758191::get_offset_of_mViewerManufacturer_14(), DigitalEyewearARController_t1398758191::get_offset_of_mUseCustomViewer_15(), DigitalEyewearARController_t1398758191::get_offset_of_mCustomViewer_16(), DigitalEyewearARController_t1398758191::get_offset_of_mCentralAnchorPoint_17(), DigitalEyewearARController_t1398758191::get_offset_of_mParentAnchorPoint_18(), DigitalEyewearARController_t1398758191::get_offset_of_mPrimaryCamera_19(), DigitalEyewearARController_t1398758191::get_offset_of_mPrimaryCameraOriginalRect_20(), DigitalEyewearARController_t1398758191::get_offset_of_mSecondaryCamera_21(), DigitalEyewearARController_t1398758191::get_offset_of_mSecondaryCameraOriginalRect_22(), DigitalEyewearARController_t1398758191::get_offset_of_mSecondaryCameraDisabledLocally_23(), DigitalEyewearARController_t1398758191::get_offset_of_mVuforiaBehaviour_24(), DigitalEyewearARController_t1398758191::get_offset_of_mDistortionRenderingBhvr_25(), DigitalEyewearARController_t1398758191::get_offset_of_mSetFocusPlaneAutomatically_26(), DigitalEyewearARController_t1398758191_StaticFields::get_offset_of_mInstance_27(), DigitalEyewearARController_t1398758191_StaticFields::get_offset_of_mPadlock_28(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1967 = { sizeof (EyewearType_t2121820252)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1967[4] = { EyewearType_t2121820252::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1968 = { sizeof (StereoFramework_t3746630162)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1968[4] = { StereoFramework_t3746630162::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1969 = { sizeof (SeeThroughConfiguration_t342269456)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1969[3] = { SeeThroughConfiguration_t342269456::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1970 = { sizeof (SerializableViewerParameters_t2750347603), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1970[11] = { SerializableViewerParameters_t2750347603::get_offset_of_Version_0(), SerializableViewerParameters_t2750347603::get_offset_of_Name_1(), SerializableViewerParameters_t2750347603::get_offset_of_Manufacturer_2(), SerializableViewerParameters_t2750347603::get_offset_of_ButtonType_3(), SerializableViewerParameters_t2750347603::get_offset_of_ScreenToLensDistance_4(), SerializableViewerParameters_t2750347603::get_offset_of_InterLensDistance_5(), SerializableViewerParameters_t2750347603::get_offset_of_TrayAlignment_6(), SerializableViewerParameters_t2750347603::get_offset_of_LensCenterToTrayDistance_7(), SerializableViewerParameters_t2750347603::get_offset_of_DistortionCoefficients_8(), SerializableViewerParameters_t2750347603::get_offset_of_FieldOfView_9(), SerializableViewerParameters_t2750347603::get_offset_of_ContainsMagnet_10(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1971 = { sizeof (EyewearDevice_t1202635122), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1972 = { sizeof (EyeID_t642957731)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1972[4] = { EyeID_t642957731::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1973 = { sizeof (EyewearCalibrationReading_t1521251591)+ sizeof (Il2CppObject), sizeof(EyewearCalibrationReading_t1521251591_marshaled_pinvoke), 0, 0 }; extern const int32_t g_FieldOffsetTable1973[5] = { EyewearCalibrationReading_t1521251591::get_offset_of_pose_0() + static_cast<int32_t>(sizeof(Il2CppObject)), EyewearCalibrationReading_t1521251591::get_offset_of_scale_1() + static_cast<int32_t>(sizeof(Il2CppObject)), EyewearCalibrationReading_t1521251591::get_offset_of_centerX_2() + static_cast<int32_t>(sizeof(Il2CppObject)), EyewearCalibrationReading_t1521251591::get_offset_of_centerY_3() + static_cast<int32_t>(sizeof(Il2CppObject)), EyewearCalibrationReading_t1521251591::get_offset_of_unused_4() + static_cast<int32_t>(sizeof(Il2CppObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1974 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1975 = { sizeof (NullHoloLensApiAbstraction_t1386933393), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1976 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1977 = { sizeof (DeviceTracker_t2183873360), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1978 = { sizeof (DeviceTrackerARController_t3939888793), -1, sizeof(DeviceTrackerARController_t3939888793_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1978[13] = { DeviceTrackerARController_t3939888793_StaticFields::get_offset_of_DEFAULT_HEAD_PIVOT_1(), DeviceTrackerARController_t3939888793_StaticFields::get_offset_of_DEFAULT_HANDHELD_PIVOT_2(), DeviceTrackerARController_t3939888793::get_offset_of_mAutoInitTracker_3(), DeviceTrackerARController_t3939888793::get_offset_of_mAutoStartTracker_4(), DeviceTrackerARController_t3939888793::get_offset_of_mPosePrediction_5(), DeviceTrackerARController_t3939888793::get_offset_of_mModelCorrectionMode_6(), DeviceTrackerARController_t3939888793::get_offset_of_mModelTransformEnabled_7(), DeviceTrackerARController_t3939888793::get_offset_of_mModelTransform_8(), DeviceTrackerARController_t3939888793::get_offset_of_mTrackerStarted_9(), DeviceTrackerARController_t3939888793::get_offset_of_mTrackerWasActiveBeforePause_10(), DeviceTrackerARController_t3939888793::get_offset_of_mTrackerWasActiveBeforeDisabling_11(), DeviceTrackerARController_t3939888793_StaticFields::get_offset_of_mInstance_12(), DeviceTrackerARController_t3939888793_StaticFields::get_offset_of_mPadlock_13(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1979 = { sizeof (DistortionRenderingMode_t3766399464)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1979[4] = { DistortionRenderingMode_t3766399464::get_offset_of_value___1() + static_cast<int32_t>(sizeof(Il2CppObject)), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1980 = { sizeof (DistortionRenderingBehaviour_t2945034146), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1980[12] = { DistortionRenderingBehaviour_t2945034146::get_offset_of_mSingleTexture_2(), DistortionRenderingBehaviour_t2945034146::get_offset_of_mRenderLayer_3(), DistortionRenderingBehaviour_t2945034146::get_offset_of_mOriginalCullingMasks_4(), DistortionRenderingBehaviour_t2945034146::get_offset_of_mStereoCameras_5(), DistortionRenderingBehaviour_t2945034146::get_offset_of_mMeshes_6(), DistortionRenderingBehaviour_t2945034146::get_offset_of_mTextures_7(), DistortionRenderingBehaviour_t2945034146::get_offset_of_mStarted_8(), DistortionRenderingBehaviour_t2945034146::get_offset_of_mVideoBackgroundChanged_9(), DistortionRenderingBehaviour_t2945034146::get_offset_of_mOriginalLeftViewport_10(), DistortionRenderingBehaviour_t2945034146::get_offset_of_mOriginalRightViewport_11(), DistortionRenderingBehaviour_t2945034146::get_offset_of_mDualTextureLeftViewport_12(), DistortionRenderingBehaviour_t2945034146::get_offset_of_mDualTextureRightViewport_13(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1981 = { sizeof (DelegateHelper_t1202011487), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1982 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1983 = { sizeof (PlayModeEyewearUserCalibratorImpl_t117253723), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1984 = { sizeof (PlayModeEyewearCalibrationProfileManagerImpl_t3632467967), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1985 = { sizeof (PlayModeEyewearDevice_t2977282393), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1985[3] = { PlayModeEyewearDevice_t2977282393::get_offset_of_mProfileManager_1(), PlayModeEyewearDevice_t2977282393::get_offset_of_mCalibrator_2(), PlayModeEyewearDevice_t2977282393::get_offset_of_mDummyPredictiveTracking_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1986 = { sizeof (DedicatedEyewearDevice_t22891981), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1986[2] = { DedicatedEyewearDevice_t22891981::get_offset_of_mProfileManager_1(), DedicatedEyewearDevice_t22891981::get_offset_of_mCalibrator_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1987 = { sizeof (CameraConfigurationUtility_t3904398347), -1, sizeof(CameraConfigurationUtility_t3904398347_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1987[6] = { CameraConfigurationUtility_t3904398347_StaticFields::get_offset_of_MIN_CENTER_0(), CameraConfigurationUtility_t3904398347_StaticFields::get_offset_of_MAX_CENTER_1(), CameraConfigurationUtility_t3904398347_StaticFields::get_offset_of_MAX_BOTTOM_2(), CameraConfigurationUtility_t3904398347_StaticFields::get_offset_of_MAX_TOP_3(), CameraConfigurationUtility_t3904398347_StaticFields::get_offset_of_MAX_LEFT_4(), CameraConfigurationUtility_t3904398347_StaticFields::get_offset_of_MAX_RIGHT_5(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1988 = { sizeof (BaseCameraConfiguration_t38459502), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1988[10] = { BaseCameraConfiguration_t38459502::get_offset_of_mCameraDeviceMode_0(), BaseCameraConfiguration_t38459502::get_offset_of_mLastVideoBackGroundMirroredFromSDK_1(), BaseCameraConfiguration_t38459502::get_offset_of_mOnVideoBackgroundConfigChanged_2(), BaseCameraConfiguration_t38459502::get_offset_of_mVideoBackgroundBehaviours_3(), BaseCameraConfiguration_t38459502::get_offset_of_mVideoBackgroundViewportRect_4(), BaseCameraConfiguration_t38459502::get_offset_of_mRenderVideoBackground_5(), BaseCameraConfiguration_t38459502::get_offset_of_mProjectionOrientation_6(), BaseCameraConfiguration_t38459502::get_offset_of_mInitialReflection_7(), BaseCameraConfiguration_t38459502::get_offset_of_mBackgroundPlaneBehaviour_8(), BaseCameraConfiguration_t38459502::get_offset_of_mCameraParameterChanged_9(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1989 = { sizeof (BaseStereoViewerCameraConfiguration_t1102239676), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1989[5] = { BaseStereoViewerCameraConfiguration_t1102239676::get_offset_of_mPrimaryCamera_10(), BaseStereoViewerCameraConfiguration_t1102239676::get_offset_of_mSecondaryCamera_11(), BaseStereoViewerCameraConfiguration_t1102239676::get_offset_of_mSkewFrustum_12(), BaseStereoViewerCameraConfiguration_t1102239676::get_offset_of_mScreenWidth_13(), BaseStereoViewerCameraConfiguration_t1102239676::get_offset_of_mScreenHeight_14(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1990 = { sizeof (StereoViewerCameraConfiguration_t3365023487), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1990[7] = { 0, StereoViewerCameraConfiguration_t3365023487::get_offset_of_mLastAppliedLeftNearClipPlane_16(), StereoViewerCameraConfiguration_t3365023487::get_offset_of_mLastAppliedLeftFarClipPlane_17(), StereoViewerCameraConfiguration_t3365023487::get_offset_of_mLastAppliedRightNearClipPlane_18(), StereoViewerCameraConfiguration_t3365023487::get_offset_of_mLastAppliedRightFarClipPlane_19(), StereoViewerCameraConfiguration_t3365023487::get_offset_of_mCameraOffset_20(), StereoViewerCameraConfiguration_t3365023487::get_offset_of_mIsDistorted_21(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1991 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1992 = { sizeof (HoloLensExtendedTrackingManager_t3502001541), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1992[15] = { HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mNumFramesStablePose_0(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mMaxPoseRelDistance_1(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mMaxPoseAngleDiff_2(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mMaxCamPoseAbsDistance_3(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mMaxCamPoseAngleDiff_4(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mMinNumFramesPoseOff_5(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mMinPoseUpdateRelDistance_6(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mMinPoseUpdateAngleDiff_7(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mTrackableSizeInViewThreshold_8(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mMaxDistanceFromViewCenterForPoseUpdate_9(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mSetWorldAnchors_10(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mTrackingList_11(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mTrackablesExtendedTrackingEnabled_12(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mTrackablesCurrentlyExtendedTracked_13(), HoloLensExtendedTrackingManager_t3502001541::get_offset_of_mExtendedTrackablesState_14(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1993 = { sizeof (PoseInfo_t1161658011)+ sizeof (Il2CppObject), sizeof(PoseInfo_t1161658011 ), 0, 0 }; extern const int32_t g_FieldOffsetTable1993[3] = { PoseInfo_t1161658011::get_offset_of_Position_0() + static_cast<int32_t>(sizeof(Il2CppObject)), PoseInfo_t1161658011::get_offset_of_Rotation_1() + static_cast<int32_t>(sizeof(Il2CppObject)), PoseInfo_t1161658011::get_offset_of_NumFramesPoseWasOff_2() + static_cast<int32_t>(sizeof(Il2CppObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1994 = { sizeof (PoseAgeEntry_t3432166560)+ sizeof (Il2CppObject), sizeof(PoseAgeEntry_t3432166560 ), 0, 0 }; extern const int32_t g_FieldOffsetTable1994[3] = { PoseAgeEntry_t3432166560::get_offset_of_Pose_0() + static_cast<int32_t>(sizeof(Il2CppObject)), PoseAgeEntry_t3432166560::get_offset_of_CameraPose_1() + static_cast<int32_t>(sizeof(Il2CppObject)), PoseAgeEntry_t3432166560::get_offset_of_Age_2() + static_cast<int32_t>(sizeof(Il2CppObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1995 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1996 = { sizeof (VuforiaExtendedTrackingManager_t2074328369), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1997 = { sizeof (VuMarkManagerImpl_t1660847547), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1997[6] = { VuMarkManagerImpl_t1660847547::get_offset_of_mBehaviours_0(), VuMarkManagerImpl_t1660847547::get_offset_of_mActiveVuMarkTargets_1(), VuMarkManagerImpl_t1660847547::get_offset_of_mDestroyedBehaviours_2(), VuMarkManagerImpl_t1660847547::get_offset_of_mOnVuMarkDetected_3(), VuMarkManagerImpl_t1660847547::get_offset_of_mOnVuMarkLost_4(), VuMarkManagerImpl_t1660847547::get_offset_of_mOnVuMarkBehaviourDetected_5(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1998 = { sizeof (InstanceIdImpl_t3955455590), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1998[5] = { InstanceIdImpl_t3955455590::get_offset_of_mDataType_0(), InstanceIdImpl_t3955455590::get_offset_of_mBuffer_1(), InstanceIdImpl_t3955455590::get_offset_of_mNumericValue_2(), InstanceIdImpl_t3955455590::get_offset_of_mDataLength_3(), InstanceIdImpl_t3955455590::get_offset_of_mCachedStringValue_4(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1999 = { sizeof (VuMarkTargetImpl_t2700679413), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1999[5] = { VuMarkTargetImpl_t2700679413::get_offset_of_mVuMarkTemplate_0(), VuMarkTargetImpl_t2700679413::get_offset_of_mInstanceId_1(), VuMarkTargetImpl_t2700679413::get_offset_of_mTargetId_2(), VuMarkTargetImpl_t2700679413::get_offset_of_mInstanceImage_3(), VuMarkTargetImpl_t2700679413::get_offset_of_mInstanceImageHeader_4(), }; #ifdef __clang__ #pragma clang diagnostic pop #endif
54.789831
211
0.855761
408794550
f06ee92972823d6b60af68a5fc9664e81b799368
646
hpp
C++
test/split.hpp
ortfero/chineseroom
6532df6af72f0ab7597e70e00c7f50c45af43c28
[ "MIT" ]
null
null
null
test/split.hpp
ortfero/chineseroom
6532df6af72f0ab7597e70e00c7f50c45af43c28
[ "MIT" ]
null
null
null
test/split.hpp
ortfero/chineseroom
6532df6af72f0ab7597e70e00c7f50c45af43c28
[ "MIT" ]
null
null
null
#pragma once #include <doctest/doctest.h> #include <chineseroom/split.hpp> TEST_CASE("splitting string '1,2,,3,'") { auto const splitted = chineseroom::split(std::string{"1,2,,3,"}, ','); REQUIRE(splitted.size() == 3); REQUIRE(splitted[0] == "1"); REQUIRE(splitted[1] == "2"); REQUIRE(splitted[2] == "3"); } TEST_CASE("strictly splitting string '1,2,,3,'") { auto const splitted = chineseroom::split_strictly(std::string{"1,2,,3,"}, ','); REQUIRE(splitted.size() == 5); REQUIRE(splitted[0] == "1"); REQUIRE(splitted[1] == "2"); REQUIRE(splitted[2] == ""); REQUIRE(splitted[3] == "3"); REQUIRE(splitted[4] == ""); }
23.925926
81
0.608359
ortfero
7eb7a059af5ad373bdf75c3559c30c7b4abc159a
4,987
cpp
C++
source/Dream/Events/Source.cpp
kurocha/dream-events
b2cf5a188d8e3be2a07a5b7d36ed3eebc812cb72
[ "MIT", "Unlicense" ]
null
null
null
source/Dream/Events/Source.cpp
kurocha/dream-events
b2cf5a188d8e3be2a07a5b7d36ed3eebc812cb72
[ "MIT", "Unlicense" ]
null
null
null
source/Dream/Events/Source.cpp
kurocha/dream-events
b2cf5a188d8e3be2a07a5b7d36ed3eebc812cb72
[ "MIT", "Unlicense" ]
null
null
null
// // Events/Source.cpp // This file is part of the "Dream" project, and is released under the MIT license. // // Created by Samuel Williams on 9/12/08. // Copyright (c) 2008 Samuel Williams. All rights reserved. // // #include "Source.hpp" #include "Loop.hpp" #include <fcntl.h> #include <iostream> #include <unistd.h> #include <Dream/Core/Logger.hpp> namespace Dream { namespace Events { // MARK: - // MARK: class NotificationSource NotificationSource::NotificationSource (CallbackT callback) : _callback(callback) { } void NotificationSource::process_events (Loop * event_loop, Event event) { if (event == NOTIFICATION) _callback(event_loop, this, event); } NotificationSource::~NotificationSource () { } static void stop_run_loop_callback (Loop * event_loop, NotificationSource * note, Event enent) { event_loop->stop(); } Ref<NotificationSource> NotificationSource::stop_loop_notification () { return new NotificationSource(stop_run_loop_callback); } // MARK: - // MARK: class TimerSource TimerSource::TimerSource (CallbackT callback, TimeT duration, bool repeats, bool strict) : _cancelled(false), _repeats(repeats), _strict(strict), _duration(duration), _callback(callback) { } TimerSource::~TimerSource () { } void TimerSource::process_events (Loop * rl, Event events) { if (!_cancelled) _callback(rl, this, events); } bool TimerSource::repeats () const { if (_cancelled) return false; return _repeats; } TimeT TimerSource::next_timeout (const TimeT & last_timeout, const TimeT & current_time) const { // This means that TimerSource will attempt to "catch-up" //return last_timeout + _duration; // This means that TimerSource will process updates as is possible, and might drop // updates if they are in the past if (!_strict && last_timeout + _duration < current_time) return current_time; else return last_timeout + _duration; } void TimerSource::cancel () { _cancelled = true; } // MARK: - // MARK: class IFileDescriptorSource void IFileDescriptorSource::debug_file_descriptor_flags(int fd) { std::stringstream log_buffer; int flags = fcntl(fd, F_GETFL); log_buffer << "Flags for #" << fd << ":"; if (flags & O_NONBLOCK) log_buffer << " NONBLOCK"; int access_mode = flags & O_ACCMODE; if (access_mode == O_RDONLY) log_buffer << " RDONLY"; else if (access_mode == O_WRONLY) log_buffer << " WRONLY"; else log_buffer << " RDWR"; if (flags & O_APPEND) log_buffer << " APPEND"; if (flags & O_CREAT) log_buffer << " CREATE"; if (flags & O_TRUNC) log_buffer << " TRUNCATE"; log_debug(log_buffer.str()); } void IFileDescriptorSource::set_will_block (bool value) { FileDescriptor curfd = file_descriptor(); if (value == false) { fcntl(curfd, F_SETFL, fcntl(curfd, F_GETFL) | O_NONBLOCK); } else { fcntl(curfd, F_SETFL, fcntl(curfd, F_GETFL) & ~O_NONBLOCK); } } bool IFileDescriptorSource::will_block () { return !(fcntl(file_descriptor(), F_GETFL) & O_NONBLOCK); } // MARK: - // MARK: class FileDescriptorSource FileDescriptorSource::FileDescriptorSource (CallbackT callback, FileDescriptor file_descriptor) : _file_descriptor(file_descriptor), _callback(callback) { } FileDescriptorSource::~FileDescriptorSource () { } void FileDescriptorSource::process_events (Loop * event_loop, Event events) { _callback(event_loop, this, events); } FileDescriptor FileDescriptorSource::file_descriptor () const { return _file_descriptor; } Ref<FileDescriptorSource> FileDescriptorSource::for_standard_in (CallbackT callback) { return new FileDescriptorSource(callback, STDIN_FILENO); } Ref<FileDescriptorSource> FileDescriptorSource::for_standard_out (CallbackT callback) { return new FileDescriptorSource(callback, STDOUT_FILENO); } Ref<FileDescriptorSource> FileDescriptorSource::for_standard_error (CallbackT callback) { return new FileDescriptorSource(callback, STDERR_FILENO); } // MARK: - // MARK: class NotificationPipeSource NotificationPipeSource::NotificationPipeSource () { int result = pipe(_file_descriptors); DREAM_ASSERT(result == 0); } NotificationPipeSource::~NotificationPipeSource () { close(_file_descriptors[0]); close(_file_descriptors[1]); } FileDescriptor NotificationPipeSource::file_descriptor () const { // Read end return _file_descriptors[0]; } void NotificationPipeSource::notify_event_loop () const { // Send a byte down the pipe write(_file_descriptors[1], "\0", 1); } void NotificationPipeSource::process_events (Loop * loop, Event event) { const std::size_t COUNT = 32; char buffer[COUNT]; // Discard all notification bytes: read(_file_descriptors[0], &buffer, COUNT); // Process urgent notifications: loop->process_notifications(); } } }
22.263393
188
0.697814
kurocha
7ec43bb8d48251e102fd7ca0fb5c2e2e4e91bbc4
302
cpp
C++
dojo/first/06_coroutine_ts/main.cpp
adrianimboden/cppusergroup-adynchronous-programming
d6fad3ff980be2e7c13ed9e3e05b62e984c9caa4
[ "MIT" ]
null
null
null
dojo/first/06_coroutine_ts/main.cpp
adrianimboden/cppusergroup-adynchronous-programming
d6fad3ff980be2e7c13ed9e3e05b62e984c9caa4
[ "MIT" ]
null
null
null
dojo/first/06_coroutine_ts/main.cpp
adrianimboden/cppusergroup-adynchronous-programming
d6fad3ff980be2e7c13ed9e3e05b62e984c9caa4
[ "MIT" ]
null
null
null
#include "http_client.h" namespace coroutines_ts { task<std::vector<std::string>> request_uris(HttpClient& http_client, const std::vector<std::string>& uris_to_request) { (void)http_client; (void)uris_to_request; co_return std::vector<std::string>{{"42"}}; } }
23.230769
63
0.652318
adrianimboden
7ec468508f106eac6bf99e10ec8bd756222a6851
1,165
hpp
C++
src/serial/SerialPlayer.hpp
stu-inc/DataCapture
d2bd01cd431867ec8372687542150391344022d6
[ "MIT" ]
null
null
null
src/serial/SerialPlayer.hpp
stu-inc/DataCapture
d2bd01cd431867ec8372687542150391344022d6
[ "MIT" ]
null
null
null
src/serial/SerialPlayer.hpp
stu-inc/DataCapture
d2bd01cd431867ec8372687542150391344022d6
[ "MIT" ]
null
null
null
#pragma once #include <QReadWriteLock> #include <QSharedPointer> #include <QThread> #include <QtSerialPort> class QFile; class QElapsedTimer; class SerialPlayer : public QThread { public: explicit SerialPlayer(QObject *parent = nullptr); virtual ~SerialPlayer() override; void start(); void stop(); void restart(); qint64 getCurrentTime() const; void setPortName(const QString &portName); void setFileName(const QString &fileName); void setBaundRate(QSerialPort::BaudRate baudRate); void setDataBits(QSerialPort::DataBits dataBits); void setParity(QSerialPort::Parity parity); void setStopBits(QSerialPort::StopBits stopBits); void setByteOrder(QSysInfo::Endian byteOrder); protected: virtual void run() override; private: mutable QReadWriteLock mLock; QSharedPointer<QSerialPort> mSerialPort; QSharedPointer<QFile> mFile; QSharedPointer<QDataStream> mDataStream; QSharedPointer<QElapsedTimer> mTimer; QString mPortName; QString mFileName; QSerialPort::BaudRate mBaundRate; QSerialPort::DataBits mDataBits; QSerialPort::Parity mParity; QSerialPort::StopBits mStopBits; QSysInfo::Endian mByteOrder; };
22.843137
52
0.771674
stu-inc
7ec85697288a121d2e81564097e612303ade086f
1,049
cpp
C++
Ejercicio4Tema11/Ejercicio4Tema11/Rio.cpp
gejors55/Algorithm
107d6cf4eb8fc7f4d0cebfe9b4e7b2811ac10533
[ "MIT" ]
null
null
null
Ejercicio4Tema11/Ejercicio4Tema11/Rio.cpp
gejors55/Algorithm
107d6cf4eb8fc7f4d0cebfe9b4e7b2811ac10533
[ "MIT" ]
null
null
null
Ejercicio4Tema11/Ejercicio4Tema11/Rio.cpp
gejors55/Algorithm
107d6cf4eb8fc7f4d0cebfe9b4e7b2811ac10533
[ "MIT" ]
null
null
null
#include "Rio.h" Rio::Rio() {} float Rio::embalsado_pantano(const string& pantano) const { return buscar_pantano(pantano).vol(); } float Rio::embalsado_total() const { DiccionarioHash<string, Pantano>::ConstIterator ipantano = _pantanos.cbegin(); DiccionarioHash<string, Pantano>::ConstIterator ifin = _pantanos.cend(); int suma =0; while (ipantano != ifin){ suma += ipantano.valor().vol(); ipantano.next(); } return suma; } const Pantano& Rio::buscar_pantano(const string& pantano) const { DiccionarioHash<string, Pantano>::ConstIterator ipantano = _pantanos.cbusca(pantano); DiccionarioHash<string, Pantano>::ConstIterator ifin = _pantanos.cend(); if (ipantano == ifin) throw EPantanoNoExiste(); return ipantano.valor(); } Pantano Rio::busca( string pantano) { DiccionarioHash<string, Pantano>::Iterator ipantano = _pantanos.busca(pantano); DiccionarioHash<string, Pantano>::Iterator ifin = _pantanos.end(); if (ipantano == ifin) throw EPantanoNoExiste(); return ipantano.valor(); }
29.971429
87
0.711153
gejors55
7ece0d313e1768940414c5fe1f211ce55e1716ec
18,342
cpp
C++
ccct.cpp
Taromati2/yaya-shiori
c49e3d4d03f167a8833f2e68810fb46dc33bac90
[ "BSD-3-Clause" ]
null
null
null
ccct.cpp
Taromati2/yaya-shiori
c49e3d4d03f167a8833f2e68810fb46dc33bac90
[ "BSD-3-Clause" ]
2
2022-01-12T03:25:46.000Z
2022-01-12T07:15:38.000Z
ccct.cpp
Taromati2/yaya-shiori
c49e3d4d03f167a8833f2e68810fb46dc33bac90
[ "BSD-3-Clause" ]
null
null
null
// // AYA version 5 // // 文字コード変換クラス Ccct // // 変換部分のコードは以下のサイトで公開されているものを利用しております。 // class CUnicodeF // kamoland // http://kamoland.com/comp/unicode.html // #if defined(WIN32) || defined(_WIN32_WCE) # include "stdafx.h" #endif #include <string.h> #include <clocale> #include <string> #include "ccct.h" #include "manifest.h" #include "globaldef.h" //#include "babel/babel.h" #ifdef POSIX # include <ctype.h> #endif /* #define PRIMARYLANGID(lgid) ((WORD)(lgid) & 0x3ff) */ //////////DEBUG///////////////////////// #ifdef _WINDOWS #ifdef _DEBUG #include <crtdbg.h> #define new new( _NORMAL_BLOCK, __FILE__, __LINE__) #endif #endif //////////////////////////////////////// #ifdef POSIX namespace { int wcsicmp(const wchar_t* a, const wchar_t* b) { size_t lenA = wcslen(a); size_t lenB = wcslen(b); if (lenA != lenB) { return lenA - lenB; } else { for (size_t i = 0; i < lenA; i++) { wchar_t A = tolower(a[i]); wchar_t B = tolower(b[i]); if (A != B) { return A - B; } } return 0; } } int stricmp(const char* a, const char* b) { size_t lenA = strlen(a); size_t lenB = strlen(b); if (lenA != lenB) { return lenA - lenB; } else { for (size_t i = 0; i < lenA; i++) { wchar_t A = tolower(a[i]); wchar_t B = tolower(b[i]); if (A != B) { return A - B; } } return 0; } } } #endif /* ----------------------------------------------------------------------- * 関数名 : Ccct::CheckCharset * 機能概要: Charset IDのチェック * ----------------------------------------------------------------------- */ bool Ccct::CheckInvalidCharset(int charset) { if (charset != CHARSET_SJIS && charset != CHARSET_UTF8 && charset != CHARSET_EUCJP && charset != CHARSET_BIG5 && charset != CHARSET_GB2312 && charset != CHARSET_EUCKR && charset != CHARSET_JIS && charset != CHARSET_BINARY && charset != CHARSET_DEFAULT) { return true; } return false; } /* ----------------------------------------------------------------------- * 関数名 : Ccct::CharsetTextToID * 機能概要: Charset 文字列->Charset ID * ----------------------------------------------------------------------- */ int Ccct::CharsetTextToID(const wchar_t *ctxt) { if (!wcsicmp(L"UTF-8",ctxt) || !wcsicmp(L"UTF8",ctxt)) return CHARSET_UTF8; else if (!wcsicmp(L"default",ctxt) || !wcsicmp(L"OSNative",ctxt)) return CHARSET_DEFAULT; else if (!wcsicmp(L"Shift_JIS",ctxt) || !wcsicmp(L"ShiftJIS",ctxt) || !wcsicmp(L"SJIS",ctxt)) return CHARSET_SJIS; else if (!wcsicmp(L"EUC_JP",ctxt) || !wcsicmp(L"EUC-JP",ctxt) || !wcsicmp(L"EUCJP",ctxt)) return CHARSET_EUCJP; else if (!wcsicmp(L"ISO-2022-JP",ctxt) || !wcsicmp(L"JIS",ctxt)) return CHARSET_JIS; else if (!wcsicmp(L"BIG5",ctxt) || !wcsicmp(L"BIG-5",ctxt)) return CHARSET_BIG5; else if (!wcsicmp(L"GB2312",ctxt) || !wcsicmp(L"GB-2312",ctxt)) return CHARSET_GB2312; else if (!wcsicmp(L"EUC_KR",ctxt) || !wcsicmp(L"EUC-KR",ctxt) || !wcsicmp(L"EUCKR",ctxt)) return CHARSET_EUCKR; else if (!wcsicmp(L"binary",ctxt)) return CHARSET_BINARY; return CHARSET_DEFAULT; } int Ccct::CharsetTextToID(const char *ctxt) { if (!stricmp("UTF-8",ctxt) || !stricmp("UTF8",ctxt)) return CHARSET_UTF8; else if (!stricmp("default",ctxt) || !stricmp("OSNative",ctxt)) return CHARSET_DEFAULT; else if (!stricmp("Shift_JIS",ctxt) || !stricmp("ShiftJIS",ctxt) || !stricmp("SJIS",ctxt)) return CHARSET_SJIS; else if (!stricmp("EUC_JP",ctxt) || !stricmp("EUC-JP",ctxt) || !stricmp("EUCJP",ctxt)) return CHARSET_EUCJP; else if (!stricmp("ISO-2022-JP",ctxt) || !stricmp("JIS",ctxt)) return CHARSET_JIS; else if (!stricmp("BIG5",ctxt) || !stricmp("BIG-5",ctxt)) return CHARSET_BIG5; else if (!stricmp("GB2312",ctxt) || !stricmp("GB-2312",ctxt)) return CHARSET_GB2312; else if (!stricmp("EUC_KR",ctxt) || !stricmp("EUC-KR",ctxt) || !stricmp("EUCKR",ctxt)) return CHARSET_EUCKR; else if (!stricmp("binary",ctxt)) return CHARSET_BINARY; return CHARSET_DEFAULT; } /* ----------------------------------------------------------------------- * 関数名 : Ccct::CharsetIDToText(A/W) * 機能概要: Charset 文字列->Charset ID * ----------------------------------------------------------------------- */ const wchar_t *Ccct::CharsetIDToTextW(const int charset) { if ( charset == CHARSET_UTF8 ) { return L"UTF-8"; } if ( charset == CHARSET_SJIS ) { return L"Shift_JIS"; } if ( charset == CHARSET_EUCJP ) { return L"EUC_JP"; } if ( charset == CHARSET_JIS ) { return L"ISO-2022-JP"; } if ( charset == CHARSET_BIG5 ) { return L"BIG5"; } if ( charset == CHARSET_GB2312 ) { return L"GB2312"; } if ( charset == CHARSET_EUCKR ) { return L"EUC_KR"; } if ( charset == CHARSET_BINARY ) { return L"binary"; } return L"default"; } const char *Ccct::CharsetIDToTextA(const int charset) { if ( charset == CHARSET_UTF8 ) { return "UTF-8"; } if ( charset == CHARSET_SJIS ) { return "Shift_JIS"; } if ( charset == CHARSET_EUCJP ) { return "EUC_JP"; } if ( charset == CHARSET_JIS ) { return "ISO-2022-JP"; } if ( charset == CHARSET_BIG5 ) { return "BIG5"; } if ( charset == CHARSET_GB2312 ) { return "GB2312"; } if ( charset == CHARSET_EUCKR ) { return "EUC_KR"; } if ( charset == CHARSET_BINARY ) { return "binary"; } return "default"; } /* ----------------------------------------------------------------------- * UTF-8変換用先行宣言 * ----------------------------------------------------------------------- */ size_t Ccct_ConvUTF8ToUnicode(aya::string_t &buf,const char* pStrIn); size_t Ccct_ConvUnicodeToUTF8(std::string &buf,const aya::char_t *pStrw); /* ----------------------------------------------------------------------- * 関数名 : Ccct::Ucs2ToMbcs * 機能概要: UTF-16BE -> MBCS へ文字列のコード変換 * ----------------------------------------------------------------------- */ static char* string_to_malloc(const std::string &str) { char* pch = (char*)malloc(str.length()+1); memcpy(pch,str.c_str(),str.length()+1); return pch; } char *Ccct::Ucs2ToMbcs(const aya::char_t *wstr, int charset) { return Ucs2ToMbcs(aya::string_t(wstr), charset); } //---- char *Ccct::Ucs2ToMbcs(const aya::string_t &wstr, int charset) { /*if ( charset == CHARSET_UTF8 ) { return string_to_malloc(babel::unicode_to_utf8(wstr)); } else if ( charset == CHARSET_SJIS ) { return string_to_malloc(babel::unicode_to_sjis(wstr)); } else if ( charset == CHARSET_EUCJP ) { return string_to_malloc(babel::unicode_to_euc(wstr)); } else if ( charset == CHARSET_JIS ) { return string_to_malloc(babel::unicode_to_jis(wstr)); }*/ if ( charset == CHARSET_UTF8 ) { std::string buf; Ccct_ConvUnicodeToUTF8(buf,wstr.c_str()); return string_to_malloc(buf); } else { return utf16be_to_mbcs(wstr.c_str(),charset); } } /* ----------------------------------------------------------------------- * 関数名 : Ccct::MbcsToUcs2 * 機能概要: MBCS -> UTF-16BE へ文字列のコード変換 * ----------------------------------------------------------------------- */ static aya::char_t* wstring_to_malloc(const aya::string_t &str) { size_t sz = (str.length()+1) * sizeof(aya::char_t); aya::char_t* pch = (aya::char_t*)malloc(sz); memcpy(pch,str.c_str(),sz); return pch; } aya::char_t *Ccct::MbcsToUcs2(const char *mstr, int charset) { return MbcsToUcs2(std::string(mstr), charset); } //---- aya::char_t *Ccct::MbcsToUcs2(const std::string &mstr, int charset) { /*if ( charset == CHARSET_UTF8 ) { return wstring_to_malloc(babel::utf8_to_unicode(mstr)); } else if ( charset == CHARSET_SJIS ) { return wstring_to_malloc(babel::sjis_to_unicode(mstr)); } else if ( charset == CHARSET_EUCJP ) { return wstring_to_malloc(babel::euc_to_unicode(mstr)); } else if ( charset == CHARSET_JIS ) { return wstring_to_malloc(babel::jis_to_unicode(mstr)); }*/ if ( charset == CHARSET_UTF8 ) { aya::string_t buf; Ccct_ConvUTF8ToUnicode(buf,mstr.c_str()); return wstring_to_malloc(buf); } else { return mbcs_to_utf16be(mstr.c_str(),charset); } } /* ----------------------------------------------------------------------- * 関数名 : Ccct::sys_setlocale * 機能概要: OSデフォルトの言語IDでロケール設定する * ----------------------------------------------------------------------- */ char *Ccct::sys_setlocale(int category) { return setlocale(category,""); } /* ----------------------------------------------------------------------- * 関数名 : Ccct::ccct_getcodepage * 機能概要: 言語ID->Windows CP * ----------------------------------------------------------------------- */ unsigned int Ccct::ccct_getcodepage(int charset) { if (charset == CHARSET_SJIS) { return 932; } else if (charset == CHARSET_EUCJP) { return 20932; } else if (charset == CHARSET_BIG5) { return 950; } else if (charset == CHARSET_GB2312) { return 936; } else if (charset == CHARSET_EUCKR) { return 949; } else if (charset == CHARSET_JIS) { return 50222; } else { #if defined(WIN32) || defined(_WIN32_WCE) return ::AreFileApisANSI() ? ::GetACP() : ::GetOEMCP(); #else return 0; #endif } } /* ----------------------------------------------------------------------- * 関数名 : Ccct::ccct_setlocale * 機能概要: 言語IDでロケール設定する * ----------------------------------------------------------------------- */ char *Ccct::ccct_setlocale(int category, int charset) { #ifdef POSIX if (charset == CHARSET_SJIS) { return setlocale(category, "ja_JP.SJIS"); } else if (charset == CHARSET_EUCJP) { return setlocale(category, "ja_JP.eucJP"); } else if (charset == CHARSET_BIG5) { return setlocale(category, "zh_TW.Big5"); } else if (charset == CHARSET_GB2312) { return setlocale(category, "zh_CN.GB2312"); } else if (charset == CHARSET_EUCKR) { return setlocale(category, "ko_KR.eucKR"); } else if (charset == CHARSET_JIS) { return setlocale(category, "ja_JP.SJIS"); } #else if (charset == CHARSET_SJIS) { return setlocale(category, ".932"); } else if (charset == CHARSET_EUCJP) { return setlocale(category, ".20932"); } else if (charset == CHARSET_BIG5) { return setlocale(category, ".950"); } else if (charset == CHARSET_GB2312) { return setlocale(category, ".936"); } else if (charset == CHARSET_EUCKR) { return setlocale(category, ".949"); } else if (charset == CHARSET_JIS) { return setlocale(category, ".50222"); } #endif else { return sys_setlocale(category); } } /* ----------------------------------------------------------------------- * setlocaleバリア * ----------------------------------------------------------------------- */ class CcctSetLocaleSwitcher { private: const char *m_oldLocale; int m_category; public: CcctSetLocaleSwitcher(int category,int charset) { m_category = category; m_oldLocale = setlocale(category,NULL); Ccct::ccct_setlocale(category,charset); } ~CcctSetLocaleSwitcher() { if ( m_oldLocale ) { setlocale(m_category,m_oldLocale); } } }; /* ----------------------------------------------------------------------- * 関数名 : Ccct::utf16be_to_mbcs * 機能概要: UTF-16BE -> MBCS へ文字列のコード変換 * ----------------------------------------------------------------------- */ char *Ccct::utf16be_to_mbcs(const aya::char_t *pUcsStr, int charset) { char *pAnsiStr = NULL; if (!pUcsStr) { return NULL; } if (!*pUcsStr) { char *p = (char*)malloc(1); p[0] = 0; return p; } #if defined(WIN32) || defined(_WIN32_WCE) int cp = ccct_getcodepage(charset); int alen = ::WideCharToMultiByte(cp,0,pUcsStr,-1,NULL,0,NULL,NULL); if ( alen <= 0 ) { return NULL; } pAnsiStr = (char*)malloc(alen+1+5); //add +5 for safety alen = ::WideCharToMultiByte(cp,0,pUcsStr,-1,pAnsiStr,alen+1,NULL,NULL); if ( alen <= 0 ) { return NULL; } pAnsiStr[alen] = 0; #else CcctSetLocaleSwitcher loc(LC_CTYPE, charset); size_t nLen = wcslen( pUcsStr); if (charset != CHARSET_BINARY) { if (pUcsStr[0] == static_cast<aya::char_t>(0xfeff) || pUcsStr[0] == static_cast<aya::char_t>(0xfffe)) { pUcsStr++; // 先頭にBOM(byte Order Mark)があれば,スキップする nLen--; } } //文字長×マルチバイト最大長+ゼロ終端 pAnsiStr = (char *)malloc((nLen*MB_CUR_MAX)+1); if (!pAnsiStr) { return NULL; } // 1文字ずつ変換する。 // まとめて変換すると、変換不能文字への対応が困難なので size_t i, nMbpos = 0; int nRet; for (i = 0; i < nLen; i++) { if (charset != CHARSET_BINARY) { nRet = wctomb(pAnsiStr+nMbpos, pUcsStr[i]); } else { pAnsiStr[nMbpos] = (char)(0x00ff & pUcsStr[i]); nRet = 1; } if ( nRet <= 0 ) { // can not conversion pAnsiStr[nMbpos++] = ' '; } else { nMbpos += nRet; } } pAnsiStr[nMbpos] = 0; #endif return pAnsiStr; } /* ----------------------------------------------------------------------- * 関数名 : Ccct::mbcs_to_utf16be * 機能概要: MBCS -> UTF-16 へ文字列のコード変換 * ----------------------------------------------------------------------- */ aya::char_t *Ccct::mbcs_to_utf16be(const char *pAnsiStr, int charset) { if (!pAnsiStr) { return NULL; } if (!*pAnsiStr) { aya::char_t* p = (aya::char_t*)malloc(2); p[0] = 0; return p; } #if defined(WIN32) || defined(_WIN32_WCE) size_t nLen = strlen(pAnsiStr); int cp = ccct_getcodepage(charset); int wlen = ::MultiByteToWideChar(cp,0,pAnsiStr,nLen,NULL,0); if ( wlen <= 0 ) { return NULL; } aya::char_t* pUcsStr = (aya::char_t*)malloc((wlen + 1 + 5) * sizeof(aya::char_t)); //add +5 for safety wlen = ::MultiByteToWideChar(cp,0,pAnsiStr,nLen,pUcsStr,wlen+1); if ( wlen <= 0 ) { return NULL; } pUcsStr[wlen] = 0; #else CcctSetLocaleSwitcher loc(LC_CTYPE, charset); size_t nLen = strlen(pAnsiStr); aya::char_t *pUcsStr = (aya::char_t *)malloc(sizeof(aya::char_t)*(nLen+7)); if (!pUcsStr) { return NULL; } // 1文字ずつ変換する。 // まとめて変換すると、変換不能文字への対応が困難なので size_t i, nMbpos = 0; int nRet; for (i = 0; i < nLen; ) { if (charset != CHARSET_BINARY) { nRet = mbtowc(pUcsStr+nMbpos, pAnsiStr+i, nLen-i); } else { pUcsStr[i]=static_cast<aya::char_t>(pAnsiStr[i]); nRet = 1; } if ( nRet <= 0 ) { // can not conversion pUcsStr[nMbpos++] = L' '; i += 1; } else { ++nMbpos; i += nRet; } } pUcsStr[nMbpos] = 0; #endif return pUcsStr; } /*-------------------------------------------- UTF-9をUTF-16に --------------------------------------------*/ size_t Ccct_ConvUTF8ToUnicode(aya::string_t &buf,const char* pStrIn) { unsigned char *pStr = (unsigned char*)pStrIn; unsigned char *pStrLast = pStr + strlen(pStrIn); unsigned char c; unsigned long tmp; while( pStr < pStrLast ){ c = *(pStr++); if( (c & 0x80) == 0 ){ //1Byte - 0??????? buf.append(1,(WORD)c); } /*else if( (c & 0xc0) == 0x80 ){ //1Byte - 10?????? -> 必ず2バイト目以降のため、単体で出たら不正 m_Str.Add() = (WORD)c; }*/ else if( (c & 0xe0) == 0xc0 ){ //2Byte - 110????? tmp = static_cast<DWORD>(c & 0x1f) << 6; //下5bit - 10-6 tmp |= static_cast<DWORD>(*(pStr++) & 0x3f); //下6bit - 5-0 buf.append(1,static_cast<WORD>(tmp)); } else if( (c & 0xf0) == 0xe0 ){ //3Byte - 1110???? tmp = static_cast<DWORD>(c & 0x0f) << 12; //下4bit - 15-12 tmp |= static_cast<DWORD>(*(pStr++) & 0x3f) << 6; //下6bit - 11-6 tmp |= static_cast<DWORD>(*(pStr++) & 0x3f); //下6bit - 5-0 if ( tmp != 0xfeff && tmp != 0xfffe ) { //BOMでない buf.append(1,static_cast<WORD>(tmp)); } } else if( (c & 0xf8) == 0xf0 ){ //4Byte - 11110??? UTF-16 Surrogate tmp = static_cast<DWORD>(c & 0x07) << 18; //下3bit -> 20-18 tmp |= static_cast<DWORD>(*(pStr++) & 0x3f) << 12; //下6bit - 17-12 tmp |= static_cast<DWORD>(*(pStr++) & 0x3f) << 6; //下6bit - 11-6 tmp |= static_cast<DWORD>(*(pStr++) & 0x3f); //下6bit - 5-0 tmp -= 0x10000; buf.append(1,(WORD)(0xD800U | ((tmp >> 10) & 0x3FF))); //上位サロゲート buf.append(1,(WORD)(0xDC00U | (tmp & 0x3FF))); //下位サロゲート } else if( (c & 0xfc) == 0xf8 ){ //5Byte - 111110?? -- UCS-4 pStr += 4; //無視 } else if( (c & 0xfe) == 0xfc ){ //6Byte - 1111110? -- UCS-4 pStr += 5; //無視 } /*else { // - 11111110 , 11111111 (0xfe,0xff) - そんな文字あるかい! m_Str.Add() = (WORD)c; }*/ } return buf.length(); } /*-------------------------------------------- UTF-16をUTF-8に --------------------------------------------*/ size_t Ccct_ConvUnicodeToUTF8(std::string &buf,const aya::char_t *pStrw) { aya::char_t w; unsigned long surrogateTemp; size_t length = wcslen(pStrw); size_t i = 0; buf.reserve(length*4+1); //4倍まで (UTF-8 5-6byte領域はUCS-2からの変換では存在しない) while(i < length){ w = pStrw[i++]; if (w < 0x80) { //1byte buf.append(1,(char)(BYTE)w); //5-0 } else if ( w < 0x0800 ) { //2byte buf.append(1,(char)(BYTE)((w >> 6) & 0x001f) | 0xc0); //10-6 buf.append(1,(char)(BYTE)(w & 0x3f) | 0x80); //5-0 } else { if ( (w & 0xF800) == 0xD800 ) { //4byte サロゲートページ D800->DFFF surrogateTemp = ( ( (w & 0x3FF) << 10 ) | (pStrw[i++] & 0x3FF) ) + 0x10000; buf.append(1,(char)(BYTE)((surrogateTemp >> 18) & 0x07) | 0xf0); //20-18 buf.append(1,(char)(BYTE)((surrogateTemp >> 12) & 0x3f) | 0x80); //17-12 buf.append(1,(char)(BYTE)((surrogateTemp >> 6 ) & 0x3f) | 0x80); //11-6 buf.append(1,(char)(BYTE)(surrogateTemp & 0x3f) | 0x80); //5-0 } else { //3byte buf.append(1,(char)(BYTE)((w >> 12) & 0x0f) | 0xe0); //15-12 buf.append(1,(char)(BYTE)((w >> 6) & 0x3f) | 0x80); //11-6 buf.append(1,(char)(BYTE)(w & 0x3f) | 0x80); //5-0 } } } return buf.length(); }
26.737609
104
0.522953
Taromati2