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
c4c2b2870bd19b8d68185006073038d950283086
1,504
cpp
C++
Uva-10948 - The primary problem.cpp
Samim-Arefin/UVa-Problem-Solution
8556639b9e718299f4a52920034dfa0264e06f8e
[ "MIT" ]
1
2020-11-02T22:18:22.000Z
2020-11-02T22:18:22.000Z
Uva-10948 - The primary problem.cpp
Samim-Arefin/UVa-Problem-Solution
8556639b9e718299f4a52920034dfa0264e06f8e
[ "MIT" ]
null
null
null
Uva-10948 - The primary problem.cpp
Samim-Arefin/UVa-Problem-Solution
8556639b9e718299f4a52920034dfa0264e06f8e
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define Max 1000001 std::bitset<Max> arr; std::vector<int> prime; void sieve() { arr[0]=true; arr[1]=true; for(int i=4;i<=Max;i+=2) { arr[i]=true; } for(int i=3;i*i<=Max;i++) { if(arr[i]==false) { for(int j=i*i;j<=Max;j+=i+i) { arr[j]=true; } } } prime.push_back(2); for(int i=3;i<=Max;i+=2) { if(arr[i]==false) { prime.push_back(i); } } } int main() { sieve(); freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); int num; while(std::cin>>num,num>0) { int beg=0,end=prime.size()-1,maximum=INT_MIN,a,b; bool check=false; while(beg<=end) { if((prime[beg]+prime[end])==num) { if((prime[end]-prime[beg])>maximum) { a=prime[beg]; b=prime[end]; maximum=(prime[end]-prime[beg]); check=true; break; } } else if((prime[beg]+prime[end])<num) { beg++; } else { end--; } } if(check==true) { std::cout<<num<<":\n"<<a<<"+"<<b<<'\n'; } else { std::cout<<num<<":\nNO WAY!\n"; } } }
19.282051
57
0.357713
Samim-Arefin
c4c3d286892a809e310541e6850a867b3a052036
7,599
hpp
C++
skynet/core/neighbor.hpp
zhangzhimin/skynet
a311b86433821a071002dd279d57333baba1f973
[ "MIT" ]
5
2015-08-02T03:10:26.000Z
2018-01-16T01:07:55.000Z
skynet/core/neighbor.hpp
zhangzhimin/skynet
a311b86433821a071002dd279d57333baba1f973
[ "MIT" ]
null
null
null
skynet/core/neighbor.hpp
zhangzhimin/skynet
a311b86433821a071002dd279d57333baba1f973
[ "MIT" ]
null
null
null
#pragma once #include <stdexcept> #include <array> #include <skynet/core/adaptor_types.hpp> namespace skynet{ template <typename B, typename size_t dim> class neighbor_adaptor : public iterator_adaptor<B> { public: typedef B neighbor_type; typedef point<size_t, dim> extent_type; typedef ptrdiff_t value_type; typedef const value_type & reference; typedef const value_type & const_reference; ptrdiff_t max_offset() const { return *std::max_element(begin(), end()); } ptrdiff_t min_offset() const { return *std::min_element(begin(), end()); } }; // * // * o * // * //It's the diamand_neighbors, star is neighbor, o is origin. template <typename size_t dim> class diamand_neighbor: public neighbor_adaptor<diamand_neighbor<dim>, dim>{ public: static const size_t neighbor_num = dim * 2; diamand_neighbor(){} diamand_neighbor &operator=(const diamand_neighbor &rhs){ _extent = rhs._extent; _offsets = rhs._offsets; return *this; } void attach(const extent_type &size){ _extent = size; _offsets[0] = 1; _offsets[0+dim] = -1; for (int i = 1; i < dim; ++i){ _offsets[i] = _offsets[i-1] * _extent[i-1]; _offsets[i + dim] = -_offsets[i]; } } const int &operator[](const size_t &index) const{ return _offsets[index]; } size_t size()const { return neighbor_num; } private: extent_type _extent; std::array<ptrdiff_t, neighbor_num> _offsets; }; /* * * * * * It's the vertex_neighbors */ template <typename size_t dim> class vertex_neighbor: public neighbor_adaptor<vertex_neighbor<dim>,dim>{ public: static const size_t neighbor_num = extent_type::dim * 2 + 1; vertex_neighbor() {} vertex_neighbor(const int &r) : _radius(r){} vertex_neighbor &operator=(const vertex_neighbor &rhs){ this->rhs._radius; this->_extent = rhs._extent; this->_offsets = rhs._offsets; return *this; } const int &operator [](const size_t &index) const{ return _offsets[index]; } void attach(const extent_type &size) { _extent = size; _offsets[0] = _radius; _offsets[0+dim] = -_radius; _offsets[neighbor_num - 1] = 0; for (int i = 1; i < dim; ++i){ _offsets[i] = _offsets[i-1] * _extent[i-1]; _offsets[i + dim] = -_offsets[i]; } }; int get_radius(){ return _radius; } size_t size() const { return neighbor_num; } private: int _radius; extent_type _extent; std::array<int, neighbor_num> _offsets; }; template <typename size_t dim_> class square_neighbor; template <> class square_neighbor<3>: public neighbor_adaptor<square_neighbor<3>, 3>{ public: static const size_t neighbor_num = 26; square_neighbor(){} square_neighbor &operator=(const square_neighbor &rhs){ _extent = rhs._extent; _offsets = rhs._offsets; return *this; } void attach(const extent_type &extent){ _extent = extent; int shift_0 = 1; int shift_1 = _extent[0]; int shift_2 = get_slice_size(_extent); int pos = 0; for (int page = -1; page <= 1; ++page){ for (int row = -1; row <= 1; ++row){ for (int col = -1; col <= 1; ++col){ if (page == 0 && row == 0 && col == 0) continue; _offsets[pos] = col * shift_0 + row * shift_1 + page * shift_2; ++pos; } } } } const int &operator[](const size_t &index) const{ return _offsets[index]; } size_t size()const { return neighbor_num; } private: extent_type _extent; std::array<int, neighbor_num> _offsets; }; template <> class square_neighbor<2> : public neighbor_adaptor<square_neighbor<2>,2> { public: static const size_t neighbor_num = 8; square_neighbor(){} square_neighbor &operator=(const square_neighbor &rhs){ _extent = rhs._extent; _offsets = rhs._offsets; return *this; } void attach(const extent_type &extent){ _extent = extent; int shift_0 = 1; int shift_1 = _extent[0]; int pos = 0; for (int row = -1; row <= 1; ++row){ for (int col = -1; col <= 1; ++col){ if (row == 0 && col == 0) continue; _offsets[pos] = col * shift_0 + row * shift_1; ++pos; } } } const int &operator[](const size_t &index) const{ return _offsets[index]; } size_t size()const { return neighbor_num; } private: extent_type _extent; std::array<int, neighbor_num> _offsets; }; template <typename size_t dim_> class cube_neighbor; template <> class cube_neighbor<3>: public neighbor_adaptor<cube_neighbor<3>,3>{ public: cube_neighbor &operator=(const cube_neighbor &rhs){ _extent = rhs._extent; _offsets = rhs._offsets; return *this; } cube_neighbor(const int radius = 1): _radius(radius){} void attach(const extent_type &extent){ _extent = extent; int shift_0 = 1; int shift_1 = _extent[0]; int shift_2 = get_slice_size(_extent); for (int page = -_radius; page <= _radius; ++page){ for (int row = -_radius; row <= _radius; ++row){ for (int col = -_radius; col <= _radius; ++col){ _offsets.push_back(col * shift_0 + row * shift_1 + page * shift_2); } } } } const int operator[](const size_t &index) const{ return _offsets[index]; } size_t size()const { return _offsets.size(); } private: extent_type _extent; std::vector<size_t> _offsets; int _radius; }; template <> class cube_neighbor<2>: public neighbor_adaptor<cube_neighbor<2>, 2>{ public: cube_neighbor &operator=(const cube_neighbor &rhs){ _extent = rhs._extent; _offsets = rhs._offsets; return *this; } cube_neighbor(const int radius = 1): _radius(radius){ // attach(extent); } void attach(const extent_type &extent){ _extent = extent; int shift_0 = 1; int shift_1 = _extent[0]; for (int row = -_radius; row <= _radius; ++row){ for (int col = -_radius; col <= _radius; ++col){ _offsets.push_back(col * shift_0 + row * shift_1); } } } const_reference operator[](const size_t &index) const{ return _offsets[index]; } size_t size() const { return _offsets.size(); } private: extent_type _extent; std::vector<size_t> _offsets; int _radius; }; template <size_t dim, typename Func> class custom_neighbor: public neighbor_adaptor<custom_neighbor<dim, Func>, dim>{ public: custom_neighbor(Func fun): _fun(fun) {} void attach(extent_type extent) { _fun(extent, std::ref(_offsets)); } const_reference operator[](size_t i) const { return _offsets[i]; } size_t size() const { return _offsets.size(); } public: extent_type _extent; std::vector<value_type> _offsets; Func _fun; }; template <size_t dim, typename Func> auto customize_neighbor(Func fun) { return custom_neighbor<dim, Func>(fun); } template <typename N, typename Func> void traverse_neighbors(const size_t &base, const N &neighbors, Func fun){ for (auto it = neighbors.begin(); it != neighbors.end(); ++it){ fun(base+(*it)); } } // }
24.12381
86
0.59521
zhangzhimin
c4c44ddee8bb17913f409a00a1b803ee5e5179a0
5,024
hh
C++
source/PPUtils/uniformobjectpool.hh
PerttuP/PPUtils
97971d6e2b662bab9a4966b4c39ac59509c01359
[ "MIT" ]
null
null
null
source/PPUtils/uniformobjectpool.hh
PerttuP/PPUtils
97971d6e2b662bab9a4966b4c39ac59509c01359
[ "MIT" ]
null
null
null
source/PPUtils/uniformobjectpool.hh
PerttuP/PPUtils
97971d6e2b662bab9a4966b4c39ac59509c01359
[ "MIT" ]
null
null
null
/* uniformobjectpool.hh * This header file defines the PPUtils::UniformObjectPool class template. This * class template can be used as a storage for complex objects or as a builder * class. * * Author: Perttu Paarlahti perttu.paarlahti@gmail.com * Created: 29-June-2015 */ #ifndef UNIFORMOBJECTPOOL_HH #define UNIFORMOBJECTPOOL_HH #include <vector> #include <memory> #include <functional> namespace PPUtils { /*! * \brief The UniformObjectPool class * This is a generic object pool. It may be used for storing complex objects * when repeatly constructing them would be too expensive. It may also used as * a builder/factory class. * * Note that there is no segmentation among stored objects i.e. all stored * objects are concerned equal and user cannot choose which kind of object he * is going to get next. If this kind of functionality is desired, use * ObjectPool instead. Objects are stored in their current state, so make sure * that stored objects are in a re-usable state when released to the pool * (or alternatively re-initialize all objects after reserveing them). * * This version of object pool is not thread safe. Use this version only from * one thread. If you need to access object pool from multiple threads, use * ConcurrentUniformObjectPool instead. * * Type arguments: * \p T: Type of stored objects. * * \p Builder: A functor class that is used to construct new objects when * needed. Builder must provide a function operator taking no arguments and * returning a dynamically allocated T-object. */ template <class T, class Builder = typename std::function<T*()> > class UniformObjectPool { public: /*! * \brief Constructor * \param builder Builder object that will be used to construct new objects. * Ownership of builder is passed to this object. * \pre builder != nullptr. */ explicit UniformObjectPool(Builder* builder); /*! * \brief Constructor * \param builder Builder object that will be used to construct new objects. * This object uses a copy of builder to do so (Builder must be * copy-constructible). */ explicit UniformObjectPool(const Builder& builder = DEFAULT_BUILDER); /*! * \brief Destructor destroys the pool and all its currently stored objects. */ virtual ~UniformObjectPool(); /*! * \brief Copy-constructor is forbidden. */ UniformObjectPool(const UniformObjectPool&) = delete; /*! * \brief Move-constructor. * \param other Moved object. * \pre None. * \post This object has the state that \p other used to have. \p other * is left into an unspecified. */ UniformObjectPool(UniformObjectPool&& other) noexcept; /*! * \brief Assignment operator is forbidden. */ UniformObjectPool& operator = (const UniformObjectPool&) = delete; /*! * \brief Move-assignment operator. * \param other Moved object. * \return Reference to this object. * \pre None. * \post This object has the state that \p other used to have. \p other * is left into a unspecified but valid state. */ UniformObjectPool& operator = (UniformObjectPool&& other) noexcept; /*! * \brief Reserve next object from pool. * \return Unique pointer to reserved object. Returned object may be re-used * or constructed using Builder. * \pre None. */ virtual typename std::unique_ptr<T> reserve(); /*! * \brief Return object (back) to the pool. * \param object Object returned to the pool. Object may be reserved from * the pool earlier or constructed other way. * \pre object != nullptr. * \post Object is stored in the pool and may be re-used calling the reserve * method. Object is stored in its current state. */ virtual void release(typename std::unique_ptr<T>&& object); /*! * \brief Return number of objects currently stored in the pool. * \pre None. */ virtual unsigned size() const final; /*! * \brief Destroy all objects currently stored in the pool. * \pre None. * \post All currently stored objects are destoyed and pool contains no * re-usable objects. */ virtual void clear(); protected: /*! * \brief DEFAULT_BUILDER * This functor constructs stored objects using their default constructor. * Instantiating this functor requires \p T to be default constructible. */ static const typename std::function<T*()> DEFAULT_BUILDER; /*! * \brief Returns pointer to the Builder object. * \pre None. */ Builder* getBuilder() const; private: typename std::vector<std::unique_ptr<T> > objects_; std::unique_ptr<Builder> builder_; }; } // Namespace PPUtils // Include template implementations. #include "uniformobjectpool_impl.hh" #endif // UNIFORMOBJECTPOOL_HH
31.204969
80
0.669785
PerttuP
c4cc576690912172f7e671be0ecf0af39a955e34
3,926
cpp
C++
src_smartcontract_db/scan_select/scan_planner/scanner/join/JoinOrCandidate.cpp
alinous-core/codablecash
04ca04c9bc179aa81d4277ed34320b4340628bd1
[ "MIT" ]
6
2019-01-06T05:02:39.000Z
2020-10-01T11:45:32.000Z
src_smartcontract_db/scan_select/scan_planner/scanner/join/JoinOrCandidate.cpp
alinous-core/codablecash
04ca04c9bc179aa81d4277ed34320b4340628bd1
[ "MIT" ]
209
2018-05-18T03:07:02.000Z
2022-03-26T11:42:41.000Z
src_smartcontract_db/scan_select/scan_planner/scanner/join/JoinOrCandidate.cpp
alinous-core/codablecash
04ca04c9bc179aa81d4277ed34320b4340628bd1
[ "MIT" ]
3
2019-07-06T09:16:36.000Z
2020-10-15T08:23:28.000Z
/* * JoinBranchCandidate.cpp * * Created on: 2020/09/01 * Author: iizuka */ #include "scan_select/scan_planner/scanner/join/JoinOrCandidate.h" #include "scan_select/scan_planner/scanner/join/AbstractJoinCandidateCollection.h" #include "scan_select/scan_planner/scanner/join/JoinCandidate.h" namespace codablecash { JoinOrCandidate::JoinOrCandidate(const JoinOrCandidate& inst) : AbstractJoinCandidate(inst.joinType) { int maxLoop = inst.list.size(); for(int i = 0; i != maxLoop; ++i){ AbstractJoinCandidateCollection* col = inst.list.get(i); AbstractJoinCandidateCollection* newCol = dynamic_cast<AbstractJoinCandidateCollection*>(col->copy()); this->list.addElement(newCol); } } JoinOrCandidate::JoinOrCandidate(int joinType) : AbstractJoinCandidate(joinType) { } JoinOrCandidate::~JoinOrCandidate() { this->list.deleteElements(); } AbstractJoinCandidate::CandidateType JoinOrCandidate::getCandidateType() const noexcept { return AbstractJoinCandidate::CandidateType::OR; } AbstractJoinCandidate* JoinOrCandidate::multiply(const AbstractJoinCandidate* other) const noexcept { JoinCandidate::CandidateType candidateType = other->getCandidateType(); if(candidateType == JoinCandidate::CandidateType::OR){ const JoinOrCandidate* orCandidate = dynamic_cast<const JoinOrCandidate*>(other); return multiplyOr(orCandidate); } JoinOrCandidate* newCond = new JoinOrCandidate(this->joinType); const AbstractJoinCandidateCollection* col = dynamic_cast<const AbstractJoinCandidateCollection*>(other); multiply(this, col, newCond); return newCond; } AbstractJoinCandidate* JoinOrCandidate::multiplyOr(const JoinOrCandidate* other) const noexcept { JoinOrCandidate* newCond = new JoinOrCandidate(this->joinType); int maxLoop = this->list.size(); for(int i = 0; i != maxLoop; ++i){ AbstractJoinCandidateCollection* col = this->list.get(i); multiply(other, col, newCond); } return newCond; } void JoinOrCandidate::multiply(const JoinOrCandidate* other, const AbstractJoinCandidateCollection* col, JoinOrCandidate* newCond) const noexcept { int maxLoop = other->list.size(); for(int i = 0; i != maxLoop; ++i){ AbstractJoinCandidateCollection* c = other->list.get(i); AbstractJoinCandidate* newC = c->multiply(col); AbstractJoinCandidateCollection* newCollection = dynamic_cast<AbstractJoinCandidateCollection*>(newC); newCond->list.addElement(newCollection); } } void JoinOrCandidate::add(const AbstractJoinCandidate* candidate) noexcept { JoinCandidate::CandidateType candidateType = candidate->getCandidateType(); if(candidateType == JoinCandidate::CandidateType::OR){ addOr(dynamic_cast<const JoinOrCandidate*>(candidate)); return; } AbstractJoinCandidateCollection* col = dynamic_cast<AbstractJoinCandidateCollection*>(candidate->copy()); this->list.addElement(col); } void JoinOrCandidate::addOr(const JoinOrCandidate* candidate) noexcept { int maxLoop = candidate->list.size(); for(int i = 0; i != maxLoop; ++i){ AbstractJoinCandidateCollection* col = dynamic_cast<AbstractJoinCandidateCollection*>(candidate->list.get(i)->copy()); this->list.addElement(col); } } AbstractJoinCandidate* JoinOrCandidate::copy() const noexcept { return new JoinOrCandidate(*this); } int JoinOrCandidate::size() const noexcept { return this->list.size(); } const AbstractJoinCandidateCollection* JoinOrCandidate::get(int i) const noexcept { return this->list.get(i); } int JoinOrCandidate::getOverHeadScore(AbstractScanTableTarget* left, AbstractScanTableTarget* right) const noexcept { int score = 0; int maxLoop = this->list.size(); for(int i = 0; i != maxLoop; ++i){ AbstractJoinCandidateCollection* col = this->list.get(i); score += col->getOverHeadScore(left, right); } return score; } CdbTableIndex* JoinOrCandidate::getIndex(const AbstractScanTableTarget* right) const noexcept { return nullptr; } } /* namespace codablecash */
30.2
120
0.767448
alinous-core
c4cc5ad1375eda855b296c1ec353a95240ffc075
10,739
cpp
C++
folly/experimental/channels/test/ChannelTest.cpp
wangzhx123/folly
94d02fac4a4b3dcd4f0e76566ae36a9aa32196ea
[ "Apache-2.0" ]
null
null
null
folly/experimental/channels/test/ChannelTest.cpp
wangzhx123/folly
94d02fac4a4b3dcd4f0e76566ae36a9aa32196ea
[ "Apache-2.0" ]
1
2022-03-28T16:56:01.000Z
2022-03-28T16:57:07.000Z
folly/experimental/channels/test/ChannelTest.cpp
wangzhx123/folly
94d02fac4a4b3dcd4f0e76566ae36a9aa32196ea
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/executors/ManualExecutor.h> #include <folly/experimental/channels/Channel.h> #include <folly/experimental/channels/test/ChannelTestUtil.h> #include <folly/experimental/coro/BlockingWait.h> #include <folly/portability/GTest.h> namespace folly { namespace channels { using namespace testing; class ChannelFixture : public Test, public WithParamInterface<ConsumptionMode>, public ChannelConsumerBase<int> { protected: ChannelFixture() : ChannelConsumerBase(GetParam()) {} ~ChannelFixture() override { cancellationSource_.requestCancellation(); if (!continueConsuming_.isFulfilled()) { continueConsuming_.setValue(false); } executor_.drain(); } folly::Executor::KeepAlive<> getExecutor() override { return &executor_; } void onNext(folly::Try<int> result) override { onNext_(std::move(result)); } folly::ManualExecutor executor_; StrictMock<MockNextCallback<int>> onNext_; }; TEST_P(ChannelFixture, SingleWriteBeforeNext_ThenCancelled) { auto [receiver, sender] = Channel<int>::create(); sender.write(1); EXPECT_CALL(onNext_, onValue(1)); EXPECT_CALL(onNext_, onCancelled()); startConsuming(std::move(receiver)); executor_.drain(); EXPECT_FALSE(sender.isReceiverCancelled()); cancellationSource_.requestCancellation(); executor_.drain(); EXPECT_TRUE(sender.isReceiverCancelled()); } TEST_P(ChannelFixture, SingleWriteAfterNext_ThenCancelled) { auto [receiver, sender] = Channel<int>::create(); startConsuming(std::move(receiver)); executor_.drain(); EXPECT_CALL(onNext_, onValue(1)); EXPECT_CALL(onNext_, onCancelled()); sender.write(1); executor_.drain(); EXPECT_FALSE(sender.isReceiverCancelled()); cancellationSource_.requestCancellation(); executor_.drain(); EXPECT_TRUE(sender.isReceiverCancelled()); } TEST_P(ChannelFixture, MultipleWrites_ThenStopConsumingByReturningFalse) { auto [receiver, sender] = Channel<int>::create(); startConsuming(std::move(receiver)); executor_.drain(); EXPECT_CALL(onNext_, onValue(1)); EXPECT_CALL(onNext_, onValue(2)); EXPECT_CALL(onNext_, onValue(3)); sender.write(1); sender.write(2); executor_.drain(); sender.write(3); sender.write(4); continueConsuming_ = folly::SharedPromise<bool>(); continueConsuming_.setValue(false); executor_.drain(); } TEST_P( ChannelFixture, MultipleWrites_ThenStopConsumingByThrowingOperationCancelled) { auto [receiver, sender] = Channel<int>::create(); startConsuming(std::move(receiver)); executor_.drain(); EXPECT_CALL(onNext_, onValue(1)); EXPECT_CALL(onNext_, onValue(2)); EXPECT_CALL(onNext_, onValue(3)); sender.write(1); sender.write(2); executor_.drain(); sender.write(3); sender.write(4); continueConsuming_ = folly::SharedPromise<bool>(); continueConsuming_.setException(folly::OperationCancelled()); executor_.drain(); } TEST_P(ChannelFixture, Close_NoException_BeforeSubscribe) { auto [receiver, sender] = Channel<int>::create(); std::move(sender).close(); EXPECT_CALL(onNext_, onClosed()); startConsuming(std::move(receiver)); executor_.drain(); } TEST_P(ChannelFixture, Close_NoException_AfterSubscribeAndWrite) { auto [receiver, sender] = Channel<int>::create(); sender.write(1); std::move(sender).close(); EXPECT_CALL(onNext_, onValue(1)); EXPECT_CALL(onNext_, onClosed()); startConsuming(std::move(receiver)); executor_.drain(); } TEST_P(ChannelFixture, Close_DueToDestruction_BeforeSubscribe) { auto [receiver, sender] = Channel<int>::create(); { auto toDestroy = std::move(sender); } EXPECT_CALL(onNext_, onClosed()); startConsuming(std::move(receiver)); executor_.drain(); } TEST_P(ChannelFixture, Close_DueToDestruction_AfterSubscribeAndWrite) { auto [receiver, sender] = Channel<int>::create(); EXPECT_CALL(onNext_, onValue(1)); EXPECT_CALL(onNext_, onClosed()); startConsuming(std::move(receiver)); sender.write(1); { auto toDestroy = std::move(sender); } executor_.drain(); } TEST_P(ChannelFixture, Close_Exception_BeforeSubscribe) { auto [receiver, sender] = Channel<int>::create(); std::move(sender).close(std::runtime_error("Error")); EXPECT_CALL(onNext_, onRuntimeError("std::runtime_error: Error")); startConsuming(std::move(receiver)); executor_.drain(); } TEST_P(ChannelFixture, Close_Exception_AfterSubscribeAndWrite) { auto [receiver, sender] = Channel<int>::create(); sender.write(1); std::move(sender).close(std::runtime_error("Error")); EXPECT_CALL(onNext_, onValue(1)); EXPECT_CALL(onNext_, onRuntimeError("std::runtime_error: Error")); startConsuming(std::move(receiver)); executor_.drain(); } TEST_P(ChannelFixture, CancellationRespected) { auto [receiver, sender] = Channel<int>::create(); EXPECT_CALL(onNext_, onValue(1)); continueConsuming_ = folly::SharedPromise<bool>(); sender.write(1); startConsuming(std::move(receiver)); executor_.drain(); EXPECT_FALSE(sender.isReceiverCancelled()); cancellationSource_.requestCancellation(); executor_.drain(); EXPECT_TRUE(sender.isReceiverCancelled()); } TEST(Channel, CancelNextWithoutClose) { folly::ManualExecutor executor; folly::CancellationSource cancelSource; auto [receiver, sender] = Channel<int>::create(); sender.write(1); EXPECT_EQ(folly::coro::blockingWait(receiver.next()).value(), 1); auto nextTask = folly::coro::co_withCancellation( cancelSource.getToken(), folly::coro::co_invoke( [&receiver = receiver]() -> folly::coro::Task<std::optional<int>> { co_return co_await receiver.next(false /* closeOnCancel */); })) .scheduleOn(&executor) .start(); executor.drain(); cancelSource.requestCancellation(); sender.write(2); executor.drain(); EXPECT_THROW( folly::coro::blockingWait(std::move(nextTask)), folly::OperationCancelled); EXPECT_EQ(folly::coro::blockingWait(receiver.next()).value(), 2); } INSTANTIATE_TEST_SUITE_P( Channel_Coro_WithTry, ChannelFixture, testing::Values(ConsumptionMode::CoroWithTry)); INSTANTIATE_TEST_SUITE_P( Channel_Coro_WithoutTry, ChannelFixture, testing::Values(ConsumptionMode::CoroWithoutTry)); INSTANTIATE_TEST_SUITE_P( Channel_Callback_WithHandle, ChannelFixture, testing::Values(ConsumptionMode::CallbackWithHandle)); INSTANTIATE_TEST_SUITE_P( Channel_Callback_WithHandleList, ChannelFixture, testing::Values(ConsumptionMode::CallbackWithHandleList)); class ChannelFixtureStress : public Test, public WithParamInterface<ConsumptionMode> { protected: ChannelFixtureStress() : producer_(std::make_unique<StressTestProducer<int>>( [value = 0]() mutable { return value++; })), consumer_(std::make_unique<StressTestConsumer<int>>( GetParam(), [lastReceived = -1](int value) mutable { EXPECT_EQ(value, ++lastReceived); })) {} static constexpr std::chrono::milliseconds kTestTimeout = std::chrono::milliseconds{5000}; std::unique_ptr<StressTestProducer<int>> producer_; std::unique_ptr<StressTestConsumer<int>> consumer_; }; TEST_P(ChannelFixtureStress, Close_NoException) { auto [receiver, sender] = Channel<int>::create(); producer_->startProducing(std::move(sender), std::nullopt /* closeEx */); consumer_->startConsuming(std::move(receiver)); /* sleep override */ std::this_thread::sleep_for(kTestTimeout); producer_->stopProducing(); EXPECT_EQ(consumer_->waitForClose().get(), CloseType::NoException); } TEST_P(ChannelFixtureStress, Close_Exception) { auto [receiver, sender] = Channel<int>::create(); producer_->startProducing(std::move(sender), std::runtime_error("Error")); consumer_->startConsuming(std::move(receiver)); /* sleep override */ std::this_thread::sleep_for(kTestTimeout); producer_->stopProducing(); EXPECT_EQ(consumer_->waitForClose().get(), CloseType::Exception); } TEST_P(ChannelFixtureStress, Cancelled) { auto [receiver, sender] = Channel<int>::create(); producer_->startProducing(std::move(sender), std::nullopt /* closeEx */); consumer_->startConsuming(std::move(receiver)); /* sleep override */ std::this_thread::sleep_for(kTestTimeout); consumer_->cancel(); EXPECT_EQ(consumer_->waitForClose().get(), CloseType::Cancelled); producer_->stopProducing(); } TEST_P(ChannelFixtureStress, Close_NoException_ThenCancelledImmediately) { auto [receiver, sender] = Channel<int>::create(); producer_->startProducing(std::move(sender), std::nullopt /* closeEx */); consumer_->startConsuming(std::move(receiver)); /* sleep override */ std::this_thread::sleep_for(kTestTimeout); producer_->stopProducing(); consumer_->cancel(); EXPECT_THAT( consumer_->waitForClose().get(), AnyOf(Eq(CloseType::NoException), Eq(CloseType::Cancelled))); } TEST_P(ChannelFixtureStress, Cancelled_ThenClosedImmediately_NoException) { auto [receiver, sender] = Channel<int>::create(); producer_->startProducing(std::move(sender), std::nullopt /* closeEx */); consumer_->startConsuming(std::move(receiver)); /* sleep override */ std::this_thread::sleep_for(kTestTimeout); consumer_->cancel(); producer_->stopProducing(); EXPECT_THAT( consumer_->waitForClose().get(), AnyOf(Eq(CloseType::NoException), Eq(CloseType::Cancelled))); } INSTANTIATE_TEST_SUITE_P( Channel_Coro_WithTry, ChannelFixtureStress, testing::Values(ConsumptionMode::CoroWithTry)); INSTANTIATE_TEST_SUITE_P( Channel_Coro_WithoutTry, ChannelFixtureStress, testing::Values(ConsumptionMode::CoroWithoutTry)); INSTANTIATE_TEST_SUITE_P( Channel_Callback_WithHandle, ChannelFixtureStress, testing::Values(ConsumptionMode::CallbackWithHandle)); INSTANTIATE_TEST_SUITE_P( Channel_Callback_WithHandleList, ChannelFixtureStress, testing::Values(ConsumptionMode::CallbackWithHandleList)); } // namespace channels } // namespace folly
28.186352
78
0.720086
wangzhx123
c4ce0dcfe681e79eb180beb08064f83d0460e66d
2,166
cpp
C++
NPSVisor/tools/svMaker/source/PDiagMirror.cpp
NPaolini/NPS_OpenSource
0c7da066b02b57ce282a1903a3901a563d04a28f
[ "Unlicense" ]
null
null
null
NPSVisor/tools/svMaker/source/PDiagMirror.cpp
NPaolini/NPS_OpenSource
0c7da066b02b57ce282a1903a3901a563d04a28f
[ "Unlicense" ]
null
null
null
NPSVisor/tools/svMaker/source/PDiagMirror.cpp
NPaolini/NPS_OpenSource
0c7da066b02b57ce282a1903a3901a563d04a28f
[ "Unlicense" ]
null
null
null
//----------- PDiagMirror.cpp ------------------------------------------------ //---------------------------------------------------------------------------- #include "precHeader.h" //---------------------------------------------------------------------------- #include "PDiagMirror.h" //---------------------------------------------------------------------------- PDiagMirror::PDiagMirror(PWin* parent, bool& all, uint& choose, bool hasSelected, uint resId, HINSTANCE hinstance) : baseClass(parent, resId, hinstance), All(all), Choose(choose), hasSelected(hasSelected) { } //---------------------------------------------------------------------------- PDiagMirror::~PDiagMirror() { } //---------------------------------------------------------------------------- bool PDiagMirror::create() { if(!baseClass::create()) return false; if(!hasSelected) { ENABLE(IDC_SELECTED, false); SET_CHECK(IDC_MIRROR_ALL); } else if(All) SET_CHECK(IDC_MIRROR_ALL); else SET_CHECK(IDC_SELECTED); if(!Choose) SET_CHECK(IDC_HORZ); else { if(Choose & emtVert) SET_CHECK(IDC_VERT); if(Choose & emtHorz) SET_CHECK(IDC_HORZ); } return true; } //---------------------------------------------------------------------------- LRESULT PDiagMirror::windowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { switch(message) { case WM_COMMAND: switch(LOWORD(wParam)) { case IDC_VERT: if(!IS_CHECKED(IDC_VERT)) SET_CHECK(IDC_HORZ); break; case IDC_HORZ: if(!IS_CHECKED(IDC_HORZ)) SET_CHECK(IDC_VERT); break; } break; } return baseClass::windowProc(hwnd, message, wParam, lParam); } //---------------------------------------------------------------------------- void PDiagMirror::CmOk() { if(!IS_CHECKED(IDC_VERT) && !IS_CHECKED(IDC_HORZ)) return; Choose = 0; if(IS_CHECKED(IDC_VERT)) Choose = emtVert; if(IS_CHECKED(IDC_HORZ)) Choose |= emtHorz; All = IS_CHECKED(IDC_MIRROR_ALL); baseClass::CmOk(); } //----------------------------------------------------------------------------
30.083333
116
0.440443
NPaolini
c4cefe124afee36b4870a0708ece73c366bad328
3,735
cpp
C++
Features/src/Host/ClientConnection.cpp
ProtocolONE/cord.app
0defd4e2cbc25d4f414fa68f8c1dfe65eadc02e7
[ "Apache-2.0" ]
8
2019-01-16T07:09:39.000Z
2020-11-06T23:13:46.000Z
Features/src/Host/ClientConnection.cpp
ProtocolONE/cord.app
0defd4e2cbc25d4f414fa68f8c1dfe65eadc02e7
[ "Apache-2.0" ]
null
null
null
Features/src/Host/ClientConnection.cpp
ProtocolONE/cord.app
0defd4e2cbc25d4f414fa68f8c1dfe65eadc02e7
[ "Apache-2.0" ]
3
2019-09-30T02:45:09.000Z
2019-09-30T23:17:26.000Z
#include <Host/ClientConnection.h> #include <Host/Dbus/ConnectionBridgeProxy.h> #include <Host/Dbus/DbusConnection.h> #include <Core/UI/Message.h> #include <RestApi/ProtocolOneCredential.h> #include <QtCore/QDebug> using P1::Host::DBus::DBusConnection; using P1::RestApi::ProtocolOneCredential; namespace P1 { namespace Host { ClientConnection::ClientConnection(const QString &name, QObject* parent /*= 0*/) : QObject(parent) , _maxTimeoutFail(30) // 3 * 10 * 5000 = 3 * 50 sec , _timeoutFail(0) , _connection(nullptr) , _appName(name) { QObject::connect(&this->_timeoutTimer, &QTimer::timeout, this, &ClientConnection::timeoutTick); this->_timeoutTimer.setInterval(5000); QObject::connect(&this->_pingpongTimer, &QTimer::timeout, this, &ClientConnection::sendPing); this->_pingpongTimer.setInterval(5000); } ClientConnection::~ClientConnection() { } void ClientConnection::init() { QDBusConnection &connection = DBusConnection::bus(); QString dbusService("com.protocolone.launcher.dbus"); this->_connection = new ConnectionBridgeProxy(dbusService, "/connection", connection, this); this->_connection->setApplicationName(this->_appName); QObject::connect(this->_connection, &ConnectionBridgeProxy::pong, this, &ClientConnection::onPong); QObject::connect(this->_connection, &ConnectionBridgeProxy::authorizationError, this, &ClientConnection::authorizationError); this->sendPing(); this->_pingpongTimer.start(); this->_timeoutTimer.start(); } void ClientConnection::timeoutTick() { // HACK disabled. Debug works very poor. //this->_timeoutFail++; //if (this->_timeoutFail < this->_maxTimeoutFail) // return; //this->internalDisconnected(); } void ClientConnection::sendPing() { Q_CHECK_PTR(this->_connection); QDBusPendingReply<> result = this->_connection->ping(); if (!result.isError()) return; qDebug() << "Ping finished with error:" << result.error().name() << "message:" << result.error().message() << "code:" << result.error().type(); if (result.error().type() == QDBusError::Disconnected) this->internalDisconnected(); } void ClientConnection::onPong() { DEBUG_LOG << "!!!! ClientConnection::onPong()"; this->_timeoutTimer.start(); this->_timeoutFail = 0; } void ClientConnection::setCredential(const P1::RestApi::ProtocolOneCredential& value) { Q_CHECK_PTR(this->_connection); this->_connection->setCredential(value.acccessTokent(), value.accessTokenExpiredTimeAsString()); } void ClientConnection::updateCredential( const P1::RestApi::ProtocolOneCredential& valueOld, const P1::RestApi::ProtocolOneCredential& valueNew) { Q_CHECK_PTR(this->_connection); this->_connection->updateCredential( valueOld.acccessTokent(), valueOld.accessTokenExpiredTimeAsString() , valueNew.acccessTokent(), valueNew.accessTokenExpiredTimeAsString()); } void ClientConnection::close() { Q_ASSERT(this->_connection); this->_connection->close(); } void ClientConnection::internalDisconnected() { this->_timeoutTimer.stop(); this->_pingpongTimer.stop(); qDebug() << "Disconnected from host"; P1::Core::UI::Message::critical(tr("DBUS_DISCONNECTED_TITLE"), tr("DBUS_DISCONNECTED_TEXT")); emit this->disconnected(); } } }
29.179688
103
0.636145
ProtocolONE
c4d003c70bb9ecb84fd4c91c3a8084a2057014ab
2,159
cpp
C++
Code/Tools/Fileserve/Main.cpp
fereeh/ezEngine
14e46cb2a1492812888602796db7ddd66e2b7110
[ "MIT" ]
null
null
null
Code/Tools/Fileserve/Main.cpp
fereeh/ezEngine
14e46cb2a1492812888602796db7ddd66e2b7110
[ "MIT" ]
null
null
null
Code/Tools/Fileserve/Main.cpp
fereeh/ezEngine
14e46cb2a1492812888602796db7ddd66e2b7110
[ "MIT" ]
null
null
null
#include <FileservePCH.h> #include <Fileserve/Main.h> #include <Foundation/Configuration/Startup.h> #include <Foundation/IO/FileSystem/FileSystem.h> #include <Foundation/Utilities/CommandLineUtils.h> #ifdef EZ_USE_QT #include <Gui.moc.h> #include <QApplication> #include <Foundation/Basics/Platform/Win/IncludeWindows.h> #endif #ifdef EZ_USE_QT int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { #else int main(int argc, const char** argv) { #endif ezFileserverApp* pApp = new ezFileserverApp(); #ifdef EZ_USE_QT ezCommandLineUtils::GetGlobalInstance()->SetCommandLine(); int argc = 0; char** argv = nullptr; QApplication* pQtApplication = new QApplication(argc, const_cast<char**>(argv)); pQtApplication->setApplicationName("ezFileserve"); pQtApplication->setOrganizationDomain("www.ezEngine.net"); pQtApplication->setOrganizationName("ezEngine Project"); pQtApplication->setApplicationVersion("1.0.0"); ezRun_Startup(pApp); CreateFileserveMainWindow(pApp); pQtApplication->exec(); ezRun_Shutdown(pApp); #else pApp->SetCommandLineArguments((ezUInt32)argc, argv); ezRun(pApp); #endif const int iReturnCode = pApp->GetReturnCode(); if (iReturnCode != 0) { std::string text = pApp->TranslateReturnCode(); if (!text.empty()) printf("Return Code: '%s'\n", text.c_str()); } delete pApp; return iReturnCode; } ezResult ezFileserverApp::BeforeCoreSystemsStartup() { ezStartup::AddApplicationTag("tool"); ezStartup::AddApplicationTag("fileserve"); return SUPER::BeforeCoreSystemsStartup(); } void ezFileserverApp::FileserverEventHandler(const ezFileserverEvent& e) { switch (e.m_Type) { case ezFileserverEvent::Type::ClientConnected: case ezFileserverEvent::Type::ClientReconnected: ++m_uiConnections; m_TimeTillClosing.SetZero(); break; case ezFileserverEvent::Type::ClientDisconnected: --m_uiConnections; if (m_uiConnections == 0 && m_CloseAppTimeout.GetSeconds() > 0) { // reset the timer m_TimeTillClosing = ezTime::Now() + m_CloseAppTimeout; } break; } }
24.816092
95
0.725799
fereeh
c4d15326bff694e1d4f7cb78450af46269c24997
4,534
cpp
C++
src/qc_ovps.cpp
Samthos/MC-MPn-Direct
cdf05c7ce7b33bf1b86b80f57f800634822c9cc6
[ "MIT" ]
1
2021-04-06T05:01:47.000Z
2021-04-06T05:01:47.000Z
src/qc_ovps.cpp
spec-org/MC-MPn-Direct
cdf05c7ce7b33bf1b86b80f57f800634822c9cc6
[ "MIT" ]
null
null
null
src/qc_ovps.cpp
spec-org/MC-MPn-Direct
cdf05c7ce7b33bf1b86b80f57f800634822c9cc6
[ "MIT" ]
3
2020-06-09T23:53:28.000Z
2022-03-02T05:44:55.000Z
#include <iostream> #include <functional> #include <algorithm> #include <cmath> #include "qc_ovps.h" template <template <typename, typename> typename Container, template <typename> typename Allocator> OVPS<Container, Allocator>::OVPS() { electron_pairs = 0; } template <template <typename, typename> typename Container, template <typename> typename Allocator> OVPS<Container, Allocator>::~OVPS() { } template <template <typename, typename> typename Container, template <typename> typename Allocator> void OVPS<Container, Allocator>::init(const int dimm, const int electron_pairs_) { electron_pairs = electron_pairs_; o_set.resize(dimm); v_set.resize(dimm); for (auto stop = 0; stop < dimm; stop++) { o_set[stop].resize(stop + 1); v_set[stop].resize(stop + 1); for (auto start = 0; start < stop + 1; start++) { o_set[stop][start].resize(electron_pairs); v_set[stop][start].resize(electron_pairs); } } } template <template <typename, typename> typename Container, template <typename> typename Allocator> void OVPS<Container, Allocator>::update(Wavefunction_Type& electron_pair_psi1, Wavefunction_Type& electron_pair_psi2, Tau* tau) { std::cerr << "Default OVPS update_ovsp not implemented\n"; exit(0); } template <> void OVPS_Host::update(Wavefunction_Type& electron_pair_psi1, Wavefunction_Type& electron_pair_psi2, Tau* tau) { auto iocc1 = electron_pair_psi1.iocc1; auto iocc2 = electron_pair_psi1.iocc2; auto ivir1 = electron_pair_psi1.ivir1; auto ivir2 = electron_pair_psi1.ivir2; auto lda = electron_pair_psi1.lda; for (auto stop = 0; stop < o_set.size(); stop++) { for (auto start = 0; start < o_set[stop].size(); start++) { auto t_val = tau->get_exp_tau(stop, start); std::transform(t_val.begin(), t_val.end(), t_val.begin(), [](double x){return sqrt(x);}); blas_wrapper.ddgmm(BLAS_WRAPPER::LEFT_SIDE, ivir2 - iocc1, electron_pairs, electron_pair_psi1.psi, iocc1, lda, t_val, iocc1, 1, electron_pair_psi1.psiTau, iocc1, lda); blas_wrapper.ddgmm(BLAS_WRAPPER::LEFT_SIDE, ivir2 - iocc1, electron_pairs, electron_pair_psi2.psi, iocc1, lda, t_val, iocc1, 1, electron_pair_psi2.psiTau, iocc1, lda); o_set[stop][start].update(electron_pair_psi1.psiTau, iocc1, electron_pair_psi2.psiTau, iocc1, iocc2 - iocc1, lda, blas_wrapper); v_set[stop][start].update(electron_pair_psi1.psiTau, ivir1, electron_pair_psi2.psiTau, ivir1, ivir2 - ivir1, lda, blas_wrapper); } } } #ifdef HAVE_CUDA template <> void OVPS_Device::update(Wavefunction_Type& electron_pair_psi1, Wavefunction_Type& electron_pair_psi2, Tau* tau) { auto iocc1 = electron_pair_psi1.iocc1; auto iocc2 = electron_pair_psi1.iocc2; auto ivir1 = electron_pair_psi1.ivir1; auto ivir2 = electron_pair_psi1.ivir2; auto lda = electron_pair_psi1.lda; for (auto stop = 0; stop < o_set.size(); stop++) { for (auto start = 0; start < o_set[stop].size(); start++) { auto t_val = tau->get_exp_tau(stop, start); std::transform(t_val.begin(), t_val.end(), t_val.begin(), [](double x){return sqrt(x);}); thrust::device_vector<double, thrust::device_allocator<double>> d_t_val = t_val; blas_wrapper.ddgmm(BLAS_WRAPPER::LEFT_SIDE, ivir2 - iocc1, electron_pairs, electron_pair_psi1.psi, iocc1, lda, d_t_val, iocc1, 1, electron_pair_psi1.psiTau, iocc1, lda); blas_wrapper.ddgmm(BLAS_WRAPPER::LEFT_SIDE, ivir2 - iocc1, electron_pairs, electron_pair_psi2.psi, iocc1, lda, d_t_val, iocc1, 1, electron_pair_psi2.psiTau, iocc1, lda); o_set[stop][start].update(electron_pair_psi1.psiTau, iocc1, electron_pair_psi2.psiTau, iocc1, iocc2 - iocc1, lda, blas_wrapper); v_set[stop][start].update(electron_pair_psi1.psiTau, ivir1, electron_pair_psi2.psiTau, ivir1, ivir2 - ivir1, lda, blas_wrapper); } } } void copy_OVPS(OVPS_Host& src, OVPS_Device& dest) { for (int i = 0; i < src.o_set.size(); i++) { for (int j = 0; j < src.o_set[i].size(); j++) { copy_OVPS_Set(src.o_set[i][j], dest.o_set[i][j]); copy_OVPS_Set(src.v_set[i][j], dest.v_set[i][j]); } } } void copy_OVPS(OVPS_Device& src, OVPS_Host& dest) { for (int i = 0; i < src.o_set.size(); i++) { for (int j = 0; j < src.o_set[i].size(); j++) { copy_OVPS_Set(src.o_set[i][j], dest.o_set[i][j]); copy_OVPS_Set(src.v_set[i][j], dest.v_set[i][j]); } } } #endif
38.423729
134
0.679974
Samthos
c4d183b6269f9964875a695555203b9382224f0f
50,419
cc
C++
cow/src/components/audio_sink_pulse.cc
halleyzhao/alios-mm
bef2a6de0c207a5ae9bf4f63de2e562df864aa3e
[ "Apache-2.0" ]
null
null
null
cow/src/components/audio_sink_pulse.cc
halleyzhao/alios-mm
bef2a6de0c207a5ae9bf4f63de2e562df864aa3e
[ "Apache-2.0" ]
null
null
null
cow/src/components/audio_sink_pulse.cc
halleyzhao/alios-mm
bef2a6de0c207a5ae9bf4f63de2e562df864aa3e
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2017 Alibaba Group Holding Limited. 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 <math.h> #include "audio_sink_pulse.h" #include "multimedia/mm_types.h" #include "multimedia/mm_errors.h" #include "multimedia/mmlistener.h" #include "multimedia/mm_cpp_utils.h" #include "multimedia/media_buffer.h" #include "multimedia/media_meta.h" #include "multimedia/media_attr_str.h" #include "multimedia/mm_audio.h" #include <pulse/sample.h> #include <pulse/pulseaudio.h> #include <pulse/thread-mainloop.h> #include <pthread.h> #include <stdio.h> #ifdef ENABLE_DEFAULT_AUDIO_CONNECTION #include <multimedia/mm_amhelper.h> #endif #ifndef MM_LOG_OUTPUT_V //#define MM_LOG_OUTPUT_V #endif #include <multimedia/mm_debug.h> namespace YUNOS_MM { MM_LOG_DEFINE_MODULE_NAME("MSP") static const char * COMPONENT_NAME = "AudioSinkPulse"; static const char * MMTHREAD_NAME = "AudioSinkPulse::Private::OutputThread"; #define DEFAULT_VOLUME 1.0 #define DEFAULT_MUTE false #define MAX_VOLUME 10.0 #define DEFAULT_SAMPLE_RATE 44100 #define DEFAULT_CHANNEL 2 #define CLOCK_TIME_NONE -1 #define PA_ERROR(_retcode, _info, _pa_err_no) do {\ ERROR("%s, retcode: %d, pa: %s\n", _info, _retcode, pa_strerror(_pa_err_no));\ return _retcode;\ }while(0) static const struct format_entry { snd_format_t spformat; pa_sample_format_t pa; } format_map[] = { {SND_FORMAT_PCM_16_BIT, PA_SAMPLE_S16LE}, {SND_FORMAT_PCM_32_BIT, PA_SAMPLE_S32LE}, {SND_FORMAT_PCM_8_BIT, PA_SAMPLE_U8}, {SND_FORMAT_INVALID, PA_SAMPLE_INVALID} }; #define ENTER() VERBOSE(">>>\n") #define EXIT() do {VERBOSE(" <<<\n"); return;}while(0) #define EXIT_AND_RETURN(_code) do {VERBOSE("<<<(status: %d)\n", (_code)); return (_code);}while(0) #define ENTER1() DEBUG(">>>\n") #define EXIT1() do {DEBUG(" <<<\n"); return;}while(0) #define EXIT_AND_RETURN1(_code) do {DEBUG("<<<(status: %d)\n", (_code)); return (_code);}while(0) #define setState(_param, _deststate) do {\ INFO("change state from %d to %s\n", _param, #_deststate);\ (_param) = (_deststate);\ }while(0) class PAMMAutoLock { public: explicit PAMMAutoLock(pa_threaded_mainloop* loop) : mPALoop(loop) { pa_threaded_mainloop_lock (mPALoop); } ~PAMMAutoLock() { pa_threaded_mainloop_unlock (mPALoop); } pa_threaded_mainloop* mPALoop; private: MM_DISALLOW_COPY(PAMMAutoLock); }; class AudioSinkPulse::Private { public: enum state_t { STATE_IDLE, STATE_PREPARED, STATE_STARTED, STATE_PAUSED, STATE_STOPED, }; struct QueueEntry { MediaBufferSP mBuffer; mm_status_t mFinalResult; }; /* start of outputthread*/ class OutputThread; typedef MMSharedPtr <OutputThread> OutputThreadSP; class OutputThread : public MMThread { public: OutputThread(Private* render) : MMThread(MMTHREAD_NAME) , mRender(render) , mContinue(true) { ENTER(); EXIT(); } ~OutputThread() { ENTER(); EXIT(); } void signalExit() { ENTER(); MMAutoLock locker(mRender->mLock); mContinue = false; mRender->mCondition.signal(); EXIT(); } void signalContinue() { ENTER(); mRender->mCondition.signal(); EXIT(); } protected: // Write PCM data to pulseaudio void main() { ENTER(); MediaBufferSP mediaBuffer; uint8_t *sourceBuf = NULL; int64_t pts = 0; int negative = 0; pa_usec_t latencyMicros = 0; int32_t offset = 0; int32_t size = 0; while(1) { { MMAutoLock locker(mRender->mLock); if (!mContinue) { break; } mRender->mPAWriteableSize = pa_stream_writable_size (mRender->mPAStream); if (mRender->mIsPaused || mRender->mAvailableSourceBuffers.empty()) { VERBOSE("waitting condition\n"); mRender->mCondition.wait(); VERBOSE("wakeup condition\n"); continue; } mediaBuffer = mRender->mAvailableSourceBuffers.front(); mediaBuffer->getBufferInfo((uintptr_t*)&sourceBuf, &offset, &size, 1); } if (!sourceBuf || size == 0) { if (mediaBuffer->isFlagSet(MediaBuffer::MBFT_EOS)) {// EOS frame PAMMAutoLock paLoop(mRender->mPALoop); mRender->streamDrain(); mRender->mAudioSink->notify(kEventEOS, 0, 0, nilParam); } { MMAutoLock locker(mRender->mLock); mRender->mAvailableSourceBuffers.pop(); } continue; } { MMAutoLock locker(mRender->mLock); if (mediaBuffer->type() != MediaBuffer::MBT_RawAudio) { ERROR("wrong buffer type %d", mediaBuffer->type()); mRender->mAvailableSourceBuffers.pop(); continue; } } sourceBuf += offset; VERBOSE("pcm buffer %p, offset %d, size %d, pts %" PRId64 " ms", sourceBuf, offset, size, mediaBuffer->pts()/1000ll); #ifdef DUMP_SINK_PULSE_DATA fwrite(sourceBuf,1,size,mRender->mDumpFile); fwrite(&size,4,1,mRender->mDumpFileSize); #endif pts = mediaBuffer->pts(); while (size > 0) { if ((mRender->mPAWriteableSize > 0) && (mRender->mScaledPlayRate == SCALED_PLAY_RATE)) { { PAMMAutoLock paLoop(mRender->mPALoop); int32_t writeSize = mRender->mPAWriteableSize < size ? mRender->mPAWriteableSize:size; if (pa_stream_get_latency(mRender->mPAStream, &latencyMicros, &negative) != 0) ERROR("get latency error"); pa_sample_format paFormat = mRender->convertFormatToPulse((snd_format_t)mRender->mFormat); pa_sample_spec sample_spec = { .format = paFormat, .rate = (uint32_t)mRender->mSampleRate, .channels = (uint8_t)mRender->mChannelCount }; int64_t duration = pa_bytes_to_usec((uint64_t)writeSize, &sample_spec); if (MM_LIKELY(!mediaBuffer->isFlagSet(MediaBuffer::MBFT_EOS))) { // Some packet->pts is -1 for TS file. So DO NOT set anchro time when pts is invalid. if (pts >= 0) { mRender->mClockWrapper->setAnchorTime(pts, Clock::getNowUs() + latencyMicros, pts + duration); } } pa_stream_write(mRender->mPAStream, sourceBuf, writeSize, NULL, 0LL, PA_SEEK_RELATIVE); size -= writeSize; if (size > 0) { sourceBuf += writeSize; mRender->mPAWriteableSize = 0; pts += duration/1000ll; } } if (size <= 0) { if (mediaBuffer->isFlagSet(MediaBuffer::MBFT_EOS)) {// EOS frame PAMMAutoLock paLoop(mRender->mPALoop); mRender->streamDrain(); mRender->mAudioSink->notify(kEventEOS, 0, 0, nilParam); } MMAutoLock locker(mRender->mLock); mRender->mAvailableSourceBuffers.pop(); break; } } else { MMAutoLock locker(mRender->mLock); VERBOSE("wait for writeable"); mRender->mCondition.wait(); VERBOSE("wait for writeable wakeup "); if (!mContinue || mRender->mAvailableSourceBuffers.empty()) { break; } if (!mRender->mIsPaused) mRender->mPAWriteableSize = pa_stream_writable_size (mRender->mPAStream); continue; } } } INFO("Output thread exited\n"); EXIT(); } private: AudioSinkPulse::Private *mRender; bool mContinue; }; /* end of outputthread*/ static PrivateSP create() { ENTER(); PrivateSP priv(new Private()); if (priv) { INFO("private create success"); } return priv; } mm_status_t init(AudioSinkPulse *audioSink) { ENTER(); mAudioSink = audioSink; #ifdef DUMP_SINK_PULSE_DATA mDumpFile = fopen("/data/audio_sink_pulse.pcm","wb"); mDumpFileSize = fopen("/data/audio_sink_pulse.size","wb"); #endif EXIT_AND_RETURN(MM_ERROR_SUCCESS); } void uninit() { #ifdef DUMP_SINK_PULSE_DATA fclose(mDumpFile); fclose(mDumpFileSize); #endif } ~Private() { #ifdef ENABLE_DEFAULT_AUDIO_CONNECTION ENSURE_AUDIO_DEF_CONNECTION_CLEAN(); #endif } snd_format_t convertFormatFromPulse(pa_sample_format paFormat); pa_sample_format convertFormatToPulse(snd_format_t format); static void contextStateCallback(pa_context *c, void *userdata); static void contextSinkinputInfoCallback(pa_context *c, const pa_sink_input_info *i, int eol, void *userdata); static void contextSubscribeCallback(pa_context *c, pa_subscription_event_type_t type, uint32_t idx, void *userdata); static void contextSinkInfoCallback(pa_context *c, const pa_sink_input_info *i, int is_last, void *userdata); static void streamStateCallback(pa_stream *s, void *userdata); static void streamLatencyUpdateCallback(pa_stream *s, void *userdata); static void streamUnderflowCallback(pa_stream *s, void *userdata); static void streamOverflowCallback(pa_stream *s, void *userdata); static void streamWriteCallback(pa_stream *s, size_t length, void *userdata); static void streamSuccessCallback(pa_stream*s, int success, void *userdata); static void streamSuspendedCallback (pa_stream * s, void *userdata); static void streamStartedCallback (pa_stream * s, void *userdata); static void streamEventCallback (pa_stream * s, const char *name, pa_proplist * pl, void *userdata); mm_status_t creatPAContext(); mm_status_t creatPAStream(); mm_status_t release(); mm_status_t freePAContext(); mm_status_t freePASteam(); mm_status_t freePALoop(); mm_status_t streamFlush(); mm_status_t streamDrain(); static void streamFlushCallback(pa_stream*s, int success, void *userdata); static void streamDrainCallback(pa_stream*s, int success, void *userdata); mm_status_t cork(int b); static void streamCorkCallback(pa_stream*s, int success, void *userdata); void clearPACallback(); void clearSourceBuffers(); mm_status_t setVolume(double volume); double getVolume(); mm_status_t setMute(bool mute); bool getMute(); bool waitPAOperation(pa_operation *op); mm_status_t resumeInternal(); pa_threaded_mainloop *mPALoop; pa_context *mPAContext; pa_stream *mPAStream; //pa_sink_input_info mPASinkInfo; int32_t mPAWriteableSize; double mVolume; bool mMute; int32_t mFormat; int32_t mSampleRate; int32_t mChannelCount; int mCorkResult; int mFlushResult; int mDrainResult; bool mIsDraining; std::queue<MediaBufferSP> mAvailableSourceBuffers; ClockWrapperSP mClockWrapper; bool mIsPaused; Condition mCondition; Lock mLock; state_t mState; int32_t mTotalBuffersQueued; OutputThreadSP mOutputThread; AudioSinkPulse *mAudioSink; #ifdef DUMP_SINK_PULSE_DATA FILE* mDumpFile; FILE* mDumpFileSize; #endif int32_t mScaledPlayRate; std::string mAudioConnectionId; #ifdef ENABLE_DEFAULT_AUDIO_CONNECTION ENSURE_AUDIO_DEF_CONNECTION_DECLARE() #endif Private() :mPALoop(NULL), mPAContext(NULL), mPAStream(NULL), mPAWriteableSize(0), mVolume(DEFAULT_VOLUME), mMute(DEFAULT_MUTE), mFormat(SND_FORMAT_PCM_16_BIT), mSampleRate(DEFAULT_SAMPLE_RATE), mChannelCount(DEFAULT_CHANNEL), mCorkResult(0), mFlushResult(0), mDrainResult(0), mIsDraining(false), mIsPaused(true), mCondition(mLock), mState(STATE_IDLE), mTotalBuffersQueued(0), mAudioSink(NULL), mScaledPlayRate(SCALED_PLAY_RATE) { ENTER(); mClockWrapper.reset(new ClockWrapper()); #ifdef ENABLE_DEFAULT_AUDIO_CONNECTION ENSURE_AUDIO_DEF_CONNECTION_INIT(); #endif EXIT(); } MM_DISALLOW_COPY(Private); }; #define ASP_MSG_prepare (msg_type)1 #define ASP_MSG_start (msg_type)2 #define ASP_MSG_resume (msg_type)3 #define ASP_MSG_pause (msg_type)4 #define ASP_MSG_stop (msg_type)5 #define ASP_MSG_flush (msg_type)6 #define ASP_MSG_seek (msg_type)7 #define ASP_MSG_reset (msg_type)8 #define ASP_MSG_setParameters (msg_type)9 #define ASP_MSG_getParameters (msg_type)10 #define ASP_MSG_write (msg_type)11 #define ASP_MSG_setMetaData (msg_type)12 BEGIN_MSG_LOOP(AudioSinkPulse) MSG_ITEM(ASP_MSG_prepare, onPrepare) MSG_ITEM(ASP_MSG_start, onStart) MSG_ITEM(ASP_MSG_resume, onResume) MSG_ITEM(ASP_MSG_pause, onPause) MSG_ITEM(ASP_MSG_stop, onStop) MSG_ITEM(ASP_MSG_flush, onFlush) MSG_ITEM(ASP_MSG_seek, onSeek) MSG_ITEM(ASP_MSG_reset, onReset) MSG_ITEM(ASP_MSG_setParameters, onSetParameters) MSG_ITEM(ASP_MSG_getParameters, onGetParameters) MSG_ITEM(ASP_MSG_write, onWrite) MSG_ITEM(ASP_MSG_setMetaData, onSetMetaData) END_MSG_LOOP() AudioSinkPulse::AudioSinkPulse(const char *mimeType, bool isEncoder) : MMMsgThread(COMPONENT_NAME) , mComponentName(COMPONENT_NAME) { mPriv = Private::create(); if (!mPriv) ERROR("no render"); } AudioSinkPulse::~AudioSinkPulse() { //release(); } Component::WriterSP AudioSinkPulse::getWriter(MediaType mediaType) { ENTER(); if ( (int)mediaType != Component::kMediaTypeAudio ) { ERROR("not supported mediatype: %d\n", mediaType); return Component::WriterSP((Component::Writer*)NULL); } Component::WriterSP wd(new AudioSinkPulse::AudioSinkWriter(this)); return wd; } mm_status_t AudioSinkPulse::init() { if (!mPriv) return MM_ERROR_NO_COMPONENT; int ret = mPriv->init(this); // MMMsgThread->run(); if (ret) EXIT_AND_RETURN(MM_ERROR_OP_FAILED); ret = MMMsgThread::run(); if (ret != 0) { ERROR("init failed, ret %d", ret); EXIT_AND_RETURN(MM_ERROR_OP_FAILED); } EXIT_AND_RETURN(MM_ERROR_SUCCESS); } void AudioSinkPulse::uninit() { ENTER(); mPriv->uninit(); MMMsgThread::exit(); EXIT(); } const char * AudioSinkPulse::name() const { return mComponentName.c_str(); } ClockSP AudioSinkPulse::provideClock() { ENTER(); if (!mPriv) ERROR("no render"); return mPriv->mClockWrapper->provideClock(); } mm_status_t AudioSinkPulse::prepare() { postMsg(ASP_MSG_prepare, 0, NULL); return MM_ERROR_ASYNC; } mm_status_t AudioSinkPulse::start() { postMsg(ASP_MSG_start, 0, NULL); return MM_ERROR_ASYNC; } mm_status_t AudioSinkPulse::resume() { postMsg(ASP_MSG_resume, 0, NULL); return MM_ERROR_ASYNC; } mm_status_t AudioSinkPulse::stop() { postMsg(ASP_MSG_stop, 0, NULL); return MM_ERROR_ASYNC; } mm_status_t AudioSinkPulse::pause() { postMsg(ASP_MSG_pause, 0, NULL); return MM_ERROR_ASYNC; } mm_status_t AudioSinkPulse::seek(int msec, int seekSequence) { postMsg(ASP_MSG_seek, 0, NULL); return MM_ERROR_ASYNC; } mm_status_t AudioSinkPulse::reset() { postMsg(ASP_MSG_reset, 0, NULL); return MM_ERROR_ASYNC; } mm_status_t AudioSinkPulse::flush() { postMsg(ASP_MSG_flush, 0, NULL); return MM_ERROR_ASYNC; } mm_status_t AudioSinkPulse::AudioSinkWriter::write(const MediaBufferSP & buf) { ENTER(); if (!mRender->mPriv) return MM_ERROR_NO_COMPONENT; AudioSinkPulse::Private::QueueEntry *pEntry = new AudioSinkPulse::Private::QueueEntry; pEntry->mBuffer = buf; ++mRender->mPriv->mTotalBuffersQueued; mRender->postMsg(ASP_MSG_write, 0, (param2_type)pEntry); EXIT_AND_RETURN(MM_ERROR_SUCCESS); } mm_status_t AudioSinkPulse::AudioSinkWriter::setMetaData(const MediaMetaSP & metaData) { ENTER(); if (!mRender->mPriv) return MM_ERROR_NO_COMPONENT; int ret = metaData->getInt32(MEDIA_ATTR_SAMPLE_RATE, mRender->mPriv->mSampleRate); if (!ret) { ERROR("fail to get int32_t data %s\n", MEDIA_ATTR_SAMPLE_RATE); EXIT_AND_RETURN(MM_ERROR_OP_FAILED); } ret = metaData->getInt32(MEDIA_ATTR_SAMPLE_FORMAT, mRender->mPriv->mFormat); if (!ret) { ERROR("fail to get int32_t data %s\n", MEDIA_ATTR_SAMPLE_FORMAT); EXIT_AND_RETURN(MM_ERROR_OP_FAILED); } ret = metaData->getInt32(MEDIA_ATTR_CHANNEL_COUNT, mRender->mPriv->mChannelCount); if (!ret) { ERROR("fail to get int32_t data %s\n", MEDIA_ATTR_CHANNEL_COUNT); EXIT_AND_RETURN(MM_ERROR_OP_FAILED); } INFO("sampleRate %d, format %d, channel %d", mRender->mPriv->mSampleRate, mRender->mPriv->mFormat, mRender->mPriv->mChannelCount); EXIT_AND_RETURN(MM_ERROR_SUCCESS); } mm_status_t AudioSinkPulse::setParameter(const MediaMetaSP & meta) { ENTER(); if (!mPriv) return MM_ERROR_NO_COMPONENT; //if (!mPriv->mPALoop) // EXIT_AND_RETURN(MM_ERROR_INVALID_PARAM); //PAMMAutoLock paLoop(mPriv->mPALoop);//remove these code to setVolume and setMute method. for ( MediaMeta::iterator i = meta->begin(); i != meta->end(); ++i ) { const MediaMeta::MetaItem & item = *i; if ( !strcmp(item.mName, MEDIA_ATTR_MUTE) ) { if ( item.mType != MediaMeta::MT_Int32 ) { WARNING("invalid type for %s\n", item.mName); continue; } mPriv->mMute = item.mValue.ii; mPriv->setMute(mPriv->mMute); INFO("key: %s, value: %d\n", item.mName, mPriv->mMute); } if ( !strcmp(item.mName, MEDIA_ATTR_VOLUME) ) { if ( item.mType != MediaMeta::MT_Int64 ) { WARNING("invalid type for %s\n", item.mName); continue; } mPriv->mVolume = item.mValue.ld; mPriv->setVolume(mPriv->mVolume); INFO("key: %s, value: %" PRId64 "\n", item.mName, mPriv->mMute); } if ( !strcmp(item.mName, MEDIA_ATTR_PALY_RATE) ) { if ( item.mType != MediaMeta::MT_Int32 ) { WARNING("invalid type for %s\n", item.mName); continue; } if (mPriv->mScaledPlayRate == item.mValue.ii) { DEBUG("play rate is already %d, just return\n", mPriv->mScaledPlayRate); continue; } mPriv->mScaledPlayRate = item.mValue.ii; DEBUG("key: %s, val: %d\n", item.mName, item.mValue.ii); continue; } } EXIT_AND_RETURN(MM_ERROR_SUCCESS); } mm_status_t AudioSinkPulse::getParameter(MediaMetaSP & meta) const { ENTER(); if (!mPriv) return MM_ERROR_NO_COMPONENT; meta->setInt32(MEDIA_ATTR_MUTE, mPriv->mMute); meta->setInt64(MEDIA_ATTR_VOLUME, mPriv->mVolume); EXIT_AND_RETURN(MM_ERROR_SUCCESS); } int64_t AudioSinkPulse::getCurrentPosition() { if (!mPriv) return MM_ERROR_NO_COMPONENT; PAMMAutoLock paLoop(mPriv->mPALoop); int64_t currentPosition = -1ll; if (mPriv->mClockWrapper && mPriv->mClockWrapper->getCurrentPosition(currentPosition) != MM_ERROR_SUCCESS) { ERROR("getCurrentPosition failed"); currentPosition = -1ll; } VERBOSE("getCurrentPosition %" PRId64 " ms", currentPosition/1000ll); return currentPosition; } void AudioSinkPulse::onSetMetaData(param1_type param1, param2_type param2, uint32_t rspId) { ENTER(); EXIT(); } void AudioSinkPulse::onPrepare(param1_type param1, param2_type param2, uint32_t rspId) { ENTER1(); mPriv->mPAWriteableSize = 0; mm_status_t ret = mPriv->creatPAContext(); if ( ret != MM_ERROR_SUCCESS ) { ERROR("failed to create context\n"); notify(kEventError, MM_ERROR_NO_MEM, 0, nilParam); EXIT1(); } ret = mPriv->creatPAStream(); if ( ret != MM_ERROR_SUCCESS ) { ERROR("failed to create stream\n"); notify(kEventError, MM_ERROR_NO_MEM, 0, nilParam); EXIT1(); } setState(mPriv->mState, mPriv->STATE_PREPARED); notify(kEventPrepareResult, MM_ERROR_SUCCESS, 0, nilParam); EXIT1(); } mm_status_t AudioSinkPulse::Private::resumeInternal() { if (!mIsPaused || mIsDraining) { ERROR("Aready started\n"); mAudioSink->notify(kEventStartResult, MM_ERROR_SUCCESS, 0, nilParam); EXIT_AND_RETURN(MM_ERROR_SUCCESS); } mm_status_t ret = cork(0); if ( ret != MM_ERROR_SUCCESS ) { ERROR("failed to create stream\n"); mAudioSink->notify(kEventError, MM_ERROR_OP_FAILED, 0, nilParam); EXIT_AND_RETURN(MM_ERROR_INVALID_PARAM); } if (mIsPaused && mClockWrapper) { mClockWrapper->resume(); } mIsPaused = false; setState(mState, STATE_STARTED); mAudioSink->notify(kEventStartResult, MM_ERROR_SUCCESS, 0, nilParam); mOutputThread->signalContinue(); EXIT_AND_RETURN(MM_ERROR_SUCCESS); } void AudioSinkPulse::onStart(param1_type param1, param2_type param2, uint32_t rspId) { ENTER1(); PAMMAutoLock paLoop(mPriv->mPALoop); // create thread to handle output buffer if (!mPriv->mOutputThread) { mPriv->mOutputThread.reset (new AudioSinkPulse::Private::OutputThread(mPriv.get()), MMThread::releaseHelper); mPriv->mOutputThread->create(); } mPriv->resumeInternal(); EXIT1(); } void AudioSinkPulse::onResume(param1_type param1, param2_type param2, uint32_t rspId) { ENTER1(); PAMMAutoLock paLoop(mPriv->mPALoop); mPriv->resumeInternal(); EXIT1(); } void AudioSinkPulse::onStop(param1_type param1, param2_type param2, uint32_t rspId) { ENTER1(); { mPriv->mIsPaused = true; if (mPriv->mOutputThread) { mPriv->mOutputThread->signalExit(); mPriv->mOutputThread.reset(); } } PAMMAutoLock paLoop(mPriv->mPALoop); if (mPriv->mState == mPriv->STATE_IDLE || mPriv->mState == mPriv->STATE_STOPED || mPriv->mIsDraining) { notify(kEventStopped, MM_ERROR_SUCCESS, 0, nilParam); EXIT1(); } if (mPriv->mState == mPriv->STATE_STARTED) { mm_status_t ret = mPriv->streamFlush(); if (MM_ERROR_SUCCESS != ret) { ERROR("flush fail"); notify(kEventError, MM_ERROR_OP_FAILED, 0, nilParam); EXIT1(); } ret = mPriv->cork(1); if (MM_ERROR_SUCCESS != ret) { ERROR("cork fail"); notify(kEventError, MM_ERROR_OP_FAILED, 0, nilParam); EXIT1(); } } mPriv->clearPACallback(); setState(mPriv->mState, mPriv->STATE_STOPED); notify(kEventStopped, MM_ERROR_SUCCESS, 0, nilParam); EXIT1(); } void AudioSinkPulse::onPause(param1_type param1, param2_type param2, uint32_t rspId) { ENTER1(); PAMMAutoLock paLoop(mPriv->mPALoop); mPriv->mIsPaused = true; if (mPriv->mState == mPriv->STATE_PAUSED || mPriv->mIsDraining) { notify(kEventPaused, MM_ERROR_SUCCESS, 0, nilParam); EXIT1(); } mm_status_t ret = mPriv->cork(1); if ( ret != MM_ERROR_SUCCESS ) { ERROR("failed to create stream\n"); notify(kEventError, MM_ERROR_OP_FAILED, 0, nilParam); EXIT(); } if (mPriv->mClockWrapper) { mPriv->mClockWrapper->pause(); } setState(mPriv->mState, mPriv->STATE_PAUSED); notify(kEventPaused, MM_ERROR_SUCCESS, 0, nilParam); EXIT1(); } void AudioSinkPulse::onFlush(param1_type param1, param2_type param2, uint32_t rspId) { ENTER1(); { PAMMAutoLock paLoop(mPriv->mPALoop); mm_status_t ret = mPriv->streamFlush(); if (MM_ERROR_SUCCESS != ret) { ERROR("flush fail"); notify(kEventError, MM_ERROR_OP_FAILED, 0, nilParam); EXIT1(); } if (mPriv->mClockWrapper) { mPriv->mClockWrapper->flush(); } } MMAutoLock locker(mPriv->mLock); mPriv->clearSourceBuffers(); notify(kEventFlushComplete, MM_ERROR_SUCCESS, 0, nilParam); EXIT1(); } void AudioSinkPulse::onSeek(param1_type param1, param2_type param2, uint32_t rspId) { ENTER1(); { PAMMAutoLock paLoop(mPriv->mPALoop); mm_status_t ret = mPriv->streamFlush(); if (MM_ERROR_SUCCESS != ret) { ERROR("flush fail"); notify(kEventError, MM_ERROR_OP_FAILED, 0, nilParam); EXIT1(); } if (mPriv->mClockWrapper) { mPriv->mClockWrapper->flush(); } } MMAutoLock locker(mPriv->mLock); mPriv->clearSourceBuffers(); notify(kEventSeekComplete, MM_ERROR_SUCCESS, 0, nilParam); EXIT1(); } void AudioSinkPulse::onReset(param1_type param1, param2_type param2, uint32_t rspId) { ENTER1(); { mPriv->mIsPaused = true; if (mPriv->mOutputThread) { mPriv->mOutputThread->signalExit(); mPriv->mOutputThread.reset(); } } { PAMMAutoLock paLoop(mPriv->mPALoop); if (mPriv->mState == mPriv->STATE_STARTED) { mm_status_t ret = mPriv->streamFlush(); if (MM_ERROR_SUCCESS != ret) { ERROR("flush fail"); notify(kEventError, MM_ERROR_OP_FAILED, 0, nilParam); EXIT1(); } if (mPriv->mClockWrapper) { mPriv->mClockWrapper->flush(); } ret = mPriv->cork(1); if (MM_ERROR_SUCCESS != ret) { ERROR("cork fail"); notify(kEventError, MM_ERROR_OP_FAILED, 0, nilParam); EXIT1(); } } mPriv->clearPACallback(); } { MMAutoLock locker(mPriv->mLock); mPriv->mScaledPlayRate = SCALED_PLAY_RATE; mPriv->clearSourceBuffers(); } mPriv->release(); setState(mPriv->mState, mPriv->STATE_IDLE); notify(kEventResetComplete, MM_ERROR_SUCCESS, 0, nilParam); EXIT1(); } void AudioSinkPulse::onSetParameters(param1_type param1, param2_type param2, uint32_t rspId) { ENTER(); /* if (!strcmp((char *)param1, "setVolume")) { setVolume((double)param2); } else if (!strcmp((char *)param1, "setMute")) { setMute((bool)param2); } else if (!strcmp((char *)param1, "sampleRate")) { mSampleRate = (uint32_t)param2; } else if (!strcmp((char *)param1, "format")) { mFormat = (snd_format_t)param2; } else if (!strcmp((char *)param1, "channel")) { mChannelCount = (uint8_t)param2; } */ //notify(EVENT_SETPARAMETERSCOMPLETE, MM_ERROR_SUCCESS, 0, NULL); EXIT(); } void AudioSinkPulse::onGetParameters(param1_type param1, param2_type param2, uint32_t rspId) { ENTER(); //if (!strcmp((char *)param1, "getVolume")) { // notify(EVENT_GETPARAMETERSCOMPLETE, getVolume(), 0, NULL); //} else if (!strcmp((char *)param1, "getMute")) { // notify(EVENT_GETPARAMETERSCOMPLETE, getMute(), 0, NULL); //} EXIT(); } void AudioSinkPulse::onWrite(param1_type param1, param2_type param2, uint32_t rspId) { ENTER(); AudioSinkPulse::Private::QueueEntry *pEntry = (AudioSinkPulse::Private::QueueEntry *)param2; if (pEntry->mBuffer) { MMAutoLock locker(mPriv->mLock); mPriv->mAvailableSourceBuffers.push(pEntry->mBuffer); mPriv->mCondition.signal(); } else { WARNING("Write NULL buffer"); } delete pEntry; EXIT(); } bool AudioSinkPulse::Private::waitPAOperation(pa_operation *op) { if (!op) { return false; } pa_operation_state_t state = pa_operation_get_state(op); while (state == PA_OPERATION_RUNNING) { pa_threaded_mainloop_wait(mPALoop); state = pa_operation_get_state(op); } pa_operation_unref(op); return state == PA_OPERATION_DONE; } snd_format_t AudioSinkPulse::Private::convertFormatFromPulse(pa_sample_format paFormat) { ENTER(); for (int i = 0; format_map[i].spformat != SND_FORMAT_INVALID; ++i) { if (format_map[i].pa == paFormat) EXIT_AND_RETURN(format_map[i].spformat); } EXIT_AND_RETURN(SND_FORMAT_INVALID); } pa_sample_format AudioSinkPulse::Private::convertFormatToPulse(snd_format_t format) { ENTER(); for (int i = 0; format_map[i].spformat != SND_FORMAT_INVALID; ++i) { if (format_map[i].spformat == format) EXIT_AND_RETURN(format_map[i].pa); } EXIT_AND_RETURN(PA_SAMPLE_INVALID); } void AudioSinkPulse::Private::contextStateCallback(pa_context *c, void *userdata) { ENTER(); if (c == NULL) { ERROR("invalid param\n"); return; } AudioSinkPulse::Private * me = static_cast<AudioSinkPulse::Private*>(userdata); MMASSERT(me); switch (pa_context_get_state(c)) { case PA_CONTEXT_CONNECTING: case PA_CONTEXT_AUTHORIZING: case PA_CONTEXT_SETTING_NAME: break; case PA_CONTEXT_READY: case PA_CONTEXT_TERMINATED: case PA_CONTEXT_FAILED: pa_threaded_mainloop_signal (me->mPALoop, 0); break; default: break; } EXIT(); } void AudioSinkPulse::Private::contextSinkinputInfoCallback(pa_context *c, const pa_sink_input_info *i, int eol, void *userdata) { ENTER(); AudioSinkPulse::Private *me = static_cast<AudioSinkPulse::Private*>(userdata); MMASSERT(me); if (!i) goto done; if (!me->mPAStream) goto done; if (i->index == pa_stream_get_index (me->mPAStream)) { me->mVolume = pa_sw_volume_to_linear (pa_cvolume_max (&i->volume)); me->mMute = i->mute; } done: pa_threaded_mainloop_signal (me->mPALoop, 0); EXIT(); } void AudioSinkPulse::Private::contextSubscribeCallback(pa_context *c, pa_subscription_event_type_t type, uint32_t idx, void *userdata) { ENTER(); AudioSinkPulse::Private *me = static_cast<AudioSinkPulse::Private*>(userdata); MMASSERT(me); unsigned facility = type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK; pa_subscription_event_type_t t = pa_subscription_event_type_t(type & PA_SUBSCRIPTION_EVENT_TYPE_MASK); switch (facility) { case PA_SUBSCRIPTION_EVENT_SINK: break; case PA_SUBSCRIPTION_EVENT_SINK_INPUT: if (me->mPAStream && idx == pa_stream_get_index(me->mPAStream )) { switch (t) { case PA_SUBSCRIPTION_EVENT_REMOVE: INFO("PulseAudio sink killed"); break; default: pa_operation *op = pa_context_get_sink_input_info(c, idx, contextSinkinputInfoCallback, me); if (!op) { ERROR("failed to get pa sink input info"); } break; } } break; case PA_SUBSCRIPTION_EVENT_CARD: INFO("PA_SUBSCRIPTION_EVENT_CARD"); break; default: break; } EXIT(); } void AudioSinkPulse::Private::contextSinkInfoCallback(pa_context *c, const pa_sink_input_info *i, int is_last, void *userdata) { ENTER(); INFO("context sink info"); EXIT(); } void AudioSinkPulse::Private::streamStateCallback(pa_stream *s, void *userdata) { ENTER(); AudioSinkPulse::Private *me = static_cast<AudioSinkPulse::Private*>(userdata); MMASSERT(me); switch (pa_stream_get_state(s)) { case PA_STREAM_FAILED: INFO("pa stream failed"); pa_threaded_mainloop_signal(me->mPALoop, 0); break; case PA_STREAM_READY: INFO("pa stream ready"); pa_threaded_mainloop_signal(me->mPALoop, 0); break; case PA_STREAM_TERMINATED: INFO("pa stream terminated"); pa_threaded_mainloop_signal(me->mPALoop, 0); break; default: break; } EXIT(); } void AudioSinkPulse::Private::streamLatencyUpdateCallback(pa_stream *s, void *userdata) { ENTER(); #if 0 AudioSinkPulse *me = static_cast<AudioSinkPulse*>(userdata); MMASSERT(me); const pa_timing_info *info; pa_usec_t sink_usec; info = pa_stream_get_timing_info (s); if (!info) { return; } sink_usec = info->configured_sink_usec; VERBOSE("write_index_corrupt = %d write_index = %llu read_index_corrupt = %d read_index = %d info->sink_usec = %llu configured_sink_usec = %llu \n", info->write_index_corrupt, info->write_index, info->read_index_corrupt, info->read_index, info->sink_usec, sink_usec); #endif EXIT(); } void AudioSinkPulse::Private::streamUnderflowCallback(pa_stream *s, void *userdata) { ENTER(); INFO("under flow"); EXIT(); } void AudioSinkPulse::Private::streamOverflowCallback(pa_stream *s, void *userdata) { ENTER(); INFO("over flow"); EXIT(); } void AudioSinkPulse::Private::streamWriteCallback(pa_stream *s, size_t length, void *userdata) { ENTER(); AudioSinkPulse::Private *me = static_cast<AudioSinkPulse::Private*>(userdata); MMASSERT(me); if (!me->mIsPaused) { MMAutoLock locker(me->mLock); if (!me->mAvailableSourceBuffers.empty()) { me->mCondition.signal(); } VERBOSE("stream write length = %d",length); } EXIT(); } void AudioSinkPulse::Private::streamSuspendedCallback (pa_stream * s, void *userdata) { ENTER(); AudioSinkPulse::Private *me = static_cast<AudioSinkPulse::Private*>(userdata); MMASSERT(me); if (pa_stream_is_suspended (s)) INFO ("stream suspended"); else INFO ("stream resumed"); EXIT(); } void AudioSinkPulse::Private::streamStartedCallback (pa_stream * s, void *userdata) { ENTER(); INFO ("stream started"); EXIT(); } void AudioSinkPulse::Private::streamEventCallback (pa_stream * s, const char *name, pa_proplist * pl, void *userdata) { ENTER(); INFO ("stream event name = %s",name); EXIT(); } mm_status_t AudioSinkPulse::Private::creatPAContext() { ENTER(); int ret; pa_mainloop_api *api; /* Set up a new main loop */ MMLOGV("newing pa thread main loop\n"); mPALoop = pa_threaded_mainloop_new(); if (mPALoop == NULL){ PA_ERROR(MM_ERROR_NO_MEM, "failed to get pa api", pa_context_errno(mPAContext)); } api = pa_threaded_mainloop_get_api(mPALoop); pa_proplist *proplist = pa_proplist_new(); if ( !proplist ) { PA_ERROR(MM_ERROR_NO_MEM, "failed to new proplist", pa_context_errno(mPAContext)); } ret = pa_proplist_sets(proplist, "log-backtrace", "10"); if ( ret < 0 ) { pa_proplist_free(proplist); PA_ERROR(MM_ERROR_NO_MEM, "failed to set proplist", ret); } mPAContext = pa_context_new_with_proplist(api, COMPONENT_NAME, proplist); pa_proplist_free(proplist); if (mPAContext == NULL) { PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa api", pa_context_errno(mPAContext)); } pa_context_set_state_callback(mPAContext, contextStateCallback, this); /* Connect the context */ INFO("connecting pa context\n"); ret = pa_context_connect(mPAContext, "127.0.0.1", PA_CONTEXT_NOFLAGS, NULL); if ( ret < 0) { PA_ERROR(MM_ERROR_OP_FAILED, "failed to connect to context", ret); } INFO("starting pa mainloop\n"); ret = pa_threaded_mainloop_start(mPALoop); if(ret != 0){ PA_ERROR(MM_ERROR_OP_FAILED, "failed to start mainloop", ret); } mm_status_t result; INFO("waitting context ready\n"); PAMMAutoLock paLoop(mPALoop); while ( 1 ) { pa_context_state_t state = pa_context_get_state (mPAContext); INFO("now state: %d\n", state); if ( state == PA_CONTEXT_READY ) { INFO("ready\n"); result = MM_ERROR_SUCCESS; break; } else if ( state == PA_CONTEXT_TERMINATED || state == PA_CONTEXT_FAILED ) { INFO("terminated or failed\n"); result = MM_ERROR_OP_FAILED; break; } INFO("not expected state, wait\n"); pa_threaded_mainloop_wait (mPALoop); } EXIT_AND_RETURN(result); } mm_status_t AudioSinkPulse::Private::creatPAStream() { ENTER(); pa_format_info *format = pa_format_info_new(); format->encoding = PA_ENCODING_PCM; pa_sample_format paFormat = convertFormatToPulse((snd_format_t)mFormat); if (paFormat == PA_SAMPLE_INVALID) { ERROR("PulseAudio: invalid format"); EXIT_AND_RETURN(MM_ERROR_INVALID_PARAM); } pa_format_info_set_sample_format(format, paFormat); pa_format_info_set_channels(format, mChannelCount); pa_format_info_set_rate(format, mSampleRate); // pa_format_info_set_channel_map(fi, NULL); if (!pa_format_info_valid(format)) { ERROR("PulseAudio: invalid format"); pa_format_info_free(format); EXIT_AND_RETURN(MM_ERROR_OP_FAILED); } pa_sample_spec ss; ss.channels = mChannelCount; ss.format = convertFormatToPulse((snd_format_t)mFormat); ss.rate = mSampleRate; pa_proplist *pl = pa_proplist_new(); if (pl) { pa_proplist_sets(pl, "log-backtrace", "10"); } #ifdef ENABLE_DEFAULT_AUDIO_CONNECTION ENSURE_AUDIO_DEF_CONNECTION_ENSURE(mAudioConnectionId, MMAMHelper::playChnnelMain()); #endif MMLOGI("device: %s\n", mAudioConnectionId.c_str()); pa_proplist_sets(pl, "connection_id", mAudioConnectionId.c_str()); mPAStream = pa_stream_new_with_proplist(mPAContext, "audio stream", &ss, NULL, pl); //mPAStream = pa_stream_new_extended(mPAContext, "audio stream", &format, 1, pl); if (!mPAStream) { pa_format_info_free(format); pa_proplist_free(pl); ERROR("PulseAudio: failed to create a stream"); EXIT_AND_RETURN(MM_ERROR_OP_FAILED); } pa_format_info_free(format); pa_proplist_free(pl); /* install essential callbacks */ pa_stream_set_write_callback(mPAStream, streamWriteCallback, this); pa_stream_set_state_callback(mPAStream, streamStateCallback, this); pa_stream_set_underflow_callback (mPAStream, streamUnderflowCallback, this); pa_stream_set_overflow_callback (mPAStream, streamOverflowCallback, this); //pa_stream_set_latency_update_callback (mPAStream, streamLatencyUpdateCallback, this); pa_stream_set_suspended_callback (mPAStream, streamSuspendedCallback, this); pa_stream_set_started_callback (mPAStream, streamStartedCallback, this); pa_stream_set_event_callback (mPAStream, streamEventCallback, this); pa_sample_spec sample_spec = { .format = paFormat, .rate = (uint32_t)mSampleRate, .channels = (uint8_t)mChannelCount }; pa_buffer_attr wanted; wanted.maxlength = (uint32_t)-1; // max buffer size on the server wanted.tlength = (uint32_t) pa_usec_to_bytes(PA_USEC_PER_MSEC * 200/*DEFAULT_TLENGTH_MSEC*/, &sample_spec); //wanted.tlength = (uint32_t)-1; // ? wanted.prebuf = 1;//(uint32_t)-1; // play as soon as possible wanted.minreq = (uint32_t)-1; wanted.fragsize = (uint32_t)-1; // PA_STREAM_NOT_MONOTONIC? pa_stream_flags_t flags = pa_stream_flags_t(PA_STREAM_NOT_MONOTONIC|PA_STREAM_INTERPOLATE_TIMING|PA_STREAM_AUTO_TIMING_UPDATE); if (pa_stream_connect_playback(mPAStream, NULL, &wanted, flags, NULL, NULL) < 0) { ERROR("PulseAudio failed: pa_stream_connect_playback"); EXIT_AND_RETURN(MM_ERROR_OP_FAILED); } PAMMAutoLock paLoop(mPALoop); while (true) { const pa_stream_state_t st = pa_stream_get_state(mPAStream); if (st == PA_STREAM_READY) break; if (!PA_STREAM_IS_GOOD(st)) { ERROR("PulseAudio stream init failed"); EXIT_AND_RETURN(MM_ERROR_OP_FAILED); } pa_threaded_mainloop_wait(mPALoop); } if (pa_stream_is_suspended(mPAStream)) { ERROR("PulseAudio stream is suspende"); EXIT_AND_RETURN(MM_ERROR_OP_FAILED); } INFO("over\n"); EXIT_AND_RETURN(MM_ERROR_SUCCESS); } mm_status_t AudioSinkPulse::Private::freePAContext() { PAMMAutoLock paLoop(mPALoop); if (mPAContext) { pa_context_disconnect (mPAContext); pa_context_unref (mPAContext); mPAContext = NULL; } EXIT_AND_RETURN(MM_ERROR_SUCCESS); } mm_status_t AudioSinkPulse::Private::freePASteam() { ENTER(); PAMMAutoLock paLoop(mPALoop); if (mPAStream) { pa_stream_disconnect (mPAStream); pa_stream_unref(mPAStream); mPAStream = NULL; } #ifdef ENABLE_DEFAULT_AUDIO_CONNECTION ENSURE_AUDIO_DEF_CONNECTION_CLEAN(); #endif EXIT_AND_RETURN(MM_ERROR_SUCCESS); } mm_status_t AudioSinkPulse::Private::freePALoop() { ENTER(); if (mPALoop) { pa_threaded_mainloop_stop(mPALoop); pa_threaded_mainloop_free(mPALoop); mPALoop = NULL; } EXIT_AND_RETURN(MM_ERROR_SUCCESS); } mm_status_t AudioSinkPulse::Private::streamFlush() { ENTER(); mFlushResult = 0; if (!waitPAOperation(pa_stream_flush(mPAStream, streamFlushCallback, this))) { PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa sink input info", pa_context_errno(mPAContext)); } INFO("result: %d\n", mFlushResult); EXIT_AND_RETURN(mFlushResult > 0 ? MM_ERROR_SUCCESS : MM_ERROR_OP_FAILED); } void AudioSinkPulse::Private::streamFlushCallback(pa_stream*s, int success, void *userdata) { ENTER(); AudioSinkPulse::Private * me = static_cast<AudioSinkPulse::Private*>(userdata); MMASSERT(me); me->mFlushResult = success ? 1 : -1; pa_threaded_mainloop_signal (me->mPALoop, 0); EXIT(); } mm_status_t AudioSinkPulse::Private::cork(int b) { ENTER(); mCorkResult = 0; if (!waitPAOperation(pa_stream_cork(mPAStream, b, streamCorkCallback, this))) { PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa sink input info", pa_context_errno(mPAContext)); } INFO("result: %d\n", mCorkResult); EXIT_AND_RETURN(mCorkResult > 0 ? MM_ERROR_SUCCESS : MM_ERROR_OP_FAILED); } void AudioSinkPulse::Private::streamCorkCallback(pa_stream*s, int success, void *userdata) { ENTER(); AudioSinkPulse::Private * me = static_cast<AudioSinkPulse::Private*>(userdata); MMASSERT(me); me->mCorkResult = success ? 1 : -1; pa_threaded_mainloop_signal (me->mPALoop, 0); EXIT(); } mm_status_t AudioSinkPulse::Private::streamDrain() { ENTER(); mDrainResult = 0; mIsDraining = true; if (!waitPAOperation(pa_stream_drain(mPAStream, streamDrainCallback, this))) { ERROR("fail to drain stream"); } INFO("mDrainResult= %d",mDrainResult); mIsDraining = false; EXIT_AND_RETURN(mFlushResult > 0 ? MM_ERROR_SUCCESS : MM_ERROR_OP_FAILED); } void AudioSinkPulse::Private::streamDrainCallback(pa_stream*s, int success, void *userdata) { ENTER(); AudioSinkPulse::Private * me = static_cast<AudioSinkPulse::Private*>(userdata); MMASSERT(me); me->mDrainResult = success ? 1 : -1; pa_threaded_mainloop_signal (me->mPALoop, 0); EXIT(); } mm_status_t AudioSinkPulse::Private::release() { ENTER(); mm_status_t ret; ret = freePASteam(); ret = freePAContext(); ret = freePALoop(); EXIT_AND_RETURN(ret); } void AudioSinkPulse::Private::clearPACallback() { if (mPAContext) { /* Make sure we don't get any further callbacks */ pa_context_set_state_callback (mPAContext, NULL, NULL); pa_context_set_subscribe_callback (mPAContext, NULL, NULL); } if (mPAStream) { /* Make sure we don't get any further callbacks */ pa_stream_set_state_callback(mPAStream, NULL, NULL); pa_stream_set_write_callback(mPAStream, NULL, NULL); pa_stream_set_underflow_callback(mPAStream, NULL, NULL); pa_stream_set_overflow_callback(mPAStream, NULL, NULL); pa_stream_set_latency_update_callback (mPAStream, NULL, NULL); pa_stream_set_suspended_callback (mPAStream, NULL, NULL); pa_stream_set_started_callback (mPAStream, NULL, NULL); pa_stream_set_event_callback (mPAStream, NULL, NULL); } } void AudioSinkPulse::Private::clearSourceBuffers() { while(!mAvailableSourceBuffers.empty()) { mAvailableSourceBuffers.pop(); } } mm_status_t AudioSinkPulse::Private::setVolume(double volume) { ENTER(); if (mPALoop) EXIT_AND_RETURN(MM_ERROR_INVALID_PARAM); PAMMAutoLock paLoop(mPALoop); pa_cvolume vol; pa_operation *o = NULL; uint32_t idx; mVolume = volume; if ((idx = pa_stream_get_index (mPAStream)) == PA_INVALID_INDEX) goto no_index; pa_cvolume_reset(&vol, mChannelCount); pa_cvolume_set(&vol, mChannelCount, pa_volume_t(volume*double(PA_VOLUME_NORM))); if (!(o = pa_context_set_sink_input_volume (mPAContext, idx, &vol, NULL, NULL))) goto volume_failed; unlock: if (o) pa_operation_unref (o); EXIT_AND_RETURN(MM_ERROR_SUCCESS); /* ERRORS */ no_index: { INFO ("we don't have a stream index"); goto unlock; } volume_failed: { PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa sink input info", pa_context_errno(mPAContext)); goto unlock; } } double AudioSinkPulse::Private::getVolume() { ENTER(); double v = DEFAULT_VOLUME; pa_operation *o = NULL; uint32_t idx; if ((idx = pa_stream_get_index (mPAStream)) == PA_INVALID_INDEX) goto no_index; if (!waitPAOperation(pa_context_get_sink_input_info(mPAContext, idx, contextSinkinputInfoCallback, this))) { PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa sink input info", pa_context_errno(mPAContext)); goto volume_failed; } unlock: v = mVolume; if (o) pa_operation_unref (o); EXIT_AND_RETURN(v); /* ERRORS */ no_index: { INFO ("we don't have a stream index"); goto unlock; } volume_failed: { PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa sink input info", pa_context_errno(mPAContext)); goto unlock; } } mm_status_t AudioSinkPulse::Private::setMute(bool mute) { ENTER(); if (!mPALoop) EXIT_AND_RETURN(MM_ERROR_INVALID_PARAM); PAMMAutoLock paLoop(mPALoop); pa_operation *o = NULL; uint32_t idx; mMute = mute; if ((idx = pa_stream_get_index (mPAStream)) == PA_INVALID_INDEX) goto no_index; if (!(o = pa_context_set_sink_input_mute (mPAContext, idx, mute, NULL, NULL))) goto mute_failed; unlock: if (o) pa_operation_unref (o); EXIT_AND_RETURN(MM_ERROR_SUCCESS); /* ERRORS */ no_index: { INFO ("we don't have a stream index"); goto unlock; } mute_failed: { PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa sink input info", pa_context_errno(mPAContext)); goto unlock; } } bool AudioSinkPulse::Private::getMute() { ENTER(); pa_operation *o = NULL; uint32_t idx; bool mute = mMute; if ((idx = pa_stream_get_index (mPAStream)) == PA_INVALID_INDEX) goto no_index; if (!waitPAOperation(pa_context_get_sink_input_info(mPAContext, idx, contextSinkinputInfoCallback, this))) { PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa sink input info", pa_context_errno(mPAContext)); goto mute_failed; } unlock: mute = mMute; if (o) pa_operation_unref (o); EXIT_AND_RETURN(mute); /* ERRORS */ no_index: { INFO ("we don't have a stream index"); goto unlock; } mute_failed: { PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa sink input info", pa_context_errno(mPAContext)); goto unlock; } } mm_status_t AudioSinkPulse::setAudioConnectionId(const char * connectionId) { mPriv->mAudioConnectionId = connectionId; return MM_ERROR_SUCCESS; } const char * AudioSinkPulse::getAudioConnectionId() const { return mPriv->mAudioConnectionId.c_str(); } } ///////////////////////////////////////////////////////////////////////////////////// extern "C" { YUNOS_MM::Component* createComponent(const char* mimeType, bool isEncoder) { //INFO("createComponent"); YUNOS_MM::AudioSinkPulse *sinkComponent = new YUNOS_MM::AudioSinkPulse(mimeType, isEncoder); if (sinkComponent == NULL) { return NULL; } return static_cast<YUNOS_MM::Component*>(sinkComponent); } void releaseComponent(YUNOS_MM::Component *component) { //INFO("createComponent"); delete component; } }
30.227218
153
0.634364
halleyzhao
c4d6b54f3224dac53975338c6ce96e7c7edfd3de
6,653
cpp
C++
StandardTetrisMSVC2005/StandardTetrisMSVC2005/source/CPF.StandardTetris.STTime.cpp
TetrisAI/StandardTetris
b5cbe25541ceb45517472fe7feabea0c81fd55b0
[ "MIT" ]
7
2016-11-28T13:42:44.000Z
2021-08-05T02:34:11.000Z
StandardTetrisMSVC2005/StandardTetrisMSVC2005/source/CPF.StandardTetris.STTime.cpp
PowerOlive/StandardTetris
b5cbe25541ceb45517472fe7feabea0c81fd55b0
[ "MIT" ]
null
null
null
StandardTetrisMSVC2005/StandardTetrisMSVC2005/source/CPF.StandardTetris.STTime.cpp
PowerOlive/StandardTetris
b5cbe25541ceb45517472fe7feabea0c81fd55b0
[ "MIT" ]
8
2015-07-31T02:53:14.000Z
2020-04-12T04:36:23.000Z
// All contents of this file written by Colin Fahey ( http://colinfahey.com ) // 2007 June 4 ; Visit web site to check for any updates to this file. #include "CPF.StandardTetris.STTime.h" #include <windows.h> #include <time.h> #include <winnt.h> namespace CPF { namespace StandardTetris { // Performance Counter Variables int STTime::m_iCounterExists = 0; LARGE_INTEGER STTime::m_LICounterFrequency = {0,0}; LARGE_INTEGER STTime::m_LICounterReferenceValue = {0,0}; // time(NULL) Variable int STTime::m_iSecondsSince1970ReferenceValue = 0; // Interval Duration LARGE_INTEGER STTime::m_LICounterIntervalReferenceValue = {0,0}; double STTime::m_double_IntervalSeconds = (0.0); float STTime::m_float_IntervalSeconds = (0.0f); // The following sets the reference time to the time of the call. // All future calls to GetTimeSecondsXXXXX() will be relative to // this reference time. void STTime::SetReferenceTimeToNow() { // Clear values STTime::m_iCounterExists = 0; STTime::m_LICounterFrequency.QuadPart = 0; STTime::m_LICounterReferenceValue.QuadPart = 0; STTime::m_iSecondsSince1970ReferenceValue = 0; STTime::m_LICounterIntervalReferenceValue.QuadPart = 0; STTime::m_double_IntervalSeconds = (0.0); STTime::m_float_IntervalSeconds = (0.0f); // Determine if we have a performance counter. // We do this by requesting the frequency. STTime::m_iCounterExists = (int) QueryPerformanceFrequency( (&(STTime::m_LICounterFrequency)) ); // If we have a performance counter, get the current // value for our starting value. This will be our // initial "current" value, too. if (STTime::m_iCounterExists) { QueryPerformanceCounter( (&(STTime::m_LICounterReferenceValue)) ); } // Set the time(NULL) reference value, too. STTime::m_iSecondsSince1970ReferenceValue = (int)(time(NULL)); // Set the Interval Duration Reference Time STTime::m_LICounterIntervalReferenceValue.QuadPart = (STTime::m_LICounterReferenceValue.QuadPart); STTime::m_double_IntervalSeconds = (0.0); STTime::m_float_IntervalSeconds = (0.0f); } double STTime::GetRelativeTimeSecondsDouble( ) { // If we don't have a performance counter, we can't honor this request. if (0 == (STTime::m_iCounterExists)) { // We don't have a performance counter. return( 0.0 ); } LARGE_INTEGER LICounterDeltaValue; QueryPerformanceCounter( (&(LICounterDeltaValue)) ); LICounterDeltaValue.QuadPart -= ((STTime::m_LICounterReferenceValue).QuadPart); double dSeconds = 0.0f; if ((STTime::m_LICounterFrequency.QuadPart) > 0) { dSeconds = (double)(LICounterDeltaValue.QuadPart) / (double)((STTime::m_LICounterFrequency.QuadPart)); } return( dSeconds ); } float STTime::GetRelativeTimeSecondsFloat( ) { return( ((float)(GetRelativeTimeSecondsDouble())) ); } int STTime::GetRelativeTimeSecondsInteger( ) { return( ((int)(GetRelativeTimeSecondsDouble())) ); } int STTime::GetTimeWallClockSecondsSince1970( ) { int iSecondsSince1970 = 0; iSecondsSince1970 = (int)time( NULL ); return ( iSecondsSince1970 ); } int STTime::GetWallClockReferenceValueSeconds( ) { return ( (STTime::m_iSecondsSince1970ReferenceValue) ); } int STTime::GetRelativeTimeWallClockSeconds( ) { int iSecondsSince1970 = 0; iSecondsSince1970 = (int)time( NULL ); return ( iSecondsSince1970 - (STTime::m_iSecondsSince1970ReferenceValue) ); } double STTime::GetIntervalDurationSecondsDouble( ) { // Return cached interval duration in seconds, as a 'double'. // ( 60fps --> 0.0166 sec/frame; 85fps --> 0.0117 sec/frame ) return( STTime::m_double_IntervalSeconds ); } float STTime::GetIntervalDurationSecondsFloat( ) { // Return cached interval duration in seconds, as a 'float'. // ( 60fps --> 0.0166 sec/frame; 85fps --> 0.0117 sec/frame ) return( STTime::m_float_IntervalSeconds ); } void STTime::NextIntervalBeginsNow( ) { // If we don't have a performance counter, we can't honor this request. if (0 == (STTime::m_iCounterExists)) { // We don't have a performance counter. return; } // Conter Value for "Now" LARGE_INTEGER LICounterValue; QueryPerformanceCounter( (&(LICounterValue)) ); // Difference between previous counter value and "Now" LARGE_INTEGER LICounterDeltaValue; LICounterDeltaValue.QuadPart = LICounterValue.QuadPart; LICounterDeltaValue.QuadPart -= ((STTime::m_LICounterIntervalReferenceValue).QuadPart); // Compute difference in seconds (double precision). double dSeconds = 0.0f; if ((STTime::m_LICounterFrequency.QuadPart) > 0) { dSeconds = (double)(LICounterDeltaValue.QuadPart) / (double)((STTime::m_LICounterFrequency.QuadPart)); } // Cast duration time to float (single precision). float fSeconds = ((float)(dSeconds)); // Cache both representations of interval duration value. STTime::m_double_IntervalSeconds = (dSeconds); STTime::m_float_IntervalSeconds = (fSeconds); // Set the interval reference value to "now". STTime::m_LICounterIntervalReferenceValue.QuadPart = LICounterValue.QuadPart; } int STTime::PerformanceCounterExists( ) { return( (STTime::m_iCounterExists) ); } void STTime::GetCounterFrequencyHighLow ( unsigned int &refHigh32, unsigned int &refLow32 ) { refHigh32 = ((STTime::m_LICounterFrequency).HighPart); refLow32 = ((STTime::m_LICounterFrequency).LowPart); } void STTime::GetCounterReferenceHighLow ( unsigned int &refHigh32, unsigned int &refLow32 ) { refHigh32 = ((STTime::m_LICounterReferenceValue).HighPart); refLow32 = ((STTime::m_LICounterReferenceValue).LowPart); } void STTime::GetCounterCurrentHighLow ( unsigned int &refHigh32, unsigned int &refLow32 ) { refHigh32 = 0; refLow32 = 0; if (0 == (STTime::m_iCounterExists)) return; LARGE_INTEGER LICounterCurrent; QueryPerformanceCounter( (&(LICounterCurrent)) ); refHigh32 = (LICounterCurrent.HighPart); refLow32 = (LICounterCurrent.LowPart); } } }
22.706485
78
0.654291
TetrisAI
c4e349124c61bfeaf017fc7be7d766f4305914b5
7,495
cpp
C++
tests/reflection_tests.cpp
Revolution-Populi/fc
02b7593a96b02d9966358c59d22f344d86fa9a19
[ "BSL-1.0", "Apache-2.0", "Zlib" ]
37
2017-02-04T09:42:48.000Z
2021-02-17T14:59:15.000Z
tests/reflection_tests.cpp
Revolution-Populi/fc
02b7593a96b02d9966358c59d22f344d86fa9a19
[ "BSL-1.0", "Apache-2.0", "Zlib" ]
120
2017-11-09T19:46:40.000Z
2022-01-20T18:26:23.000Z
tests/reflection_tests.cpp
Revolution-Populi/fc
02b7593a96b02d9966358c59d22f344d86fa9a19
[ "BSL-1.0", "Apache-2.0", "Zlib" ]
109
2017-01-16T14:24:31.000Z
2022-03-18T21:10:07.000Z
#include <boost/test/unit_test.hpp> #include <fc/exception/exception.hpp> #include <type_traits> struct reflect_test_base { int x = 1; char y = 'a'; }; struct reflect_test_derived : reflect_test_base { double z = 3.14; }; struct reflect_layer_1 { reflect_test_base b; int32_t n; }; struct reflect_layer_2 { reflect_layer_1 l1; reflect_test_derived d; }; struct reflect_layer_3 { reflect_layer_2 l2; int32_t i; }; FC_REFLECT( reflect_test_base, (x)(y) ); FC_REFLECT_DERIVED( reflect_test_derived, (reflect_test_base), (z) ); FC_REFLECT( reflect_layer_1, (b)(n) ); FC_REFLECT( reflect_layer_2, (l1)(d) ); FC_REFLECT( reflect_layer_3, (l2)(i) ); BOOST_AUTO_TEST_SUITE( fc_reflection ) BOOST_AUTO_TEST_CASE( reflection_static_tests ) { // These are all compile-time tests, nothing actually happens here at runtime using base_reflection = fc::reflector<reflect_test_base>; using derived_reflection = fc::reflector<reflect_test_derived>; static_assert(fc::typelist::length<base_reflection::members>() == 2, ""); static_assert(fc::typelist::length<derived_reflection::members>() == 3, ""); static_assert(fc::typelist::at<derived_reflection::members, 0>::is_derived, ""); static_assert(std::is_same<fc::typelist::at<derived_reflection::members, 0>::field_container, reflect_test_base>::value, ""); static_assert(fc::typelist::at<derived_reflection::members, 1>::is_derived, ""); static_assert(std::is_same<fc::typelist::at<derived_reflection::members, 1>::field_container, reflect_test_base>::value, ""); static_assert(fc::typelist::at<derived_reflection::members, 2>::is_derived == false, ""); static_assert(std::is_same<fc::typelist::slice<fc::typelist::list<int, bool, char>, 0, 1>, fc::typelist::list<int>>::value, ""); static_assert(std::is_same<fc::typelist::slice<fc::typelist::list<int, bool, char>, 0, 2>, fc::typelist::list<int, bool>>::value, ""); static_assert(std::is_same<fc::typelist::slice<fc::typelist::list<int, bool, char>, 0, 3>, fc::typelist::list<int, bool, char>>::value, ""); static_assert(std::is_same<fc::typelist::slice<fc::typelist::list<int, bool, char>, 1, 3>, fc::typelist::list<bool, char>>::value, ""); static_assert(std::is_same<fc::typelist::slice<fc::typelist::list<int, bool, char>, 2, 3>, fc::typelist::list<char>>::value, ""); static_assert(std::is_same<fc::typelist::slice<fc::typelist::list<int, bool, char>, 1, 2>, fc::typelist::list<bool>>::value, ""); static_assert(std::is_same<fc::typelist::slice<fc::typelist::list<int, bool, char>, 1>, fc::typelist::list<bool, char>>::value, ""); static_assert(std::is_same<fc::typelist::make_sequence<0>, fc::typelist::list<>>::value, ""); static_assert(std::is_same<fc::typelist::make_sequence<1>, fc::typelist::list<std::integral_constant<size_t, 0>>>::value, ""); static_assert(std::is_same<fc::typelist::make_sequence<2>, fc::typelist::list<std::integral_constant<size_t, 0>, std::integral_constant<size_t, 1>>>::value, ""); static_assert(std::is_same<fc::typelist::make_sequence<3>, fc::typelist::list<std::integral_constant<size_t, 0>, std::integral_constant<size_t, 1>, std::integral_constant<size_t, 2>>>::value, ""); static_assert(std::is_same<fc::typelist::zip<fc::typelist::list<>, fc::typelist::list<>>, fc::typelist::list<>>::value, ""); static_assert(std::is_same<fc::typelist::zip<fc::typelist::list<bool>, fc::typelist::list<char>>, fc::typelist::list<fc::typelist::list<bool, char>>>::value, ""); static_assert(std::is_same<fc::typelist::zip<fc::typelist::list<int, bool>, fc::typelist::list<char, double>>, fc::typelist::list<fc::typelist::list<int, char>, fc::typelist::list<bool, double>>>::value, ""); static_assert(std::is_same<fc::typelist::index<fc::typelist::list<>>, fc::typelist::list<>>::value, ""); static_assert(std::is_same<fc::typelist::index<fc::typelist::list<int, bool, char, double>>, fc::typelist::list<fc::typelist::list<std::integral_constant<size_t, 0>, int>, fc::typelist::list<std::integral_constant<size_t, 1>, bool>, fc::typelist::list<std::integral_constant<size_t, 2>, char>, fc::typelist::list<std::integral_constant<size_t, 3>, double>> >::value, ""); } BOOST_AUTO_TEST_CASE( typelist_dispatch_test ) { using list = fc::typelist::list<float, bool, char>; auto get_name = [](auto t) -> std::string { return fc::get_typename<typename decltype(t)::type>::name(); }; BOOST_CHECK_EQUAL(fc::typelist::runtime::dispatch(list(), 0ul, get_name), "float"); BOOST_CHECK_EQUAL(fc::typelist::runtime::dispatch(list(), 1ul, get_name), "bool"); BOOST_CHECK_EQUAL(fc::typelist::runtime::dispatch(list(), 2ul, get_name), "char"); } // Helper template to use fc::typelist::at without a comma, for macro friendliness template<typename T> struct index_from { template<std::size_t idx> using at = fc::typelist::at<T, idx>; }; BOOST_AUTO_TEST_CASE( reflection_get_test ) { try { reflect_test_derived derived; reflect_test_base& base = derived; using base_reflector = fc::reflector<reflect_test_base>; using derived_reflector = fc::reflector<reflect_test_derived>; BOOST_CHECK(index_from<base_reflector::members>::at<0>::get(base) == 1); BOOST_CHECK(index_from<base_reflector::members>::at<1>::get(base) == 'a'); fc::typelist::at<base_reflector::members, 0>::get(base) = 5; fc::typelist::at<base_reflector::members, 1>::get(base) = 'q'; BOOST_CHECK(index_from<base_reflector::members>::at<0>::get(base) == 5); BOOST_CHECK(index_from<base_reflector::members>::at<1>::get(base) == 'q'); BOOST_CHECK(index_from<derived_reflector::members>::at<0>::get(derived) == 5); BOOST_CHECK(index_from<derived_reflector::members>::at<1>::get(derived) == 'q'); BOOST_CHECK(index_from<derived_reflector::members>::at<2>::get(derived) == 3.14); fc::typelist::at<derived_reflector::members, 1>::get(derived) = 'X'; BOOST_CHECK(index_from<base_reflector::members>::at<1>::get(base) == 'X'); reflect_layer_3 l3; BOOST_CHECK(index_from<index_from<index_from<index_from<fc::reflector<reflect_layer_3>::members>::at<0> ::reflector::members>::at<0>::reflector::members>::at<0>::reflector::members>::at<1>::get(l3.l2.l1.b) == 'a'); BOOST_CHECK(index_from<index_from<index_from<fc::reflector<reflect_layer_3>::members>::at<0>::reflector::members> ::at<1>::reflector::members>::at<1>::get(l3.l2.d) == 'a'); BOOST_CHECK(index_from<index_from<index_from<fc::reflector<reflect_layer_3>::members>::at<0>::reflector::members> ::at<1>::reflector::members>::at<2>::get(l3.l2.d) == 3.14); } FC_CAPTURE_LOG_AND_RETHROW( (0) ) } BOOST_AUTO_TEST_SUITE_END()
59.015748
116
0.623616
Revolution-Populi
c4e5f434f6c43ca834c0c4c6709c294eed762910
15,230
cpp
C++
SRC/text/text_render.cpp
GlisGames/vbEngine
239659e154c08d1867418e611891a7961dbe8258
[ "MIT" ]
null
null
null
SRC/text/text_render.cpp
GlisGames/vbEngine
239659e154c08d1867418e611891a7961dbe8258
[ "MIT" ]
null
null
null
SRC/text/text_render.cpp
GlisGames/vbEngine
239659e154c08d1867418e611891a7961dbe8258
[ "MIT" ]
null
null
null
#include "text_render.h" //#include "scope_guard.h" #include "math.h" #include "rlgl.h" #include <assert.h> #include <ft2build.h> #include FT_FREETYPE_H #include FT_OUTLINE_H //#define TEXT_USE_SHADER #include <algorithm> #include <cstdlib> #include <cstdio> #if defined(PLATFORM_DESKTOP) #define GLSL_VERSION 330 #else // PLATFORM_RPI, PLATFORM_ANDROID, PLATFORM_WEB #define GLSL_VERSION 100 #endif //------------------------------------------------------------------------------ static const char* vertex_shader_string = R"( #version 100 attribute vec3 vertexPosition; attribute vec2 vertexTexCoord; attribute vec3 vertexNormal; attribute vec4 vertexColor; uniform mat4 mvp; varying vec2 fragTexCoord; varying vec4 fragColor; void main() { fragTexCoord = vertexTexCoord; fragColor = vertexColor; gl_Position = mvp*vec4(vertexPosition, 1.0); } )"; static const char* sdf_shader = R"( #version 100 precision mediump float; // Input vertex attributes (from vertex shader) varying vec2 fragTexCoord; varying vec4 fragColor; // Input uniform values uniform sampler2D texture0; uniform vec4 colDiffuse; // NOTE: Add here your custom variables const float smoothing = 1.0/16.0; void main() { // Texel color fetching from texture sampler // NOTE: Calculate alpha using signed distance field (SDF) float distance = texture2D(texture0, fragTexCoord).a; float alpha = smoothstep(0.5 - smoothing, 0.5 + smoothing, distance); // Calculate final fragment color //gl_FragColor = vec4(fragColor.rgb, fragColor.a*alpha); gl_FragColor = vec4(fragColor.rgb, texture2D(texture0, fragTexCoord).r*alpha); } )"; static const char* sdf_shader33 = R"( #version 330 // Input vertex attributes (from vertex shader) in vec2 fragTexCoord; in vec4 fragColor; // Input uniform values uniform sampler2D texture0; uniform vec4 colDiffuse; // Output fragment color out vec4 finalColor; // NOTE: Add here your custom variables void main() { // Texel color fetching from texture sampler // NOTE: Calculate alpha using signed distance field (SDF) float distanceFromOutline = texture(texture0, fragTexCoord).a - 0.5; float distanceChangePerFragment = length(vec2(dFdx(distanceFromOutline), dFdy(distanceFromOutline))); float alpha = smoothstep(-distanceChangePerFragment, distanceChangePerFragment, distanceFromOutline); // Calculate final fragment color //finalColor = vec4(fragColor.rgb, fragColor.a*alpha); finalColor = vec4(fragColor.rgb, texture2D(texture0, fragTexCoord).r*alpha); } )"; static const char* fragment_shader_string = R"( #version 100 precision mediump float; // Input vertex attributes (from vertex shader) varying vec2 fragTexCoord; varying vec4 fragColor; // Input uniform values uniform sampler2D texture0; uniform vec4 textColor; void main() { vec4 texelColor = vec4(1.0, 1.0, 1.0, texture2D(texture0, fragTexCoord).r); gl_FragColor = texelColor*textColor; } )"; const int TextureAtlasWidth = 1024; const int TextureAtlasHeight = 1024; //------------------------------------------------------------------------------ TextRender::TextRender() : texReq_(0), texHit_(0), texEvict_(0), line_(Glyph{}), lastTexID_(0) { } TextRender::~TextRender() { } bool TextRender::Init(int numTextureAtlas) { assert(numTextureAtlas > 0 && numTextureAtlas <= 16); std::string errorLog; #if !defined(PLATFORM_WEB) && !defined(PLATFORM_RPI) mys = LoadShader("vertex_shader.txt", "fragment_shader.txt");//FromMemory(vertex_shader_string, fragment_shader_string); //sdfShader = LoadShader("vertex_shader.txt", "fragment_shader.txt");//FromMemory(vertex_shader_string, fragment_shader_string); #else mys = LoadShaderFromMemory(vertex_shader_string, fragment_shader_string); #endif mysLocation = GetShaderLocation(mys, "textColor"); //for (int i = 0; i < numTextureAtlas; i++) //{ // std::unique_ptr<TextureAtlas> t(new TextureAtlas); // if (!t->Init(TextureAtlasWidth, TextureAtlasHeight)) // { // return false; // } // tex_.push_back(std::move(t)); // texGen_.push_back(0); //} line_.TexIdx = -1; return true; } void TextRender::DrawTextureFonthere(Texture2D texture, Rectangle source, Rectangle dest, Vector2 origin, float rotation, Color tint) { // Check if texture is valid if (texture.id > 0) { float width = (float)texture.width; float height = (float)texture.height; bool flipX = false; if (source.width < 0) { flipX = true; source.width *= -1; } if (source.height < 0) source.y -= source.height; Vector2 topLeft = { 0 }; Vector2 topRight = { 0 }; Vector2 bottomLeft = { 0 }; Vector2 bottomRight = { 0 }; // Only calculate rotation if needed if (rotation == 0.0f) { float x = dest.x - origin.x; float y = dest.y - origin.y; topLeft = { x, y }; topRight = { x + dest.width, y }; bottomLeft = { x, y + dest.height }; bottomRight = { x + dest.width, y + dest.height }; } else { float sinRotation = sinf(rotation * DEG2RAD); float cosRotation = cosf(rotation * DEG2RAD); float x = dest.x; float y = dest.y; float dx = -origin.x; float dy = -origin.y; topLeft.x = x + dx * cosRotation - dy * sinRotation; topLeft.y = y + dx * sinRotation + dy * cosRotation; topRight.x = x + (dx + dest.width) * cosRotation - dy * sinRotation; topRight.y = y + (dx + dest.width) * sinRotation + dy * cosRotation; bottomLeft.x = x + dx * cosRotation - (dy + dest.height) * sinRotation; bottomLeft.y = y + dx * sinRotation + (dy + dest.height) * cosRotation; bottomRight.x = x + (dx + dest.width) * cosRotation - (dy + dest.height) * sinRotation; bottomRight.y = y + (dx + dest.width) * sinRotation + (dy + dest.height) * cosRotation; } rlCheckRenderBatchLimit(4); // Make sure there is enough free space on the batch buffer rlBegin(RL_QUADS); rlSetTexture(texture.id); rlColor4ub(tint.r, tint.g, tint.b, tint.a); rlNormal3f(0.0f, 0.0f, 1.0f); // Normal vector pointing towards viewer // Top-left corner for texture and quad rlTexCoord2f(source.x, source.y); rlVertex2f(topLeft.x, topLeft.y); // Bottom-left corner for texture and quad rlTexCoord2f(source.x, (source.y + source.height)); rlVertex2f(bottomLeft.x, bottomLeft.y); // Bottom-right corner for texture and quad rlTexCoord2f((source.x + source.width), (source.y + source.height)); rlVertex2f(bottomRight.x, bottomRight.y); // Top-right corner for texture and quad rlTexCoord2f((source.x + source.width), source.y); rlVertex2f(topRight.x, topRight.y); rlEnd(); rlSetTexture(0); } } #define MEMCMP(a, b) memcmp((a), (b), (sizeof(a) < sizeof(b)) ? sizeof(a) : sizeof(b)) void TextRender::DrawTextBoundingAlfons(vbTextbox* text, float initialx, float initialy, Color color, float zoom, float rotation) { #ifdef TEXT_USE_SHADER BeginShaderMode(mys); if (MEMCMP(&color, &currentColor_) != 0) { currentColor_ = color; float tocolor[4] = { (float)color.r / 255.0f, (float)color.g / 255.0f, (float)color.b / 255.0f, (float)color.a / 255.0f, }; SetShaderValue(mys, this->mysLocation, tocolor, SHADER_UNIFORM_VEC4); } #endif text->draw(initialx, initialy); #ifdef TEXT_USE_SHADER EndShaderMode(); #endif if (text->debugBox) //debug bounding box DrawRectangleLinesEx({ initialx, initialy, text->getBoundingBox().x ,text->getBoundingBox().y }, 1, RED); //DrawLine(initialx, initialy, 1000, initialy, VIOLET); //Debug baseline } /* void TextRender::CacheText(vbTextbox* text) { // Iterate over each glyph. size_t glyph_count = text->GetGlyphCount(); float x = 0; float y = 0; float zoom = 1; float maxs = text->getMaxHeight(); Vector2 box = text->getPrintSize(); UnloadTexture(text->cachetxt); //------------------------------------- RenderTexture2D target = LoadRenderTexture(box.x, box.y); BeginTextureModePro(target); this->DrawText(text, 0, 0, text->colour, text->zoom, text->rotation); //text->cachetxt = target.texture; Image toflip = GetTextureData(target.texture); ImageFlipVertical(&toflip); text->cachetxt = LoadTextureFromImage(toflip); //void *data = rlReadScreenPixels(target.) EndTextureMode(); UnloadRenderTexture(target); //rlUnloadFramebuffer(target.id); return; /* //Image im = GenImageColor(box.x, box.y, CLITERAL(Color){ 255, 0, 0, 255 }); //im.format = PIXELFORMAT_UNCOMPRESSED_GRAYSCALE; text->cachetxt = LoadTextureFromImage(GenImageColor(box.x, box.y, BLANK)); //UpdateTexture for (size_t i = 0; i < glyph_count; i++) { GlyphInfo info; text->GetGlyph(i, info); Glyph g; if (!getGlyph(text->GetFont(), info.glyphid, g)) { // TODO: error log break; } if (g.Size.x > 0 && g.Size.y > 0) { TextureAtlas* t = tex_[g.TexIdx].get(); float glyph_x = (x + g.Bearing.x * zoom + info.x_offset * zoom); float glyph_y = y - (g.descent * zoom + g.Bearing.y * zoom) - info.y_offset * zoom; //OK NO FLIP glyph_y += (g.ff->bbox.yMax / 64.0f) * zoom; glyph_y += maxs; float glyph_w = (float)g.Size.x; float glyph_h = (float)g.Size.y; float tex_x = g.TexOffset.x; float tex_y = g.TexOffset.y; float tex_w = glyph_w * zoom; float tex_h = glyph_h * zoom; Rectangle source = { tex_x, tex_y, tex_w, tex_h }; Rectangle dest = { glyph_x, glyph_y, glyph_w * zoom, glyph_h * zoom }; UpdateTextureRec(text->cachetxt, dest, rlReadTexturePixelsRect(t->texture_, source)); //text->cachetxt.format = PIXELFORMAT_UNCOMPRESSED_GRAYSCALE; //UpdateTextureRec(text->cachetxt, dest, g.ff->glyph->bitmap.buffer); } // advance cursors for next glyph x += info.x_advance * zoom; y += info.y_advance * zoom; } } */ void TextRender::PrintStats() { fprintf(stdout, "\n"); fprintf(stdout, "----glyph texture cache stats----\n"); fprintf(stdout, "texture atlas size: %d %d\n", TextureAtlasWidth, TextureAtlasHeight); fprintf(stdout, "texture atlas count: %d\n", (int)tex_.size()); fprintf(stdout, "texture atlas occupancy:"); for (size_t i = 0; i < tex_.size(); i++) { //float rate = tex_[i]->get()->Occupancy() * 100.f; //HACK float rate = tex_[i]->Occupancy() * 100.f; fprintf(stdout, " %.1f%%", rate); } fprintf(stdout, "\n"); fprintf(stdout, "texture atlas evict: %llu\n", texEvict_); fprintf(stdout, "request: %llu\n", texReq_); fprintf(stdout, "hit : %llu (%.2f%%)\n", texHit_, (double)texHit_ / texReq_ * 100); fprintf(stdout, "\n"); } bool TextRender::getGlyph(vbFont *font, unsigned int glyph_index, Glyph& x) { GlyphKey key = GlyphKey{ font->getID(), glyph_index }; GlyphCache::iterator iter = glyphs_.find(key); if (iter != glyphs_.end()) { x = iter->second; if (x.TexIdx < 0) { return true; } else if (x.TexGen == texGen_[x.TexIdx]) // check texture atlas generation { texReq_++; texHit_++; return true; } } // load glyph FT_Face face = font->getFTFont(); if (FT_Load_Glyph(face, glyph_index, FT_LOAD_DEFAULT)) //FT_LOAD_DEFAULT { return false; } if (font->synthesisItalic()) { // horizontal shear FT_Matrix matrix; matrix.xx = 0x10000L; matrix.xy = (FT_Fixed)(0.3 * 0x10000L); matrix.yx = 0; matrix.yy = 0x10000L; FT_Outline_Transform(&face->glyph->outline, &matrix); } if (font->synthesisBold()) { FT_Outline_Embolden(&face->glyph->outline, (FT_Pos)(font->getSize() * 0.04 * 64)); } if (FT_Render_Glyph(face->glyph, FT_RENDER_MODE_NORMAL)) { return false; } int texIdx = -1; unsigned int texGen = 0; uint16_t texOffsetX = 0, texOffsetY = 0; if (face->glyph->bitmap.width > 0 && face->glyph->bitmap.rows > 0) { if (!addToTextureAtlas(face->glyph->bitmap.width, face->glyph->bitmap.rows, face->glyph->bitmap.buffer, texIdx, texGen, texOffsetX, texOffsetY)) { return false; } texReq_++; } // now store Glyph for later use x = Glyph{ {(float)face->glyph->bitmap.width,(float)face->glyph->bitmap.rows}, {(float)face->glyph->bitmap_left, (float)face->glyph->bitmap_top}, {(float)texOffsetX, (float)texOffsetY}, texIdx, texGen, (float)face->ascender/64.0f, (float)face->bbox.yMax/ 64.0f, (float)face->size->metrics.height / 64.0f, face }; glyphs_[key] = x; return true; } bool TextRender::setupLineGlyph() { if (line_.TexIdx >= 0 && line_.TexGen == texGen_[line_.TexIdx]) { return true; } static uint8_t data[4*4] = { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, }; uint16_t tex_x, tex_y; if (addToTextureAtlas(4, 4, data, line_.TexIdx, line_.TexGen, tex_x, tex_y)) { line_.Size.x = 4; line_.Size.y = 4; line_.TexOffset.x = tex_x; line_.TexOffset.y = tex_y; return true; } return false; } bool TextRender::addToTextureAtlas(uint16_t width, uint16_t height, const uint8_t *data, int &tex_idx, unsigned int &tex_gen, uint16_t &tex_x, uint16_t &tex_y) { for (size_t i = 0; i < tex_.size(); i++) { //TextureAtlas *t = tex_[i].get(); //HACK TextureAtlas *t = tex_[i]; if (t->AddRegion(width, height, data, tex_x, tex_y)) { tex_idx = (unsigned int)i; tex_gen = texGen_[i]; return true; } } // evict a random choosed one size_t index = (size_t)rand() % tex_.size(); //TextureAtlas *tex = tex_[index].get();// TextureAtlas *tex = tex_[index]; // clear contents tex->Clear(); // increment generation texGen_[index]++; texEvict_++; // retry if (tex->AddRegion(width, height, data, tex_x, tex_y)) { tex_idx = index; tex_gen = texGen_[index]; return true; } return false; } void TextRender::setTexID(unsigned int texID) { } void TextRender::commitDraw() { }
29.746094
133
0.599146
GlisGames
c4e789272073d984d72598c4e43028f912886c60
2,198
hpp
C++
include/gaenari/supul/db/sqlite/sqlite.type.hpp
greenfish77/gaenari
cb9374498b6122800702ebcfc19543c9563345b4
[ "Apache-2.0" ]
2
2022-03-10T05:51:24.000Z
2022-03-15T10:32:26.000Z
include/gaenari/supul/db/sqlite/sqlite.type.hpp
greenfish77/gaenari
cb9374498b6122800702ebcfc19543c9563345b4
[ "Apache-2.0" ]
null
null
null
include/gaenari/supul/db/sqlite/sqlite.type.hpp
greenfish77/gaenari
cb9374498b6122800702ebcfc19543c9563345b4
[ "Apache-2.0" ]
null
null
null
#ifndef HEADER_GAENARI_SUPUL_DB_SQLITE_SQLITE_TYPE_HPP #define HEADER_GAENARI_SUPUL_DB_SQLITE_SQLITE_TYPE_HPP namespace supul { namespace db { namespace sqlite { // include sqlite3.h inside the namespace. #include "sqlite/sqlite3.h" // query type. enum class stmt { unknown, count_string_table, get_string_table_last_id, get_string_table, add_string_table, add_chunk, add_instance, add_instance_info, get_not_updated_instance, get_chunk, get_is_generation_empty, add_generation, update_generation, update_generation_etc, get_treenode_last_id, add_rule, add_leaf_node, add_treenode, get_instance_by_chunk_id, get_first_root_ref_treenode_id, get_treenode, update_instance_info, update_chunk, update_chunk_total_count, get_chunk_list, get_chunk_updated, update_leaf_info, get_weak_treenode, update_leaf_info_by_go_to_generation_id, get_instance_by_go_to_generation_id, get_correct_instance_count_by_go_to_generation_id, update_instance_info_with_weak_count_increment, get_root_ref_treenode_id, copy_rule, update_rule_value_integer, get_generation_id_by_treenode_id, get_leaf_info_by_chunk_id, get_total_count_by_chunk_id, delete_instance_by_chunk_id, delete_instance_info_by_chunk_id, delete_chunk_by_id, get_global_row_count, add_global_one_row, get_global, get_instance_count, get_instance_correct_count, get_updated_instance_count, get_sum_leaf_info_total_count, get_sum_weak_count, get_instance_actual_predicted, get_global_confusion_matrix, get_global_confusion_matrix_item_count, add_global_confusion_matrix_item, update_global_confusion_matrix_item_increment, get_chunk_initial_accuracy, get_chunk_last_id, get_chunk_by_id, get_chunk_for_report, get_generation_for_report, }; // implement the prepared statement to satisfy performance and security. // define statement information. // - stmt : sqlite statement object // - fields : fields of the query result. struct stmt_info { sqlite3_stmt* stmt = nullptr; type::fields fields; stmt_info(_in sqlite3_stmt* stmt, _in const type::fields& fields): stmt{stmt}, fields{fields} {} }; } // sqlite } // db } // gaenari #endif // HEADER_GAENARI_SUPUL_DB_SQLITE_SQLITE_TYPE_HPP
24.153846
97
0.838944
greenfish77
c4e941a3ea7ed2482032b80ed52b01701de9c04e
7,086
cpp
C++
libs/DiabloUI/src/selyesno.cpp
Chronimal/devilution
a7ef09e1403771f0b27d9fa1c7e5f04e8a26f9e8
[ "Unlicense" ]
null
null
null
libs/DiabloUI/src/selyesno.cpp
Chronimal/devilution
a7ef09e1403771f0b27d9fa1c7e5f04e8a26f9e8
[ "Unlicense" ]
null
null
null
libs/DiabloUI/src/selyesno.cpp
Chronimal/devilution
a7ef09e1403771f0b27d9fa1c7e5f04e8a26f9e8
[ "Unlicense" ]
null
null
null
#include "inc.h" // ref: 0x1000FA49 int __fastcall SelYesNo_YesNoDialog(HWND hWnd, char* dialogstr, char* hero, int nofocus) { yesno_dialog_string = dialogstr; yesno_hero_name = hero; yesno_remove_focus = nofocus; yesno_is_popup = 0; YesNoFunc = 0; return SDlgDialogBoxParam(ghUiInst, "SELYESNO_DIALOG", hWnd, SelYesNo_WndProc, 0); } // 1002A500: using guessed type int yesno_remove_focus; // 1002A508: using guessed type int (*YesNoFunc)(void); // 1002A50C: using guessed type int yesno_is_popup; // ref: 0x1000FA87 LRESULT __stdcall SelYesNo_WndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { HWND v4; // eax HWND v5; // eax int v7; // edx HWND v8; // eax LONG v9; // eax HWND v10; // ecx HWND v11; // eax if (Msg == 2) { SelYesNo_RemoveYNDialog(hWnd); return (LRESULT)SDlgDefDialogProc(hWnd, Msg, (HDC)wParam, (HWND)lParam); } if (Msg > 0x103) { if (Msg <= 0x105) { v11 = (HWND)SDrawGetFrameWindow(NULL); SendMessageA(v11, Msg, wParam, lParam); return (LRESULT)SDlgDefDialogProc(hWnd, Msg, (HDC)wParam, (HWND)lParam); } switch (Msg) { case 0x110u: SelYesNo_LoadSelYN_GFX(hWnd); return 0; case WM_COMMAND: if (HIWORD(wParam) == 7) { Focus_GetAndBlitSpin(hWnd, lParam); } else if (HIWORD(wParam) == 6) { Focus_CheckPlayMove(lParam); Focus_DoBlitSpinIncFrame(hWnd, (HWND)lParam); } else { v7 = 1; if ((WORD)wParam == 1) { v8 = GetFocus(); v9 = GetWindowLongA(v8, -12); v10 = hWnd; if (v9 == 1109) { v7 = 1; } else { v7 = 2; } } else { if ((WORD)wParam == 2) { v7 = 2; } else if ((WORD)wParam != 1109) { return (LRESULT)SDlgDefDialogProc(hWnd, Msg, (HDC)wParam, (HWND)lParam); } v10 = hWnd; } SelYesNo_DoSelectYesNo(v10, v7); } break; case WM_TIMER: v4 = GetFocus(); if (!Focus_DoBlitSpinIncFrame(hWnd, v4)) { v5 = GetDlgItem(hWnd, 1109); if (!v5) { v5 = GetDlgItem(hWnd, 2); } SetFocus(v5); } return 0; } } return (LRESULT)SDlgDefDialogProc(hWnd, Msg, (HDC)wParam, (HWND)lParam); } // 10010382: using guessed type DWORD __stdcall SDrawGetFrameWindow(); // ref: 0x1000FBC7 void __fastcall SelYesNo_RemoveYNDialog(HWND hWnd) { HWND v1; // esi void** v2; // eax HWND v3; // eax v1 = hWnd; v2 = (void**)GetWindowLongA(hWnd, -21); local_FreeMemPtr(v2); if (yesno_remove_focus) { Focus_DeleteSpinners(); } Doom_DeleteFreeProcs(v1, yesno_msgtbl1); Doom_DeleteFreeProcs(v1, yesno_msgtbl2); if (yesno_hero_name) { v3 = GetParent(v1); SelHero_SetStringWithMsg(v3, 0); } } // 1002A500: using guessed type int yesno_remove_focus; // ref: 0x1000FC1C void __fastcall SelYesNo_LoadSelYN_GFX(HWND hWnd) { HWND v2; // eax DWORD* v3; // eax DWORD* v4; // edi const char* v5; // eax char* v6; // ST18_4 HWND v7; // eax v2 = GetParent(hWnd); if (yesno_hero_name) { SelHero_SetStringWithMsg(v2, yesno_hero_name); } v3 = local_AllocWndLongData(); v4 = v3; if (v3) { SetWindowLongA(hWnd, -21, (LONG)v3); if (yesno_is_popup) { if (DiabloUI_GetSpawned()) { v5 = "ui_art\\swmmpop.pcx"; } else { v5 = "ui_art\\mmpopup.pcx"; } } else { v5 = "ui_art\\black.pcx"; } local_LoadArtWithPal(hWnd, 0, "Popup", -1, 1, v5, (BYTE**)v4, v4 + 1, 1); } v6 = yesno_dialog_string; v7 = GetDlgItem(hWnd, 1026); SetWindowTextA(v7, v6); Doom_ParseWndProc3(hWnd, yesno_msgtbl2, AF_MEDGRAY); Doom_ParseWndProcs(hWnd, yesno_msgtbl1, AF_BIG, 1); if (yesno_remove_focus) { Focus_LoadSpinner("ui_art\\focus.pcx"); } else { Focus_ResetSpinToZero(); } SDlgSetTimer(hWnd, 1, 55, 0); local_DoUiWndProc2(hWnd, (DWORD*)yesno_msgtbl1); } // 1002A500: using guessed type int yesno_remove_focus; // 1002A50C: using guessed type int yesno_is_popup; // ref: 0x1000FCF6 void __fastcall SelYesNo_DoSelectYesNo(HWND hWnd, int option) { HWND v4; // eax TitleSnd_PlaySelectSound(); SDlgKillTimer(hWnd, 1); if (option == 2) { if (!YesNoFunc) { goto LABEL_6; } YesNoFunc(); } if (option == 1) { v4 = GetFocus(); option = GetWindowLongA(v4, -12); } LABEL_6: SDlgEndDialog(hWnd, (HANDLE)option); } // 1002A508: using guessed type int (*YesNoFunc)(void); // ref: 0x1000FD39 int __fastcall SelYesNo_SelOkDialog(HWND hWnd, char* dialogstr, char* hero, int nofocus) { yesno_dialog_string = dialogstr; yesno_hero_name = hero; yesno_remove_focus = nofocus; yesno_is_popup = 0; YesNoFunc = 0; return SDlgDialogBoxParam(ghUiInst, "SELOK_DIALOG", hWnd, SelYesNo_WndProc, 0); } // 1002A500: using guessed type int yesno_remove_focus; // 1002A508: using guessed type int (*YesNoFunc)(void); // 1002A50C: using guessed type int yesno_is_popup; // ref: 0x1000FD77 int __fastcall SelYesNo_SpawnErrDialog(HWND hWnd, int string_rsrc, int is_popup) { char Buffer[256]; // [esp+4h] [ebp-100h] LoadStringA(ghUiInst, string_rsrc, Buffer, 255); yesno_is_popup = is_popup; yesno_remove_focus = 0; yesno_hero_name = 0; yesno_dialog_string = Buffer; YesNoFunc = 0; return SDlgDialogBoxParam(ghUiInst, "SPAWNERR_DIALOG", hWnd, SelYesNo_WndProc, 0); } // 1002A500: using guessed type int yesno_remove_focus; // 1002A508: using guessed type int (*YesNoFunc)(void); // 1002A50C: using guessed type int yesno_is_popup; // ref: 0x1000FDE3 void __cdecl SelYesNo_cpp_init() { SelYesNo_cpp_float = SelYesNo_cpp_float_value; } // 1001F478: using guessed type int SelYesNo_cpp_float_value; // 1002A4FC: using guessed type int SelYesNo_cpp_float;
28.457831
100
0.530059
Chronimal
c4eb3145a84a203a033f3ed4f2842fecbab9fd67
540
cpp
C++
10 Days of Statistics/Day_6/CLT_2.cpp
yurkovak/HackerRank
a10136e508692f98e76e7c27d9cd801a3380f8ba
[ "MIT" ]
null
null
null
10 Days of Statistics/Day_6/CLT_2.cpp
yurkovak/HackerRank
a10136e508692f98e76e7c27d9cd801a3380f8ba
[ "MIT" ]
null
null
null
10 Days of Statistics/Day_6/CLT_2.cpp
yurkovak/HackerRank
a10136e508692f98e76e7c27d9cd801a3380f8ba
[ "MIT" ]
null
null
null
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <math.h> // using namespace std; float CDF(float mean, float stdev, float x){ float erf_arg = (x - mean) / (pow(2, 0.5) * stdev); return (1 + erf(erf_arg))/2.; } int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ float a, n; float mean, stdev; std::cin >> a >> n; std::cin >> mean >> stdev; printf ("%.4f\n", CDF(mean*n, stdev*pow(n, 0.5), a)); return 0; }
20.769231
79
0.588889
yurkovak
c4eef379800c3039198dc9a3ffe9d7eef52dccb3
680
cpp
C++
PostScrimmageBot/Commands/TurHop/Fire.cpp
FRC-Team-1410/UA2013-FRC1410-Robot
51afc88149e97ff474693ed6a69ff13ba65440e3
[ "BSD-3-Clause" ]
null
null
null
PostScrimmageBot/Commands/TurHop/Fire.cpp
FRC-Team-1410/UA2013-FRC1410-Robot
51afc88149e97ff474693ed6a69ff13ba65440e3
[ "BSD-3-Clause" ]
null
null
null
PostScrimmageBot/Commands/TurHop/Fire.cpp
FRC-Team-1410/UA2013-FRC1410-Robot
51afc88149e97ff474693ed6a69ff13ba65440e3
[ "BSD-3-Clause" ]
1
2020-05-21T09:24:15.000Z
2020-05-21T09:24:15.000Z
#include "Fire.h" Fire::Fire() { // Use requires() here to declare subsystem dependencies Requires(turhop); } // Called just before this Command runs the first time void Fire::Initialize() { } // Called repeatedly when this Command is scheduled to run void Fire::Execute() { turhop->FeederToggle(); } // Make this return true when this Command no longer needs to run execute() bool Fire::IsFinished() { return false; } // Called once after isFinished returns true void Fire::End() { turhop->SetFiringOff(); } // Called when another command which requires one or more of the same // subsystems is scheduled to run void Fire::Interrupted() { turhop->SetFiringOff(); }
20.606061
75
0.720588
FRC-Team-1410
c4f0337e7b61072e9779741064b4c624f93c7f94
6,578
hpp
C++
Code/Engine/EventSystem/NamedProperties.hpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
2
2017-10-02T03:18:55.000Z
2018-11-21T16:30:36.000Z
Code/Engine/EventSystem/NamedProperties.hpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
null
null
null
Code/Engine/EventSystem/NamedProperties.hpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
null
null
null
#pragma once #include "Engine/General/Core/EngineCommon.hpp" #include <map> ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //ENUMS ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// enum ePropertyGetResult { PGR_SUCCESS = 0, PGR_WRONG_TYPE, PGR_NOT_PRESENT, PGR_EMPTY }; enum ePropertySetResult { PSR_SET_EXISTING = 0, PSR_ADDED_NEW_PROPERTY, PSR_EXISTS_BUT_WRONG_TYPE }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //BASE AND TYPED BASE PROPERTY STRUCTS ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct NamedBaseProperty { virtual ~NamedBaseProperty() { } }; template <typename T> struct TypedNamedProperty : public NamedBaseProperty { public: TypedNamedProperty(const T& data) : m_data(data) { } T m_data; }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //NAMED PROPERTIES ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class NamedProperties { public: //STRUCTORS NamedProperties() { } template <typename T> NamedProperties(const String& property1, const T& data1); template <typename T, typename S> NamedProperties(const String& property1, const T& data1, const String& property2, const S& data2); template <typename T, typename S, typename U> NamedProperties(const String& property1, const T& data1, const String& property2, const S& data2, const String& property3, const U& data3); inline ~NamedProperties(); //GET SET template <typename T> ePropertyGetResult GetProperty(const String& name, T& out); template <typename T> ePropertySetResult SetProperty(const String& name, const T& dataToSet); private: std::map<String, NamedBaseProperty*> m_properties; }; //////////////////////////////////////////////////// //------------------------------------------ //INLINES AND TEMPLATE DEFS ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //STRUCTORS ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //--------------------------------------------------------------------------------------------------------------------------- template <typename T> NamedProperties::NamedProperties(const String& property1, const T& data1) { NamedBaseProperty* newProperty1 = new TypedNamedProperty<T>(data1); m_properties.insert(std::pair<String, NamedBaseProperty*>(property1, newProperty1)); } //--------------------------------------------------------------------------------------------------------------------------- template <typename T, typename S> NamedProperties::NamedProperties(const String& property1, const T& data1, const String& property2, const S& data2) { NamedBaseProperty* newProperty1 = new TypedNamedProperty<T>(data1); m_properties.insert(std::pair<String, NamedBaseProperty*>(property1, newProperty1)); NamedBaseProperty* newProperty2 = new TypedNamedProperty<S>(data2); m_properties.insert(std::pair<String, NamedBaseProperty*>(property2, newProperty2)); } //--------------------------------------------------------------------------------------------------------------------------- template <typename T, typename S, typename U> NamedProperties::NamedProperties(const String& property1, const T& data1, const String& property2, const S& data2, const String& property3, const U& data3) { NamedBaseProperty* newProperty1 = new TypedNamedProperty<T>(data1); m_properties.insert(std::pair<String, NamedBaseProperty*>(property1, newProperty1)); NamedBaseProperty* newProperty2 = new TypedNamedProperty<S>(data2); m_properties.insert(std::pair<String, NamedBaseProperty*>(property2, newProperty2)); NamedBaseProperty* newProperty3 = new TypedNamedProperty<U>(data3); m_properties.insert(std::pair<String, NamedBaseProperty*>(property3, newProperty3)); } //--------------------------------------------------------------------------------------------------------------------------- NamedProperties::~NamedProperties() { std::map<String, NamedBaseProperty*>::iterator propertyIt = m_properties.begin(); for (propertyIt; propertyIt != m_properties.end(); ++propertyIt) { delete propertyIt->second; } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //GET SET ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //--------------------------------------------------------------------------------------------------------------------------- template <typename T> ePropertyGetResult NamedProperties::GetProperty(const String& name, T& out) { //First do find based on string //If not found return err not found //If found, we return a NamedPropertyBase if (m_properties.empty()) { return PGR_EMPTY; } std::map<String, NamedBaseProperty*>::iterator propertyIt = m_properties.find(name); if (propertyIt != m_properties.end()) { NamedBaseProperty* baseProperty = propertyIt->second; TypedNamedProperty<T>* typedProperty = dynamic_cast<TypedNamedProperty<T>*>(baseProperty); if (!typedProperty) { return PGR_WRONG_TYPE; } else { out = typedProperty->m_data; return PGR_SUCCESS; } } else { return PGR_NOT_PRESENT; } } //--------------------------------------------------------------------------------------------------------------------------- template <typename T> ePropertySetResult NamedProperties::SetProperty(const String& name, const T& dataToSet) { std::map<String, NamedBaseProperty*>::iterator propertyIt = m_properties.find(name); if (propertyIt != m_properties.end()) { NamedBaseProperty* baseProperty = propertyIt->second; TypedNamedProperty<T>* typedProperty = dynamic_cast<TypedNamedProperty<T>*>(baseProperty); if (!typedProperty) { return PSR_EXISTS_BUT_WRONG_TYPE; } else { typedProperty->m_data = dataToSet; return PSR_SET_EXISTING; } } else { TypedNamedProperty<T>* newProperty = new TypedNamedProperty<T>(dataToSet); m_properties.insert(std::pair<String, NamedBaseProperty*>(name, newProperty)); return PSR_ADDED_NEW_PROPERTY; } }
36.142857
157
0.514746
ntaylorbishop
c4f1c688bbdf3c982034716a61c40966dbeb6b72
1,626
cpp
C++
source/engine/resources/MusicLoader.cpp
AlexKoukoulas2074245K/Genesis
23c114cfe06b65b0b7b5f7807a9ceb4faf8cdf88
[ "MIT" ]
null
null
null
source/engine/resources/MusicLoader.cpp
AlexKoukoulas2074245K/Genesis
23c114cfe06b65b0b7b5f7807a9ceb4faf8cdf88
[ "MIT" ]
null
null
null
source/engine/resources/MusicLoader.cpp
AlexKoukoulas2074245K/Genesis
23c114cfe06b65b0b7b5f7807a9ceb4faf8cdf88
[ "MIT" ]
null
null
null
///------------------------------------------------------------------------------------------------ /// MusicLoader.cpp /// Genesis /// /// Created by Alex Koukoulas on 20/11/2019. ///------------------------------------------------------------------------------------------------ #include "MusicLoader.h" #include "MusicResource.h" #include "../common/utils/Logging.h" #include "../common/utils/OSMessageBox.h" #include <fstream> ///------------------------------------------------------------------------------------------------ namespace genesis { ///------------------------------------------------------------------------------------------------ namespace resources { ///------------------------------------------------------------------------------------------------ void MusicLoader::VInitialize() { } ///------------------------------------------------------------------------------------------------ std::unique_ptr<IResource> MusicLoader::VCreateAndLoadResource(const std::string& resourcePath) const { std::ifstream file(resourcePath); if (!file.good()) { ShowMessageBox(MessageBoxType::ERROR, "File could not be found", resourcePath.c_str()); return nullptr; } auto* loadedMusic = Mix_LoadMUS(resourcePath.c_str()); if (!loadedMusic) { ShowMessageBox(MessageBoxType::ERROR, "SDL_mixer could not load music", Mix_GetError()); return nullptr; } return std::unique_ptr<IResource>(new MusicResource(loadedMusic)); } ///------------------------------------------------------------------------------------------------ } }
28.034483
101
0.383764
AlexKoukoulas2074245K
c4f68e726acf92760962a2790d3daec79466c23b
667
hpp
C++
src/Move.hpp
PolyDevTeam/Polybasite
c705d1e0c7286e55c487ddbcd17cdcabfb057b7a
[ "MIT" ]
1
2017-12-22T15:31:36.000Z
2017-12-22T15:31:36.000Z
src/Move.hpp
PolyDevTeam/Polybasite
c705d1e0c7286e55c487ddbcd17cdcabfb057b7a
[ "MIT" ]
1
2017-12-26T23:18:53.000Z
2017-12-26T23:18:53.000Z
src/Move.hpp
PolyDevTeam/Polybasite
c705d1e0c7286e55c487ddbcd17cdcabfb057b7a
[ "MIT" ]
1
2017-11-20T21:21:01.000Z
2017-11-20T21:21:01.000Z
#ifndef __MOVE_HPP__ #define __MOVE_HPP__ #include <vector> #include <sstream> #include "Serializable.hpp" #include "Miner.hpp" enum DIRECTIONS { STILL = 0, NORTH = 1, EAST = 2, SOUTH = 3, WEST = 4, }; class Move : public Serializable { public: Move(); Move(unsigned minerId, DIRECTIONS directions); virtual ~Move(); virtual std::string serialize(); virtual void deserialize(std::string &serializable); void move(std::vector<Miner*> &miners) const; bool operator<(const Move& move) const; Move& operator=(const Move& move); DIRECTIONS m_directions; unsigned m_minerId; }; #endif /* __MOVE_HPP__ */
18.027027
56
0.661169
PolyDevTeam
c4f75585518af5f6afe024bfc40d2efdd21da4b2
5,870
cpp
C++
src/cpp/ports-runtime.cpp
friedolino78/rtosc
5006acfc030465944b45180942e439b3cf4d617a
[ "MIT" ]
null
null
null
src/cpp/ports-runtime.cpp
friedolino78/rtosc
5006acfc030465944b45180942e439b3cf4d617a
[ "MIT" ]
null
null
null
src/cpp/ports-runtime.cpp
friedolino78/rtosc
5006acfc030465944b45180942e439b3cf4d617a
[ "MIT" ]
null
null
null
#include "../util.h" #include <cstdarg> #include <cstring> #include <cassert> #include <rtosc/pretty-format.h> #include <rtosc/ports.h> #include <rtosc/ports-runtime.h> namespace rtosc { namespace helpers { //! RtData subclass to capture argument values pretty-printed from //! a runtime object class CapturePretty : public RtData { char* buffer; std::size_t buffersize; int cols_used; void reply(const char *) override { assert(false); } /* void replyArray(const char*, const char *args, rtosc_arg_t *vals) { size_t cur_idx = 0; for(const char* ptr = args; *ptr; ++ptr, ++cur_idx) { assert(cur_idx < max_args); arg_vals[cur_idx].type = *ptr; arg_vals[cur_idx].val = vals[cur_idx]; } // TODO: refactor code, also with Capture ? size_t wrt = rtosc_print_arg_vals(arg_vals, cur_idx, buffer, buffersize, NULL, cols_used); assert(wrt); }*/ void reply_va(const char *args, va_list va) { size_t nargs = strlen(args); STACKALLOC(rtosc_arg_val_t, arg_vals, nargs); rtosc_v2argvals(arg_vals, nargs, args, va); size_t wrt = rtosc_print_arg_vals(arg_vals, nargs, buffer, buffersize, NULL, cols_used); assert(wrt); (void)wrt; } void broadcast(const char *, const char *args, ...) override { va_list va; va_start(va,args); reply_va(args, va); va_end(va); } void reply(const char *, const char *args, ...) override { va_list va; va_start(va,args); reply_va(args, va); va_end(va); } public: //! Return the argument values, pretty-printed const char* value() const { return buffer; } CapturePretty(char* buffer, std::size_t size, int cols_used) : buffer(buffer), buffersize(size), cols_used(cols_used) {} }; const char* get_value_from_runtime(void* runtime, const Ports& ports, size_t loc_size, char* loc, char* buffer_with_port, std::size_t buffersize, int cols_used) { std::size_t addr_len = strlen(buffer_with_port); // use the port buffer to print the result, but do not overwrite the // port name CapturePretty d(buffer_with_port + addr_len, buffersize - addr_len, cols_used); d.obj = runtime; d.loc_size = loc_size; d.loc = loc; d.matches = 0; // does the message at least fit the arguments? assert(buffersize - addr_len >= 8); // append type memset(buffer_with_port + addr_len, 0, 8); // cover string end and arguments buffer_with_port[addr_len + (4-addr_len%4)] = ','; d.message = buffer_with_port; // buffer_with_port is a message in this call: ports.dispatch(buffer_with_port, d, false); return d.value(); } //! RtData subclass to capture argument values from a runtime object class Capture : public RtData { size_t max_args; rtosc_arg_val_t* arg_vals; int nargs; void chain(const char *path, const char *args, ...) override { nargs = 0; } void chain(const char *msg) override { nargs = 0; } void reply(const char *) override { assert(false); } void replyArray(const char*, const char *args, rtosc_arg_t *vals) override { size_t cur_idx = 0; for(const char* ptr = args; *ptr; ++ptr, ++cur_idx) { assert(cur_idx < max_args); arg_vals[cur_idx].type = *ptr; arg_vals[cur_idx].val = vals[cur_idx]; } nargs = cur_idx; } void reply_va(const char *args, va_list va) { nargs = strlen(args); assert((size_t)nargs <= max_args); rtosc_v2argvals(arg_vals, nargs, args, va); } void broadcast(const char *, const char *args, ...) override { va_list va; va_start(va, args); reply_va(args, va); va_end(va); } void reply(const char *, const char *args, ...) override { va_list va; va_start(va,args); reply_va(args, va); va_end(va); } public: //! Return the number of argument values stored int size() const { return nargs; } Capture(std::size_t max_args, rtosc_arg_val_t* arg_vals) : max_args(max_args), arg_vals(arg_vals), nargs(-1) {} //! Silence compiler warnings std::size_t dont_use_this_function() { return max_args; } }; size_t get_value_from_runtime(void* runtime, const Port& port, size_t loc_size, char* loc, const char* portname_from_base, char* buffer_with_port, std::size_t buffersize, std::size_t max_args, rtosc_arg_val_t* arg_vals) { fast_strcpy(buffer_with_port, portname_from_base, buffersize); std::size_t addr_len = strlen(buffer_with_port); Capture d(max_args, arg_vals); d.obj = runtime; d.loc_size = loc_size; d.loc = loc; d.port = &port; d.matches = 0; assert(*loc); // does the message at least fit the arguments? assert(buffersize - addr_len >= 8); // append type memset(buffer_with_port + addr_len, 0, 8); // cover string end and arguments buffer_with_port[addr_len + (4-addr_len%4)] = ','; // TODO? code duplication // buffer_with_port is a message in this call: d.message = buffer_with_port; port.cb(buffer_with_port, d); assert(d.size() >= 0); return d.size(); } } // namespace helpers } // namespace rtosc
28.086124
80
0.575468
friedolino78
c4facf834dd49dc246cf62833602fc69b4658c77
885
cpp
C++
Hacke Rank Problems/Week Of Codes 34/maxgcd.cpp
anand434/-Algorithm-And-DataStructures
e4197db5342def163a8bd22de4187b90bc5ff1d3
[ "MIT" ]
null
null
null
Hacke Rank Problems/Week Of Codes 34/maxgcd.cpp
anand434/-Algorithm-And-DataStructures
e4197db5342def163a8bd22de4187b90bc5ff1d3
[ "MIT" ]
null
null
null
Hacke Rank Problems/Week Of Codes 34/maxgcd.cpp
anand434/-Algorithm-And-DataStructures
e4197db5342def163a8bd22de4187b90bc5ff1d3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 6; int cnt[N]; int lmulA[N]; int lmulB[N]; int n; int ar[N]; int br[N]; int main(){ scanf("%d" , &n); for(int i = 1; i <= n; ++i) { scanf("%d" , ar + i); } for(int i = 1; i <= n; ++i) { scanf("%d" , br + i); } for(int i = 1; i <= n; ++i) { ++cnt[arr[i]]; } for(int i = 1; i < N; ++i) { for(int j = i; j < N; j += i) { if(cnt[j]) { lmulA[i] = max(lmulA[i] , j); } } } for(int i = 1; i <= n; ++i) { --cnt[arr[i]]; } for(int i = 1; i <= n; ++i) { ++cnt[brr[i]]; } for(int i = 1; i < N; ++i) { for(int j = i; j < N; j += i) { if(cnt[j]) { lmulB[i] = max(lmulB[i] , j); } } } int mx = 0; for(int i = 1; i < N; ++i) { if(lmulA[i] && lmulB[i]) { mx = i; } } printf("%d\n" , lmulA[mx] + lmulB[mx]); return 0; }
14.75
40
0.39322
anand434
c4ffcd978b48424108f794dde17767d8aa8f8418
6,214
cpp
C++
Castlevania/Input.cpp
ctelotuong/CaslteVania
dd4631a4895b0b91d5d8f80ba505dad7c4d81fab
[ "MIT" ]
null
null
null
Castlevania/Input.cpp
ctelotuong/CaslteVania
dd4631a4895b0b91d5d8f80ba505dad7c4d81fab
[ "MIT" ]
null
null
null
Castlevania/Input.cpp
ctelotuong/CaslteVania
dd4631a4895b0b91d5d8f80ba505dad7c4d81fab
[ "MIT" ]
null
null
null
#include "Input.h" namespace input { Input::Input(core::CGame* game, core::SceneManager* scenes) { this->game = game; this->scenes = scenes; } Input::~Input() { } bool Input::Animation_Standby() { int status; scenes->Get_Simon()->GetStatus(status); if (status == UPDATE && scenes->Get_Simon()->animations[UPDATE]->IsOver(400)==false ) { return true; } //3 frames if (status == ATTACK && scenes->Get_Simon()->animations[ATTACK]->IsOver(300) == false) { return true; } if (status == ATTACK_SIT && scenes->Get_Simon()->animations[ATTACK_SIT]->IsOver(300) == false) { return true; } if (status == ATTACK_STAND && scenes->Get_Simon()->animations[ATTACK_STAND]->IsOver(300) == false) { return true; } if(status==STAIR_UP && scenes->Get_Simon()->animations[STAIR_UP]->IsOver(200)==false) { return true; } if (status == STAIR_DOWN && scenes->Get_Simon()->animations[STAIR_DOWN]->IsOver(200) == false) { return true; } return false; } bool Input::CanProcessKeyboard() { if (Animation_Standby() == true) { return false; } int status; scenes->Get_Simon()->GetStatus(status); //Nếu simon k chạm đất và đang dứng ( đánh trên không trung) hoặc k chạm dất và đang nhảy thì không xử lý if ((scenes->Get_Simon()->isOntheGround == false && status == STAND) || (scenes->Get_Simon()->isOntheGround == false && status == JUMP) || status==DEFLECT || scenes->Get_Simon()->isFalling==true) { return false; } return true; } void Input::KeyState(BYTE* state) { bool isCollideWithStair = false; simon::Simon* simon = scenes->Get_Simon(); vector<core::LPGAMEOBJECT>* listStairs = scenes->Get_List_Stairs(); if(simon->CheckCollisionSimonAndStair(listStairs)==true) { isCollideWithStair = true; } if (CanProcessKeyboard() == false) { return; } if (game->IsKeyDown(DIK_RIGHT)) { if (game->IsKeyDown(DIK_DOWN)) { scenes->Get_Simon()->SetOrientation_x(1); scenes->Get_Simon()->SetStatus(SIT); } else { scenes->Get_Simon()->SetOrientation_x(1); scenes->Get_Simon()->SetStatus(WALK); } } else if (game->IsKeyDown(DIK_LEFT)) { if (game->IsKeyDown(DIK_DOWN)) { scenes->Get_Simon()->SetOrientation_x(-1); scenes->Get_Simon()->SetStatus(SIT); } else { scenes->Get_Simon()->SetOrientation_x(-1); scenes->Get_Simon()->SetStatus(WALK); } } else if (game->IsKeyDown(DIK_DOWN)) { if(isCollideWithStair==true) { if(simon->Get_Is_Move_Down()==false) { return; } int status1; simon->GetStatus(status1); int prevState = status1; simon->SetOrientation_x(-simon->Get_Stair_Direction()); simon->SetStatus(STAIR_DOWN); if(simon->Get_Is_Onstair()==false) { simon->Set_On_Stair(true); simon->PositionCorrection(); } else if(prevState==STAIR_UP)//nếu simon đột nhien chuyển từ trang thai stairup sang stair down { simon->PositionCorrection(prevState); } return; } scenes->Get_Simon()->SetStatus(SIT); } else if (game->IsKeyDown(DIK_UP)) { int prevStave; simon->GetStatus(prevStave); if (isCollideWithStair == true) { if (simon->Get_Is_Move_Up() == false) { simon->SetStatus(STAND); if (prevStave == STAIR_UP) { float sx, sy; simon->GetPosition(sx, sy); int nx; simon->GetOrientation_x(nx); simon->SetPosition(sx + nx * 5.0f, sy - 5.0f); } return; } simon->SetOrientation_x(simon->Get_Stair_Direction()); simon->SetStatus(STAIR_UP); if (simon->Get_Is_Onstair() == false) { simon->Set_On_Stair(true); simon->PositionCorrection(); } else if (prevStave == STAIR_DOWN)//nếu simon dot nhien chuyển từ trang thái stairdown sang stairup { simon->PositionCorrection(prevStave); } } else { simon->SetStatus(STAND); } } else { int status2; simon->GetStatus(status2); if(isCollideWithStair==true &&(status2==STAIR_UP ||status2==STAIR_DOWN)) { simon->StandOnStair(); simon->animations[status2]->Reset(); return; } scenes->Get_Simon()->SetStatus(STAND); } } void Input::OnKeyDown(int KeyCode) { if (KeyCode != DIK_Z) { if (CanProcessKeyboard() == false) return; } DebugOut(L"[INFO] KeyDown: %d\n", KeyCode); int status; scenes->Get_Simon()->GetStatus(status); switch (KeyCode) { case DIK_SPACE: scenes->Get_Simon()->SetStatus(JUMP); break; case DIK_Z: if (!game->IsKeyDown(DIK_UP)) { if(status == JUMP || status == STAND) scenes->Get_Simon()->SetStatus(ATTACK_STAND); else if(status ==WALK) { scenes->Get_Simon()->SetStatus(ATTACK_STAND); scenes->Get_Simon()->vx = 0; } else if (status == SIT) { scenes->Get_Simon()->SetStatus(ATTACK_SIT); } } else if(game->IsKeyDown(DIK_UP)) { bool enable; scenes->Get_Sub_Weapon()->GetEnable(enable); int status; scenes->Get_Simon()->GetStatus(status); if (scenes->Get_Simon()->GetSubweapon() == -1 || scenes->Get_Simon()->GetMana() == 0 || enable==true) // không có vũ khí hoặc enery = 0 return; if (status == STAND || status == JUMP) { simon::Simon* simon = scenes->Get_Simon(); simon::SubWeapon* weapon = scenes->Get_Sub_Weapon(); float sx, sy; // position simon->GetPosition(sx, sy); weapon->SetPosition(sx, sy+10); int ox; simon->GetOrientation_x(ox); // orientation weapon->SetOrientation_x(ox); // state weapon weapon->SetState(simon->GetSubweapon()); weapon->SetEnable(true); int mana; mana= simon->GetMana(); simon->SetMana(mana-1); simon->SetStatus(ATTACK); } } break; case DIK_1: scenes->Get_Simon()->SetSubweapon(DAGGER); break; case DIK_2: scenes->Get_Simon()->SetSubweapon(FLYING_AXE); break; case DIK_3: scenes->Get_Simon()->SetSubweapon(BOOMERANG); break; case DIK_4: scenes->Get_Simon()->SetSubweapon(HOLY_WATER); break; case DIK_Q: scenes->Init(SCENE_1); break; } } void Input::OnKeyUp(int KeyCode) { DebugOut(L"[INFO] KeyUp: %d\n", KeyCode); } }
23.717557
139
0.623592
ctelotuong
f2047d442b81465a2549c37263c825451b64f114
6,972
cpp
C++
lesson04/src/helper_functions.cpp
just-4-name/CPPExercises2021
4df4b93b470bde7f05de91e5e1ed76e63daf49d8
[ "MIT" ]
null
null
null
lesson04/src/helper_functions.cpp
just-4-name/CPPExercises2021
4df4b93b470bde7f05de91e5e1ed76e63daf49d8
[ "MIT" ]
null
null
null
lesson04/src/helper_functions.cpp
just-4-name/CPPExercises2021
4df4b93b470bde7f05de91e5e1ed76e63daf49d8
[ "MIT" ]
null
null
null
#include "helper_functions.h" #include <cstdlib> #include <ctime> #include <iostream> #include <libutils/rasserts.h> using namespace std; using namespace cv; cv::Mat makeAllBlackPixelsBlue(cv::Mat image) { // TODO реализуйте функцию которая каждый черный пиксель картинки сделает синим int height = image.rows, width = image.cols; for(int i = 0; i<height; ++i) { for (int j = 0; j < width; ++j) { Vec3b color = image.at<Vec3b>(i, j); unsigned char b = color[0], g = color[1], r = color[2]; if (r < 30 && g < 30 && b < 30) { b = 255; r = g = 0; } image.at<Vec3b>(i, j) = Vec3b(b, g, r); } } // ниже приведен пример как узнать цвет отдельного пикселя - состоящий из тройки чисел BGR (Blue Green Red) // чем больше значение одного из трех чисел - тем насыщеннее его оттенок // всего их диапазон значений - от 0 до 255 включительно // т.е. один байт, поэтому мы используем ниже тип unsigned char - целое однобайтовое неотрицательное число // cv::Vec3b color = image.at<cv::Vec3b>(13, 5); // взяли и узнали что за цвет в пикселе в 14-ом ряду (т.к. индексация с нуля) и 6-ой колонке // unsigned char blue = color[0]; // если это число равно 255 - в пикселе много синего, если равно 0 - в пикселе нет синего // unsigned char green = color[1]; // unsigned char red = color[2]; // // // как получить белый цвет? как получить черный цвет? как получить желтый цвет? // // поэкспериментируйте! например можете всю картинку заполнить каким-то одним цветом // // // пример как заменить цвет по тем же координатам // red = 255; // // запустите эту версию функции и посмотрите на получившуюся картинку - lesson03/resultsData/01_blue_unicorn.jpg // // какой пиксель изменился? почему он не чисто красный? // image.at<cv::Vec3b>(13, 5) = cv::Vec3b(blue, green, red); return image; } cv::Mat invertImageColors(cv::Mat image) { // TODO реализуйте функцию которая каждый цвет картинки инвертирует: // т.е. пусть ночь станет днем, а сумрак рассеется // иначе говоря замените каждое значение яркости x на (255-x) (т.к находится в диапазоне от 0 до 255) int height = image.rows, width = image.cols; for(int i = 0; i<height; ++i) { for (int j = 0; j < width; ++j) { Vec3b color = image.at<Vec3b>(i, j); unsigned char b = color[0], g = color[1], r = color[2]; b = 255 - b; g = 255 - g; r = 255 - r; image.at<Vec3b>(i, j) = Vec3b(b, g, r); } } return image; } cv::Mat addBackgroundInsteadOfBlackPixels(cv::Mat object, cv::Mat background) { // TODO реализуйте функцию которая все черные пиксели картинки-объекта заменяет на пиксели с картинки-фона // т.е. что-то вроде накладного фона получится // гарантируется что размеры картинок совпадают - проверьте это через rassert, вот например сверка ширины: rassert(object.cols == background.cols, 341241251251351); rassert(object.rows == background.rows, 341241251251351); int height = object.rows, width = object.cols; for(int i = 0; i<height; ++i) { for (int j = 0; j < width; ++j) { Vec3b color = object.at<Vec3b>(i, j); Vec3b color1 = background.at<Vec3b>(i,j); unsigned char b = color[0], g = color[1], r = color[2]; if(b<30 && r<30 && g<30){ object.at<Vec3b>(i,j) = color1; } } } return object; } cv::Mat addBackgroundInsteadOfBlackPixelsLargeBackground(cv::Mat object, cv::Mat largeBackground) { // теперь вам гарантируется что largeBackground гораздо больше - добавьте проверок этого инварианта (rassert-ов) // TODO реализуйте функцию так, чтобы нарисовался объект ровно по центру на данном фоне, при этом черные пиксели объекта не должны быть нарисованы int height = object.rows, width = object.cols; int height1 = largeBackground.rows, width1 = largeBackground.cols; for(int i = 0; i<height; ++i) { for (int j = 0; j < width; ++j) { Vec3b color = object.at<Vec3b>(i, j); unsigned char b = color[0], g = color[1], r = color[2]; if(!(b<30 && r<30 && g<30)){ largeBackground.at<Vec3b>(i+(height1-height)/2, j + (width1-width)/2) = color; } } } return largeBackground; } Mat drawNUnicorns(Mat object, Mat background, int n){ srand((unsigned)time(0)); for(int i=0;i<n;++i){ int x = (rand() % (background.cols - object.cols-5)); int y = (rand() % (background.rows - object.rows-5)); for(int j = 0;j<object.rows;++j){ for(int k = 0; k<object.cols;++k){ Vec3b color = object.at<Vec3b>(j, k); unsigned char b = color[0], g = color[1], r = color[2]; if(!(b<30 && r<30 && g<30)){ rassert(y+j>=0 && y+j<=background.rows,2131441) background.at<Vec3b>(y + j, x + k) = color; } } } } return background; } Mat makeBlackPixelsRand(Mat img){ srand((unsigned)time(0)); for(int i = 0;i<img.rows;++i){ for(int j = 0;j<img.cols;++j){ Vec3b color = img.at<Vec3b>(i,j); unsigned char b = color[0], g = color[1], r = color[2]; if(b<30 && r<30 && g<30){ r = rand()%256; g = rand()%256; b = rand()%256; img.at<Vec3b>(i,j) = Vec3b(b,g,r); } } }return img; } vector<vector<int>> dilate(vector<vector<int>> mask, int r){ //0 - обьект for(int i=0;i<mask.size();++i){ for(int j = 0;j<mask[i].size();++j){ for(int dy = -r;dy<=r;++dy){ for(int dx = -r;dx<=r;++dx){ int y = i + dy; int x = j + dx; if(y<0 || y>=mask.size()) continue; if(x<0 || x>=mask[i].size()) continue; if(mask[y][x] == 0){ mask[i][j] = 0; } } } } }return mask; } vector<vector<int>> erode(vector<vector<int>> mask, int r){ //0 - обьект for(int i=0;i<mask.size();++i){ for(int j = 0;j<mask[i].size();++j){ for(int dy = -r;dy<=r;++dy){ for(int dx = -r;dx<=r;++dx){ int y = i + dy; int x = j + dx; if(y<0 || y>=mask.size()) continue; if(x<0 || x>=mask[i].size()) continue; if(mask[y][x] == 1){ mask[i][j] = 1; } } } } }return mask; } bool equeal(Vec3b c1, Vec3b c2){ if(abs(c1[0] - c2[0])<20 && abs(c1[1] - c2[1])<20 && abs(c1[2] - c2[2])<20){ return 1; }else return 0; }
35.753846
150
0.535714
just-4-name
f20490673fc389cdb393578973c2b8d7488dbdcd
217
cpp
C++
Game_Girls_AutoChess_2019_06_04/Lib/UIObject.cpp
AhriHaran/Unity
90a84d8cabd5ef890f3fb7d9624437b1ef8157a9
[ "Unlicense" ]
null
null
null
Game_Girls_AutoChess_2019_06_04/Lib/UIObject.cpp
AhriHaran/Unity
90a84d8cabd5ef890f3fb7d9624437b1ef8157a9
[ "Unlicense" ]
null
null
null
Game_Girls_AutoChess_2019_06_04/Lib/UIObject.cpp
AhriHaran/Unity
90a84d8cabd5ef890f3fb7d9624437b1ef8157a9
[ "Unlicense" ]
2
2019-09-04T06:04:23.000Z
2019-09-16T07:44:16.000Z
#include "UIObject.h" namespace JEngine { UIObject::UIObject() { } UIObject::~UIObject() { } void UIObject::SetPos(int left, int top, int right, int bottom) { m_rcPos.Set(left, top, right, bottom); } }
11.421053
64
0.645161
AhriHaran
f2065ef3ba4d32ba05f9a7114fb2acfac53a9ccf
4,106
inl
C++
trunk/libs/angsys/include/ang/maths/implement/double4x4_simd.inl
ChuyX3/angsys
89b2eaee866bcfd11e66efda49b38acc7468c780
[ "Apache-2.0" ]
null
null
null
trunk/libs/angsys/include/ang/maths/implement/double4x4_simd.inl
ChuyX3/angsys
89b2eaee866bcfd11e66efda49b38acc7468c780
[ "Apache-2.0" ]
null
null
null
trunk/libs/angsys/include/ang/maths/implement/double4x4_simd.inl
ChuyX3/angsys
89b2eaee866bcfd11e66efda49b38acc7468c780
[ "Apache-2.0" ]
null
null
null
#ifndef __COFFE_GRAPH_MATHS_H__ #error ... #elif !defined __COFFE_GRAPH_MATHS_FLOAT4X4_HPP__ #define __COFFE_GRAPH_MATHS_FLOAT4X4_HPP__ inline coffe::math::float4x4::float4x4() { memset(_mat, 0, sizeof(_mat)); } inline coffe::math::float4x4::float4x4(float_t val) { _mat[0] = _mm_set1_ps(val); _mat[1] = _mm_set1_ps(val); _mat[2] = _mm_set1_ps(val); _mat[3] = _mm_set1_ps(val); } inline coffe::math::float4x4::float4x4(float4_t const& v0, float4_t const& v1, float4_t const& v2, float4_t const& v3) { _mat[0] = v0._vector; _mat[1] = v1._vector; _mat[2] = v2._vector; _mat[3] = v3._vector; } inline coffe::math::float4x4::float4x4(const float4x4& mat) { _mat[0] = mat._mat[0]; _mat[1] = mat._mat[1]; _mat[2] = mat._mat[2]; _mat[3] = mat._mat[3]; } inline coffe::math::float4x4_t& coffe::math::float4x4::operator = (const float4x4_t& mat) { _mat[0] = mat._mat[0]; _mat[1] = mat._mat[1]; _mat[2] = mat._mat[2]; _mat[3] = mat._mat[3]; return*this; } inline coffe::math::float4x4_t& coffe::math::float4x4::operator += (const float4x4_t& mat) { _mat[0] = _mm_add_ps(_mat[0], mat._mat[0]); _mat[1] = _mm_add_ps(_mat[0], mat._mat[0]); _mat[2] = _mm_add_ps(_mat[0], mat._mat[0]); _mat[3] = _mm_add_ps(_mat[0], mat._mat[0]); return*this; } inline coffe::math::float4x4_t& coffe::math::float4x4::operator -= (const float4x4_t& mat) { _mat[0] = _mm_sub_ps(_mat[0], mat._mat[0]); _mat[1] = _mm_sub_ps(_mat[0], mat._mat[0]); _mat[2] = _mm_sub_ps(_mat[0], mat._mat[0]); _mat[3] = _mm_sub_ps(_mat[0], mat._mat[0]); return*this; } inline coffe::math::float4x4_t& coffe::math::float4x4::operator *= (float_t k) { _mat[0] = _mm_mul_ps(_mat[0], _mm_set1_ps(k)); _mat[1] = _mm_mul_ps(_mat[1], _mm_set1_ps(k)); _mat[2] = _mm_mul_ps(_mat[2], _mm_set1_ps(k)); _mat[3] = _mm_mul_ps(_mat[3], _mm_set1_ps(k)); return*this; } inline coffe::math::float4x4_t& coffe::math::float4x4::operator /= (float_t k) { _mat[0] = _mm_div_ps(_mat[0], _mm_set1_ps(k)); _mat[1] = _mm_div_ps(_mat[1], _mm_set1_ps(k)); _mat[2] = _mm_div_ps(_mat[2], _mm_set1_ps(k)); _mat[3] = _mm_div_ps(_mat[3], _mm_set1_ps(k)); return*this; } template<> inline coffe::math::float4_t& coffe::math::float4x4::get<0>() { return*reinterpret_cast<coffe::math::float4_t*>(&_mat[0]); } template<> inline coffe::math::float4_t& coffe::math::float4x4::get<1>() { return*reinterpret_cast<coffe::math::float4_t*>(&_mat[1]); } template<> inline coffe::math::float4_t& coffe::math::float4x4::get<2>() { return*reinterpret_cast<coffe::math::float4_t*>(&_mat[2]); } template<> inline coffe::math::float4_t& coffe::math::float4x4::get<3>() { return*reinterpret_cast<coffe::math::float4_t*>(&_mat[3]); } template<> inline coffe::math::float4_t const& coffe::math::float4x4::get<0>()const { return*reinterpret_cast<coffe::math::float4_t const*>(&_mat[0]); } template<> inline coffe::math::float4_t const& coffe::math::float4x4::get<1>()const { return*reinterpret_cast<coffe::math::float4_t const*>(&_mat[1]); } template<> inline coffe::math::float4_t const& coffe::math::float4x4::get<2>()const { return*reinterpret_cast<coffe::math::float4_t const*>(&_mat[2]); } template<> inline coffe::math::float4_t const& coffe::math::float4x4::get<3>()const { return*reinterpret_cast<coffe::math::float4_t const*>(&_mat[3]); } inline coffe::math::float4_t& coffe::math::float4x4::operator [](coffe::int_t idx) { return *reinterpret_cast<coffe::math::float4_t*>(&_mat[idx]); } inline coffe::math::float4_t const& coffe::math::float4x4::operator [](coffe::int_t idx)const { return *reinterpret_cast<coffe::math::float4_t const*>(&_mat[idx]); } inline coffe::bool_t coffe::math::float4x4::operator == (const coffe::math::float4x4_t& mat)const { return get<0>() == mat.get<0>() && get<1>() == mat.get<1>() && get<2>() == mat.get<2>() && get<3>() == mat.get<3>(); } inline coffe::bool_t coffe::math::float4x4::operator != (const coffe::math::float4x4_t& mat)const { return get<0>() != mat.get<0>() || get<1>() != mat.get<1>() || get<2>() != mat.get<2>() || get<3>() != mat.get<3>(); } #endif//__COFFE_GRAPH_MATHS_FLOAT4X4_HPP__
38.735849
152
0.677058
ChuyX3
f206b5424336bef9ddea354fd51410339489df3e
4,569
hpp
C++
src/tests-core/tests/packed/sequence/fse/pseq_test_base.hpp
victor-smirnov/memoria
c36a957c63532176b042b411b1646c536e71a658
[ "BSL-1.0", "Apache-2.0", "OLDAP-2.8", "BSD-3-Clause" ]
2
2021-07-30T16:54:24.000Z
2021-09-08T15:48:17.000Z
src/tests-core/tests/packed/sequence/fse/pseq_test_base.hpp
victor-smirnov/memoria
c36a957c63532176b042b411b1646c536e71a658
[ "BSL-1.0", "Apache-2.0", "OLDAP-2.8", "BSD-3-Clause" ]
null
null
null
src/tests-core/tests/packed/sequence/fse/pseq_test_base.hpp
victor-smirnov/memoria
c36a957c63532176b042b411b1646c536e71a658
[ "BSL-1.0", "Apache-2.0", "OLDAP-2.8", "BSD-3-Clause" ]
2
2020-03-14T15:15:25.000Z
2020-06-15T11:26:56.000Z
// Copyright 2013 Victor Smirnov // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <memoria/tests/tests.hpp> #include <memoria/tests/assertions.hpp> #include <memoria/core/packed/sseq/packed_fse_searchable_seq.hpp> #include <memoria/core/packed/tools/packed_struct_ptrs.hpp> #include <memoria/reactor/reactor.hpp> #include <memory> namespace memoria { namespace tests { template < int32_t Bits, typename IndexType, template <typename> class ReindexFnType, template <typename> class SelectFnType, template <typename> class RankFnType, template <typename> class ToolsFnType > class PackedSearchableSequenceTestBase: public TestState { using Base = TestState; typedef PackedSearchableSequenceTestBase< Bits, IndexType, ReindexFnType, SelectFnType, RankFnType, ToolsFnType > MyType; typedef PkdFSSeqTypes< Bits, 1024, IndexType, ReindexFnType, SelectFnType, RankFnType, ToolsFnType > Types; protected: using Seq = PkdFSSeq<Types>; using SeqPtr = PkdStructSPtr<Seq>; typedef typename Seq::Value Value; static const int32_t Blocks = Seq::Indexes; static const int32_t Symbols = 1 << Bits; static const int32_t VPB = Seq::ValuesPerBranch; int32_t iterations_ = 100; int64_t size_{32768}; public: MMA_STATE_FILEDS(size_, iterations_); SeqPtr createEmptySequence(int32_t block_size = 1024*1024) { return MakeSharedPackedStructByBlock<Seq>(block_size); } std::vector<int32_t> populate(SeqPtr& seq, int32_t size, Value value = 0) { std::vector<int32_t> symbols(size); for (auto& s: symbols) s = value; seq->clear().get_or_throw(); seq->insert(0, size, [&](){ return value; }).get_or_throw(); assertEqual(seq, symbols); assertIndexCorrect(MA_SRC, seq); return symbols; } std::vector<int32_t> populateRandom(SeqPtr& seq, int32_t size) { seq->clear().get_or_throw(); return fillRandom(seq, size); } std::vector<int32_t> fillRandom(SeqPtr& seq, int32_t size) { std::vector<int32_t> symbols; seq->insert(0, size, [&]() { int32_t sym = getRandom(Blocks); symbols.push_back(sym); return sym; }).get_or_throw(); seq->check().get_or_throw(); this->assertIndexCorrect(MA_SRC, seq); this->assertEqual(seq, symbols); return symbols; } int32_t rank(const SeqPtr& seq, int32_t start, int32_t end, int32_t symbol) { int32_t rank = 0; for (int32_t c = start; c < end; c++) { rank += seq->test(c, symbol); } return rank; } void assertIndexCorrect(const char* src, const SeqPtr& seq) { try { seq->check().get_or_throw(); } catch (Exception& e) { out() << "Sequence structure check failed" << std::endl; seq->dump(out()); throw e; } } void assertEmpty(const SeqPtr& seq) { assert_equals(seq->size(), 0); assert_equals(false, seq->has_index()); } void assertEqual(const SeqPtr& seq, const std::vector<int32_t>& symbols) { assert_equals(seq->size(), (int32_t)symbols.size()); try { for (int32_t c = 0; c < seq->size(); c++) { assert_equals((uint64_t)seq->symbol(c), (uint64_t)symbols[c], "Index: {}", c); } } catch(...) { seq->dump(this->out()); throw; } } }; }}
25.104396
94
0.562267
victor-smirnov
f20745a76d6d68fcb0bf77b7addba4c2e9d6c8a7
6,427
hpp
C++
headers/rpnx/hsalsa.hpp
rpnx-net/rpnx-crypto
795487338f4d569d56886ab2b685bcd38a433142
[ "MIT" ]
1
2020-12-17T07:25:03.000Z
2020-12-17T07:25:03.000Z
headers/rpnx/hsalsa.hpp
rpnx-net/rpnx-crypto
795487338f4d569d56886ab2b685bcd38a433142
[ "MIT" ]
null
null
null
headers/rpnx/hsalsa.hpp
rpnx-net/rpnx-crypto
795487338f4d569d56886ab2b685bcd38a433142
[ "MIT" ]
null
null
null
// // Created by rnicholl on 12/16/20. // #ifndef RPNX_DJB_CRYPTO_HSALSA_HPP #define RPNX_DJB_CRYPTO_HSALSA_HPP #include <utility> #include <cinttypes> #include <tuple> #include <cstddef> #include "rpnx/crypto_common.hpp" #include <stdint.h> #include <stdlib.h> namespace rpnx::c_djb_crypto { template <std::size_t Rounds> void core_hsalsa(std::byte *out, const std::byte *in, const std::byte *k, const std::byte *c) { static_assert(Rounds % 2 == 0); std::uint32_t x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15; if (c == nullptr) { x0 = std::uint32_t(0x61707865u); x5 = std::uint32_t(0x3320646eu); x10 = std::uint32_t(0x79622d32u); x15 = std::uint32_t(0x6b206574u); } else { x0 = load_little_endian32(c + 0); x5 = load_little_endian32(c + 4); x10 = load_little_endian32(c + 8); x15 = load_little_endian32(c + 12); } x1 = load_little_endian32(k + 0); x2 = load_little_endian32(k + 4); x3 = load_little_endian32(k + 8); x4 = load_little_endian32(k + 12); x11 = load_little_endian32(k + 16); x12 = load_little_endian32(k + 20); x13 = load_little_endian32(k + 24); x14 = load_little_endian32(k + 28); x6 = load_little_endian32(in + 0); x7 = load_little_endian32(in + 4); x8 = load_little_endian32(in + 8); x9 = load_little_endian32(in + 12); for (int i = Rounds; i > 0; i -= 2) { x4 ^= rotate_up_32(x0 + x12, 7); x8 ^= rotate_up_32(x4 + x0, 9); x12 ^= rotate_up_32(x8 + x4, 13); x0 ^= rotate_up_32(x12 + x8, 18); x9 ^= rotate_up_32(x5 + x1, 7); x13 ^= rotate_up_32(x9 + x5, 9); x1 ^= rotate_up_32(x13 + x9, 13); x5 ^= rotate_up_32(x1 + x13, 18); x14 ^= rotate_up_32(x10 + x6, 7); x2 ^= rotate_up_32(x14 + x10, 9); x6 ^= rotate_up_32(x2 + x14, 13); x10 ^= rotate_up_32(x6 + x2, 18); x3 ^= rotate_up_32(x15 + x11, 7); x7 ^= rotate_up_32(x3 + x15, 9); x11 ^= rotate_up_32(x7 + x3, 13); x15 ^= rotate_up_32(x11 + x7, 18); x1 ^= rotate_up_32(x0 + x3, 7); x2 ^= rotate_up_32(x1 + x0, 9); x3 ^= rotate_up_32(x2 + x1, 13); x0 ^= rotate_up_32(x3 + x2, 18); x6 ^= rotate_up_32(x5 + x4, 7); x7 ^= rotate_up_32(x6 + x5, 9); x4 ^= rotate_up_32(x7 + x6, 13); x5 ^= rotate_up_32(x4 + x7, 18); x11 ^= rotate_up_32(x10 + x9, 7); x8 ^= rotate_up_32(x11 + x10, 9); x9 ^= rotate_up_32(x8 + x11, 13); x10 ^= rotate_up_32(x9 + x8, 18); x12 ^= rotate_up_32(x15 + x14, 7); x13 ^= rotate_up_32(x12 + x15, 9); x14 ^= rotate_up_32(x13 + x12, 13); x15 ^= rotate_up_32(x14 + x13, 18); } store_little_endian32(out + 0, x0); store_little_endian32(out + 4, x5); store_little_endian32(out + 8, x10); store_little_endian32(out + 12, x15); store_little_endian32(out + 16, x6); store_little_endian32(out + 20, x7); store_little_endian32(out + 24, x8); store_little_endian32(out + 28, x9); } } namespace rpnx::crypto { template <std::size_t Rounds, typename OutIt, typename InputIt, typename KeyIt > void core_hsalsa(OutIt out, InputIt in, KeyIt k) { static_assert(Rounds % 2 == 0); std::uint32_t x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15; x0 = std::uint32_t(0x61707865u); x5 = std::uint32_t(0x3320646eu); x10 = std::uint32_t(0x79622d32u); x15 = std::uint32_t(0x6b206574u); x1 = load_little_endian32(k + 0); x2 = load_little_endian32(k + 4); x3 = load_little_endian32(k + 8); x4 = load_little_endian32(k + 12); x11 = load_little_endian32(k + 16); x12 = load_little_endian32(k + 20); x13 = load_little_endian32(k + 24); x14 = load_little_endian32(k + 28); x6 = load_little_endian32(in + 0); x7 = load_little_endian32(in + 4); x8 = load_little_endian32(in + 8); x9 = load_little_endian32(in + 12); for (int i = Rounds; i > 0; i -= 2) { x4 ^= rotate_up_32(x0 + x12, 7); x8 ^= rotate_up_32(x4 + x0, 9); x12 ^= rotate_up_32(x8 + x4, 13); x0 ^= rotate_up_32(x12 + x8, 18); x9 ^= rotate_up_32(x5 + x1, 7); x13 ^= rotate_up_32(x9 + x5, 9); x1 ^= rotate_up_32(x13 + x9, 13); x5 ^= rotate_up_32(x1 + x13, 18); x14 ^= rotate_up_32(x10 + x6, 7); x2 ^= rotate_up_32(x14 + x10, 9); x6 ^= rotate_up_32(x2 + x14, 13); x10 ^= rotate_up_32(x6 + x2, 18); x3 ^= rotate_up_32(x15 + x11, 7); x7 ^= rotate_up_32(x3 + x15, 9); x11 ^= rotate_up_32(x7 + x3, 13); x15 ^= rotate_up_32(x11 + x7, 18); x1 ^= rotate_up_32(x0 + x3, 7); x2 ^= rotate_up_32(x1 + x0, 9); x3 ^= rotate_up_32(x2 + x1, 13); x0 ^= rotate_up_32(x3 + x2, 18); x6 ^= rotate_up_32(x5 + x4, 7); x7 ^= rotate_up_32(x6 + x5, 9); x4 ^= rotate_up_32(x7 + x6, 13); x5 ^= rotate_up_32(x4 + x7, 18); x11 ^= rotate_up_32(x10 + x9, 7); x8 ^= rotate_up_32(x11 + x10, 9); x9 ^= rotate_up_32(x8 + x11, 13); x10 ^= rotate_up_32(x9 + x8, 18); x12 ^= rotate_up_32(x15 + x14, 7); x13 ^= rotate_up_32(x12 + x15, 9); x14 ^= rotate_up_32(x13 + x12, 13); x15 ^= rotate_up_32(x14 + x13, 18); } store_little_endian32(out + 0, x0); store_little_endian32(out + 4, x5); store_little_endian32(out + 8, x10); store_little_endian32(out + 12, x15); store_little_endian32(out + 16, x6); store_little_endian32(out + 20, x7); store_little_endian32(out + 24, x8); store_little_endian32(out + 28, x9); } } #endif
36.725714
84
0.512214
rpnx-net
f2075a00fc92920bb9bc55067dff1d81e2b85834
17,352
cpp
C++
Source/DBHandler/database.cpp
Iskeletu/SimpleDB
73429b63bb7c05617e2258c2bd33510044c1746c
[ "MIT" ]
3
2021-12-10T03:09:01.000Z
2021-12-27T17:24:22.000Z
Source/DBHandler/database.cpp
Iskeletu/SimpleDB
73429b63bb7c05617e2258c2bd33510044c1746c
[ "MIT" ]
null
null
null
Source/DBHandler/database.cpp
Iskeletu/SimpleDB
73429b63bb7c05617e2258c2bd33510044c1746c
[ "MIT" ]
null
null
null
/* Database managment file. All work done in the non-compressed database (.db) file is handled by this file. */ //Libraries #include <string> #include <vector> #include <fstream> #include <filesystem> //Header Files #include "database.h" //Local Database Base Direcaroty Reference const std::string basedir("./Data"); //Default directory databases are loaded from. //=====================Namespace==================== namespace fs = std::filesystem; //================================================== //====================Constructor=================== Database::Database(std::string dbname, std::string path, std::vector<Index> index_vector) : member_name(dbname), member_path(path), member_size(-1), member_last_insertion(-1), member_index(index_vector) {;} //================================================== //=================Database Creator================= Database Database::CreateDatabase(std::string dbname) { //Creates and return a reference to a database. std::string dbfolder(basedir + "/" + dbname); //!This will not work on windows. std::string dbfile(dbfolder + "/" + dbname + ".db"); //!This will not work on windows. if(!fs::exists(basedir)) { //Creates the base folder (default = .{ProjectRoot}/Data/) if it does not exist. fs::create_directory(basedir); } if(!fs::exists(dbfolder)) { //Creates database folder if it does not exist. fs::create_directory(dbfolder); } else { //Deletes contents in folder if it exits but a database creation was called. fs::remove_all(dbfolder); fs::create_directory(dbfolder); } //Creates a new database file and it's reference. std::ofstream ofile(dbfile, std::ios::binary); //Creates file and open as input and output. Database db(dbname, dbfolder, Index::CreateIndex(dbname)); //Creates database reference to previouly created file. //Formats as a default blank database file. db.member_size = 0; db.member_last_insertion = 0; size_t string_size = dbname.size(); ofile.write((char*)&string_size, sizeof(size_t)); //Inserts size of "dbname" string. ofile.write(&dbname[0], string_size); //Inserts "dbname" string. ofile.write((char*)&db.member_size, sizeof(int)); //Inserts database size integer. ofile.flush(); if(!ofile.good()) { //Throws an exception if writing was not successful. throw std::runtime_error("Database::CreateDatabase=writingfailure"); } ofile.close(); //Closes file. //Return the new reference. return db; } //================================================== //==================Database Reader================= void ReadDatabase(Database* db, int* database_size, int* last_insertion, std::vector<Index>* newindex) { //This function loads database members store in binary database file to primary memory. //Slave function to "Database::LoadDatabase". std::string dbfile = (db->GetDirectory() + "/" + db->GetName() +".db"); //!This will not work on windows. std::ifstream ifile(dbfile, std::ios::binary); //Opens file as input. //Reads database size. size_t string_size; ifile.read((char*)&string_size, sizeof(size_t)); //Gets size of database name string on file. ifile.seekg(sizeof(size_t) + string_size); //Sets read location to database size. ifile.read((char*)database_size, sizeof(int)); //Gets database size value. //Reads the number of the last inserted key. if(*database_size > 0) { //The database has at least one key stored. std::string key; int scan = (sizeof(size_t) + string_size + sizeof(int)); //Sets read location to the first key inserted. for(int i = 1; i < *database_size; i++) { //Goes to the last key stored. ifile.seekg(scan); ifile.read((char*)&string_size, sizeof(size_t)); scan = (scan + sizeof(size_t) + string_size + sizeof(int)); ifile.seekg(scan); ifile.read((char*)&string_size, sizeof(size_t)); scan = (scan + sizeof(size_t) + string_size); } ifile.seekg(scan); ifile.read((char*)&string_size, sizeof(size_t)); //Gets size of key string on file. key.resize(string_size); ifile.read(&key[0], string_size); //Gets value of the last key string from file and store on "key". key.erase(0, 4); //Removes "key_" from "key" string for integer conversion. *last_insertion = std::stoi(key); //Defines "last_insertion" as the value of the integer conversion from "key" string. } else { //The database has no keys stored. *last_insertion = 0; } ifile.close(); //Closes file. *newindex = Index::LoadIndex(db->GetName(), dbfile, *database_size); //Generates a complete index for the database. //!(might slow down start up). } //================================================== //==================Database Loader================= Database Database::LoadDatabase(std::string dbname) { //Load and return a reference to an existing database. std::string dbfolder(basedir + "/" + dbname); //!This will not work on windows. std::string dbfile(dbfolder + "/" + dbname + ".db"); //!This will not work on windows. if(!fs::exists(dbfolder)) { //Throws a runtime error if the path the function is trying to load the database from does not exist. throw std::runtime_error("Database::LoadDatabase=inexistent_path"); } if(fs::exists(dbfile)) { //Checks if database file exists. //Checks if file is valid by comparing "dbname" with database name stored on the binary file. std::ifstream ifile(dbfile, std::ios::binary); //Opens file as input. size_t string_size; std::string temp; ifile.read((char*)&string_size, sizeof(size_t)); //Gets size of database name string on file. temp.resize(string_size); ifile.read(&temp[0], string_size); //Gets database name on file. ifile.close(); //Closes file. if(temp == dbname) { //The file exist and it's contents are valid. std::vector<Index> newindex = Index::CreateIndex(dbname); Database loadeddb(dbname, dbfolder, newindex); //Creates a database reference. //Loads relevant members to primary memory. int database_size, last_insertion; ReadDatabase(&loadeddb, &database_size, &last_insertion, &newindex); loadeddb.member_size = database_size; //Updates database size. loadeddb.member_last_insertion = last_insertion; //Updates last insertion value. loadeddb.member_index = newindex; //Updates index. return loadeddb; //Returns previouly created database reference. } else { //The file exist but it's contets are invalid. Throws a runtime error. throw std::runtime_error("Database::LoadDatabase=invalid_file"); } } else { //Throws a runtime error if the database the function is trying to load does no exist. throw std::runtime_error("Database::LoadDatabase=inexistent_file"); } } //================================================== //=================Get Name Function================ std::string Database::GetName() { //Returns the name of the database folder. return member_name; } //================================================== //=================Get Size Function================ int Database::GetSize() { //Returns size of the database. return member_size; } //================================================== //================Get Index Function================ std::vector<Index>* Database::GetIndex() { //Returns the database index. return &member_index; } //================================================== //=================Get Path Function================ std::string Database::GetDirectory() { //Returns the full path of the database folder. return member_path; } //================================================== //=================Generete New Key================= std::string Database::NewUniqueKey(void) { //Generates a ney unique key string; return("key_" + std::to_string(member_last_insertion + 1)); } //================================================== //=================Insert Key-Value================= void Database::InsertKeyValue(Datacell* newcell) { //Creates a folder with a name based on the "key" value and store "value" on it. std::string path = (member_path + "/" + member_name + ".db"); //!This will not work on windows. //Extract cell data to local variables. std::string key = newcell->GetKey(); int sorting_key = newcell->GetSortingKey(); std::string value = newcell->GetValue(); //Opens Database file std::ofstream ofile(path, std::ios::binary | std::ios::app); //Opens file as output and set to append to the end of the file. //Datacell insertion. size_t string_size = key.size(); ofile.write((char*)&string_size, sizeof(size_t)); //Inserts size of "key" string. ofile.write(&key[0], string_size); //Inserts "key" strig. ofile.write((char*)&sorting_key, sizeof(int)); //Insert sorting key integer. string_size = value.size(); ofile.write((char*)&string_size, sizeof(size_t)); //Inserts size of "value" string. ofile.write(&value[0], string_size); //Inserts "value" string. if(!ofile.good()) { //Throws an exception if writing was not successful. throw std::runtime_error("Database::InsertKeyValue=writingfailure"); } ofile.close(); ofile.open(path, std::ios::binary | std::ios::in); //Reopens file as output and set to not overwrite unwanted data. member_size++; ofile.seekp(sizeof(size_t) + member_name.size()); //Sets write location to database size. ofile.write((char*)&member_size, sizeof(int)); //Overwrites database size. ofile.close(); //Closes file. //Updates value of the last insertion to the database. key.erase(0,4); //Removes "key_" from "key" string for integer conversion. member_last_insertion = std::stoi(key); //Defines "member_last_insertion" as the value of the integer conversion from "key" string. Index::InsertIndexKey(&member_index, newcell); //Updates index. } //================================================== //=================Search Key-Value================= bool Database::SearchKeyValue(Datacell* existingcell) { //Searchs and loads key value from database file, returns true if informed key exists within the database file and false if not. //Extracts index vector key location if it exists, recieves -1 if it does not. int search_result = Index::IsValidKey(&member_index, stoi((existingcell->GetKey()).erase(0,4))); //Checks if key exist within the index file. if(search_result != -1) { //Key exists, reads value from file and returns true. std::string dbfile(member_path + "/" + member_name + ".db"); //!This will not work on windows. std::string value; value.resize(member_index[search_result].GetValueSize()); std::ifstream ifile(dbfile, std::ios::binary); //Opes file as input. ifile.seekg(member_index[search_result].GetValuePosition()); //Sets read point to desired value. ifile.read(&value[0], member_index[search_result].GetValueSize()); //Reads value to "value" string. ifile.close(); //Closes file. //Updates existing cell. existingcell->UpdateValues(existingcell->GetKey(), member_index[search_result].GetSortingKey(), value); return true; } else { //Key does not exist, return false. return false; } } //================================================== //=================Remove Key-Value================= /*? Complex Function: This function removes the desied key frpom the index, it then uses the remaining values to create a temporary (.temp) file with the contents of main .db files with the exception of the key deleted. When the writing is done, this function replaces the existing .db file with the temporary file, the database then reloads itself (mainly to update index value positions). */ bool Database::RemoveKeyValue(Database* db, Datacell* existingcell) { //Deletes an existing key stored inside the database, returns true if informed key exists within the database file and false if not. //Local references std::string dbname = db->GetName(); std::string filewithoutextension = ((db->GetDirectory()) + "/" + dbname); //!This will not work on windows. std::vector<Index>* index = db->GetIndex(); int dbsize = (db->GetSize() - 1); //Extracts index vector key location if it exists, recieves -1 if it does not. int key = stoi((existingcell->GetKey()).erase(0,4)); int search_result = Index::IsValidKey(index, key); //Checks if key exist within the index file. if(search_result != -1) { //Key exists, deletes key and its values from file and returns true. //? Check function documentation above. size_t string_size; std::string tempstring; int tempint; //Opens database file as input and creates temporary file as output. std::ifstream ifile((filewithoutextension + ".db"), std::ios::binary); std::ofstream ofile((filewithoutextension + ".temp"), std::ios::binary); //Updates datacell information (Same as value search). string_size = (*index)[search_result].GetValueSize(); tempstring.resize(string_size); ifile.seekg((*index)[search_result].GetValuePosition()); ifile.read(&tempstring[0], string_size); existingcell->UpdateValues(existingcell->GetKey(), (*index)[search_result].GetSortingKey(), tempstring); Index::RemoveIndexKey(index, key); //Removes key from index. Index::SortIndex(index, 1); //Sorts index by main key values. //Header writing to temporary file (Same as database creation). string_size = dbname.size(); ofile.write((char*)&string_size, sizeof(size_t)); ofile.write(&dbname[0], string_size); ofile.write((char*)&dbsize, sizeof(int)); for(int i = 1; i < index->size(); i++) { //Writes index information to temporary file. //Key-value writing to temporary file (Same as key insertion). string_size = (*index)[i].GetKeySize(); ofile.write((char*)&string_size, sizeof(size_t)); tempstring = ("key_" + std::to_string((*index)[i].GetKey())); ofile.write(&tempstring[0], string_size); tempint = (*index)[i].GetSortingKey(); ofile.write((char*)&tempint, sizeof(int)); string_size = (*index)[i].GetValueSize(); ofile.write((char*)&string_size, sizeof(size_t)); tempstring.resize(string_size); ifile.seekg((*index)[i].GetValuePosition()); ifile.read(&tempstring[0], string_size); ofile.write(&tempstring[0], string_size); } //Closes files. ifile.close(); ofile.close(); //Replaces main database file with the newly generated temporary file. fs::rename(filewithoutextension + ".temp", filewithoutextension + ".db"); *db = Database::LoadDatabase(dbname); return true; } else { //Key does not exist, return false. return false; } } //================================================== //==================Erase Database================== void Database::Erase() { //Deletes all files and folders related to the database. if (fs::exists(member_path)) { fs::remove_all(member_path); } } //==================================================
43.707809
171
0.55423
Iskeletu
f20bff75d668a7720e9d7bf1a7cfa39d0dfece88
1,135
cpp
C++
Source/GameWindow.cpp
sergipa/The-Creator-3D
69acf8a4ac169f96ef8ed15e6eb1a47c3a372bda
[ "MIT" ]
6
2017-11-24T06:15:40.000Z
2021-01-05T04:47:21.000Z
Source/GameWindow.cpp
sergipa/The-Creator-3D
69acf8a4ac169f96ef8ed15e6eb1a47c3a372bda
[ "MIT" ]
null
null
null
Source/GameWindow.cpp
sergipa/The-Creator-3D
69acf8a4ac169f96ef8ed15e6eb1a47c3a372bda
[ "MIT" ]
3
2017-11-21T13:11:47.000Z
2019-07-01T09:22:49.000Z
#include "GameWindow.h" #include "Application.h" #include "ModuleRenderer3D.h" #include "RenderTextureMSAA.h" #include "ComponentCamera.h" GameWindow::GameWindow() { active = true; window_name = "Game"; game_scene_width = 0; game_scene_height = 0; } GameWindow::~GameWindow() { } void GameWindow::DrawWindow() { if (ImGui::BeginDock(window_name.c_str(), false, false, false, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)) { ImVec2 size = ImGui::GetContentRegionAvail(); if (game_scene_width != size.x || game_scene_height != size.y) { if (App->renderer3D->game_camera != nullptr) { App->renderer3D->OnResize(size.x, size.y, App->renderer3D->game_camera); } game_scene_width = size.x; game_scene_height = size.y; } App->renderer3D->SetActiveTexture2D(true); if (App->renderer3D->game_camera != nullptr && App->renderer3D->game_camera->GetViewportTexture() != nullptr) { ImGui::Image((void*)App->renderer3D->game_camera->GetViewportTexture()->GetTextureID(), size, ImVec2(0, 1), ImVec2(1, 0)); } App->renderer3D->SetActiveTexture2D(false); } ImGui::EndDock(); }
25.795455
125
0.711013
sergipa
f20cf856963535ffb585dff01fe1dff5d00d992b
3,535
cpp
C++
Banking101/GoodEvent.cpp
tiberius26/Banking101
2cc5e58b4d848643ba0409427381fd9a13c68c21
[ "MIT" ]
null
null
null
Banking101/GoodEvent.cpp
tiberius26/Banking101
2cc5e58b4d848643ba0409427381fd9a13c68c21
[ "MIT" ]
null
null
null
Banking101/GoodEvent.cpp
tiberius26/Banking101
2cc5e58b4d848643ba0409427381fd9a13c68c21
[ "MIT" ]
null
null
null
#include "GoodEvent.h" GoodEvent::GoodEvent()//set some random information for the event variables { std::srand(std::time(nullptr));//set a seed for the random number generation based on time m_EventName = ""; m_Description = ""; m_ItemName = ""; m_ItemCount = 0; } void GoodEvent::EventManager(Player* Player, Debug* Debug) { if (EventChance() == true)//checks if an event should happen and carries it out { ChooseEvent(Debug, Player); DisplayEvent(Debug, Player); EnactEvent(Player); ClearEvent(); } } bool GoodEvent::EventChance() { int chance = std::rand() % 100 + 1; if (chance <= 20)// 20% chance of a good event { return true; } return false; } void GoodEvent::ChooseEvent(Debug* Debug, Player* Player) { m_EventIndex = std::rand() % 12 + 1;//determines what event to load std::fstream EventData; std::string EventDataLine; char FileToLoad[50]; sprintf_s(FileToLoad, "data/GoodEvents/GoodEvent%d.ini", m_EventIndex);//loads the data of the event EventData.open(FileToLoad); if (!EventData.is_open()) { char Failure[50]; sprintf_s(Failure, "Error reading good event file %d", m_EventIndex);//error checking... Debug->Log(Failure, Serious); } while (!EventData.eof()) { std::getline(EventData, EventDataLine); auto LineSplitter = EventDataLine.find("="); std::string Id = EventDataLine.substr(0, LineSplitter);//where to start and how much to go m_EventData[Id] = EventDataLine.substr(LineSplitter + 1, EventDataLine.size() - (LineSplitter + 1));//stores the data from the read line } EventData.close(); } void GoodEvent::DisplayEvent(Debug* Debug, Player* Player) { std::cout << std::endl << "###################################" << std::endl; std::cout <<"!"<< m_EventData["EventName"]<<"!"<<std::endl; std::cout << m_EventData["Description"] << std::endl; if (Player->CheckItems(m_EventData["ItemName"]) == false) { Player->AddItem(m_EventData["ItemName"],1); std::fstream EventArt; std::string EventArtLineLine; std::string ToDraw; SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 2); char FileToLoad[50]; sprintf_s(FileToLoad, "data/GoodEventArt/GoodEventArt%d.ini", m_EventIndex); //drawing here because I want to have different error messages and art locations without having extra checks EventArt.open(FileToLoad); if (!EventArt.is_open()) { char Failure[50]; sprintf_s(Failure, "Error reading good event art %d", m_EventIndex); Debug->Log(Failure, Serious); } while (!EventArt.eof()) { std::getline(EventArt, EventArtLineLine); ToDraw += EventArtLineLine + "\n"; } EventArt.close(); std::cout << "The item you got:" << std::endl; std::cout << ToDraw; SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7); } else { std::cout << "Unfortunatelly we cannot hold any more of these, so we sold it for 5000$ (not added to total below)" << std::endl; Player->SetMoney(5000); } } void GoodEvent::EnactEvent(Player* Player) { m_MoneyGained = stoi(m_EventData["MoneyGained"]);//aded it in a variable because I want a clear way of displaying it (line 92) instead of acessing it through the array Player->SetMoney(m_MoneyGained); std::cout << "This event brought the bank " << m_MoneyGained <<"$"<<std::endl; std::cout << std::endl << "###################################" << std::endl; system("pause"); } void GoodEvent::ClearEvent() //kept it separate so I can see it better { m_EventData.clear(); }
35.35
188
0.668741
tiberius26
f20f54b02370c97a0c316c14b2f0d563ac53bd25
1,049
cpp
C++
BZOJ/4044/dna.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
BZOJ/4044/dna.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
BZOJ/4044/dna.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cmath> #include<cstring> #define maxn 101005 #define getl(x) min(w[(x)],min(r-(x)+1,(x)-l)) #define inf 1e9 using namespace std; int t,n,w[maxn]; char dna[maxn]; bool ok(char c){ return c=='A'||c=='T'||c=='C'||c=='G'; } int count(int l,int r){ int maxl=0; int ans=r-l+1; for(int i=l+1;i<=r;++i)maxl=max(maxl,getl(i)); if(maxl*2==r-l+1)return count(l,(l+r)/2)+1; for(int i=l+1;i<=r;++i){ int k=getl(i); if(k*2-int(ceil(log(k*2)/log(2)))>=maxl){ if(i-k!=l||i+k-1!=r)ans=min(ans,count(i-k,i+k-1)+r-(i+k-1)+i-k-l); } } return ans; } int main(){ scanf("%d",&t); for(int test=0;test<t;++test){ char ch=getchar(); while(!ok(ch))ch=getchar(); for(n=0;ok(ch);++n,ch=getchar())dna[n]=ch; int ms=1,r=0; memset(w,0,sizeof(w)); for(int i=1;i<n;++i){ w[i]=min(max(0,ms+r-i),w[2*ms-i]); while(i+w[i]<n&&i-w[i]-1>=0&&dna[i+w[i]]==dna[i-w[i]-1])++w[i]; if(i+w[i]>ms+r)ms=i,r=w[i]; } printf("%d\n",count(0,n-1)); } return 0; }
22.319149
70
0.527169
sjj118
f216ab6b3df5c5c41380a9d098bcd33cbba95bb7
4,132
cpp
C++
SpectatorView/Compositor/CompositorDLL/OpenCVFrameProvider.cpp
matealex/MixedRealityCompanionKit
cbd61ca6b2a45f8dd6855995bf539cbdfe194ea7
[ "MIT" ]
204
2017-08-12T12:57:26.000Z
2019-04-25T20:22:12.000Z
SpectatorView/Compositor/CompositorDLL/OpenCVFrameProvider.cpp
Troy-Ferrell/MixedRealityCompanionKit
3ce06ce1e32e91b826d4370b6df5d28918982b2f
[ "MIT" ]
159
2017-08-12T09:38:46.000Z
2019-04-25T17:04:50.000Z
SpectatorView/Compositor/CompositorDLL/OpenCVFrameProvider.cpp
Troy-Ferrell/MixedRealityCompanionKit
3ce06ce1e32e91b826d4370b6df5d28918982b2f
[ "MIT" ]
159
2017-08-13T22:51:09.000Z
2019-05-02T02:32:55.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. #include "stdafx.h" #include "OpenCVFrameProvider.h" #if USE_OPENCV OpenCVFrameProvider::OpenCVFrameProvider() { QueryPerformanceFrequency(&freq); rgbaFrame = cv::Mat(FRAME_HEIGHT, FRAME_WIDTH, CV_8UC4); for (int i = 0; i < 4; i++) { rgbaConversion[i * 2] = i; rgbaConversion[(i * 2) + 1] = i; } for (int i = 0; i < MAX_NUM_CACHED_BUFFERS; i++) { bufferCache[i].buffer = new BYTE[FRAME_BUFSIZE]; bufferCache[i].timeStamp = 0; } captureFrameIndex = 0; } OpenCVFrameProvider::~OpenCVFrameProvider() { for (int i = 0; i < MAX_NUM_CACHED_BUFFERS; i++) { delete[] bufferCache[i].buffer; } } HRESULT OpenCVFrameProvider::Initialize(ID3D11ShaderResourceView* srv) { if (IsEnabled()) { return S_OK; } _colorSRV = srv; if (_colorSRV != nullptr) { _colorSRV->GetDevice(&_device); } HRESULT hr = E_PENDING; videoCapture = new cv::VideoCapture(CAMERA_ID); for (int i = 0; i < MAX_NUM_CACHED_BUFFERS; i++) { ZeroMemory(bufferCache[i].buffer, FRAME_BUFSIZE); } captureFrameIndex = 0; if (videoCapture->open(CAMERA_ID)) { // Attempt to update camera resolution to desired resolution. // This must be called after opening. // Note: This may fail, and your capture will resume at the camera's native resolution. // In this case, the Update loop will print an error with the expected frame resolution. videoCapture->set(cv::CAP_PROP_FRAME_WIDTH, FRAME_WIDTH); videoCapture->set(cv::CAP_PROP_FRAME_HEIGHT, FRAME_HEIGHT); if (IsEnabled()) { hr = S_OK; } } return hr; } bool OpenCVFrameProvider::IsEnabled() { if (videoCapture != nullptr) { return videoCapture->isOpened(); } return false; } void OpenCVFrameProvider::Update(int compositeFrameIndex) { if (!IsEnabled() || _colorSRV == nullptr || _device == nullptr) { return; } concurrency::create_task([=] { if (videoCapture->grab()) { LARGE_INTEGER time; QueryPerformanceCounter(&time); if (videoCapture->retrieve(frame)) { latestTimeStamp = time.QuadPart; double width = videoCapture->get(cv::CAP_PROP_FRAME_WIDTH); double height = videoCapture->get(cv::CAP_PROP_FRAME_HEIGHT); if (width != FRAME_WIDTH) { OutputDebugString(L"ERROR: captured width does not equal FRAME_WIDTH. Expecting: "); OutputDebugString(std::to_wstring(width).c_str()); OutputDebugString(L"\n"); } if (height != FRAME_HEIGHT) { OutputDebugString(L"ERROR: captured height does not equal FRAME_HEIGHT. Expecting: "); OutputDebugString(std::to_wstring(height).c_str()); OutputDebugString(L"\n"); } // Convert from rgb to rgba mixChannels(&frame, 2, &rgbaFrame, 1, rgbaConversion, 4); captureFrameIndex++; BYTE* buffer = bufferCache[captureFrameIndex % MAX_NUM_CACHED_BUFFERS].buffer; memcpy(buffer, rgbaFrame.data, FRAME_BUFSIZE); bufferCache[captureFrameIndex % MAX_NUM_CACHED_BUFFERS].timeStamp = (latestTimeStamp * S2HNS) / freq.QuadPart; } } }); const BufferCache& buffer = bufferCache[compositeFrameIndex % MAX_NUM_CACHED_BUFFERS]; if (buffer.buffer != nullptr) { DirectXHelper::UpdateSRV(_device, _colorSRV, buffer.buffer, FRAME_WIDTH * FRAME_BPP); } } void OpenCVFrameProvider::Dispose() { if (videoCapture != nullptr) { videoCapture->release(); videoCapture = nullptr; } captureFrameIndex = 0; } #endif
26.658065
126
0.593901
matealex
35ea17c6b284d5f384918c1f343ff211c8c621e2
598
cpp
C++
src/UOJ_1031 - (1619983) Accepted.cpp
miguelarauj1o/UOJ
eb195754829c42c3dcf1a68616e63da1386cb5a9
[ "MIT" ]
80
2015-01-07T01:18:40.000Z
2021-05-04T15:23:18.000Z
src/UOJ_1031 - (1619983) Accepted.cpp
miguelarauj1o/OJ
eb195754829c42c3dcf1a68616e63da1386cb5a9
[ "MIT" ]
1
2019-01-07T01:13:32.000Z
2019-01-07T01:13:32.000Z
src/UOJ_1031 - (1619983) Accepted.cpp
miguelarauj1o/OJ
eb195754829c42c3dcf1a68616e63da1386cb5a9
[ "MIT" ]
28
2015-03-05T11:53:23.000Z
2020-07-05T15:50:42.000Z
#include <cstdio> #include <vector> #define PB push_back #define SC1(a) scanf("%d", &a) #define REP(i, a, b) for (int i = (a); i <= (b); ++i) using namespace std; typedef vector<int> VI; bool crisis(int n, int k) { int p = 0; VI v; REP(i, 1, n) v.PB(i); if(v.size() > 1){ do{ v.erase(v.begin() + p); p = (p - 1 + k) % v.size(); }while(v.size() > 1); } return (v[0] == 13); } int main(int argc, char const *argv[]) { int n, r; while(SC1(n) && n) { r = 1; while(!crisis(n, r)) r++; printf("%d\n", r); } return 0; }
13.590909
54
0.4699
miguelarauj1o
35ebb0c5e0efdacfc53b3be2fbcdef1937324c1d
1,503
cpp
C++
SOURCES/falclib/token.cpp
IsraelyFlightSimulator/Negev-Storm
86de63e195577339f6e4a94198bedd31833a8be8
[ "Unlicense" ]
1
2021-02-19T06:06:31.000Z
2021-02-19T06:06:31.000Z
src/falclib/token.cpp
markbb1957/FFalconSource
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
[ "BSD-2-Clause" ]
null
null
null
src/falclib/token.cpp
markbb1957/FFalconSource
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
[ "BSD-2-Clause" ]
2
2019-08-20T13:35:13.000Z
2021-04-24T07:32:04.000Z
#include <string.h> #include <stdlib.h> #include "token.h" // MLR 12/13/2003 - Simple token parsing char *tokenStr=0; float TokenF(float def) { return(TokenF(tokenStr,def)); } float TokenF(char *str, float def) { char *bs; tokenStr=0; if(bs=strtok(str," ,\t\n")) { return((float)atof(bs)); } return(def); } int TokenI(int def) { return(TokenI(tokenStr,def)); } int TokenI(char *str, int def) { char *bs; tokenStr=0; if(bs=strtok(str," ,\t\n")) { return(atoi(bs)); } return(def); } int TokenFlags(int def, char *flagstr) { return(TokenFlags(tokenStr, def, flagstr)); } int TokenFlags(char *str, int def, char *flagstr) { char *arg; int flags=0; tokenStr=0; if(arg=strtok(str," ,\t\n")) { while(*arg) { int l; for(l=0;l<32 && flagstr[l];l++) { if(*arg==flagstr[l]) { flags|=1<<l; } } arg++; } return(flags); } return(def); } int TokenEnum(char **enumnames, int def) { return(TokenEnum(tokenStr,enumnames,def)); } int TokenEnum(char *str, char **enumnames, int def) { char *arg; int i=0; tokenStr=0; if(arg=strtok(str," ,\t\n")) { while(*enumnames) { if(stricmp(arg,*enumnames)==0) { return i; } enumnames++; i++; } } return def; } void SetTokenString(char *str) { tokenStr = str; } char *TokenStr(char *def) { return(TokenStr(tokenStr,def)); } char *TokenStr(char *str, char *def) { char *bs; tokenStr=0; if(bs=strtok(str," :,\t\n")) { return(bs); } return(def); }
11.300752
51
0.590818
IsraelyFlightSimulator
35f0d56503f8e1476114f760b630a85adb39b170
11,127
cpp
C++
volante.cpp
AraragiRukasu/interfazLAC
abd0f3e98e659fbe0459c29afad3972197f864c7
[ "BSD-3-Clause" ]
1
2019-05-20T11:52:35.000Z
2019-05-20T11:52:35.000Z
volante.cpp
AraragiRukasu/interfazLAC
abd0f3e98e659fbe0459c29afad3972197f864c7
[ "BSD-3-Clause" ]
null
null
null
volante.cpp
AraragiRukasu/interfazLAC
abd0f3e98e659fbe0459c29afad3972197f864c7
[ "BSD-3-Clause" ]
null
null
null
#include "volante.h" #include "ui_volante.h" #include <QMessageBox> #include <QtCore> #include <QtGui> #include <QTimer> #include "PC.h" #include <QtMath> #include "assert.h" //Esta ventana es homologa a la del generador (pero mas simple), referirse //a aquella para entender el funcionamiento de esta volante::volante(QWidget *parent) : QDialog(parent), ui(new Ui::volante) { ui->setupUi(this); this->setWindowTitle("Volante de Inercia"); this->setWindowFlags(Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint); mw = qobject_cast<MainWindow*>(this->parent()); send_queries = true; //Inicializacion de Labels ui->label_vol_io->setText("----"); ui->label_vol_vo->setText("----"); ui->label_vol_ibat->setText("----"); ui->label_vol_po->setText("----"); ui->label_vol_vel->setText("----"); ui->label_vol_tor->setText("----"); ui->label_vol_ener->setText("----"); blockAllSpinSignals(true); ui->spin_vol_isd_ref->setMinimum(LACAN_VAR_VOL_ISD_MIN); ui->spin_vol_isd_ref->setMaximum(LACAN_VAR_VOL_ISD_MAX); ui->spin_vol_sbyspeed_ref->setMinimum(LACAN_VAR_VOL_STANDBY_W_MIN); ui->spin_vol_sbyspeed_ref->setMaximum(LACAN_VAR_VOL_STANDBY_W_MAX); //TIMER ENCARGADO DE REFRESCAR LOS VALORES Y DE ENVIAR LAS NUEVAS CONSULTAS time_2sec = new QTimer(); connect(time_2sec, SIGNAL(timeout()), this, SLOT(timer_handler())); time_2sec->start(2000); //velocidad de refresco (en ms) send_qry_variables(); //envio las primeras consultas send_qry_references(); referenceChanged=false; editHotKey = new QShortcut(QKeySequence(tr("Ctrl+E", "Edit")), this); connect(editHotKey, SIGNAL(activated()), this, SLOT(changeEditState())); ui->label_edit->setDisabled(true); //INICIALIZAR ICONO DEL BOTON STOP QPixmap pixmap(":/Imagenes/stop_normal.png"); QIcon ButtonIcon(pixmap); ui->pushButton_stop->setIcon(ButtonIcon); } volante::~volante() { delete ui; disconnect(editHotKey, SIGNAL(activated()), this, SLOT(changeEditState())); delete editHotKey; disconnect(time_2sec, SIGNAL(timeout()), this, SLOT(timer_handler())); delete time_2sec; } void volante::timer_handler(){ static uint count = 0; if(mw->device_is_connected(LACAN_ID_VOLANTE)){ if(send_queries){ ui->pushButton_start->blockSignals(false); refresh_values(); //actualiza los valores de la pantalla count++; send_qry_variables(); if(count%5==0 || referenceChanged){ send_qry_references(); referenceChanged = false; count = 0; } } } else{ //si no esta conectado, se cierra la pantalla QMessageBox::StandardButton reply; reply = QMessageBox::warning(this,"Conexion perdida","El volante se ha desconectado de la red. Esta ventana se cerrara inmediatamente"); if(reply){ this->close(); } } } void volante::VOLpost_Handler(LACAN_MSG msg){ recibed_val.var_char[0]=msg.BYTE2; recibed_val.var_char[1]=msg.BYTE3; recibed_val.var_char[2]=msg.BYTE4; recibed_val.var_char[3]=msg.BYTE5; switch (msg.BYTE1) { case LACAN_VAR_VO_INST: vol_vo = recibed_val.var_float; break; case LACAN_VAR_IO_INST: vol_io = recibed_val.var_float; break; case LACAN_VAR_PO_INST: vol_po = recibed_val.var_float; break; case LACAN_VAR_W_INST: vol_vel = recibed_val.var_float; break; case LACAN_VAR_TORQ_INST: vol_tor = recibed_val.var_float; break; case LACAN_VAR_I_BAT_INST: vol_ibat = recibed_val.var_float; break; case LACAN_VAR_STANDBY_W_SETP: standby_ref=recibed_val.var_float; break; case LACAN_VAR_ISD_SETP: id_ref=recibed_val.var_float; break; case LACAN_VAR_MOD: actual_mode=recibed_val.var_char[0]; break; default: break; } refresh_values(); } void volante::send_qry_variables(){ mw->LACAN_Query(LACAN_VAR_VO_INST,false,dest); //vol_vo mw->LACAN_Query(LACAN_VAR_IO_INST,false,dest); //vol_io mw->LACAN_Query(LACAN_VAR_I_BAT_INST,false,dest); //vol_ibat mw->LACAN_Query(LACAN_VAR_W_INST,false,dest); //vol_vel mw->LACAN_Query(LACAN_VAR_TORQ_INST,false,dest); //vol_ibat mw->LACAN_Query(LACAN_VAR_PO_INST,false,dest); //vol_po mw->LACAN_Query(LACAN_VAR_MOD,false,dest); //modo } void volante::send_qry_references(){ mw->LACAN_Query(LACAN_VAR_ISD_SETP,false,dest); //id_ref mw->LACAN_Query(LACAN_VAR_STANDBY_W_SETP,false,dest); //standby_ref } void volante::refresh_values(){ if(double(id_ref) > refValue) ui->spin_vol_isd_ref->setEnabled(true); if(double(standby_ref) > refValue) ui->spin_vol_sbyspeed_ref->setEnabled(true); ui->spin_vol_sbyspeed_ref->setValue(double(standby_ref)); ui->spin_vol_isd_ref->setValue(double(id_ref)); double speedrev = double(vol_vel)*(2*M_PI/60); vol_ener = float(0.5 * J * speedrev * speedrev); if(double(vol_vo)>refValue) ui->label_vol_vo->setText(QString::number(double(vol_vo),'f',2)); if(double(vol_io)>refValue) ui->label_vol_io->setText(QString::number(double(vol_io),'f',2)); if(double(vol_ibat)>refValue) ui->label_vol_ibat->setText(QString::number(double(vol_ibat),'f',2)); if(double(vol_po)>refValue) ui->label_vol_po->setText(QString::number(double(vol_po),'f',2)); if(double(vol_tor)>refValue) ui->label_vol_tor->setText(QString::number(double(vol_tor),'f',2)); if(double(vol_vel)>refValue) ui->label_vol_vel->setText(QString::number(double(vol_vel),'f',2)); if(double(vol_ener)>refValue) ui->label_vol_ener->setText(QString::number(double(vol_ener),'f',2)); if(double(actual_mode)>refValue){ switch(actual_mode){ case LACAN_VAR_MOD_PREARRANQUE: ui->label_modo->setText("PREARRANQUE"); break; case LACAN_VAR_MOD_INICIO: ui->label_modo->setText("INICIO"); break; case LACAN_VAR_MOD_ARRANQUE: ui->label_modo->setText("ARRANQUE"); break; case LACAN_VAR_MOD_COMPENSACION: ui->label_modo->setText("CMPENSACION"); break; case LACAN_VAR_MOD_LIMITACION: ui->label_modo->setText("LIMITACION"); break; case LACAN_VAR_MOD_APAGADO: ui->label_modo->setText("APAGADO"); break; case LACAN_VAR_MOD_RECUPERACION: ui->label_modo->setText("RECUPERACION"); break; case LACAN_VAR_MOD_PROTEGIDO: ui->label_modo->setText("PROTEGIDO"); break; default: ui->label_modo->setText("DESCONCIDO"); } } } void volante::on_pushButton_start_clicked() { cmd=LACAN_CMD_START; mw->LACAN_Do(cmd,false,dest); assert(mw->msg_ack.back()); connect(&(mw->msg_ack.back()->ack_timer),SIGNAL(timeout()), mw, SLOT(verificarACK())); mw->agregar_log_sent(); } void volante::on_pushButton_stop_clicked() { cmd=LACAN_CMD_STOP; mw->LACAN_Do(cmd,false,dest); assert(mw->msg_ack.back()); connect(&(mw->msg_ack.back()->ack_timer),SIGNAL(timeout()), mw, SLOT(verificarACK())); mw->agregar_log_sent(); } void volante::on_pushButton_stop_released() { QPixmap pixmap(":/Imagenes/stop_normal.png"); QIcon ButtonIcon(pixmap); ui->pushButton_stop->setIcon(ButtonIcon); } void volante::on_pushButton_stop_pressed() { QPixmap pixmap(":/Imagenes/stop_press.png"); QIcon ButtonIcon(pixmap); ui->pushButton_stop->setIcon(ButtonIcon); } void volante::on_pushButton_clicked() { cmd=LACAN_CMD_ENABLE; mw->LACAN_Do(cmd,false,dest); assert(mw->msg_ack.back()); connect(&(mw->msg_ack.back()->ack_timer),SIGNAL(timeout()), mw, SLOT(verificarACK())); mw->agregar_log_sent(); } void volante::on_pushButton_shutdown_clicked() { cmd=LACAN_CMD_SHUTDOWN; mw->LACAN_Do(cmd,false,dest); assert(mw->msg_ack.back()); connect(&(mw->msg_ack.back()->ack_timer),SIGNAL(timeout()), mw, SLOT(verificarACK())); mw->agregar_log_sent(); } void volante::on_pushButton_comandar_clicked() { Comandar *comwin = new Comandar(mw,dest); comwin->setAttribute(Qt::WA_DeleteOnClose); comwin->setModal(true); comwin->show(); } void volante::closeEvent(QCloseEvent *e){ time_2sec->stop(); emit volWindowsClosed(); QDialog::closeEvent(e); } void volante::processEditingFinished(QDoubleSpinBox* spin, uint16_t var, float prevValue) { blockAllSpinSignals(true); spin->clearFocus(); data_can data; float value = float(spin->value()); QMessageBox::StandardButton reply; QString str = "El valor a enviar es: "; str.append(QString::number(double(value))); str.append(". Confirma que desea enviar este valor?"); reply=QMessageBox::question(this,"Valor a enviar",str,QMessageBox::Yes|QMessageBox::No); if(reply==QMessageBox::Yes){ data.var_float = value; //si esta seleccionado algo que no sea modo, manda el valor de spin mw->LACAN_Set(var, data, 1, dest); mw->agregar_log_sent(); referenceChanged = true; } blockAllSpinSignals(false); spin->setValue(double(prevValue)); ui->edit_checkBox->setCheckState(Qt::CheckState::Unchecked); } void volante::blockAllSpinSignals(bool b){ ui->spin_vol_isd_ref->blockSignals(b); ui->spin_vol_sbyspeed_ref->blockSignals(b); } void volante::on_spin_vol_sbyspeed_ref_editingFinished() { processEditingFinished(ui->spin_vol_sbyspeed_ref, LACAN_VAR_STANDBY_W_SETP, standby_ref); } void volante::on_spin_vol_isd_ref_editingFinished() { processEditingFinished(ui->spin_vol_isd_ref, LACAN_VAR_ISD_SETP, id_ref); } void volante::on_edit_checkBox_stateChanged(int check) { if(check){ send_queries = false; ui->pushButton_start->blockSignals(true); ui->pushButton_comandar->setDisabled(true); ui->pushButton_start->setDisabled(true); ui->pushButton_stop->setDisabled(true); ui->pushButton_shutdown->setDisabled(true); ui->spin_vol_sbyspeed_ref->clearFocus(); ui->spin_vol_isd_ref->clearFocus(); blockAllSpinSignals(false); ui->spin_vol_sbyspeed_ref->setReadOnly(false); ui->spin_vol_isd_ref->setReadOnly(false); ui->label_edit->setEnabled(true); }else{ send_queries = true; ui->pushButton_comandar->setDisabled(false); ui->pushButton_start->setDisabled(false); ui->pushButton_stop->setDisabled(false); ui->pushButton_shutdown->setDisabled(false); blockAllSpinSignals(true); ui->spin_vol_sbyspeed_ref->setReadOnly(true); ui->spin_vol_isd_ref->setReadOnly(true); ui->label_edit->setDisabled(true); } } void volante::changeEditState() { ui->edit_checkBox->toggle(); }
30.652893
144
0.662892
AraragiRukasu
35f78f425e52fe462ade87bf2df6da28376329b8
6,076
hpp
C++
SDK/ARKSurvivalEvolved_Buff_GrabbedByBeam_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_Buff_GrabbedByBeam_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_Buff_GrabbedByBeam_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Buff_GrabbedByBeam_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Buff_GrabbedByBeam.Buff_GrabbedByBeam_C // 0x0065 (0x09C5 - 0x0960) class ABuff_GrabbedByBeam_C : public ABuff_Base_C { public: float maxDistanceToApplyImpulse; // 0x0960(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float maxImpulseToInstigator; // 0x0964(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float minImpulseToInstigator; // 0x0968(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float minDistanceToApplyImpulse; // 0x096C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float maxAdditionalMultiplier; // 0x0970(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float minAdditionalMultiplier; // 0x0974(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float maxWeightForCalculationns; // 0x0978(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float minWeightForCalculations; // 0x097C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float logDeviation; // 0x0980(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float minProgressDeltaBasedOnDistance; // 0x0984(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float maxProgressDeltaBasedOnDistance; // 0x0988(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float maxProgress; // 0x098C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float RequiredLookDirDotToCapture; // 0x0990(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float maxProgressMultiplierForMinWeight; // 0x0994(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) bool bIsInitialized; // 0x0998(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData00[0x3]; // 0x0999(0x0003) MISSED OFFSET float CurrentBeamProgress; // 0x099C(0x0004) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float additionalMultiplier; // 0x09A0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float maxProgressMultiplierForMaxWeight; // 0x09A4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float maxAngleForCalculations; // 0x09A8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) struct FVector ParentSkiff_CurrentBeamStartLoc; // 0x09AC(0x000C) (Edit, BlueprintVisible, ZeroConstructor, Transient, DisableEditOnInstance, IsPlainOldData) struct FVector ParentSkiff_CurrentBeamEndLoc; // 0x09B8(0x000C) (Edit, BlueprintVisible, ZeroConstructor, Transient, DisableEditOnInstance, IsPlainOldData) TEnumAsByte<E_HoverSkiffBeamState> ParentSkiff_CurrentBeamState; // 0x09C4(0x0001) (Edit, BlueprintVisible, ZeroConstructor, Transient, DisableEditOnInstance, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass Buff_GrabbedByBeam.Buff_GrabbedByBeam_C"); return ptr; } void ReceiveSkiffVars(const struct FVector& BeamStartLoc, const struct FVector& BeamEndLoc, TEnumAsByte<E_HoverSkiffBeamState> BeamState); void GetBeamCapturePercent(float* Percent); float GetOwnerDragWeight(); void GetMaxProgress(float* maxProgress); void Calculate_Progress(float timeDelta, float* NewProgress); void CalculateBeamProgressDelta(float timeDelta, float* ProgressDelta, bool* bInvalidProgress); void InitializeBuff(float MaxBeamLength); void BuffTickServer(float* DeltaTime); void UserConstructionScript(); void ExecuteUbergraph_Buff_GrabbedByBeam(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
85.577465
219
0.574062
2bite
35fa0fa040dadf8a7258780224d795dd69d2af02
3,008
cpp
C++
modules/task_2/belyaev_i_readers_writers/main.cpp
Gurgen-Arm/pp_2021_autumn
ad549e49d765612c4544f34b04c9eb9432ac0dc7
[ "BSD-3-Clause" ]
null
null
null
modules/task_2/belyaev_i_readers_writers/main.cpp
Gurgen-Arm/pp_2021_autumn
ad549e49d765612c4544f34b04c9eb9432ac0dc7
[ "BSD-3-Clause" ]
null
null
null
modules/task_2/belyaev_i_readers_writers/main.cpp
Gurgen-Arm/pp_2021_autumn
ad549e49d765612c4544f34b04c9eb9432ac0dc7
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2021 Belyaev Ilya #include <gtest/gtest.h> #include "./readers_writers.h" #include <gtest-mpi-listener.hpp> TEST(r_w_MPI, no_one) { int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); if (rank == 0) { storage(rank, 1); } MPI_Barrier(MPI_COMM_WORLD); ASSERT_NO_THROW(); } TEST(r_w_MPI, equally) { int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); if (rank == 0) { storage(rank, size); } else { if (rank % 2 == 0) { readers(rank); } else { writers(rank); } } MPI_Barrier(MPI_COMM_WORLD); ASSERT_NO_THROW(); } TEST(r_w_MPI, only_w) { int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); if (rank == 0) { storage(rank, size); } else { writers(rank); } MPI_Barrier(MPI_COMM_WORLD); ASSERT_NO_THROW(); } TEST(r_w_MPI, only_r) { int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); if (rank == 0) { storage(rank, size); } else { readers(rank); } MPI_Barrier(MPI_COMM_WORLD); ASSERT_NO_THROW(); } TEST(r_w_MPI, one_w) { int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); if (rank == 0) { storage(rank, size); } else { if (rank == 1) { writers(rank); } else { readers(rank); } } MPI_Barrier(MPI_COMM_WORLD); ASSERT_NO_THROW(); } TEST(r_w_MPI, two_w) { int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); if (rank == 0) { storage(rank, size); } else { if (rank == 2 || rank == 1) { writers(rank); } else { readers(rank); } } MPI_Barrier(MPI_COMM_WORLD); ASSERT_NO_THROW(); } TEST(r_w_MPI, One_r) { int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); if (rank == 0) { storage(rank, size); } else { if (rank == 1) { readers(rank); } else { writers(rank); } } MPI_Barrier(MPI_COMM_WORLD); ASSERT_NO_THROW(); } TEST(r_w_MPI, two_r) { int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); if (rank == 0) { storage(rank, size); } else { if (rank == 2 || rank == 1) { readers(rank); } else { writers(rank); } } MPI_Barrier(MPI_COMM_WORLD); ASSERT_NO_THROW(); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); MPI_Init(&argc, &argv); std::srand(std::time(nullptr)); ::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment); ::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance()->listeners(); listeners.Release(listeners.default_result_printer()); listeners.Release(listeners.default_xml_generator()); listeners.Append(new GTestMPIListener::MPIMinimalistPrinter); return RUN_ALL_TESTS(); }
18.918239
76
0.636636
Gurgen-Arm
35fa77ab7dcf25fb1f09a7989d6438fb113416f6
3,852
cpp
C++
src/type_lookup_table.cpp
syoummer/boost.actor
58f35499bac8871b8f5b0b024246a467b63c6fb0
[ "BSL-1.0" ]
2
2015-03-20T21:11:16.000Z
2020-01-20T08:05:41.000Z
src/type_lookup_table.cpp
syoummer/boost.actor
58f35499bac8871b8f5b0b024246a467b63c6fb0
[ "BSL-1.0" ]
null
null
null
src/type_lookup_table.cpp
syoummer/boost.actor
58f35499bac8871b8f5b0b024246a467b63c6fb0
[ "BSL-1.0" ]
null
null
null
/******************************************************************************\ * * * ____ _ _ _ * * | __ ) ___ ___ ___| |_ / \ ___| |_ ___ _ __ * * | _ \ / _ \ / _ \/ __| __| / _ \ / __| __/ _ \| '__| * * | |_) | (_) | (_) \__ \ |_ _ / ___ \ (__| || (_) | | * * |____/ \___/ \___/|___/\__(_)_/ \_\___|\__\___/|_| * * * * * * * * Copyright (C) 2011 - 2014 * * Dominik Charousset <dominik.charousset@haw-hamburg.de> * * * * Distributed under the Boost Software License, Version 1.0. See * * accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt * \******************************************************************************/ #include <algorithm> #include "boost/actor/singletons.hpp" #include "boost/actor/type_lookup_table.hpp" #include "boost/actor/detail/uniform_type_info_map.hpp" namespace boost { namespace actor { type_lookup_table::type_lookup_table() { auto uti_map = get_uniform_type_info_map(); auto get = [=](const char* cstr) { return uti_map->by_uniform_name(cstr); }; emplace(1, get("@<>+@atom")); emplace(2, get("@<>+@atom+@u32")); emplace(3, get("@<>+@atom+@proc")); emplace(4, get("@<>+@atom+@proc+@u32")); emplace(5, get("@<>+@atom+@proc+@u32+@u32")); emplace(6, get("@<>+@atom+@actor")); emplace(7, get("@<>+@atom+@u32+@str")); } auto type_lookup_table::by_id(std::uint32_t id) const -> pointer { auto i = find(id); return (i == m_data.end() || i->first != id) ? nullptr : i->second; } auto type_lookup_table::by_name(const std::string& name) const -> pointer { auto e = m_data.end(); auto i = std::find_if(m_data.begin(), e, [&](const value_type& val) { return val.second->name() == name; }); return (i != e) ? i->second : nullptr; } std::uint32_t type_lookup_table::id_of(const std::string& name) const { auto e = m_data.end(); auto i = std::find_if(m_data.begin(), e, [&](const value_type& val) { return val.second->name() == name; }); return (i != e) ? i->first : 0; } std::uint32_t type_lookup_table::id_of(pointer uti) const { auto e = m_data.end(); auto i = std::find_if(m_data.begin(), e, [&](const value_type& val) { return val.second == uti; }); return (i != e) ? i->first : 0; } void type_lookup_table::emplace(std::uint32_t id, pointer instance) { BOOST_ACTOR_REQUIRE(instance != nullptr); value_type kvp{id, instance}; auto i = find(id); if (i == m_data.end()) m_data.push_back(std::move(kvp)); else if (i->first == id) throw std::runtime_error("key already defined"); else m_data.insert(i, std::move(kvp)); } auto type_lookup_table::find(std::uint32_t arg) const -> const_iterator { return std::lower_bound(m_data.begin(), m_data.end(), arg, [](const value_type& lhs, std::uint32_t id) { return lhs.first < id; }); } auto type_lookup_table::find(std::uint32_t arg) -> iterator { return std::lower_bound(m_data.begin(), m_data.end(), arg, [](const value_type& lhs, std::uint32_t id) { return lhs.first < id; }); } std::uint32_t type_lookup_table::max_id() const { return m_data.empty() ? 0 : m_data.back().first; } } // namespace actor } // namespace boost
38.138614
108
0.482606
syoummer
35facbd9a9c7e6f5ce5145cf473a1c131a841db0
708
cxx
C++
cpp_fund/explicit.cxx
jsrdzhk/algo_snippet
a929f73db1ad14468f12ee45d503cdba8ed12f40
[ "MIT" ]
null
null
null
cpp_fund/explicit.cxx
jsrdzhk/algo_snippet
a929f73db1ad14468f12ee45d503cdba8ed12f40
[ "MIT" ]
null
null
null
cpp_fund/explicit.cxx
jsrdzhk/algo_snippet
a929f73db1ad14468f12ee45d503cdba8ed12f40
[ "MIT" ]
null
null
null
/* * @title: todo * @author: Rodney Cheung * @date: 2021-07-15 11:20:53 * @last_author: Rodney Cheung * @last_edit_time: 2021-07-15 11:41:04 */ #include "precompiled_headers.h" class SalesData{ private: std::string data; public: explicit SalesData(const std::string& d):data(d){ } explicit operator bool(){ return !data.empty(); } static void output(SalesData salesData){ std::cout<<salesData.data<<std::endl; } }; int main(){ SalesData::output(static_cast<SalesData>(std::string("kask"))); SalesData s(static_cast<SalesData>(std::string("kask"))); if(s){ std::cout<<std::boolalpha<<static_cast<bool>(s)<<std::endl; } }
20.228571
67
0.620056
jsrdzhk
35fc424d216a117737ceaf67217967c836a22f89
778
cpp
C++
quick-sort.cpp
zhiwei1988/leetcode_20211220
d158c5ec567381610f4d442d427df7fa035dcd84
[ "MIT" ]
null
null
null
quick-sort.cpp
zhiwei1988/leetcode_20211220
d158c5ec567381610f4d442d427df7fa035dcd84
[ "MIT" ]
null
null
null
quick-sort.cpp
zhiwei1988/leetcode_20211220
d158c5ec567381610f4d442d427df7fa035dcd84
[ "MIT" ]
null
null
null
// // Created by zhiwei on 1/6/2022. // #include "playground.h" int Partition(vector<int> &nums, int left, int right) { int pivot = nums[right]; // 每次取最右边的值为锚点 int wall = left; for (int i = left; i < right; i++) { if (nums[i] < pivot) { swap(nums[i], nums[wall]); wall++; } } swap(nums[wall], nums[right]); return wall; } void Helper(vector<int> &nums, int left, int right) { if (left >= right) { return; } int pivot = Partition(nums, left, right); Helper(nums, left, pivot - 1); Helper(nums, pivot + 1, right); } void QuickSort(vector<int> &nums) { Helper(nums, 0, nums.size() - 1); } int main() { vector<int> nums = {3, 2, 1, 4}; QuickSort(nums); return 0; }
16.913043
53
0.537275
zhiwei1988
c40066c5064027015912264a6e188cbdf6eec19a
1,128
cpp
C++
common/modifiers.cpp
kirmorozov/PHP-CPP
fde096ca0a23c33c63e7c5f529891e9b679601a1
[ "Apache-2.0" ]
1,027
2015-01-05T02:52:17.000Z
2022-03-26T22:30:14.000Z
common/modifiers.cpp
kirmorozov/PHP-CPP
fde096ca0a23c33c63e7c5f529891e9b679601a1
[ "Apache-2.0" ]
312
2015-01-01T08:58:12.000Z
2022-03-31T09:26:55.000Z
common/modifiers.cpp
kirmorozov/PHP-CPP
fde096ca0a23c33c63e7c5f529891e9b679601a1
[ "Apache-2.0" ]
324
2015-01-06T01:57:21.000Z
2022-03-31T14:13:49.000Z
/** * Modifiers.cpp * * In this file an enumeration type is with the possible * member modifiers * * @author Martijn Otto <martijn.otto@copernica.com> * @author Emiel Bruijntjes <emiel.bruijntjes@copernica.com> * * @copyright 2014 Copernica BV */ #include "includes.h" #include <php.h> /** * Set up namespace */ namespace Php { /** * The modifiers are constants */ #if PHP_VERSION_ID >= 70400 const int Static = 0x10; const int Abstract = 0x40; const int Final = 0x20; const int Public = 0x01; const int Protected = 0x02; const int Private = 0x04; const int Const = 0; #else const int Static = 0x01; const int Abstract = 0x02; const int Final = 0x04; const int Public = 0x100; const int Protected = 0x200; const int Private = 0x400; const int Const = 0; #endif /** * Modifiers that are supported for methods and properties */ const int MethodModifiers = Final | Public | Protected | Private | Static; const int PropertyModifiers = Final | Public | Protected | Private | Const | Static; /** * End namespace */ }
22.117647
94
0.643617
kirmorozov
c402043b18d94d4c0494ca395f02ff742d138ad8
8,995
hpp
C++
lib/strict_variant_0.3/include/strict_variant/variant_dispatch.hpp
garbageslam/libwml
c50bc4595c0c86864cd41dbfa80a522e674e0c2f
[ "WTFPL" ]
1
2022-03-18T23:56:54.000Z
2022-03-18T23:56:54.000Z
lib/strict_variant_0.3/include/strict_variant/variant_dispatch.hpp
garbageslam/libwml
c50bc4595c0c86864cd41dbfa80a522e674e0c2f
[ "WTFPL" ]
null
null
null
lib/strict_variant_0.3/include/strict_variant/variant_dispatch.hpp
garbageslam/libwml
c50bc4595c0c86864cd41dbfa80a522e674e0c2f
[ "WTFPL" ]
null
null
null
// (C) Copyright 2016 Christopher Beck // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <strict_variant/mpl/find_with.hpp> #include <strict_variant/mpl/nonstd_traits.hpp> #include <strict_variant/mpl/std_traits.hpp> #include <strict_variant/mpl/typelist.hpp> #include <strict_variant/mpl/ulist.hpp> #include <strict_variant/variant_fwd.hpp> #include <type_traits> #include <utility> #ifdef STRICT_VARIANT_DEBUG #include <cassert> #define STRICT_VARIANT_ASSERT(X) \ do { \ assert((X)); \ } while (0) #else // STRICT_VARIANT_DEBUG #define STRICT_VARIANT_ASSERT(X) \ do { \ static_cast<void>(X); \ } while (0) #endif // STRICT_VARIANT_DEBUG namespace strict_variant { namespace detail { /*** * Dispatch mechanism: * These two templates are used to dispatch visitor objects to * the variant's storage. The problem that is being solved here is, * how do we actually recover type information from the runtime * value of `m_which`, so that we can call the appropriate overload * of a visitor to the variant. */ /// Function which evaluates a visitor against a variant's internals /// Reinteprets the "storage" as a value of type T or const T, /// then applies the visitor object. #define RESULT_EXPR \ std::forward<Visitor>(v)(std::forward<Storage>(s).template get_value<index>(Internal())) template <unsigned index, typename Internal, typename Storage, typename Visitor> auto visitor_caller(Storage && s, Visitor && v) noexcept(noexcept(RESULT_EXPR)) -> decltype(RESULT_EXPR) { return RESULT_EXPR; } #undef RESULT_EXPR /// Helper which figures out the return type of multiple visitor calls /// It's better for this to be separate of the dispatch mechanism, because /// std::common_type can technically be order dependent. It's confusing if the /// return type can change depending on the dispatch strategy used, and it /// simplifies the dispatch code to only have to implement this once. template <typename Internal, typename Storage, typename Visitor> struct return_typer { #define RESULT_EXPR \ visitor_caller<index, Internal, Storage>(std::forward<Storage>(std::declval<Storage>()), \ std::forward<Visitor>(std::declval<Visitor>())) template <unsigned index> struct at_index { using type = decltype(RESULT_EXPR); }; template <unsigned index> struct noexcept_prop { static constexpr bool value = noexcept(RESULT_EXPR); using type = std::integral_constant<bool, value>; }; #undef RESULT_EXPR }; /// Helper object which dispatches a visitor object to the appropriate /// interpretation of our storage value, based on value of "which". /// /// The solution here is that for each possible value of `which`, we create an /// appropriate function using the above function template, and store them each /// in an array, using parameter pack expansion. (A little 'jump table'.) /// /// Then we dereference the array at index `m_which` and call that function. /// This means we pick out the right function very quickly, but it may not be /// inlined by the compiler even if it is small. template <typename return_t, typename Internal, typename ulist> struct jumptable_dispatch; template <typename return_t, typename Internal, unsigned... Indices> struct jumptable_dispatch<return_t, Internal, mpl::ulist<Indices...>> { template <typename Storage, typename Visitor> return_t operator()(const unsigned int which, Storage && storage, Visitor && visitor) { using whichCaller = return_t (*)(Storage, Visitor); static whichCaller callers[sizeof...(Indices)] = { &visitor_caller<Indices, Internal, Storage, Visitor>...}; STRICT_VARIANT_ASSERT(which < static_cast<unsigned int>(sizeof...(Indices))); return (*callers[which])(std::forward<Storage>(storage), std::forward<Visitor>(visitor)); } }; /// Same as the above, but we use a different strategy based on a binary tree, /// and repeated testing of the "which" value. /// /// The idea is that if there are multiple types, we just test if we are looking /// in the first half or the second half, and branch to two different /// instantiations of the binary_search_dispatch object as appropriate. /// /// When arranged this way, the compiler can always inline the visitor calls, /// and so for variants with few types this may be significantly faster. /// /// The "which" value is not changed even as the type list gets smaller, /// instead, the "base" value is increased. template <typename return_t, typename Internal, unsigned int base, unsigned int num_types> struct binary_search_dispatch { static_assert(num_types >= 2, "Something wrong with binary search dispatch"); static constexpr unsigned int half = num_types / 2; template <typename Storage, typename Visitor> return_t operator()(const unsigned int which, Storage && storage, Visitor && visitor) { if (which < base + half) { return binary_search_dispatch<return_t, Internal, base, half>{}( which, std::forward<Storage>(storage), std::forward<Visitor>(visitor)); } else { return binary_search_dispatch<return_t, Internal, base + half, num_types - half>{}( which, std::forward<Storage>(storage), std::forward<Visitor>(visitor)); } } }; template <typename return_t, typename Internal, unsigned int base> struct binary_search_dispatch<return_t, Internal, base, 1u> { template <typename Storage, typename Visitor> return_t operator()(const unsigned int which, Storage && storage, Visitor && visitor) { STRICT_VARIANT_ASSERT(which == base); return visitor_caller<base, Internal, Storage, Visitor>(std::forward<Storage>(storage), std::forward<Visitor>(visitor)); } }; /// Choose the jumptable dispatch strategy when the number of types is > switch /// point /// choose the binary search dispatch for less than that. /// Tentatively choosing 4 for switch point, potentially 8 is better... ? /// Needs more rigorous benchmarking template <typename Internal, size_t num_types> struct visitor_dispatch { // static constexpr unsigned int switch_point = 4; // Helper which takes the conjunction of a typelist of `std::integral_constant<bool>`. template <typename T> struct conjunction; template <typename... Types> struct conjunction<mpl::TypeList<Types...>> { template <typename T> struct is_false_prop : std::is_same<T, std::integral_constant<bool, false>> {}; static constexpr bool value = !mpl::Find_Any<is_false_prop, Types...>::value; }; // Helper which figures out return type and noexcept status, for given storage and visitor template <typename Storage, typename Visitor> struct call_helper { using rtyper = return_typer<Internal, Storage, Visitor>; using indices = mpl::count_t<num_types>; static constexpr bool noexcept_value = conjunction<mpl::ulist_map_t<rtyper::template noexcept_prop, indices>>::value; using return_type = typename mpl::typelist_fwd<mpl::common_return_type_t, mpl::ulist_map_t<rtyper::template at_index, indices>>::type; }; // Invoke the actual dispatcher template <typename Storage, typename Visitor> auto operator()(const unsigned int which, Storage && storage, Visitor && visitor) noexcept(call_helper<Storage, Visitor>::noexcept_value) -> typename call_helper<Storage, Visitor>::return_type { using return_t = typename call_helper<Storage, Visitor>::return_type; // using chosen_dispatch_t = jumptable_dispatch<return_t, Internal, mpl::count_t<num_types>>; // using chosen_dispatch_t = // typename std::conditional<(num_types > switch_point), // jumptable_dispatch<return_t, Internal, mpl::count_t<num_types>>, // binary_search_dispatch<return_t, Internal, 0, // num_types>>::type; using chosen_dispatch_t = binary_search_dispatch<return_t, Internal, 0, num_types>; return chosen_dispatch_t{}(which, std::forward<Storage>(storage), std::forward<Visitor>(visitor)); } }; } // end namespace detail } // end namespace strict_variant #undef STRICT_VARIANT_ASSERT
39.800885
100
0.662813
garbageslam
c404c9bd1852b6a0b6a16a8985f4edd9e05ff1a1
3,677
cpp
C++
tools/src/fmlhpp32.cpp
georgekap1an/tuxpp
eb62d765b029c63c35a35375fb040227c7e7d96b
[ "MIT" ]
null
null
null
tools/src/fmlhpp32.cpp
georgekap1an/tuxpp
eb62d765b029c63c35a35375fb040227c7e7d96b
[ "MIT" ]
null
null
null
tools/src/fmlhpp32.cpp
georgekap1an/tuxpp
eb62d765b029c63c35a35375fb040227c7e7d96b
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <string> #include <sstream> #include <iomanip> #include <cstring> #include <map> #include <vector> #include <algorithm> #include "fml32.h" using namespace std; map<string, int> field_types = { {"short", FLD_SHORT}, {"long", FLD_LONG}, {"char", FLD_CHAR}, {"float", FLD_FLOAT}, {"double", FLD_DOUBLE}, {"string", FLD_STRING}, {"carray", FLD_CARRAY}, {"mbstring", FLD_MBSTRING}, {"ptr", FLD_PTR}, {"fml32", FLD_FML32}, {"view32", FLD_VIEW32} }; struct field_def { string name; int number = 0; FLDID32 id = 0; string type_str; }; bool starts_with(string const& source, string const& pattern) { if(source.size() < pattern.size()) { return false; } return memcmp(source.data(), pattern.data(), pattern.size()) == 0; } vector<field_def> read_input(istream& is) { vector<field_def> result; string line; int base = 0; while(getline(is, line)) { if(line.empty() || line[0] == '#') { continue; } else if(starts_with(line, "*base")) { base = stoi(line.substr(5)); } else { string name, type_str; int number = 0; stringstream s(line); s >> name >> number >> type_str; if(name.empty() || type_str.empty()) { continue; } number += base; FLDID32 id = Fmkfldid32(field_types[type_str], number); if(id == BADFLDID) { throw runtime_error(line + "[" + Fstrerror32(Ferror32) + "]"); } field_def f; f.name = name; f.number = number; f.id = id; f.type_str = type_str; result.push_back(f); } } return result; } size_t get_max_name_size(vector<field_def> const& fields) { size_t result = 0; for(auto&& f : fields) { result = max(result, f.name.size()); } return result; } void write_output(ostream& os, vector<field_def> const& fields) { size_t name_width = get_max_name_size(fields); os << R"( #include "fml32.h" namespace field32 { )"; for(auto&& f : fields) { os << "const FLDID32 " << setw(name_width) << left << f.name << " = " << setw(12) << f.id << "; // number: " << setw(12) << f.number << " type: " << f.type_str << "\n"; } os << "} // end namespace" << endl; } int main(int argc, char** argv) { try { string program_name = argv[0]; if(argc < 3) { throw runtime_error("Usage: " + program_name + " INPUT_FILE OUTPUT_FILE"); } string input_file_name = argv[1]; string output_file_name = argv[2]; ifstream is(input_file_name); if(!is) { throw runtime_error("error reading from " + input_file_name); } ofstream os(output_file_name); if(!os) { throw runtime_error("error opening " + output_file_name + " for write"); } write_output(os, read_input(is)); return 0; } catch(exception const& e) { cerr << "error: " << e.what() << endl; return 1; } }
25.013605
86
0.468045
georgekap1an
c406b67425e72a0706e0b857c7b610d383085ed7
1,285
cpp
C++
firmware/communicator.cpp
rustbuggy/sharprust
8a72b0bed544216529d8a65012be23ca2790a995
[ "MIT" ]
null
null
null
firmware/communicator.cpp
rustbuggy/sharprust
8a72b0bed544216529d8a65012be23ca2790a995
[ "MIT" ]
null
null
null
firmware/communicator.cpp
rustbuggy/sharprust
8a72b0bed544216529d8a65012be23ca2790a995
[ "MIT" ]
null
null
null
#include "communicator.h" #include "buggy.h" #define TELEMETRY_SEND_INTERVAL_MS 20 Communicator::Communicator() : rx_len(0), tx_len(0), hdlc(rx_buffer, 255) { } Communicator::~Communicator() { } void Communicator::setup() { SERIALDEV.begin(57600); } void Communicator::send_telemetry(bc_telemetry_packet_t& telemetry) { if (send_telemetry_timer.start_or_triggered(telemetry.time, TELEMETRY_SEND_INTERVAL_MS, false, true)) { tx_len = hdlc.encode((uint8_t*) &telemetry, sizeof(bc_telemetry_packet_t), tx_buffer); SERIALDEV.write(tx_buffer, tx_len); } } drive_cmd_t& Communicator::read_command(bc_telemetry_packet_t& telemetry) { drive_cmd.received = false; while (SERIALDEV.available() > 0) { rx_len = hdlc.decode(SERIALDEV.read()); // check if HDLC packet is received if (rx_len > 0) { uint8_t header = ((uint8_t*) rx_buffer)[0]; if (CB_MOTOR_COMMAND == header) { cb_motor_command_packet_t* motor = (cb_motor_command_packet_t*) rx_buffer; drive_cmd.received = true; drive_cmd.automatic = motor->automatic; drive_cmd.steering_pwm = motor->steering_pwm; drive_cmd.driving_pwm = motor->driving_pwm; } } } Buggy::clamp_steering_and_speed(drive_cmd); return drive_cmd; }
25.7
105
0.703502
rustbuggy
c410f0432ed40acfb602906bd40567884995f094
4,384
hxx
C++
src/B200Control.hxx
kb1vc/SoDaRadio
0a41fa3d795b1c93795ad62ad17bf2de5f60a752
[ "BSD-2-Clause" ]
14
2017-10-27T16:01:05.000Z
2021-03-16T08:12:42.000Z
src/B200Control.hxx
dd0vs/SoDaRadio
0a41fa3d795b1c93795ad62ad17bf2de5f60a752
[ "BSD-2-Clause" ]
11
2017-09-16T03:13:11.000Z
2020-12-11T09:11:35.000Z
src/B200Control.hxx
dd0vs/SoDaRadio
0a41fa3d795b1c93795ad62ad17bf2de5f60a752
[ "BSD-2-Clause" ]
6
2017-09-13T12:47:43.000Z
2020-12-02T20:54:25.000Z
/* Copyright (c) 2015, Matthew H. Reilly (kb1vc) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef B200Serial_HDR #define B200Serial_HDR #include "TRControl.hxx" #include "IPSockets.hxx" #include <string> #include <list> #include <boost/format.hpp> #include <iostream> #include <uhd/usrp/multi_usrp.hpp> namespace SoDa { /** * @brief B2xxy-z subtypes for simplified usage (DD0VS) * * This is a workaraound, to integrate B200mini (Sept 2019) into * SoDaRadio. * All specific action for B200/B210/B2xx are not carried out for * B200mini. * On specific places special care will be taken for B200mini only. * In a first attempt TX/RX relay switching will be implemented via * B200mini GPIO pin. Today (16th of Feb 2020, all versions of B2xx * have GPIOs). To avoid interferences with the original code only * B200mini specific actions will be carried, the others are kept * functional. */ typedef enum { eB200, // e = enum; B200 seems to be defined somewhere else eB210, eB200mini, eB200mini_i, eB205mini_i } SoDa_B200_type_t; /** * @brief Transmit/Receive switch control for B200/B210 via the * FX3 debug GPIO pins. * * This module requires a special version of the B2x0 fpga firmware. * * On TRANSMIT, pin 1 of J400 will be pulled HIGH. On RECEIVE * pin 1 of J400 will be pulled LOW. * On TRANSMIT, pin 3 of J400 will be pulled LOW. On RECEIVE * pin 1 of J400 will be pulled HIGH. */ class B200Control : public TRControl { public: /** * @brief constructor * @param usrp a pointer to the radio object * @param mboard which B200 object in the usrp * */ B200Control(uhd::usrp::multi_usrp::sptr usrp, int mboard = 0); /** * @brief activate external controls to enable transmit mode. * @return true if the operation completed successfully */ bool setTXOn(); /** * @brief activate external controls to disable transmit mode. * @return true if the operation completed successfully */ bool setTXOff(); /** * @brief report state of transmit-enable. * @return true iff the transmitter is currently enabled. */ bool getTX(); /** * @brief turn on/off signal path for selected band * note that multiple bands can be enabled at one time(!) * * @param band band selector (typically index from 1...7) * @param state true to enable band, false otherwise. * @return true if band state was changed. */ bool setBand(unsigned int band, bool state); /** * @brief query state of signal path for selected band * * @param band band selector (typically index from 1...7) * @return true if band signal path is enabled. */ bool getBand(unsigned int band); private: bool sendCommand(const std::string & cmd, int retry_count); uhd::usrp::multi_usrp::sptr usrp; int mboard; SoDa_B200_type_t B200_type; //see comment above std::string modelname; //is redundant, but used for simpler programming }; } #endif
33.465649
76
0.697765
kb1vc
c414c54065c421c49d58c31d44f944112adfe4a8
689
cpp
C++
experiments/InternalOscillatorCalibration/src/main.cpp
chacal/arduino
6b77e59138a36d0627ab6f529e6f2ea7e65bcdfd
[ "Apache-2.0" ]
4
2016-12-10T13:20:52.000Z
2019-10-25T19:47:44.000Z
experiments/InternalOscillatorCalibration/src/main.cpp
chacal/arduino
6b77e59138a36d0627ab6f529e6f2ea7e65bcdfd
[ "Apache-2.0" ]
null
null
null
experiments/InternalOscillatorCalibration/src/main.cpp
chacal/arduino
6b77e59138a36d0627ab6f529e6f2ea7e65bcdfd
[ "Apache-2.0" ]
1
2019-05-03T17:31:38.000Z
2019-05-03T17:31:38.000Z
#include "Arduino.h" int initialValue = OSCCAL; void setup() { OSCCAL = 152; Serial.begin(115200); Serial.print("Factory OSCCAL value: "); Serial.println(initialValue); delay(1000); int start = initialValue - 30; int end = initialValue + 30; for(int i = start; i <= end; i++) { OSCCAL = i; Serial.print("Trying value "); Serial.println(OSCCAL); delay(30); } OSCCAL = 152; Serial.print("Trying value "); Serial.println(OSCCAL); Serial.println("Done!"); pinMode(13, OUTPUT); } void loop() { digitalWrite(13,!digitalRead(13));// Turn the LED from off to on, or on to off delay(10000); // Wait for 1 second (1000 milliseconds) }
20.264706
80
0.63135
chacal
c41b4b5918c025516f31de6bedf75081b80944b7
4,667
cc
C++
src/ts_date.cc
viild/Timestamp
9eefb7246bfc454b9f078f572ba17c54dbeea41a
[ "Apache-2.0" ]
null
null
null
src/ts_date.cc
viild/Timestamp
9eefb7246bfc454b9f078f572ba17c54dbeea41a
[ "Apache-2.0" ]
null
null
null
src/ts_date.cc
viild/Timestamp
9eefb7246bfc454b9f078f572ba17c54dbeea41a
[ "Apache-2.0" ]
null
null
null
#include "ts_date.h" #include <iostream> namespace timestamp { /** * Date - class constructor * @_date_separator: date separator specifier * @_date_format: date format specifier * * This constructor creates an object of the Date class. This also sets variables * date_separator and date_format by values given by an user. */ Date::Date(const DateSeparator & _date_separator, const DateFormat & _date_format) : date_separator(_date_separator), date_format(_date_format) {} /** * Get - return date in specific format * * This method forms string with current date in format defined by "date_format" * and "date_separator" and then returns it. */ const std::string Date::Get() const { std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); time_t tt = std::chrono::system_clock::to_time_t(now); tm local_tm = *localtime(&tt); int day = local_tm.tm_mday; int month = local_tm.tm_mon + 1; int year = local_tm.tm_year + 1900; std::stringstream string_stream; switch (this->date_format) { case timestamp::Date::DateFormat::DMY: switch (this->date_separator) { case timestamp::Date::DateSeparator::DASH: string_stream << AuxStamp::PlaceTwoDigits(day) << "-" << AuxStamp::PlaceTwoDigits(month) << "-" << AuxStamp::PlaceFourDigits(year); return string_stream.str(); case timestamp::Date::DateSeparator::DOT: string_stream << AuxStamp::PlaceTwoDigits(day) << "." << AuxStamp::PlaceTwoDigits(month) << "." << AuxStamp::PlaceFourDigits(year); return string_stream.str(); case timestamp::Date::DateSeparator::SLASH: string_stream << AuxStamp::PlaceTwoDigits(day) << "/" << AuxStamp::PlaceTwoDigits(month) << "/" << AuxStamp::PlaceFourDigits(year); return string_stream.str(); default: return ""; } ; break; case timestamp::Date::DateFormat::MDY: switch (this->date_separator) { case timestamp::Date::DateSeparator::DASH: string_stream << AuxStamp::PlaceTwoDigits(month) << "-" << AuxStamp::PlaceTwoDigits(day) << "-" << AuxStamp::PlaceFourDigits(year); return string_stream.str(); case timestamp::Date::DateSeparator::DOT: string_stream << AuxStamp::PlaceTwoDigits(month) << "." << AuxStamp::PlaceTwoDigits(day) << "." << AuxStamp::PlaceFourDigits(year); return string_stream.str(); case timestamp::Date::DateSeparator::SLASH: string_stream << AuxStamp::PlaceTwoDigits(month) << "/" << AuxStamp::PlaceTwoDigits(day) << "/" << AuxStamp::PlaceFourDigits(year); return string_stream.str(); default: return ""; } ; break; case timestamp::Date::DateFormat::YMD: switch (this->date_separator) { case timestamp::Date::DateSeparator::DASH: string_stream << AuxStamp::PlaceFourDigits(year) << "-" << AuxStamp::PlaceTwoDigits(day) << "-" << AuxStamp::PlaceTwoDigits(month); return string_stream.str(); case timestamp::Date::DateSeparator::DOT: string_stream << AuxStamp::PlaceFourDigits(year) << "." << AuxStamp::PlaceTwoDigits(day) << "." << AuxStamp::PlaceTwoDigits(month); return string_stream.str(); case timestamp::Date::DateSeparator::SLASH: string_stream << AuxStamp::PlaceFourDigits(year) << "/" << AuxStamp::PlaceTwoDigits(day) << "/" << AuxStamp::PlaceTwoDigits(month); return string_stream.str(); default: return ""; } ; break; default: return ""; }; } } // namespace timestamp
42.816514
84
0.501393
viild
c42248c19c9cc378643079329c525eae88ba2b59
650
cpp
C++
cells.cpp
mdyring/tumor_phenotyping
dcc5ee38bc56128d649759b96a2f984b54375d18
[ "MIT" ]
null
null
null
cells.cpp
mdyring/tumor_phenotyping
dcc5ee38bc56128d649759b96a2f984b54375d18
[ "MIT" ]
null
null
null
cells.cpp
mdyring/tumor_phenotyping
dcc5ee38bc56128d649759b96a2f984b54375d18
[ "MIT" ]
null
null
null
#include "cells.hpp" double distance(cell_ptr_type const& cell, cell_ptr_type const& candidate) { std::int64_t const x_distance(cell->x - candidate->x); std::int64_t const y_distance(cell->y - candidate->y); return std::sqrt((x_distance * x_distance) + (y_distance * y_distance)); } void nearest(cell_ptr_type const& cell, cells_type const& candidates, double& nearest_distance, cell_ptr_type& nearest_cell) { for(auto const& candidate: candidates) { double const candidate_distance(distance(cell, candidate)); if(candidate_distance < nearest_distance) { nearest_distance = candidate_distance; nearest_cell = candidate; } } }
27.083333
124
0.750769
mdyring
c42518839cae6410547324002541980702a5a16f
5,739
cpp
C++
empirical-analyses-sort-algorithms/src/timing_template.cpp
fernando-ff/EDB
d87fadb58623f71d028ba2b3434a4b59a94be694
[ "MIT" ]
null
null
null
empirical-analyses-sort-algorithms/src/timing_template.cpp
fernando-ff/EDB
d87fadb58623f71d028ba2b3434a4b59a94be694
[ "MIT" ]
null
null
null
empirical-analyses-sort-algorithms/src/timing_template.cpp
fernando-ff/EDB
d87fadb58623f71d028ba2b3434a4b59a94be694
[ "MIT" ]
null
null
null
/*! * This is a template code to demonstrate how to measure runtime of part of your code. * I'm using the chrono C++ library. * @date September 8th, 2020. * @author Selan */ #include <iostream> #include "../include/sorting.h" using namespace sa; using namespace scenario; int main(int argc, char* argv[]) { unsigned int limit_sample { 100000 };// limit sample if(argc > 1) { if(strcmp(argv[1],"--help") == 0)// Reading command line arguments { render::help(); return EXIT_SUCCESS; } else limit_sample = std::stoi(argv[1]); } unsigned int* arr = new unsigned int[1000000]; //array that will contain the samples // unsigned long int sample { 10000 }; // default sample value unsigned long int sample { 1000 }; unsigned long int sample_backup { sample }; unsigned short int indx_algth { 0 };//index of algorithm analyses unsigned short int indx_scn { 0 };// index of scenario analyses std::chrono::duration<double> avarege_time; std::chrono::duration<double> avarege_time_backup; std::string file_path[6] { "../data/1-scenario/", "../data/2-scenario/", "../data/3-scenario/", "../data/4-scenario/", "../data/5-scenario/", "../data/6-scenario/" }; std::string files_name[7] { "insertion_sort.data", "selection_sort.data", "bublle_sort.data", "shell_sort.data", "quick_sort.data", "merge_sort.data", "radix sort" }; unsigned short int execution { 1 };// counter of executions std::string algorithm_name[7] { "Insertion Sort", "Selection Sort", "Bubble Sort", "Shell Sort", "Quick Sort", "Merge Sort", "Radix Sort" }; void (*scenario_functions[6]) (array_type * first, array_type *last); scenario_functions[0] = first; scenario_functions[1] = second; scenario_functions[2] = third; scenario_functions[3] = fourth; scenario_functions[4] = fifth; scenario_functions[5] = sixth; void (*sort_algorithms[7]) (value_type *first, value_type * last); sort_algorithms[0] = insertion; sort_algorithms[1] = selection; sort_algorithms[2] = bubble; sort_algorithms[3] = shell; sort_algorithms[4] = quicksort; sort_algorithms[5] = mergesort; sort_algorithms[6] = radix; bool open_file { false }; char input_file; unsigned short input; render::intro(); while (true) { render::guide(); std::cin.clear(); std::cin >> input; indx_algth = input; if(indx_algth == 8) break; render::open_file_guide(); std::cin.clear(); std::cin>> input_file; if(input_file == 'y') open_file = true; else open_file = false; auto start_all_analyses = std::chrono::steady_clock::now(); indx_scn = 0; std::ofstream file; while(indx_scn < 6) { if(open_file) { file.open(file_path[indx_scn] + files_name[indx_algth]); std::cout << ">>> File name: " << file_path[indx_scn] + files_name[indx_algth] << std::endl; if(file.is_open()) { std::cout << ">>> Open with sucess!" << std::endl; std::cout << "This will cost a time, so... make a coffe, read a book! And after look here!" << std::endl; } else { std::cout << ">>> We cannot open this file, I'm sorry" << std::endl; std::cout << " Try again!" << std::endl; return EXIT_SUCCESS; } } sample = sample_backup; while( sample <= limit_sample) { avarege_time = avarege_time_backup; execution = 1; while(execution <= 50) { (*scenario_functions[indx_algth]) (arr, arr+sample); auto start = std::chrono::steady_clock::now(); (*sort_algorithms[indx_algth]) (arr, arr+sample); auto end = std::chrono::steady_clock::now(); std::chrono::duration<double> time_taken = end - start; // render::body( sample,time_taken, algorithm_name[indx_algth], execution, indx_scn+1); avarege_time += ((time_taken - avarege_time)/execution); execution++; } render::body( sample,avarege_time, algorithm_name[indx_algth], execution, indx_scn+1); file << sample << "\t" << std::chrono::duration <double, std::milli> (avarege_time).count() << std::endl;; sample += 4 * 1000; } file.close(); indx_scn++; } auto end_all_analyses = std::chrono::steady_clock::now(); std::chrono::duration<double> time_taken_all_analyses = end_all_analyses - start_all_analyses; std::cout << "\nAll analyses costed [" << std::chrono::duration <double, std::milli> (time_taken_all_analyses).count() << "]" << std::endl; std::cout << "Inital Sample: " << sample << " " << " Limit Sample: " << limit_sample <<"\n"<< std::endl; std::cin.sync(); } std::cout << "\nBye bye! ;D" << std::endl; return EXIT_SUCCESS; }
32.241573
147
0.520822
fernando-ff
c427e994ecf404db3580dad5752fd8d515da6ca9
929
cpp
C++
Infinity Runner/Motor2D/Button.cpp
DavidTello1/IDI-game
db242c47389a6219f50fde68a4b475fe9262033e
[ "MIT" ]
null
null
null
Infinity Runner/Motor2D/Button.cpp
DavidTello1/IDI-game
db242c47389a6219f50fde68a4b475fe9262033e
[ "MIT" ]
null
null
null
Infinity Runner/Motor2D/Button.cpp
DavidTello1/IDI-game
db242c47389a6219f50fde68a4b475fe9262033e
[ "MIT" ]
null
null
null
#include "Button.h" Button::Button() { initial_pos = { 0,0 }; position = { 0,0 }; state = IDLE; type = UIType::BUTTON; action = NO_ACTION; parent = nullptr; callback = nullptr; visible = true; color = GREY; movable = false; is_moving = false; } Button::Button(iPoint pos,const Button & b,ActionType action, UIElement* parent) : UIElement(b.type, parent, b.visible) { this->initial_pos = pos; this->position = pos; this->state = IDLE; this->action = action; this->callback = b.callback; this->rect[IDLE] = b.rect[IDLE]; this->rect[HOVER] = b.rect[HOVER]; this->rect[CLICK_DOWN] = b.rect[CLICK_DOWN]; this->rect[CLICK_UP] = b.rect[CLICK_UP]; this->color = b.color; } void Button::HandleAction() { switch (action) { case JUMP: App->entitycontroller->want_jump = true; break; case SLIDE: App->entitycontroller->want_slide = true; break; } }
18.58
119
0.629709
DavidTello1
c42afb3fa52986dae505e3caccfae1a6374c7b86
2,154
cpp
C++
LEDSignToolKit/LEDSignToolKit/LogFile.cpp
cuongquay/led-matrix-display
6dd0e3be9ee23862610dab7b0d40970c6900e5e4
[ "Apache-2.0" ]
null
null
null
LEDSignToolKit/LEDSignToolKit/LogFile.cpp
cuongquay/led-matrix-display
6dd0e3be9ee23862610dab7b0d40970c6900e5e4
[ "Apache-2.0" ]
null
null
null
LEDSignToolKit/LEDSignToolKit/LogFile.cpp
cuongquay/led-matrix-display
6dd0e3be9ee23862610dab7b0d40970c6900e5e4
[ "Apache-2.0" ]
1
2020-06-13T08:34:26.000Z
2020-06-13T08:34:26.000Z
#include "stdafx.h" char _szLogFilePath[MAX_PATH] = _T(""); bool _bEnableLogFile = TRUE; #define MAX_LOG_FILE_SIZE (10*1024*1024) void LOG_TO_FILE(const char* szMsg, ... ) { int nBuf; CFile file; BOOL result=FALSE; TCHAR szLog[MAX_PATH]; TCHAR szBuffer[MAX_PATH]; SYSTEMTIME time; DWORD dwFileSize = 0; TCHAR szPath[MAX_PATH] = _T(""); try{ GetLocalTime(&time); if (_bEnableLogFile){ #ifdef _UNICODE swprintf(szPath,_T("%s%02d%02d%02d.log"),_szLogFilePath,time.wYear,time.wMonth,time.wDay); result=file.Open(szPath,CFile::modeCreate|CFile::modeNoTruncate|CFile::modeReadWrite); #else sprintf(szPath,"%s%02d%02d%02d.log",_szLogFilePath,time.wYear,time.wMonth,time.wDay); result=file.Open(szPath,CFile::modeCreate|CFile::modeNoTruncate|CFile::modeReadWrite); #endif if (result){ dwFileSize = file.SeekToEnd(); if (dwFileSize > MAX_LOG_FILE_SIZE) { file.Flush(); file.Close(); file.Open(szPath,CFile::modeCreate|CFile::modeReadWrite); } } } va_list args; va_start(args, szMsg); nBuf = _vsntprintf(szBuffer, sizeof(szBuffer), szMsg, args); va_end(args); #ifdef _UNICODE swprintf(szLog,_T("[%02d:%02d:%02d]- %s\r\n"),time.wHour,time.wMinute,time.wSecond,szBuffer); char szTemp[MAX_PATH]; UnicodeToMultiByte(szTemp,sizeof(szTemp),szLog); if (_bEnableLogFile){ if (result){ file.Write(szTemp,strlen(szTemp)+1); } } #else sprintf(szLog,_T("[%02d:%02d:%02d]- %s\r\n"),time.wHour,time.wMinute,time.wSecond,szBuffer); if (_bEnableLogFile){ if (result){ file.Write(szLog,strlen(szLog)+1); } } #endif if (_bEnableLogFile){ if (result){ file.Close(); } } TRACE(szLog); } catch( CMemoryException* e ){ TCHAR szError[MAX_PATH]; e->GetErrorMessage(szError,sizeof(szError),0); TRACE(szError); } catch( CFileException* e ){ TCHAR szError[MAX_PATH]; e->GetErrorMessage(szError,sizeof(szError),0); TRACE(szError); } catch( CException* e ){ TCHAR szError[MAX_PATH]; e->GetErrorMessage(szError,sizeof(szError),0); TRACE(szError); } // end of LOG_FILE }
24.477273
96
0.665738
cuongquay
c42bd72bc949eae469cdb64fb79257ba0a6f03c7
337
cpp
C++
B/B463.cpp
Darknez07/Codeforces-sol
afd926c197f43784c12220430bb3c06011bb185e
[ "MIT" ]
null
null
null
B/B463.cpp
Darknez07/Codeforces-sol
afd926c197f43784c12220430bb3c06011bb185e
[ "MIT" ]
null
null
null
B/B463.cpp
Darknez07/Codeforces-sol
afd926c197f43784c12220430bb3c06011bb185e
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(){ int sum = 0,prev = 0,n,curr,mx = -1; cin>>n; for(int i=0;i<n;i++){ cin>>curr; mx = max(mx, curr); sum+=(prev - curr); prev = curr; } if(-mx < sum){ cout<<mx<<endl; }else{ cout<<(-sum)<<endl; } return 0; }
18.722222
40
0.445104
Darknez07
c42ef21b974a5abebada1141571cd117b3940722
6,072
hpp
C++
src/rank-tree.hpp
jcipar/stack-distance
641aab09fcde746dd1cd0d5f05c4aeac841ac0ce
[ "MIT" ]
23
2015-04-22T19:50:01.000Z
2021-12-14T03:15:28.000Z
src/rank-tree.hpp
jcipar/stack-distance
641aab09fcde746dd1cd0d5f05c4aeac841ac0ce
[ "MIT" ]
2
2015-12-03T01:57:57.000Z
2017-08-02T10:35:16.000Z
src/rank-tree.hpp
jcipar/stack-distance
641aab09fcde746dd1cd0d5f05c4aeac841ac0ce
[ "MIT" ]
7
2015-04-24T18:50:05.000Z
2021-09-01T22:26:16.000Z
#ifndef __RANK_TREE_H__ #define __RANK_TREE_H__ #define __STDC_LIMIT_MACROS #include <cstdint> #include <set> #include <string> using namespace std; class RankTree; class RankTreeNode; /* This file contains two classes that implement a treap-based RankTree. A RankTree is an unsorted (i.e. not sorted by the values of the data) binary tree augmented with parent pointers and weights. The weight of a node is the number of nodes rooted at that subtree. Using this extra data, the tree can be viewed as a vector that supports the following operations efficiently: - Insert(node, i): insert a new node at position i. - Get(i): get the node at position i. - GetLast(i): get the last node. - Remove(i): remove the node at position i. - Rank(node): find the position of the node in the tree. Note that Rank() is *not* finding the position of a node in the tree with matching data, as in a binary search tree. The node must be a pointer to an actual element of the tree (generally one returned by Get(). For purposes of this program only a subset of these operations are supported, though the tree could be easily extended to support the more general set of operations. These are the supported operations: - Insert(node or string): insert at position 0, i.e. Insert(_, i). - First(): i.e. Get(0). - GetLast() - Remove(node) - Rank(node) */ class RankTreeNode { friend class RankTree; public: // Rank() gives the number of nodes in the tree with a lower // position (in standard tree traversal order) than this one. Runs // in O(lg n) time. int64_t Rank(); void setWeight(uint64_t weight); // ~RankTreeNode() deletes the node's children, recursively // freeing the tree. ~RankTreeNode(); private: string _name; int64_t _subtreeWeight; uint64_t _weight; int _priority; RankTreeNode* _left; RankTreeNode* _right; RankTreeNode* _parent; // RankTreeNode() constructs a new node with the given name. RankTreeNode(string name, uint64_t weight); bool leaf(); // leaf() indicates that this node is a leaf. bool root(); // root() indicates that this node is the root. // leftChild() and rightChild() indicate that this node is the // left (or right) child of its parent. bool leftChild(); bool rightChild(); // leftWeight() and rightWeight() get the weight of the left (or // right child of this node. If the child doesn't exist, they // return 0. int64_t leftWeight(); int64_t rightWeight(); // print() recursively prints the nodes, indenting each node to // indicate its level in the tree. void print(int level); // fixWeights() recursively (up the tree, following parent // pointers) fixes the weights of nodes after an insertion or // deletion. void fixWeights(); // promote() performs a rotation on the parent node to make this // node closer to the root. It is an error to promote the root. void promote(); // demote() performs a rotation on this node to make one of its // children its new parent. If demote() changes the root (i.e. the // given node was the root), it returns the new root. Otherwise it // returns nullptr. RankTreeNode* demote(); // unlink() removes the node from the tree, and calls fixWeights() // so that the weight invariant is restored. It is an error to // unlink a non-leaf. void unlink(); // makeLeaf() demotes the node until it's a leaf. If this causes the // root to change, it returns the new root. RankTreeNode* makeLeaf(); // fixPriority() returns true if this node is the new head. bool fixPriority(); // leftChildRank() and rightChildRank() are called recursively (up // the tree towards the root) by Rank() to compute the rank of a // node. Their parameter is the currently computed rank based on // the subtree. leftChildRank() is called if the current node is a // left child, rightChildRank() is called if the current node is a // right child. int64_t leftChildRank(int64_t); int64_t rightChildRank(int64_t); //// //// Check functions //// // checkWeights() recursively checks that the weight is equal to the // number of nodes rooted at the given subtree (including the // current node). int64_t checkWeights(); // checkPriorities() recursively checks that child nodes' priorities // are <= their parent nodes' priority. void checkPriorities(int priority); // checkParentPointers() recursively checks that each nodes' // children point back to it. void checkParentPointers(RankTreeNode* parent); // checkUniqueness() checks that each node only appears in the tree // once. void checkUniqueness(std::set<RankTreeNode*>& ptrs); size_t computeSize(); }; class RankTree { public: // RankTree() constructs a new empty tree. RankTree(); // Insert() creates a new node with the given name and inserts it // into the tree. O(lg n) RankTreeNode* Insert(string name, uint64_t weight); // InsertNode() inserts the given node into the tree. O(lg n) void InsertNode(RankTreeNode* node); // Remove() removes a node from the tree, BUT DOES NOT DELETE THE // OBJECT. It is now the caller's responsibility to free the // memory. O(lg n) void Remove(RankTreeNode* node); // The following methods are public to ease testing. While they // are safe to use by other classes, they are not considered part // of the main public API. Following golang conventions, they're // given lower case names to indicate this. // first() returns the first node in the tree. O(lg n) RankTreeNode* first(); // last() returns the last node in the tree. O(lg n) RankTreeNode* last(); // print() prints a representation of the tree to stdout. void print(); // check() verifies the invariants of the tree. E.g. "are parent // pointers pointing the right place?" "are the heap properties // maintained?" void check(); // computeSize() computes the total size of the tree by walking all // pointers. int64_t computeSize(); // ~RankTree() frees all nodes still in the tree. ~RankTree(); private: RankTreeNode* _root; }; #endif // #ifndef __RANK_TREE_H__
30.512563
70
0.716074
jcipar
c431a77079049e64dc2de53094506c3399cfd1ea
7,501
cpp
C++
src/Rendering/GUI/QtGUI/NodeEditor/QtNodeWidget.cpp
hanxingyixue/peridyno
5c963dae20384f6af7a15866dac0d06adfcba236
[ "Apache-2.0" ]
2
2022-01-29T08:51:50.000Z
2022-02-22T12:07:09.000Z
src/Rendering/GUI/QtGUI/NodeEditor/QtNodeWidget.cpp
hanxingyixue/peridyno
5c963dae20384f6af7a15866dac0d06adfcba236
[ "Apache-2.0" ]
null
null
null
src/Rendering/GUI/QtGUI/NodeEditor/QtNodeWidget.cpp
hanxingyixue/peridyno
5c963dae20384f6af7a15866dac0d06adfcba236
[ "Apache-2.0" ]
null
null
null
#include "QtNodeWidget.h" #include "Node.h" #include "NodePort.h" #include "Common.h" #include "FInstance.h" #include "Field.h" namespace Qt { QtNodeWidget::QtNodeWidget(std::shared_ptr<Node> base) { mNode = base; if (mNode != nullptr) { //initialize in node ports auto inputs = mNode->getImportNodes(); auto input_num = inputs.size(); mNodeInport.resize(input_num); for (int i = 0; i < inputs.size(); i++) { mNodeInport[i] = std::make_shared<QtImportNode>(inputs[i]); } //initialize out node ports mNodeExport = std::make_shared<QtExportNode>(base); int output_fnum = getOutputFields().size(); mFieldExport.resize(output_fnum); auto fOutputs = getOutputFields(); for (int i = 0; i < fOutputs.size(); i++) { mFieldExport[i] = std::make_shared<QtFieldData>(fOutputs[i]); } //initialize in ports int input_fnum = getInputFields().size(); mFieldInport.resize(input_fnum); auto fInputs = getInputFields(); for (int i = 0; i < fInputs.size(); i++) { mFieldInport[i] = std::make_shared<QtFieldData>(fInputs[i]);; } } } QtNodeWidget::~QtNodeWidget() { } unsigned int QtNodeWidget::nPorts(PortType portType) const { unsigned int result; if (portType == PortType::In) { result = (unsigned int)mNode->getImportNodes().size() + mFieldInport.size(); } else { result = 1 + mFieldExport.size(); } return result; } NodeDataType QtNodeWidget::dataType(PortType portType, PortIndex portIndex) const { switch (portType) { case PortType::In: if (portIndex < mNodeInport.size()) { return NodeDataType{ "port", "port", PortShape::Bullet }; } else { auto& inputFields = this->getInputFields(); std::string str = inputFields[portIndex - mNodeInport.size()]->getClassName(); return NodeDataType{ str.c_str(), str.c_str(), PortShape::Point }; } break; case PortType::Out: if (portIndex == 0) { return NodeDataType{ "port", "port", PortShape::Bullet }; } else { auto& outputFields = this->getOutputFields(); std::string str = outputFields[portIndex - 1]->getClassName(); return NodeDataType{ str.c_str(), str.c_str(), PortShape::Point }; } break; case PortType::None: break; } return NodeDataType{ "port", "port", PortShape::Point }; } std::shared_ptr<QtNodeData> QtNodeWidget::outData(PortIndex port) { return port == 0 ? std::static_pointer_cast<QtNodeData>(mNodeExport) : std::static_pointer_cast<QtNodeData>(mFieldExport[port - 1]); } // std::shared_ptr<QtNodeData> QtNodeWidget::inData(PortIndex port) // { // return port < mNodeInport.size() ? std::static_pointer_cast<QtNodeData>(mNodeInport[port]) : std::static_pointer_cast<QtNodeData>(mFieldInport[port - mNodeInport.size()]); // } QString QtNodeWidget::caption() const { return dyno::FormatBlockCaptionName(mNode->getClassInfo()->getClassName()); } QString QtNodeWidget::name() const { return QString::fromStdString(mNode->getClassInfo()->getClassName()); } bool QtNodeWidget::portCaptionVisible(PortType portType, PortIndex portIndex) const { Q_UNUSED(portType); Q_UNUSED(portIndex); return true; } QString QtNodeWidget::portCaption(PortType portType, PortIndex portIndex) const { switch (portType) { case PortType::In: if (portIndex < mNodeInport.size()) { return dyno::FormatBlockPortName(mNode->getImportNodes()[portIndex]->getPortName()); } else { auto& inputFields = this->getInputFields(); return dyno::FormatBlockPortName(inputFields[portIndex - mNodeInport.size()]->getObjectName()); } break; case PortType::Out: if (portIndex == 0) { //return dyno::FormatBlockPortName(mNode->getClassInfo()->getClassName()); return dyno::FormatBlockPortName("Out"); } else { auto& outputFields = this->getOutputFields(); return dyno::FormatBlockPortName(outputFields[portIndex - 1]->getObjectName()); } break; case PortType::None: break; } } void QtNodeWidget::setInData(std::shared_ptr<QtNodeData> data, PortIndex portIndex) { if (!mEditingEnabled) return; if (portIndex < mNodeInport.size()) { auto node_port = std::dynamic_pointer_cast<QtExportNode>(data); if (node_port != nullptr) { auto nd = node_port->getNode(); if (node_port->connectionType() == CntType::Break) { //mNodeInport[portIndex]->getNodePort()->removeNode(nd.get()); nd->disconnect(mNodeInport[portIndex]->getNodePort()); //TODO: recover the connection state, use a more elegant way in the future data->setConnectionType(CntType::Link); } else { //mNodeInport[portIndex]->getNodePort()->addNode(nd.get()); nd->connect(mNodeInport[portIndex]->getNodePort()); } } } else { auto fieldData = std::dynamic_pointer_cast<QtFieldData>(data); if (fieldData != nullptr) { auto field = fieldData->getField(); if (fieldData->connectionType() == CntType::Break) { field->disconnect(mFieldInport[portIndex - mNodeInport.size()]->getField()); fieldData->setConnectionType(CntType::Link); } else { field->connect(mFieldInport[portIndex - mNodeInport.size()]->getField()); } } } updateModule(); } bool QtNodeWidget::tryInData(PortIndex portIndex, std::shared_ptr<QtNodeData> nodeData) { if (!mEditingEnabled) return false; if (portIndex < mNodeInport.size()) { try { auto& nodeExp = std::dynamic_pointer_cast<QtExportNode>(nodeData); if (nodeExp == nullptr) return false; auto nodeInp = mNodeInport[portIndex]; return nodeInp->getNodePort()->isKindOf(nodeExp->getNode().get());; } catch (std::bad_cast) { return false; } } else { try { auto& fieldExp = std::dynamic_pointer_cast<QtFieldData>(nodeData); if (fieldExp == nullptr) return false; auto fieldInp = mFieldInport[portIndex - mNodeInport.size()]; if (fieldInp->getField()->getClassName() == fieldExp->getField()->getClassName()) { std::string className = fieldInp->getField()->getClassName(); if (className == dyno::InstanceBase::className()) { return true; } else return fieldInp->getField()->getTemplateName() == fieldExp->getField()->getTemplateName(); } else { return false; } } catch (std::bad_cast) { return false; } } } NodeValidationState QtNodeWidget::validationState() const { return modelValidationState; } QtNodeDataModel::ConnectionPolicy QtNodeWidget::portInConnectionPolicy(PortIndex portIndex) const { if (portIndex < mNodeInport.size()) { auto portType = mNodeInport[portIndex]->getNodePort()->getPortType(); return portType == dyno::NodePortType::Single ? ConnectionPolicy::One : ConnectionPolicy::Many; } else { return ConnectionPolicy::One; } } std::shared_ptr<Node> QtNodeWidget::getNode() { return mNode; } QString QtNodeWidget::validationMessage() const { return modelValidationError; } void QtNodeWidget::updateModule() { modelValidationState = NodeValidationState::Valid; } std::vector<FBase*>& QtNodeWidget::getOutputFields() const { return mNode->getOutputFields(); } std::vector<FBase*>& QtNodeWidget::getInputFields() const { return mNode->getInputFields(); } void QtNodeWidget::enableEditing() { mEditingEnabled = true; } void QtNodeWidget::disableEditing() { mEditingEnabled = false; } }
22.730303
176
0.669111
hanxingyixue
c43c00bdcc437ef647e6ce9b56c6a0577620bd87
317
hpp
C++
pds2/vpls/lista_problematica/List.hpp
pganaclara/ufmg
2325803427a7b4d5d150574bfd80243274cab527
[ "MIT" ]
null
null
null
pds2/vpls/lista_problematica/List.hpp
pganaclara/ufmg
2325803427a7b4d5d150574bfd80243274cab527
[ "MIT" ]
null
null
null
pds2/vpls/lista_problematica/List.hpp
pganaclara/ufmg
2325803427a7b4d5d150574bfd80243274cab527
[ "MIT" ]
null
null
null
#ifndef LIST_H #define LIST_H #include <iostream> #include <cstdlib> struct Node{ int _value; Node *_next; }; struct List{ Node *_head; Node *_toe; int _size; List(); void insert(int value); void remove(int value); void print(); void clearList(); int removeFirst(); int indexOf(int value); }; #endif
12.192308
24
0.678233
pganaclara
c43f941882e34e24e3847d5a088a4dd6c6c05ad7
1,588
hpp
C++
rmf_task/test/mock/MockEvent.hpp
Rouein/rmf_task
32de25ff127aed754ca760ef462ef8c3e7dd56a1
[ "Apache-2.0" ]
null
null
null
rmf_task/test/mock/MockEvent.hpp
Rouein/rmf_task
32de25ff127aed754ca760ef462ef8c3e7dd56a1
[ "Apache-2.0" ]
null
null
null
rmf_task/test/mock/MockEvent.hpp
Rouein/rmf_task
32de25ff127aed754ca760ef462ef8c3e7dd56a1
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2021 Open Source Robotics Foundation * * 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 TEST__MOCK__MOCKEVENT_HPP #define TEST__MOCK__MOCKEVENT_HPP #include <rmf_task/Event.hpp> namespace test_rmf_task { //============================================================================== class MockEvent : public rmf_task::Event::State { public: MockEvent( uint64_t id_, std::string name_, std::string detail_, Status initial_status = Status::Standby); // Interface uint64_t id() const final; Status status() const final; rmf_task::VersionedString::View name() const final; rmf_task::VersionedString::View detail() const final; rmf_task::Log::View log() const final; std::vector<rmf_task::Event::ConstStatePtr> dependencies() const final; // Fields uint64_t _id; Status _status; rmf_task::VersionedString _name; rmf_task::VersionedString _detail; rmf_task::Log _log; std::vector<std::shared_ptr<MockEvent>> _dependencies; }; } // namespace test_rmf_task #endif // TEST__MOCK__MOCKCONDITION_HPP
27.859649
80
0.702141
Rouein
c451dd0429e13c18467bad9561ae85fed6c0d775
4,557
cpp
C++
src/proposals/suspend_proposal.cpp
josejulio/dao-contracts
2c774185f00ac89c31061da4e15567140876b1c8
[ "MIT" ]
null
null
null
src/proposals/suspend_proposal.cpp
josejulio/dao-contracts
2c774185f00ac89c31061da4e15567140876b1c8
[ "MIT" ]
null
null
null
src/proposals/suspend_proposal.cpp
josejulio/dao-contracts
2c774185f00ac89c31061da4e15567140876b1c8
[ "MIT" ]
null
null
null
#include <algorithm> #include <eosio/asset.hpp> #include <eosio/crypto.hpp> #include <document_graph/document.hpp> #include <document_graph/content_wrapper.hpp> #include <common.hpp> #include <util.hpp> #include <proposals/suspend_proposal.hpp> #include <assignment.hpp> #include <period.hpp> #include <logger/logger.hpp> namespace hypha { void SuspendProposal::proposeImpl(const name &proposer, ContentWrapper &contentWrapper) { //TODO: Setup ballot_title according to document type [Assignment, Badge, etc.] TRACE_FUNCTION() // original_document is a required hash auto originalDocHash = contentWrapper.getOrFail(DETAILS, ORIGINAL_DOCUMENT)->getAs<eosio::checksum256>(); Document originalDoc(m_dao.get_self(), originalDocHash); ContentWrapper ocw = originalDoc.getContentWrapper(); auto type = ocw.getOrFail(SYSTEM, TYPE)->getAs<name>(); switch (type.value) { case common::ASSIGNMENT.value: { Assignment assignment(&m_dao, originalDoc.getHash()); auto currentTimeSecs = eosio::current_time_point().sec_since_epoch(); auto lastPeriodEndSecs = assignment.getLastPeriod() .getEndTime() .sec_since_epoch(); EOS_CHECK( currentTimeSecs < lastPeriodEndSecs, "Assignment is already expired" ); } break; default: EOS_CHECK( false, to_str("Unexpected document type for suspension: ", type, ". Valid types [", common::ASSIGNMENT ,"]") ); break; } auto title = ocw.getOrFail(DETAILS, TITLE)->getAs<string>(); ContentWrapper::insertOrReplace(*contentWrapper.getGroupOrFail(DETAILS), Content { TITLE, to_str("Suspention of ", type, ":", title ) }); } void SuspendProposal::postProposeImpl (Document &proposal) { TRACE_FUNCTION() auto originalDocHash = proposal.getContentWrapper() .getOrFail(DETAILS, ORIGINAL_DOCUMENT) ->getAs<eosio::checksum256>(); Edge::write (m_dao.get_self(), m_dao.get_self(), proposal.getHash(), originalDocHash, common::SUSPEND); } void SuspendProposal::passImpl(Document &proposal) { TRACE_FUNCTION() auto edges = m_dao.getGraph().getEdgesFrom(proposal.getHash(), common::SUSPEND); EOS_CHECK( edges.size() == 1, "Missing edge from suspension proposal: " + readableHash(proposal.getHash()) + " to document" ); Document originalDoc(m_dao.get_self(), edges[0].getToNode()); ContentWrapper ocw = originalDoc.getContentWrapper(); auto type = ocw.getOrFail(SYSTEM, TYPE)->getAs<name>(); switch (type.value) { case common::ASSIGNMENT.value: { Assignment assignment(&m_dao, originalDoc.getHash()); auto cw = assignment.getContentWrapper(); auto originalPeriods = assignment.getPeriodCount(); //Calculate the number of periods since start period to the current period auto currentPeriod = Period::current(&m_dao); auto periodsToCurrent = assignment.getStartPeriod().getPeriodCountTo(currentPeriod); periodsToCurrent = std::min(periodsToCurrent + 1, originalPeriods); if (originalPeriods != periodsToCurrent) { auto detailsGroup = cw.getGroupOrFail(DETAILS); ContentWrapper::insertOrReplace(*detailsGroup, Content { PERIOD_COUNT, periodsToCurrent }); auto newHash = m_dao.getGraph().updateDocument(assignment.getCreator(), assignment.getHash(), cw.getContentGroups()).getHash(); assignment = Assignment(&m_dao, newHash); } m_dao.modifyCommitment(assignment, 0, std::nullopt, common::MOD_WITHDRAW); } break; default: { EOS_CHECK( false, to_str("Unexpected document type for suspension: ", type, ". Valid types [", common::ASSIGNMENT ,"]") ); } break; } } std::string SuspendProposal::getBallotContent (ContentWrapper &contentWrapper) { TRACE_FUNCTION() return getTitle(contentWrapper); } name SuspendProposal::getProposalType () { return common::SUSPEND; } } // namespace hypha
31.645833
111
0.608075
josejulio
c4537ba4537cc9b03abcf586ad609e65902780fd
178,970
cpp
C++
GameEngineCore/VulkanAPI/VulkanHardwareRenderer.cpp
csyonghe/spire-engine
9c98b277a6643688365f9ce308e8621d90af9c97
[ "MIT" ]
null
null
null
GameEngineCore/VulkanAPI/VulkanHardwareRenderer.cpp
csyonghe/spire-engine
9c98b277a6643688365f9ce308e8621d90af9c97
[ "MIT" ]
null
null
null
GameEngineCore/VulkanAPI/VulkanHardwareRenderer.cpp
csyonghe/spire-engine
9c98b277a6643688365f9ce308e8621d90af9c97
[ "MIT" ]
null
null
null
#include "../GameEngineCore/HardwareRenderer.h" #include "CoreLib/WinForm/Debug.h" #include "CoreLib/VectorMath.h" #include "CoreLib/PerformanceCounter.h" #include "../Engine.h" #include "CoreLib/ShortList.h" #include "CoreLib/LibIO.h" #include "volk.h" #include "vulkan.hpp" #include <mutex> // Only execute actions of DEBUG_ONLY in DEBUG mode #if _DEBUG #define DEBUG_ONLY(x) { x; } #define USE_VALIDATION_LAYER 1 #else #define DEBUG_ONLY(x) {} #endif #ifdef __linux__ #undef Always #undef None #endif using namespace GameEngine; using namespace CoreLib::IO; using namespace CoreLib; namespace VK { const int TargetVulkanVersion_Major = 1; const int TargetVulkanVersion_Minor = 0; const int MaxRenderThreads = 4; int MaxThreadCount = MaxRenderThreads; unsigned int GpuId = 0; thread_local int renderThreadId = -1; namespace VkDebug { // Print device info void PrintDeviceInfo(const std::vector<vk::PhysicalDevice>& physicalDevices); // Debug callback direct to stderr VKAPI_ATTR VkBool32 VKAPI_CALL DebugCallback( VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode, const char* pLayerPrefix, const char* pMessage, void* pUserData); // VkDebug Implementation void PrintDeviceInfo(const std::vector<vk::PhysicalDevice>& physicalDevices) { for (uint32_t i = 0; i < physicalDevices.size(); i++) { // Print out device properties vk::PhysicalDeviceProperties deviceProperties = physicalDevices.at(i).getProperties(); printf("Device ID: %d\n", deviceProperties.deviceID); printf("Driver Version: %d\n", deviceProperties.driverVersion); printf("Device Name: %s\n", deviceProperties.deviceName); printf("Device Type: %d\n", static_cast<int>(deviceProperties.deviceType)); printf("API Version: %d.%d.%d\n", VK_VERSION_MAJOR(deviceProperties.apiVersion), VK_VERSION_MINOR(deviceProperties.apiVersion), VK_VERSION_PATCH(deviceProperties.apiVersion)); printf("\n"); // Print out device queue info std::vector<vk::QueueFamilyProperties> familyProperties = physicalDevices.at(i).getQueueFamilyProperties(); for (size_t j = 0; j < familyProperties.size(); j++) { printf("Count of Queues: %d\n", familyProperties[j].queueCount); printf("Supported operations on this queue: %s\n", to_string(familyProperties[j].queueFlags).c_str()); printf("\n"); } // Print out device memory properties vk::PhysicalDeviceMemoryProperties memoryProperties = physicalDevices.at(i).getMemoryProperties(); printf("Memory Type Count: %d\n", memoryProperties.memoryTypeCount); for (size_t j = 0; j < memoryProperties.memoryTypeCount; j++) { auto type = memoryProperties.memoryTypes[j]; printf("(Heap %d) %s\n", type.heapIndex, to_string(type.propertyFlags).c_str()); } printf("\n"); printf("Memory Heap Count: %d\n", memoryProperties.memoryHeapCount); for (size_t j = 0; j < memoryProperties.memoryHeapCount; j++) { auto heap = memoryProperties.memoryHeaps[j]; printf("(Heap %zu)\n", j); printf("\tsize: %u MB\n", static_cast<unsigned>(heap.size / 1024 / 1024)); printf("\tflags:%s\n", to_string(heap.flags).c_str()); printf("\n"); } printf("\n"); // Print out device features printf("Supported Features:\n"); vk::PhysicalDeviceFeatures deviceFeatures = physicalDevices.at(i).getFeatures(); if (deviceFeatures.shaderClipDistance == VK_TRUE) printf("Shader Clip Distance\n"); if (deviceFeatures.textureCompressionBC == VK_TRUE) printf("BC Texture Compression\n"); printf("\n"); // Print out device limits printf("Device Limits:\n"); printf("Max Vertex Input Attributes: %u\n", deviceProperties.limits.maxVertexInputAttributes); printf("Max Push Constants Size: %u\n", deviceProperties.limits.maxPushConstantsSize); // Readability printf("\n---\n\n"); } } VKAPI_ATTR VkBool32 VKAPI_CALL DebugCallback( VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t /*object*/, size_t /*location*/, int32_t messageCode, const char* pLayerPrefix, const char* pMessage, void* /*pUserData*/) { if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) CoreLib::Diagnostics::Debug::Write("ERROR"); if (flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) CoreLib::Diagnostics::Debug::Write("WARNING"); if (flags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT) CoreLib::Diagnostics::Debug::Write("PERFORMANCE"); if (flags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT) CoreLib::Diagnostics::Debug::Write("INFO"); if (flags & VK_DEBUG_REPORT_DEBUG_BIT_EXT) CoreLib::Diagnostics::Debug::Write("DEBUG"); CoreLib::Diagnostics::Debug::Write(" ["); CoreLib::Diagnostics::Debug::Write(pLayerPrefix); CoreLib::Diagnostics::Debug::Write("] "); CoreLib::Diagnostics::Debug::Write("("); CoreLib::Diagnostics::Debug::Write(to_string((vk::DebugReportObjectTypeEXT)objectType).c_str()); CoreLib::Diagnostics::Debug::Write(") "); CoreLib::Diagnostics::Debug::Write((long long)messageCode); CoreLib::Diagnostics::Debug::Write(" "); CoreLib::Diagnostics::Debug::WriteLine(pMessage); return VK_FALSE; } } class DescriptorPoolObject : public CoreLib::Object { public: vk::DescriptorPool pool; DescriptorPoolObject(); ~DescriptorPoolObject(); }; /* * Internal Vulkan state */ class RendererState { //TODO: check class for multithreading safety private: bool initialized = false; int rendererCount = 0; vk::DebugReportCallbackEXT callback; vk::Instance instance; vk::PhysicalDevice physicalDevice; vk::Device device; vk::DescriptorSetLayout emptyDescriptorSetLayout; vk::DescriptorSet emptyDescriptorSet; vk::CommandPool swapchainCommandPool; CoreLib::Array<vk::CommandPool, MaxRenderThreads> renderCommandPools; CoreLib::Array<CoreLib::RefPtr<CoreLib::List<CoreLib::List<vk::CommandBuffer>>>, MaxRenderThreads> renderCommandBufferPools; int currentBufferVersions[MaxRenderThreads] = {}; int renderCommandBufferAllocPtrs[MaxRenderThreads] = {}; int renderQueueIndex; int transferQueueIndex; vk::Queue presentQueue; CoreLib::Array<vk::Queue, MaxRenderThreads> renderQueues; vk::Queue transferQueue; vk::PipelineCache pipelineCache; CoreLib::String pipelineCacheLocation; CoreLib::Array<CoreLib::RefPtr<CoreLib::List<DescriptorPoolObject*>>, MaxRenderThreads> descriptorPoolChains; RendererState() {} static vk::CommandBuffer GetTempCommandBuffer(vk::CommandPool cmdPool, CoreLib::List<CoreLib::List<vk::CommandBuffer>> & bufferPool, int & allocPtr) { if (allocPtr == bufferPool[State().currentBufferVersions[renderThreadId]].Count()) { bufferPool[State().currentBufferVersions[renderThreadId]].Add(CreateCommandBuffer(cmdPool, vk::CommandBufferLevel::ePrimary)); } return bufferPool[State().currentBufferVersions[renderThreadId]][allocPtr++]; } static RendererState& State() { static RendererState singleton; return singleton; } static void CreateDebugCallback() { vk::DebugReportCallbackCreateInfoEXT callbackCreateInfo( vk::DebugReportFlagsEXT( //vk::DebugReportFlagBitsEXT::eInformation | vk::DebugReportFlagBitsEXT::eDebug | vk::DebugReportFlagBitsEXT::ePerformanceWarning | vk::DebugReportFlagBitsEXT::eWarning | vk::DebugReportFlagBitsEXT::eError ), &VkDebug::DebugCallback, nullptr // userdata ); State().callback = State().instance.createDebugReportCallbackEXT(callbackCreateInfo); } static void CreateInstance() { // Application and Instance Info vk::ApplicationInfo appInfo = vk::ApplicationInfo() .setPApplicationName("lll") .setPEngineName("Engine") .setEngineVersion(1) .setApiVersion(VK_API_VERSION_1_0); // Enabled Layers CoreLib::List<const char*> enabledInstanceLayers; #if _DEBUG bool hasValidationLayer = false; auto supportedLayers = vk::enumerateInstanceLayerProperties(); for (auto & l : supportedLayers) if (strcmp(l.layerName, "VK_LAYER_KHRONOS_validation") == 0) { hasValidationLayer = true; break; } #if USE_VALIDATION_LAYER if (hasValidationLayer) enabledInstanceLayers.Add("VK_LAYER_KHRONOS_validation"); #endif #endif // Enabled Extensions CoreLib::List<const char*> enabledInstanceExtensions; enabledInstanceExtensions.Add(VK_KHR_SURFACE_EXTENSION_NAME); enabledInstanceExtensions.Add(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME); #if _WIN32 enabledInstanceExtensions.Add(VK_KHR_WIN32_SURFACE_EXTENSION_NAME); #elif defined(__linux__) enabledInstanceExtensions.Add(VK_KHR_XLIB_SURFACE_EXTENSION_NAME); #endif DEBUG_ONLY(enabledInstanceExtensions.Add(VK_EXT_DEBUG_REPORT_EXTENSION_NAME)); // Instance Create Info vk::InstanceCreateInfo instInfo = vk::InstanceCreateInfo() .setPApplicationInfo(&appInfo) .setEnabledLayerCount(enabledInstanceLayers.Count()) .setPpEnabledLayerNames(enabledInstanceLayers.Buffer()) .setEnabledExtensionCount(enabledInstanceExtensions.Count()) .setPpEnabledExtensionNames(enabledInstanceExtensions.Buffer()); // Create the instance State().instance = vk::createInstance(instInfo); // Load instance level function pointers volkLoadInstance((VkInstance)(State().instance)); // Create callbacks DEBUG_ONLY(CreateDebugCallback()); } static void SelectPhysicalDevice() { std::vector<vk::PhysicalDevice> physicalDevices = State().instance.enumeratePhysicalDevices(); //DEBUG_ONLY(VkDebug::PrintDeviceInfo(physicalDevices)); if (GpuId >= physicalDevices.size()) GpuId = 0; State().physicalDevice = physicalDevices[GpuId]; printf("Using GPU %d\n", GpuId); } static void SelectPhysicalDevice(vk::SurfaceKHR surface) { std::vector<vk::PhysicalDevice> physicalDevices = State().instance.enumeratePhysicalDevices(); //DEBUG_ONLY(VkDebug::PrintDeviceInfo(physicalDevices)); int k = 0; for (auto physDevice : physicalDevices) { for (size_t i = 0; i < physDevice.getQueueFamilyProperties().size(); i++) { if (physDevice.getSurfaceSupportKHR((uint32_t)i, surface)) { State().physicalDevice = physDevice; GpuId = k; printf("Using GPU %d\n", GpuId); return; } } k++; } } static void CreateDevice() { // Initialize Queues CoreLib::List<float> renderQueuePriorities; CoreLib::List<float> transferQueuePriorities; renderQueuePriorities.Add(1.0f); std::vector<vk::QueueFamilyProperties> queueFamilyProperties = PhysicalDevice().getQueueFamilyProperties(); MaxThreadCount = Math::Min(MaxThreadCount, (int)queueFamilyProperties[0].queueCount); for (int i = 0; i < MaxThreadCount - 1; i++) { renderQueuePriorities.Add(1.0f); } //transferQueuePriorities.Add(1.0f); //TODO: improve int renderQueueFamilyIndex = 0; int transferQueueFamilyIndex = 0; //NOTE: When changing this, resources created by the transferQueue will also need to have // their ownership transferred to the renderQueue, if they are created with // vk::SharingMode::eExclusive. https://www.khronos.org/registry/vulkan/specs/1.0/xhtml/vkspec.html#resources-sharing CoreLib::List<vk::DeviceQueueCreateInfo> deviceQueueInfoVec; deviceQueueInfoVec.Add( vk::DeviceQueueCreateInfo() .setQueueFamilyIndex(renderQueueFamilyIndex) .setQueueCount(renderQueuePriorities.Count()) .setPQueuePriorities(renderQueuePriorities.Buffer()) ); //deviceQueueInfoVec.Add( // vk::DeviceQueueCreateInfo() // .setQueueFamilyIndex(transferQueueFamilyIndex) // .setQueueCount(transferQueuePriorities.Count()) // .setPQueuePriorities(transferQueuePriorities.Buffer()) //); // Lambda to check if layer is present and then add it auto AddLayer = [](CoreLib::List<const char*>& enabledDeviceLayers, const char* layerName) { for (auto layer : State().physicalDevice.enumerateDeviceLayerProperties()) { if (!strcmp(layerName, layer.layerName)) { enabledDeviceLayers.Add(layerName); return; } } printf("Layer %s not supported\n", layerName); }; CoreLib::List<const char*> enabledDeviceLayers; #if USE_VALIDATION_LAYER DEBUG_ONLY(AddLayer(enabledDeviceLayers, "VK_LAYER_LUNARG_standard_validation")); #endif // Lambda to check if extension is present and then add it auto AddExtension = [](CoreLib::List<const char*>& enabledDeviceExtensions, const char* extensionName) { for (auto extension : State().physicalDevice.enumerateDeviceExtensionProperties()) { if (!strcmp(extensionName, extension.extensionName)) { enabledDeviceExtensions.Add(extensionName); return; } } printf("Extension %s not supported\n", extensionName); }; CoreLib::List<const char*> enabledDeviceExtensions; AddExtension(enabledDeviceExtensions, VK_KHR_SWAPCHAIN_EXTENSION_NAME); AddExtension(enabledDeviceExtensions, VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME); DEBUG_ONLY(AddExtension(enabledDeviceExtensions, VK_EXT_DEBUG_MARKER_EXTENSION_NAME)); // Device Features vk::PhysicalDeviceFeatures enabledDeviceFeatures = State().physicalDevice.getFeatures(); vk::DeviceCreateInfo deviceInfo = vk::DeviceCreateInfo() .setQueueCreateInfoCount(deviceQueueInfoVec.Count()) .setPQueueCreateInfos(deviceQueueInfoVec.Buffer()) .setEnabledLayerCount(enabledDeviceLayers.Count()) .setPpEnabledLayerNames(enabledDeviceLayers.Buffer()) .setEnabledExtensionCount(enabledDeviceExtensions.Count()) .setPpEnabledExtensionNames(enabledDeviceExtensions.Buffer()) .setPEnabledFeatures(&enabledDeviceFeatures); State().device = State().physicalDevice.createDevice(deviceInfo); // Load device level function pointers volkLoadDevice((VkDevice)(State().device)); State().presentQueue = State().device.getQueue(renderQueueFamilyIndex, 0); State().renderQueues.SetSize(MaxThreadCount); for (int i = 0; i < renderQueuePriorities.Count(); i++) { State().renderQueues[i] = State().device.getQueue(renderQueueFamilyIndex, i); } State().transferQueue = State().device.getQueue(transferQueueFamilyIndex, renderQueuePriorities.Count() - 1);//TODO: Change the index if changing family } static void CreateCommandPool() { vk::CommandPoolCreateInfo commandPoolCreateInfo = vk::CommandPoolCreateInfo() .setFlags(vk::CommandPoolCreateFlagBits::eResetCommandBuffer) .setQueueFamilyIndex(State().renderQueueIndex); State().swapchainCommandPool = State().device.createCommandPool(commandPoolCreateInfo); //TODO: multiple pools for multiple threads vk::CommandPoolCreateInfo renderCommandPoolCreateInfo = vk::CommandPoolCreateInfo() .setFlags(vk::CommandPoolCreateFlagBits::eResetCommandBuffer) .setQueueFamilyIndex(State().renderQueueIndex); State().renderCommandPools.SetSize(MaxThreadCount); for (int i = 0; i < MaxThreadCount; i++) State().renderCommandPools[i] = State().device.createCommandPool(renderCommandPoolCreateInfo); State().renderCommandBufferPools.SetSize(MaxThreadCount); for (int i = 0; i < MaxThreadCount; i++) State().renderCommandBufferPools[i] = new List<List<vk::CommandBuffer>>(); } static void CreateDescriptorPoolChain() { State().descriptorPoolChains.SetSize(MaxThreadCount); for (int i = 0; i < MaxThreadCount; i++) { State().descriptorPoolChains[i] = new CoreLib::List<DescriptorPoolObject*>(); } } // This function encapsulates all device-specific initialization static void InitDevice() { CreateDevice(); CreateCommandPool(); CreateDescriptorPoolChain(); List<unsigned char> initialData; if (File::Exists(State().pipelineCacheLocation)) { initialData = File::ReadAllBytes(State().pipelineCacheLocation); } vk::PipelineCacheCreateInfo createInfo = vk::PipelineCacheCreateInfo() .setInitialDataSize(initialData.Count()) .setPInitialData(initialData.Buffer()); State().pipelineCache = State().device.createPipelineCache(createInfo); } static void Init() { if (State().initialized) return; renderThreadId = 0; State().initialized = true; if (volkInitialize() != VK_SUCCESS) { printf("Fatal error: Vulkan driver not found on the current system.\n"); exit(-1); } CreateInstance(); SelectPhysicalDevice(); InitDevice(); vk::DescriptorSetLayoutCreateInfo descLayoutCreateInfo; descLayoutCreateInfo.setBindingCount(0); State().emptyDescriptorSetLayout = State().device.createDescriptorSetLayout(descLayoutCreateInfo); State().emptyDescriptorSet = AllocateDescriptorSet(State().emptyDescriptorSetLayout).second; } static void DestroyDevice() { State().device.destroyDescriptorSetLayout(State().emptyDescriptorSetLayout); State().device.destroy(); } static void DestroyInstance() { DEBUG_ONLY(State().instance.destroyDebugReportCallbackEXT(State().callback)); State().instance.destroy(); } static void DestroyCommandPool() { for (int i = 0; i < MaxThreadCount; i++) State().device.destroyCommandPool(State().renderCommandPools[i]); State().device.destroyCommandPool(State().swapchainCommandPool); for (auto & pool : State().renderCommandBufferPools) pool = nullptr; } static void DestroyDescriptorPoolChain() { for (auto & chain : State().descriptorPoolChains) { for (auto& descriptorPool : *chain) delete descriptorPool; chain = nullptr; } } // This function encapsulates all device-specific destruction static void UninitDevice() { State().device.waitIdle(); if (State().pipelineCacheLocation.Length()) { const size_t maxPipelineCacheSize = (64 << 20); // limit cache size to 64MB size_t size = 0; vkGetPipelineCacheData(State().device, State().PipelineCache(), &size, nullptr); if (size > maxPipelineCacheSize) size = maxPipelineCacheSize; List<unsigned char> buffer; buffer.SetSize((int)size); vkGetPipelineCacheData(State().device, State().PipelineCache(), &size, buffer.Buffer()); File::WriteAllBytes(State().pipelineCacheLocation, buffer.Buffer(), (size_t)buffer.Count()); } State().device.destroyPipelineCache(State().pipelineCache); DestroyDescriptorPoolChain(); DestroyCommandPool(); DestroyDevice(); } static void Destroy() { if (!State().initialized) return; UninitDevice(); DestroyInstance(); State().SetPipelineCacheLocation(String()); State().initialized = false; }; static void DeviceLost() { UninitDevice(); SelectPhysicalDevice(); InitDevice(); //TODO: send message to user of engine that signals to recreate resources } public: RendererState(RendererState const&) = delete; void operator=(RendererState const&) = delete; ~RendererState() { Destroy();//TODO: Does this need to be here? } // Const reference access to class variables static const vk::Instance& Instance() { return State().instance; } static vk::DescriptorSet GetEmptyDescriptorSet() { return State().emptyDescriptorSet; } static const vk::PhysicalDevice& PhysicalDevice() { return State().physicalDevice; } static const vk::Device& Device() { return State().device; } static void Init(int versionCount) { auto & state = State(); for (int i = 0; i < MaxThreadCount; i++) state.renderCommandBufferPools[i]->SetSize(versionCount); } static void ResetTempBufferVersion(int version) { auto & state = State(); state.currentBufferVersions[renderThreadId] = version; state.renderCommandBufferAllocPtrs[renderThreadId] = 0; } static const vk::CommandPool& SwapchainCommandPool() { //TODO: do I want to expose these command pools? return State().swapchainCommandPool; } static const vk::CommandPool& TransferCommandPool() { return RenderCommandPool(); } static const vk::CommandPool& RenderCommandPool() { return State().renderCommandPools[renderThreadId]; } static vk::CommandBuffer GetTempTransferCommandBuffer() { return GetTempRenderCommandBuffer(); } static vk::CommandBuffer GetTempRenderCommandBuffer() { return GetTempCommandBuffer(State().renderCommandPools[renderThreadId], *State().renderCommandBufferPools[renderThreadId], State().renderCommandBufferAllocPtrs[renderThreadId]); } static const vk::Queue& TransferQueue() { return RenderQueue(); } static const vk::Queue& RenderQueue() { return State().renderQueues[renderThreadId]; } static const vk::Queue& PresentQueue() { return State().presentQueue; } static const vk::PipelineCache& PipelineCache() { return State().pipelineCache; } static const vk::DescriptorPool& DescriptorPool() { if (State().descriptorPoolChains[renderThreadId]->Count() == 0) State().descriptorPoolChains[renderThreadId]->Add(new DescriptorPoolObject()); return State().descriptorPoolChains[renderThreadId]->Last()->pool; } static std::pair<vk::DescriptorPool, vk::DescriptorSet> AllocateDescriptorSet(vk::DescriptorSetLayout layout, bool canTryAgain = true) { //TODO: add counter mechanism to DescriptorPoolObject so we know when to destruct std::pair<vk::DescriptorPool, vk::DescriptorSet> res; res.first = State().DescriptorPool(); // Create Descriptor Set vk::DescriptorSetAllocateInfo descriptorSetAllocateInfo = vk::DescriptorSetAllocateInfo() .setDescriptorPool(res.first) .setDescriptorSetCount(1) .setPSetLayouts(&layout); auto err = RendererState::Device().allocateDescriptorSets(&descriptorSetAllocateInfo, &res.second); if (err != vk::Result::eSuccess) { if (canTryAgain) { RendererState::State().descriptorPoolChains[renderThreadId]->Add(new DescriptorPoolObject()); return AllocateDescriptorSet(layout, false); } else CORELIB_ABORT("Couldn't allocate descriptor set."); } else return res; } static void SetPipelineCacheLocation(String loc) { State().pipelineCacheLocation = loc; } // Bookkeeping for multiple instances of HardwareRenderer static void AddRenderer() { if (!State().initialized) Init(); State().rendererCount++; } static void RemRenderer() { State().rendererCount--; if (RendererCount() == 0) Destroy();//TODO: Should I destroy the state here? } static int RendererCount() { return State().rendererCount; } // Resource creation functions static vk::SurfaceKHR CreateSurface(WindowHandle windowHandle) { // Create the surface. vk::SurfaceKHR surface; #if _WIN32 vk::Win32SurfaceCreateInfoKHR surfaceCreateInfo = vk::Win32SurfaceCreateInfoKHR() .setHwnd((HWND)windowHandle) .setHinstance(GetModuleHandle(NULL)); surface = State().instance.createWin32SurfaceKHR(surfaceCreateInfo); #elif __linux__ vk::XlibSurfaceCreateInfoKHR surfaceCreateInfo = vk::XlibSurfaceCreateInfoKHR() .setWindow(windowHandle.window) .setDpy((Display*)windowHandle.display); surface = State().instance.createXlibSurfaceKHR(surfaceCreateInfo); #elif __ANDROID__ vk::AndroidSurfaceCreateInfoKHR surfaceCreateInfo = vk::AndroidSurfaceCreaetInfoKHR() .setWindow((ANativeWindow*)window); surface = State().instance.createAndroidSurfaceKHR(surfaceCreateInfo); #endif // Check to see if the current physical device supports the surface bool supported = false; for (unsigned int i = 0; i < State().physicalDevice.getQueueFamilyProperties().size(); i++) { if (State().physicalDevice.getSurfaceSupportKHR(i, surface)) { supported = true; break; } } // If not supported, recreate logical device with a compatible physical device if (!supported) { printf("GPU %d does not support current surface\n", GpuId); UninitDevice(); SelectPhysicalDevice(surface); InitDevice(); //TODO: Notify user to recreate any resources they have created prior to this point } return surface; } //TODO: I should probably wrap command buffers in a class that contain both the handle and a reference to the command pool created from static vk::CommandBuffer CreateCommandBuffer(vk::CommandPool commandPool, vk::CommandBufferLevel level = vk::CommandBufferLevel::ePrimary) { vk::CommandBufferAllocateInfo commandBufferAllocateInfo = vk::CommandBufferAllocateInfo() .setCommandPool(commandPool) .setLevel(level) .setCommandBufferCount(1); vk::CommandBuffer commandBuffer; //TODO: lock mutex on commandPool or allocate commandPool per thread commandBuffer = State().device.allocateCommandBuffers(commandBufferAllocateInfo).front(); //TODO: unlock mutex on commandPool return commandBuffer; } static vk::CommandBuffer DestroyCommandBuffer(vk::CommandPool commandPool, vk::CommandBuffer commandBuffer) { //TODO: lock mutex on commandPool State().device.freeCommandBuffers(commandPool, commandBuffer); //TODO: unlock mutex on commandPool return commandBuffer; } }; DescriptorPoolObject::DescriptorPoolObject() { CoreLib::List<vk::DescriptorPoolSize> poolSizes; poolSizes.Add(vk::DescriptorPoolSize(vk::DescriptorType::eSampler, 200)); poolSizes.Add(vk::DescriptorPoolSize(vk::DescriptorType::eSampledImage, 20000)); poolSizes.Add(vk::DescriptorPoolSize(vk::DescriptorType::eUniformBuffer, 5000)); poolSizes.Add(vk::DescriptorPoolSize(vk::DescriptorType::eStorageBuffer, 2500)); poolSizes.Add(vk::DescriptorPoolSize(vk::DescriptorType::eStorageImage, 32)); vk::DescriptorPoolCreateInfo poolCreateInfo = vk::DescriptorPoolCreateInfo() .setFlags(vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet) .setMaxSets(5000) .setPoolSizeCount(poolSizes.Count()) .setPPoolSizes(poolSizes.Buffer()); pool = RendererState::Device().createDescriptorPool(poolCreateInfo); } DescriptorPoolObject::~DescriptorPoolObject() { if (pool) RendererState::Device().destroyDescriptorPool(pool); } /* * Interface to Vulkan translation functions */ vk::Format TranslateStorageFormat(StorageFormat format) { switch (format) { case StorageFormat::R_F16: return vk::Format::eR16Sfloat; case StorageFormat::R_F32: return vk::Format::eR32Sfloat; case StorageFormat::R_I8: return vk::Format::eR8Uint; case StorageFormat::R_I16: return vk::Format::eR16Uint; case StorageFormat::R_8: return vk::Format::eR8Unorm; case StorageFormat::R_16: return vk::Format::eR16Unorm; case StorageFormat::Int32_Raw: return vk::Format::eR32Sint;// case StorageFormat::RG_F16: return vk::Format::eR16G16Sfloat; case StorageFormat::RG_F32: return vk::Format::eR32G32Sfloat; case StorageFormat::RG_I8: return vk::Format::eR8G8Uint; case StorageFormat::RG_8: return vk::Format::eR8G8Unorm; case StorageFormat::RG_16: return vk::Format::eR16G16Unorm; case StorageFormat::RG_I16: return vk::Format::eR16G16Uint; case StorageFormat::RG_I32_Raw: return vk::Format::eR32G32Sint;// case StorageFormat::RGBA_F16: return vk::Format::eR16G16B16A16Sfloat; case StorageFormat::RGBA_F32: return vk::Format::eR32G32B32A32Sfloat; case StorageFormat::RGBA_8: return vk::Format::eR8G8B8A8Unorm; case StorageFormat::RGBA_8_SRGB: return vk::Format::eR8G8B8A8Srgb; case StorageFormat::RGBA_16: return vk::Format::eR16G16B16A16Snorm; case StorageFormat::RGBA_I8: return vk::Format::eR8G8B8A8Uint; case StorageFormat::RGBA_I16: return vk::Format::eR16G16B16A16Uint; case StorageFormat::RGBA_I32_Raw: return vk::Format::eR32G32B32A32Sint;// case StorageFormat::BC1: return vk::Format::eBc1RgbUnormBlock;// case StorageFormat::BC1_SRGB: return vk::Format::eBc1RgbSrgbBlock;// case StorageFormat::BC5: return vk::Format::eBc5UnormBlock; case StorageFormat::BC3: return vk::Format::eBc3UnormBlock; case StorageFormat::BC6H: return vk::Format::eBc6HUfloatBlock; case StorageFormat::RGBA_Compressed: return vk::Format::eBc7UnormBlock;// case StorageFormat::R11F_G11F_B10F: return vk::Format::eB10G11R11UfloatPack32; // need to swizzle? case StorageFormat::RGB10_A2: return vk::Format::eA2R10G10B10UnormPack32;// case StorageFormat::Depth24: return vk::Format::eX8D24UnormPack32; case StorageFormat::Depth32: return vk::Format::eD32Sfloat; case StorageFormat::Depth24Stencil8: return vk::Format::eD24UnormS8Uint; default: CORELIB_NOT_IMPLEMENTED("TranslateStorageFormat"); } }; vk::BufferUsageFlags TranslateUsageFlags(BufferUsage usage) { switch (usage) { case BufferUsage::ArrayBuffer: return vk::BufferUsageFlagBits::eVertexBuffer; case BufferUsage::IndexBuffer: return vk::BufferUsageFlagBits::eIndexBuffer; case BufferUsage::StorageBuffer: return vk::BufferUsageFlagBits::eStorageBuffer; case BufferUsage::UniformBuffer: return vk::BufferUsageFlagBits::eUniformBuffer; default: CORELIB_NOT_IMPLEMENTED("TranslateUsageFlags"); } } vk::Format TranslateVertexAttribute(VertexAttributeDesc attribute) { switch (attribute.Type) { case DataType::Byte: return attribute.Normalized ? vk::Format::eR8Unorm : vk::Format::eR8Uint; case DataType::Char: return attribute.Normalized ? vk::Format::eR8Snorm : vk::Format::eR8Sint; case DataType::Byte2: return attribute.Normalized ? vk::Format::eR8G8Unorm : vk::Format::eR8G8Uint; case DataType::Char2: return attribute.Normalized ? vk::Format::eR8G8Snorm : vk::Format::eR8G8Sint; case DataType::Byte3: return attribute.Normalized ? vk::Format::eR8G8B8Unorm : vk::Format::eR8G8B8Uint; case DataType::Char3: return attribute.Normalized ? vk::Format::eR8G8B8Snorm : vk::Format::eR8G8B8Sint; case DataType::Byte4: return attribute.Normalized ? vk::Format::eR8G8B8A8Unorm : vk::Format::eR8G8B8A8Uint; case DataType::Char4: return attribute.Normalized ? vk::Format::eR8G8B8A8Snorm : vk::Format::eR8G8B8A8Sint; case DataType::Short: return attribute.Normalized ? vk::Format::eR16Snorm : vk::Format::eR16Sint; case DataType::UShort: return attribute.Normalized ? vk::Format::eR16Unorm : vk::Format::eR16Uint; case DataType::Half: return attribute.Normalized ? throw HardwareRendererException("Unsupported data type.") : vk::Format::eR16Sfloat;// case DataType::Short2: return attribute.Normalized ? vk::Format::eR16G16Snorm : vk::Format::eR16G16Sint; case DataType::UShort2: return attribute.Normalized ? vk::Format::eR16G16Unorm : vk::Format::eR16G16Uint; case DataType::Half2: return attribute.Normalized ? throw HardwareRendererException("Unsupported data type.") : vk::Format::eR16G16Sfloat;// case DataType::Short3: return attribute.Normalized ? vk::Format::eR16G16B16Snorm : vk::Format::eR16G16B16Sint; case DataType::UShort3: return attribute.Normalized ? vk::Format::eR16G16B16Unorm : vk::Format::eR16G16B16Uint; case DataType::Half3: return attribute.Normalized ? throw HardwareRendererException("Unsupported data type.") : vk::Format::eR16G16B16Sfloat;// case DataType::Short4: return attribute.Normalized ? vk::Format::eR16G16B16A16Snorm : vk::Format::eR16G16B16A16Sint; case DataType::UShort4: return attribute.Normalized ? vk::Format::eR16G16B16A16Unorm : vk::Format::eR16G16B16A16Uint; case DataType::Half4: return attribute.Normalized ? vk::Format::eR16G16B16A16Snorm : vk::Format::eR16G16B16A16Sfloat;// case DataType::Int: return attribute.Normalized ? throw HardwareRendererException("Unsupported data type.") : vk::Format::eR32Sint; case DataType::UInt: return attribute.Normalized ? throw HardwareRendererException("Unsupported data type.") : vk::Format::eR32Uint; case DataType::Float: return attribute.Normalized ? throw HardwareRendererException("Unsupported data type.") : vk::Format::eR32Sfloat; case DataType::Int2: return attribute.Normalized ? throw HardwareRendererException("Unsupported data type.") : vk::Format::eR32G32Sint; case DataType::Float2: return attribute.Normalized ? throw HardwareRendererException("Unsupported data type.") : vk::Format::eR32G32Sfloat; case DataType::Int3: return attribute.Normalized ? throw HardwareRendererException("Unsupported data type.") : vk::Format::eR32G32B32Sint; case DataType::Float3: return attribute.Normalized ? throw HardwareRendererException("Unsupported data type.") : vk::Format::eR32G32B32Sfloat; case DataType::Int4: return attribute.Normalized ? throw HardwareRendererException("Unsupported data type.") : vk::Format::eR32G32B32A32Sint; case DataType::UInt4_10_10_10_2: throw HardwareRendererException("Unsupported data type."); case DataType::Float4: return attribute.Normalized ? throw HardwareRendererException("Unsupported data type.") : vk::Format::eR32G32B32Sfloat; default: throw HardwareRendererException("Unimplemented data type."); } } vk::DescriptorType TranslateBindingType(BindingType bindType) { switch (bindType) { case BindingType::Texture: return vk::DescriptorType::eSampledImage; case BindingType::StorageTexture: return vk::DescriptorType::eStorageImage; case BindingType::Sampler: return vk::DescriptorType::eSampler; case BindingType::UniformBuffer: return vk::DescriptorType::eUniformBuffer; case BindingType::StorageBuffer: return vk::DescriptorType::eStorageBuffer; case BindingType::RWStorageBuffer: return vk::DescriptorType::eStorageBuffer; case BindingType::Unused: throw HardwareRendererException("Attempting to use unused binding"); default: CORELIB_NOT_IMPLEMENTED("TranslateBindingType"); } } vk::ShaderStageFlags TranslateStageFlags(StageFlags flag) { switch (flag) { case StageFlags::sfVertex: return vk::ShaderStageFlagBits::eVertex; case StageFlags::sfFragment: return vk::ShaderStageFlagBits::eFragment; case StageFlags::sfGraphics:return vk::ShaderStageFlagBits::eAllGraphics; case StageFlags::sfCompute: return vk::ShaderStageFlagBits::eCompute; case StageFlags::sfGraphicsAndCompute: return vk::ShaderStageFlagBits::eCompute | vk::ShaderStageFlagBits::eAllGraphics; default: CORELIB_NOT_IMPLEMENTED("TranslateStageFlags"); } } vk::ImageLayout LayoutFromUsage(TextureUsage usage) { //TODO: fix this function to deal with the mask correctly switch (usage) { case TextureUsage::ColorAttachment: case TextureUsage::SampledColorAttachment: return vk::ImageLayout::eColorAttachmentOptimal; case TextureUsage::DepthAttachment: case TextureUsage::SampledDepthAttachment: return vk::ImageLayout::eDepthStencilAttachmentOptimal; case TextureUsage::Sampled: return vk::ImageLayout::eShaderReadOnlyOptimal; case TextureUsage::Storage: case TextureUsage::SampledStorage: return vk::ImageLayout::eGeneral; default: CORELIB_NOT_IMPLEMENTED("LayoutFromUsage"); } } vk::CompareOp TranslateCompareFunc(CompareFunc compareFunc) { switch (compareFunc) { case CompareFunc::Disabled: return vk::CompareOp::eNever; case CompareFunc::Equal: return vk::CompareOp::eEqual; case CompareFunc::Less: return vk::CompareOp::eLess; case CompareFunc::Greater: return vk::CompareOp::eGreater; case CompareFunc::LessEqual: return vk::CompareOp::eLessOrEqual; case CompareFunc::GreaterEqual: return vk::CompareOp::eGreaterOrEqual; case CompareFunc::NotEqual: return vk::CompareOp::eNotEqual; case CompareFunc::Always: return vk::CompareOp::eAlways; case CompareFunc::Never: return vk::CompareOp::eNever; default: CORELIB_NOT_IMPLEMENTED("TranslateCompareFunc"); } } vk::StencilOp TranslateStencilOp(StencilOp stencilOp) { switch (stencilOp) { case StencilOp::Keep: return vk::StencilOp::eKeep; case StencilOp::Zero: return vk::StencilOp::eZero; case StencilOp::Replace: return vk::StencilOp::eReplace; case StencilOp::Increment: return vk::StencilOp::eIncrementAndClamp; case StencilOp::IncrementWrap: return vk::StencilOp::eIncrementAndWrap; case StencilOp::Decrement: return vk::StencilOp::eDecrementAndClamp; case StencilOp::DecrementWrap: return vk::StencilOp::eDecrementAndWrap; case StencilOp::Invert: return vk::StencilOp::eInvert; default: CORELIB_NOT_IMPLEMENTED("TranslateStencilOp"); } } vk::CullModeFlags TranslateCullMode(CullMode mode) { switch (mode) { case CullMode::CullBackFace: return vk::CullModeFlagBits::eBack; case CullMode::CullFrontFace: return vk::CullModeFlagBits::eFront; case CullMode::Disabled: return vk::CullModeFlagBits::eNone; default: throw CoreLib::NotImplementedException("TranslateCullMode"); } } vk::PrimitiveTopology TranslatePrimitiveTopology(PrimitiveType ptype) { switch (ptype) { case PrimitiveType::Triangles: return vk::PrimitiveTopology::eTriangleList; case PrimitiveType::Points: return vk::PrimitiveTopology::ePointList; case PrimitiveType::Lines: return vk::PrimitiveTopology::eLineList; case PrimitiveType::TriangleStrips: return vk::PrimitiveTopology::eTriangleStrip; case PrimitiveType::LineStrips: return vk::PrimitiveTopology::eLineStrip; default: CORELIB_NOT_IMPLEMENTED("TranslatePrimitiveTopology"); } } vk::AttachmentLoadOp TranslateLoadOp(LoadOp op) { switch (op) { case LoadOp::Load: return vk::AttachmentLoadOp::eLoad; case LoadOp::Clear: return vk::AttachmentLoadOp::eClear; case LoadOp::DontCare: return vk::AttachmentLoadOp::eDontCare; default: CORELIB_NOT_IMPLEMENTED("TranslateLoadOp"); } } vk::AttachmentStoreOp TranslateStoreOp(StoreOp op) { switch (op) { case StoreOp::Store: return vk::AttachmentStoreOp::eStore; case StoreOp::DontCare: return vk::AttachmentStoreOp::eDontCare; default: CORELIB_NOT_IMPLEMENTED("TranslateStoreOp"); } } /* * Vulkan helper functions */ vk::AccessFlags LayoutFlags(vk::ImageLayout layout) { switch (layout) { case vk::ImageLayout::eUndefined: return vk::AccessFlags(); case vk::ImageLayout::eGeneral: return vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eInputAttachmentRead | vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite; case vk::ImageLayout::eColorAttachmentOptimal: return vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eInputAttachmentRead; case vk::ImageLayout::eDepthStencilAttachmentOptimal: return vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite; case vk::ImageLayout::eDepthStencilReadOnlyOptimal: return vk::AccessFlagBits::eDepthStencilAttachmentRead; case vk::ImageLayout::eShaderReadOnlyOptimal: return vk::AccessFlagBits::eShaderRead; case vk::ImageLayout::eTransferSrcOptimal: return vk::AccessFlagBits::eTransferRead; case vk::ImageLayout::eTransferDstOptimal: return vk::AccessFlagBits::eTransferWrite; case vk::ImageLayout::ePreinitialized: return vk::AccessFlagBits::eHostWrite; case vk::ImageLayout::ePresentSrcKHR: return vk::AccessFlagBits::eMemoryRead; default: CORELIB_ABORT("Invalid ImageLayout"); } } vk::SampleCountFlagBits SampleCount(int samples) { if (samples <= 0 || (samples & (samples - 1)) != 0) CORELIB_ABORT("samples must be a power of 2"); return (vk::SampleCountFlagBits)samples; } int32_t GetMemoryType(uint32_t memoryTypeBits, vk::MemoryPropertyFlags memoryPropertyFlags) { int32_t memoryTypeIndex = 0; auto memProperties = RendererState::PhysicalDevice().getMemoryProperties(); for (uint32_t k = 0; k < 32; k++) { if ((memoryTypeBits & 1) == 1) { if ((memProperties.memoryTypes[k].propertyFlags & memoryPropertyFlags) == memoryPropertyFlags) { memoryTypeIndex = k; return memoryTypeIndex; } } memoryTypeBits >>= 1; } CORELIB_ABORT("Could not find a valid memory type index."); } vk::ShaderStageFlagBits ShaderStage(ShaderType stage) { switch (stage) { case ShaderType::VertexShader: return vk::ShaderStageFlagBits::eVertex; case ShaderType::FragmentShader: return vk::ShaderStageFlagBits::eFragment; case ShaderType::ComputeShader: return vk::ShaderStageFlagBits::eCompute; default: CORELIB_NOT_IMPLEMENTED("ShaderStageFlagBits"); } } class Texture : public CoreLib::Object { public: StorageFormat format; TextureUsage usage; int width; int height; int depth; int mipLevels; int arrayLayers; int numSamples; bool isCubeArray = false; vk::Image image; CoreLib::List<vk::ImageView> views; vk::DeviceMemory memory; uint32_t lastLayoutCheckTaskId = 0; CoreLib::List<vk::ImageLayout> currentSubresourceLayouts; Texture(String name, TextureUsage usage, int width, int height, int depth, int mipLevels, int arrayLayers, int numSamples, StorageFormat format, bool isArray, vk::ImageCreateFlags createFlags = vk::ImageCreateFlags()) { this->usage = usage; this->format = format; this->width = width; this->height = height; this->depth = depth; this->mipLevels = mipLevels; this->arrayLayers = arrayLayers; this->numSamples = numSamples; this->currentSubresourceLayouts.SetSize(arrayLayers * mipLevels); for (auto& currentLayout : this->currentSubresourceLayouts) currentLayout = vk::ImageLayout::eUndefined; // Create texture resources vk::ImageAspectFlags aspectFlags = vk::ImageAspectFlagBits::eColor; vk::ImageUsageFlags usageFlags; if (!!(this->usage & TextureUsage::ColorAttachment)) { aspectFlags = vk::ImageAspectFlagBits::eColor; usageFlags = vk::ImageUsageFlagBits::eColorAttachment; } else if (!!(this->usage & TextureUsage::DepthAttachment)) { aspectFlags = vk::ImageAspectFlagBits::eDepth; usageFlags = vk::ImageUsageFlagBits::eDepthStencilAttachment; if (this->format == StorageFormat::Depth24Stencil8) aspectFlags |= vk::ImageAspectFlagBits::eStencil; } if (!!(this->usage & TextureUsage::Sampled)) { usageFlags |= vk::ImageUsageFlagBits::eSampled; } if (!!(this->usage & TextureUsage::Storage)) { usageFlags |= vk::ImageUsageFlagBits::eStorage; } vk::ImageCreateInfo imageCreateInfo = vk::ImageCreateInfo() .setFlags(createFlags) .setImageType(depth == 1 ? vk::ImageType::e2D : vk::ImageType::e3D) .setFormat(TranslateStorageFormat(this->format)) .setExtent(vk::Extent3D(width, height, depth)) .setMipLevels(mipLevels) .setArrayLayers(arrayLayers) .setSamples(SampleCount(numSamples)) .setTiling(vk::ImageTiling::eOptimal) .setUsage(vk::ImageUsageFlagBits::eTransferSrc | vk::ImageUsageFlagBits::eTransferDst | usageFlags) .setSharingMode(vk::SharingMode::eExclusive) .setQueueFamilyIndexCount(0) .setPQueueFamilyIndices(nullptr) .setInitialLayout(vk::ImageLayout::eUndefined); image = RendererState::Device().createImage(imageCreateInfo); vk::MemoryRequirements imageMemoryRequirements = RendererState::Device().getImageMemoryRequirements(image); vk::MemoryAllocateInfo imageAllocateInfo = vk::MemoryAllocateInfo() .setAllocationSize(imageMemoryRequirements.size) .setMemoryTypeIndex(GetMemoryType(imageMemoryRequirements.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal)); memory = RendererState::Device().allocateMemory(imageAllocateInfo); RendererState::Device().bindImageMemory(image, memory, 0); vk::ImageSubresourceRange imageSubresourceRange = vk::ImageSubresourceRange() .setAspectMask(aspectFlags) .setBaseMipLevel(0) .setLevelCount(mipLevels) .setBaseArrayLayer(0) .setLayerCount(arrayLayers); vk::ImageViewType viewType = vk::ImageViewType::e2D; if (depth == 1) { if (createFlags & vk::ImageCreateFlagBits::eCubeCompatible) { if (isArray) viewType = vk::ImageViewType::eCubeArray; else viewType = vk::ImageViewType::eCube; } else if (isArray) viewType = vk::ImageViewType::e2DArray; } else viewType = vk::ImageViewType::e3D; vk::ImageViewCreateInfo imageViewCreateInfo = vk::ImageViewCreateInfo() .setFlags(vk::ImageViewCreateFlags()) .setImage(image) .setViewType(viewType) .setFormat(imageCreateInfo.format) .setComponents(vk::ComponentMapping(vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eG, vk::ComponentSwizzle::eB, vk::ComponentSwizzle::eA))// .setSubresourceRange(imageSubresourceRange); views.Add(RendererState::Device().createImageView(imageViewCreateInfo)); if (isDepthFormat(this->format)) { aspectFlags = vk::ImageAspectFlagBits::eDepth; imageSubresourceRange = vk::ImageSubresourceRange() .setAspectMask(aspectFlags) .setBaseMipLevel(0) .setLevelCount(1) .setBaseArrayLayer(0) .setLayerCount(arrayLayers); imageViewCreateInfo = vk::ImageViewCreateInfo() .setFlags(vk::ImageViewCreateFlags()) .setImage(image) .setViewType(viewType) .setFormat(imageCreateInfo.format) .setComponents(vk::ComponentMapping(vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eR))// .setSubresourceRange(imageSubresourceRange); views.Add(RendererState::Device().createImageView(imageViewCreateInfo)); } if (this->format == StorageFormat::Depth24Stencil8) { aspectFlags = vk::ImageAspectFlagBits::eStencil; imageSubresourceRange = vk::ImageSubresourceRange() .setAspectMask(aspectFlags) .setBaseMipLevel(0) .setLevelCount(1) .setBaseArrayLayer(0) .setLayerCount(arrayLayers); imageViewCreateInfo = vk::ImageViewCreateInfo() .setFlags(vk::ImageViewCreateFlags()) .setImage(image) .setViewType(viewType) .setFormat(imageCreateInfo.format) .setComponents(vk::ComponentMapping(vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eR))// .setSubresourceRange(imageSubresourceRange); views.Add(RendererState::Device().createImageView(imageViewCreateInfo)); } #ifdef _DEBUG if (vkDebugMarkerSetObjectNameEXT) { vk::DebugMarkerObjectNameInfoEXT nameInfo = vk::DebugMarkerObjectNameInfoEXT() .setObject((uint64_t)(VkImage)image) .setObjectType(vk::DebugReportObjectTypeEXT::eImage) .setPObjectName(name.Buffer()); vkDebugMarkerSetObjectNameEXT(RendererState::Device(), &(VkDebugMarkerObjectNameInfoEXT&)nameInfo); } #else CORELIB_UNUSED(name); #endif } ~Texture() { if (memory) RendererState::Device().freeMemory(memory); for (auto view : views) RendererState::Device().destroyImageView(view); if (image) RendererState::Device().destroyImage(image); } void TransferLayout(vk::ImageLayout targetLayout, List<vk::ImageMemoryBarrier>& imageBarriers) { struct LayoutTransferOp { vk::ImageSubresourceRange subresourceRange; vk::ImageLayout oldLayout; }; CoreLib::ShortList<LayoutTransferOp> transferOps; vk::CommandBuffer transferCommandBuffer = RendererState::GetTempTransferCommandBuffer(); vk::ImageAspectFlags aspectFlags; if (isDepthFormat(format)) { aspectFlags = vk::ImageAspectFlagBits::eDepth; if (format == StorageFormat::Depth24Stencil8) aspectFlags |= vk::ImageAspectFlagBits::eStencil; } else aspectFlags = vk::ImageAspectFlagBits::eColor; // Record command buffer transferOps.Clear(); for (int i = 0; i < arrayLayers; i++) { for (int j = 0; j < mipLevels; j++) { int subresourceIndex = i * mipLevels + j; if (currentSubresourceLayouts[subresourceIndex] != targetLayout) { vk::ImageSubresourceRange range = vk::ImageSubresourceRange() .setAspectMask(aspectFlags) .setBaseMipLevel(j) .setLevelCount(1) .setBaseArrayLayer(i) .setLayerCount(1); if (transferOps.Count()) { auto& last = transferOps.Last(); if (last.subresourceRange.baseArrayLayer == (uint32_t)i && last.oldLayout == currentSubresourceLayouts[subresourceIndex] && last.subresourceRange.baseMipLevel + last.subresourceRange.levelCount == (uint32_t)j) { last.subresourceRange.levelCount++; if (transferOps.Count() > 1) { auto& last2 = transferOps[transferOps.Count() - 2]; if (last2.oldLayout == last.oldLayout && last2.subresourceRange.baseArrayLayer + last2.subresourceRange.layerCount == (uint32_t)i && last2.subresourceRange.baseMipLevel == last.subresourceRange.baseMipLevel && last2.subresourceRange.levelCount == last.subresourceRange.levelCount) { last2.subresourceRange.layerCount++; transferOps.SetSize(transferOps.Count() - 1); } } continue; } } transferOps.Add(LayoutTransferOp{ range, currentSubresourceLayouts[subresourceIndex] }); } } } for (int i = 0; i < transferOps.Count(); i++) { vk::ImageMemoryBarrier textureUsageBarrier = vk::ImageMemoryBarrier() .setSrcAccessMask(LayoutFlags(transferOps[i].oldLayout)) .setDstAccessMask(LayoutFlags(targetLayout)) .setOldLayout(transferOps[i].oldLayout) .setNewLayout(targetLayout) .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setImage(this->image) .setSubresourceRange(transferOps[i].subresourceRange); imageBarriers.Add(textureUsageBarrier); } for (auto& currentLayout : currentSubresourceLayouts) currentLayout = targetLayout; } DataType GetDataTypeElementType(DataType type) { return (DataType)((int)(type)&(~3)); } void SetData(int level, int layer, int xOffset, int yOffset, int zOffset, int pwidth, int pheight, int pdepth, int layerCount, DataType inputType, void* data) { CORELIB_ASSERT(numSamples == 1 && "samples must be equal to 1"); CORELIB_ASSERT(this->mipLevels > level && "Attempted to set mipmap data for invalid level"); CORELIB_ASSERT(this->mipLevels > level && "Attempted to set layer data for invalid layer"); vk::ImageAspectFlags aspectFlags; if (isDepthFormat(format)) { aspectFlags = vk::ImageAspectFlagBits::eDepth; if (format == StorageFormat::Depth24Stencil8) aspectFlags |= vk::ImageAspectFlagBits::eStencil; } else aspectFlags = vk::ImageAspectFlagBits::eColor; int dataTypeSize = DataTypeSize(inputType); List<unsigned short> translatedBuffer; if (data && (format == StorageFormat::R_F16 || format == StorageFormat::RG_F16 || format == StorageFormat::RGBA_F16) && (GetDataTypeElementType(inputType) != DataType::Half)) { // transcode f32 to f16 int channelCount = 1; switch (format) { case StorageFormat::RG_F16: channelCount = 2; break; case StorageFormat::RGBA_F16: channelCount = 4; break; default: channelCount = 1; break; } translatedBuffer.SetSize(pwidth * pheight * pdepth * layerCount * channelCount); float * src = (float*)data; for (int i = 0; i < translatedBuffer.Count(); i++) translatedBuffer[i] = FloatToHalf(src[i]); dataTypeSize >>= 1; data = (void*)translatedBuffer.Buffer(); } // Set up staging buffer and copy data to new image int bufferSize = pwidth * pheight * pdepth * layerCount * dataTypeSize; if (format == StorageFormat::BC1 || format == StorageFormat::BC1_SRGB|| format == StorageFormat::BC5 || format == StorageFormat::BC3 || format == StorageFormat::BC6H) { int blocks = (int)(ceil(pwidth / 4.0f) * ceil(pheight / 4.0f)); bufferSize = (format == StorageFormat::BC1||format == StorageFormat::BC1_SRGB) ? blocks * 8 : blocks * 16; bufferSize *= layerCount; } vk::BufferCreateInfo stagingBufferCreateInfo = vk::BufferCreateInfo() .setFlags(vk::BufferCreateFlags()) .setSize(bufferSize) .setUsage(vk::BufferUsageFlagBits::eTransferSrc) .setSharingMode(vk::SharingMode::eExclusive) .setQueueFamilyIndexCount(0) .setPQueueFamilyIndices(nullptr); vk::Buffer stagingBuffer = RendererState::Device().createBuffer(stagingBufferCreateInfo); vk::MemoryRequirements stagingBufferMemoryRequirements = RendererState::Device().getBufferMemoryRequirements(stagingBuffer); vk::MemoryAllocateInfo bufferAllocateInfo = vk::MemoryAllocateInfo() .setAllocationSize(stagingBufferMemoryRequirements.size) .setMemoryTypeIndex(GetMemoryType(stagingBufferMemoryRequirements.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible)); vk::DeviceMemory stagingMemory = RendererState::Device().allocateMemory(bufferAllocateInfo); RendererState::Device().bindBufferMemory(stagingBuffer, stagingMemory, 0); void* stagingMappedMemory = RendererState::Device().mapMemory(stagingMemory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags()); if (data) { memcpy(stagingMappedMemory, data, bufferSize); } else { memset(stagingMappedMemory, 0, bufferSize); } RendererState::Device().flushMappedMemoryRanges(vk::MappedMemoryRange(stagingMemory, 0, VK_WHOLE_SIZE)); RendererState::Device().unmapMemory(stagingMemory); // Create buffer image copy information vk::BufferImageCopy stagingCopy = vk::BufferImageCopy() .setBufferOffset(0) .setBufferRowLength(0) .setBufferImageHeight(0) .setImageSubresource(vk::ImageSubresourceLayers().setAspectMask(aspectFlags).setMipLevel(level).setBaseArrayLayer(layer).setLayerCount(layerCount)) .setImageOffset(vk::Offset3D(xOffset, yOffset, zOffset)) .setImageExtent(vk::Extent3D(pwidth, pheight, pdepth)); // Create command buffer //TODO: Use CommandBuffer class? vk::CommandBuffer transferCommandBuffer = RendererState::GetTempTransferCommandBuffer(); // Record command buffer vk::CommandBufferBeginInfo transferBeginInfo = vk::CommandBufferBeginInfo() .setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit) .setPInheritanceInfo(nullptr); transferCommandBuffer.begin(transferBeginInfo); List<vk::ImageMemoryBarrier> barriers; barriers.Clear(); for (int i = 0; i < mipLevels; i++) { vk::ImageSubresourceRange textureSubresourceRange = vk::ImageSubresourceRange() .setAspectMask(aspectFlags) .setBaseMipLevel(i) .setLevelCount(1) .setBaseArrayLayer(0) .setLayerCount(arrayLayers); vk::ImageMemoryBarrier textureCopyBarrier = vk::ImageMemoryBarrier() .setSrcAccessMask(LayoutFlags(vk::ImageLayout::eUndefined)) .setDstAccessMask(LayoutFlags(vk::ImageLayout::eTransferDstOptimal)) .setOldLayout(vk::ImageLayout::eUndefined) .setNewLayout(vk::ImageLayout::eTransferDstOptimal) .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setImage(this->image) .setSubresourceRange(textureSubresourceRange); barriers.Add(textureCopyBarrier); } transferCommandBuffer.pipelineBarrier( vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer, vk::DependencyFlags(), nullptr, nullptr, vk::ArrayProxy<const vk::ImageMemoryBarrier>(barriers.Count(), barriers.Buffer()) ); transferCommandBuffer.copyBufferToImage( stagingBuffer, this->image, vk::ImageLayout::eTransferDstOptimal, stagingCopy ); barriers.Clear(); for (int i = 0; i < mipLevels; i++) { vk::ImageSubresourceRange textureSubresourceRange = vk::ImageSubresourceRange() .setAspectMask(aspectFlags) .setBaseMipLevel(i) .setLevelCount(1) .setBaseArrayLayer(0) .setLayerCount(arrayLayers); vk::ImageMemoryBarrier textureUsageBarrier = vk::ImageMemoryBarrier() .setSrcAccessMask(LayoutFlags(vk::ImageLayout::eTransferDstOptimal)) .setDstAccessMask(LayoutFlags(LayoutFromUsage(this->usage))) .setOldLayout(vk::ImageLayout::eTransferDstOptimal) .setNewLayout(LayoutFromUsage(this->usage)) .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setImage(this->image) .setSubresourceRange(textureSubresourceRange); for (int l = 0; l < arrayLayers; l++) { int subresourceIndex = l * mipLevels + i; currentSubresourceLayouts[subresourceIndex] = LayoutFromUsage(this->usage); } barriers.Add(textureUsageBarrier); } transferCommandBuffer.pipelineBarrier( vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eAllCommands, vk::DependencyFlags(), nullptr, nullptr, vk::ArrayProxy<const vk::ImageMemoryBarrier>(barriers.Count(), barriers.Buffer()) ); transferCommandBuffer.end(); // Submit to queue vk::SubmitInfo transferSubmitInfo = vk::SubmitInfo() .setWaitSemaphoreCount(0) .setPWaitSemaphores(nullptr) .setPWaitDstStageMask(nullptr) .setCommandBufferCount(1) .setPCommandBuffers(&transferCommandBuffer) .setSignalSemaphoreCount(0) .setPSignalSemaphores(nullptr); RendererState::TransferQueue().submit(transferSubmitInfo, vk::Fence()); RendererState::TransferQueue().waitIdle(); // Destroy staging resources RendererState::Device().freeMemory(stagingMemory); RendererState::Device().destroyBuffer(stagingBuffer); for (auto& currentLayout : currentSubresourceLayouts) currentLayout = LayoutFromUsage(this->usage); } void GetData(int mipLevel, int arrayLayer, void* data, int bufSize) { CORELIB_UNUSED(bufSize); // Set up staging buffer and copy data to new image int bufferSize = 0; if (format == StorageFormat::BC1 || format == StorageFormat::BC1_SRGB || format == StorageFormat::BC5 || format == StorageFormat::BC3) { int blocks = (int)(ceil(width / 4.0f) * ceil(height / 4.0f)); bufferSize = (format == StorageFormat::BC1 || format == StorageFormat::BC1_SRGB) ? blocks * 8 : blocks * 16; } else { bufferSize = width * height * StorageFormatSize(format); } CORELIB_ASSERT(bufferSize <= bufSize && "buffer size is too small"); vk::BufferCreateInfo stagingBufferCreateInfo = vk::BufferCreateInfo() .setFlags(vk::BufferCreateFlags()) .setSize(bufferSize) .setUsage(vk::BufferUsageFlagBits::eTransferDst) .setSharingMode(vk::SharingMode::eExclusive) .setQueueFamilyIndexCount(0) .setPQueueFamilyIndices(nullptr); vk::Buffer stagingBuffer = RendererState::Device().createBuffer(stagingBufferCreateInfo); vk::MemoryRequirements stagingBufferMemoryRequirements = RendererState::Device().getBufferMemoryRequirements(stagingBuffer); vk::MemoryAllocateInfo bufferAllocateInfo = vk::MemoryAllocateInfo() .setAllocationSize(stagingBufferMemoryRequirements.size) .setMemoryTypeIndex(GetMemoryType(stagingBufferMemoryRequirements.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible)); vk::DeviceMemory stagingMemory = RendererState::Device().allocateMemory(bufferAllocateInfo); RendererState::Device().bindBufferMemory(stagingBuffer, stagingMemory, 0); // Get image aspect flags vk::ImageAspectFlags aspectFlags = vk::ImageAspectFlagBits::eColor; if (!!(usage & TextureUsage::ColorAttachment)) { aspectFlags = vk::ImageAspectFlagBits::eColor; } else if (!!(usage & TextureUsage::DepthAttachment)) { aspectFlags = vk::ImageAspectFlagBits::eDepth; if (format == StorageFormat::Depth24Stencil8) aspectFlags |= vk::ImageAspectFlagBits::eStencil; } // Create buffer image copy information vk::BufferImageCopy stagingCopy = vk::BufferImageCopy() .setBufferOffset(0) .setBufferRowLength(0) .setBufferImageHeight(0) .setImageSubresource(vk::ImageSubresourceLayers().setAspectMask(aspectFlags).setMipLevel(mipLevel).setBaseArrayLayer(arrayLayer).setLayerCount(1)) .setImageOffset(vk::Offset3D()) .setImageExtent(vk::Extent3D(Math::Max(1, width >> mipLevel), Math::Max(1, height >> mipLevel), 1)); // Create command buffer //TODO: Use CommandBuffer class? vk::CommandBuffer transferCommandBuffer = RendererState::CreateCommandBuffer(RendererState::TransferCommandPool()); // Record command buffer vk::ImageSubresourceRange textureSubresourceRange = vk::ImageSubresourceRange() .setAspectMask(aspectFlags) .setBaseMipLevel(0) .setLevelCount(mipLevels) .setBaseArrayLayer(0) .setLayerCount(arrayLayers); int subresourceIndex = arrayLayer * mipLevels + mipLevel; vk::ImageMemoryBarrier textureCopyBarrier = vk::ImageMemoryBarrier() .setSrcAccessMask(LayoutFlags(currentSubresourceLayouts[subresourceIndex])) .setDstAccessMask(LayoutFlags(vk::ImageLayout::eTransferSrcOptimal)) .setOldLayout(currentSubresourceLayouts[subresourceIndex]) .setNewLayout(vk::ImageLayout::eTransferSrcOptimal) .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setImage(this->image) .setSubresourceRange(textureSubresourceRange); vk::ImageMemoryBarrier textureUsageBarrier = vk::ImageMemoryBarrier() .setSrcAccessMask(LayoutFlags(vk::ImageLayout::eTransferSrcOptimal)) .setDstAccessMask(LayoutFlags(currentSubresourceLayouts[subresourceIndex])) .setOldLayout(vk::ImageLayout::eTransferSrcOptimal) .setNewLayout(currentSubresourceLayouts[subresourceIndex]) .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setImage(this->image) .setSubresourceRange(textureSubresourceRange); vk::CommandBufferBeginInfo transferBeginInfo = vk::CommandBufferBeginInfo() .setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit) .setPInheritanceInfo(nullptr); transferCommandBuffer.begin(transferBeginInfo); transferCommandBuffer.pipelineBarrier( vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eTransfer, vk::DependencyFlags(), nullptr, nullptr, textureCopyBarrier ); transferCommandBuffer.copyImageToBuffer( this->image, vk::ImageLayout::eTransferSrcOptimal, stagingBuffer, stagingCopy ); transferCommandBuffer.pipelineBarrier( vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eAllCommands, vk::DependencyFlags(), nullptr, nullptr, textureUsageBarrier ); transferCommandBuffer.end(); // Submit to queue vk::SubmitInfo transferSubmitInfo = vk::SubmitInfo() .setWaitSemaphoreCount(0) .setPWaitSemaphores(nullptr) .setPWaitDstStageMask(nullptr) .setCommandBufferCount(1) .setPCommandBuffers(&transferCommandBuffer) .setSignalSemaphoreCount(0) .setPSignalSemaphores(nullptr); RendererState::TransferQueue().submit(transferSubmitInfo, vk::Fence()); RendererState::TransferQueue().waitIdle(); RendererState::DestroyCommandBuffer(RendererState::TransferCommandPool(), transferCommandBuffer); // Map memory and copy assert(bufSize >= bufferSize); float* stagingMappedMemory = (float*)RendererState::Device().mapMemory(stagingMemory, 0, bufferSize, vk::MemoryMapFlags()); memcpy(data, stagingMappedMemory, bufferSize); RendererState::Device().unmapMemory(stagingMemory); // Destroy staging resources RendererState::Device().freeMemory(stagingMemory); RendererState::Device().destroyBuffer(stagingBuffer); } void BuildMipmaps() { vk::ImageAspectFlags aspectFlags; if (isDepthFormat(format)) { aspectFlags = vk::ImageAspectFlagBits::eDepth; if (format == StorageFormat::Depth24Stencil8) aspectFlags |= vk::ImageAspectFlagBits::eStencil; } else aspectFlags = vk::ImageAspectFlagBits::eColor; // Create command buffer vk::CommandBuffer transferCommandBuffer = RendererState::GetTempTransferCommandBuffer(); vk::Filter blitFilter = vk::Filter::eLinear; switch (format) { case StorageFormat::R_I8: case StorageFormat::R_I16: case StorageFormat::Int32_Raw: case StorageFormat::RG_I8: case StorageFormat::RG_I16: case StorageFormat::RG_I32_Raw: case StorageFormat::RGBA_I8: case StorageFormat::RGBA_I16: case StorageFormat::RGBA_I32_Raw: blitFilter = vk::Filter::eNearest; default: break; } vk::CommandBufferBeginInfo transferBeginInfo = vk::CommandBufferBeginInfo() .setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit) .setPInheritanceInfo(nullptr); transferCommandBuffer.begin(transferBeginInfo); vk::ImageSubresourceRange level0SubresourceRange = vk::ImageSubresourceRange() .setAspectMask(aspectFlags) .setBaseMipLevel(0) .setLevelCount(1) .setBaseArrayLayer(0) .setLayerCount(arrayLayers); vk::ImageMemoryBarrier textureSrcBarrier = vk::ImageMemoryBarrier() .setSrcAccessMask(LayoutFlags(currentSubresourceLayouts[0])) .setDstAccessMask(LayoutFlags(vk::ImageLayout::eTransferSrcOptimal)) .setOldLayout(currentSubresourceLayouts[0]) .setNewLayout(vk::ImageLayout::eTransferSrcOptimal) .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setImage(this->image) .setSubresourceRange(level0SubresourceRange); transferCommandBuffer.pipelineBarrier( vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eAllCommands, vk::DependencyFlags(), nullptr, nullptr, textureSrcBarrier ); for (int i = 1; i < mipLevels; i++) { // Record command buffer vk::ImageSubresourceRange textureSrcSubresourceRange = vk::ImageSubresourceRange() .setAspectMask(aspectFlags) .setBaseMipLevel(i - 1) .setLevelCount(1) .setBaseArrayLayer(0) .setLayerCount(arrayLayers); vk::ImageSubresourceRange textureDstSubresourceRange = vk::ImageSubresourceRange() .setAspectMask(aspectFlags) .setBaseMipLevel(i) .setLevelCount(1) .setBaseArrayLayer(0) .setLayerCount(arrayLayers); vk::ImageMemoryBarrier textureDstBarrier = vk::ImageMemoryBarrier() .setSrcAccessMask(LayoutFlags(vk::ImageLayout::eUndefined)) .setDstAccessMask(LayoutFlags(vk::ImageLayout::eTransferDstOptimal)) .setOldLayout(vk::ImageLayout::eUndefined) .setNewLayout(vk::ImageLayout::eTransferDstOptimal) .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setImage(this->image) .setSubresourceRange(textureDstSubresourceRange); transferCommandBuffer.pipelineBarrier( vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eAllCommands, vk::DependencyFlags(), nullptr, nullptr, textureDstBarrier ); vk::ImageBlit blitRegion; blitRegion.setSrcSubresource(vk::ImageSubresourceLayers().setAspectMask(aspectFlags).setMipLevel(i - 1).setBaseArrayLayer(0).setLayerCount(arrayLayers)) .setSrcOffsets(std::array<vk::Offset3D, 2>{vk::Offset3D(0, 0, 0), vk::Offset3D(Math::Max(1, width >> (i - 1)), Math::Max(1, height >> (i - 1)), Math::Max(1, depth >> (i - 1)))}) .setDstSubresource(vk::ImageSubresourceLayers().setAspectMask(aspectFlags).setMipLevel(i).setBaseArrayLayer(0).setLayerCount(arrayLayers)) .setDstOffsets(std::array<vk::Offset3D, 2>{vk::Offset3D(0, 0, 0), vk::Offset3D(Math::Max(1, width >> i), Math::Max(1, height >> i), Math::Max(1, depth >> i))}); // Blit texture to each mip level transferCommandBuffer.blitImage( image, vk::ImageLayout::eTransferSrcOptimal, image, vk::ImageLayout::eTransferDstOptimal, blitRegion, blitFilter ); vk::ImageMemoryBarrier textureDstFinishBarrier = vk::ImageMemoryBarrier() .setSrcAccessMask(LayoutFlags(vk::ImageLayout::eTransferDstOptimal)) .setDstAccessMask(LayoutFlags(vk::ImageLayout::eTransferSrcOptimal)) .setOldLayout(vk::ImageLayout::eTransferDstOptimal) .setNewLayout(vk::ImageLayout::eTransferSrcOptimal) .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setImage(this->image) .setSubresourceRange(textureDstSubresourceRange); transferCommandBuffer.pipelineBarrier( vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eAllCommands, vk::DependencyFlags(), nullptr, nullptr, textureDstFinishBarrier ); } vk::ImageSubresourceRange allSubresourceRange = vk::ImageSubresourceRange() .setAspectMask(aspectFlags) .setBaseMipLevel(0) .setLevelCount(mipLevels) .setBaseArrayLayer(0) .setLayerCount(arrayLayers); vk::ImageMemoryBarrier textureDstFinishBarrier = vk::ImageMemoryBarrier() .setSrcAccessMask(LayoutFlags(vk::ImageLayout::eTransferSrcOptimal)) .setDstAccessMask(LayoutFlags(currentSubresourceLayouts[0])) .setOldLayout(vk::ImageLayout::eTransferSrcOptimal) .setNewLayout(LayoutFromUsage(this->usage)) .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setImage(this->image) .setSubresourceRange(allSubresourceRange); transferCommandBuffer.pipelineBarrier( vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eAllCommands, vk::DependencyFlags(), nullptr, nullptr, textureDstFinishBarrier ); transferCommandBuffer.end(); // Submit to queue vk::SubmitInfo transferSubmitInfo = vk::SubmitInfo() .setWaitSemaphoreCount(0) .setPWaitSemaphores(nullptr) .setPWaitDstStageMask(nullptr) .setCommandBufferCount(1) .setPCommandBuffers(&transferCommandBuffer) .setSignalSemaphoreCount(0) .setPSignalSemaphores(nullptr); RendererState::TransferQueue().submit(transferSubmitInfo, vk::Fence()); for (auto& currentLayout : currentSubresourceLayouts) currentLayout = LayoutFromUsage(this->usage); } void* Ptr() { return this; } }; class Texture2D : public VK::Texture, public GameEngine::Texture2D { //TODO: Need some way of determining layouts and performing transitions properly. public: Texture2D(String name, TextureUsage usage, int width, int height, int mipLevelCount, StorageFormat format) : VK::Texture(name, usage, width, height, 1, mipLevelCount, 1, 1, format, false) {}; void GetSize(int& pwidth, int& pheight) override { pwidth = width; pheight = height; } virtual bool IsDepthStencilFormat() override { return this->format == StorageFormat::Depth24 || this->format == StorageFormat::Depth24Stencil8 || this->format == StorageFormat::Depth32; } void SetData(int level, int pwidth, int pheight, int /*numSamples*/, DataType inputType, void* data) override { VK::Texture::SetData(level, 0, 0, 0, 0, pwidth, pheight, 1, 1, inputType, data); } void SetData(int pwidth, int pheight, int /*numSamples*/, DataType inputType, void* data) override { VK::Texture::SetData(0, 0, 0, 0, 0, pwidth, pheight, 1, 1, inputType, data); } void BuildMipmaps() override { VK::Texture::BuildMipmaps(); } void GetData(int mipLevel, void * data, int bufSize) override { VK::Texture::GetData(mipLevel, 0, data, bufSize); } void* GetInternalPtr() override { return VK::Texture::Ptr(); } }; class Texture2DArray : public VK::Texture, public GameEngine::Texture2DArray { public: Texture2DArray(String name, TextureUsage usage, int width, int height, int mipLevels, int arrayLayers, StorageFormat newFormat) : VK::Texture(name, usage, width, height, 1, mipLevels, arrayLayers, 1, newFormat, true) {}; virtual void GetSize(int& pwidth, int& pheight, int& players) override { pwidth = this->width; pheight = this->height; players = this->arrayLayers; } virtual bool IsDepthStencilFormat() override { return this->format == StorageFormat::Depth24 || this->format == StorageFormat::Depth24Stencil8 || this->format == StorageFormat::Depth32; } virtual void SetData(int mipLevel, int xOffset, int yOffset, int layerOffset, int pwidth, int pheight, int layerCount, DataType inputType, void * data) override { VK::Texture::SetData(mipLevel, layerOffset, xOffset, yOffset, 0, pwidth, pheight, 1, layerCount, inputType, data); } virtual void BuildMipmaps() override { VK::Texture::BuildMipmaps(); } void* GetInternalPtr() override { return VK::Texture::Ptr(); } }; class TextureCube : public VK::Texture, public GameEngine::TextureCube { public: TextureCube(String name, TextureUsage usage, int psize, int mipLevels, StorageFormat format) : VK::Texture(name, usage, psize, psize, 1, mipLevels, 6, 1, format, false, vk::ImageCreateFlagBits::eCubeCompatible), size(psize) { List<float> zeroMem; zeroMem.SetSize(psize * psize * 6 * 4); for (int i = 0; i < zeroMem.Count(); i++) zeroMem[i] = 0.0f; for (int i = 0; i < mipLevels; i++) VK::Texture::SetData(i, 0, 0, 0, 0, psize >> i, psize >> i, 1, 6, DataType::Float4, zeroMem.Buffer()); }; int size = 0; virtual void GetSize(int & psize) override { psize = size; } virtual void SetData(int mipLevel, int xOffset, int yOffset, int layerOffset, int pwidth, int pheight, int layerCount, DataType inputType, void* data) override { VK::Texture::SetData(mipLevel, layerOffset, xOffset, yOffset, 0, pwidth, pheight, 1, layerCount, inputType, data); } virtual bool IsDepthStencilFormat() override { return this->format == StorageFormat::Depth24 || this->format == StorageFormat::Depth24Stencil8 || this->format == StorageFormat::Depth32; } void* GetInternalPtr() override { return VK::Texture::Ptr(); } }; class TextureCubeArray : public VK::Texture, public GameEngine::TextureCubeArray { public: int count; TextureCubeArray(String name, TextureUsage usage, int cubeCount, int psize, int mipLevels, StorageFormat format) : VK::Texture(name, usage, psize, psize, 1, mipLevels, cubeCount * 6, 1, format, true, vk::ImageCreateFlagBits::eCubeCompatible), size(psize) { this->isCubeArray = true; List<float> zeroMem; zeroMem.SetSize(psize * psize * 6 * 4 * cubeCount); for (int i = 0; i < zeroMem.Count(); i++) zeroMem[i] = 0.0f; for (int i = 0; i < mipLevels; i++) VK::Texture::SetData(i, 0, 0, 0, 0, psize >> i, psize >> i, 1, cubeCount * 6, DataType::Float4, zeroMem.Buffer()); count = cubeCount; }; int size = 0; virtual void GetSize(int & psize, int &pCount) override { psize = size; pCount = count; } virtual void SetData(int mipLevel, int xOffset, int yOffset, int layerOffset, int pwidth, int pheight, int layerCount, DataType inputType, void* data) override { VK::Texture::SetData(mipLevel, layerOffset, xOffset, yOffset, 0, pwidth, pheight, 1, layerCount, inputType, data); } virtual bool IsDepthStencilFormat() override { return this->format == StorageFormat::Depth24 || this->format == StorageFormat::Depth24Stencil8 || this->format == StorageFormat::Depth32; } void* GetInternalPtr() override { return VK::Texture::Ptr(); } }; class Texture3D : public VK::Texture, public GameEngine::Texture3D { public: Texture3D(String name, TextureUsage usage, int width, int height, int depth, int mipLevels, StorageFormat newFormat) : VK::Texture(name, usage, width, height, depth, mipLevels, 1, 1, newFormat, false) {}; virtual void GetSize(int& pwidth, int& pheight, int& pdepth) override { pwidth = this->width; pheight = this->height; pdepth = this->depth; } virtual void SetData(int mipLevel, int xOffset, int yOffset, int zOffset, int pwidth, int pheight, int pdepth, DataType inputType, void * data) override { VK::Texture::SetData(mipLevel, 0, xOffset, yOffset, zOffset, pwidth, pheight, pdepth, 1, inputType, data); } virtual bool IsDepthStencilFormat() override { return this->format == StorageFormat::Depth24 || this->format == StorageFormat::Depth24Stencil8 || this->format == StorageFormat::Depth32; } void* GetInternalPtr() override { return VK::Texture::Ptr(); } }; class TextureSampler : public GameEngine::TextureSampler { public: vk::Sampler sampler; TextureFilter filter = TextureFilter::Nearest; WrapMode wrap = WrapMode::Repeat; CompareFunc op = CompareFunc::Disabled; void CreateSampler() { DestroySampler(); // Default sampler create info vk::SamplerCreateInfo samplerCreateInfo = vk::SamplerCreateInfo() .setFlags(vk::SamplerCreateFlags()) .setMinFilter(vk::Filter::eNearest) .setMagFilter(vk::Filter::eNearest) .setMipmapMode(vk::SamplerMipmapMode::eNearest) .setAddressModeU(vk::SamplerAddressMode::eRepeat) .setAddressModeV(vk::SamplerAddressMode::eRepeat) .setAddressModeW(vk::SamplerAddressMode::eRepeat) .setMipLodBias(0.0f) .setAnisotropyEnable(VK_FALSE) .setMaxAnisotropy(1.0f) .setCompareEnable(op != CompareFunc::Disabled) .setCompareOp(TranslateCompareFunc(op)) .setMinLod(0.0f) .setMaxLod(0.0f) .setBorderColor(vk::BorderColor::eFloatTransparentBlack) .setUnnormalizedCoordinates(VK_FALSE); // Modify create info based on parameters switch (filter) { case TextureFilter::Nearest: samplerCreateInfo.setMinFilter(vk::Filter::eNearest); samplerCreateInfo.setMagFilter(vk::Filter::eNearest); break; case TextureFilter::Linear: samplerCreateInfo.setMinFilter(vk::Filter::eLinear); samplerCreateInfo.setMagFilter(vk::Filter::eLinear); break; case TextureFilter::Trilinear: samplerCreateInfo.setMinFilter(vk::Filter::eLinear); samplerCreateInfo.setMagFilter(vk::Filter::eLinear); samplerCreateInfo.setMipmapMode(vk::SamplerMipmapMode::eLinear); samplerCreateInfo.setMaxLod(15.0f); break; case TextureFilter::Anisotropic4x: samplerCreateInfo.setMinFilter(vk::Filter::eLinear); samplerCreateInfo.setMagFilter(vk::Filter::eLinear); samplerCreateInfo.setMipmapMode(vk::SamplerMipmapMode::eLinear); samplerCreateInfo.setMaxLod(15.0f); samplerCreateInfo.setAnisotropyEnable(VK_TRUE); samplerCreateInfo.setMaxAnisotropy(4.0f); break; case TextureFilter::Anisotropic8x: samplerCreateInfo.setMinFilter(vk::Filter::eLinear); samplerCreateInfo.setMagFilter(vk::Filter::eLinear); samplerCreateInfo.setMipmapMode(vk::SamplerMipmapMode::eLinear); samplerCreateInfo.setMaxLod(15.0f); samplerCreateInfo.setAnisotropyEnable(VK_TRUE); samplerCreateInfo.setMaxAnisotropy(8.0f); break; case TextureFilter::Anisotropic16x: samplerCreateInfo.setMinFilter(vk::Filter::eLinear); samplerCreateInfo.setMagFilter(vk::Filter::eLinear); samplerCreateInfo.setMipmapMode(vk::SamplerMipmapMode::eLinear); samplerCreateInfo.setMaxLod(15.0f); samplerCreateInfo.setAnisotropyEnable(VK_TRUE); samplerCreateInfo.setMaxAnisotropy(16.0f); break; } switch (wrap) { case WrapMode::Clamp: samplerCreateInfo.setAddressModeU(vk::SamplerAddressMode::eClampToEdge); samplerCreateInfo.setAddressModeV(vk::SamplerAddressMode::eClampToEdge); samplerCreateInfo.setAddressModeW(vk::SamplerAddressMode::eClampToEdge); break; case WrapMode::Repeat: samplerCreateInfo.setAddressModeU(vk::SamplerAddressMode::eRepeat); samplerCreateInfo.setAddressModeV(vk::SamplerAddressMode::eRepeat); samplerCreateInfo.setAddressModeW(vk::SamplerAddressMode::eRepeat); break; case WrapMode::Mirror: samplerCreateInfo.setAddressModeU(vk::SamplerAddressMode::eMirroredRepeat); samplerCreateInfo.setAddressModeV(vk::SamplerAddressMode::eMirroredRepeat); samplerCreateInfo.setAddressModeW(vk::SamplerAddressMode::eMirroredRepeat); break; } sampler = RendererState::Device().createSampler(samplerCreateInfo); } void DestroySampler() { if (sampler) RendererState::Device().destroySampler(sampler); } public: TextureSampler() { CreateSampler(); } ~TextureSampler() { DestroySampler(); } TextureFilter GetFilter() { return filter; } void SetFilter(TextureFilter pfilter) { filter = pfilter; // If anisotropy is not supported and we want anisotropic filtering, make trilinear filter if (!RendererState::PhysicalDevice().getFeatures().samplerAnisotropy) { if (filter == TextureFilter::Anisotropic4x || filter == TextureFilter::Anisotropic8x || filter == TextureFilter::Anisotropic16x) { CoreLib::Diagnostics::Debug::WriteLine("Anisotropic filtering is not supported. Changing to trilinear."); filter = TextureFilter::Trilinear; } } else { TextureFilter oldFilter = filter; float maxAnisotropy = RendererState::PhysicalDevice().getProperties().limits.maxSamplerAnisotropy; switch (filter) { case TextureFilter::Anisotropic16x: if (maxAnisotropy < 16.0f) filter = TextureFilter::Anisotropic8x; // Fall through case TextureFilter::Anisotropic8x: if (maxAnisotropy < 8.0f) filter = TextureFilter::Anisotropic4x; // Fall through case TextureFilter::Anisotropic4x: if (maxAnisotropy < 4.0f) filter = TextureFilter::Trilinear; // Fall through default: break; } if (oldFilter != filter) { CoreLib::Diagnostics::Debug::Write("Max supported anisotropy is "); CoreLib::Diagnostics::Debug::WriteLine(maxAnisotropy); } } CreateSampler(); } WrapMode GetWrapMode() { return wrap; } void SetWrapMode(WrapMode pwrap) { this->wrap = pwrap; CreateSampler(); } CompareFunc GetCompareFunc() { return op; } void SetDepthCompare(CompareFunc pop) { this->op = pop; CreateSampler(); } }; class BufferObject : public GameEngine::Buffer { friend class HardwareRenderer; public: vk::Buffer buffer; vk::DeviceMemory memory; vk::BufferUsageFlags usage; vk::MemoryPropertyFlags location; int mapOffset = 0; int mapSize = -1; int size = 0; public: BufferObject(vk::BufferUsageFlags usage, int psize, vk::MemoryPropertyFlags location) { //TODO: Should pass as input a requiredLocation and an optimalLocation? this->location = location; this->usage = usage; this->size = psize; // If we can't map the buffer, we need to specify it will be a transfer dest if (!(this->location & vk::MemoryPropertyFlagBits::eHostVisible)) this->usage |= vk::BufferUsageFlagBits::eTransferDst; // Create a buffer with the requested size vk::BufferCreateInfo bufferCreateInfo = vk::BufferCreateInfo() .setFlags(vk::BufferCreateFlags()) .setSize(this->size) .setUsage(this->usage) .setSharingMode(vk::SharingMode::eExclusive) .setQueueFamilyIndexCount(0) .setPQueueFamilyIndices(nullptr); this->buffer = RendererState::Device().createBuffer(bufferCreateInfo); // Check to see how much memory we actually require vk::MemoryRequirements memoryRequirements = RendererState::Device().getBufferMemoryRequirements(this->buffer); int backingSize = (int)memoryRequirements.size; // If we allocate more memory than requested, recreate buffer to backing size if (this->size != backingSize) { this->size = backingSize; vk::BufferCreateInfo fullsizeBufferCreateInfo = vk::BufferCreateInfo() .setFlags(vk::BufferCreateFlags()) .setSize(this->size) .setUsage(this->usage) .setSharingMode(vk::SharingMode::eExclusive) .setQueueFamilyIndexCount(0) .setPQueueFamilyIndices(nullptr); RendererState::Device().destroyBuffer(this->buffer); this->buffer = RendererState::Device().createBuffer(fullsizeBufferCreateInfo); } // Allocate memory for the buffer vk::MemoryRequirements fullsizeMemoryRequirements = RendererState::Device().getBufferMemoryRequirements(this->buffer); vk::MemoryAllocateInfo fullsizeMemoryAllocateInfo = vk::MemoryAllocateInfo() .setAllocationSize(fullsizeMemoryRequirements.size) .setMemoryTypeIndex(GetMemoryType(fullsizeMemoryRequirements.memoryTypeBits, this->location)); this->memory = RendererState::Device().allocateMemory(fullsizeMemoryAllocateInfo); RendererState::Device().bindBufferMemory(this->buffer, this->memory, 0); } ~BufferObject() { if (this->buffer) RendererState::Device().destroyBuffer(this->buffer); if (this->memory) RendererState::Device().freeMemory(this->memory); } void SetDataAsync(int offset, void* data, int psize) { if (psize == 0) return; // If the buffer is mappable, map and memcpy if (location & vk::MemoryPropertyFlagBits::eHostVisible) { //TODO: Should memcpy + flush in chunks? void* mappedMemory = Map(offset, psize); memcpy(mappedMemory, data, psize); Flush(); Unmap(); } // Otherwise, we need to use command buffers else { // Create command buffer vk::CommandBuffer transferCommandBuffer = RendererState::GetTempTransferCommandBuffer(); assert(psize % 4 == 0); assert(offset % 4 == 0); // Record command buffer vk::CommandBufferBeginInfo transferBeginInfo = vk::CommandBufferBeginInfo() .setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit) .setPInheritanceInfo(nullptr); // Transfer the data in chunks of <= 65536 bytes transferCommandBuffer.begin(transferBeginInfo); int remainingSize = psize; int dataOffset = 0; while (remainingSize > 65536) { transferCommandBuffer.updateBuffer(this->buffer, offset + dataOffset, 65536, static_cast<char*>(data) + dataOffset); remainingSize -= 65536; dataOffset += 65536; } transferCommandBuffer.updateBuffer(this->buffer, offset + dataOffset, remainingSize, static_cast<char*>(data) + dataOffset); transferCommandBuffer.end(); // Submit to queue vk::SubmitInfo transferSubmitInfo = vk::SubmitInfo() .setWaitSemaphoreCount(0) .setPWaitSemaphores(nullptr) .setPWaitDstStageMask(nullptr) .setCommandBufferCount(1) .setPCommandBuffers(&transferCommandBuffer) .setSignalSemaphoreCount(0) .setPSignalSemaphores(nullptr); RendererState::TransferQueue().submit(transferSubmitInfo, vk::Fence()); } } void SetData(int offset, void* data, int psize) { CORELIB_ASSERT(data && "Initialize buffer with size preferred."); // If the buffer is mappable, map and memcpy if (location & vk::MemoryPropertyFlagBits::eHostVisible) { //TODO: Should memcpy + flush in chunks? void* mappedMemory = Map(offset, psize); memcpy(mappedMemory, data, psize); Flush(); Unmap(); } // Otherwise, we need to use command buffers else { // Create command buffer //TODO: Should this use a global buffer? How to handle thread safety? vk::CommandBuffer transferCommandBuffer = RendererState::GetTempTransferCommandBuffer(); //TODO: Improve switching logic bool staging = psize > (1 << 18); if (staging) { // Create staging buffer vk::BufferCreateInfo stagingCreateInfo = vk::BufferCreateInfo() .setFlags(vk::BufferCreateFlags()) .setSize(psize) .setUsage(vk::BufferUsageFlagBits::eTransferSrc) .setSharingMode(vk::SharingMode::eExclusive) .setQueueFamilyIndexCount(0) .setPQueueFamilyIndices(nullptr); vk::Buffer stagingBuffer = RendererState::Device().createBuffer(stagingCreateInfo); vk::MemoryRequirements stagingMemoryRequirements = RendererState::Device().getBufferMemoryRequirements(stagingBuffer); vk::MemoryAllocateInfo stagingMemoryAllocateInfo = vk::MemoryAllocateInfo() .setAllocationSize(stagingMemoryRequirements.size) .setMemoryTypeIndex(GetMemoryType(stagingMemoryRequirements.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible)); vk::DeviceMemory stagingMemory = RendererState::Device().allocateMemory(stagingMemoryAllocateInfo); RendererState::Device().bindBufferMemory(stagingBuffer, stagingMemory, 0); // Copy data to staging buffer void* stagingMappedMemory = RendererState::Device().mapMemory(stagingMemory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags()); memcpy(stagingMappedMemory, data, psize); RendererState::Device().unmapMemory(stagingMemory); // Create copy region description vk::BufferCopy transferRegion = vk::BufferCopy() .setSrcOffset(0) .setDstOffset(offset) .setSize(psize); // Record command buffer vk::CommandBufferBeginInfo transferBeginInfo = vk::CommandBufferBeginInfo() .setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit) .setPInheritanceInfo(nullptr); transferCommandBuffer.begin(transferBeginInfo); transferCommandBuffer.copyBuffer(stagingBuffer, this->buffer, transferRegion); transferCommandBuffer.end(); // Submit to queue vk::SubmitInfo transferSubmitInfo = vk::SubmitInfo() .setWaitSemaphoreCount(0) .setPWaitSemaphores(nullptr) .setPWaitDstStageMask(nullptr) .setCommandBufferCount(1) .setPCommandBuffers(&transferCommandBuffer) .setSignalSemaphoreCount(0) .setPSignalSemaphores(nullptr); RendererState::TransferQueue().submit(transferSubmitInfo, vk::Fence()); RendererState::TransferQueue().waitIdle(); //TODO: Remove // Destroy staging resources RendererState::Device().freeMemory(stagingMemory); RendererState::Device().destroyBuffer(stagingBuffer); } else { assert(psize % 4 == 0); assert(offset % 4 == 0); // Record command buffer vk::CommandBufferBeginInfo transferBeginInfo = vk::CommandBufferBeginInfo() .setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit) .setPInheritanceInfo(nullptr); // Transfer the data in chunks of <= 65536 bytes transferCommandBuffer.begin(transferBeginInfo); int remainingSize = psize; int dataOffset = 0; while (remainingSize > 65536) { transferCommandBuffer.updateBuffer(this->buffer, offset + dataOffset, 65536, static_cast<char*>(data) + dataOffset); remainingSize -= 65536; dataOffset += 65536; } transferCommandBuffer.updateBuffer(this->buffer, offset + dataOffset, remainingSize, static_cast<char*>(data) + dataOffset); transferCommandBuffer.end(); // Submit to queue vk::SubmitInfo transferSubmitInfo = vk::SubmitInfo() .setWaitSemaphoreCount(0) .setPWaitSemaphores(nullptr) .setPWaitDstStageMask(nullptr) .setCommandBufferCount(1) .setPCommandBuffers(&transferCommandBuffer) .setSignalSemaphoreCount(0) .setPSignalSemaphores(nullptr); RendererState::TransferQueue().submit(transferSubmitInfo, vk::Fence()); RendererState::TransferQueue().waitIdle(); //TODO: Remove } } } void SetData(void* data, int psize) { SetData(0, data, psize); } void GetData(void * pBuffer, int offset, int psize) { //TODO: Implement // If the buffer is mappable, map and memcpy if (location & vk::MemoryPropertyFlagBits::eHostVisible) { //TODO: Should memcpy + flush in chunks? void* mappedMemory = Map(offset, psize); memcpy(pBuffer, mappedMemory, psize); Unmap(); } else { vk::CommandBuffer transferCommandBuffer = RendererState::CreateCommandBuffer(RendererState::TransferCommandPool()); // Create staging buffer vk::BufferCreateInfo stagingCreateInfo = vk::BufferCreateInfo() .setFlags(vk::BufferCreateFlags()) .setSize(psize) .setUsage(vk::BufferUsageFlagBits::eTransferDst) .setSharingMode(vk::SharingMode::eExclusive) .setQueueFamilyIndexCount(0) .setPQueueFamilyIndices(nullptr); vk::Buffer stagingBuffer = RendererState::Device().createBuffer(stagingCreateInfo); vk::MemoryRequirements stagingMemoryRequirements = RendererState::Device().getBufferMemoryRequirements(stagingBuffer); vk::MemoryAllocateInfo stagingMemoryAllocateInfo = vk::MemoryAllocateInfo() .setAllocationSize(stagingMemoryRequirements.size) .setMemoryTypeIndex(GetMemoryType(stagingMemoryRequirements.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible)); vk::DeviceMemory stagingMemory = RendererState::Device().allocateMemory(stagingMemoryAllocateInfo); RendererState::Device().bindBufferMemory(stagingBuffer, stagingMemory, 0); // Create copy region description vk::BufferCopy transferRegion = vk::BufferCopy() .setSrcOffset(0) .setDstOffset(offset) .setSize(psize); // Record command buffer vk::CommandBufferBeginInfo transferBeginInfo = vk::CommandBufferBeginInfo() .setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit) .setPInheritanceInfo(nullptr); transferCommandBuffer.begin(transferBeginInfo); transferCommandBuffer.copyBuffer(this->buffer, stagingBuffer, transferRegion); transferCommandBuffer.end(); // Submit to queue vk::SubmitInfo transferSubmitInfo = vk::SubmitInfo() .setWaitSemaphoreCount(0) .setPWaitSemaphores(nullptr) .setPWaitDstStageMask(nullptr) .setCommandBufferCount(1) .setPCommandBuffers(&transferCommandBuffer) .setSignalSemaphoreCount(0) .setPSignalSemaphores(nullptr); RendererState::RenderQueue().submit(transferSubmitInfo, vk::Fence()); RendererState::RenderQueue().waitIdle(); //TODO: Remove // map memory and copy void* stagingMappedMemory = RendererState::Device().mapMemory(stagingMemory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags()); memcpy(pBuffer, stagingMappedMemory, psize); RendererState::Device().unmapMemory(stagingMemory); RendererState::DestroyCommandBuffer(RendererState::TransferCommandPool(), transferCommandBuffer); // Destroy staging resources RendererState::Device().freeMemory(stagingMemory); RendererState::Device().destroyBuffer(stagingBuffer); } } int GetSize() { return size; } void* Map(int offset, int psize) { //TEMP assert(buffer); assert(this->mapSize == -1); //ENDTEMP // Buffer must have host visible flag to be mappable if (!(location & vk::MemoryPropertyFlagBits::eHostVisible)) return nullptr; //TODO: We need to guarantee that all previous commands writing to this range have completed // Can probably do this by associating each buffer with a fence, and waiting on the fence //TODO: Lock mutex for memory this->mapOffset = offset; this->mapSize = psize; return RendererState::Device().mapMemory(memory, offset, psize, vk::MemoryMapFlags()); } void* Map() { return Map(0, this->size); } // If the buffer is not host coherent, we need to flush to guarantee writes visible to device void Flush(int offset, int psize) { assert(this->mapSize >= 0); // We only need to flush if not host coherent if (!(location & vk::MemoryPropertyFlagBits::eHostCoherent)) { //TEMP assert(offset >= this->mapOffset); assert(offset % (RendererState::PhysicalDevice().getProperties().limits.nonCoherentAtomSize) == 0); assert(psize % (RendererState::PhysicalDevice().getProperties().limits.nonCoherentAtomSize) == 0); assert(psize <= this->mapSize || (this->mapSize == -1 && psize <= (this->size - offset))); //TODO: Round down offset and round up size? //ENDTEMP //TODO: We need to make sure we do this before command buffers using the memory are submitted vk::MappedMemoryRange memoryRange = vk::MappedMemoryRange() .setMemory(this->memory) .setOffset(offset) .setSize(psize); RendererState::Device().flushMappedMemoryRanges(memoryRange); } } void Flush() { Flush(this->mapOffset, this->mapSize); } void Unmap() { assert(this->mapSize >= 0); RendererState::Device().unmapMemory(memory); this->mapSize = -1; this->mapOffset = 0; //TODO: unlock mutex } }; class Shader : public GameEngine::Shader { public: ShaderType stage; vk::ShaderModule module; Shader() {} ~Shader() { Destroy(); } void Create(ShaderType pstage, const char* data, int size) { Destroy(); this->stage = pstage; vk::ShaderModuleCreateInfo createInfo(vk::ShaderModuleCreateFlags(), (size_t)size, (const uint32_t*)data); this->module = RendererState::Device().createShaderModule(createInfo); } void Destroy() { if (module) RendererState::Device().destroyShaderModule(module); module = vk::ShaderModule(); } }; class RenderTargetLayout : public GameEngine::RenderTargetLayout { public: CoreLib::List<vk::AttachmentReference> colorReferences; vk::AttachmentReference depthReference; vk::RenderPass renderPass, renderPassClear; private: void Resize(CoreLib::List<vk::AttachmentDescription> &descriptions, int size) { if (descriptions.Count() < size) descriptions.SetSize(size); } void SetColorAttachment(CoreLib::List<vk::AttachmentDescription> & descriptions, int binding, StorageFormat format, bool ignoreInitialContent, LoadOp loadOp = LoadOp::Load, StoreOp storeOp = StoreOp::Store) { Resize(descriptions, binding + 1); if (ignoreInitialContent && loadOp == LoadOp::Load) loadOp = LoadOp::DontCare; descriptions[binding] = vk::AttachmentDescription() .setFlags(vk::AttachmentDescriptionFlags()) .setFormat(TranslateStorageFormat(format))// .setInitialLayout(ignoreInitialContent ? vk::ImageLayout::eUndefined : vk::ImageLayout::eColorAttachmentOptimal)// .setFinalLayout(vk::ImageLayout::eColorAttachmentOptimal)// .setSamples(SampleCount(1)) .setLoadOp(TranslateLoadOp(loadOp)) .setStoreOp(TranslateStoreOp(storeOp)) .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)// .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare);// //if (samples > 1) //{ // //TODO: need to resolve? //} } void SetDepthAttachment(CoreLib::List<vk::AttachmentDescription> &descriptions, int binding, StorageFormat format, bool ignoreInitialContent, LoadOp loadOp = LoadOp::Load, StoreOp storeOp = StoreOp::Store) { CORELIB_ASSERT(depthReference.layout == vk::ImageLayout::eUndefined && "Only 1 depth/stencil attachment allowed."); Resize(descriptions, binding + 1); if (ignoreInitialContent && loadOp == LoadOp::Load) loadOp = LoadOp::DontCare; descriptions[binding] = vk::AttachmentDescription() .setFlags(vk::AttachmentDescriptionFlags()) .setFormat(TranslateStorageFormat(format)) .setInitialLayout(ignoreInitialContent ? vk::ImageLayout::eUndefined : vk::ImageLayout::eDepthStencilAttachmentOptimal) .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal) .setSamples(SampleCount(1)) .setLoadOp(TranslateLoadOp(loadOp)) .setStoreOp(TranslateStoreOp(storeOp)) .setStencilLoadOp(TranslateLoadOp(loadOp)) .setStencilStoreOp(TranslateStoreOp(storeOp)); } public: RenderTargetLayout() {}; RenderTargetLayout(CoreLib::ArrayView<AttachmentLayout> bindings, bool ignoreInitialContent) { depthReference.attachment = VK_ATTACHMENT_UNUSED; List<vk::AttachmentDescription> descriptions, descriptionsClear; int location = 0; for (auto binding : bindings) { switch (binding.Usage) { case TextureUsage::ColorAttachment: case TextureUsage::SampledColorAttachment: SetColorAttachment(descriptions, location, binding.ImageFormat, ignoreInitialContent); SetColorAttachment(descriptionsClear, location, binding.ImageFormat, ignoreInitialContent, LoadOp::Clear); break; case TextureUsage::DepthAttachment: case TextureUsage::SampledDepthAttachment: SetDepthAttachment(descriptions, location, binding.ImageFormat, ignoreInitialContent); SetDepthAttachment( descriptionsClear, location, binding.ImageFormat, ignoreInitialContent, LoadOp::Clear); break; case TextureUsage::Unused: break; default: throw HardwareRendererException("Unsupported attachment usage"); } location++; } int binding = 0; for (auto description : descriptions) { if (description.finalLayout == vk::ImageLayout::eColorAttachmentOptimal) colorReferences.Add(vk::AttachmentReference(binding, vk::ImageLayout::eColorAttachmentOptimal)); else if (description.finalLayout == vk::ImageLayout::eDepthStencilAttachmentOptimal) depthReference = vk::AttachmentReference(binding, vk::ImageLayout::eDepthStencilAttachmentOptimal); binding++; } // Create Subpass Descriptions //TODO: Subpasses need to be implemented CoreLib::List<vk::SubpassDescription> subpassDescriptions; subpassDescriptions.Add( vk::SubpassDescription() .setFlags(vk::SubpassDescriptionFlags()) .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics) .setInputAttachmentCount(0) .setPInputAttachments(nullptr) .setColorAttachmentCount(colorReferences.Count()) .setPColorAttachments(colorReferences.Buffer()) .setPResolveAttachments(nullptr) .setPDepthStencilAttachment(&depthReference) .setPreserveAttachmentCount(0) .setPPreserveAttachments(nullptr) ); // Create RenderPass vk::RenderPassCreateInfo renderPassCreateInfo = vk::RenderPassCreateInfo() .setFlags(vk::RenderPassCreateFlags()) .setAttachmentCount(descriptions.Count()) .setPAttachments(descriptions.Buffer()) .setSubpassCount(subpassDescriptions.Count()) .setPSubpasses(subpassDescriptions.Buffer()) .setDependencyCount(0) .setPDependencies(nullptr); this->renderPass = RendererState::Device().createRenderPass(renderPassCreateInfo); renderPassCreateInfo.setPAttachments(descriptionsClear.Buffer()); this->renderPassClear = RendererState::Device().createRenderPass(renderPassCreateInfo); } ~RenderTargetLayout() { if (renderPass) RendererState::Device().destroyRenderPass(renderPass); if (renderPassClear) RendererState::Device().destroyRenderPass(renderPassClear); } virtual GameEngine::FrameBuffer* CreateFrameBuffer(const RenderAttachments& renderAttachments) override; }; class FrameBuffer : public GameEngine::FrameBuffer { public: int width; int height; vk::Framebuffer framebuffer, framebufferClear; CoreLib::RefPtr<RenderTargetLayout> renderTargetLayout; RenderAttachments renderAttachments; CoreLib::Array<vk::ClearValue, 10> clearValues; CoreLib::List<vk::ImageView> attachmentImageViews; FrameBuffer() {}; ~FrameBuffer() { if (framebuffer) RendererState::Device().destroyFramebuffer(framebuffer); if (framebufferClear) RendererState::Device().destroyFramebuffer(framebufferClear); for (auto view : attachmentImageViews) RendererState::Device().destroyImageView(view); } virtual RenderAttachments& GetRenderAttachments() override { return renderAttachments; } }; GameEngine::FrameBuffer* RenderTargetLayout::CreateFrameBuffer(const RenderAttachments& renderAttachments) { #if _DEBUG // Ensure the RenderAttachments are compatible with this RenderTargetLayout for (auto colorReference : colorReferences) { TextureUsage usage = TextureUsage::ColorAttachment; if (renderAttachments.attachments[colorReference.attachment].handle.tex2D) usage = dynamic_cast<Texture2D*>(renderAttachments.attachments[colorReference.attachment].handle.tex2D)->usage; else if (renderAttachments.attachments[colorReference.attachment].handle.tex2DArray) usage = dynamic_cast<Texture2DArray*>(renderAttachments.attachments[colorReference.attachment].handle.tex2DArray)->usage; if (!(usage & TextureUsage::ColorAttachment)) throw HardwareRendererException("Incompatible RenderTargetLayout and RenderAttachments"); } if (depthReference.layout != vk::ImageLayout::eUndefined) { TextureUsage usage = TextureUsage::ColorAttachment; if (renderAttachments.attachments[depthReference.attachment].handle.tex2D) usage = dynamic_cast<Texture2D*>(renderAttachments.attachments[depthReference.attachment].handle.tex2D)->usage; else if (renderAttachments.attachments[depthReference.attachment].handle.tex2DArray) usage = dynamic_cast<Texture2DArray*>(renderAttachments.attachments[depthReference.attachment].handle.tex2DArray)->usage; if (!(usage & TextureUsage::DepthAttachment)) throw HardwareRendererException("Incompatible RenderTargetLayout and RenderAttachments"); } #endif FrameBuffer* result = new FrameBuffer(); result->renderTargetLayout = this; result->renderAttachments = renderAttachments; result->attachmentImageViews.Clear(); for (auto attachment : renderAttachments.attachments) { vk::ImageAspectFlags aspectFlags; if (attachment.handle.tex2D) { auto tex = dynamic_cast<Texture2D*>(attachment.handle.tex2D); if (isDepthFormat(tex->format)) { aspectFlags = vk::ImageAspectFlagBits::eDepth; if (tex->format == StorageFormat::Depth24Stencil8) aspectFlags |= vk::ImageAspectFlagBits::eStencil; } else aspectFlags = vk::ImageAspectFlagBits::eColor; vk::ImageSubresourceRange imageSubresourceRange = vk::ImageSubresourceRange() .setAspectMask(aspectFlags) .setBaseMipLevel(0) .setLevelCount(1) .setBaseArrayLayer(0) .setLayerCount(1); vk::ImageViewCreateInfo imageViewCreateInfo = vk::ImageViewCreateInfo() .setFlags(vk::ImageViewCreateFlags()) .setImage(tex->image) .setViewType(vk::ImageViewType::e2D) .setFormat(TranslateStorageFormat(tex->format)) .setComponents(vk::ComponentMapping(vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eG, vk::ComponentSwizzle::eB, vk::ComponentSwizzle::eA))// .setSubresourceRange(imageSubresourceRange); result->attachmentImageViews.Add(RendererState::Device().createImageView(imageViewCreateInfo)); } else if (attachment.handle.tex2DArray) { auto tex = dynamic_cast<Texture2DArray*>(attachment.handle.tex2DArray); if (isDepthFormat(tex->format)) { aspectFlags = vk::ImageAspectFlagBits::eDepth; if (tex->format == StorageFormat::Depth24Stencil8) aspectFlags |= vk::ImageAspectFlagBits::eStencil; } else aspectFlags = vk::ImageAspectFlagBits::eColor; vk::ImageSubresourceRange imageSubresourceRange = vk::ImageSubresourceRange() .setAspectMask(aspectFlags) .setBaseMipLevel(0) .setLevelCount(1) .setBaseArrayLayer(attachment.layer) .setLayerCount(1); vk::ImageViewCreateInfo imageViewCreateInfo = vk::ImageViewCreateInfo() .setFlags(vk::ImageViewCreateFlags()) .setImage(tex->image) .setViewType(vk::ImageViewType::e2D) .setFormat(TranslateStorageFormat(tex->format)) .setComponents(vk::ComponentMapping(vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eG, vk::ComponentSwizzle::eB, vk::ComponentSwizzle::eA))// .setSubresourceRange(imageSubresourceRange); result->attachmentImageViews.Add(RendererState::Device().createImageView(imageViewCreateInfo)); } else if (attachment.handle.texCube) { auto tex = dynamic_cast<TextureCube*>(attachment.handle.texCube); if (isDepthFormat(tex->format)) { aspectFlags = vk::ImageAspectFlagBits::eDepth; if (tex->format == StorageFormat::Depth24Stencil8) aspectFlags |= vk::ImageAspectFlagBits::eStencil; } else aspectFlags = vk::ImageAspectFlagBits::eColor; vk::ImageSubresourceRange imageSubresourceRange = vk::ImageSubresourceRange() .setAspectMask(aspectFlags) .setBaseMipLevel(attachment.level) .setLevelCount(1) .setBaseArrayLayer((int)attachment.face) .setLayerCount(1); vk::ImageViewCreateInfo imageViewCreateInfo = vk::ImageViewCreateInfo() .setFlags(vk::ImageViewCreateFlags()) .setImage(tex->image) .setViewType(vk::ImageViewType::e2D) .setFormat(TranslateStorageFormat(tex->format)) .setComponents(vk::ComponentMapping(vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eG, vk::ComponentSwizzle::eB, vk::ComponentSwizzle::eA))// .setSubresourceRange(imageSubresourceRange); result->attachmentImageViews.Add(RendererState::Device().createImageView(imageViewCreateInfo)); } else if (attachment.handle.texCubeArray) { auto tex = dynamic_cast<TextureCubeArray*>(attachment.handle.texCubeArray); if (isDepthFormat(tex->format)) { aspectFlags = vk::ImageAspectFlagBits::eDepth; if (tex->format == StorageFormat::Depth24Stencil8) aspectFlags |= vk::ImageAspectFlagBits::eStencil; } else aspectFlags = vk::ImageAspectFlagBits::eColor; vk::ImageSubresourceRange imageSubresourceRange = vk::ImageSubresourceRange() .setAspectMask(aspectFlags) .setBaseMipLevel(attachment.level) .setLevelCount(1) .setBaseArrayLayer((int)attachment.face + attachment.layer * 6) .setLayerCount(1); vk::ImageViewCreateInfo imageViewCreateInfo = vk::ImageViewCreateInfo() .setFlags(vk::ImageViewCreateFlags()) .setImage(tex->image) .setViewType(vk::ImageViewType::e2D) .setFormat(TranslateStorageFormat(tex->format)) .setComponents(vk::ComponentMapping(vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eG, vk::ComponentSwizzle::eB, vk::ComponentSwizzle::eA))// .setSubresourceRange(imageSubresourceRange); result->attachmentImageViews.Add(RendererState::Device().createImageView(imageViewCreateInfo)); } if (aspectFlags == vk::ImageAspectFlagBits::eColor) { result->clearValues.Add(vk::ClearValue(vk::ClearColorValue())); } else { result->clearValues.Add(vk::ClearDepthStencilValue(1.0f, 0U)); } } vk::FramebufferCreateInfo framebufferCreateInfo = vk::FramebufferCreateInfo() .setFlags(vk::FramebufferCreateFlags()) .setRenderPass(renderPass) .setAttachmentCount(result->attachmentImageViews.Count()) .setPAttachments(result->attachmentImageViews.Buffer()) .setWidth(renderAttachments.width) .setHeight(renderAttachments.height) .setLayers(1); result->framebuffer = RendererState::Device().createFramebuffer(framebufferCreateInfo); framebufferCreateInfo.setRenderPass(renderPassClear); result->framebufferClear = RendererState::Device().createFramebuffer(framebufferCreateInfo); result->width = renderAttachments.width; result->height = renderAttachments.height; return result; } class DescriptorSetLayout : public GameEngine::DescriptorSetLayout { public: CoreLib::List<vk::DescriptorSetLayoutBinding> layoutBindings; vk::DescriptorSetLayout layout; #if _DEBUG CoreLib::ArrayView<GameEngine::DescriptorLayout> descriptors; #endif DescriptorSetLayout(CoreLib::ArrayView<GameEngine::DescriptorLayout> descriptors) { #if _DEBUG this->descriptors = descriptors; CoreLib::Array<int, 32> usedDescriptors; usedDescriptors.SetSize(32); for (auto& desc : usedDescriptors) desc = false; #endif for (auto& desc : descriptors) { #if _DEBUG if (usedDescriptors[desc.Location] != false) throw HardwareRendererException("Descriptor location already in use."); usedDescriptors[desc.Location] = true; #endif layoutBindings.Add( vk::DescriptorSetLayoutBinding() .setBinding(desc.Location) .setDescriptorType(TranslateBindingType(desc.Type)) .setDescriptorCount(desc.ArraySize) .setStageFlags(TranslateStageFlags(desc.Stages)) .setPImmutableSamplers(nullptr) ); } vk::DescriptorSetLayoutCreateInfo createInfo = vk::DescriptorSetLayoutCreateInfo() .setFlags(vk::DescriptorSetLayoutCreateFlags()) .setBindingCount(layoutBindings.Count()) .setPBindings(layoutBindings.Buffer()); layout = RendererState::Device().createDescriptorSetLayout(createInfo); } ~DescriptorSetLayout() { RendererState::Device().destroyDescriptorSetLayout(layout); } }; struct TextureUse { VK::Texture* texture; vk::ImageLayout targetLayout; }; class DescriptorSet : public GameEngine::DescriptorSet { public: //TODO: previous implementation in PipelineInstance would keep track of // previously bound descriptors and then create new imageInfo/bufferInfo // and swap them with the old one, as well as only updating the descriptors // that had changed. Should this do that too? vk::DescriptorSet descriptorSet; vk::DescriptorPool descriptorPool; CoreLib::RefPtr<DescriptorSetLayout> descriptorSetLayout; CoreLib::List<vk::DescriptorImageInfo> imageInfo; CoreLib::List<vk::DescriptorBufferInfo> bufferInfo; CoreLib::List<vk::WriteDescriptorSet> writeDescriptorSets; CoreLib::List<CoreLib::List<TextureUse>> textureUses; public: DescriptorSet() {} DescriptorSet(DescriptorSetLayout* layout) { // We need to keep a ref pointer to the layout because we need to have // the layout available when we call vkUpdateDescriptorSets (2.3.1) descriptorSetLayout = layout; std::pair<vk::DescriptorPool, vk::DescriptorSet> res = RendererState::AllocateDescriptorSet(layout->layout); descriptorPool = res.first; descriptorSet = res.second; } ~DescriptorSet() { if (descriptorSet) RendererState::Device().freeDescriptorSets(descriptorPool, descriptorSet); } virtual void BeginUpdate() override { imageInfo.Clear(); bufferInfo.Clear(); writeDescriptorSets.Clear(); } virtual void Update(int location, ArrayView<GameEngine::Texture*> textures, TextureAspect aspect) override { int imageInfoStart = imageInfo.Count(); if (textureUses.Count() <= location) textureUses.SetSize(location + 1); textureUses[location].Clear(); for (auto texture : textures) { if (texture) { VK::Texture* internalTexture = dynamic_cast<VK::Texture*>(texture); if (internalTexture->usage != TextureUsage::Sampled) { // Track layout of this texture textureUses[location].Add(TextureUse{ internalTexture, vk::ImageLayout::eShaderReadOnlyOptimal }); } vk::ImageView view = internalTexture->views[0]; if (isDepthFormat(internalTexture->format)/* && aspect == TextureAspect::Depth*/) view = internalTexture->views[1]; if (internalTexture->format == StorageFormat::Depth24Stencil8 && aspect == TextureAspect::Stencil) view = internalTexture->views[2]; imageInfo.Add( vk::DescriptorImageInfo() .setSampler(vk::Sampler()) .setImageView(view) .setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal) ); } else imageInfo.Add( vk::DescriptorImageInfo() .setSampler(vk::Sampler()) .setImageView(vk::ImageView()) .setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal) ); } writeDescriptorSets.Add( vk::WriteDescriptorSet() .setDstSet(this->descriptorSet) .setDstBinding(location) .setDstArrayElement(0) .setDescriptorCount(textures.Count()) .setDescriptorType(vk::DescriptorType::eSampledImage) .setPImageInfo(imageInfo.Buffer() + imageInfoStart) .setPBufferInfo(nullptr) .setPTexelBufferView(nullptr) ); } virtual void UpdateStorageImage(int location, ArrayView<GameEngine::Texture*> textures, TextureAspect aspect) override { int imageInfoStart = imageInfo.Count(); if (textureUses.Count() <= location) textureUses.SetSize(location + 1); textureUses[location].Clear(); for (auto texture : textures) { if (texture) { VK::Texture* internalTexture = dynamic_cast<VK::Texture*>(texture); // Track layout of this texture textureUses[location].Add(TextureUse{ internalTexture, vk::ImageLayout::eGeneral }); vk::ImageView view = internalTexture->views[0]; if (isDepthFormat(internalTexture->format) /*&& aspect == TextureAspect::Depth*/) view = internalTexture->views[1]; if (internalTexture->format == StorageFormat::Depth24Stencil8 && aspect == TextureAspect::Stencil) view = internalTexture->views[2]; imageInfo.Add( vk::DescriptorImageInfo() .setSampler(vk::Sampler()) .setImageView(view) .setImageLayout(vk::ImageLayout::eGeneral)// ); } else imageInfo.Add( vk::DescriptorImageInfo() .setSampler(vk::Sampler()) .setImageView(vk::ImageView()) .setImageLayout(vk::ImageLayout::eGeneral)// ); } writeDescriptorSets.Add( vk::WriteDescriptorSet() .setDstSet(this->descriptorSet) .setDstBinding(location) .setDstArrayElement(0) .setDescriptorCount(textures.Count()) .setDescriptorType(vk::DescriptorType::eStorageImage) .setPImageInfo(imageInfo.Buffer() + imageInfoStart) .setPBufferInfo(nullptr) .setPTexelBufferView(nullptr) ); } virtual void Update(int location, GameEngine::Texture* texture, TextureAspect aspect) override { Update(location, MakeArrayView(texture), aspect); } virtual void Update(int location, GameEngine::TextureSampler* sampler) override { VK::TextureSampler* internalSampler = reinterpret_cast<VK::TextureSampler*>(sampler); imageInfo.Add( vk::DescriptorImageInfo() .setSampler(internalSampler->sampler) .setImageView(vk::ImageView()) .setImageLayout(vk::ImageLayout::eUndefined) ); writeDescriptorSets.Add( vk::WriteDescriptorSet() .setDstSet(this->descriptorSet) .setDstBinding(location) .setDstArrayElement(0) .setDescriptorCount(1) .setDescriptorType(vk::DescriptorType::eSampler) .setPImageInfo(&imageInfo.Last()) .setPBufferInfo(nullptr) .setPTexelBufferView(nullptr) ); } virtual void Update(int location, GameEngine::Buffer* buffer, int offset = 0, int length = -1) override { VK::BufferObject* internalBuffer = reinterpret_cast<VK::BufferObject*>(buffer); vk::DescriptorType descriptorType; if (internalBuffer->usage & vk::BufferUsageFlagBits::eUniformBuffer) descriptorType = vk::DescriptorType::eUniformBuffer; else descriptorType = vk::DescriptorType::eStorageBuffer; int range = (length == -1) ? internalBuffer->size : length; bufferInfo.Add( vk::DescriptorBufferInfo() .setBuffer(internalBuffer->buffer) .setOffset(offset) .setRange(range) ); writeDescriptorSets.Add( vk::WriteDescriptorSet() .setDstSet(this->descriptorSet) .setDstBinding(location) .setDstArrayElement(0) .setDescriptorCount(1) .setDescriptorType(descriptorType) .setPImageInfo(nullptr) .setPBufferInfo(&bufferInfo.Last()) .setPTexelBufferView(nullptr) ); } virtual void EndUpdate() override { if (writeDescriptorSets.Count() > 0) RendererState::Device().updateDescriptorSets( vk::ArrayProxy<const vk::WriteDescriptorSet>(writeDescriptorSets.Count(), writeDescriptorSets.Buffer()), nullptr); } }; class PipelineBuilder; class Pipeline : public GameEngine::Pipeline { public: #if _DEBUG CoreLib::ArrayView<GameEngine::DescriptorSetLayout*> descriptorSets; bool isGraphics = true; #endif int descSetCount = 0; vk::PipelineLayout pipelineLayout; vk::Pipeline pipeline; vk::PipelineBindPoint pipelineBindPoint; public: Pipeline() = default; Pipeline(RenderTargetLayout* renderTargetLayout, PipelineBuilder* pipelineBuilder); ~Pipeline() { if (pipeline) RendererState::Device().destroyPipeline(pipeline); if (pipelineLayout) RendererState::Device().destroyPipelineLayout(pipelineLayout); } }; class PipelineBuilder : public GameEngine::PipelineBuilder { public: #if _DEBUG CoreLib::String debugName; CoreLib::ArrayView<GameEngine::DescriptorSetLayout*> descriptorSets; #endif CoreLib::List<vk::DescriptorSetLayout> setLayouts; CoreLib::List<vk::PushConstantRange> pushConstantRanges;//TODO: CoreLib::List<vk::PipelineShaderStageCreateInfo> shaderStages; CoreLib::List<vk::VertexInputBindingDescription> vertexBindingDescriptions; CoreLib::List<vk::VertexInputAttributeDescription> vertexAttributeDescriptions; public: virtual void SetShaders(CoreLib::ArrayView<GameEngine::Shader*> shaders) override { shaderStages.Clear(); #if _DEBUG bool vertPresent = false; bool tescControlPresent = false; bool tescEvalPresent = false; bool geometryPresent = false; bool fragPresent = false; #endif for (auto shader : shaders) { #if _DEBUG // Ensure that the device supports requested shader stages if (ShaderStage(dynamic_cast<VK::Shader*>(shader)->stage) == vk::ShaderStageFlagBits::eGeometry) assert(RendererState::PhysicalDevice().getFeatures().geometryShader); if (ShaderStage(dynamic_cast<VK::Shader*>(shader)->stage) == vk::ShaderStageFlagBits::eTessellationControl) assert(RendererState::PhysicalDevice().getFeatures().tessellationShader); if (ShaderStage(dynamic_cast<VK::Shader*>(shader)->stage) == vk::ShaderStageFlagBits::eTessellationEvaluation) assert(RendererState::PhysicalDevice().getFeatures().tessellationShader); // Ensure only one of any shader stage is present in the requested shader stage switch (ShaderStage(dynamic_cast<VK::Shader*>(shader)->stage)) { case vk::ShaderStageFlagBits::eVertex: assert(vertPresent == false); vertPresent = true; break; case vk::ShaderStageFlagBits::eTessellationControl: assert(tescControlPresent == false); tescControlPresent = true; break; case vk::ShaderStageFlagBits::eTessellationEvaluation: assert(tescEvalPresent == false); tescEvalPresent = true; break; case vk::ShaderStageFlagBits::eGeometry: assert(geometryPresent == false); geometryPresent = true; break; case vk::ShaderStageFlagBits::eFragment: assert(fragPresent == false); fragPresent = true; break; case vk::ShaderStageFlagBits::eCompute: throw HardwareRendererException("Can't use compute shader in graphics pipeline"); break; default: throw HardwareRendererException("Unknown shader stage"); } #endif shaderStages.Add( vk::PipelineShaderStageCreateInfo() .setFlags(vk::PipelineShaderStageCreateFlagBits()) .setStage(ShaderStage(reinterpret_cast<VK::Shader*>(shader)->stage)) .setModule(reinterpret_cast<VK::Shader*>(shader)->module) .setPName("main") .setPSpecializationInfo(nullptr) ); } } virtual void SetVertexLayout(VertexFormat vertexFormat) override { //TODO: Improve int location = 0; int maxOffset = -1; int stride = 0; vertexAttributeDescriptions.Clear(); vertexBindingDescriptions.Clear(); for (auto attribute : vertexFormat.Attributes) { vertexAttributeDescriptions.Add( vk::VertexInputAttributeDescription() .setLocation(attribute.Location) .setBinding(0) .setFormat(TranslateVertexAttribute(attribute)) .setOffset(attribute.StartOffset) ); location++; if (attribute.StartOffset > maxOffset) { maxOffset = attribute.StartOffset; stride = maxOffset + DataTypeSize(attribute.Type); } } if (vertexAttributeDescriptions.Count() > 0) { vertexBindingDescriptions.Add( vk::VertexInputBindingDescription() .setBinding(0) .setStride(stride) .setInputRate(vk::VertexInputRate::eVertex)//TODO: per instance data? ); } } virtual void SetBindingLayout(CoreLib::ArrayView<GameEngine::DescriptorSetLayout*> pDescriptorSets) override { #if _DEBUG this->descriptorSets = pDescriptorSets; #endif for (auto& set : pDescriptorSets) { if (set) //TODO: ? setLayouts.Add(reinterpret_cast<VK::DescriptorSetLayout*>(set)->layout); } } virtual void SetDebugName(CoreLib::String name) override { #if _DEBUG debugName = name; #endif } virtual Pipeline* ToPipeline(GameEngine::RenderTargetLayout* renderTargetLayout) override { return new Pipeline(reinterpret_cast<RenderTargetLayout*>(renderTargetLayout), this); } virtual Pipeline* CreateComputePipeline(CoreLib::ArrayView<GameEngine::DescriptorSetLayout*> pDescriptorSets, GameEngine::Shader* shader) override { Pipeline * result = new Pipeline(); #if _DEBUG result->descriptorSets = pDescriptorSets; #endif result->pipelineBindPoint = vk::PipelineBindPoint::eCompute; List<vk::DescriptorSetLayout> descSetLayouts; for (auto& set : pDescriptorSets) { if (set) descSetLayouts.Add(reinterpret_cast<VK::DescriptorSetLayout*>(set)->layout); } // Create Pipeline Layout vk::PipelineLayoutCreateInfo layoutCreateInfo = vk::PipelineLayoutCreateInfo() .setFlags(vk::PipelineLayoutCreateFlags()) .setSetLayoutCount(pDescriptorSets.Count()) .setPSetLayouts(descSetLayouts.Buffer()) .setPushConstantRangeCount(0) .setPPushConstantRanges(nullptr); #ifdef _DEBUG result->isGraphics = false; #endif result->descSetCount = descSetLayouts.Count(); result->pipelineLayout = RendererState::Device().createPipelineLayout(layoutCreateInfo); vk::ComputePipelineCreateInfo createInfo; createInfo.setLayout(result->pipelineLayout) .stage.setModule(reinterpret_cast<VK::Shader*>(shader)->module) .setStage(vk::ShaderStageFlagBits::eCompute) .setPName("main"); result->pipeline = RendererState::Device().createComputePipeline(RendererState::PipelineCache(), createInfo); return result; } }; vk::PolygonMode TranslatePolygonMode(PolygonMode mode) { switch (mode) { case PolygonMode::Fill: return vk::PolygonMode::eFill; case PolygonMode::Line: return vk::PolygonMode::eLine; case PolygonMode::Point: return vk::PolygonMode::ePoint; default: return vk::PolygonMode::eFill; } } Pipeline::Pipeline(RenderTargetLayout* renderTargetLayout, PipelineBuilder* pipelineBuilder) { #if _DEBUG this->descriptorSets = pipelineBuilder->descriptorSets; #endif // Create Pipeline Layout vk::PipelineLayoutCreateInfo layoutCreateInfo = vk::PipelineLayoutCreateInfo() .setFlags(vk::PipelineLayoutCreateFlags()) .setSetLayoutCount(pipelineBuilder->setLayouts.Count()) .setPSetLayouts(pipelineBuilder->setLayouts.Buffer()) .setPushConstantRangeCount(pipelineBuilder->pushConstantRanges.Count()) .setPPushConstantRanges(pipelineBuilder->pushConstantRanges.Buffer()); this->descSetCount = pipelineBuilder->setLayouts.Count(); this->pipelineLayout = RendererState::Device().createPipelineLayout(layoutCreateInfo); // Vertex Input Description vk::PipelineVertexInputStateCreateInfo vertexInputCreateInfo = vk::PipelineVertexInputStateCreateInfo() .setFlags(vk::PipelineVertexInputStateCreateFlags()) .setVertexBindingDescriptionCount(pipelineBuilder->vertexBindingDescriptions.Count()) .setPVertexBindingDescriptions(pipelineBuilder->vertexBindingDescriptions.Buffer()) .setVertexAttributeDescriptionCount(pipelineBuilder->vertexAttributeDescriptions.Count()) .setPVertexAttributeDescriptions(pipelineBuilder->vertexAttributeDescriptions.Buffer()); // Create Input Assembly Description vk::PipelineInputAssemblyStateCreateInfo inputAssemblyCreateInfo = vk::PipelineInputAssemblyStateCreateInfo() .setFlags(vk::PipelineInputAssemblyStateCreateFlags()) .setTopology(TranslatePrimitiveTopology(pipelineBuilder->FixedFunctionStates.PrimitiveTopology)) .setPrimitiveRestartEnable(pipelineBuilder->FixedFunctionStates.PrimitiveRestartEnabled); // Create Viewport Description vk::PipelineViewportStateCreateInfo viewportCreateInfo = vk::PipelineViewportStateCreateInfo() .setFlags(vk::PipelineViewportStateCreateFlags()) .setViewportCount(1) .setPViewports(nullptr) .setScissorCount(1) .setPScissors(nullptr); // Create Rasterization Description vk::PipelineRasterizationStateCreateInfo rasterizationCreateInfo = vk::PipelineRasterizationStateCreateInfo() .setFlags(vk::PipelineRasterizationStateCreateFlags()) .setDepthClampEnable(VK_FALSE) .setRasterizerDiscardEnable(VK_FALSE) .setPolygonMode(TranslatePolygonMode(pipelineBuilder->FixedFunctionStates.PolygonFillMode)) .setCullMode(TranslateCullMode(pipelineBuilder->FixedFunctionStates.cullMode)) .setFrontFace(vk::FrontFace::eClockwise) .setDepthBiasEnable(pipelineBuilder->FixedFunctionStates.EnablePolygonOffset) .setDepthBiasConstantFactor(pipelineBuilder->FixedFunctionStates.PolygonOffsetUnits) .setDepthBiasClamp(0.0f) .setDepthBiasSlopeFactor(pipelineBuilder->FixedFunctionStates.PolygonOffsetFactor) .setLineWidth(1.0f); VkPipelineRasterizationConservativeStateCreateInfoEXT conservativeRasterStateCI{}; if (pipelineBuilder->FixedFunctionStates.ConsevativeRasterization) { conservativeRasterStateCI.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_CONSERVATIVE_STATE_CREATE_INFO_EXT; conservativeRasterStateCI.conservativeRasterizationMode = VK_CONSERVATIVE_RASTERIZATION_MODE_OVERESTIMATE_EXT; rasterizationCreateInfo.pNext = &conservativeRasterStateCI; } // Create Multisampling Description //TODO: Implement multisampling vk::PipelineMultisampleStateCreateInfo multisampleCreateInfo = vk::PipelineMultisampleStateCreateInfo() .setFlags(vk::PipelineMultisampleStateCreateFlags()) .setRasterizationSamples(vk::SampleCountFlagBits::e1) .setSampleShadingEnable(VK_FALSE) .setMinSampleShading(1.0f) .setPSampleMask(nullptr) .setAlphaToCoverageEnable(VK_FALSE) .setAlphaToOneEnable(VK_FALSE); // Create Depth Stencil Description vk::PipelineDepthStencilStateCreateInfo depthStencilCreateInfo = vk::PipelineDepthStencilStateCreateInfo() .setFlags(vk::PipelineDepthStencilStateCreateFlags()) .setDepthTestEnable(pipelineBuilder->FixedFunctionStates.DepthCompareFunc != CompareFunc::Disabled) .setDepthWriteEnable(pipelineBuilder->FixedFunctionStates.DepthCompareFunc != CompareFunc::Disabled) .setDepthCompareOp(TranslateCompareFunc(pipelineBuilder->FixedFunctionStates.DepthCompareFunc)) .setDepthBoundsTestEnable(VK_FALSE) .setMinDepthBounds(0.0f) .setMaxDepthBounds(1.0f) .setStencilTestEnable(pipelineBuilder->FixedFunctionStates.StencilCompareFunc != CompareFunc::Disabled) .setFront(vk::StencilOpState() .setCompareOp(TranslateCompareFunc(pipelineBuilder->FixedFunctionStates.StencilCompareFunc)) .setPassOp(TranslateStencilOp(pipelineBuilder->FixedFunctionStates.StencilDepthPassOp)) .setFailOp(TranslateStencilOp(pipelineBuilder->FixedFunctionStates.StencilFailOp)) .setDepthFailOp(TranslateStencilOp(pipelineBuilder->FixedFunctionStates.StencilDepthFailOp)) .setCompareMask(pipelineBuilder->FixedFunctionStates.StencilMask) .setWriteMask(pipelineBuilder->FixedFunctionStates.StencilMask) .setReference(pipelineBuilder->FixedFunctionStates.StencilReference)) .setBack(vk::StencilOpState() .setCompareOp(TranslateCompareFunc(pipelineBuilder->FixedFunctionStates.StencilCompareFunc)) .setPassOp(TranslateStencilOp(pipelineBuilder->FixedFunctionStates.StencilDepthPassOp)) .setFailOp(TranslateStencilOp(pipelineBuilder->FixedFunctionStates.StencilFailOp)) .setDepthFailOp(TranslateStencilOp(pipelineBuilder->FixedFunctionStates.StencilDepthFailOp)) .setCompareMask(pipelineBuilder->FixedFunctionStates.StencilMask) .setWriteMask(pipelineBuilder->FixedFunctionStates.StencilMask) .setReference(pipelineBuilder->FixedFunctionStates.StencilReference)); // Create Blending Description CoreLib::List<vk::PipelineColorBlendAttachmentState> colorBlendAttachments; for (int i = 0; i<renderTargetLayout->colorReferences.Count(); i++) { colorBlendAttachments.Add( vk::PipelineColorBlendAttachmentState() .setBlendEnable(pipelineBuilder->FixedFunctionStates.blendMode != BlendMode::Replace) .setSrcColorBlendFactor(pipelineBuilder->FixedFunctionStates.blendMode == BlendMode::AlphaBlend ? vk::BlendFactor::eSrcAlpha : vk::BlendFactor::eOne) .setDstColorBlendFactor(pipelineBuilder->FixedFunctionStates.blendMode == BlendMode::AlphaBlend ? vk::BlendFactor::eOneMinusSrcAlpha : vk::BlendFactor::eZero) .setColorBlendOp(vk::BlendOp::eAdd) .setSrcAlphaBlendFactor(pipelineBuilder->FixedFunctionStates.blendMode == BlendMode::AlphaBlend ? vk::BlendFactor::eSrcAlpha : vk::BlendFactor::eOne) .setDstAlphaBlendFactor(pipelineBuilder->FixedFunctionStates.blendMode == BlendMode::AlphaBlend ? vk::BlendFactor::eSrcAlpha : vk::BlendFactor::eZero) .setAlphaBlendOp(vk::BlendOp::eAdd) .setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA) ); } vk::PipelineColorBlendStateCreateInfo colorBlendCreateInfo = vk::PipelineColorBlendStateCreateInfo() .setFlags(vk::PipelineColorBlendStateCreateFlags()) .setLogicOpEnable(VK_FALSE) .setLogicOp(vk::LogicOp::eCopy) .setAttachmentCount(colorBlendAttachments.Count()) .setPAttachments(colorBlendAttachments.Count() > 0 ? colorBlendAttachments.Buffer() : nullptr) .setBlendConstants({ 0.0f, 0.0f, 0.0f, 0.0f }); // Create Dynamic Description CoreLib::Array<vk::DynamicState,2> dynamicStates; dynamicStates.Add(vk::DynamicState::eViewport); dynamicStates.Add(vk::DynamicState::eScissor); vk::PipelineDynamicStateCreateInfo dynamicStateCreateInfo = vk::PipelineDynamicStateCreateInfo() .setFlags(vk::PipelineDynamicStateCreateFlags()) .setDynamicStateCount(dynamicStates.Count()) .setPDynamicStates(dynamicStates.Buffer()); // Create Pipeline Create Info vk::GraphicsPipelineCreateInfo pipelineCreateInfo = vk::GraphicsPipelineCreateInfo() .setFlags(vk::PipelineCreateFlags()) .setStageCount(pipelineBuilder->shaderStages.Count()) .setPStages(pipelineBuilder->shaderStages.Buffer()) .setPVertexInputState(&vertexInputCreateInfo) .setPInputAssemblyState(&inputAssemblyCreateInfo) .setPTessellationState(nullptr) .setPViewportState(&viewportCreateInfo) .setPRasterizationState(&rasterizationCreateInfo) .setPMultisampleState(&multisampleCreateInfo) .setPDepthStencilState(reinterpret_cast<VK::RenderTargetLayout*>(renderTargetLayout)->depthReference.layout == vk::ImageLayout::eUndefined ? nullptr : &depthStencilCreateInfo) .setPColorBlendState(reinterpret_cast<VK::RenderTargetLayout*>(renderTargetLayout)->colorReferences.Count() == 0 ? nullptr : &colorBlendCreateInfo) .setPDynamicState(&dynamicStateCreateInfo) .setLayout(pipelineLayout) .setRenderPass(reinterpret_cast<VK::RenderTargetLayout*>(renderTargetLayout)->renderPass) .setSubpass(0) .setBasePipelineHandle(vk::Pipeline()) .setBasePipelineIndex(-1); this->pipeline = RendererState::Device().createGraphicsPipelines(RendererState::PipelineCache(), pipelineCreateInfo)[0]; this->pipelineBindPoint = vk::PipelineBindPoint::eGraphics; //#if _DEBUG // vk::DebugMarkerObjectNameInfoEXT nameInfo = vk::DebugMarkerObjectNameInfoEXT() // .setObjectType(vk::DebugReportObjectTypeEXT::ePipeline) // .setObject(pipeline.operator VkPipeline) // .setPObjectName(pipelineBuilder->debugName.Buffer()); // // RendererState::Device().debugMarkerSetObjectNameEXT(&nameInfo); //#endif } class Fence : public GameEngine::Fence { public: vk::Fence assocFence; public: Fence() { vk::FenceCreateInfo createInfo; createInfo.setFlags(vk::FenceCreateFlagBits::eSignaled); assocFence = RendererState::Device().createFence(createInfo); } ~Fence() { RendererState::Device().destroyFence(assocFence); } virtual void Reset() override { RendererState::Device().resetFences(assocFence); } virtual void Wait() override { static int waitCounter = 0; while (RendererState::Device().waitForFences( assocFence, VK_TRUE, 1 ) != vk::Result::eSuccess) { waitCounter++; }; /*if (waitCounter > 10) Print("waited %d\n", waitCounter);*/ } }; class CommandBuffer : public GameEngine::CommandBuffer { public: const vk::CommandPool& pool; vk::CommandBuffer buffer; Pipeline* curPipeline = nullptr; CoreLib::Array<vk::DescriptorSet, 32> pendingDescSets; CoreLib::List<VK::DescriptorSet*> descSets; CommandBuffer(const vk::CommandPool& commandPool) : pool(commandPool) { pendingDescSets.SetSize(32); buffer = RendererState::CreateCommandBuffer(pool, vk::CommandBufferLevel::eSecondary); } CommandBuffer() : CommandBuffer(RendererState::RenderCommandPool()) {} ~CommandBuffer() { RendererState::DestroyCommandBuffer(pool, buffer); } Buffer* lastVertBuffer = nullptr; int lastVertBufferOffset = 0; Buffer * lastIndexBuffer = nullptr; int lastIndexBufferOffset = 0; void ResetInternalState() { curPipeline = nullptr; lastVertBuffer = nullptr; lastIndexBuffer = nullptr; lastVertBufferOffset = 0; lastIndexBufferOffset = 0; descSets.Clear(); } virtual void SetEventMarker(const char * /*name*/, uint32_t /*color*/) override { } virtual void BeginRecording(GameEngine::FrameBuffer *frameBuffer) override { vk::RenderPass renderPass; if (frameBuffer) { renderPass = reinterpret_cast<VK::FrameBuffer *>(frameBuffer)->renderTargetLayout->renderPass; } ResetInternalState(); for (int k = 0; k < pendingDescSets.Count(); k++) pendingDescSets[k] = vk::DescriptorSet(); vk::CommandBufferInheritanceInfo inheritanceInfo = vk::CommandBufferInheritanceInfo() .setRenderPass(renderPass) .setSubpass(0) .setOcclusionQueryEnable(VK_FALSE) .setQueryFlags(vk::QueryControlFlags()) .setPipelineStatistics(vk::QueryPipelineStatisticFlags()); vk::CommandBufferBeginInfo commandBufferBeginInfo = vk::CommandBufferBeginInfo() .setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse | vk::CommandBufferUsageFlagBits::eRenderPassContinue) .setPInheritanceInfo(&inheritanceInfo); buffer.begin(commandBufferBeginInfo); } virtual void EndRecording() override { buffer.end(); } virtual void BindVertexBuffer(Buffer* vertexBuffer, int byteOffset) override { if (byteOffset != lastVertBufferOffset || vertexBuffer != lastVertBuffer) { buffer.bindVertexBuffers(0, reinterpret_cast<VK::BufferObject*>(vertexBuffer)->buffer, { (vk::DeviceSize)byteOffset }); lastVertBuffer = vertexBuffer; lastVertBufferOffset = byteOffset; } } virtual void BindIndexBuffer(Buffer* indexBuffer, int byteOffset) override { if (byteOffset != lastIndexBufferOffset || indexBuffer != lastIndexBuffer) { buffer.bindIndexBuffer(reinterpret_cast<VK::BufferObject*>(indexBuffer)->buffer, (vk::DeviceSize)byteOffset, vk::IndexType::eUint32); lastIndexBuffer = indexBuffer; lastIndexBufferOffset = byteOffset; } } virtual void BindDescriptorSet(int binding, GameEngine::DescriptorSet* descSet) override { VK::DescriptorSet* internalDescriptorSet = reinterpret_cast<VK::DescriptorSet*>(descSet); descSets.Add(internalDescriptorSet); if (descSet == nullptr) pendingDescSets[binding] = RendererState::GetEmptyDescriptorSet(); else pendingDescSets[binding] = (internalDescriptorSet->descriptorSet); } virtual void BindPipeline(GameEngine::Pipeline* pipeline) override { auto newPipeline = reinterpret_cast<VK::Pipeline*>(pipeline); if (curPipeline != newPipeline) { curPipeline = newPipeline; buffer.bindPipeline(newPipeline->pipelineBindPoint, newPipeline->pipeline); } } virtual void SetViewport(Viewport viewport) override { vk::Viewport vkViewport; vkViewport.x = viewport.x; vkViewport.y = viewport.y; vkViewport.width = viewport.w; vkViewport.height = viewport.h; vkViewport.minDepth = viewport.minZ; vkViewport.maxDepth = viewport.maxZ; buffer.setViewport(0, 1, &vkViewport); vk::Rect2D scissorRect = vk::Rect2D( vk::Offset2D((int)viewport.x, (int)viewport.y), vk::Extent2D((int)viewport.w, (int)viewport.h)); buffer.setScissor(0, 1, &scissorRect); } virtual void DispatchCompute(int groupCountX, int groupCountY, int groupCountZ) override { buffer.bindDescriptorSets( curPipeline->pipelineBindPoint, curPipeline->pipelineLayout, 0, curPipeline->descSetCount, pendingDescSets.Buffer(), 0, nullptr); buffer.dispatch(groupCountX, groupCountY, groupCountZ); } virtual void Draw(int firstVertex, int vertexCount) override { buffer.bindDescriptorSets( curPipeline->pipelineBindPoint, curPipeline->pipelineLayout, 0, curPipeline->descSetCount, pendingDescSets.Buffer(), 0, nullptr); buffer.draw(vertexCount, 1, firstVertex, 0); } virtual void DrawInstanced(int numInstances, int firstVertex, int vertexCount) override { buffer.bindDescriptorSets( curPipeline->pipelineBindPoint, curPipeline->pipelineLayout, 0, curPipeline->descSetCount, pendingDescSets.Buffer(), 0, nullptr); buffer.draw(vertexCount, numInstances, firstVertex, 0); } virtual void DrawIndexed(int firstIndex, int indexCount) override { buffer.bindDescriptorSets( curPipeline->pipelineBindPoint, curPipeline->pipelineLayout, 0, curPipeline->descSetCount, pendingDescSets.Buffer(), 0, nullptr); buffer.drawIndexed(indexCount, 1, firstIndex, 0, 0); } virtual void DrawIndexedInstanced(int numInstances, int firstIndex, int indexCount) override { buffer.bindDescriptorSets( curPipeline->pipelineBindPoint, curPipeline->pipelineLayout, 0, curPipeline->descSetCount, pendingDescSets.Buffer(), 0, nullptr); buffer.drawIndexed(indexCount, numInstances, firstIndex, 0, 0); } }; class VkWindowSurface : public GameEngine::WindowSurface { public: WindowHandle handle = {}; int width = -1; int height = -1; vk::SurfaceKHR surface; vk::SwapchainKHR swapchain; CoreLib::List<vk::Image> images; //alternatively could call getSwapchainImages each time CoreLib::List<vk::CommandBuffer> presentCommandBuffers, clearCommandBuffers; CoreLib::List<vk::Fence> presentCommandBufferFences; vk::Semaphore imageAvailableSemaphore, renderFinishedSemaphore; VkWindowSurface(WindowHandle windowHandle, int w, int h) { handle = windowHandle; width = w; height = h; if (windowHandle) surface = RendererState::CreateSurface(windowHandle); CreateSwapchain(); CreateSemaphores(); Clear(); } ~VkWindowSurface() { UnbindWindow(); } void Present(GameEngine::Texture2D * srcImage) { if (images.Count() == 0) return; uint32_t nextImage = 0; try { nextImage = RendererState::Device().acquireNextImageKHR(swapchain, UINT64_MAX, imageAvailableSemaphore, vk::Fence()).value; } catch (vk::OutOfDateKHRError) { CreateSwapchain(); return; } static int frameId = 0; frameId++; vk::CommandBufferBeginInfo commandBufferBeginInfo = vk::CommandBufferBeginInfo() .setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit) .setPInheritanceInfo(nullptr); vk::ImageSubresourceRange imageSubresourceRange = vk::ImageSubresourceRange() .setAspectMask(vk::ImageAspectFlagBits::eColor) .setBaseMipLevel(0) .setLevelCount(1) .setBaseArrayLayer(0) .setLayerCount(1); vk::ImageMemoryBarrier postPresentBarrier = vk::ImageMemoryBarrier() .setSrcAccessMask(LayoutFlags(vk::ImageLayout::eUndefined)) .setDstAccessMask(LayoutFlags(vk::ImageLayout::eTransferDstOptimal)) .setOldLayout(vk::ImageLayout::eUndefined) .setNewLayout(vk::ImageLayout::eTransferDstOptimal) .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setImage(images[nextImage]) .setSubresourceRange(imageSubresourceRange); vk::ImageMemoryBarrier prePresentBarrier = vk::ImageMemoryBarrier() .setSrcAccessMask(LayoutFlags(vk::ImageLayout::eTransferDstOptimal)) .setDstAccessMask(LayoutFlags(vk::ImageLayout::ePresentSrcKHR)) .setOldLayout(vk::ImageLayout::eTransferDstOptimal) .setNewLayout(vk::ImageLayout::ePresentSrcKHR) .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setImage(images[nextImage]) .setSubresourceRange(imageSubresourceRange); int cmdBufId = frameId % presentCommandBuffers.Count(); auto cmdBuffer = presentCommandBuffers[cmdBufId]; RendererState::Device().waitForFences(1, &presentCommandBufferFences[cmdBufId], true, 0); RendererState::Device().resetFences(1, &presentCommandBufferFences[cmdBufId]); cmdBuffer.begin(commandBufferBeginInfo); // start recording cmdBuffer.pipelineBarrier( vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eAllCommands, vk::DependencyFlags(), nullptr, nullptr, postPresentBarrier ); if (srcImage == nullptr) { // If no source image, clear to debug purple cmdBuffer.clearColorImage( images[nextImage], vk::ImageLayout::eTransferDstOptimal, vk::ClearColorValue(std::array<float, 4>{ 1.0f, 0.0f, 1.0f, 0.0f }), imageSubresourceRange ); } else { auto srcTexture = dynamic_cast<Texture2D*>(srcImage); vk::ImageMemoryBarrier textureTransferBarrier = vk::ImageMemoryBarrier() .setSrcAccessMask(LayoutFlags(srcTexture->currentSubresourceLayouts[0])) .setDstAccessMask(LayoutFlags(vk::ImageLayout::eTransferSrcOptimal)) .setOldLayout(srcTexture->currentSubresourceLayouts[0]) .setNewLayout(vk::ImageLayout::eTransferSrcOptimal) .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setImage(srcTexture->image) .setSubresourceRange(imageSubresourceRange); cmdBuffer.pipelineBarrier( vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eAllCommands, vk::DependencyFlags(), nullptr, nullptr, textureTransferBarrier ); srcTexture->currentSubresourceLayouts[0] = vk::ImageLayout::eTransferSrcOptimal; // Blit vk::ImageSubresourceLayers subresourceLayers = vk::ImageSubresourceLayers() .setAspectMask(vk::ImageAspectFlagBits::eColor) .setMipLevel(0) .setBaseArrayLayer(0) .setLayerCount(1); std::array<vk::Offset3D, 2> srcOffsets; srcOffsets[0] = vk::Offset3D(0, 0, 0); srcOffsets[1] = vk::Offset3D(dynamic_cast<VK::Texture2D*>(srcImage)->width, dynamic_cast<VK::Texture2D*>(srcImage)->height, 1); std::array<vk::Offset3D, 2> dstOffsets; dstOffsets[0] = vk::Offset3D(0, 0, 0); dstOffsets[1] = vk::Offset3D(width, height, 1); vk::ImageBlit blitRegions = vk::ImageBlit() .setSrcSubresource(subresourceLayers) .setSrcOffsets(srcOffsets) .setDstSubresource(subresourceLayers) .setDstOffsets(dstOffsets); cmdBuffer.blitImage( dynamic_cast<VK::Texture2D*>(srcImage)->image, vk::ImageLayout::eTransferSrcOptimal, images[nextImage], vk::ImageLayout::eTransferDstOptimal, blitRegions, vk::Filter::eNearest ); } cmdBuffer.pipelineBarrier( vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eAllCommands, vk::DependencyFlags(), nullptr, nullptr, prePresentBarrier ); cmdBuffer.end(); // stop recording vk::PipelineStageFlags waitDstStageMask = vk::PipelineStageFlags(vk::PipelineStageFlagBits::eTransfer); vk::SubmitInfo submitInfo = vk::SubmitInfo() .setWaitSemaphoreCount(1) .setPWaitSemaphores(&imageAvailableSemaphore) .setPWaitDstStageMask(&waitDstStageMask) .setCommandBufferCount(1) .setPCommandBuffers(&cmdBuffer) .setSignalSemaphoreCount(1) .setPSignalSemaphores(&renderFinishedSemaphore); RendererState::RenderQueue().submit(submitInfo, presentCommandBufferFences[cmdBufId]); vk::PresentInfoKHR presentInfo = vk::PresentInfoKHR() .setWaitSemaphoreCount(1) .setPWaitSemaphores(&renderFinishedSemaphore) .setSwapchainCount(1) .setPSwapchains(&swapchain) .setPImageIndices(&nextImage) .setPResults(nullptr); try { RendererState::RenderQueue().presentKHR(presentInfo); } catch (vk::OutOfDateKHRError) { CreateSwapchain(); } } void CreateSwapchain() { if (!surface) return; vkDeviceWaitIdle(RendererState::Device()); std::vector<vk::SurfaceFormatKHR> surfaceFormats = RendererState::PhysicalDevice().getSurfaceFormatsKHR(surface); vk::Format format; vk::ColorSpaceKHR colorSpace = surfaceFormats.at(0).colorSpace; if ((surfaceFormats.size() == 1) && (surfaceFormats.at(0).format == vk::Format::eUndefined)) format = vk::Format::eB8G8R8A8Unorm; else format = surfaceFormats.at(0).format; // Select presentation mode vk::PresentModeKHR presentMode = vk::PresentModeKHR::eFifo; // Fifo presentation mode is guaranteed for (auto & mode : RendererState::PhysicalDevice().getSurfacePresentModesKHR(surface)) { // If we can use mailbox, use it. if (mode == vk::PresentModeKHR::eMailbox) { presentMode = mode; break; } } vk::SurfaceCapabilitiesKHR surfaceCapabilities = RendererState::PhysicalDevice().getSurfaceCapabilitiesKHR(surface); unsigned int desiredSwapchainImages = 2; if (desiredSwapchainImages < surfaceCapabilities.minImageCount) { desiredSwapchainImages = surfaceCapabilities.minImageCount; } if (surfaceCapabilities.maxImageCount > 0 && desiredSwapchainImages > surfaceCapabilities.maxImageCount) { desiredSwapchainImages = surfaceCapabilities.maxImageCount; } vk::Extent2D swapchainExtent = {}; if (surfaceCapabilities.currentExtent.width == -1) { swapchainExtent.width = this->width; swapchainExtent.height = this->height; } else { swapchainExtent = surfaceCapabilities.currentExtent; this->width = swapchainExtent.width; this->height = swapchainExtent.height; } // Select swapchain pre-transform // (Can be useful on tablets, etc.) vk::SurfaceTransformFlagBitsKHR preTransform = surfaceCapabilities.currentTransform; if (surfaceCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) { // Select identity transform if we can preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity; } vk::SwapchainKHR oldSwapchain = swapchain; vk::SwapchainCreateInfoKHR swapchainCreateInfo = vk::SwapchainCreateInfoKHR() .setMinImageCount(desiredSwapchainImages) .setSurface(surface) .setImageFormat(format) .setImageColorSpace(colorSpace) .setImageExtent(swapchainExtent) .setImageArrayLayers(1) .setImageUsage(vk::ImageUsageFlagBits::eTransferDst) // we only draw to screen by blit .setImageSharingMode(vk::SharingMode::eExclusive) .setQueueFamilyIndexCount(0) .setPQueueFamilyIndices(VK_NULL_HANDLE) .setPreTransform(preTransform) .setCompositeAlpha(vk::CompositeAlphaFlagBitsKHR::eOpaque) .setPresentMode(presentMode) .setClipped(VK_TRUE) .setOldSwapchain(oldSwapchain); swapchain = RendererState::Device().createSwapchainKHR(swapchainCreateInfo); DestroySwapchain(oldSwapchain); auto vkImages = RendererState::Device().getSwapchainImagesKHR(swapchain); images.SetSize((int)vkImages.size()); memcpy(images.Buffer(), &vkImages[0], vkImages.size() * sizeof(vk::Image)); CreateCommandBuffers(); } void CreateCommandBuffers() { DestroyCommandBuffers(); vk::CommandBufferAllocateInfo commandBufferAllocateInfo = vk::CommandBufferAllocateInfo() .setCommandPool(RendererState::SwapchainCommandPool()) .setLevel(vk::CommandBufferLevel::ePrimary) .setCommandBufferCount((uint32_t)images.Count() * 2); presentCommandBuffers.SetSize(commandBufferAllocateInfo.commandBufferCount); RendererState::Device().allocateCommandBuffers(&commandBufferAllocateInfo, presentCommandBuffers.Buffer()); clearCommandBuffers.SetSize(commandBufferAllocateInfo.commandBufferCount); RendererState::Device().allocateCommandBuffers(&commandBufferAllocateInfo, clearCommandBuffers.Buffer()); presentCommandBufferFences.SetSize(presentCommandBuffers.Count()); vk::FenceCreateInfo fenceCreateInfo; fenceCreateInfo.setFlags(vk::FenceCreateFlagBits::eSignaled); for (int i = 0; i < presentCommandBuffers.Count(); i++) presentCommandBufferFences[i] = RendererState::Device().createFence(fenceCreateInfo); // record clear command buffers for (int image = 0; image < images.Count(); image++) { //TODO: see if following line is beneficial //commandBuffers[image].reset(vk::CommandBufferResetFlags()); // implicitly done by begin vk::CommandBufferBeginInfo commandBufferBeginInfo = vk::CommandBufferBeginInfo() .setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit) .setPInheritanceInfo(nullptr); vk::ImageSubresourceRange imageSubresourceRange = vk::ImageSubresourceRange() .setAspectMask(vk::ImageAspectFlagBits::eColor) .setBaseMipLevel(0) .setLevelCount(1) .setBaseArrayLayer(0) .setLayerCount(1); vk::ImageMemoryBarrier postPresentBarrier = vk::ImageMemoryBarrier() .setSrcAccessMask(vk::AccessFlags()) .setDstAccessMask(LayoutFlags(vk::ImageLayout::eTransferDstOptimal)) .setOldLayout(vk::ImageLayout::eUndefined) .setNewLayout(vk::ImageLayout::eTransferDstOptimal) .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setImage(images[image]) .setSubresourceRange(imageSubresourceRange); vk::ImageMemoryBarrier prePresentBarrier = vk::ImageMemoryBarrier() .setSrcAccessMask(LayoutFlags(vk::ImageLayout::eTransferDstOptimal)) .setDstAccessMask(LayoutFlags(vk::ImageLayout::ePresentSrcKHR)) .setOldLayout(vk::ImageLayout::eTransferDstOptimal) .setNewLayout(vk::ImageLayout::ePresentSrcKHR) .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setImage(images[image]) .setSubresourceRange(imageSubresourceRange); clearCommandBuffers[image].begin(commandBufferBeginInfo); // start recording clearCommandBuffers[image].pipelineBarrier( vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer, vk::DependencyFlags(), nullptr, nullptr, postPresentBarrier ); clearCommandBuffers[image].clearColorImage( images[image], vk::ImageLayout::eTransferDstOptimal, vk::ClearColorValue(std::array<float, 4>{ 0.467f, 0.725f, 0.0f, 0.0f }), imageSubresourceRange ); clearCommandBuffers[image].pipelineBarrier( vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eBottomOfPipe, vk::DependencyFlags(), nullptr, nullptr, prePresentBarrier ); clearCommandBuffers[image].end(); // stop recording } // record present command buffers } void CreateSemaphores() { DestroySemaphores(); vk::SemaphoreCreateInfo semaphoreCreateInfo; imageAvailableSemaphore = RendererState::Device().createSemaphore(semaphoreCreateInfo); renderFinishedSemaphore = RendererState::Device().createSemaphore(semaphoreCreateInfo); } void DestroySemaphores() { if (imageAvailableSemaphore) RendererState::Device().destroySemaphore(imageAvailableSemaphore); if (renderFinishedSemaphore) RendererState::Device().destroySemaphore(renderFinishedSemaphore); } void DestroyCommandBuffers() { if (presentCommandBufferFences.Count()) RendererState::Device().waitForFences(presentCommandBufferFences.Count(), presentCommandBufferFences.Buffer(), true, 0); for (auto fence : presentCommandBufferFences) RendererState::Device().destroyFence(fence); for (auto commandBuffer : presentCommandBuffers) RendererState::Device().freeCommandBuffers(RendererState::SwapchainCommandPool(), commandBuffer); for (auto commandBuffer : clearCommandBuffers) RendererState::Device().freeCommandBuffers(RendererState::SwapchainCommandPool(), commandBuffer); presentCommandBufferFences.Clear(); } void DestroySwapchain() { RendererState::Device().waitIdle(); if (swapchain) DestroySwapchain(swapchain); } void DestroySwapchain(vk::SwapchainKHR pswapchain) { if (pswapchain) RendererState::Device().destroySwapchainKHR(pswapchain);// shouldn't need this if, but nvidia driver is broken. } void UnbindWindow() { DestroySemaphores(); DestroyCommandBuffers(); DestroySwapchain(); if (surface) RendererState::Instance().destroySurfaceKHR(surface); handle = WindowHandle(); } void Clear() { } virtual void Resize(int pwidth, int pheight) override { if (!handle) return; if (width != pwidth || height != pheight) { this->width = pwidth; this->height = pheight; CreateSwapchain(); } } virtual void GetSize(int & w, int & h) override { w = this->width; h = this->height; } virtual WindowHandle GetWindowHandle() override { return this->handle; } }; class HardwareRenderer : public GameEngine::HardwareRenderer { private: List<vk::Semaphore> transferSemaphores; CoreLib::Array<vk::CommandBuffer, MaxRenderThreads> jobSubmissionBuffers; List<vk::ImageMemoryBarrier> imageMemoryBarriers; uint32_t taskId = 0; std::mutex queueMutex; public: virtual TargetShadingLanguage GetShadingLanguage() override { return TargetShadingLanguage::SPIRV; } public: HardwareRenderer(String pipelineCacheLocation) { RendererState::SetPipelineCacheLocation(pipelineCacheLocation); RendererState::AddRenderer(); jobSubmissionBuffers.SetSize(MaxRenderThreads); }; ~HardwareRenderer() { RendererState::Device().waitIdle(); for (auto & sem : transferSemaphores) RendererState::Device().destroySemaphore(sem); RendererState::RemRenderer(); } virtual void ThreadInit(int threadId) override { renderThreadId = threadId; } virtual void Init(int versionCount) override { RendererState::Init(versionCount); } virtual void ResetTempBufferVersion(int version) override { RendererState::ResetTempBufferVersion(version); } virtual WindowSurface* CreateSurface(WindowHandle windowHandle, int pwidth, int pheight) override { VkWindowSurface * rs = new VkWindowSurface(windowHandle, pwidth, pheight); return rs; } virtual void BeginJobSubmission() override { // Create command buffer begin info vk::CommandBufferBeginInfo primaryBeginInfo = vk::CommandBufferBeginInfo() .setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit) .setPInheritanceInfo(nullptr); jobSubmissionBuffers[renderThreadId] = RendererState::GetTempRenderCommandBuffer(); jobSubmissionBuffers[renderThreadId].begin(primaryBeginInfo); } virtual void EndJobSubmission(GameEngine::Fence* fence) override { auto primaryBuffer = jobSubmissionBuffers[renderThreadId]; primaryBuffer.end(); vk::SubmitInfo submitInfo = vk::SubmitInfo() .setWaitSemaphoreCount(0) .setPWaitSemaphores(nullptr) .setPWaitDstStageMask(nullptr) .setCommandBufferCount(1) .setPCommandBuffers(&primaryBuffer) .setSignalSemaphoreCount(0) .setPSignalSemaphores(nullptr); RendererState::RenderQueue().submit(submitInfo, fence ? ((VK::Fence*)fence)->assocFence : nullptr); } void QueuePipelineBarrier(vk::CommandBuffer cmdBuffer, PipelineBarriers barriers) { if (barriers == PipelineBarriers::Memory || barriers == PipelineBarriers::MemoryAndImage) { auto memBarrier = vk::MemoryBarrier() .setSrcAccessMask(vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eHostWrite) .setDstAccessMask(vk::AccessFlagBits::eShaderRead); cmdBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eAllCommands, vk::DependencyFlags(), 1, &memBarrier, 0, nullptr, imageMemoryBarriers.Count(), imageMemoryBarriers.Buffer()); } else if (barriers == PipelineBarriers::ExecutionOnly) { cmdBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eAllCommands, vk::DependencyFlags(), 0, nullptr, 0, nullptr, 0, nullptr); } } virtual void QueueComputeTask(GameEngine::Pipeline* computePipeline, GameEngine::DescriptorSet* descriptorSet, int x, int y, int z, PipelineBarriers barriers) override { std::lock_guard<std::mutex> lock(queueMutex); taskId++; imageMemoryBarriers.Clear(); if (barriers == PipelineBarriers::MemoryAndImage) { auto vkDescSet = (VK::DescriptorSet*)descriptorSet; for (auto& textureUseList : vkDescSet->textureUses) { for (auto textureUse : textureUseList) { if (textureUse.texture->lastLayoutCheckTaskId == taskId) continue; textureUse.texture->lastLayoutCheckTaskId = taskId; textureUse.texture->TransferLayout(textureUse.targetLayout, imageMemoryBarriers); } } } auto primaryBuffer = jobSubmissionBuffers[renderThreadId]; QueuePipelineBarrier(primaryBuffer, barriers); auto pipeline = dynamic_cast<VK::Pipeline*>(computePipeline); auto descSet = dynamic_cast<VK::DescriptorSet*>(descriptorSet); primaryBuffer.bindPipeline(pipeline->pipelineBindPoint, pipeline->pipeline); primaryBuffer.bindDescriptorSets(pipeline->pipelineBindPoint, pipeline->pipelineLayout, 0, 1, &descSet->descriptorSet, 0, nullptr); primaryBuffer.dispatch(x, y, z); } virtual void QueueRenderPass(GameEngine::FrameBuffer *frameBuffer, bool clearFrameBuffer, CoreLib::ArrayView<GameEngine::CommandBuffer *> commands, PipelineBarriers barriers) override { std::lock_guard<std::mutex> lock(queueMutex); taskId++; imageMemoryBarriers.Clear(); auto vkframeBuffer = (VK::FrameBuffer*)frameBuffer; if (barriers == PipelineBarriers::MemoryAndImage) { // Determine texture layout transfer ops that are necessary Array<GameEngine::Texture*, 8> attachmentTextures; vkframeBuffer->renderAttachments.GetTextures(attachmentTextures); for (auto texture : attachmentTextures) { auto vkTexture = dynamic_cast<VK::Texture*>(texture); if (vkTexture->lastLayoutCheckTaskId == taskId) continue; vkTexture->lastLayoutCheckTaskId = taskId; if (texture->IsDepthStencilFormat()) vkTexture->TransferLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal, imageMemoryBarriers); else vkTexture->TransferLayout(vk::ImageLayout::eColorAttachmentOptimal, imageMemoryBarriers); } for (auto cmdBuf : commands) { auto vkCmdBuf = (VK::CommandBuffer*)cmdBuf; for (auto descSet : vkCmdBuf->descSets) { for (auto& textureUseList : descSet->textureUses) for (auto textureUse : textureUseList) { if (textureUse.texture->lastLayoutCheckTaskId == taskId) continue; textureUse.texture->lastLayoutCheckTaskId = taskId; textureUse.texture->TransferLayout(textureUse.targetLayout, imageMemoryBarriers); } } } } // Create render pass begin info vk::RenderPassBeginInfo renderPassBeginInfo = vk::RenderPassBeginInfo() .setRenderPass(clearFrameBuffer ? vkframeBuffer->renderTargetLayout->renderPassClear : vkframeBuffer->renderTargetLayout->renderPass) .setFramebuffer(clearFrameBuffer ? vkframeBuffer->framebufferClear : vkframeBuffer->framebuffer) .setRenderArea(vk::Rect2D() .setOffset(vk::Offset2D(0, 0)) .setExtent(vk::Extent2D(reinterpret_cast<VK::FrameBuffer *>(frameBuffer)->width, reinterpret_cast<VK::FrameBuffer *>(frameBuffer)->height))) .setClearValueCount(vkframeBuffer->clearValues.Count()) .setPClearValues(vkframeBuffer->clearValues.Buffer()); // Aggregate secondary command buffers CoreLib::List<vk::CommandBuffer> renderPassCommandBuffers; for (auto& buffer : commands) { auto internalBuffer = static_cast<VK::CommandBuffer*>(buffer); renderPassCommandBuffers.Add(internalBuffer->buffer); } // Record primary command buffer auto primaryBuffer = jobSubmissionBuffers[renderThreadId]; QueuePipelineBarrier(primaryBuffer, barriers); if (renderPassCommandBuffers.Count() > 0) { primaryBuffer.beginRenderPass(renderPassBeginInfo, vk::SubpassContents::eSecondaryCommandBuffers); primaryBuffer.executeCommands(renderPassCommandBuffers.Count(), renderPassCommandBuffers.Buffer()); primaryBuffer.endRenderPass(); } } virtual void Wait() override { RendererState::Device().waitIdle(); } virtual void Blit(GameEngine::Texture2D *dstImage, GameEngine::Texture2D *srcImage, VectorMath::Vec2i dstOffset, SourceFlipMode flipSrc) override { auto primaryBuffer = jobSubmissionBuffers[renderThreadId]; vk::ImageSubresourceRange imageSubresourceRange = vk::ImageSubresourceRange() .setAspectMask(vk::ImageAspectFlagBits::eColor) .setBaseMipLevel(0) .setLevelCount(1) .setBaseArrayLayer(0) .setLayerCount(1); auto dstTexture = dynamic_cast<VK::Texture*>(dstImage); vk::ImageMemoryBarrier preBlitBarrier = vk::ImageMemoryBarrier() .setSrcAccessMask(LayoutFlags(vk::ImageLayout::eUndefined)) .setDstAccessMask(LayoutFlags(vk::ImageLayout::eTransferDstOptimal)) .setOldLayout(dstTexture->currentSubresourceLayouts[0]) .setNewLayout(vk::ImageLayout::eTransferDstOptimal) .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setImage(dstTexture->image) .setSubresourceRange(imageSubresourceRange); dstTexture->currentSubresourceLayouts[0] = vk::ImageLayout::eTransferDstOptimal; auto srcTexture = dynamic_cast<Texture2D*>(srcImage); vk::ImageMemoryBarrier textureTransferBarrier = vk::ImageMemoryBarrier() .setSrcAccessMask(LayoutFlags(vk::ImageLayout::eColorAttachmentOptimal)) .setDstAccessMask(LayoutFlags(vk::ImageLayout::eTransferSrcOptimal)) .setOldLayout(srcTexture->currentSubresourceLayouts[0]) .setNewLayout(vk::ImageLayout::eTransferSrcOptimal) .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setImage(srcTexture->image) .setSubresourceRange(imageSubresourceRange); primaryBuffer.pipelineBarrier( vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eTransfer, vk::DependencyFlags(), 0, nullptr, 0, nullptr, 2, MakeArray(preBlitBarrier, textureTransferBarrier).Buffer()); // Blit vk::ImageSubresourceLayers subresourceLayers = vk::ImageSubresourceLayers() .setAspectMask(vk::ImageAspectFlagBits::eColor) .setMipLevel(0) .setBaseArrayLayer(0) .setLayerCount(1); int srcWidth, srcHeight, destWidth, destHeight; dynamic_cast<VK::Texture2D*>(srcImage)->GetSize(srcWidth, srcHeight); dynamic_cast<VK::Texture2D*>(dstImage)->GetSize(destWidth, destHeight); std::array<vk::Offset3D, 2> srcOffsets; if (flipSrc != SourceFlipMode::None) { srcOffsets[0] = vk::Offset3D(0, srcHeight, 0); srcOffsets[1] = vk::Offset3D(srcWidth, 0, 1); } else { srcOffsets[0] = vk::Offset3D(0, 0, 0); srcOffsets[1] = vk::Offset3D(srcWidth, srcHeight, 1); } std::array<vk::Offset3D, 2> dstOffsets; dstOffsets[0] = vk::Offset3D(dstOffset.x, dstOffset.y, 0); dstOffsets[1] = vk::Offset3D(dstOffset.x + srcWidth, dstOffset.y + srcHeight, 1); int wFix = 0, hFix = 0; if (dstOffsets[1].x > destWidth) wFix = destWidth - dstOffsets[1].x; if (dstOffsets[1].y > destHeight) hFix = destHeight - dstOffsets[1].y; dstOffsets[1].x += wFix; dstOffsets[1].y += hFix; srcOffsets[1].x += wFix; srcOffsets[1].y += hFix; vk::ImageBlit blitRegions = vk::ImageBlit() .setSrcSubresource(subresourceLayers) .setSrcOffsets(srcOffsets) .setDstSubresource(subresourceLayers) .setDstOffsets(dstOffsets); primaryBuffer.blitImage( srcTexture->image, vk::ImageLayout::eTransferSrcOptimal, dstTexture->image, vk::ImageLayout::eTransferDstOptimal, blitRegions, vk::Filter::eNearest ); srcTexture->currentSubresourceLayouts[0] = vk::ImageLayout::eTransferSrcOptimal; } virtual void Present(GameEngine::WindowSurface *surface, GameEngine::Texture2D* srcImage) override { ((VkWindowSurface*)surface)->Present(srcImage); } virtual BufferObject* CreateBuffer(BufferUsage usage, int size, const BufferStructureInfo* structInfo) override { CORELIB_UNUSED(structInfo); return new BufferObject(TranslateUsageFlags(usage) | vk::BufferUsageFlagBits::eTransferSrc, size, vk::MemoryPropertyFlagBits::eDeviceLocal); } virtual BufferObject* CreateMappedBuffer(BufferUsage usage, int size, const BufferStructureInfo* structInfo) override { CORELIB_UNUSED(structInfo); return new BufferObject(TranslateUsageFlags(usage), size, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent); } Texture2D* CreateTexture2D(CoreLib::String name, int pwidth, int pheight, StorageFormat format, DataType dataType, void* data) override { TextureUsage usage; usage = TextureUsage::Sampled; int mipLevelCount = (int)Math::Log2Floor(Math::Max(pwidth, pheight)) + 1; Texture2D* res = new Texture2D(name, usage, pwidth, pheight, mipLevelCount, format); res->SetData(pwidth, pheight, 1, dataType, data); res->BuildMipmaps(); return res; } Texture2D* CreateTexture2D(CoreLib::String name, TextureUsage usage, int pwidth, int pheight, int mipLevelCount, StorageFormat format) override { Texture2D* res = new Texture2D(name, usage, pwidth, pheight, mipLevelCount, format); return res; } Texture2D* CreateTexture2D(CoreLib::String name, TextureUsage usage, int pwidth, int pheight, int mipLevelCount, StorageFormat format, DataType dataType, CoreLib::ArrayView<void*> mipLevelData) override { Texture2D* res = new Texture2D(name, usage, pwidth, pheight, mipLevelCount, format); for (int level = 0; level < mipLevelCount; level++) res->SetData(level, Math::Max(pwidth >> level, 1), Math::Max(pheight >> level, 1), 1, dataType, mipLevelData[level]); return res; } Texture2DArray* CreateTexture2DArray(CoreLib::String name, TextureUsage usage, int w, int h, int layers, int mipLevelCount, StorageFormat format) override { Texture2DArray* res = new Texture2DArray(name, usage, w, h, mipLevelCount, layers, format); return res; } TextureCube* CreateTextureCube(CoreLib::String name, TextureUsage usage, int size, int mipLevelCount, StorageFormat format) override { TextureCube* res = new TextureCube(name, usage, size, mipLevelCount, format); return res; } virtual TextureCubeArray* CreateTextureCubeArray(CoreLib::String name, TextureUsage usage, int size, int mipLevelCount, int cubemapCount, StorageFormat format) override { TextureCubeArray * rs = new TextureCubeArray(name, usage, cubemapCount, size, mipLevelCount, format); return rs; } Texture3D* CreateTexture3D(CoreLib::String name, TextureUsage usage, int w, int h, int d, int mipLevelCount, StorageFormat format) override { Texture3D* res = new Texture3D(name, usage, w, h, d, mipLevelCount, format); return res; } TextureSampler* CreateTextureSampler() override { return new TextureSampler(); } Shader* CreateShader(ShaderType stage, const char* data, int size) override { Shader* result = new Shader(); result->Create(stage, data, size); return result; } virtual RenderTargetLayout* CreateRenderTargetLayout(CoreLib::ArrayView<AttachmentLayout> bindings, bool ignoreInitialContent) override { return new RenderTargetLayout(bindings, ignoreInitialContent); } virtual PipelineBuilder* CreatePipelineBuilder() override { return new PipelineBuilder(); } virtual DescriptorSetLayout* CreateDescriptorSetLayout(CoreLib::ArrayView<DescriptorLayout> descriptors) override { return new DescriptorSetLayout(descriptors); } virtual DescriptorSet * CreateDescriptorSet(GameEngine::DescriptorSetLayout* layout) override { return new DescriptorSet(reinterpret_cast<VK::DescriptorSetLayout*>(layout)); } Fence* CreateFence() override { return new Fence(); } CommandBuffer* CreateCommandBuffer() override { return new CommandBuffer(); } virtual int UniformBufferAlignment() override { return (int)RendererState::PhysicalDevice().getProperties().limits.minUniformBufferOffsetAlignment; } virtual int StorageBufferAlignment() override { return (int)RendererState::PhysicalDevice().getProperties().limits.minStorageBufferOffsetAlignment; } virtual String GetRendererName() override { return RendererState::PhysicalDevice().getProperties().deviceName; } virtual bool IsImageSpaceYAxisInverted() override { return true; } }; } HardwareRenderer* GameEngine::CreateVulkanHardwareRenderer(int gpuId, String pipelineCacheLocation) { VK::GpuId = gpuId; return new VK::HardwareRenderer(pipelineCacheLocation); }
37.630362
204
0.709493
csyonghe
c4553de6373a9657acb50c651dc4c0b91d3cef5e
3,529
hpp
C++
qtgui/soda_comboboxes.hpp
kb1vc/SoDaRadio
0a41fa3d795b1c93795ad62ad17bf2de5f60a752
[ "BSD-2-Clause" ]
14
2017-10-27T16:01:05.000Z
2021-03-16T08:12:42.000Z
qtgui/soda_comboboxes.hpp
dd0vs/SoDaRadio
0a41fa3d795b1c93795ad62ad17bf2de5f60a752
[ "BSD-2-Clause" ]
11
2017-09-16T03:13:11.000Z
2020-12-11T09:11:35.000Z
qtgui/soda_comboboxes.hpp
dd0vs/SoDaRadio
0a41fa3d795b1c93795ad62ad17bf2de5f60a752
[ "BSD-2-Clause" ]
6
2017-09-13T12:47:43.000Z
2020-12-02T20:54:25.000Z
/* Copyright (c) 2017 Matthew H. Reilly (kb1vc) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SODA_WFALL_COMBO_BOXES_H #define SODA_WFALL_COMBO_BOXES_H #include <QWidget> #include <QComboBox> #include <QString> #include <vector> #include <map> #include <cmath> #include <iostream> namespace GUISoDa { class ValComboBox : public QComboBox { Q_OBJECT public: explicit ValComboBox(QWidget * parent = 0) : QComboBox(parent) { clear(); connect(this, &QComboBox::currentTextChanged, this, &ValComboBox::textChanged); } double value() { return valmap[currentText()]; } public slots: void addValue(QString lab, double val); void setValue(double v); signals: void valueChanged(double v); protected: void textChanged(const QString & txt); std::map<QString, double> valmap; }; class WFallDynRangeComboBox : public ValComboBox { Q_OBJECT public: WFallDynRangeComboBox(QWidget * parent = 0) : ValComboBox(parent) { addValue("50", 50.0); addValue("45", 45.0); addValue("40", 40.0); addValue("35", 35.0); addValue("30", 30.0); addValue("25", 25.0); addValue("15", 15.0); addValue("10", 10.0); addValue("5", 5.0); setValue(25.0); } }; class WFallSpanComboBox : public ValComboBox { Q_OBJECT public: WFallSpanComboBox(QWidget * parent = 0) : ValComboBox(parent) { addValue("200", 200.0); addValue("100", 100.0); addValue("50", 50.0); addValue("25", 25.0); addValue("10", 10.0); setValue(200.0); } }; class IntValComboBox : public QComboBox { Q_OBJECT public: explicit IntValComboBox(QWidget * parent = 0) : QComboBox(parent) { clear(); connect(this, &QComboBox::currentTextChanged, this, &IntValComboBox::textChanged); } int value() { return valmap[currentText()]; } public slots: void addValue(QString lab, int val); void setValue(int v); void setValue(const QString & s); signals: void valueChanged(int v); protected: void textChanged(const QString & txt); std::map<QString, int> valmap; }; } #endif
27.356589
90
0.672428
kb1vc
c465c8d17760be36b0247edede5e4117f865bfaa
1,578
cc
C++
src/media_factory_sdl.cc
Jaween/september
17b712a1a278d159e69cb5134109255472e11098
[ "Apache-2.0" ]
null
null
null
src/media_factory_sdl.cc
Jaween/september
17b712a1a278d159e69cb5134109255472e11098
[ "Apache-2.0" ]
null
null
null
src/media_factory_sdl.cc
Jaween/september
17b712a1a278d159e69cb5134109255472e11098
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <SDL2/SDL_mixer.h> #include "media_factory_sdl.hpp" #include "image_sdl.hpp" #include "window_manager_sdl.hpp" MediaFactorySdl::MediaFactorySdl() { initialiseSdl(); } MediaFactorySdl::~MediaFactorySdl() { Mix_FreeMusic(music_); music_ = NULL; Mix_Quit(); IMG_Quit(); SDL_Quit(); } WindowManager* MediaFactorySdl::createWindowManager() { WindowManager* window_manager = new WindowManagerSdl(); window_managers.push_back(window_manager); return window_manager; } Image* MediaFactorySdl::createImage(unsigned int width, unsigned int height, unsigned int words_per_pixel) { Image* image = new ImageSdl(width, height, words_per_pixel); images.push_back(image); return image; } bool MediaFactorySdl::initialiseSdl() { if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) == -1) { std::cerr << "Failed to initialise SDL" << std::endl; return false; } int flags = IMG_INIT_PNG; if ((IMG_Init(flags) & flags) == -1) { std::cerr << "Failed to initialise SDL_image" << std::endl; return false; } if ((Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) == -1)) { std::cerr << "Failed to initialise SDL_mixer" << std::endl; return false; } return true; } void MediaFactorySdl::playAudio(std::string filename, bool loop) { music_ = Mix_LoadMUS(filename.c_str()); if (music_ == NULL) { std::cerr << "Could not open " << filename << std::endl; } if (loop) { Mix_PlayMusic(music_, -1); } else { Mix_PlayMusic(music_, 1); } }
23.909091
108
0.688213
Jaween
c466dadaccef19813483ba8370f6b329ac159cbb
711
cpp
C++
GEAR_CORE/src/Core/Timer.cpp
AndrewRichards-Code/GEAR_CORE
4d4e77bf643dc9b98de9f38445eae690290e1895
[ "MIT" ]
3
2020-12-13T19:53:17.000Z
2021-12-29T14:53:35.000Z
GEAR_CORE/src/Core/Timer.cpp
AndrewRichards-Code/GEAR_CORE
4d4e77bf643dc9b98de9f38445eae690290e1895
[ "MIT" ]
1
2021-10-06T09:36:34.000Z
2021-10-09T03:46:37.000Z
GEAR_CORE/src/Core/Timer.cpp
AndrewRichards-Code/GEAR
c08dfce35ccaa4bde046eb5b9e94d53eb65e7586
[ "MIT" ]
null
null
null
#include "gear_core_common.h" #include "Timer.h" using namespace gear; using namespace core; Timer::Timer() { m_StartTimePoint = std::chrono::system_clock::now(); m_NowTimePoint = std::chrono::system_clock::now(); } Timer::~Timer() { } void Timer::Update() { GetDeltaTime(); } double Timer::GetTime() { m_NowTimePoint = std::chrono::system_clock::now(); m_ElapsedDuration = m_NowTimePoint - m_StartTimePoint; return m_ElapsedDuration.count(); } double Timer::GetElapsedTime() { m_ElapsedTime = GetTime(); return m_ElapsedTime; } double Timer::GetDeltaTime() { GetElapsedTime(); m_DeltaTime = m_ElapsedTime - m_PreviousElapsedTime; m_PreviousElapsedTime = m_ElapsedTime; return m_DeltaTime; }
16.928571
55
0.739803
AndrewRichards-Code
c466dcdd1f20af1289d978da91deb2db339b9179
2,811
cpp
C++
Project 19-/26 Compute Shader Beginning/GameApp.cpp
MKXJun/DX11-Without-DirectX-SDK
31756de150248fc8f4ccb6ce0c5e2837da718c2d
[ "MIT" ]
3
2018-05-29T12:18:08.000Z
2018-06-20T16:14:13.000Z
Project 19-/26 Compute Shader Beginning/GameApp.cpp
MKXJun/DX11-Without-DirectX-SDK
31756de150248fc8f4ccb6ce0c5e2837da718c2d
[ "MIT" ]
null
null
null
Project 19-/26 Compute Shader Beginning/GameApp.cpp
MKXJun/DX11-Without-DirectX-SDK
31756de150248fc8f4ccb6ce0c5e2837da718c2d
[ "MIT" ]
null
null
null
#include "GameApp.h" using namespace DirectX; GameApp::GameApp(HINSTANCE hInstance) : D3DApp(hInstance) { } GameApp::~GameApp() { } bool GameApp::Init() { if (!D3DApp::Init()) return false; if (!InitResource()) return false; return true; } void GameApp::Compute() { assert(m_pd3dImmediateContext); //#if defined(DEBUG) | defined(_DEBUG) // ComPtr<IDXGraphicsAnalysis> graphicsAnalysis; // HR(DXGIGetDebugInterface1(0, __uuidof(graphicsAnalysis.Get()), reinterpret_cast<void**>(graphicsAnalysis.GetAddressOf()))); // graphicsAnalysis->BeginCapture(); //#endif m_pd3dImmediateContext->CSSetShaderResources(0, 1, m_pTextureInputA.GetAddressOf()); m_pd3dImmediateContext->CSSetShaderResources(1, 1, m_pTextureInputB.GetAddressOf()); m_pd3dImmediateContext->CSSetShader(m_pTextureMul_CS.Get(), nullptr, 0); m_pd3dImmediateContext->CSSetUnorderedAccessViews(0, 1, m_pTextureOutputUAV.GetAddressOf(), nullptr); m_pd3dImmediateContext->Dispatch(32, 32, 1); //#if defined(DEBUG) | defined(_DEBUG) // graphicsAnalysis->EndCapture(); //#endif SaveDDSTextureToFile(m_pd3dImmediateContext.Get(), m_pTextureOutput.Get(), L"..\\Texture\\flareoutput.dds"); MessageBox(nullptr, L"请打开..\\Texture文件夹观察输出文件flareoutput.dds", L"运行结束", MB_OK); } bool GameApp::InitResource() { CreateDDSTextureFromFile(m_pd3dDevice.Get(), L"..\\Texture\\flare.dds", nullptr, m_pTextureInputA.GetAddressOf()); CreateDDSTextureFromFile(m_pd3dDevice.Get(), L"..\\Texture\\flarealpha.dds", nullptr, m_pTextureInputB.GetAddressOf()); // DXGI_FORMAT | RWTexture2D<T> // --------------------------------+------------------ // DXGI_FORMAT_R8G8B8A8_UNORM | unorm float4 // DXGI_FORMAT_R16G16B16A16_UNORM | unorm float4 // DXGI_FORMAT_R8G8B8A8_SNORM | snorm float4 // DXGI_FORMAT_R16G16B16A16_SNORM | snorm float4 // DXGI_FORMAT_R16G16B16A16_FLOAT | float4 或 half4? // DXGI_FORMAT_R32G32B32A32_FLOAT | float4 DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM; CD3D11_TEXTURE2D_DESC texDesc(format, 512, 512, 1, 1, D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS); m_pd3dDevice->CreateTexture2D(&texDesc, nullptr, m_pTextureOutput.GetAddressOf()); // 创建无序访问视图 CD3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc(D3D11_UAV_DIMENSION_TEXTURE2D, format); m_pd3dDevice->CreateUnorderedAccessView(m_pTextureOutput.Get(), &uavDesc, m_pTextureOutputUAV.GetAddressOf()); // 创建计算着色器 ComPtr<ID3DBlob> blob; D3DReadFileToBlob(L"Shaders\\TextureMul_CS.cso", blob.GetAddressOf()); m_pd3dDevice->CreateComputeShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, m_pTextureMul_CS.GetAddressOf()); return true; }
31.943182
129
0.708645
MKXJun
c467b7e1d8f23903c808048aaf4e21c7effcd1c6
1,104
cpp
C++
Languages/C++/all_possible_permutations_for_n_numbers.cpp
anujjain5699/Hacktoberfest
05a2a8f813e301012240b14d729d015b35fbded7
[ "MIT" ]
null
null
null
Languages/C++/all_possible_permutations_for_n_numbers.cpp
anujjain5699/Hacktoberfest
05a2a8f813e301012240b14d729d015b35fbded7
[ "MIT" ]
null
null
null
Languages/C++/all_possible_permutations_for_n_numbers.cpp
anujjain5699/Hacktoberfest
05a2a8f813e301012240b14d729d015b35fbded7
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define int long long #define rep(i,n) for(int i=0;i<n;i++) #define fast ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); /*n=3 3 1 3 6 1 3 6 1 6 3 3 1 6 3 6 1 6 1 3 6 3 1 */ vector<vector<int>> permute(vector<int> &num) { if(num.size()<=1) return {num}; vector<vector<int>> result; for(int i=0;i<num.size();i++) { vector<int>v(num.begin(),num.end()); v.erase(v.begin()+i); auto res=permute(v); for(int j=0;j<res.size();j++) { vector<int> _v=res[j]; _v.insert(_v.begin(),num[i]); result.push_back(_v); } } return result; } int32_t main(){ fast int n; cin>>n; vector<int> v; rep(i,n) { int num; cin>>num; v.push_back(num); } vector<vector<int>> res=permute(v); for (int i = 0; i < res.size();i++) { for (auto it = res[i].begin();it != res[i].end(); it++) cout << *it << " "; cout << endl; } return 0; }
18.098361
84
0.48913
anujjain5699
c469ae0d20e412b6b651b03d9b5b605532924a60
3,075
hpp
C++
llarp/net/net_addr.hpp
tewinget/loki-network
556277a2609dfc7417a67a61c1a5e3951640c764
[ "Zlib" ]
1
2021-02-10T03:41:22.000Z
2021-02-10T03:41:22.000Z
llarp/net/net_addr.hpp
tzf-key/loki-network
01b3c0363caa746abf0fa52d27ffef1c84141cc3
[ "Zlib" ]
2
2019-12-19T15:37:07.000Z
2020-01-31T19:42:28.000Z
llarp/net/net_addr.hpp
tzf-key/loki-network
01b3c0363caa746abf0fa52d27ffef1c84141cc3
[ "Zlib" ]
null
null
null
#ifndef LLARP_NET_ADDR_HPP #define LLARP_NET_ADDR_HPP #include <net/address_info.hpp> #include <net/net.h> #include <net/net.hpp> #include <util/string_view.hpp> #include <net/net_int.hpp> #include <string> namespace llarp { // real work struct Addr { // network order sockaddr_in6 _addr; sockaddr_in _addr4; // why do we even have this? favor cpu over memory ~Addr(); Addr(); Addr(const Addr& other); void port(uint16_t port); in6_addr* addr6(); in_addr* addr4(); const in6_addr* addr6() const; const in_addr* addr4() const; Addr(const std::string str); Addr(const std::string str, const uint16_t p_port); Addr(string_view addr_str, string_view port_str); bool from_char_array(const char* str); Addr(const char* str); bool from_4int(const uint8_t one, const uint8_t two, const uint8_t three, const uint8_t four); Addr(const uint8_t one, const uint8_t two, const uint8_t three, const uint8_t four); Addr(const uint8_t one, const uint8_t two, const uint8_t three, const uint8_t four, const uint16_t p_port); Addr(const AddressInfo& other); Addr(const sockaddr_in& other); Addr(const sockaddr_in6& other); Addr(const sockaddr& other); std::string ToString() const; friend std::ostream& operator<<(std::ostream& out, const Addr& a); operator const sockaddr*() const; operator sockaddr*() const; void CopyInto(sockaddr* other) const; int af() const; uint16_t port() const; bool operator<(const Addr& other) const; bool operator==(const Addr& other) const; Addr& operator=(const sockaddr& other); inline uint32_t tohl() const { return ntohl(addr4()->s_addr); } inline huint32_t xtohl() const { return huint32_t{ntohl(addr4()->s_addr)}; } inline uint32_t ton() const { return addr4()->s_addr; } inline nuint32_t xtonl() const { return nuint32_t{addr4()->s_addr}; } bool sameAddr(const Addr& other) const; bool operator!=(const Addr& other) const; inline uint32_t getHostLong() { in_addr_t addr = this->addr4()->s_addr; uint32_t byte = ntohl(addr); return byte; } bool isTenPrivate(uint32_t byte); bool isOneSevenPrivate(uint32_t byte); bool isOneNinePrivate(uint32_t byte); /// return true if our ipv4 address is a bogon /// TODO: ipv6 bool IsBogon() const; socklen_t SockLen() const; bool isPrivate() const; bool isLoopback() const; struct Hash { std::size_t operator()(Addr const& a) const noexcept { if(a.af() == AF_INET) { return a.port() ^ a.addr4()->s_addr; } static const uint8_t empty[16] = {0}; return (a.af() + memcmp(a.addr6(), empty, 16)) ^ a.port(); } }; }; // end struct } // namespace llarp #endif
17.877907
75
0.602276
tewinget
c46a08da8a12a35a95113790233bd223db6b80b4
376
cpp
C++
ACM-ICPC/2455.cpp
KimBoWoon/ACM-ICPC
146c36999488af9234d73f7b4b0c10d78486604f
[ "MIT" ]
null
null
null
ACM-ICPC/2455.cpp
KimBoWoon/ACM-ICPC
146c36999488af9234d73f7b4b0c10d78486604f
[ "MIT" ]
null
null
null
ACM-ICPC/2455.cpp
KimBoWoon/ACM-ICPC
146c36999488af9234d73f7b4b0c10d78486604f
[ "MIT" ]
null
null
null
#include <cstdio> #include <algorithm> using namespace std; int x, y; int station[4]; int main() { // 조건에 맞게 실행하면 된다 for (int i = 0; i < 4; i++) { scanf("%d %d", &x, &y); station[i] = station[i - 1] - x; station[i] = station[i] + y; } printf("%d\n", max(station[0], max(station[1], max(station[2], station[3])))); }
20.888889
83
0.489362
KimBoWoon
c46ac87562bbd364481c80a2db80feb7f61e5bcc
504
cpp
C++
src/main.cpp
DannyHavenith/SimpleProjectSkeleton
163e1973eeecf845be308c6c58fc4a03c7057de9
[ "BSL-1.0" ]
null
null
null
src/main.cpp
DannyHavenith/SimpleProjectSkeleton
163e1973eeecf845be308c6c58fc4a03c7057de9
[ "BSL-1.0" ]
null
null
null
src/main.cpp
DannyHavenith/SimpleProjectSkeleton
163e1973eeecf845be308c6c58fc4a03c7057de9
[ "BSL-1.0" ]
null
null
null
/** * Distributed under the Boost Software License, Version 1.0. (See * accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ #include <iostream> #include <exception> void error( const std::string &what) { throw std::runtime_error( what); } int main(int argc, char* argv[]) { try { std::cout << "It's working!\n"; } catch (std::exception &e) { std::cerr << "something went wrong: " << e.what() << '\n'; } return 0; }
15.75
66
0.595238
DannyHavenith
c46bb90f4171afb1b290cd9bcaf163f5c6ba264e
6,586
cpp
C++
src/prod/src/retail/native/fabrichost/FabricActivatorService.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/retail/native/fabrichost/FabricActivatorService.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/retail/native/fabrichost/FabricActivatorService.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace ServiceModel; using namespace Common; using namespace Transport; using namespace Hosting2; using namespace FabricHost; RealConsole console; const StringLiteral TraceType("FabricHost"); FabricActivatorService::FabricActivatorService( bool runAsService, bool activateHidden, bool skipFabricSetup) : ServiceBase(FabricHost::Constants::ServiceName), runAsService_(runAsService), activateHidden_(activateHidden), skipFabricSetup_(skipFabricSetup), stopping_(false), activationManager_() { } void FabricActivatorService::OnStart(Common::StringCollection const &) { Trace.WriteInfo(TraceType, "FabricActivatorService starting ..."); if (runAsService_) { ServiceModeStartWait(); } else { ConsoleModeStartWait(); } } #if !defined(PLATFORM_UNIX) void FabricActivatorService::OnPreshutdown() { Trace.WriteInfo(TraceType, "Received Preshutdown notification, stopping ..."); if (Hosting2::FabricHostConfig::GetConfig().EnableRestartManagement && runAsService_) { SetServiceState(SERVICE_STOP_PENDING, 4, 30000); Threadpool::Post([this]() { this->DisableNode(); }); } else { OnStop(false); } } #endif void FabricActivatorService::OnStop(bool shutdown) { Trace.WriteInfo(TraceType, "service stopping (shutdown = {0}) ...", shutdown); if(stopping_) { Trace.WriteInfo(TraceType, "service is already in stopping process"); return; } stopping_ = true; if (runAsService_) { ServiceModeStopWait(); } else { ConsoleModeStopWait(); } } void FabricActivatorService::OnPause() { Assert::CodingError("{0} does not support pause", FabricHost::Constants::ServiceName); } void FabricActivatorService::OnContinue() { Assert::CodingError("{0} does not support continue", FabricHost::Constants::ServiceName); } void FabricActivatorService::ServiceModeStartWait() { StartActivationManager(); } void FabricActivatorService::ConsoleModeStartWait() { StartActivationManager(); } void FabricActivatorService::ServiceModeStopWait() { StopActivationManager(); } void FabricActivatorService::ConsoleModeStopWait() { console.WriteLine(StringResource::Get(IDS_FABRICHOST_CLOSING)); StopActivationManager(); console.WriteLine(StringResource::Get(IDS_FABRICHOST_CLOSED)); } void FabricActivatorService::OnOpenComplete(AsyncOperationSPtr operation) { ErrorCode error = activationManager_->EndOpen(operation); Trace.WriteTrace(error.ToLogLevel(), TraceType, "FabricActivatorManager open returned {0}", error); if(!error.IsSuccess()) { ::ExitProcess(1); } } void FabricActivatorService::CreateAndOpen(AutoResetEvent & openEvent) { activationManager_ = make_shared<FabricActivationManager>(activateHidden_, skipFabricSetup_); activationManager_->BeginOpen(Hosting2::FabricHostConfig::GetConfig().StartTimeout, [&openEvent, this] (AsyncOperationSPtr const& operation) { this->OnOpenComplete(operation); openEvent.Set(); }, activationManager_->CreateAsyncOperationRoot() ); } void FabricActivatorService::StartActivationManager() { AutoResetEvent openEvent; Threadpool::Post([this, &openEvent]() { this->CreateAndOpen(openEvent); }); openEvent.WaitOne(); } void FabricActivatorService::OnCloseCompleted(AsyncOperationSPtr operation) { ErrorCode error = activationManager_->EndClose(operation); Trace.WriteTrace( error.ToLogLevel(), TraceType, "FabricActivatorManager close returned {0}", error); } void FabricActivatorService::Close(AutoResetEvent & closeEvent) { Trace.WriteInfo( TraceType, "FabricActivatorService close with timeout {0} ", Hosting2::FabricHostConfig::GetConfig().StopTimeout); activationManager_->BeginClose(Hosting2::FabricHostConfig::GetConfig().StopTimeout, [&closeEvent, this](AsyncOperationSPtr operation) { this->OnCloseCompleted(operation); closeEvent.Set(); }, activationManager_->CreateAsyncOperationRoot()); } void FabricActivatorService::StopActivationManager() { Trace.WriteInfo( TraceType, "FabricActivatorService StopActivationManager called {0}", Hosting2::FabricHostConfig::GetConfig().StopTimeout); AutoResetEvent closeEvent; Threadpool::Post([this, &closeEvent]() { this->Close(closeEvent); }); closeEvent.WaitOne(); } #if !defined(PLATFORM_UNIX) void FabricActivatorService::DisableNode() { AutoResetEvent disableEvent; int checkpoint = 5; SetServiceState(SERVICE_STOP_PENDING, checkpoint++, 30000); Trace.WriteInfo( TraceType, "FabricActivatorService DisableNode called with timeout {0}", FabricHost::Constants::NodeDisableWaitTimeInMinutes); Threadpool::Post([this, &disableEvent]() { auto asyncPtr = activationManager_->FabricRestartManagerObj->BeginNodeDisable( TimeSpan::FromMinutes(FabricHost::Constants::NodeDisableWaitTimeInMinutes), [&disableEvent, this](AsyncOperationSPtr operation) { this->activationManager_->FabricRestartManagerObj->EndNodeDisable(operation); disableEvent.Set(); }, activationManager_->CreateAsyncOperationRoot()); if (asyncPtr->CompletedSynchronously) { this->activationManager_->FabricRestartManagerObj->EndNodeDisable(asyncPtr); disableEvent.Set(); } }); SetServiceState(SERVICE_STOP_PENDING, checkpoint++, 30000); while (!disableEvent.WaitOne(TimeSpan::FromSeconds(15))) { Trace.WriteInfo(TraceType, "FabricActivatorService DisableNode, Still Waiting {0}", checkpoint); SetServiceState(SERVICE_STOP_PENDING, checkpoint++, 30000); } Trace.WriteInfo(TraceType, "Node disabled:{0}", checkpoint); SetServiceState(SERVICE_STOP_PENDING, checkpoint++, 30000); OnStop(false); Trace.WriteInfo(TraceType, "Stopping service..."); SetServiceState(SERVICE_STOPPED, checkpoint++); } #endif
27.90678
104
0.684482
AnthonyM
c47023396d2b11a6e4bc5eec694d80d879aca542
631
cpp
C++
samples/hello_ar_c/app/src/main/gef_abertay/maths/vector2.cpp
JD1305/arcore-android-sdk
ac3661d9dc65a608235d775cf6a916df2329b399
[ "Apache-2.0" ]
null
null
null
samples/hello_ar_c/app/src/main/gef_abertay/maths/vector2.cpp
JD1305/arcore-android-sdk
ac3661d9dc65a608235d775cf6a916df2329b399
[ "Apache-2.0" ]
null
null
null
samples/hello_ar_c/app/src/main/gef_abertay/maths/vector2.cpp
JD1305/arcore-android-sdk
ac3661d9dc65a608235d775cf6a916df2329b399
[ "Apache-2.0" ]
null
null
null
#include <maths/vector2.h> #include <math.h> namespace gef { const Vector2 Vector2::kZero(0.0f, 0.0f); const Vector2 Vector2::kOne(1.0f, 1.0f); void Vector2::Normalise() { float length = Length(); x /= length; y /= length; } float Vector2::LengthSqr() const { return (x*x + y*y); } float Vector2::Length() const { return sqrtf(x*x + y*y); } Vector2 Vector2::Rotate(float angle) { Vector2 result; result.x = x*cosf(angle) - y*sinf(angle); result.y = x*sinf(angle) + y*cosf(angle); return result; } float Vector2::DotProduct(const Vector2& _vec) const { return x*_vec.x + y*_vec.y; } }
14.674419
53
0.630745
JD1305
c4704897edbdc6505338ba35d372c032016f8987
3,329
cc
C++
src/geometry/test/test_Mesh1D.cc
RLReed/libdetran
77637c788823e0a14aae7e40e476a291f6f3184b
[ "MIT" ]
4
2015-03-07T16:20:23.000Z
2020-02-10T13:40:16.000Z
src/geometry/test/test_Mesh1D.cc
RLReed/libdetran
77637c788823e0a14aae7e40e476a291f6f3184b
[ "MIT" ]
3
2018-02-27T21:24:22.000Z
2020-12-16T00:56:44.000Z
src/geometry/test/test_Mesh1D.cc
RLReed/libdetran
77637c788823e0a14aae7e40e476a291f6f3184b
[ "MIT" ]
9
2015-03-07T16:20:26.000Z
2022-01-29T00:14:23.000Z
//----------------------------------*-C++-*----------------------------------// /*! * \file test_Mesh1D.cc * \author Jeremy Roberts * \date Apr 1, 2012 * \brief Test of Mesh1D class. * \note Copyright (C) 2012 Jeremy Roberts. */ //---------------------------------------------------------------------------// // LIST OF TEST FUNCTIONS #define TEST_LIST \ FUNC(test_Mesh1D) \ FUNC(test_Mesh1D_serialize) // Detran headers #include "TestDriver.hh" #include "Mesh1D.hh" // System headers #include <fstream> // Setup #include "mesh_fixture.hh" using namespace detran_geometry; using namespace detran_utilities; using namespace detran_test; using namespace std; int main(int argc, char *argv[]) { RUN(argc, argv); } //----------------------------------------------// // TEST DEFINITIONS //----------------------------------------------// int test_Mesh1D(int argc, char *argv[]) { // Get the mesh SP_mesh mesh = mesh_1d_fixture(); // Mesh properties: // cm = [ 0.0 5.0 10.0] // fm = [ 5 5 ] // mt = [ 0 1 ] // Basic mesh things. TEST(mesh->number_cells() == 10); TEST(mesh->number_cells_x() == 10); TEST(mesh->number_cells_y() == 1); TEST(mesh->number_cells_z() == 1); TEST(mesh->dx(0) == 1.0); TEST(mesh->dy(0) == 1.0); TEST(mesh->dz(0) == 1.0); TEST(mesh->dimension() == 1); int cell = 5; TEST(mesh->index(5) == cell); TEST(mesh->cell_to_i(cell) == 5); TEST(mesh->cell_to_j(cell) == 0); TEST(mesh->cell_to_k(cell) == 0); TEST(mesh->volume(cell) == 1.0); vec_int mat_map = mesh->mesh_map("MATERIAL"); TEST(mat_map[0] == 0); TEST(mat_map[5] == 1); TESTFALSE(mesh->mesh_map_exists("SHOULDNOTEXIST")); return 0; } int test_Mesh1D_serialize(int argc, char *argv[]) { #ifdef DETRAN_ENABLE_BOOST { // Get the mesh and pack it SP_mesh mesh = mesh_1d_fixture(); mesh->display(); std::ofstream ofs("mesh1d.archive"); boost::archive::binary_oarchive oa(ofs); oa << mesh; ofs.close(); } { // Unpack SP_mesh mesh; std::ifstream ifs("mesh1d.archive"); boost::archive::binary_iarchive ia(ifs); ia >> mesh; ifs.close(); mesh->display(); // Test TEST(mesh->number_cells() == 10); TEST(mesh->number_cells_x() == 10); TEST(mesh->number_cells_y() == 1); TEST(mesh->number_cells_z() == 1); TEST(mesh->dx(0) == 1.0); TEST(mesh->dy(0) == 1.0); TEST(mesh->dz(0) == 1.0); TEST(mesh->dimension() == 1); int cell = 5; TEST(mesh->index(5) == cell); TEST(mesh->cell_to_i(cell) == 5); TEST(mesh->cell_to_j(cell) == 0); TEST(mesh->cell_to_k(cell) == 0); TEST(mesh->volume(cell) == 1.0); vec_int mat_map = mesh->mesh_map("MATERIAL"); TEST(mat_map[0] == 0); TEST(mat_map[5] == 1); TESTFALSE(mesh->mesh_map_exists("SHOULDNOTEXIST")); } #endif return 0; } //---------------------------------------------------------------------------// // end of test_Mesh3D.cc //---------------------------------------------------------------------------//
26.420635
79
0.479423
RLReed
c4709fa177c376c60cb488f07a8d73a95f86c4d4
6,522
cpp
C++
source/core/fluid-solver.cpp
linusmossberg/fluid-simulator
629301987fff9e82cf1f1cc99b010b5f8619136b
[ "MIT" ]
24
2021-03-16T13:22:08.000Z
2022-02-20T12:43:35.000Z
source/core/fluid-solver.cpp
linusmossberg/fluid-simulator
629301987fff9e82cf1f1cc99b010b5f8619136b
[ "MIT" ]
null
null
null
source/core/fluid-solver.cpp
linusmossberg/fluid-simulator
629301987fff9e82cf1f1cc99b010b5f8619136b
[ "MIT" ]
4
2021-03-16T16:38:54.000Z
2022-01-17T17:31:55.000Z
#include "fluid-solver.hpp" #include <iostream> #include "util.hpp" #include "../gl-util/fbo.hpp" #include "../gl-util/shader.hpp" #include "../gl-util/quad.hpp" #include "../shaders/screen.vert" #include "../shaders/stencil.vert" #include "../shaders/fluid-solver/advect.frag" #include "../shaders/fluid-solver/force.frag" #include "../shaders/fluid-solver/jacobi-diffusion.frag" #include "../shaders/fluid-solver/jacobi-pressure.frag" #include "../shaders/fluid-solver/divergence.frag" #include "../shaders/fluid-solver/curl.frag" #include "../shaders/fluid-solver/vorticity.frag" #include "../shaders/fluid-solver/gradient-subtract.frag" #include "../shaders/fluid-solver/speed.frag" FluidSolver::FluidSolver(const std::shared_ptr<Config>& cfg) : cfg(cfg) { setSize(glm::ivec2(128)); } void FluidSolver::step() { glViewport(0, 0, grid_cells.x, grid_cells.y); glScissor(0, 0, grid_cells.x, grid_cells.y); dx = cfg->sim_width / grid_cells.x; if (clear_velocity) { velocity->clear(glm::vec4(0.0f)); pressure->clear(glm::vec4(0.0f)); clear_velocity = false; } Quad::bind(); applyForce(); applyVorticityConfinement(); advect(velocity, temp_fbo); diffuseVelocity(); subtractPressureGradient(); computeSpeed(); } void FluidSolver::advect(std::unique_ptr<FBO>& quantity, std::unique_ptr<FBO>& temp_quantity) { static const Shader advect_shader(screen_vert, advect_frag, "advect"); temp_quantity->bind(); advect_shader.use(); glUniform1f(advect_shader.getLocation("dt"), cfg->dt); glm::vec2 world2tx = 1.0f / ((float)cfg->sim_width * glm::vec2(1.0f, y_aspect)); glUniform2fv(advect_shader.getLocation("world2tx"), 1, &world2tx[0]); velocity->bindTexture(0, GL_LINEAR); quantity->bindTexture(1, GL_LINEAR); Quad::draw(); std::swap(quantity, temp_quantity); } void FluidSolver::diffuseVelocity() { static const Shader jacobi_diffusion_shader(stencil_vert, jacobi_diffusion_frag, "jacobi-diffusion"); float nu = cfg->mu / cfg->rho; // Solver approaches unchanged velocity when dx2_nudt // approaches infinity, so this should be correct. if (nu <= 0.0f) return; jacobi_diffusion_shader.use(); float dx2_nudt = std::pow(dx, 2) / (nu * cfg->dt); glUniform2fv(jacobi_diffusion_shader.getLocation("tx_size"), 1, &cell_size[0]); glUniform1f(jacobi_diffusion_shader.getLocation("dx2_nudt"), dx2_nudt); temp_fbo2->bind(); velocity->bindTexture(0); velocity->bindTexture(1); Quad::draw(); for (int i = 0; i < cfg->viscosity_iterations - 1.0f; i++) { temp_fbo->bind(); temp_fbo2->bindTexture(0); Quad::draw(); std::swap(temp_fbo2, temp_fbo); } std::swap(velocity, temp_fbo2); } void FluidSolver::applyForce() { static const Shader force_shader(screen_vert, force_frag, "force"); temp_fbo->bind(); force_shader.use(); velocity->bindTexture(0); glm::vec2 force = (float)cfg->F * glm::vec2(std::cos(cfg->F_angle), std::sin(cfg->F_angle)); glUniform2fv(force_shader.getLocation("tx_size"), 1, &cell_size[0]); glUniform2fv(force_shader.getLocation("pos"), 1, &force_pos[0]); glUniform2fv(force_shader.getLocation("force"), 1, &force[0]); glUniform1f(force_shader.getLocation("dt"), cfg->dt); Quad::draw(); std::swap(velocity, temp_fbo); } void FluidSolver::computeCurl() { static const Shader curl_shader(stencil_vert, curl_frag, "curl"); curl->bind(); curl_shader.use(); velocity->bindTexture(0); glUniform2fv(curl_shader.getLocation("tx_size"), 1, &cell_size[0]); glUniform1f(curl_shader.getLocation("half_inv_dx"), 0.5f / dx); Quad::draw(); } void FluidSolver::applyVorticityConfinement() { static const Shader vorticity_shader(stencil_vert, vorticity_frag, "vorticity"); computeCurl(); if (cfg->vorticity < 1e-6f) return; temp_fbo->bind(); vorticity_shader.use(); velocity->bindTexture(0); curl->bindTexture(1); glUniform2fv(vorticity_shader.getLocation("tx_size"), 1, &cell_size[0]); glUniform1f(vorticity_shader.getLocation("half_inv_dx"), 0.5f / dx); glUniform1f(vorticity_shader.getLocation("dt"), cfg->dt); glUniform1f(vorticity_shader.getLocation("vorticity_scale"), cfg->vorticity); Quad::draw(); std::swap(temp_fbo, velocity); } void FluidSolver::computeDivergence() { static const Shader divergence_shader(stencil_vert, divergence_frag, "divergence"); divergence->bind(); divergence_shader.use(); velocity->bindTexture(0); glUniform2fv(divergence_shader.getLocation("tx_size"), 1, &cell_size[0]); glUniform1f(divergence_shader.getLocation("half_inv_dx"), 0.5f / dx); Quad::draw(); } void FluidSolver::computePressure() { static const Shader jacobi_pressure_shader(stencil_vert, jacobi_pressure_frag, "jacobi-pressure"); computeDivergence(); if (clear_pressure) pressure->clear(glm::vec4(0.0f)); jacobi_pressure_shader.use(); glUniform2fv(jacobi_pressure_shader.getLocation("tx_size"), 1, &cell_size[0]); glUniform1f(jacobi_pressure_shader.getLocation("dx2"), std::pow(dx, 2)); divergence->bindTexture(1); for (int i = 0; i < cfg->pressure_iterations; i++) { temp_fbo->bind(); pressure->bindTexture(0); Quad::draw(); std::swap(temp_fbo, pressure); } } void FluidSolver::subtractPressureGradient() { static const Shader gradient_subtract_shader(stencil_vert, gradient_subtract_frag, "gradient"); computePressure(); temp_fbo->bind(); gradient_subtract_shader.use(); pressure->bindTexture(0); velocity->bindTexture(1); glUniform2fv(gradient_subtract_shader.getLocation("tx_size"), 1, &cell_size[0]); glUniform1f(gradient_subtract_shader.getLocation("half_inv_dx"), 0.5f / dx); Quad::draw(); std::swap(temp_fbo, velocity); } void FluidSolver::computeSpeed() { static const Shader speed_shader(screen_vert, speed_frag, "speed"); speed->bind(); speed_shader.use(); velocity->bindTexture(0); Quad::draw(); } void FluidSolver::setSize(const glm::ivec2& grid_cells_) { grid_cells = grid_cells_; cell_size = 1.0f / glm::vec2(grid_cells); y_aspect = grid_cells.y / (float)grid_cells.x; for (auto& fbo : { &temp_fbo, &temp_fbo2, &velocity, &pressure, &divergence, &curl, &speed }) { *fbo = std::make_unique<FBO>(grid_cells); } }
25.778656
105
0.679853
linusmossberg
c4746985d107bc2f5bbec86fa80042245f0952ec
5,554
cpp
C++
tests/test-hdr/set/hdr_splitlist_set_dhp.cpp
simple555a/libcds
d05a0909402369d4a79eb82aed1742a7b227548b
[ "BSD-2-Clause" ]
2
2016-12-03T22:09:50.000Z
2021-08-31T12:44:24.000Z
tests/test-hdr/set/hdr_splitlist_set_dhp.cpp
TatyanaBerlenko/libcds
3f4dfab2aea72d70ce44e7fbc02da9a6908f0781
[ "BSD-2-Clause" ]
null
null
null
tests/test-hdr/set/hdr_splitlist_set_dhp.cpp
TatyanaBerlenko/libcds
3f4dfab2aea72d70ce44e7fbc02da9a6908f0781
[ "BSD-2-Clause" ]
2
2018-05-26T19:27:12.000Z
2021-08-31T12:44:28.000Z
//$$CDS-header$$ #include "set/hdr_set.h" #include <cds/container/michael_list_dhp.h> #include <cds/container/split_list_set.h> namespace set { namespace { struct DHP_cmp_traits: public cc::split_list::traits { typedef cc::michael_list_tag ordered_list; typedef HashSetHdrTest::hash_int hash; typedef HashSetHdrTest::simple_item_counter item_counter; typedef cc::opt::v::relaxed_ordering memory_model; enum { dynamic_bucket_table = false }; struct ordered_list_traits: public cc::michael_list::traits { typedef HashSetHdrTest::cmp<HashSetHdrTest::item> compare; }; }; struct DHP_less_traits: public cc::split_list::traits { typedef cc::michael_list_tag ordered_list; typedef HashSetHdrTest::hash_int hash; typedef HashSetHdrTest::simple_item_counter item_counter; typedef cc::opt::v::sequential_consistent memory_model; enum { dynamic_bucket_table = false }; struct ordered_list_traits: public cc::michael_list::traits { typedef HashSetHdrTest::less<HashSetHdrTest::item> less; }; }; struct DHP_cmpmix_traits: public cc::split_list::traits { typedef cc::michael_list_tag ordered_list; typedef HashSetHdrTest::hash_int hash; typedef HashSetHdrTest::simple_item_counter item_counter; struct ordered_list_traits: public cc::michael_list::traits { typedef HashSetHdrTest::cmp<HashSetHdrTest::item> compare; typedef HashSetHdrTest::less<HashSetHdrTest::item> less; }; }; struct DHP_cmpmix_stat_traits : public DHP_cmpmix_traits { typedef cc::split_list::stat<> stat; }; } void HashSetHdrTest::Split_DHP_cmp() { // traits-based version typedef cc::SplitListSet< cds::gc::DHP, item, DHP_cmp_traits > set; test_int< set >(); // option-based version typedef cc::SplitListSet< cds::gc::DHP, item, cc::split_list::make_traits< cc::split_list::ordered_list<cc::michael_list_tag> ,cc::opt::hash< hash_int > ,cc::opt::item_counter< simple_item_counter > ,cc::opt::memory_model< cc::opt::v::relaxed_ordering > ,cc::split_list::dynamic_bucket_table< true > ,cc::split_list::ordered_list_traits< cc::michael_list::make_traits< cc::opt::compare< cmp<item> > >::type > >::type > opt_set; test_int< opt_set >(); } void HashSetHdrTest::Split_DHP_less() { // traits-based version typedef cc::SplitListSet< cds::gc::DHP, item, DHP_less_traits > set; test_int< set >(); // option-based version typedef cc::SplitListSet< cds::gc::DHP, item, cc::split_list::make_traits< cc::split_list::ordered_list<cc::michael_list_tag> ,cc::opt::hash< hash_int > ,cc::opt::item_counter< simple_item_counter > ,cc::opt::memory_model< cc::opt::v::sequential_consistent > ,cc::split_list::dynamic_bucket_table< false > ,cc::split_list::ordered_list_traits< cc::michael_list::make_traits< cc::opt::less< less<item> > >::type > >::type > opt_set; test_int< opt_set >(); } void HashSetHdrTest::Split_DHP_cmpmix() { // traits-based version typedef cc::SplitListSet< cds::gc::DHP, item, DHP_cmpmix_traits > set; test_int< set >(); // option-based version typedef cc::SplitListSet< cds::gc::DHP, item, cc::split_list::make_traits< cc::split_list::ordered_list<cc::michael_list_tag> ,cc::opt::hash< hash_int > ,cc::opt::item_counter< simple_item_counter > ,cc::split_list::ordered_list_traits< cc::michael_list::make_traits< cc::opt::less< less<item> > ,cc::opt::compare< cmp<item> > >::type > >::type > opt_set; test_int< opt_set >(); } void HashSetHdrTest::Split_DHP_cmpmix_stat() { // traits-based version typedef cc::SplitListSet< cds::gc::DHP, item, DHP_cmpmix_stat_traits > set; test_int< set >(); // option-based version typedef cc::SplitListSet< cds::gc::DHP, item, cc::split_list::make_traits< cc::split_list::ordered_list<cc::michael_list_tag> ,cc::opt::hash< hash_int > ,cc::opt::item_counter< simple_item_counter > ,cc::split_list::ordered_list_traits< cc::michael_list::make_traits< cc::opt::less< less<item> > ,cc::opt::compare< cmp<item> > >::type > ,cds::opt::stat< cc::split_list::stat<> > >::type > opt_set; test_int< opt_set >(); } } // namespace set
35.151899
83
0.53547
simple555a
c47b7ead145c3e58aa8d9672e76278c81ffb18e1
2,019
cpp
C++
WindowsInternals/ExceptionHandling/ExceptionHandling.cpp
alonf/Windows-Internals-Course-Materials
591a84cfa349c17e66dc58d16e8b5f4662cad967
[ "MIT" ]
5
2017-04-28T10:30:36.000Z
2019-08-26T05:53:55.000Z
WindowsInternals/ExceptionHandling/ExceptionHandling.cpp
alonf/Windows-Internals-Course-Materials
591a84cfa349c17e66dc58d16e8b5f4662cad967
[ "MIT" ]
null
null
null
WindowsInternals/ExceptionHandling/ExceptionHandling.cpp
alonf/Windows-Internals-Course-Materials
591a84cfa349c17e66dc58d16e8b5f4662cad967
[ "MIT" ]
null
null
null
// ---------------------------------------------------------------------- // <copyright file="ExceptionHandling.cpp" company="CodeValue"> // Copyright (c) 2011 by CodeValue Ltd. All rights reserved // </copyright> // // http://codevalue.com // Licensed under the Educational Community License version 1.0 (http://www.opensource.org/licenses/ecl1) // This example was written as a demonstration of principles only // // ------------------------------------------------------------------------ // ExceptionHandling.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <Windows.h> #include <functional> #include <iostream> using namespace std; void CheckException(int depth) { __try { if (depth == 0) RaiseException(5, 0, 0, nullptr); __try { CheckException(depth - 1); } __finally { wcout << L"Called in the finally statement, depth: " << depth << L" Abnormal Termination:" << (AbnormalTermination() ? L"True" : L"False") << endl; } wcout << L"*** This is never written" << endl; } __except (EXCEPTION_CONTINUE_SEARCH) { } } void Test(PWSTR message) { wcout << endl << endl; wcout << "============================================" << endl; wcout << "========= N E W T E S T =============" << endl; wcout << "============================================" << endl; __try { CheckException(10); } __except (EXCEPTION_EXECUTE_HANDLER) { wcout << L"Test, message:" << message << endl;; } } LONG WINAPI VectoredHandler(_EXCEPTION_POINTERS *ExceptionInfo) { wcout << "Vectored Handler" << endl; return EXCEPTION_EXECUTE_HANDLER; } int main() { __try { Test(L"First"); PVOID hHandler = AddVectoredExceptionHandler(2, VectoredHandler); Test(L"After adding exception handler"); RemoveVectoredExceptionHandler(hHandler); Test(L"Last"); } __finally { wcout << L"Called in the finally statement of main. Abnormal Termination:" << (AbnormalTermination() ? L"True" : L"False") << endl; } return 0; }
22.433333
105
0.583952
alonf
c48569951844b3364da391edfc422359933cc089
1,048
cpp
C++
MatchMaster/Classes/Jewel.cpp
Ghost233/MatchMaster
03c5920e8dda487ccf1ecfdac9837a91c1e3763f
[ "MIT" ]
null
null
null
MatchMaster/Classes/Jewel.cpp
Ghost233/MatchMaster
03c5920e8dda487ccf1ecfdac9837a91c1e3763f
[ "MIT" ]
null
null
null
MatchMaster/Classes/Jewel.cpp
Ghost233/MatchMaster
03c5920e8dda487ccf1ecfdac9837a91c1e3763f
[ "MIT" ]
1
2019-08-15T04:59:08.000Z
2019-08-15T04:59:08.000Z
// // Jewel.cpp // MatchMaster // // Created by Ghost on 14-3-18. // // #include "Jewel.h" Jewel::Jewel():x(-1), y(-1) { } Jewel::~Jewel() { } bool Jewel::init() { return true; } bool Jewel::initWithJewelType(JewelType tempType) { if (!this->init()) return false; type = tempType; return true; } void Jewel::destroyAnimation() { auto action1 = FadeOut::create(0.5); auto action2 = ScaleBy::create(0.5, 1.5); auto action3 = Spawn::createWithTwoActions(action1, action2); auto action4 = CallFunc::create(CC_CALLBACK_0(Jewel::finalRemove, this)); auto action5 = Sequence::createWithTwoActions(action3, action4); this->runAction(action5); } void Jewel::finalRemove() { this->removeFromParentAndCleanup(true); } bool Jewel::fall(int targetX, int targetY) { if (y == targetY) return false; float length = (y - targetY) * SPACEY; auto action1 = MoveBy::create(length / FALL_SPEED_PER_SECOND, Point(0, -length)); y = targetY; this->runAction(action1); return true; }
18.385965
85
0.647901
Ghost233
c4890b4eefdcb2aa0ce94060079a7a1916c33d93
3,546
cpp
C++
src/core/visual/win32/krmovie/ogg/OggStreamMapper.cpp
miahmie/krkrz
e4948f61393ca4a2acac0301a975165dd4efc643
[ "Unlicense", "Apache-2.0", "Libpng", "FTL", "IJG" ]
null
null
null
src/core/visual/win32/krmovie/ogg/OggStreamMapper.cpp
miahmie/krkrz
e4948f61393ca4a2acac0301a975165dd4efc643
[ "Unlicense", "Apache-2.0", "Libpng", "FTL", "IJG" ]
null
null
null
src/core/visual/win32/krmovie/ogg/OggStreamMapper.cpp
miahmie/krkrz
e4948f61393ca4a2acac0301a975165dd4efc643
[ "Unlicense", "Apache-2.0", "Libpng", "FTL", "IJG" ]
null
null
null
#include "oggstdafx.h" #include "OggStreamMapper.h" #include "OggDemuxFilter.h" #include "OggDemuxOutputPin.h" OggStreamMapper::OggStreamMapper(OggDemuxFilter* inParentFilter, CCritSec* inParentFilterLock): mStreamState(STRMAP_READY), mParentFilter(inParentFilter), mParentFilterLock(inParentFilterLock), mFishHeadPacket(NULL), mSkeletonSerialNo(0) { } OggStreamMapper::~OggStreamMapper(void) { for (size_t i = 0; i < mPins.size(); i++) { delete mPins[i]; } } OggDemuxOutputPin* OggStreamMapper::getPinByIndex(unsigned long inIndex) { if (inIndex < mPins.size()) { return mPins[inIndex]; } return NULL; } bool OggStreamMapper::acceptOggPage(OggPage* inOggPage) { switch (mStreamState) { case STRMAP_READY: //WARNING::: Partial fall through if (inOggPage->header()->isBOS()) { mStreamState = STRMAP_PARSING_BOS_PAGES; } else { mStreamState = STRMAP_ERROR; delete inOggPage; return false; } //Partial fall through case STRMAP_PARSING_BOS_PAGES: //WARNING::: Partial fall through if (!allStreamsReady()) { if (inOggPage->header()->isBOS()) { return addNewPin(inOggPage); } else { mStreamState = STRMAP_DATA; } } //Partial fall through case STRMAP_DATA: { // TODO: remove useless code // if (mFishHeadPacket != NULL) // { // if (inOggPage->header()->StreamSerialNo() == mSkeletonSerialNo) // { // int x = 2; // } // } OggDemuxOutputPin* locPin = getMatchingPin(inOggPage->header()->StreamSerialNo()); if (locPin != NULL) { return locPin->acceptOggPage(inOggPage); } else { //Ignore unknown streams delete inOggPage; return true; } } break; case STRMAP_FINISHED: case STRMAP_ERROR: default: return false; } } bool OggStreamMapper::allStreamsReady() { bool locAllReady = true; //OggDemuxOutputPin* locPin = NULL; for (size_t i = 0; i < mPins.size(); i++) { locAllReady = locAllReady && mPins[i]->IsStreamReady(); } return locAllReady && (mPins.size() > 0); } bool OggStreamMapper::isFishHead(OggPage* inOggPage) { StampedOggPacket* locPacket = inOggPage->getStampedPacket(0); if (locPacket == NULL) { return false; } else { if ((strncmp((const char*)locPacket->packetData(), "fishead\0", 8)) == 0) { return true; } } return false; } bool OggStreamMapper::handleFishHead(OggPage* inOggPage) { mFishHeadPacket = inOggPage->getStampedPacket(0)->clone(); mSkeletonSerialNo = inOggPage->header()->StreamSerialNo(); delete inOggPage; return true; } bool OggStreamMapper::addNewPin(OggPage* inOggPage) { //FISH::: Catch the fishead here. if (isFishHead(inOggPage)) { return handleFishHead(inOggPage); } else { OggDemuxOutputPin* locNewPin = new OggDemuxOutputPin(NAME("OggPageSourcePin"), mParentFilter, mParentFilterLock, inOggPage->getPacket(0)->clone(), inOggPage->header()->StreamSerialNo()); //locNewPin->AddRef(); delete inOggPage; mPins.push_back(locNewPin); return true; } } OggDemuxOutputPin* OggStreamMapper::getMatchingPin(unsigned long inSerialNo) { OggDemuxOutputPin* locPin = NULL; for (size_t i = 0; i < mPins.size(); i++) { locPin = mPins[i]; if (locPin->getSerialNo() == inSerialNo) { return locPin; } } return NULL; }
21.754601
188
0.632262
miahmie
c4899eee09beb6df36ed93266dd2fd1c24838d29
3,365
cpp
C++
Atif/src/source/volumefraction.cpp
jiangj-physchem/Interface_project
36d17fc28dc1e3dec0b9c80575242b792eb9671b
[ "MIT" ]
15
2021-01-16T04:49:08.000Z
2022-02-22T14:17:35.000Z
Atif/program/src/volumefraction.cpp
leying-w/Atif
7d4c4e0cc8fa159912e2f634056608023257f986
[ "MIT" ]
null
null
null
Atif/program/src/volumefraction.cpp
leying-w/Atif
7d4c4e0cc8fa159912e2f634056608023257f986
[ "MIT" ]
4
2021-01-16T08:16:57.000Z
2022-03-24T05:18:51.000Z
//***********solve the possion equation****************// #include "clibrary.h" #include "volumefraction.h" #include "simpsonintegration.h" #include "constantnum.h" extern double dr; extern short nspecies; extern int LLIM; //the minimum lower limit of intergral extern int ngrid; //the number of grids extern int ngrid_m; //the number of grids: the middle between two surfaces void VolumeFraction(double eta_t,float* D,double* etar,double** rho) { short hspecies; double eta0; double* D3; double* eta; hspecies = nspecies - 1; eta = new double[hspecies](); D3 = new double[nspecies](); for(short i=0; i<nspecies; ++i) { D3[i] = D[i]*D[i]*D[i]*Pi/6.0; } for(int k=LLIM; k<=ngrid_m; ++k) { for(short i=0; i<hspecies; ++i) { eta[i] = rho[i][k]*D3[i]; } eta0 = 0; for(short i=0; i<hspecies; ++i) { eta0 += eta[i]; } if(eta0 > eta_t) { for(short i=0; i<hspecies; ++i) { if(eta[i] > etar[i]) { rho[i][k] = rho[i][k]*etar[i]/eta[i]; rho[i][ngrid-k] = rho[i][k]; } } } eta0= 0; for(short i=0; i<hspecies; ++i) { eta0 += rho[i][k]*D3[i]; } rho[hspecies][k] = (eta_t - eta0)/D3[hspecies]; rho[hspecies][ngrid-k] = rho[hspecies][k]; if(rho[hspecies][k] < 0) { std::cerr<<"Error in VolumeFraction.cpp: solvent concentration is negative"<<std::endl; exit(0); } } delete [] eta; delete [] D3; } void VolumeFraction(int i,int* LLI,int* ULI,float* D,double** rho,double* eta) { //LLI: the lower limit of intergral: LLI[i]=round(D[i]*0.5/dr) //ULI: the upper limit of intergral: ULI[i]=round((size-D[i]*0.5)/dr) double* N3I; double R,rin,rip,D2,temp; int kin,kip,hspecies; hspecies = nspecies - 1; N3I = new double[hspecies](); R = i*dr; for(short j=0; j<hspecies; ++j) { rin = R - 0.5*D[j]; rip = R + 0.5*D[j]; kin = round(rin/dr); kip = round(rip/dr); D2 = D[j]*D[j]*0.25; if(kin < LLI[j]) kin = LLI[j]; if(kip > ULI[j]) kip = ULI[j]; temp =SimpsonIntegration(rho[j],0,ngrid,kin,kip,D2,i); N3I[j]=Pi*temp; eta[j] = N3I[j]; } delete [] N3I; } void VolumeFractionDFT(double eta_t,float* D,int* LLI,int* ULI,double* etar,double** rho) { short hspecies; double eta0; double* eta; hspecies = nspecies - 1; eta = new double[hspecies](); for(int k=LLIM; k<=ngrid_m; ++k) { VolumeFraction(k,LLI,ULI,D,rho,eta); eta0 = 0; for(short i=0; i<hspecies; ++i) { eta0 += eta[i]; } if(eta0 > eta_t) { for(short i=0; i<hspecies; ++i) { if(eta[i] > etar[i]) { rho[i][k] = rho[i][k]*etar[i]/eta[i]; rho[i][ngrid-k] = rho[i][k]; } } } } delete [] eta; }
23.047945
99
0.453195
jiangj-physchem
c48b85bae19a358d7910403bc2e1c2f37226976a
12,349
cpp
C++
Code/main.cpp
Avramis/ClassificationByNumbers
6c36aa4998173e3f78c4f27b27cfd66350b9ae07
[ "MIT" ]
1
2019-03-27T15:16:06.000Z
2019-03-27T15:16:06.000Z
Code/main.cpp
Avramis/ClassificationByNumbers
6c36aa4998173e3f78c4f27b27cfd66350b9ae07
[ "MIT" ]
null
null
null
Code/main.cpp
Avramis/ClassificationByNumbers
6c36aa4998173e3f78c4f27b27cfd66350b9ae07
[ "MIT" ]
null
null
null
// // main.cpp // ClassificationTool // // Created by Avraam Tapinos // Copyright © 2018 Avraam Tapinos. All rights reserved. // #include <iostream> #include <sys/types.h> #include <sys/stat.h> #include "ClassificationTree.hpp" #include "ClassificationInitiation.hpp" #include "InstructionsClass.hpp" #include "Print_Time.hpp" #include "TestFileExistance.hpp" int main(int argc, const char * argv[]) { ClassificationTree CVPT; Print_Time PT; TestFileExistance TE; bool vptprov = false, faprov = false, rprov = false , outprov = false, pKNN = true, pRange = false, vpts = false, inddirprov = false, preporc = true, accu = false, znorm = false, ptd = false, repall = true, isen = false; std::string fadir = "", vptdir = "", readsdir = "", outdir = "", rep = "Tetrahedron", tra = "DWT", indexdir = "", sapp = "DTW"; int kmer = 64, clvl = 4, knn = 5; double range = 0.15; clock_t start, stop; size_t sidx = readsdir.find_last_of("."); std::cout << readsdir.substr(0,sidx+1) << "\n"; std::cout << "#############################################################\n"; std::cout << "# #\n"; std::cout << "# CBN #\n"; std::cout << "# ClassificationByNumbers #\n"; std::cout << "# #\n"; std::cout << "#############################################################\n"; int civ = (argc - 1) % 2; if (civ || argc - 1 == 0) { for (int i = 1; i < argc; i++) { if ((std::string) (argv[i]) == "-h" || (std::string) (argv[i]) == "-help" || (std::string) (argv[i]) == "-H" || (std::string) (argv[i]) == "-Help" || (std::string) (argv[i]) == "-HELP") { InstructionsClass instructions(1); return 1; } } InstructionsClass instreuctions(0); return 1; } else { for (int i = 1; i < argc; i += 2) { if ((std::string) (argv[i]) == "-h" || (std::string) (argv[i]) == "-help" || (std::string) (argv[i]) == "-H" || (std::string) (argv[i]) == "-Help" || (std::string) (argv[i]) == "-HELP") { InstructionsClass instructions(0); } else if ((std::string) (argv[i]) == "-o") { outdir = (std::string) (argv[i + 1]); outprov = true; } else if ((std::string) (argv[i]) == "-r") { readsdir = (std::string) (argv[i + 1]); rprov = TE.exists_test(readsdir); if (rprov == false){ std::cout << "> No such file or directory exist for the provided fastq file\n"; InstructionsClass instructions(0); return 1; } } else if ((std::string) (argv[i]) == "-fa"){ fadir = (std::string) (argv[i + 1]); faprov = TE.exists_test(fadir); if(faprov == false){ std::cout << "> No such file or directory exist for the provided fasta file\n"; InstructionsClass instructions(0); return 1; } } else if ((std::string) (argv[i]) == "-vpt_load"){ vptdir = (std::string) (argv[i + 1]); size_t didx = vptdir.find(".vptstruct"); if(!(didx != std::string::npos)){ vptprov = TE.exists_test(vptdir+".vptstruct"); if(vptprov == true){ vptdir+=".vptstruct"; } else{ std::cout << "> No such file or directory exist for the provided VPTree index file\n"; InstructionsClass instructions(1); return 1; } } else{ vptprov = TE.exists_test(vptdir); if(vptprov == false){ std::cout << "> No such file or directory exist for the provided VPTree index file\n"; InstructionsClass instructions(1); return 1; } } } else if ((std::string) (argv[i]) == "-kmer") { kmer = std::stoi(argv[i + 1]); } else if ((std::string) (argv[i]) == "-rep") { rep = (std::string) (argv[i + 1]); } else if ((std::string) (argv[i]) == "-tra") { tra = (std::string) (argv[i + 1]); } else if ((std::string) (argv[i]) == "-clvl") { clvl = std::stoi(argv[i + 1]); } else if ((std::string) (argv[i]) == "-knn") { knn = std::stoi(argv[i + 1]); pKNN = true; pRange = false; } else if ((std::string) (argv[i]) == "-ra") { range = std::stod(argv[i + 1]); pKNN = false; pRange = true; } else if ((std::string) (argv[i]) == "-s") { if((std::string) (argv[i + 1]) == "y" || (std::string) (argv[i + 1]) == "Y" || (std::string) (argv[i + 1]) == "Yes"){ vpts = true; } else{ vpts = false; } } else if ((std::string) (argv[i]) == "-vpt_save") { indexdir = (std::string) (argv[i + 1]); inddirprov = true; vpts = true; } else if((std::string) (argv[i]) == "-sen"){ if((std::string) (argv[i + 1]) == "y" || (std::string) (argv[i + 1]) == "Y" || (std::string) (argv[i + 1]) == "Yes"){ isen = true; } else{ isen = false; } } else if ((std::string) (argv[i]) == "-evs") { if((std::string) (argv[i + 1]) == "s" ||(std::string) (argv[i + 1]) == "S" || (std::string) (argv[i + 1]) == "Slow" || (std::string) (argv[i + 1]) == "SLOW" || (std::string) (argv[i + 1]) == "slow"){ sapp = "SW"; } else if((std::string) (argv[i + 1]) == "m" ||(std::string) (argv[i + 1]) == "M" || (std::string) (argv[i + 1]) == "Medium" || (std::string) (argv[i + 1]) == "MEDIUM" || (std::string) (argv[i + 1]) == "medium"){ sapp = "DTW"; } else{ sapp = "ED"; } } else if ((std::string) (argv[i]) == "-proc") { if((std::string) (argv[i + 1]) == "y" || (std::string) (argv[i + 1]) == "Y" || (std::string) (argv[i + 1]) == "Yes"){ preporc = true; } else{ preporc = false; } } else if ((std::string) (argv[i]) == "-accu") { if((std::string) (argv[i + 1]) == "y" || (std::string) (argv[i + 1]) == "Y" || (std::string) (argv[i + 1]) == "Yes"){ accu = true; } else{ accu = false; } } else if ((std::string) (argv[i]) == "-znorm") { if((std::string) (argv[i + 1]) == "y" || (std::string) (argv[i + 1]) == "Y" || (std::string) (argv[i + 1]) == "Yes"){ znorm = true; } else{ znorm = false; } } else if ((std::string) (argv[i]) == "-ptd") { if((std::string) (argv[i + 1]) == "y" || (std::string) (argv[i + 1]) == "Y" || (std::string) (argv[i + 1]) == "Yes"){ ptd = true; } else{ ptd = false; } } else if ((std::string) (argv[i]) == "-repall") { if((std::string) (argv[i + 1]) == "y" || (std::string) (argv[i + 1]) == "Y" || (std::string) (argv[i + 1]) == "Yes"){ repall = true; } else{ repall = false; } } } } if( vptprov == false && faprov == false){ std::cout << "> No index file or fasta file reference file has been provided.\n"; std::cout << "> Process is termianted.\n"; InstructionsClass instructions(1); } if(rprov == false){ std::cout << "> No reads file has been provided.\n"; std::cout << "> Process is termianted.\n"; InstructionsClass instructions(1); } if(outprov == false){ size_t sidx = readsdir.find_last_of("."); outdir = readsdir.substr(0,sidx); if(pKNN == true){ outdir += "> KNN_Classification.txt"; } else{ outdir += "> Range_Search_Classification.txt"; } std::cout << "> No output directory has been provided for storing the classification results.\n"; std::cout << "> Results will be stored in:\n"; std::cout << "> " << outdir << "\n"; } if (inddirprov == true){ vpts = true; }; if(vpts == true){ if(vptprov == true){ std::cout << "> Indexing tree already exist in loaction:\n"; std::cout << "> " << vptdir << "n"; std::cout << "> Tree will not be saved.\n"; vpts = false; } else{ if(inddirprov == false){ size_t sidx = fadir.find_last_of("."); indexdir = fadir.substr(0,sidx); std::cout << "> No directory has been provided for storing the indexing tree.\n"; std::cout << "> Indexing tree will be storied in:\n"; std::cout << "> " << indexdir << "\n"; } } } if(vptprov == true){ std::cout << "> Initiate loading indexing structure.\n"; start = clock(); CVPT.loadTree(vptdir); stop = clock(); std::cout << "> Loading indexing structure completed.\n"; std::cout << "> Loading tree elapsed time: " << PT.returnTimestr(start, stop) << "\n"; } else{ start = clock(); std::cout << "> Initiate building indexing structure.\n"; start = clock(); CVPT.BuildTree(fadir, kmer, rep, tra, clvl, accu, znorm); stop = clock(); std::cout << "> Building indexing structure completed.\n"; std::cout << "> Building tree elapsed time: " << PT.returnTimestr(start, stop) << "\n"; } if(ptd == true){ std::cout << "> Index tree contains " << CVPT.TreeNodesNum() << " nodes\n"; CVPT.TreeprintAllTau(); } if(pKNN == true){ std::cout << "> Initiate KNN search.\n"; start = clock(); ClassificationInitiation CIKNN(&CVPT, readsdir, outdir, sapp, knn, preporc, repall, isen); stop = clock(); std::cout << "> KNN search completed.\n"; std::cout << "> KNN search elapsed time: " << PT.returnTimestr(start, stop) << "\n"; } else if(pRange == true){ std::cout << "> Initiate range search.\n"; start = clock(); ClassificationInitiation CIRange(&CVPT, readsdir, outdir ,sapp, range, preporc, repall); stop = clock(); std::cout << "> Range search completed.\n"; std::cout << "> Range search elapsed time: " << PT.returnTimestr(start, stop) << "\n"; } if(vpts == true){ std::cout << "> Initiate saving indexing structure.\n"; start = clock(); CVPT.saveTree(indexdir); stop = clock(); std::cout << "> Saving indexing structure completed.\n"; std::cout << "> Saving indexing structure elapsed time: " << PT.returnTimestr(start, stop) << "\n"; } std::cout << "#############################################################\n\n"; return 0; }
40.224756
226
0.412746
Avramis
c49028d1192c300940990602f81a94e14d93b315
1,720
hh
C++
inc/EHttpProxyResponse.hh
developkits/CxxMina
705734fccc5ef87c7faa385b77cd1e67c46c5c75
[ "Apache-2.0" ]
7
2016-08-25T14:22:36.000Z
2020-05-25T17:27:51.000Z
inc/EHttpProxyResponse.hh
developkits/CxxMina
705734fccc5ef87c7faa385b77cd1e67c46c5c75
[ "Apache-2.0" ]
1
2018-07-11T12:37:55.000Z
2018-07-12T00:05:33.000Z
inc/EHttpProxyResponse.hh
developkits/CxxMina
705734fccc5ef87c7faa385b77cd1e67c46c5c75
[ "Apache-2.0" ]
2
2017-06-09T01:22:36.000Z
2021-09-29T16:27:58.000Z
/* * EHttpProxyResponse.hh * * Created on: 2016-6-16 * Author: cxxjava@lotuseed.com */ #ifndef EHTTPPROXYRESPONSE_HH_ #define EHTTPPROXYRESPONSE_HH_ #include "Efc.hh" namespace efc { namespace eio { /** * HttpProxyResponse.java - Wrapper class for HTTP requests. * * @author <a href="http://mina.apache.org">Apache MINA Project</a> * @since MINA 2.0.0-M3 */ class EHttpProxyResponse: public EObject { public: /** * @return the HTTP response protocol version. */ const char* getHttpVersion(); /** * @return the HTTP response status code. */ int getStatusCode(); /** * @return the HTTP response status line. */ const char* getStatusLine(); /** * @return the HTTP response body. */ const char* getBody(); /** * Sets the HTTP response body. * * @param body The HTTP Body */ void setBody(const char* body); /** * @return the HTTP response headers. */ EMap<EString*, EList<EString*>*>* getHeaders(); /*protected:*/ /** * Constructor of an HTTP proxy response. * * @param httpVersion the protocol version * @param statusLine the response status line * @param headers the response headers */ EHttpProxyResponse(const char* httpVersion, const char* statusLine, EMap<EString*, EList<EString*>*>* headers); private: /** * The HTTP response protocol version. */ EString httpVersion; /** * The HTTP response status line. */ EString statusLine; /** * The HTTP response status code; */ int statusCode; /** * The HTTP response headers. */ EHashMap<EString*, EList<EString*>* > headers; /** * The HTTP response body. */ EString body; }; } /* namespace eio */ } /* namespace efc */ #endif /* EHTTPPROXYRESPONSE_HH_ */
17.55102
68
0.656977
developkits
c4929eabdecbf5c91d24efca9ac82ed4aa17b111
1,529
cpp
C++
src/core/notebook/bundlenotebook.cpp
lizhyumzi/vnote
7c4d89b0272cf817902272e8733d56c2cddb797a
[ "MIT" ]
null
null
null
src/core/notebook/bundlenotebook.cpp
lizhyumzi/vnote
7c4d89b0272cf817902272e8733d56c2cddb797a
[ "MIT" ]
null
null
null
src/core/notebook/bundlenotebook.cpp
lizhyumzi/vnote
7c4d89b0272cf817902272e8733d56c2cddb797a
[ "MIT" ]
null
null
null
#include "bundlenotebook.h" #include <QDebug> #include <notebookconfigmgr/bundlenotebookconfigmgr.h> #include <notebookconfigmgr/notebookconfig.h> #include <utils/fileutils.h> using namespace vnotex; BundleNotebook::BundleNotebook(const NotebookParameters &p_paras, QObject *p_parent) : Notebook(p_paras, p_parent) { auto configMgr = getBundleNotebookConfigMgr(); auto config = configMgr->readNotebookConfig(); m_nextNodeId = config->m_nextNodeId; } BundleNotebookConfigMgr *BundleNotebook::getBundleNotebookConfigMgr() const { return dynamic_cast<BundleNotebookConfigMgr *>(getConfigMgr().data()); } ID BundleNotebook::getNextNodeId() const { return m_nextNodeId; } ID BundleNotebook::getAndUpdateNextNodeId() { auto id = m_nextNodeId++; getBundleNotebookConfigMgr()->writeNotebookConfig(); return id; } void BundleNotebook::updateNotebookConfig() { getBundleNotebookConfigMgr()->writeNotebookConfig(); } void BundleNotebook::removeNotebookConfig() { getBundleNotebookConfigMgr()->removeNotebookConfig(); } void BundleNotebook::remove() { // Remove all nodes. removeNode(getRootNode()); // Remove notebook config. removeNotebookConfig(); // Remove notebook root folder if it is empty. if (!FileUtils::removeDirIfEmpty(getRootFolderAbsolutePath())) { qInfo() << QString("root folder of notebook (%1) is not empty and needs manual clean up") .arg(getRootFolderAbsolutePath()); } }
25.065574
97
0.717462
lizhyumzi
c496dbaf648e776db621b9e232a872c94c9bbb9a
1,759
cpp
C++
Actor/Characters/Player/GBox/State/States/State_GBox_PortalFalling.cpp
Bornsoul/Revenger_JoyContinue
599716970ca87a493bf3a959b36de0b330b318f1
[ "MIT" ]
null
null
null
Actor/Characters/Player/GBox/State/States/State_GBox_PortalFalling.cpp
Bornsoul/Revenger_JoyContinue
599716970ca87a493bf3a959b36de0b330b318f1
[ "MIT" ]
null
null
null
Actor/Characters/Player/GBox/State/States/State_GBox_PortalFalling.cpp
Bornsoul/Revenger_JoyContinue
599716970ca87a493bf3a959b36de0b330b318f1
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "State_GBox_PortalFalling.h" #include "Components/ArrowComponent.h" #include "Kismet/KismetMathLibrary.h" void UState_GBox_PortalFalling::Init(class UStateMng_GC* pMng) { Super::Init(pMng); } void UState_GBox_PortalFalling::Enter() { Super::Enter(); if (m_pStartPortal == nullptr) { ULOG(TEXT("StartPortal is Nullptr")); return; } m_vStartLoc = m_pStartPortal->GetComponentLocation(); GetRootChar()->SetActorRotation(FRotator(0.0f, m_pStartPortal->GetComponentRotation().Yaw, 0.0f)); GetRootChar()->SetActorLocation(m_vStartLoc); GetRootChar()->GetAnimationMng()->PlayAnimationSequnceBase(TEXT("Portal_Falling"), TEXT("DefaultSlot"), 0.0f, 0.2f, 1.0f); m_bMotionEnd = false; } void UState_GBox_PortalFalling::Exit() { Super::Exit(); GetRootChar()->GetSpringArm()->CameraLagSpeed = 10.0f; //GetRootChar()->GetSlowGage()->SetInit(GetRootChar(), GetRootChar()->m_vSlowGagePos); m_pStartPortal = nullptr; GetRootChar()->SetVisibleHUD(true); GetRootChar()->GetAnimationMng()->StopAnimation_SequnceBaseSlot(TEXT("DefaultSlot"), 0.2f); if (GetRootChar()->GetStick() != nullptr) { GetRootChar()->GetStick()->Control_Portal(false); } } void UState_GBox_PortalFalling::Update(float fDeltaTime) { Super::Update(fDeltaTime); if (m_pStartPortal == nullptr) return; if (m_bMotionEnd == true) { ChangeState(static_cast<int32>(E_State_GBox::E_Idle)); return; } } void UState_GBox_PortalFalling::StateMessage(FString StateMessage) { Super::StateMessage(StateMessage); if (StateMessage == "MotionEnd") { m_bMotionEnd = true; } } void UState_GBox_PortalFalling::SetPortal(UArrowComponent * pPortal) { m_pStartPortal = pPortal; }
23.453333
123
0.744741
Bornsoul
7bca72dc0998bc5a01d85613d7788660c4674b5a
2,835
cpp
C++
src/core/contract/Signable.cpp
nopdotcom/opentxs
140428ba8f1bd4c09654ebf0a1c1725f396efa8b
[ "MIT" ]
null
null
null
src/core/contract/Signable.cpp
nopdotcom/opentxs
140428ba8f1bd4c09654ebf0a1c1725f396efa8b
[ "MIT" ]
null
null
null
src/core/contract/Signable.cpp
nopdotcom/opentxs
140428ba8f1bd4c09654ebf0a1c1725f396efa8b
[ "MIT" ]
null
null
null
// Copyright (c) 2018 The Open-Transactions developers // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "stdafx.hpp" #include "opentxs/core/contract/Signable.hpp" #include "opentxs/core/Data.hpp" #include "opentxs/core/Identifier.hpp" #include "opentxs/core/Log.hpp" namespace opentxs { Signable::Signable(const ConstNym& nym) : alias_() , id_(Identifier::Factory()) , nym_(nym) , signatures_() , version_() , conditions_() , lock_() { } Signable::Signable(const ConstNym& nym, const std::uint32_t version) : alias_() , id_(Identifier::Factory()) , nym_(nym) , signatures_() , version_(version) , conditions_() , lock_() { } Signable::Signable( const ConstNym& nym, const std::uint32_t version, const std::string& conditions) : alias_() , id_(Identifier::Factory()) , nym_(nym) , signatures_() , version_(version) , conditions_(conditions) , lock_() { } std::string Signable::Alias() const { Lock lock(lock_); return alias_; } bool Signable::CalculateID(const Lock& lock) { id_ = Identifier::Factory(GetID(lock)); return true; } bool Signable::CheckID(const Lock& lock) const { return (GetID(lock) == id_); } OTIdentifier Signable::id(const Lock& lock) const { OT_ASSERT(verify_write_lock(lock)); return id_; } OTIdentifier Signable::ID() const { Lock lock(lock_); return id(lock); } ConstNym Signable::Nym() const { return nym_; } void Signable::SetAlias(const std::string& alias) { Lock lock(lock_); alias_ = alias; } const std::string& Signable::Terms() const { Lock lock(lock_); return conditions_; } bool Signable::update_signature(const Lock& lock) { OT_ASSERT(verify_write_lock(lock)); if (!nym_) { otErr << __FUNCTION__ << ": Missing nym." << std::endl; return false; } return true; } bool Signable::Validate() const { Lock lock(lock_); return validate(lock); } bool Signable::verify_write_lock(const Lock& lock) const { if (lock.mutex() != &lock_) { otErr << __FUNCTION__ << ": Incorrect mutex." << std::endl; return false; } if (false == lock.owns_lock()) { otErr << __FUNCTION__ << ": Lock not owned." << std::endl; return false; } return true; } bool Signable::verify_signature(const Lock& lock, const proto::Signature&) const { OT_ASSERT(verify_write_lock(lock)); if (!nym_) { otErr << __FUNCTION__ << ": Missing nym." << std::endl; return false; } return true; } const std::uint32_t& Signable::Version() const { return version_; } } // namespace opentxs
18.9
80
0.635626
nopdotcom
7bceb4b4391f4d47a51fa2ffaa23871c2b0e0154
1,251
cpp
C++
code/test2/3.cpp
Bc-Gg/Algorithms
0c35fd4e002ff4b0ad6ebb243df3df278e366595
[ "MIT" ]
8
2022-03-13T10:25:33.000Z
2022-03-30T08:26:00.000Z
code/test2/3.cpp
Bc-Gg/Algorithms
0c35fd4e002ff4b0ad6ebb243df3df278e366595
[ "MIT" ]
null
null
null
code/test2/3.cpp
Bc-Gg/Algorithms
0c35fd4e002ff4b0ad6ebb243df3df278e366595
[ "MIT" ]
2
2022-03-20T12:09:52.000Z
2022-03-21T03:43:01.000Z
#include<iostream> #include<vector> #include<string> using namespace std; vector<string> vec; void reload(string str){ for(int i = 0 ; i < str.size(); i++){ if(!isdigit(str[i])) vec.push_back(str.substr(i,1)); else{ int k = i; while(k < str.size() && isdigit(str[k])){ k++; } vec.push_back(str.substr(i,k-i)); i = k - 1; } } } vector<int> conquer(int le,int ri){ if(le == ri){ vector<int> ret; ret.push_back(stoi(vec[le])); return ret; } vector<int> ret; for(auto i = le + 1; i < ri; i+=2){ auto ans_le = conquer(le,i - 1); auto ans_ri = conquer(i + 1, ri); // i is '+' || '-' || '*' for(auto l :ans_le){ for (auto r :ans_ri){ if(vec[i] == "+") ret.push_back(l+r); else if (vec[i] == "-") ret.push_back(l-r); else if (vec[i] == "*") ret.push_back(l*r); } } } return ret; } int main(){ string str; cin >> str; reload(str); auto ret = conquer(0,vec.size()-1); sort(ret.begin(),ret.end()); for(auto re : ret){ cout << re << endl; } return 0; }
23.603774
60
0.446843
Bc-Gg
7bd1cfc86febc7e5396c15b3672edf01a9161a05
719
hpp
C++
compilax/project_env.hpp
deqyra/CompilaX
a7ce9effdaf607bb1632ca39cb30b8c7ace83dbf
[ "MIT" ]
null
null
null
compilax/project_env.hpp
deqyra/CompilaX
a7ce9effdaf607bb1632ca39cb30b8c7ace83dbf
[ "MIT" ]
null
null
null
compilax/project_env.hpp
deqyra/CompilaX
a7ce9effdaf607bb1632ca39cb30b8c7ace83dbf
[ "MIT" ]
null
null
null
/* // \\ // \\ // \\ //WARNING\\ // \\ ============= DO NOT edit project_env.hpp, or your changes will be OVERWRITTEN at the next run of CMake. Instead, edit config/project_env.config.hpp. */ #ifndef RENDERBOI__PROJECT_ENV_HPP #define RENDERBOI__PROJECT_ENV_HPP #define PROJECT_NAME "CompilaX" #define PROJECT_VERSION "1.0" #define COPYRIGHT_NOTICE "2021 © François Brachais <deqyra@gmail.com>" #define MIT_LICENSE_NOTICE "This software and its source code are subject to the "\ "MIT license.\nSee file LICENSE.md at https://github.com/deqyra/CompilaX. " #define GL_CONTEXT_VERSION_MAJOR #define GL_CONTEXT_VERSION_MINOR #endif//RENDERBOI__PROJECT_ENV_HPP
28.76
83
0.69541
deqyra
7bda53c935b0e4f4ecfc7bd36fb9a8023239cad7
19,914
hpp
C++
src/common/kmer_iterators.hpp
tcpan/bliss
0062fe91fdeef66fce4d1e897c15318241130277
[ "Apache-2.0" ]
16
2016-06-07T22:12:02.000Z
2021-12-15T12:40:52.000Z
src/common/kmer_iterators.hpp
tcpan/bliss
0062fe91fdeef66fce4d1e897c15318241130277
[ "Apache-2.0" ]
1
2017-11-13T20:59:33.000Z
2018-12-14T16:40:01.000Z
src/common/kmer_iterators.hpp
tcpan/bliss
0062fe91fdeef66fce4d1e897c15318241130277
[ "Apache-2.0" ]
7
2016-08-19T21:31:41.000Z
2021-12-19T14:58:45.000Z
/* * Copyright 2015 Georgia Institute of Technology * * 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. */ /** * @file kmer_iterators.hpp * @ingroup common * @author Patrick Flick * @author Tony Pan <tpan7@gatech.edu> * @brief iterator to generate kmers from a sequence of characters in alphabet (DNA, etc) * @details include support for Kmer and reverse Kmer (for reverse complement) * * These classes DO NOT perform translation from ASCII to selected alphabet. * To handle that, use "bliss::utils::ASCII2<ALPHABET>" functor with a transform iterator * e.g. bliss::iterator::transform_iterator, or boost's transform iterator * then set the transform iterator as base iterator type for kmerGenerationIterators below. */ #ifndef BLISS_COMMON_KMER_ITERATORS_H #define BLISS_COMMON_KMER_ITERATORS_H // C std lib includes: #include <cstdlib> // C++ STL includes: #include <iterator> #include <type_traits> // own includes #include "common/base_types.hpp" #include "common/padding.hpp" #include "common/kmer.hpp" #include "iterators/sliding_window_iterator.hpp" // TODO: Need convenience functions to make start and end iterators (the true/false flags are not easy to remember.) // TODO: Need convenience typedef to allow for reverse complement generation. namespace bliss { namespace common { /** * @brief The sliding window operator for k-mer generation from character data. * * @tparam BaseIterator Type of the underlying base iterator, which returns * characters. * @tparam Kmer The k-mer type, must be of type bliss::Kmer */ template <class BaseIterator, class Kmer> class KmerSlidingWindow {}; template <typename BaseIterator, unsigned int KMER_SIZE, typename ALPHABET, typename word_type> class KmerSlidingWindow<BaseIterator, bliss::common::Kmer<KMER_SIZE, ALPHABET, word_type> > { public: /// The Kmer type (same as the `value_type` of this iterator) typedef bliss::common::Kmer<KMER_SIZE, ALPHABET, word_type> kmer_type; typedef BaseIterator base_iterator_type; /// The value_type of the underlying iterator typedef typename std::iterator_traits<BaseIterator>::value_type base_value_type; /** * @brief Initializes the sliding window. * * @param it[in|out] The current base iterator position. This will be set to * the last read position. */ inline void init(BaseIterator& it) { kmer.fillFromChars(it, true); } /** * @brief Slides the window by one character taken from the given iterator. * * This will read the current character of the iterator and then advance the * iterator by one. * * @param it[in|out] The underlying iterator position, this will be read * and then advanced. */ inline void next(BaseIterator& it) { kmer.nextFromChar(*it); ++it; } /** * @brief Returns the value of the current sliding window, i.e., the current * k-mer value. * * @return The current k-mer value. */ inline kmer_type getValue() { // return a copy of the current kmer return this->kmer; } private: /// The kmer buffer (i.e. the window of the sliding window) kmer_type kmer; }; /** * @brief The sliding window operator for reverse k-mer generation from character data. * @note to create reverse complement, use a transform iterator to change the char to complement * * @tparam BaseIterator Type of the underlying base iterator, which returns * characters. * @tparam Kmer The k-mer type, must be of type bliss::Kmer */ template <class BaseIterator, class Kmer> class ReverseKmerSlidingWindow {}; template <typename BaseIterator, unsigned int KMER_SIZE, typename ALPHABET, typename word_type> class ReverseKmerSlidingWindow<BaseIterator, bliss::common::Kmer<KMER_SIZE, ALPHABET, word_type> > { public: /// The Kmer type (same as the `value_type` of this iterator) typedef bliss::common::Kmer<KMER_SIZE, ALPHABET, word_type> kmer_type; typedef BaseIterator base_iterator_type; /// The value_type of the underlying iterator typedef typename std::iterator_traits<BaseIterator>::value_type base_value_type; /** * @brief Initializes the sliding window. * * @param it[in|out] The current base iterator position. This will be set to * the last read position. */ inline void init(BaseIterator& it) { kmer.fillReverseFromChars(it, true); } /** * @brief Slides the window by one character taken from the given iterator. * * This will read the current character of the iterator and then advance the * iterator by one. * * @param it[in|out] The underlying iterator position, this will be read * and then advanced. */ inline void next(BaseIterator& it) { kmer.nextReverseFromChar(*it); ++it; } /** * @brief Returns the value of the current sliding window, i.e., the current * k-mer value. * * @return The current k-mer value. */ inline kmer_type getValue() { // return a copy of the current kmer return this->kmer; } private: /// The kmer buffer (i.e. the window of the sliding window) kmer_type kmer; }; /** * @brief Iterator that generates k-mers from character data. * * @tparam BaseIterator The underlying iterator of characters. E.g. a * std::string::iterator. Any iterator yielding * `char` works. * @tparam Kmer The type of the Kmer, this has to be of type * bliss::Kmer. */ template <class SlidingWindow> class KmerGenerationIteratorBase : public iterator::sliding_window_iterator<typename SlidingWindow::base_iterator_type, SlidingWindow > { protected: typedef typename SlidingWindow::base_iterator_type BaseIterator; /// The type of the base class typedef iterator::sliding_window_iterator<BaseIterator, SlidingWindow > base_class_t; /// The difference_type of character offsets typedef typename std::iterator_traits<base_class_t>::difference_type diff_type; /// The type of the sliding window. typedef SlidingWindow functor_t; public: /// Default constructor. KmerGenerationIteratorBase() : base_class_t() {} /** * @brief Constructor for the kmer generation iterator using the underlying * iterator `baseBegin` as starting point. * * @param baseBegin An iterator pointing to the first character of the * sequence to be used for generating k-mers. */ KmerGenerationIteratorBase(const BaseIterator& baseBegin) : base_class_t(baseBegin, true) {} /** * @brief Constructor for the kmer generation iterator using the underlying * iterator `baseBegin` as starting point. * * @param baseBegin An iterator pointing to the first character of the * sequence to be used for generating k-mers. * @param initialze_window Whether to read the first `KMER_SIZE` characters * to initialize the sliding window. This will * have to be set to `false` for creating * `end` style iterators which would otherwise * read past the valid range. */ KmerGenerationIteratorBase(const BaseIterator& baseBegin, bool initialize_window) : base_class_t(baseBegin, initialize_window) {} protected: /***************************** * non public constructors * *****************************/ // handleing of the `window` object instances is strictly hidden /** * @brief Constructor for the kmer generation iterator using the underlying * iterator `baseBegin` as starting point. * * @param baseBegin An iterator pointing to the first character of the * sequence to be used for generating k-mers. * @param window The sliding window object used by the iterator. */ KmerGenerationIteratorBase(const BaseIterator& baseBegin, const functor_t& window) : base_class_t(baseBegin, window, true) {} /** * @brief Constructor for the kmer generation iterator using the underlying * iterator `baseBegin` as starting point. * * @param baseBegin An iterator pointing to the first character of the * sequence to be used for generating k-mers. * @param window The sliding window object used by the iterator. * @param initialze_window Whether to read the first `KMER_SIZE` characters * to initialize the sliding window. This will * have to be set to `false` for creating * `end` style iterators which would otherwise * read past the valid range. */ KmerGenerationIteratorBase(const BaseIterator& baseBegin, const functor_t& window, bool initialize_window) : base_class_t(baseBegin, window, initialize_window) {} }; /// normal KmerGenerationIterator for generating kmers from a sequence of alphabet characters template <class BaseIterator, class Kmer> using KmerGenerationIterator = KmerGenerationIteratorBase<KmerSlidingWindow<BaseIterator, Kmer > >; /// reverse KmerGenerationIterator for generating kmers from a sequence of alphabet characters. can be used for reverse complements. template <class BaseIterator, class Kmer> using ReverseKmerGenerationIterator = KmerGenerationIteratorBase<ReverseKmerSlidingWindow<BaseIterator, Kmer > >; /** * @brief The sliding window operator for k-mer generation from packed data. * * @tparam BaseIterator Type of the underlying base iterator, which returns * elements of packed data. * @tparam Kmer The k-mer type, must be of type bliss::Kmer */ template <class BaseIterator, class Kmer> class PackedKmerSlidingWindow {}; template <typename BaseIterator, unsigned int KMER_SIZE, typename ALPHABET, typename word_type> class PackedKmerSlidingWindow<BaseIterator, bliss::common::Kmer<KMER_SIZE, ALPHABET, word_type> > { public: /// The Kmer type (same as the `value_type` of this iterator) typedef bliss::common::Kmer<KMER_SIZE, ALPHABET, word_type> kmer_type; /// The value_type of the underlying iterator typedef typename std::iterator_traits<BaseIterator>::value_type base_value_type; /// The padding traits of the underlying stream typedef PackingTraits<base_value_type, bliss::common::AlphabetTraits<ALPHABET>::getBitsPerChar()> padtraits; /** * @brief Initializes the sliding window. * * @tparam offset_t The offset type. * @param it[in|out] The current base iterator, this will be set * to the last read position. * @param offset[in|out] The current bit/character offset in the current position * of the base iterator. This will be set to the * position that was read last. */ template<typename offset_t> inline void init(BaseIterator& it, offset_t& offset) { // there is no implementation yet to handle the case that the first // k-mer starts from an offset != 0: assert(offset == 0); // fill kmer from the given packed and padded stream // this leaves the iterator and the offset ON the last read position // and NOT AFTER this (i.e. NOT on the position to be read NEXT) offset = kmer.fillFromPackedStream(it, offset, true); } /** * @brief Slides the window by one character, taken from the given iterator. * * This will read the current character of the iterator and then increase * the (iterator, offset) position by one character. * * @tparam offset_t The offset type. * @param it[in|out] The current base iterator, this will be set * to the next position. * @param offset[in|out] The current bit/character offset in the current position * of the base iterator. This will be set to one * character past the character read. */ template<typename offset_t> inline void next(BaseIterator& it, offset_t& offset) { kmer.nextFromPackedStream(it, offset); } /** * @brief Returns the value of the current sliding window, i.e., the current * k-mer value. * * @return The current k-mer value. */ inline kmer_type getValue() { // return a copy of the current kmer return this->kmer; } /** * @brief Skips over `advance_by` characters in the current (iterator, * offset) position. * * @tparam offset_t Type of the offset. * @param it[in|out] The current iterator position. Will be modified to * the position after skipping `advance_by` chars. * @param offset The current offset position. Will be modified to * the position after skipping `advance_by` chars. * @param advance_by The number of characters to skip. */ template<typename offset_t> // TODO: - [ ] separate offset types // [ ] FIX: from any starting offset, not only from offset=0 // void skip(BaseIterator& it, offset_t& offset, offset_t advance_by) { // get offset for underlying iterator offset_t nWords = advance_by / padtraits::chars_per_word; // get offset for bitwise offset offset_t bit_offset = advance_by % padtraits::chars_per_word; bit_offset *= padtraits::bits_per_char; // add it to the base iterator std::advance(it, nWords); offset += bit_offset; } private: /// The kmer buffer (i.e. the window of the sliding window) kmer_type kmer; }; /** * @brief Iterator that generates k-mers from packed data. * * @tparam BaseIterator The underlying iterator, which supplies any integer * type of packed character data. * @tparam Kmer The type of the Kmer, this has to be of type * bliss::Kmer. */ template <class BaseIterator, class Kmer> class PackedKmerGenerationIterator {}; // template specialization for bliss::Kmer as kmer type // The template parameters KMER_SIZE, ALPHABET and word_type are // set to the appropriate template parameters of bliss::Kmer and do not // have to be explicitly stated when creating this class. template <typename BaseIterator, unsigned int KMER_SIZE, typename ALPHABET, typename word_type> class PackedKmerGenerationIterator<BaseIterator, bliss::common::Kmer<KMER_SIZE, ALPHABET, word_type> > : public iterator::one2many_sliding_window_iterator<BaseIterator, PackedKmerSlidingWindow<BaseIterator, bliss::common::Kmer<KMER_SIZE, ALPHABET, word_type> > > { protected: /// The type of the base class typedef iterator::one2many_sliding_window_iterator<BaseIterator, PackedKmerSlidingWindow<BaseIterator, bliss::common::Kmer<KMER_SIZE, ALPHABET, word_type> > > base_class_t; /// The difference_type of character offsets typedef typename std::iterator_traits<base_class_t>::difference_type diff_type; /// The type of the sliding window. typedef PackedKmerSlidingWindow<BaseIterator, bliss::common::Kmer<KMER_SIZE, ALPHABET, word_type> > functor_t; public: /// Default constructor PackedKmerGenerationIterator() : base_class_t() {} /** * @brief Constructor for the kmer generation iterator using the underlying * iterator `baseBegin` as starting point. * * @param baseBegin An iterator pointing to the first element of the * packed and padded sequence to be used for generating * k-mers. */ PackedKmerGenerationIterator(const BaseIterator& baseBegin) : base_class_t(baseBegin, functor_t()) {} /** * @brief Constructor for the kmer generation iterator using the underlying * iterator `baseBegin` as starting point and advancing * `char_offset` characters into the underlying sequence. * * @param baseBegin An iterator pointing to the first element of the * packed and padded sequence to be used for generating * k-mers. * @param offset A character offset, the constructed iterator is * advanced by this many positions at construction time. * This can be used to create the `end` iterator for * generating sequences. */ PackedKmerGenerationIterator(const BaseIterator& baseBegin, diff_type offset) : base_class_t(baseBegin, functor_t(), offset) {} protected: /***************************** * non public constructors * *****************************/ // handleing of the `window` object instances is strictly hidden /** * @brief Constructor for the kmer generation iterator using the underlying * iterator `baseBegin` as starting point. * * @param baseBegin An iterator pointing to the first element of the * packed and padded sequence to be used for generating * k-mers. * @param window The sliding window object used by the iterator. */ PackedKmerGenerationIterator(const BaseIterator& baseBegin, const functor_t& window) : base_class_t(baseBegin, window) {} /** * @brief Constructor for the kmer generation iterator using the underlying * iterator `baseBegin` as starting point and advancing * `char_offset` characters into the underlying sequence. * * @param baseBegin An iterator pointing to the first element of the * packed and padded sequence to be used for generating * k-mers. * @param offset A character offset, the constructed iterator is * advanced by this many positions at construction time. * This can be used to create the `end` iterator for * generating sequences. * @param window The sliding window object used by the iterator. */ PackedKmerGenerationIterator(const BaseIterator& baseBegin, const functor_t& window, diff_type offset) : base_class_t(baseBegin, window, offset) {} }; } //namespace common } // namespace bliss #endif // BLISS_COMMON_KMER_ITERATORS_H
39.828
162
0.638496
tcpan
7bdf2919746c1ef8a07bf6b606e7bef8996c222e
4,284
cpp
C++
src/texture.cpp
asp437/Garmez
eeb42cc91eeeea7893af0ce1fd8ccdf1e4af7d26
[ "MIT" ]
1
2019-10-14T09:16:49.000Z
2019-10-14T09:16:49.000Z
src/texture.cpp
asp437/Garmez
eeb42cc91eeeea7893af0ce1fd8ccdf1e4af7d26
[ "MIT" ]
null
null
null
src/texture.cpp
asp437/Garmez
eeb42cc91eeeea7893af0ce1fd8ccdf1e4af7d26
[ "MIT" ]
null
null
null
#include <texture.hpp> #include <glad/glad.h> #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> namespace RGLA { Texture::~Texture() { if (_id) { glDeleteTextures(1, &_id); } } void Texture::BindData() { RGLA_ENSURE(_data, "Texture data is null"); glGenTextures(1, &_id); UpdateData(); } void Texture::UpdateData() { // TODO: Dynamic source image format detection glBindTexture(GL_TEXTURE_2D, _id); if (_channels == 4) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _width, _height, 0, GL_RGBA, GL_UNSIGNED_BYTE, _data); } else { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, _width, _height, 0, GL_RGB, GL_UNSIGNED_BYTE, _data); } glGenerateMipmap(GL_TEXTURE_2D); } void Texture::Use(uint textureUnit) const { glActiveTexture(GL_TEXTURE0 + textureUnit); glBindTexture(GL_TEXTURE_2D, _id); } void Texture::SetFilteringMode(TextureFilter filter) { glBindTexture(GL_TEXTURE_2D, _id); switch (filter) { case TextureFilter::TF_NEAREST: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); break; case TextureFilter::TF_LINEAR: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); break; } } Pixel Texture::GetPixel(int x, int y) const { if (x < 0 || x >= _width || y < 0 || y >= _height) { throw std::runtime_error("Try to get pixel out of bounds of the texture"); } uint32* addr = (uint32*)(_data + (x + y * _width) * _channels); uint32 pixelData = *addr; switch (_channels) { case 3: pixelData = (pixelData & 0xFFFFFF) | 0xFF000000; return Pixel(pixelData); case 4: return Pixel(pixelData); } RGLA_ENSURE(false, "Unsupported channels count in GetPixel()"); } TextureFilter Texture::GetFilteringMode() const { return TextureFilter::TF_LINEAR; // TODO: } FileTexture::FileTexture(const std::string& fileName, bool flipVertical) { stbi_set_flip_vertically_on_load(flipVertical); _data = stbi_load(fileName.c_str(), &_width, &_height, &_channels, 0); if (!_data) { throw std::runtime_error("Can't load image " + fileName); } BindData(); } FileTexture::~FileTexture() { if (_data) { stbi_image_free(_data); _data = nullptr; } } InMemoryTexture::InMemoryTexture(const int width, const int height, const int channels) { RGLA_ENSURE(channels == 4, "InMemoryTexture can be only with 4 channels"); _width = width; _height = height; _channels = channels; _data = (unsigned char*) malloc(_width * _height * _channels); memset(_data, 0x00, _width * _height * _channels); BindData(); } InMemoryTexture::InMemoryTexture(const Texture& texture) { _width = texture.GetWidth(); _height = texture.GetHeight(); _channels = 4; _data = (unsigned char*) malloc(_width * _height * _channels); for (int x = 0; x < _width; x++) { for (int y = 0; y < _height; y++) { SetPixel(x, y, texture.GetPixel(x, y)); } } BindData(); } InMemoryTexture::~InMemoryTexture() { free(_data); } void InMemoryTexture::SetPixel(int x, int y, Pixel color) { if (x < 0 || x >= _width || y < 0 || y >= _height) { throw std::runtime_error("Try to set pixel out of bounds of the texture"); } uint32* addr = (uint32*)(_data + (x + y * _width) * _channels); (*addr) = color.data; } std::ostream& operator<<(std::ostream& out, const Pixel& pixel) { out << "(" << (int)pixel.components.r << "," << (int)pixel.components.g << "," << (int)pixel.components.b << "," << (int)pixel.components.a << ")"; return out; } }
33.46875
155
0.57493
asp437
7beae5cc43cbe3529528fa238c0aa6e1844d096a
1,373
cpp
C++
src/ds/heap/min.cpp
bound1ess/cs
0824e5ffbc4c1e170486c5e2e481c1a934d3dc63
[ "MIT" ]
1
2015-03-26T14:49:14.000Z
2015-03-26T14:49:14.000Z
src/ds/heap/min.cpp
bound1ess/cs
0824e5ffbc4c1e170486c5e2e481c1a934d3dc63
[ "MIT" ]
null
null
null
src/ds/heap/min.cpp
bound1ess/cs
0824e5ffbc4c1e170486c5e2e481c1a934d3dc63
[ "MIT" ]
null
null
null
#include <cstdio> #include <algorithm> #include <cassert> using namespace std; class MinHeap { private: int *heap, size; bool dirty; void restore(); public: MinHeap(int *heap, int size); ~MinHeap(); int extract(); }; int main() { int n; scanf("%d", &n); assert(n > 0); int *arr = new int[n]; for (int i = 0; i < n; ++i) { scanf("%d", arr + i); } MinHeap heap(arr, n); for (int i = 0; i < n; ++i) { printf("%d\n", heap.extract()); } delete[] arr; return 0; } MinHeap::MinHeap(int *heap, int size) { this->size = size; this->dirty = true; this->heap = new int[size]; for (int i = 0; i < size; ++i) { this->heap[i] = heap[i]; } } MinHeap::~MinHeap() { delete[] this->heap; } int MinHeap::extract() { assert(this->size > 0); this->restore(); this->dirty = true; swap(this->heap[0], this->heap[this->size - 1]); --this->size; return this->heap[this->size]; } void MinHeap::restore() { if (this->dirty) { this->dirty = false; for (int i = this->size / 2; i >= 0; --i) { int left = i * 2 + 1, right = i * 2 + 2; if (left < this->size && this->heap[i] > this->heap[left]) { swap(this->heap[i], this->heap[left]); } if (right < this->size && this->heap[i] > this->heap[right]) { swap(this->heap[i], this->heap[right]); } } } }
19.614286
68
0.525127
bound1ess
7bec1dbe1f989c7bf2d177c3d1f54a8ec8d9e2c9
26,694
cpp
C++
src/sim/rwr/advancedhts.cpp
markbb1957/FFalconSource
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
[ "BSD-2-Clause" ]
1
2021-02-19T06:06:31.000Z
2021-02-19T06:06:31.000Z
src/sim/rwr/advancedhts.cpp
markbb1957/FFalconSource
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
[ "BSD-2-Clause" ]
null
null
null
src/sim/rwr/advancedhts.cpp
markbb1957/FFalconSource
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
[ "BSD-2-Clause" ]
2
2019-08-20T13:35:13.000Z
2021-04-24T07:32:04.000Z
//**************************************************** // RV - I-Hawk // Starting HARM avionics systems upgrade 07/2008 //**************************************************** #include "stdhdr.h" #include "F4Vu.h" #include "missile.h" #include "Graphics\Include\display.h" #include "simveh.h" #include "airunit.h" #include "simdrive.h" #include "fcc.h" #include "sms.h" #include "object.h" #include "team.h" #include "entity.h" #include "simmover.h" #include "soundfx.h" #include "classtbl.h" #include "rwr.h" #include "AdvancedHTS.h" #include "aircrft.h" const float CURSOR_SIZE = 0.065f; AdvancedHarmTargetingPod::AdvancedHarmTargetingPod(int idx, SimMoverClass* self) : HarmTargetingPod (idx, self) { curMissile = NULL; curTarget = NULL; curTargetWP = prevTargetWP = NULL; curTOF = 0.0f; timer = 0; prevTOF = -1.0f; prevTargteSymbol = prevWPNum = 0; missileLaunched = false; AircraftClass *playerAC = SimDriver.GetPlayerAircraft(); SMSClass* Sms; if ( playerAC ) { Sms = playerAC->Sms; if ( Sms ) { curMissile = (MissileClass*)(Sms->GetCurrentWeapon()); } } } AdvancedHarmTargetingPod::~AdvancedHarmTargetingPod (void) { } // RV - I-Hawk - HAD display void AdvancedHarmTargetingPod::HADDisplay (VirtualDisplay* activeDisplay) { float displayX, displayY; float x2, y2; float wpX, wpY, wpZ; float cosAng, sinAng; WayPointClass *curWaypoint; GroundListElement* tmpElement; mlTrig trig; FireControlComputer* FCC = ((SimVehicleClass*)platform)->GetFCC(); // Let the base class do the basics HarmTargetingPod::HADDisplay( activeDisplay ); // Set up the trig functions of our current heading mlSinCos (&trig, platform->Yaw()); cosAng = trig.cos; sinAng = trig.sin; // Draw all known emmitters for (tmpElement = FCC->GetFirstGroundElement(); tmpElement; tmpElement = tmpElement->GetNext()) { if (tmpElement->BaseObject() == NULL) { continue; } // Check if emitter is on priority list if ( !IsInPriorityList ( tmpElement->symbol ) ) { continue; } // Compute the world space oriented, display space scaled, ownship relative postion of the emitter y2 = (tmpElement->BaseObject()->XPos() - platform->XPos()) * FT_TO_NM / displayRange * HTS_DISPLAY_RADIUS; x2 = (tmpElement->BaseObject()->YPos() - platform->YPos()) * FT_TO_NM / displayRange * HTS_DISPLAY_RADIUS; // Rotate it into heading up space and translate it down to deal with our vertical offset displayX = cosAng * x2 - sinAng * y2; displayY = sinAng * x2 + cosAng * y2 + HTS_Y_OFFSET; // Skip this one if its off screen if ((fabs(displayX) > 1.0f) || (fabs(displayY) > 1.0f)) { continue; } // JB 010726 Clear the designated target if behind the 3/9 line. if (displayY - HTS_Y_OFFSET < 0) { if (lockedTarget && tmpElement->BaseObject() == lockedTarget->BaseData()) { FCC->dropTrackCmd = TRUE; } } DrawEmitter ( tmpElement, displayX, displayY, displayY ); // Mark the locked target // Mark the locked target if (displayY - HTS_Y_OFFSET > 0 && lockedTarget && tmpElement->BaseObject() == lockedTarget->BaseData()) { display->SetColor( GetMfdColor(MFD_WHITE) ); display->Line (-CURSOR_SIZE, -CURSOR_SIZE, -CURSOR_SIZE, CURSOR_SIZE); display->Line ( CURSOR_SIZE, -CURSOR_SIZE, CURSOR_SIZE, CURSOR_SIZE); display->Line ( -CURSOR_SIZE, CURSOR_SIZE, CURSOR_SIZE, CURSOR_SIZE); display->Line ( -CURSOR_SIZE, -CURSOR_SIZE, CURSOR_SIZE, -CURSOR_SIZE); handedoff = true; // Immediate hadnoff in HAD mode } display->AdjustOriginInViewport (-displayX, -displayY); } // Adjust our viewport origin display->AdjustOriginInViewport (0.0f, HTS_Y_OFFSET); // Draw the waypoints display->SetColor( 0xFF00FF00 ); display->AdjustRotationAboutOrigin(-platform->Yaw()); curWaypoint = ((SimVehicleClass*)platform)->waypoint; if (curWaypoint) { curWaypoint->GetLocation (&wpX, &wpY, &wpZ); y2 = (wpX - platform->XPos()) * FT_TO_NM / displayRange * HTS_DISPLAY_RADIUS; x2 = (wpY - platform->YPos()) * FT_TO_NM / displayRange * HTS_DISPLAY_RADIUS; curWaypoint = curWaypoint->GetNextWP(); while (curWaypoint) { curWaypoint->GetLocation (&wpX, &wpY, &wpZ); displayY = (wpX - platform->XPos()) * FT_TO_NM / displayRange * HTS_DISPLAY_RADIUS; displayX = (wpY - platform->YPos()) * FT_TO_NM / displayRange * HTS_DISPLAY_RADIUS; display->Line (x2, y2, displayX, displayY); x2 = displayX; y2 = displayY; curWaypoint = curWaypoint->GetNextWP(); } } // Reset our display parameters display->ZeroRotationAboutOrigin(); display->CenterOriginInViewport (); } // RV - I-Hawk - HAD EXP display void AdvancedHarmTargetingPod::HADExpDisplay( VirtualDisplay* activeDisplay ) { float displayX, displayY; float x, y; float cosAng, sinAng, origCosAng, origSinAng; float EXP1OffsetX, EXP1OffsetY, EXP2OffsetX, EXP2OffsetY; float yawOffsetAng; float origDisplayX, origDisplayY; DWORD tempColor; GroundListElement* tmpElement; mlTrig trig, trig2; FireControlComputer* FCC = ((SimVehicleClass*)platform)->GetFCC(); // Let the base class do the basics HarmTargetingPod::HADExpDisplay( activeDisplay ); // Set up the trig functions of our heading when entered zoom mode mlSinCos (&trig, yawBackup); cosAng = trig.cos; sinAng = trig.sin; // Set up the trig functions of our heading mlSinCos ( &trig2, platform->Yaw() ); origCosAng = trig2.cos; origSinAng = trig2.sin; // Draw all known emmitters for (tmpElement = FCC->GetFirstGroundElement(); tmpElement; tmpElement = tmpElement->GetNext()) { if (tmpElement->BaseObject() == NULL) { continue; } // Check if emitter is on priority list if ( !IsInPriorityList ( tmpElement->symbol ) ) { continue; } // Hold original positions to keep track if locked target hadn't past 3-9 o'clock line y = (tmpElement->BaseObject()->XPos() - platform->XPos()) * FT_TO_NM / displayRange * HTS_DISPLAY_RADIUS; x = (tmpElement->BaseObject()->YPos() - platform->YPos()) * FT_TO_NM / displayRange * HTS_DISPLAY_RADIUS; origDisplayX = origCosAng * x - origSinAng * y; origDisplayY = origSinAng * x + origCosAng * y + HTS_Y_OFFSET; // Compute the world space oriented, display space scaled, obacked up ownship relative position of the emitter y = (tmpElement->BaseObject()->XPos() - XPosBackup) * FT_TO_NM / displayRange * HTS_DISPLAY_RADIUS; x = (tmpElement->BaseObject()->YPos() - YPosBackup) * FT_TO_NM / displayRange * HTS_DISPLAY_RADIUS; // Rotate it into heading up space and translate it down to deal with our vertical offset displayX = cosAng * x - sinAng * y; displayY = sinAng * x + cosAng * y; // Deal with the EXP1 offset EXP1OffsetX = 2.0f * HadOrigCursorX; EXP1OffsetY = 2.0f * HadOrigCursorY; displayX -= EXP1OffsetX; displayY -= EXP1OffsetY; // Here also add the EXP2 offset if appropriate if ( HadZoomMode == EXP2 ) { EXP2OffsetX = 2.0f * HadOrigCursorX + 2.0f * HadOrigCursorX2; EXP2OffsetY = 2.0f * HadOrigCursorY + 2.0f * HadOrigCursorY2; EXP2OffsetY += 2.0f * HTS_Y_OFFSET; if ( displayRange < 10 ) { EXP2OffsetY -= HTS_Y_OFFSET / 2.0f; if ( displayRange < 5 ) { EXP2OffsetY -= HTS_Y_OFFSET / 2.0f; } } displayX -= EXP2OffsetX; displayY -= EXP2OffsetY; } // Skip this one if its off screen if ((fabs(displayX) > 1.0f) || (fabs(displayY) > 1.0f)) { continue; } // JB 010726 Clear the designated target if behind the 3/9 line. if ( origDisplayY - HTS_Y_OFFSET < 0 ) { if ( lockedTarget && tmpElement->BaseObject() == lockedTarget->BaseData() ) { FCC->dropTrackCmd = TRUE; } } DrawEmitter (tmpElement, displayX, displayY, origDisplayY); // Mark the locked target if (origDisplayY - HTS_Y_OFFSET > 0 && lockedTarget && tmpElement->BaseObject() == lockedTarget->BaseData()) { tempColor = display->Color(); display->SetColor( GetMfdColor(MFD_WHITE) ); display->Line (-CURSOR_SIZE, -CURSOR_SIZE, -CURSOR_SIZE, CURSOR_SIZE); display->Line ( CURSOR_SIZE, -CURSOR_SIZE, CURSOR_SIZE, CURSOR_SIZE); display->Line ( -CURSOR_SIZE, CURSOR_SIZE, CURSOR_SIZE, CURSOR_SIZE); display->Line ( -CURSOR_SIZE, -CURSOR_SIZE, CURSOR_SIZE, -CURSOR_SIZE); handedoff = true; } display->AdjustOriginInViewport (-displayX, -displayY); display->SetColor( 0xFF00FF00 ); } // Now draw the ownship symbol in relation to the zoomed area y = (platform->XPos() - XPosBackup) * FT_TO_NM / displayRange * HTS_DISPLAY_RADIUS; x = (platform->YPos() - YPosBackup) * FT_TO_NM / displayRange * HTS_DISPLAY_RADIUS; // Rotate it into heading up space and translate it down to deal with our vertical offset displayX = cosAng * x - sinAng * y; displayY = sinAng * x + cosAng * y; // Add the EXP1 offset displayX -= EXP1OffsetX; displayY -= EXP1OffsetY; // Here also add the EXP2 offset if appropriate if ( HadZoomMode == EXP2 ) { displayX -= EXP2OffsetX; displayY -= EXP2OffsetY; } tempColor = display->Color(); display->AdjustOriginInViewport (displayX, displayY); // RV - I-Hawk - Ownship "airplane" marker. Here the display is relatively "static" and the // only thing that moves and turn is the ownship AC marker display->SetColor( GetMfdColor( MFD_CYAN ) ); static const float NOSE = 0.02f; static const float TAIL = 0.08f; static const float WING = 0.06f; static const float TAIL_WING = 0.02f; yawOffsetAng = platform->Yaw() - yawBackup; float yawOffsetAng2 = yawBackup - platform->Yaw(); mlTrig offset, offset2; mlSinCos( &offset, yawOffsetAng ); mlSinCos( &offset2, yawOffsetAng2 ); sinAng = offset2.sin; cosAng = offset2.cos; float r; float offsetX, offsetY; r = WING * 0.7f; x = r * cosAng; y = r * sinAng; offsetY = 0.05f * cosAng; offsetX = 0.05f * sinAng; display->Line( x, y, -x, -y); r = TAIL_WING; x = r * cosAng; y = r * sinAng; offsetY = 0.04f * cosAng; offsetX = 0.04f * sinAng; sinAng = offset.sin; cosAng = offset.cos; r = (NOSE + TAIL) / 1.35f; y = r * cosAng; x = r * sinAng; display->Line( x, y, -x, -y); display->SetColor ( 0xFF00FF00 ); display->AdjustOriginInViewport (-displayX, -displayY); // Adjust our viewport origin display->AdjustOriginInViewport (0.0f, HTS_Y_OFFSET); // Reset our display parameters display->ZeroRotationAboutOrigin(); display->CenterOriginInViewport (); } // RV - I-Hawk - HAS mode void AdvancedHarmTargetingPod::HASDisplay (VirtualDisplay* activeDisplay) { unsigned numOfDrawnTargets, curTime; float displayX, displayY, NormDisplayX, NormDisplayY, NormDisplayYNoOffset; float x, y, x2, y2; float cosAng, sinAng; float range, alpha, ex, ey, phi, elevation; float rangeX, rangeY, trueRange; GroundListElement* tmpElement; mlTrig trig; FireControlComputer* FCC = ((SimVehicleClass*)platform)->GetFCC(); // Let the base class do the basics HarmTargetingPod::HASDisplay( activeDisplay ); // Set up the trig functions of our current heading mlSinCos (&trig, platform->Yaw()); cosAng = trig.cos; sinAng = trig.sin; curTime = (unsigned)((SimLibElapsedTime - HASTimer) * MSEC_TO_SEC); // Draw all known emmitters ClearDTSB(); // clear DTSB first numOfDrawnTargets = 0; for (tmpElement = FCC->GetFirstGroundElement(); tmpElement; tmpElement = tmpElement->GetNext()) { if (tmpElement->BaseObject() == NULL) { continue; } // Check if emitter is on priority list if ( !IsInPriorityList ( tmpElement->symbol ) ) { continue; } // Check if range is less than 60NM (no reason to get anything beyond...) rangeY = (tmpElement->BaseObject()->XPos() - platform->XPos()) * FT_TO_NM; rangeX = (tmpElement->BaseObject()->YPos() - platform->YPos()) * FT_TO_NM; rangeY *= rangeY; rangeX *= rangeX; trueRange = sqrtf( rangeX + rangeY ); if ( trueRange > 60.0f ) { continue; } // Compute the world space oriented, display space scaled, ownship relative postion of the emitter y = (tmpElement->BaseObject()->XPos() - platform->XPos()) * FT_TO_NM / displayRange * HAS_DISPLAY_RADIUS; x = (tmpElement->BaseObject()->YPos() - platform->YPos()) * FT_TO_NM / displayRange * HAS_DISPLAY_RADIUS; float alt = (-platform->ZPos() - (-tmpElement->BaseObject()->ZPos())) * FT_TO_NM / displayRange * HAS_DISPLAY_RADIUS; // Now calculate elevation (and not range) x2 = x * x; y2 = y * y; range = sqrt( x2 + y2 ); // Get range alpha = atan ( alt / range ); // Get the elevation angle elevation = (1.0f - (alpha / HALF_PI)) * HAS_DISPLAY_RADIUS; NormDisplayX = cosAng * x - sinAng * y; NormDisplayYNoOffset = sinAng * x + cosAng * y; NormDisplayY = sinAng * x + cosAng * y + HTS_Y_OFFSET; phi = atan ( NormDisplayX / NormDisplayYNoOffset ); ex = elevation * sin(phi); ey = elevation * cos(phi); displayX = ex * zoomFactor; displayY = ey * zoomFactor + HTS_Y_OFFSET; // RV - I-Hawk - Diplay only what's inside the ALIC video if ( !IsInsideALIC(displayX, displayY) ) { continue; } // What's behind the 3-9 line, display at ALIC bottom line if ( NormDisplayY < 0.0f + HTS_Y_OFFSET ) { displayY = 0.0f + HTS_Y_OFFSET; displayX = -displayX; // Switch sides when it gets inverted... } // JB 010726 Clear the designated target if behind the 3/9 line. if (NormDisplayY - HTS_Y_OFFSET < 0.0f) { if (lockedTarget && tmpElement->BaseObject() == lockedTarget->BaseData()) { FCC->dropTrackCmd = TRUE; } } // Draw only emitters which their time had come to be shown according to the HAS timer if ( numOfDrawnTargets <= curTime ) { DrawEmitter ( tmpElement, displayX, displayY, displayY ); UpdateDTSB ( tmpElement->symbol, displayX, displayY ); } numOfDrawnTargets++; // Adjust bac display viewport as DrawEmitter function is changing the viewport! display->AdjustOriginInViewport (-displayX, -displayY); } HASNumTargets = numOfDrawnTargets; // RV - I-Hawk - If we have a locked target, go to handoff mode if ( lockedTarget && lockedTarget->BaseData() ) { SetSubMode( Handoff ); preHandoffMode = Has; handoffRefTime = SimLibElapsedTime; handedoff = false; } display->SetColor( 0xFF00FF00 ); // Reset our display parameters display->ZeroRotationAboutOrigin(); display->CenterOriginInViewport (); } // RV - I-Hawk - Handoff mode (getting here after target is locked in HAS mode) void AdvancedHarmTargetingPod::HandoffDisplay (VirtualDisplay* activeDisplay) { float displayX, displayY, NormDisplayX, NormDisplayY, NormDisplayYNoOffset; float x, y, x2, y2; float cosAng, sinAng; float range, alpha, ex, ey, phi, elevation; mlTrig trig; FireControlComputer* FCC = ((SimVehicleClass*)platform)->GetFCC(); GroundListElement* tmpElement = NULL; // Let the base class do the basics HarmTargetingPod::HandoffDisplay( activeDisplay ); display = activeDisplay; // Set up the trig functions of our current heading mlSinCos (&trig, platform->Yaw()); cosAng = trig.cos; sinAng = trig.sin; // Draw only the locked target ClearDTSB(); // clear DTSB first if ( preHandoffMode == Has ) { for (tmpElement = FCC->GetFirstGroundElement(); tmpElement; tmpElement = tmpElement->GetNext()) { if ( !lockedTarget || !lockedTarget->BaseData() || preHandoffMode == Pos ) { break; } if (tmpElement->BaseObject() == NULL) { continue; } // Compute the world space oriented, display space scaled, ownship relative postion of the emitter y = (tmpElement->BaseObject()->XPos() - platform->XPos()) * FT_TO_NM / displayRange * HAS_DISPLAY_RADIUS; x = (tmpElement->BaseObject()->YPos() - platform->YPos()) * FT_TO_NM / displayRange * HAS_DISPLAY_RADIUS; float alt = (-platform->ZPos() - (-tmpElement->BaseObject()->ZPos())) * FT_TO_NM / displayRange * HAS_DISPLAY_RADIUS; // Displaying azimuth/elevation like HAS mode x2 = x * x; y2 = y * y; range = sqrt( x2 + y2 ); alpha = atan ( alt / range ); elevation = (1.0f - (alpha / HALF_PI)) * HAS_DISPLAY_RADIUS; NormDisplayX = cosAng * x - sinAng * y; NormDisplayYNoOffset = sinAng * x + cosAng * y; NormDisplayY = sinAng * x + cosAng * y + HTS_Y_OFFSET; phi = atan ( NormDisplayX / NormDisplayYNoOffset ); ex = elevation * sin(phi); ey = elevation * cos(phi); displayX = ex; displayY = ey + HTS_Y_OFFSET; // Skip this one if its off screen //if ((fabs(displayX) > 1.0f) || (fabs(displayY) > 1.0f)) // RV - I-Hawk - Diplay only what's inside the ALIC video if ( !IsInsideALIC(displayX, displayY) ) { continue; } // although not drawing none-target emitters on main display, still keep DTSB updated display->AdjustOriginInViewport (displayX, displayY); UpdateDTSB ( tmpElement->symbol, displayX, displayY); display->AdjustOriginInViewport (-displayX, -displayY); // Only show the locked up target (after we finished updating DTSB list) if ( tmpElement->BaseObject() != lockedTarget->BaseData() ) { continue; } // JB 010726 Clear the designated target if behind the 3/9 line. if (NormDisplayY - HTS_Y_OFFSET < 0.0f) { if (lockedTarget && tmpElement->BaseObject() == lockedTarget->BaseData()) { FCC->dropTrackCmd = TRUE; } } DrawEmitter ( tmpElement, displayX, displayY, displayY ); BoxTargetDTSB ( tmpElement->symbol, displayX, displayY ); // Mark the locked target if (displayY - HTS_Y_OFFSET > 0 && lockedTarget && tmpElement->BaseObject() == lockedTarget->BaseData()) { display->SetColor( GetMfdColor(MFD_WHITE) ); display->Line (-CURSOR_SIZE, -CURSOR_SIZE, -CURSOR_SIZE, CURSOR_SIZE); display->Line ( CURSOR_SIZE, -CURSOR_SIZE, CURSOR_SIZE, CURSOR_SIZE); display->Line ( -CURSOR_SIZE, CURSOR_SIZE, CURSOR_SIZE, CURSOR_SIZE); display->Line ( -CURSOR_SIZE, -CURSOR_SIZE, CURSOR_SIZE, -CURSOR_SIZE); } display->AdjustOriginInViewport (-displayX, -displayY); } } if ( !lockedTarget ) // Back to HAS mode { SetSubMode( HAS ); ((SimVehicleClass*)platform)->SOIManager(SimVehicleClass::SOI_WEAPON); handedoff = false; } // Check if 3 seconds past since the lock for handoff "delay" if ( handedoff == false ) { if ( SimLibElapsedTime - handoffRefTime > 3 * SEC_TO_MSEC ) { handedoff = true; } } display->SetColor( 0xFF00FF00 ); // Adjust our viewport origin display->AdjustOriginInViewport (0.0f, HTS_Y_OFFSET); // Reset our display parameters display->ZeroRotationAboutOrigin(); display->CenterOriginInViewport (); } // RV - I-Hawk - POS display void AdvancedHarmTargetingPod::POSDisplay (VirtualDisplay* activeDisplay) { int OsbIndex; int boxed; int days, hours, minutes, seconds; DWORD tempColor; float OsbPosX, OsbPosY; float LDLVerticalPos = (ALICTOP + ALICBOTTOM) / 2.0f + 0.05f; float theRange; float dx, dy, ETA; float wpX, wpY, wpZ; float temp; GroundListElement* tmpElement = NULL; WayPointClass* tempWP = NULL; int theWPnum; char str[24]; FireControlComputer* FCC = ((SimVehicleClass*)platform)->GetFCC(); AircraftClass *playerAC = SimDriver.GetPlayerAircraft(); SMSClass* Sms; if ( playerAC ) { Sms = playerAC->Sms; } if ( Sms && !curMissile ) { curMissile = (MissileClass*)(Sms->GetCurrentWeapon()); } display = activeDisplay; display->ZeroRotationAboutOrigin(); display->CenterOriginInViewport (); // Let the base class do the basics HarmTargetingPod::POSDisplay( activeDisplay ); ClearDTSB(); ClearPOSTargets(); BuildPOSTargets(); OsbIndex = 0; for ( int i = 0; i < MAX_POS_TARGETS; i++ ) { if ( POSTargets[i] ) { boxed = 0; tmpElement = POSTargets[i]; tempWP = POSTargetsWPs[i]; GetOsbPos(OsbIndex, OsbPosX, OsbPosY); tempColor = display->Color(); display->SetColor (GetMfdColor(MFD_WHITY_GRAY)); // "whity" gray // This one is the current target if ( i == POSTargetIndex && tmpElement && lockedTarget && tmpElement->BaseObject() == lockedTarget->BaseData() ) { curTarget = POSTargets[i]; curTargetWP = POSTargetsWPs[i]; // If the target had not been handed off already, flash the box. if ( handedoff == false ) { boxed = flash ? 2:0; } else { boxed = 2; // Box it } float zero = 0.0f; UpdateDTSB ( curTarget->symbol, zero, zero ); // Get it into DTSB display->AdjustOriginInViewport ( -0.55f, LDLVerticalPos - 0.1f + HTS_Y_OFFSET ); DrawEmitterSymbol( curTarget->symbol, boxed ); display->AdjustOriginInViewport ( 0.55f, -(LDLVerticalPos - 0.1f + HTS_Y_OFFSET) ); // Get the waypoint number where this target is at, we need to display it // under the LSDL line theWPnum = FindWaypointNum ( curTargetWP ); sprintf (str, "%02d", theWPnum); display->TextCenter ( -0.54f, LDLVerticalPos - 0.15f + HTS_Y_OFFSET, str ); // Get missile TOF. Should also be with the under-LSDL pre-launch info if ( curMissile && curTarget && curTarget->BaseObject() ) { // Get the range to the tmpElement which is the current target "candidate" dx = fabs(playerAC->XPos() - curTarget->BaseObject()->XPos()); dx *= dx; dy = fabs(playerAC->YPos() - curTarget->BaseObject()->YPos()); dy *= dy; theRange = sqrt(dx + dy); curTOF = curMissile->GetTOF( -playerAC->ZPos(), playerAC->GetVt(), 0.0f, 0.0f, theRange); } if ( curTOF > 0.0f ) { temp = curTOF; minutes = FloatToInt32 ( temp / 60.0f ); temp -= minutes * 60.0f; seconds = FloatToInt32 ( temp ); sprintf ( str, "%d:%02d", abs(minutes), abs(seconds) ); display->TextCenter ( -0.55f, LDLVerticalPos - 0.28f + HTS_Y_OFFSET, str ); } // RV - I-Hawk - Get ETA - BTW I noticed the HUD ETA for waypoints is fucked up // and not following the DED ETA which is the accurate one... probably the WP // time arrival function is foobard (which is what the HUD is using) // Here calculating same way as the DED curTargetWP->GetLocation ( &wpX, &wpY, &wpZ ); ETA = (float)(SimLibElapsedTime / SEC_TO_MSEC) + FloatToInt32(Distance( playerAC->XPos(), playerAC->YPos(), wpX, wpY) / playerAC->GetVt()); // Calculate ETA // Get rid of any days first days = FloatToInt32 ( ETA / 86400.0f ); // 86400 seconds in 24 hours ETA -= days * 86400.0f; hours = FloatToInt32 ( ETA / 3600.0f ); ETA -= hours * 3600.0f; minutes = FloatToInt32 ( ETA / 60.0f ); ETA -= minutes * 60.0f; seconds = FloatToInt32 ( ETA ); sprintf ( str, "%d:%02d:%02d", abs(hours), abs(minutes), abs(seconds) ); display->TextCenter ( -0.56f, LDLVerticalPos - 0.37f + HTS_Y_OFFSET, str ); } display->AdjustOriginInViewport (OsbPosX + 0.1f, OsbPosY); DrawEmitterSymbol( tmpElement->symbol, boxed ); display->AdjustOriginInViewport (-(OsbPosX + 0.1f), -OsbPosY); display->SetColor (tempColor); display->CenterOriginInViewport (); OsbIndex++; } else { break; } } // In case of a launch, save the target's symbol and WP if ( curMissile && curMissile->launchState != MissileClass::PreLaunch && lockedTarget ) { // Stop tracking the missile curMissile = NULL; // Backup info on the launched target, and launched waypoint, for TOF if (curTarget) { prevTargteSymbol = curTarget->symbol; prevWPNum = FindWaypointNum ( curTargetWP ); prevTOF = curTOF; missileLaunched = true; // update the flag timer = SimLibElapsedTime; } } if ( missileLaunched ) // Handle the last launched missile data { tempColor = display->Color(); display->SetColor(GetMfdColor(MFD_WHITY_GRAY)); // Draw the emitter simbol above the LSDL line at the post-launch info slot is display->AdjustOriginInViewport ( 0.5f, LDLVerticalPos + 0.1f + HTS_Y_OFFSET ); DrawEmitterSymbol( prevTargteSymbol, 0 ); display->AdjustOriginInViewport ( -0.5f, -(LDLVerticalPos + 0.1f + HTS_Y_OFFSET) ); // Get the previous target waypoint number sprintf (str, "%02d", prevWPNum); display->TextCenter ( 0.49f, LDLVerticalPos + 0.25f + HTS_Y_OFFSET, str ); // Get the launched missile TOF, it's just a "dummy" counter... if ( prevTOF <= 0.0f ) { prevTOF = 0.0f; } else // Tick down the prevTOF { if ( SimLibElapsedTime - timer > 1 * SEC_TO_MSEC ) { prevTOF -= 1.0f; timer += 1 * SEC_TO_MSEC; } } if ( prevTOF >= 0.0f ) { temp = prevTOF; minutes = FloatToInt32 ( temp / 60.0f ); temp -= minutes * 60.0f; seconds = FloatToInt32 ( temp ); sprintf ( str, "%d:%02d", abs(minutes), abs(seconds) ); display->TextCenter ( 0.48f, LDLVerticalPos + 0.38f + HTS_Y_OFFSET, str ); } display->SetColor(tempColor); } // RV - I-Hawk - If we have a locked target, go to handoff mode if ( lockedTarget && lockedTarget->BaseData() ) { preHandoffMode = Pos; if ( handedoff == false ) // Tick the Handoff timer down { if ( SimLibElapsedTime - handoffRefTime > 3 * SEC_TO_MSEC ) { handedoff = true; } } } display->SetColor( 0xFF00FF00 ); // Adjust our viewport origin display->AdjustOriginInViewport (0.0f, HTS_Y_OFFSET); // Reset our display parameters display->ZeroRotationAboutOrigin(); display->CenterOriginInViewport (); } void AdvancedHarmTargetingPod::DrawEmitter ( GroundListElement* tmpElement, float &displayX, float &displayY, float &origDisplayY ) { DWORD color; int boxed; switch ( submode ) { case HAS: color = GetMfdColor(MFD_WHITY_GRAY); boxed = 0; break; case Handoff: color = GetMfdColor(MFD_WHITY_GRAY); boxed = 2; break; case HAD: default: // Set the symbols draw intensity based on its state if ( origDisplayY - HTS_Y_OFFSET < 0 ) { color = 0x00008000; boxed = 0; } else if ( tmpElement->IsSet(GroundListElement::Launch) ) { color = GetMfdColor( MFD_RED ); boxed = flash ? 2 : 0; } else if ( tmpElement->IsSet(GroundListElement::Track) ) { color = GetMfdColor(MFD_RED); boxed = 2; } else if ( tmpElement->IsSet(GroundListElement::Radiate) ) { color = GetMfdColor(MFD_YELLOW); boxed = 0; } else { color = 0x00008000; boxed = 0; } break; } // Adjust our display location and draw the emitter symbol DWORD tmpColor = display->Color(); display->AdjustOriginInViewport (displayX, displayY); display->SetColor( color ); DrawEmitterSymbol( tmpElement->symbol, boxed ); display->SetColor( tmpColor ); } void AdvancedHarmTargetingPod::GetOsbPos ( int &OsbIndex, float &OsbPosX, float &OsbPosY ) { switch ( OsbIndex ) { case 0: GetButtonPos(16, &OsbPosX, &OsbPosY); break; case 1: GetButtonPos(17, &OsbPosX, &OsbPosY); break; case 2: GetButtonPos(18, &OsbPosX, &OsbPosY); break; case 3: default: GetButtonPos(19, &OsbPosX, &OsbPosY); break; } }
30.57732
131
0.674908
markbb1957
7bed2175f712018866ba8bfb087e58ac472f3cb8
3,906
hpp
C++
src/Module/Module.hpp
codechecker123/aff3ct
030af3e990027fa803fb2c68f974c9ec0ee79b5d
[ "MIT" ]
null
null
null
src/Module/Module.hpp
codechecker123/aff3ct
030af3e990027fa803fb2c68f974c9ec0ee79b5d
[ "MIT" ]
null
null
null
src/Module/Module.hpp
codechecker123/aff3ct
030af3e990027fa803fb2c68f974c9ec0ee79b5d
[ "MIT" ]
null
null
null
/*! * \file * \brief A Module is an abstract concept. Basically, all the objects used in a Simulation are a Module. * * \section LICENSE * This file is under MIT license (https://opensource.org/licenses/MIT). */ #ifndef MODULE_HPP_ #define MODULE_HPP_ #include <string> #include <sstream> #include <typeinfo> #include <typeindex> #include <unordered_map> #include <map> #include <functional> #include "Task.hpp" #include "Socket.hpp" #ifdef SYSTEMC_MODULE #include "SC_Module.hpp" #endif #include "Tools/Exception/exception.hpp" namespace aff3ct { namespace module { /*! * \class Module * * \brief A Module is an abstract concept. Basically, all the objects used in a Simulation are a Module. */ class Module { protected: int n_frames; /*!< Number of frames to process in this Module */ std::string name; /*!< Name of the Module. */ std::string short_name; /*!< Short name of the Module. */ std::vector<Task*> tasks_with_nullptr; public: std::vector<Task*> tasks; #ifdef SYSTEMC_MODULE friend SC_Module_container; SC_Module_container sc; #endif /*! * \brief Constructor. * * \param n_frames: number of frames to process in this Module. * \param name : Module's name. */ explicit Module(const int n_frames = 1) : n_frames(n_frames), name("Module"), short_name("Module") #ifdef SYSTEMC_MODULE , sc(*this) #endif { if (n_frames <= 0) { std::stringstream message; message << "'n_frames' has to be greater than 0 ('n_frames' = " << n_frames << ")."; throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str()); } } /*! * \brief Destructor. */ virtual ~Module() { for (auto t : tasks) delete t; } /*! * \brief Get the number of frames. * * \return the number of frames to process in this Module. */ virtual int get_n_frames() const { return n_frames; } inline void set_name(const std::string &name) { this->name = name; } inline const std::string& get_name() const { return this->name; } inline void set_short_name(const std::string &short_name) { this->short_name = short_name; } inline const std::string& get_short_name() const { return this->short_name; } inline Task& operator[](const int id) { return *tasks_with_nullptr[id]; } protected: Task& create_task(const std::string &name, const int id = -1) { bool autoalloc = false, autoexec = false, stats = false, fast = false, debug = false; auto t = new Task(*this, name, autoalloc, autoexec, stats, fast, debug); if (id < 0) { tasks.push_back(t); tasks_with_nullptr.push_back(t); } else { if (tasks_with_nullptr.size() > (size_t)id && tasks_with_nullptr[id] == nullptr) { tasks.push_back(t); tasks_with_nullptr[id] = t; }else { delete t; std::stringstream message; message << "Impossible to create the task ('task.name' = " << name << ", 'task.id' = " << id << ", 'tasks.size()' = " << tasks.size() << ", 'module.name' = " << this->get_name() << ")."; throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str()); } } return *t; } template <typename T> Socket& create_socket_in(Task& task, const std::string &name, const size_t n_elmts) { return task.template create_socket_in<T>(name, n_elmts); } template <typename T> Socket& create_socket_in_out(Task& task, const std::string &name, const size_t n_elmts) { return task.template create_socket_in_out<T>(name, n_elmts); } template <typename T> Socket& create_socket_out(Task& task, const std::string &name, const size_t n_elmts) { return task.template create_socket_out<T>(name, n_elmts); } void create_codelet(Task& task, std::function<int(void)> codelet) { task.create_codelet(codelet); } void register_timer(Task& task, const std::string &key) { task.register_timer(key); } }; } } #endif /* MODULE_HPP_ */
21.821229
104
0.664875
codechecker123
7bf41dbef6119e66d3f13a2a1786b8f77b4dcdf4
3,480
cpp
C++
source/rcnn/modeling/roi_heads/mask_head/mask_head.cpp
kerry-Cho/maskrcnn_benchmark.cpp
f110f7b6d6ac87b919b8f7aa95527c68f74d234a
[ "MIT" ]
99
2019-05-01T15:23:45.000Z
2022-01-30T05:11:40.000Z
source/rcnn/modeling/roi_heads/mask_head/mask_head.cpp
conanhung/maskrcnn_benchmark.cpp
eab9787d3140e003662a31a8e01f7ae39469e9a0
[ "MIT" ]
18
2019-05-21T11:31:44.000Z
2020-04-03T09:59:27.000Z
source/rcnn/modeling/roi_heads/mask_head/mask_head.cpp
conanhung/maskrcnn_benchmark.cpp
eab9787d3140e003662a31a8e01f7ae39469e9a0
[ "MIT" ]
27
2019-05-12T05:41:08.000Z
2021-02-07T01:58:01.000Z
#include "roi_heads/mask_head/mask_head.h" namespace rcnn{ namespace modeling{ std::pair<std::vector<rcnn::structures::BoxList>, std::vector<torch::Tensor>> KeepOnlyPositiveBoxes(std::vector<rcnn::structures::BoxList> boxes){ std::vector<rcnn::structures::BoxList> positive_boxes; std::vector<torch::Tensor> positive_inds; int num_boxes = 0; for(auto& boxes_per_image : boxes){ torch::Tensor labels = boxes_per_image.GetField("labels"); torch::Tensor inds_mask = labels > 0; torch::Tensor inds = inds_mask.nonzero().squeeze(1); positive_boxes.push_back(boxes_per_image[inds]); positive_inds.push_back(inds_mask); } return std::make_pair(positive_boxes, positive_inds); } ROIMaskHeadImpl::ROIMaskHeadImpl(int64_t in_channels) :feature_extractor(MakeROIMaskFeatureExtractor(in_channels)), predictor(MakeROIMaskPredictor(feature_extractor->out_channels())), post_processor(MakeRoiMaskPostProcessor()), loss_evaluator(MakeROIMaskLossEvaluator()){} std::tuple<torch::Tensor, std::vector<rcnn::structures::BoxList>, std::map<std::string, torch::Tensor>> ROIMaskHeadImpl::forward(std::vector<torch::Tensor> features, std::vector<rcnn::structures::BoxList> proposals, std::vector<rcnn::structures::BoxList> targets) { if(is_training()){ torch::Tensor mask_logits, x, loss_mask; std::vector<rcnn::structures::BoxList> positive_boxes, all_proposals; std::vector<torch::Tensor> positive_inds; all_proposals = proposals; std::tie(positive_boxes, positive_inds) = KeepOnlyPositiveBoxes(proposals); x = feature_extractor->forward(features, proposals); mask_logits = predictor->forward<torch::Tensor>(x); loss_mask = loss_evaluator(proposals, mask_logits, targets); return std::make_tuple(x, all_proposals, std::map<std::string, torch::Tensor>{{"loss_mask", loss_mask}}); } else{ return forward(features, proposals); } } std::tuple<torch::Tensor, std::vector<rcnn::structures::BoxList>, std::map<std::string, torch::Tensor>> ROIMaskHeadImpl::forward(std::vector<torch::Tensor> features, std::vector<rcnn::structures::BoxList> proposals){ //No target, No training torch::Tensor x = feature_extractor->forward(features, proposals); torch::Tensor mask_logits = predictor->forward(x); std::vector<rcnn::structures::BoxList> result = post_processor(mask_logits, proposals); return std::make_tuple(x, result, std::map<std::string, torch::Tensor>{}); } std::tuple<torch::Tensor, std::vector<rcnn::structures::BoxList>, std::map<std::string, torch::Tensor>> ROIMaskHeadImpl::forward(torch::Tensor features, std::vector<rcnn::structures::BoxList> proposals, std::vector<rcnn::structures::BoxList> targets){ //share feature => training std::vector<rcnn::structures::BoxList> positive_boxes, all_proposals; std::vector<torch::Tensor> positive_inds; torch::Tensor mask_logits, x, loss_mask; all_proposals = proposals; std::tie(positive_boxes, positive_inds) = KeepOnlyPositiveBoxes(proposals); x = features[torch::cat(positive_inds, 0)]; mask_logits = predictor->forward(x); loss_mask = loss_evaluator(proposals, mask_logits, targets); return std::make_tuple(x, all_proposals, std::map<std::string, torch::Tensor>{{"loss_mask", loss_mask}}); } ROIMaskHead BuildROIMaskHead(int64_t in_channels){ return ROIMaskHead(in_channels); } } }
44.615385
251
0.718103
kerry-Cho
7bf645240fb591fe4703883df53f340eae8e37bc
7,397
hpp
C++
include/lexy/dsl/whitespace.hpp
IohannRabeson/lexy
881beb56f030e8f4761514e70cb50d809ac4ad17
[ "BSL-1.0" ]
null
null
null
include/lexy/dsl/whitespace.hpp
IohannRabeson/lexy
881beb56f030e8f4761514e70cb50d809ac4ad17
[ "BSL-1.0" ]
null
null
null
include/lexy/dsl/whitespace.hpp
IohannRabeson/lexy
881beb56f030e8f4761514e70cb50d809ac4ad17
[ "BSL-1.0" ]
null
null
null
// Copyright (C) 2020-2021 Jonathan Müller <jonathanmueller.dev@gmail.com> // This file is subject to the license terms in the LICENSE file // found in the top-level directory of this distribution. #ifndef LEXY_DSL_WHITESPACE_HPP_INCLUDED #define LEXY_DSL_WHITESPACE_HPP_INCLUDED #include <lexy/dsl/base.hpp> #include <lexy/dsl/choice.hpp> #include <lexy/dsl/loop.hpp> #include <lexy/dsl/token.hpp> #include <lexy/engine/while.hpp> #include <lexy/token.hpp> #ifdef LEXY_IGNORE_DEPRECATED_WHITESPACE # define LEXY_DEPRECATED_WHITESPACE #else # define LEXY_DEPRECATED_WHITESPACE \ [[deprecated("operator[] has been deprecated; use dsl::whitespace(ws) instead.")]] #endif namespace lexyd { template <typename Rule> struct _wsr : rule_base { template <typename NextParser> struct parser { template <typename Context, typename Reader, typename... Args> LEXY_DSL_FUNC bool parse(Context& context, Reader& reader, Args&&... args) { auto begin = reader.cur(); if constexpr (lexy::is_token<Rule>) { // Parsing a token repeatedly cannot fail, so we can optimize it using an engine. using engine = lexy::engine_while<typename Rule::token_engine>; engine::match(reader); } else { // We need to mark the context with the tag to prevent infinite recursion. auto ws_context = context.insert(lexy::_tag_whitespace{}, lexy::_tag_whitespace{}); // We can then parse the rule repeatedly using the special context. using loop_parser = lexy::rule_parser<decltype(loop(Rule{} | break_)), lexy::context_discard_parser<decltype(ws_context)>>; if (!loop_parser::parse(ws_context, reader)) return false; } auto end = reader.cur(); // Add a whitespace token node. if (begin != end) context.token(lexy::whitespace_token_kind, begin, end); return NextParser::parse(context, reader, LEXY_FWD(args)...); } }; template <typename R> friend constexpr auto operator|(_wsr<Rule>, R r) { return _wsr<decltype(Rule{} | r)>{}; } template <typename R> friend constexpr auto operator|(R r, _wsr<Rule>) { return _wsr<decltype(r | Rule{})>{}; } template <typename R> friend constexpr auto operator/(_wsr<Rule>, R r) { return _wsr<decltype(Rule{} / r)>{}; } template <typename R> friend constexpr auto operator/(R r, _wsr<Rule>) { return _wsr<decltype(r / Rule{})>{}; } }; struct _ws : rule_base { template <typename NextParser> struct parser { template <typename Context, typename Reader, typename... Args> LEXY_DSL_FUNC bool parse(Context& context, Reader& reader, Args&&... args) { return lexy::whitespace_parser<Context, NextParser>::parse(context, reader, LEXY_FWD(args)...); } }; /// Overrides implicit whitespace detection. template <typename Rule> constexpr auto operator()(Rule) const { return _wsr<Rule>{}; } }; /// Matches whitespace. constexpr auto whitespace = _ws{}; } // namespace lexyd namespace lexyd { template <typename Rule> struct _wsn : rule_base { static constexpr auto is_branch = Rule::is_branch; static constexpr auto is_unconditional_branch = Rule::is_unconditional_branch; template <typename NextParser> struct parser { struct _cont { template <typename WsContext, typename Reader, typename Context, typename... Args> LEXY_DSL_FUNC bool parse(WsContext&, Reader& reader, Context& context, Args&&... args) { // Continue with the normal context, after skipping whitespace. return lexy::whitespace_parser<Context, NextParser>::parse(context, reader, LEXY_FWD(args)...); } }; template <typename Context, typename Reader, typename... Args> LEXY_DSL_FUNC auto try_parse(Context& context, Reader& reader, Args&&... args) -> lexy::rule_try_parse_result { // Parse the rule using the context that doesn't allow inner whitespace. auto ws_context = context.insert(lexy::_tag_no_whitespace{}, lexy::_tag_no_whitespace{}); return lexy::rule_parser<Rule, _cont>::try_parse(ws_context, reader, context, LEXY_FWD(args)...); } template <typename Context, typename Reader, typename... Args> LEXY_DSL_FUNC bool parse(Context& context, Reader& reader, Args&&... args) { // Parse the rule using the context that doesn't allow inner whitespace. auto ws_context = context.insert(lexy::_tag_no_whitespace{}, lexy::_tag_no_whitespace{}); return lexy::rule_parser<Rule, _cont>::parse(ws_context, reader, context, LEXY_FWD(args)...); } }; }; /// Disables automatic skipping of whitespace for all tokens of the given rule. template <typename Rule> constexpr auto no_whitespace(Rule) { if constexpr (lexy::is_token<Rule>) return Rule{}; // Token already behaves that way. else return _wsn<Rule>{}; } } // namespace lexyd namespace lexyd { template <typename Rule, typename Whitespace> struct _wsd : rule_base { static constexpr auto is_branch = Rule::is_branch; static constexpr auto is_unconditional_branch = Rule::is_unconditional_branch; template <typename NextParser> struct parser { template <typename Context, typename Reader, typename... Args> LEXY_DSL_FUNC auto try_parse(Context& context, Reader& reader, Args&&... args) -> lexy::rule_try_parse_result { using ws = decltype(token(loop(Whitespace{} | break_))); lexy::engine_try_match<typename ws::token_engine>(reader); return lexy::rule_parser<Rule, NextParser>::try_parse(context, reader, LEXY_FWD(args)...); } template <typename Context, typename Reader, typename... Args> LEXY_DSL_FUNC bool parse(Context& context, Reader& reader, Args&&... args) { using rule = decltype(loop(token(Whitespace{}) | break_) + Rule{}); return lexy::rule_parser<rule, NextParser>::parse(context, reader, LEXY_FWD(args)...); } }; template <typename Tag> constexpr auto error() const { static_assert(lexy::is_token<Rule>); return Rule{}.template error<Tag>(); } }; /// Matches whitespace before parsing rule. template <typename Rule, typename Whitespace> LEXY_DEPRECATED_WHITESPACE constexpr auto whitespaced(Rule, Whitespace) { return _wsd<Rule, Whitespace>{}; } } // namespace lexyd #endif // LEXY_DSL_WHITESPACE_HPP_INCLUDED
34.565421
100
0.596728
IohannRabeson
7bf87b1b45b9b9d354e72a09ee6337256937ac23
5,695
cpp
C++
fft.cpp
doug65536/FastSpectrumAnalyzer
061022f5acb50929c5cd84ec914220e9a087c356
[ "MIT" ]
4
2016-11-29T06:48:50.000Z
2021-05-07T00:47:34.000Z
fft.cpp
doug65536/FastSpectrumAnalyzer
061022f5acb50929c5cd84ec914220e9a087c356
[ "MIT" ]
null
null
null
fft.cpp
doug65536/FastSpectrumAnalyzer
061022f5acb50929c5cd84ec914220e9a087c356
[ "MIT" ]
null
null
null
#include "fft.h" #include <vector> #include <iostream> #include <iomanip> #include <memory> #include <limits> #include "stopwatch.h" #include "asserts.h" static double worstError0, worstError1, worstError2; //template<typename T, int logPoints> //int64_t testffttype(FFT<T, logPoints> &fft, bool fulltest = false) //{ // typedef T Real; //// std::array<Real, 65536> input; // std::vector<Real> result; // // int64_t microseconds = 0; // int64_t bestMicroseconds = std::numeric_limits<int64_t>::max(); // int64_t totalMicroseconds = 0; // int64_t totalCount = 0; // // // Exhaustive brute force test that mixes a pair of waves with // // different amplitudes at two different nearby frequencies, // // for halfPoints points - 2. Error and worst case error are measured. // // for (auto chk = 1, e = fft.getHalfPoints()-2; chk < e; ++chk) // { // auto freq = fft.getFrequency(chk); // auto freq2 = fft.getFrequency(chk+2); // // Stopwatch sw; // sw.start(); // fft.selfTestIn(freq, 1, false); // fft.selfTestIn(freq2, 0.001, true); // fft.process(std::back_inserter(result)); // sw.update(); // microseconds = sw.elapsedMicroseconds(); // totalMicroseconds += microseconds; // ++totalCount; // if (bestMicroseconds > microseconds) // bestMicroseconds = microseconds; // // // for (std::size_t i = 0, e = input.size(); i != e; ++i) //// { //// input[i] = Real(sin(2 * 3.14159265358979323 * freq * i / fft.maxFreq()) //// + 0.001 * sin(2 * 3.14159265358979323 * freq2 * i / fft.maxFreq())); //// } // //// fft.process(input.begin(), input.end(), std::back_inserter(result)); // // auto dumpResult = [&] // { // for (auto i = result.begin() + std::max(chk - 3, 0), // e = result.begin() + std::min(chk + 3, fft.getPoints()); // i != e; ++i) // std::cout << (i - result.begin()) << ": " << std::setprecision(16) << *i << std::endl; // std::cout << std::endl; // }; // // for (auto i = 0, e = fft.getHalfPoints(); i < e; ++i) // { // // If not full test, check the first 100 values // if (i >= 50 && !fulltest) // { // // Shortcuts // // // Jump to 100 points before the check frequency // // or do nothing if there aren't over 100 points // // after i before chk // if (i < chk - 50) // { //// std::cout << "Cheating from " << i << " to " << (chk - 100) << std::endl; // i = chk - 50; // } // // // Jump to 100 points before the end if after both // // check points // if (i > chk + 2 + 50 && i < e - 100) // { //// std::cout << "Cheating from " << i << " to " << (e - 100) << std::endl; // i = e - 50; // } // } // // double error0 = std::abs(0.0 - result[i]); // double error1 = std::abs(1.0 - result[i]); // double error2 = std::abs(0.001 - result[i]); // // if (i == chk) // { // worstError1 = std::max(worstError1, error1); // if (!AssertBreakForce(error1 < 0.0015)) // dumpResult(); // } // else if (i == chk + 2) // { // worstError2 = std::max(worstError2, error2); // if (!AssertBreakForce(error2 < 0.0002)) // // float, logPoints=15, i=12186, 0.0006371234194375575 // dumpResult(); // } // else // { // worstError0 = std::max(worstError0, error0); // if (!AssertBreakForce(error0 < 0.00075)) // dumpResult(); // } // } // // result.clear(); // } // // std::cout << "Worst error 0: " << worstError0 << std::endl; // std::cout << "Worst error 1: " << worstError1 << std::endl; // std::cout << "Worst error 2: " << worstError2 << std::endl; // std::cout << "Best microseconds: " << bestMicroseconds << std::endl; // // return totalMicroseconds / totalCount; //} //template<typename T, int points> //class TestFFT //{ //public: // static void test() // { // // Recursively expand and call templates of smaller point count // // if the point count is > 4 // std::conditional<(points > 4), TestFFT<T, points-1>, Empty>::type::test(); // // auto fft = std::make_shared<FFT<T, points>>(44100); // // std::cout << "Size is " << (sizeof(*fft)) << std::endl; // // auto avg = testffttype(*fft); // std::cout << (1<<points) << " point: " << avg << " us" << std::endl; // } // //private: // class Empty // { // public: // static void test() // { // } // }; //}; // //void testfft() //{ // // 256 point is about 5 microseconds // // 1024 point is about 21 microseconds // // 2048 point is about 49 microseconds // // 4096 point is about 141 microseconds // // 8192 point is about 332 microseconds // // 16384 point is about 837 microseconds // // 32768 point is about 2214 microseconds // // 65536 point is about 5233 microseconds // std::cout << "===================" << std::endl; // std::cout << "double" << std::endl; // std::cout << "===================" << std::endl; // TestFFT<double, 12>::test(); // TestFFT<float, 12>::test(); //}
33.89881
104
0.482704
doug65536
d0007e4615c7d6b1caca6af03543590e94d246ee
4,831
cpp
C++
lib/EEPROM/EEPROMController.cpp
samuelmoll/TapTimer
8391d248b09ad8d80df5d640728f9ad57a4b6b1c
[ "MIT" ]
null
null
null
lib/EEPROM/EEPROMController.cpp
samuelmoll/TapTimer
8391d248b09ad8d80df5d640728f9ad57a4b6b1c
[ "MIT" ]
null
null
null
lib/EEPROM/EEPROMController.cpp
samuelmoll/TapTimer
8391d248b09ad8d80df5d640728f9ad57a4b6b1c
[ "MIT" ]
null
null
null
#include "EEPROMController.hpp" EEPROMController::EEPROMController(Valve* v1, Valve* v2, Valve* v3, Valve* v4) { valve1 = v1; valve2 = v2; valve3 = v3; valve4 = v4; } void EEPROMController::initValves(){ uint16_t sig; sig = eeprom_read_word(&signature); Serial.print(sig); if (sig == 0x74EE) { Serial.print("EEPROM data detected - loading valves."); uint8_t v1StartHour; uint8_t v1StartMin; uint8_t v1Duration; uint8_t v1Period; uint8_t v1Enable; v1StartHour = eeprom_read_byte(&valve1StartHour); v1StartMin = eeprom_read_byte(&valve1StartMin); v1Duration = eeprom_read_byte(&valve1Duration); v1Period = eeprom_read_byte(&valve1Period); v1Enable = eeprom_read_byte(&valve1Enable); valve1->setStartTime(v1StartHour, v1StartMin); valve1->setDuration(v1Duration); valve1->setPeriod(v1Period); valve1->enableValve(v1Enable); uint8_t v2StartHour; uint8_t v2StartMin; uint8_t v2Duration; uint8_t v2Period; uint8_t v2Enable; v2StartHour = eeprom_read_byte(&valve2StartHour); v2StartMin = eeprom_read_byte(&valve2StartMin); v2Duration = eeprom_read_byte(&valve2Duration); v2Period = eeprom_read_byte(&valve2Period); v2Enable = eeprom_read_byte(&valve2Enable); valve2->setStartTime(v2StartHour, v2StartMin); valve2->setDuration(v2Duration); valve2->setPeriod(v2Period); valve2->enableValve(v2Enable); uint8_t v3StartHour; uint8_t v3StartMin; uint8_t v3Duration; uint8_t v3Period; uint8_t v3Enable; v3StartHour = eeprom_read_byte(&valve3StartHour); v3StartMin = eeprom_read_byte(&valve3StartMin); v3Duration = eeprom_read_byte(&valve3Duration); v3Period = eeprom_read_byte(&valve3Period); v3Enable = eeprom_read_byte(&valve3Enable); valve3->setStartTime(v3StartHour, v3StartMin); valve3->setDuration(v3Duration); valve3->setPeriod(v3Period); valve3->enableValve(v3Enable); uint8_t v4StartHour; uint8_t v4StartMin; uint8_t v4Duration; uint8_t v4Period; uint8_t v4Enable; v4StartHour = eeprom_read_byte(&valve4StartHour); v4StartMin = eeprom_read_byte(&valve4StartMin); v4Duration = eeprom_read_byte(&valve4Duration); v4Period = eeprom_read_byte(&valve4Period); v4Enable = eeprom_read_byte(&valve4Enable); valve4->setStartTime(v4StartHour, v4StartMin); valve4->setDuration(v4Duration); valve4->setPeriod(v4Period); valve4->enableValve(v4Enable); } } void EEPROMController::updateEEPROM(){ Serial.println("updating EEprom"); uint8_t v1StartHour = valve1->getStartHour(); uint8_t v1StartMin = valve1->getStartMinute(); uint8_t v1Duration = valve1->getDuration(); uint8_t v1Period = valve1->getPeriod(); uint8_t v1Enable = valve1->isEnabled(); eeprom_update_byte((uint8_t*)&valve1StartHour, v1StartHour); eeprom_update_byte((uint8_t*)&valve1StartMin, v1StartMin); eeprom_update_byte((uint8_t*)&valve1Duration, v1Duration); eeprom_update_byte((uint8_t*)&valve1Period, v1Period); eeprom_update_byte((uint8_t*)&valve1Enable, v1Enable); uint8_t v2StartHour = valve2->getStartHour(); uint8_t v2StartMin = valve2->getStartMinute(); uint8_t v2Duration = valve2->getDuration(); uint8_t v2Period = valve2->getPeriod(); uint8_t v2Enable = valve2->isEnabled(); eeprom_update_byte((uint8_t*)&valve2StartHour, v2StartHour); eeprom_update_byte((uint8_t*)&valve2StartMin, v2StartMin); eeprom_update_byte((uint8_t*)&valve2Duration, v2Duration); eeprom_update_byte((uint8_t*)&valve2Period, v2Period); eeprom_update_byte((uint8_t*)&valve2Enable, v2Enable); uint8_t v3StartHour = valve3->getStartHour(); uint8_t v3StartMin = valve3->getStartMinute(); uint8_t v3Duration = valve3->getDuration(); uint8_t v3Period = valve3->getPeriod(); uint8_t v3Enable = valve3->isEnabled(); eeprom_update_byte((uint8_t*)&valve3StartHour, v3StartHour); eeprom_update_byte((uint8_t*)&valve3StartMin, v3StartMin); eeprom_update_byte((uint8_t*)&valve3Duration, v3Duration); eeprom_update_byte((uint8_t*)&valve3Period, v3Period); eeprom_update_byte((uint8_t*)&valve3Enable, v3Enable); uint8_t v4StartHour = valve4->getStartHour(); uint8_t v4StartMin = valve4->getStartMinute(); uint8_t v4Duration = valve4->getDuration(); uint8_t v4Period = valve4->getPeriod(); uint8_t v4Enable = valve4->isEnabled(); eeprom_update_byte((uint8_t*)&valve4StartHour, v4StartHour); eeprom_update_byte((uint8_t*)&valve4StartMin, v4StartMin); eeprom_update_byte((uint8_t*)&valve4Duration, v4Duration); eeprom_update_byte((uint8_t*)&valve4Period, v4Period); eeprom_update_byte((uint8_t*)&valve4Enable, v4Enable); eeprom_update_word((uint16_t*)&signature, 0x74EE); }
36.598485
80
0.732354
samuelmoll
d00111b7d02c5829f3f6b20ff69e453bed2b1704
1,576
cpp
C++
Sources/Vulkan/erm/rendering/buffers/IBuffer.cpp
JALB91/ERM
5d2c56db6330efc7d662c24796fdc49e43d26e40
[ "MIT" ]
5
2019-02-26T18:46:52.000Z
2022-01-27T23:48:26.000Z
Sources/Vulkan/erm/rendering/buffers/IBuffer.cpp
JALB91/ERM
5d2c56db6330efc7d662c24796fdc49e43d26e40
[ "MIT" ]
1
2020-06-07T23:44:29.000Z
2021-04-03T18:49:54.000Z
Sources/Vulkan/erm/rendering/buffers/IBuffer.cpp
JALB91/ERM
5d2c56db6330efc7d662c24796fdc49e43d26e40
[ "MIT" ]
null
null
null
#include "erm/rendering/buffers/IBuffer.h" #include "erm/rendering/Device.h" #include "erm/utils/Utils.h" #include "erm/utils/VkUtils.h" namespace erm { IBuffer::IBuffer( Device& device, size_t size, vk::BufferUsageFlags buf, vk::MemoryPropertyFlags mpf) : mDevice(device) , mBufferSize(size) , mBuf(buf) , mMpf(mpf) { VkUtils::CreateBufferUnique( device.GetVkPhysicalDevice(), device.GetVkDevice(), size, buf, mpf, mBuffer, mBufferMemory); mLayout.mBuffer = mBuffer.get(); mLayout.mInfos.emplace_back(BufferInfo {0, mBufferSize}); } IBuffer::IBuffer(const IBuffer& other) : mDevice(other.mDevice) , mBufferSize(other.mBufferSize) , mBuf(other.mBuf) , mMpf(other.mMpf) { VkUtils::CreateBufferUnique( mDevice.GetVkPhysicalDevice(), mDevice.GetVkDevice(), mBufferSize, mBuf, mMpf, mBuffer, mBufferMemory); mLayout.mBuffer = mBuffer.get(); mLayout.mInfos.emplace_back(BufferInfo {0, mBufferSize}); } IBuffer::IBuffer(IBuffer&& other) : mDevice(other.mDevice) , mBufferSize(other.mBufferSize) , mLayout(std::move(other.mLayout)) , mBuf(std::move(other.mBuf)) , mMpf(std::move(other.mMpf)) , mBuffer(std::move(other.mBuffer)) , mBufferMemory(std::move(other.mBufferMemory)) {} IBuffer& IBuffer::operator=(IBuffer&& other) { if (this == &other) return *this; ASSERT(&mDevice == &other.mDevice); mBufferSize = other.mBufferSize; mBuf = std::move(other.mBuf); mMpf = std::move(other.mMpf); mBuffer = std::move(other.mBuffer); mBufferMemory = std::move(other.mBufferMemory); return *this; } } // namespace erm
20.205128
58
0.713198
JALB91
d002dacc2b7be2a4fc0cc23114bf1b0d8927518a
4,849
cpp
C++
demos/monotone/main.cpp
Roastmaster/soloud
cf1252478439aca4e2505c3e4d22c1810b13a841
[ "Zlib" ]
13
2016-10-19T00:33:23.000Z
2022-02-23T07:55:30.000Z
demos/monotone/main.cpp
Roastmaster/soloud
cf1252478439aca4e2505c3e4d22c1810b13a841
[ "Zlib" ]
1
2020-10-03T03:47:09.000Z
2020-10-03T03:47:09.000Z
demos/monotone/main.cpp
Roastmaster/soloud
cf1252478439aca4e2505c3e4d22c1810b13a841
[ "Zlib" ]
7
2017-07-19T11:24:27.000Z
2022-02-23T07:55:34.000Z
/* SoLoud audio engine Copyright (c) 2013-2015 Jari Komppa This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <stdlib.h> #include <math.h> #include <stdio.h> #include "imgui.h" #include "soloud_demo_framework.h" #include "soloud.h" #include "soloud_monotone.h" #include "soloud_lofifilter.h" #include "soloud_biquadresonantfilter.h" #include "soloud_echofilter.h" #include "soloud_dcremovalfilter.h" SoLoud::Soloud gSoloud; SoLoud::Monotone gMusic; SoLoud::BiquadResonantFilter gBiquad; SoLoud::LofiFilter gLofi; SoLoud::EchoFilter gEcho; SoLoud::DCRemovalFilter gDCRemoval; int gMusichandle; float filter_param0[4] = { 0, 0, 0, 0 }; float filter_param1[4] = { 1000, 8000, 0, 0 }; float filter_param2[4] = { 2, 3, 0, 0 }; int hwchannels = 4; int waveform = 0; void DemoMainloop() { gSoloud.setFilterParameter(gMusichandle, 0, 0, filter_param0[0]); gSoloud.setFilterParameter(gMusichandle, 1, 0, filter_param0[1]); gSoloud.setFilterParameter(gMusichandle, 2, 0, filter_param0[2]); gSoloud.setFilterParameter(gMusichandle, 3, 0, filter_param0[3]); gSoloud.setFilterParameter(gMusichandle, 0, 2, filter_param1[0]); gSoloud.setFilterParameter(gMusichandle, 0, 3, filter_param2[0]); gSoloud.setFilterParameter(gMusichandle, 1, 1, filter_param1[1]); gSoloud.setFilterParameter(gMusichandle, 1, 2, filter_param2[1]); DemoUpdateStart(); float *buf = gSoloud.getWave(); float *fft = gSoloud.calcFFT(); ONCE(ImGui::SetNextWindowPos(ImVec2(500, 20))); ImGui::Begin("Output"); ImGui::PlotLines("##Wave", buf, 256, 0, "Wave", -1, 1, ImVec2(264, 80)); ImGui::PlotHistogram("##FFT", fft, 256/2, 0, "FFT", 0, 10, ImVec2(264,80),8); ImGui::Text("Music volume : %d%%", (int)floor(gSoloud.getVolume(gMusichandle) * 100)); ImGui::Text("Active voices : %d", gSoloud.getActiveVoiceCount()); ImGui::End(); ONCE(ImGui::SetNextWindowPos(ImVec2(20, 20))); ImGui::Begin("Control"); if (ImGui::SliderInt("Channels", &hwchannels, 1, 4)) { gMusic.setParams(hwchannels, waveform); } if (ImGui::CollapsingHeader("Waveform", (const char*)0, true, false)) { if (ImGui::RadioButton("Square", waveform == SoLoud::Monotone::SQUARE)) { waveform = SoLoud::Monotone::SQUARE; gMusic.setParams(hwchannels, waveform); } if (ImGui::RadioButton("Saw", waveform == SoLoud::Monotone::SAW)) { waveform = SoLoud::Monotone::SAW; gMusic.setParams(hwchannels, waveform); } if (ImGui::RadioButton("Sin", waveform == SoLoud::Monotone::SIN)) { waveform = SoLoud::Monotone::SIN; gMusic.setParams(hwchannels, waveform); } if (ImGui::RadioButton("SawSin", waveform == SoLoud::Monotone::SAWSIN)) { waveform = SoLoud::Monotone::SAWSIN; gMusic.setParams(hwchannels, waveform); } } ImGui::Separator(); ImGui::Text("Biquad filter (lowpass)"); ImGui::SliderFloat("Wet##4", &filter_param0[0], 0, 1); ImGui::SliderFloat("Frequency##4", &filter_param1[0], 0, 8000); ImGui::SliderFloat("Resonance##4", &filter_param2[0], 1, 20); ImGui::Separator(); ImGui::Text("Lofi filter"); ImGui::SliderFloat("Wet##2", &filter_param0[1], 0, 1); ImGui::SliderFloat("Rate##2", &filter_param1[1], 1000, 8000); ImGui::SliderFloat("Bit depth##2", &filter_param2[1], 0, 8); ImGui::Separator(); ImGui::Text("Echo filter"); ImGui::SliderFloat("Wet##3", &filter_param0[2], 0, 1); ImGui::Separator(); ImGui::Text("DC removal filter"); ImGui::SliderFloat("Wet##1", &filter_param0[3], 0, 1); ImGui::End(); DemoUpdateEnd(); } int DemoEntry(int argc, char *argv[]) { gMusic.load("audio/Jakim - Aboriginal Derivatives.mon"); gMusic.setParams(10); gEcho.setParams(0.2f, 0.5f, 0.05f); gBiquad.setParams(SoLoud::BiquadResonantFilter::LOWPASS, 44100, 4000, 2); gMusic.setLooping(1); gMusic.setFilter(0, &gBiquad); gMusic.setFilter(1, &gLofi); gMusic.setFilter(2, &gEcho); gMusic.setFilter(3, &gDCRemoval); gSoloud.init(SoLoud::Soloud::CLIP_ROUNDOFF | SoLoud::Soloud::ENABLE_VISUALIZATION); gMusichandle = gSoloud.play(gMusic); waveform = SoLoud::Monotone::SAW; gMusic.setParams(hwchannels, waveform); return 0; }
31.901316
91
0.716849
Roastmaster
d007579be52b2bc3053deb5e6505441e1af4de2d
2,791
cc
C++
src/mediaengine/open_cdm_mediaengine_impl.cc
vishalbhoj/open-content-decryption-module
8a08d6c25a612be0a1a83493cb1229d5748f2a21
[ "Apache-2.0" ]
7
2018-12-19T15:04:49.000Z
2020-05-22T07:28:33.000Z
src/mediaengine/open_cdm_mediaengine_impl.cc
vishalbhoj/open-content-decryption-module
8a08d6c25a612be0a1a83493cb1229d5748f2a21
[ "Apache-2.0" ]
4
2018-07-11T15:09:08.000Z
2018-10-19T14:19:56.000Z
src/mediaengine/open_cdm_mediaengine_impl.cc
vishalbhoj/open-content-decryption-module
8a08d6c25a612be0a1a83493cb1229d5748f2a21
[ "Apache-2.0" ]
5
2018-06-27T19:19:42.000Z
2019-05-02T05:09:27.000Z
/* * Copyright 2014 Fraunhofer FOKUS * * 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 "open_cdm_mediaengine_impl.h" #include <rpc_cdm_mediaengine_handler.h> #include <cdm_logging.h> namespace media { OpenCdmMediaengineImpl::OpenCdmMediaengineImpl(char *session_id_val, uint32_t session_id_len) { media_engine_com_ = &(RpcCdmMediaengineHandler::getInstance()); CDM_DLOG() << "Created new media engine impl "; if( !media_engine_com_->CreateMediaEngineSession(session_id_val, session_id_len, 0, 0)) { CDM_DLOG() << "Failed to create media engine session"; } } OpenCdmMediaengineImpl::OpenCdmMediaengineImpl(char *session_id_val, uint32_t session_id_len, uint8_t *auth_data_val, uint32_t auth_data_len) { // create media engine session media_engine_com_ = &(RpcCdmMediaengineHandler::getInstance()); if(!media_engine_com_->CreateMediaEngineSession(session_id_val, session_id_len, auth_data_val, auth_data_len)) { CDM_DLOG() << "Failed to create media engine session"; } } OpenCdmMediaengineImpl::~OpenCdmMediaengineImpl() { CDM_DLOG() << "OpenCdmMediaengineImpl destruct!"; } DecryptResponse OpenCdmMediaengineImpl::Decrypt(const uint8_t *pbIv, uint32_t cbIv, const uint8_t *pbData, uint32_t cbData, uint8_t *out, uint32_t &out_size) { printf("_------ Decrypt \n"); CDM_DLOG() << "OpenCdmMediaengineImpl::Decrypt: "; DecryptResponse response; response = media_engine_com_->Decrypt(pbIv, cbIv, pbData, cbData, out, out_size); return response; } int OpenCdmMediaengineImpl::ReleaseMem() { CDM_DLOG() << "OpenCdmMediaengineImpl::ReleaseMem "; int response; response = media_engine_com_->ReleaseMem(); return response; } } // namespace media
37.716216
78
0.601218
vishalbhoj
d007dd1f0b1cb50a338cc2ad623470753bf57881
2,149
cpp
C++
euhat/common/JyBuf.cpp
euhat/EuhatExpert
3932238a0bd72a8f12b4ae6ced1ade6482228fe0
[ "BSD-2-Clause" ]
null
null
null
euhat/common/JyBuf.cpp
euhat/EuhatExpert
3932238a0bd72a8f12b4ae6ced1ade6482228fe0
[ "BSD-2-Clause" ]
null
null
null
euhat/common/JyBuf.cpp
euhat/EuhatExpert
3932238a0bd72a8f12b4ae6ced1ade6482228fe0
[ "BSD-2-Clause" ]
null
null
null
#include <EuhatPreDef.h> #include <common/OpCommon.h> #include <common/JyDataStream.h> #include <common/md5.h> #include <common/JyDataCrypto.h> #include "JyBuf.h" #include <EuhatPostDef.h> JyBuf::JyBuf(int len) { reset(len); } JyBuf::JyBuf(const string& str) { reset(opMemDup(str.c_str(), str.length()), str.length()); } JyBuf::JyBuf(JyBuf&& in) { reset(std::move(in)); } JyBuf::~JyBuf() { } JyBuf& JyBuf::operator=(JyBuf&& in) { reset(std::move(in)); return *this; } void JyBuf::reset(JyBuf&& in) { data_.reset(in.data_.release()); size_ = in.size_; in.size_ = 0; } void JyBuf::reset(int len) { if (len > 0) data_.reset(new char[len]); else data_.reset(); size_ = len; } void JyBuf::reset(char *buf, int len) { data_.reset(buf); size_ = len; } JyBuf JyBuf::md5(const JyBuf& in) { JyBuf out(16); Md5Ctx md5; md5Init(&md5); md5Update(&md5, (unsigned char *)in.data_.get(), in.size_); md5Final(&md5, (unsigned char *)out.data_.get()); return std::move(out); } JyBuf JyBuf::xorData(const JyBuf& other) { JyDataWriteStream ds; ::xorData(ds, data_.get(), size_, other); JyBuf buf = std::move(ds.buf_); buf.size_ = ds.size(); return std::move(buf); } int JyBuf::eq(const JyBuf& other) { return size_ == other.size_ && opMemEq(data_.get(), other.data_.get(), size_); } JyBufPool::JyBufPool(int unitSize, int maxReserved) { unitSize_ = unitSize; maxReserved_ = maxReserved; } JyBufPool::~JyBufPool() { } void JyBufPool::get(JyBufGuard &guard) { WhMutexGuard g(&mutex_); guard.pool_ = this; if (pool_.size() == 0) { guard.reset(new char[unitSize_]); return; } guard.reset(pool_.front().release()); pool_.pop_front(); } void JyBufPool::ret(char *p) { WhMutexGuard guard(&mutex_); unique_ptr<char[]> ptr(p); pool_.push_back(move(ptr)); if (pool_.size() > (size_t)maxReserved_) pool_.pop_front(); } JyBufGuard::JyBufGuard() { pool_ = NULL; p_ = NULL; } JyBufGuard::~JyBufGuard() { reset(); } void JyBufGuard::reset(char *p) { if (NULL != p_) { pool_->ret(p_); } p_ = p; } char *JyBufGuard::release() { char *p = p_; p_ = NULL; return p; } char *JyBufGuard::get() { return p_; }
14.82069
79
0.651931
euhat
d00da18a0a2cbde1713a1834424e176d8bdde966
425
cpp
C++
math/kth_root_mod/gen/small.cpp
tko919/library-checker-problems
007a3ef79d1a1824e68545ab326d1523d9c05262
[ "Apache-2.0" ]
290
2019-06-06T22:20:36.000Z
2022-03-27T12:45:04.000Z
math/kth_root_mod/gen/small.cpp
tko919/library-checker-problems
007a3ef79d1a1824e68545ab326d1523d9c05262
[ "Apache-2.0" ]
536
2019-06-06T18:25:36.000Z
2022-03-29T11:46:36.000Z
math/kth_root_mod/gen/small.cpp
tko919/library-checker-problems
007a3ef79d1a1824e68545ab326d1523d9c05262
[ "Apache-2.0" ]
82
2019-06-06T18:17:55.000Z
2022-03-21T07:40:31.000Z
#include <iostream> bool is_prime(long long a){ for (long long div=2;div*div<=a;++div){ if(a%div==0)return false; } return true; } int main() { int t = 2397; printf("%d\n", t); int q=0; for (long long p=2;p<30;++p){ if (!is_prime(p))continue; for (long long k=0;k<p;++k){ for (long long y=0;y<p;++y){ printf("%lld %lld %lld\n", k, y, p); ++q; } } } return 0; }
17
44
0.501176
tko919
d01103efef5d7119a48afd53996f7d0d68957148
1,511
hpp
C++
source/hls/_FIRMWARE/shared_dram.hpp
somdipdey/Traffic_Analysis_Images__Dataset
9620c68ca71cda951a821aeaf89fcde6a7bb81fb
[ "MIT" ]
1
2019-02-22T12:23:31.000Z
2019-02-22T12:23:31.000Z
source/hls/_FIRMWARE/shared_dram.hpp
maxpark/MAT-CNN-SOPC
9620c68ca71cda951a821aeaf89fcde6a7bb81fb
[ "MIT" ]
1
2018-06-26T22:17:03.000Z
2018-06-26T22:17:34.000Z
source/hls/_FIRMWARE/shared_dram.hpp
somdipdey/MAT-CNN-FPGA_Traffic_Analysis_Using_CNNs_On_FPGA
9620c68ca71cda951a821aeaf89fcde6a7bb81fb
[ "MIT" ]
1
2018-06-29T09:59:33.000Z
2018-06-29T09:59:33.000Z
#ifndef SHARED_DRAM_H_9B5B43B5 #define SHARED_DRAM_H_9B5B43B5 #include <sys/mman.h> #include <fcntl.h> #include <err.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stddef.h> #include <stdint.h> #include "xfpga_hw.hpp" // Register addresses typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; // Location + Size of SHARED DRAM segment: // - from Vivado Block Designer (Address Editor): // AXI M memory bus starts at 0x00000000 – 0xFFFFFFFF, SIZE: 4GB // - from information by Simon Wright: // top 128MB of 1GB system memory are not OS-managed // - from "free -m" on Zynq: // total mem 882MB -> 118MB not OS-managed // -> place SHARED_DRAM at 896MB (-> max. activations ~100MB) // -> 896MB = 896*1024*1024 = 0x3800'0000 bytes // -> 96MB = 96*1024*1024 = 0x600'0000 bytes const off_t SHARED_DRAM_BASE_ADDR = 0x38000000; const size_t SHARED_DRAM_MEM_SIZE = 0x06000000; extern int SHARED_DRAM_FD; extern volatile u32* SHARED_DRAM_PTR; // External Interface bool SHARED_DRAM_open(); bool SHARED_DRAM_close(); volatile u32* SHARED_DRAM_virtual(); volatile u32* SHARED_DRAM_physical(); // Internal Functions volatile u32* map_SHARED_DRAM(off_t base_addr); void release_SHARED_DRAM(volatile u32* axilite); // unused: // 32-bit word read + write (other sizes not supported!) /* void shared_DRAM_write(u32 byte_addr, u32 value); u32 shared_DRAM_read(u32 byte_addr); */ #endif /* end of include guard: SHARED_DRAM_H_9B5B43B5 */
26.982143
68
0.733951
somdipdey
d011cc3e7e0512dd095e3bef663f0c6469948965
19,018
cpp
C++
moai/src/moaicore/MOAICameraFitter2D.cpp
jjimenezg93/ai-pathfinding
e32ae8be30d3df21c7e64be987134049b585f1e6
[ "MIT" ]
null
null
null
moai/src/moaicore/MOAICameraFitter2D.cpp
jjimenezg93/ai-pathfinding
e32ae8be30d3df21c7e64be987134049b585f1e6
[ "MIT" ]
null
null
null
moai/src/moaicore/MOAICameraFitter2D.cpp
jjimenezg93/ai-pathfinding
e32ae8be30d3df21c7e64be987134049b585f1e6
[ "MIT" ]
null
null
null
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #include "pch.h" #include <moaicore/MOAICameraAnchor2D.h> #include <moaicore/MOAICameraFitter2D.h> #include <moaicore/MOAIGfxDevice.h> #include <moaicore/MOAILogMessages.h> #include <moaicore/MOAITransform.h> #include <moaicore/MOAIViewport.h> //----------------------------------------------------------------// /** @name clearAnchors @text Remove all camera anchors from the fitter. @in MOAICameraFitter2D self @out nil */ int MOAICameraFitter2D::_clearAnchors ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) self->Clear (); return 0; } //----------------------------------------------------------------// /** @name clearFitMode @text Clears bits in the fitting mask. @in MOAICameraFitter2D self @opt number mask Default value is FITTING_MODE_MASK @out nil */ int MOAICameraFitter2D::_clearFitMode( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) u32 mask = state.GetValue < u32 >( 2, FITTING_MODE_MASK ); self->mFittingMode &= ~mask; return 0; } //----------------------------------------------------------------// /** @name getFitDistance @text Returns the distance between the camera's current x, y, scale and the target x, y, scale. As the camera approaches its target, the distance approaches 0. Check the value returned by this function against a small epsilon value. @in MOAICameraFitter2D self @out number distance */ int MOAICameraFitter2D::_getFitDistance ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) float distance = self->GetFitDistance (); lua_pushnumber ( state, distance ); return 1; } //----------------------------------------------------------------// /** @name getFitLoc @text Get the fitter location. @in MOAICameraFitter2D self @out number x @out number y */ int MOAICameraFitter2D::_getFitLoc ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) lua_pushnumber ( state, self->mFitLoc.mX ); lua_pushnumber ( state, self->mFitLoc.mY ); return 2; } //----------------------------------------------------------------// /** @name getFitMode @text Gets bits in the fitting mask. @in MOAICameraFitter2D self @out number mask */ int MOAICameraFitter2D::_getFitMode ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) state.Push ( self->mFittingMode ); return 1; } //----------------------------------------------------------------// /** @name getFitScale @text Returns the fit scale @in MOAICameraFitter2D self @out number scale */ int MOAICameraFitter2D::_getFitScale ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) lua_pushnumber ( state, self->mFitScale ); return 1; } //----------------------------------------------------------------// /** @name getTargetLoc @text Get the target location. @in MOAICameraFitter2D self @out number x @out number y */ int MOAICameraFitter2D::_getTargetLoc ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) lua_pushnumber ( state, self->mTargetLoc.mX ); lua_pushnumber ( state, self->mTargetLoc.mY ); return 2; } //----------------------------------------------------------------// /** @name getTargetScale @text Returns the target scale @in MOAICameraFitter2D self @out number scale */ int MOAICameraFitter2D::_getTargetScale ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) lua_pushnumber ( state, self->mTargetScale ); return 1; } //----------------------------------------------------------------// /** @name insertAnchor @text Add an anchor to the fitter. @in MOAICameraFitter2D self @in MOAICameraAnchor2D anchor @out nil */ int MOAICameraFitter2D::_insertAnchor ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "UU" ) MOAICameraAnchor2D* anchor = state.GetLuaObject < MOAICameraAnchor2D >( 2, true ); if ( anchor ) { self->AddAnchor ( *anchor ); } return 0; } //----------------------------------------------------------------// /** @name removeAnchor @text Remove an anchor from the fitter. @in MOAICameraFitter2D self @in MOAICameraAnchor2D anchor @out nil */ int MOAICameraFitter2D::_removeAnchor ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "UU" ) MOAICameraAnchor2D* anchor = state.GetLuaObject < MOAICameraAnchor2D >( 2, true ); if ( anchor ) { self->RemoveAnchor ( *anchor ); } return 0; } //----------------------------------------------------------------// /** @name setBounds @text Sets or clears the world bounds of the fitter. The camera will not move outside of the fitter's bounds. @overload @in MOAICameraFitter2D self @in number xMin @in number yMin @in number xMax @in number yMax @out nil @overload @in MOAICameraFitter2D self @out nil */ int MOAICameraFitter2D::_setBounds ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) if ( state.CheckParams ( 2, "NNNN" )) { float x0 = state.GetValue < float >( 2, 0.0f ); float y0 = state.GetValue < float >( 3, 0.0f ); float x1 = state.GetValue < float >( 4, 0.0f ); float y1 = state.GetValue < float >( 5, 0.0f ); self->mBounds.Init ( x0, y0, x1, y1 ); self->mFittingMode |= FITTING_MODE_APPLY_BOUNDS; } else { self->mFittingMode &= ~FITTING_MODE_APPLY_BOUNDS; } return 0; } //----------------------------------------------------------------// /** @name setCamera @text Set a MOAITransform for the fitter to use as a camera. The fitter will dynamically change the location and scale of the camera to keep all of the anchors on the screen. @in MOAICameraFitter2D self @opt MOAITransform camera Default value is nil. @out nil */ int MOAICameraFitter2D::_setCamera ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) self->mCamera.Set ( *self, state.GetLuaObject < MOAITransform >( 2, true )); return 0; } //----------------------------------------------------------------// /** @name setDamper @text Set's the fitter's damper coefficient. This is a scalar applied to the difference between the camera transform's location and the fitter's target location every frame. The smaller the coefficient, the tighter the fit will be. A value of '0' will not dampen at all; a value of '1' will never move the camera. @in MOAICameraFitter2D self @opt number damper Default value is 0. @out nil */ int MOAICameraFitter2D::_setDamper ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) self->mDamper = state.GetValue < float >( 2, 0.0f ); return 0; } //----------------------------------------------------------------// /** @name setFitLoc @text Set the fitter's location. @in MOAICameraFitter2D self @opt number x Default value is 0. @opt number y Default value is 0. @opt boolean snap Default value is false. @out nil */ int MOAICameraFitter2D::_setFitLoc ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) self->mFitLoc.mX = state.GetValue < float >( 2, 0.0f ); self->mFitLoc.mY = state.GetValue < float >( 3, 0.0f ); self->mFittingMode &= ~FITTING_MODE_APPLY_ANCHORS; self->UpdateTarget (); bool snap = state.GetValue < bool >( 4, false ); if ( snap && self->mCamera ) { self->SnapToTargetLoc ( *self->mCamera ); } return 0; } //----------------------------------------------------------------// /** @name setFitMode @text Sets bits in the fitting mask. @in MOAICameraFitter2D self @opt number mask Default value is FITTING_MODE_DEFAULT @out nil */ int MOAICameraFitter2D::_setFitMode ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) self->mFittingMode |= state.GetValue < u32 >( 2, FITTING_MODE_DEFAULT ); return 0; } //----------------------------------------------------------------// /** @name setFitScale @text Set the fitter's scale. @in MOAICameraFitter2D self @opt number scale Default value is 1. @opt boolean snap Default value is false. @out nil */ int MOAICameraFitter2D::_setFitScale ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) self->mFitScale = state.GetValue < float >( 2, 1.0f ); self->mFittingMode &= ~FITTING_MODE_APPLY_ANCHORS; self->UpdateTarget (); bool snap = state.GetValue < bool >( 3, false ); if ( snap && self->mCamera ) { self->SnapToTargetScale ( *self->mCamera ); } return 0; } //----------------------------------------------------------------// /** @name setMin @text Set the minimum number of world units to be displayed by the camera along either axis. @in MOAICameraFitter2D self @opt number min Default value is 0. @out nil */ int MOAICameraFitter2D::_setMin ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) self->mMin = state.GetValue < float >( 2, 0.0f ); return 0; } //----------------------------------------------------------------// /** @name setViewport @text Set the viewport to be used for fitting. @in MOAICameraFitter2D self @opt MOAIViewport viewport Default value is nil. @out nil */ int MOAICameraFitter2D::_setViewport ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) self->mViewport.Set ( *self, state.GetLuaObject < MOAIViewport >( 2, true )); return 0; } //----------------------------------------------------------------// /** @name snapToTarget @text Snap the camera to the target fitting. @overload Snap the fitter's camera transform to the target. @in MOAICameraFitter2D self @out nil @overload Snap a passed in transform to the target. @in MOAICameraFitter2D self @in MOAITransform @out nil */ int MOAICameraFitter2D::_snapToTarget ( lua_State* L ) { MOAI_LUA_SETUP ( MOAICameraFitter2D, "U" ) MOAITransform* camera = state.GetLuaObject < MOAITransform >( 2, true ); if ( camera ) { self->SnapToTargetLoc ( *camera ); self->SnapToTargetScale ( *camera ); } else { if ( self->mCamera ) { self->SnapToTargetLoc ( *self->mCamera ); self->SnapToTargetScale ( *self->mCamera ); } } return 0; } //================================================================// // MOAICameraFitter2D //================================================================// //----------------------------------------------------------------// void MOAICameraFitter2D::AddAnchor ( MOAICameraAnchor2D& anchor ) { if ( !this->mAnchors.contains ( &anchor )) { this->LuaRetain ( &anchor ); this->mAnchors.insert ( &anchor ); } } //----------------------------------------------------------------// void MOAICameraFitter2D::Clear () { while ( this->mAnchors.size ()) { AnchorIt anchorIt = this->mAnchors.begin (); MOAICameraAnchor2D* anchor = *anchorIt; this->mAnchors.erase ( anchorIt ); this->LuaRelease ( anchor ); } this->mCamera.Set ( *this, 0 ); this->mViewport.Set ( *this, 0 ); } //----------------------------------------------------------------// USRect MOAICameraFitter2D::GetAnchorRect () { // expand the world rect to include all the anchors AnchorIt anchorIt = this->mAnchors.begin (); USRect worldRect = ( *anchorIt )->GetRect (); ++anchorIt; for ( ; anchorIt != this->mAnchors.end (); ++anchorIt ) { MOAICameraAnchor2D* anchor = *anchorIt; worldRect.Grow ( anchor->GetRect ()); } // clip the world rect to the bounds if ( this->mFittingMode & FITTING_MODE_APPLY_BOUNDS ) { this->mBounds.Clip ( worldRect ); } // enforce the minimum float width = worldRect.Width (); float height = worldRect.Height (); float pad; if ( this->mMin > 0.0f ) { if ( width < this->mMin ) { pad = ( this->mMin - width ) * 0.5f; worldRect.mXMin -= pad; worldRect.mXMax += pad; } if ( height < this->mMin ) { pad = ( this->mMin - height ) * 0.5f; worldRect.mYMin -= pad; worldRect.mYMax += pad; } } return worldRect; } //----------------------------------------------------------------// void MOAICameraFitter2D::GetCamera ( USAffine3D& camera ) { camera.ScRoTr ( this->mTargetScale, this->mTargetScale, 1.0f, 0.0f, 0.0f, 0.0f, this->mTargetLoc.mX, this->mTargetLoc.mY, 0.0f ); } //----------------------------------------------------------------// float MOAICameraFitter2D::GetFitDistance () { if ( this->mCamera ) { USVec3D loc = this->mCamera->GetLoc (); float scale = this->mCamera->GetScl ().mX; USVec3D current ( loc.mX, loc.mY, scale ); USVec3D target ( this->mTargetLoc.mX, this->mTargetLoc.mY, this->mTargetScale ); return USDist::VecToVec ( current, target ); } return 0.0f; } //----------------------------------------------------------------// bool MOAICameraFitter2D::IsDone () { return false; } //----------------------------------------------------------------// MOAICameraFitter2D::MOAICameraFitter2D () : mMin ( 0.0f ), mDamper ( 0.0f ), mFittingMode ( FITTING_MODE_DEFAULT ) { RTTI_BEGIN RTTI_EXTEND ( MOAIAction ) RTTI_EXTEND ( MOAINode ) RTTI_END this->mFitLoc.Init ( 0.0f, 0.0f, 0.0f ); this->mFitScale = 1.0f; this->mTargetLoc.Init ( 0.0f, 0.0f, 0.0f ); this->mTargetScale = 1.0f; } //----------------------------------------------------------------// MOAICameraFitter2D::~MOAICameraFitter2D () { this->Clear (); } //----------------------------------------------------------------// void MOAICameraFitter2D::OnDepNodeUpdate () { this->UpdateFit (); this->UpdateTarget (); if ( this->mCamera ) { float d = 1.0f - USFloat::Clamp ( this->mDamper, 0.0f, 1.0f ); USVec3D loc = this->mCamera->GetLoc (); float scale = this->mCamera->GetScl ().mX; loc.mX += ( this->mTargetLoc.mX - loc.mX ) * d; loc.mY += ( this->mTargetLoc.mY - loc.mY ) * d; scale += ( this->mTargetScale - scale ) * d; USVec3D scaleVec; scaleVec.Init ( scale, scale, 1.0f ); this->mCamera->SetScl ( scaleVec ); this->mCamera->SetLoc ( loc ); this->mCamera->ScheduleUpdate (); } } //----------------------------------------------------------------// void MOAICameraFitter2D::OnUpdate ( float step ) { UNUSED ( step ); this->ScheduleUpdate (); // make sure all the anchors are ahead of fitter in the update schedule AnchorIt anchorIt = this->mAnchors.begin (); for ( ; anchorIt != this->mAnchors.end (); ++anchorIt ) { MOAICameraAnchor2D* anchor = *anchorIt; anchor->Activate ( *this ); } } //----------------------------------------------------------------// void MOAICameraFitter2D::RemoveAnchor ( MOAICameraAnchor2D& anchor ) { if ( this->mAnchors.contains ( &anchor )) { this->mAnchors.erase ( &anchor ); this->LuaRelease ( &anchor ); } } //----------------------------------------------------------------// void MOAICameraFitter2D::SnapToTargetLoc ( MOAITransform& camera ) { camera.SetLoc ( this->mTargetLoc ); camera.ScheduleUpdate (); } //----------------------------------------------------------------// void MOAICameraFitter2D::SnapToTargetScale ( MOAITransform& camera ) { USVec3D scaleVec; scaleVec.Init ( this->mTargetScale, this->mTargetScale, 1.0f ); camera.SetScl ( scaleVec ); camera.ScheduleUpdate (); } //----------------------------------------------------------------// void MOAICameraFitter2D::UpdateFit () { if ( !( this->mFittingMode & FITTING_MODE_APPLY_ANCHORS )) return; if ( !this->mAnchors.size ()) return; if ( !this->mViewport ) return; // reset the fitter this->mFitLoc.Init ( 0.0f, 0.0f, 0.0f ); this->mFitScale = 1.0f; // grab the view transform USMatrix4x4 ident; ident.Ident (); USMatrix4x4 wndToWorld = this->mViewport->GetWndToWorldMtx ( ident ); // grab the view rect in world space // TODO: take viewport offset into account USRect worldViewRect = this->mViewport->GetRect (); wndToWorld.Transform ( worldViewRect ); worldViewRect.Bless (); // build the anchor rect (clipped to bounds) USRect anchorRect = this->GetAnchorRect (); // fit the view rect around the target rect while preserving aspect ratio USRect fitViewRect = worldViewRect; anchorRect.FitOutside ( fitViewRect ); // get the fitting this->mFitScale = fitViewRect.Width () / worldViewRect.Width (); fitViewRect.GetCenter ( this->mFitLoc ); } //----------------------------------------------------------------// void MOAICameraFitter2D::UpdateTarget () { if ( !this->mViewport ) return; // reset the fitter this->mTargetLoc = this->mFitLoc; this->mTargetScale = this->mFitScale; // clamp to bounds if ( this->mFittingMode & FITTING_MODE_APPLY_BOUNDS ) { // grab the view transform USMatrix4x4 ident; ident.Ident (); USMatrix4x4 wndToWorld = this->mViewport->GetWndToWorldMtx ( ident ); // grab the view rect in world space // TODO: take viewport offset into account USRect worldViewRect = this->mViewport->GetRect (); wndToWorld.Transform ( worldViewRect ); worldViewRect.Bless (); // get the camera's target position and scale USAffine3D cameraMtx; float rot = this->mCamera ? this->mCamera->GetRot ().mZ : 0.0f; cameraMtx.ScRoTr ( this->mFitScale, this->mFitScale, 1.0f, 0.0f, 0.0f, rot * ( float )D2R, this->mFitLoc.mX, this->mFitLoc.mY, 0.0f ); // get the camera rect USRect cameraRect = worldViewRect; cameraMtx.Transform ( cameraRect ); cameraRect.Bless (); this->mBounds.ConstrainWithAspect ( cameraRect ); // get the fitting this->mTargetScale = cameraRect.Width () / worldViewRect.Width (); cameraRect.GetCenter ( this->mTargetLoc ); } } //----------------------------------------------------------------// void MOAICameraFitter2D::RegisterLuaClass ( MOAILuaState& state ) { MOAIAction::RegisterLuaClass ( state ); MOAINode::RegisterLuaClass ( state ); } //----------------------------------------------------------------// void MOAICameraFitter2D::RegisterLuaFuncs ( MOAILuaState& state ) { MOAIAction::RegisterLuaFuncs ( state ); MOAINode::RegisterLuaFuncs ( state ); state.SetField ( -1, "FITTING_MODE_SEEK_LOC", ( u32 )FITTING_MODE_SEEK_LOC ); state.SetField ( -1, "FITTING_MODE_SEEK_SCALE", ( u32 )FITTING_MODE_SEEK_SCALE ); state.SetField ( -1, "FITTING_MODE_APPLY_ANCHORS", ( u32 )FITTING_MODE_APPLY_ANCHORS ); state.SetField ( -1, "FITTING_MODE_APPLY_BOUNDS", ( u32 )FITTING_MODE_APPLY_BOUNDS ); state.SetField ( -1, "FITTING_MODE_DEFAULT", ( u32 )FITTING_MODE_DEFAULT ); state.SetField ( -1, "FITTING_MODE_MASK", ( u32 )FITTING_MODE_MASK ); luaL_Reg regTable [] = { { "clearAnchors", _clearAnchors }, { "clearFitMode", _clearFitMode }, { "getFitDistance", _getFitDistance }, { "getFitLoc", _getFitLoc }, { "getFitMode", _getFitMode }, { "getFitScale", _getFitScale }, { "getTargetLoc", _getTargetLoc }, { "getTargetScale", _getTargetScale }, { "insertAnchor", _insertAnchor }, { "removeAnchor", _removeAnchor }, { "setBounds", _setBounds }, { "setCamera", _setCamera }, { "setDamper", _setDamper }, { "setFitLoc", _setFitLoc }, { "setFitMode", _setFitMode }, { "setFitScale", _setFitScale }, { "setMin", _setMin }, { "setViewport", _setViewport }, { "snapToTarget", _snapToTarget }, { NULL, NULL } }; luaL_register ( state, 0, regTable ); }
27.723032
136
0.595331
jjimenezg93
d016c65b6c93c608d54d99c52c4a512c7f7617cd
6,369
hpp
C++
include/private/configuration.hpp
TetraSomia/liblapin
f5ee3ce9b0fff8459ec15d5e24287f2c16e5ae35
[ "BSD-3-Clause" ]
1
2021-06-14T19:26:42.000Z
2021-06-14T19:26:42.000Z
include/private/configuration.hpp
TetraSomia/liblapin
f5ee3ce9b0fff8459ec15d5e24287f2c16e5ae35
[ "BSD-3-Clause" ]
null
null
null
include/private/configuration.hpp
TetraSomia/liblapin
f5ee3ce9b0fff8459ec15d5e24287f2c16e5ae35
[ "BSD-3-Clause" ]
null
null
null
/* ** Jason Brillante "Damdoshi" ** Hanged Bunny Studio 2014-2016 ** ** ** Bibliotheque Lapin */ #ifndef __LAPIN_PRIVATE_CONFIGURATION_HPP__ # define __LAPIN_PRIVATE_CONFIGURATION_HPP__ # include <iomanip> # include <sstream> struct SmallConf; t_bunny_configuration *_bunny_read_ini(const char *code, t_bunny_configuration *config); t_bunny_configuration *_bunny_read_dabsic(const char *code, t_bunny_configuration *config); t_bunny_configuration *_bunny_read_xml(const char *code, t_bunny_configuration *config); t_bunny_configuration *_bunny_read_lua(const char *code, t_bunny_configuration *config); char *_bunny_write_ini(const t_bunny_configuration *config); char *_bunny_write_dabsic(const t_bunny_configuration *config); char *_bunny_write_xml(const t_bunny_configuration *config); char *_bunny_write_lua(const t_bunny_configuration *config); int chekchar(const char *str, ssize_t &index, const char *token); bool readchar(const char *str, ssize_t &index, const char *token); bool readtext(const char *str, ssize_t &index, const char *token); void skipspace(const char *str, ssize_t &i); bool readfield(const char *str, ssize_t &index); bool getfieldname(const char *code, ssize_t &i, char *out, ssize_t len, SmallConf &scope, bool overwrite); bool readdouble(const char *code, ssize_t &i, double &d); bool readinteger(const char *code, ssize_t &i, int &d); bool readstring(const char *code, ssize_t &i, char *d, ssize_t len); bool readrawchar(const char *code, ssize_t &i, char *d, ssize_t len, char endtok); bool readvalue(const char *code, ssize_t &i, SmallConf &nod, char endtok); int whichline(const char *code, int i); void writestring(std::stringstream &ss, std::string &str); bool read_data(const char *code, ssize_t &i, SmallConf &config); bool read_sequence(const char *code, ssize_t &i, SmallConf &config); bool read_function(const char *code, ssize_t &i, SmallConf &config); void writevalue(std::stringstream &ss, const SmallConf &cnf); extern const char *fieldname_first_char; extern const char *fieldname; extern const char *numbers; struct SmallConf { enum Type { INTEGER, DOUBLE, STRING, RAWSTRING }; std::map <std::string, SmallConf*> nodes; std::vector <SmallConf*> array; std::map< std::string, SmallConf* >::iterator iterator; std::string name; mutable bool have_value; mutable std::string original_value; mutable double converted; mutable int converted_2; mutable bool is_converted; static bool create_mode; SmallConf *father; Type last_type; void SetCreateMode(bool cm) { create_mode = cm; } std::map <std::string, SmallConf*> ::iterator Begin(void) { return (iterator = nodes.begin()); } std::map <std::string, SmallConf*> ::iterator End(void) { return (nodes.end()); } std::map <std::string, SmallConf*> ::iterator &It(void) { return (iterator); } size_t Size(void) const { return (array.size()); } SmallConf &operator[](const std::string &str) { SmallConf **slot; if (*(slot = &nodes[str]) == NULL) { if (create_mode) { *slot = new SmallConf; (*slot)->name = str; (*slot)->father = this; } else { nodes.erase(str); throw 0; } } return (**slot); } SmallConf &operator[](size_t i) { size_t olsize; if ((olsize = array.size()) <= i) { if (!create_mode) throw 0; array.resize(i + 1); while (olsize <= i) { std::stringstream ss; ss << this->name << "[" << i << "]"; array[olsize] = new SmallConf; array[olsize]->father = this; array[olsize]->name = ss.str(); olsize += 1; } } return (*array[i]); } bool Access(const std::string &str) { return (nodes.find(str) != nodes.end()); } bool Access(ssize_t i) { std::stringstream ss; ss << std::setfill('0') << std::setw(8) << i; return (nodes.find(ss.str()) != nodes.end()); } void SetString(const std::string &in, bool raw = false) { original_value = in; have_value = true; if (raw) last_type = RAWSTRING; else last_type = STRING; } bool GetString(const char **out) const { if (have_value == false) return (false); *out = original_value.c_str(); return (true); } void SetInt(int i) { std::stringstream ss; ss << i; original_value = ss.str(); converted_2 = converted = i; is_converted = true; have_value = true; last_type = INTEGER; } bool GetInt(int *i) const { double d; if (GetDouble(&d) == false) return (false); converted_2 = converted; *i = converted_2; return (true); } void SetDouble(double v) { std::stringstream ss; ss << v; original_value = ss.str(); converted_2 = converted = v; is_converted = true; have_value = true; last_type = DOUBLE; } bool GetDouble(double *v) const { if (have_value == false) return (false); if (is_converted == false) { ssize_t i; if (readdouble(original_value.c_str(), i, converted) == false) return (false); is_converted = true; } *v = converted; return (true); } SmallConf(void) : have_value(false), converted(0), converted_2(0), is_converted(false), father(NULL) {} ~SmallConf(void) { std::map<std::string, SmallConf*>::iterator it; std::map<std::string, SmallConf*> dup = nodes; if (father != NULL) father->nodes.erase(name); for (it = dup.begin(); it != dup.end(); ++it) delete it->second; } }; #endif /* __LAPIN_PRIVATE_CONFIGURATION_HPP__ */
22.347368
66
0.57403
TetraSomia