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
15ea3ecde4733a3e20052b4a81f09ee8400f6a40
713
cpp
C++
PRACTICE/cntMvs_Hanoi.cpp
prasantmahato/CP-Practice
54ca79117fcb0e2722bfbd1007b972a3874bef03
[ "MIT" ]
null
null
null
PRACTICE/cntMvs_Hanoi.cpp
prasantmahato/CP-Practice
54ca79117fcb0e2722bfbd1007b972a3874bef03
[ "MIT" ]
null
null
null
PRACTICE/cntMvs_Hanoi.cpp
prasantmahato/CP-Practice
54ca79117fcb0e2722bfbd1007b972a3874bef03
[ "MIT" ]
null
null
null
#include <iostream> #include <math.h> using namespace std; int num=0; void tower_of_brahma(int n,char a, char c,char b,char p) { if(n==0) exit(0); if(n==1) { cout<<"\nMove Disk "<<n<<" from "<<a<<" to "<<c; { if((a=='x' || b=='x'|| c=='x') && (a==p || b==p || c==p)) num++; } } else { tower_of_brahma(n-1,a,c,b,p); tower_of_brahma(n-1,a,b,c,p); tower_of_brahma(n-1,b,a,c,p); } } int main() { int n; char p; cin>>n>>p; tower_of_brahma(n,'X','Y','Z',p); cout<<"\n\nMoves:- "<<pow(2,n)-1<<endl; cout<<"\nNumber of Moves between X and "<<p<<" is "<<num; return 0; }
16.97619
69
0.4446
prasantmahato
15ebaa37a6285c8fb979107dbc94bfba7d7dee1b
142
hxx
C++
src/Providers/UNIXProviders/PolicyRuleValidityPeriod/UNIX_PolicyRuleValidityPeriod_ZOS.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
1
2020-10-12T09:00:09.000Z
2020-10-12T09:00:09.000Z
src/Providers/UNIXProviders/PolicyRuleValidityPeriod/UNIX_PolicyRuleValidityPeriod_ZOS.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
src/Providers/UNIXProviders/PolicyRuleValidityPeriod/UNIX_PolicyRuleValidityPeriod_ZOS.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
#ifdef PEGASUS_OS_ZOS #ifndef __UNIX_POLICYRULEVALIDITYPERIOD_PRIVATE_H #define __UNIX_POLICYRULEVALIDITYPERIOD_PRIVATE_H #endif #endif
11.833333
49
0.866197
brunolauze
15ecef24af6f7759bcada9beba84d795cc6dc336
22,295
hpp
C++
include/adl/std/string_view.hpp
flisboac/adl
a29f4ab2652e8146d4f97fd10f52526e4bc3563c
[ "MIT" ]
2
2021-01-12T12:04:09.000Z
2022-03-21T10:09:54.000Z
include/adl/std/string_view.hpp
flisboac/adl
a29f4ab2652e8146d4f97fd10f52526e4bc3563c
[ "MIT" ]
70
2017-02-25T16:37:48.000Z
2018-01-28T22:15:42.000Z
include/adl/std/string_view.hpp
flisboac/adl
a29f4ab2652e8146d4f97fd10f52526e4bc3563c
[ "MIT" ]
null
null
null
// $flisboac 2017-04-01 /** * @file string_view.hpp */ #ifndef adl__std__string_view__hpp__ #define adl__std__string_view__hpp__ #if adl_CONFIG_LANG_IS_CPP17 #include <string_view> #else #include "adl/char_helper.hpp" #endif #include <string> #include <iterator> #include <type_traits> #include <stdexcept> #include "adl.cfg.hpp" // // [[ API ]] // adl_BEGIN_ROOT_MODULE #if adl_CONFIG_LANG_IS_CPP17 template <typename Char, typename Traits = std::char_traits<Char>> using basic_string_view = std::basic_string_view<Char, Traits>; using string_view = std::string_view; using wstring_view = std::wstring_view; template <typename Char> using char_traits = std::char_traits<Char>; #else template <typename Char> using char_traits = char_helper<Char>; template <typename Char, typename Traits = char_traits<Char>> class basic_string_view; using string_view = basic_string_view<char>; using wstring_view = basic_string_view<wchar_t>; template <typename Char, typename Traits> class basic_string_view { private: using helper_ = char_helper<Char>; public: using traits_type = Traits; using value_type = Char; using pointer = Char*; using const_pointer = const Char*; using reference = Char&; using const_reference = const Char&; using size_type = std::size_t; using difference_type = std::ptrdiff_t; constexpr static const size_type npos = (size_type) -1; static_assert(std::is_same<value_type, typename traits_type::char_type>::value, "Character types must be the same."); class const_iterator { public: constexpr const_iterator() noexcept = default; constexpr const_iterator(const const_iterator&) = default; constexpr const_iterator(const Char* value, size_type size, size_type pos, bool reverse) noexcept; constexpr bool operator==(const_iterator rhs) const noexcept; constexpr bool operator!=(const_iterator rhs) const noexcept; constexpr bool operator>=(const_iterator rhs) const noexcept; constexpr bool operator> (const_iterator rhs) const noexcept; constexpr bool operator<=(const_iterator rhs) const noexcept; constexpr bool operator< (const_iterator rhs) const noexcept; constexpr const_iterator operator+(size_type rhs) const; constexpr const_iterator operator-(size_type rhs) const; constexpr const_iterator& operator+=(size_type rhs); constexpr const_iterator& operator-=(size_type rhs); constexpr const Char& operator*() const; constexpr const Char& operator[](size_type rhs) const; constexpr const_iterator& operator++(); constexpr const_iterator operator++(int); constexpr const_iterator& operator--(); constexpr const_iterator operator--(int); private: bool reverse_ = false; size_type size_ { 0 }; size_type pos_ { 0 }; const_pointer value_ { helper_::empty_c_str }; }; using iterator = const_iterator; using const_reverse_iterator = iterator; using reverse_iterator = const_reverse_iterator; // Constructors and assignments constexpr basic_string_view() noexcept = default; constexpr basic_string_view(const basic_string_view& rhs) noexcept = default; constexpr basic_string_view(const Char* s, size_type count) noexcept; constexpr basic_string_view(const Char* s); basic_string_view& operator=(const basic_string_view& rhs) noexcept = default; // Iterators constexpr const_iterator begin() const noexcept; constexpr const_iterator cbegin() const noexcept; constexpr const_iterator end() const noexcept; constexpr const_iterator cend() const noexcept; constexpr const_iterator rbegin() const noexcept; constexpr const_iterator crbegin() const noexcept; constexpr const_iterator rend() const noexcept; constexpr const_iterator crend() const noexcept; // Accessors and properties constexpr const_reference at(size_type pos) const; constexpr const_reference front() const; constexpr const_reference back() const; constexpr const_pointer data() const noexcept; constexpr size_type size() const noexcept; constexpr size_type length() const noexcept; constexpr size_type max_size() const noexcept; constexpr bool empty() const noexcept; // Operations inline size_type copy(Char* dest, size_type count, size_type pos = 0) const; constexpr basic_string_view substr(size_type pos = 0, size_type count = npos) const; constexpr int compare(basic_string_view rhs) const; constexpr int compare(size_type pos, size_type count, basic_string_view rhs) const; constexpr int compare( size_type pos1, size_type count1, basic_string_view rhs, size_type pos2, size_type count2 ) const; constexpr int compare(const Char* s) const; constexpr int compare(size_type pos1, size_type count1, const Char* s) const; constexpr int compare(size_type pos1, size_type count1, const Char* s, size_type count2) const; // Operators constexpr const_reference operator[](size_type pos) const; constexpr bool operator==(basic_string_view rhs) const; constexpr bool operator!=(basic_string_view rhs) const; constexpr bool operator< (basic_string_view rhs) const; constexpr bool operator<=(basic_string_view rhs) const; constexpr bool operator> (basic_string_view rhs) const; constexpr bool operator>=(basic_string_view rhs) const; private: constexpr int compare_result_(int cmp, size_t rhs_size) const; private: size_type size_ { 0 }; const_pointer value_ { helper_::empty_c_str }; }; #endif template <typename Char> std::string to_string(basic_string_view<Char> const& str); std::string to_string(std::string str); namespace literals { inline namespace string_view { constexpr basic_string_view<char> operator "" _sv(const char* str, std::size_t len) noexcept; constexpr basic_string_view<wchar_t> operator "" _sv(const wchar_t* str, std::size_t len) noexcept; constexpr basic_string_view<char16_t> operator "" _sv(const char16_t* str, std::size_t len) noexcept; constexpr basic_string_view<char32_t> operator "" _sv(const char32_t* str, std::size_t len) noexcept; } } template <typename T> adl_IAPI T const* string_printf_basic_arg_(basic_string_view<T> const& value) noexcept(false); adl_END_ROOT_MODULE #if !adl_CONFIG_LANG_IS_CPP17 template <class CharT, class Traits> std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, adl::basic_string_view<CharT, Traits> v ); template <typename Char, typename Traits> constexpr typename adl::basic_string_view<Char, Traits>::const_iterator operator+( typename adl::basic_string_view<Char, Traits>::size_type rhs, typename adl::basic_string_view<Char, Traits>::const_iterator iter ); template <typename Char, typename Traits> constexpr typename adl::basic_string_view<Char, Traits>::const_iterator operator-( typename adl::basic_string_view<Char, Traits>::size_type rhs, typename adl::basic_string_view<Char, Traits>::const_iterator iter ); #endif // // [[ IMPLEMENTATION ]] // adl_BEGIN_ROOT_MODULE // // functions // template <typename Char> adl_IMPL std::string to_string(basic_string_view<Char> const& str) { return std::string(str.data(), str.size()); } adl_IMPL std::string to_string(std::string str) { return str; } template <typename T> adl_IMPL T const* string_printf_basic_arg_(basic_string_view<T> const& value) noexcept(false) { throw std::invalid_argument("Cannot string_printf with a basic_string_view argument."); } namespace literals { inline namespace string_view { constexpr basic_string_view<char> operator ""_sv(const char* str, std::size_t len) noexcept { return basic_string_view<char>(str, len); } constexpr basic_string_view<wchar_t> operator ""_sv(const wchar_t* str, std::size_t len) noexcept { return basic_string_view<wchar_t>(str, len); } constexpr basic_string_view<char16_t> operator ""_sv(const char16_t* str, std::size_t len) noexcept { return basic_string_view<char16_t>(str, len); } constexpr basic_string_view<char32_t> operator ""_sv(const char32_t* str, std::size_t len) noexcept { return basic_string_view<char32_t>(str, len); } } } adl_END_ROOT_MODULE #if !adl_CONFIG_LANG_IS_CPP17 template <class CharT, class Traits> adl_IMPL std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, adl::basic_string_view<CharT, Traits> v) { auto string = adl::to_string(v); os << string; return os; } template <typename Char, typename Traits> constexpr typename adl::basic_string_view<Char, Traits>::const_iterator operator+( typename adl::basic_string_view<Char, Traits>::size_type rhs, typename adl::basic_string_view<Char, Traits>::const_iterator iter ) { return iter + rhs; } template <typename Char, typename Traits> constexpr typename adl::basic_string_view<Char, Traits>::const_iterator operator-( typename adl::basic_string_view<Char, Traits>::size_type rhs, typename adl::basic_string_view<Char, Traits>::const_iterator iter ) { return iter - rhs; } #endif // !adl_CONFIG_LANG_IS_CPP17 // // [[ TEMPLATE IMPLEMENTATION ]] // #if !adl_CONFIG_LANG_IS_CPP17 // // basic_string_view // adl_BEGIN_ROOT_MODULE template <typename Char, typename Traits> constexpr basic_string_view<Char, Traits>::basic_string_view( const Char* s, typename basic_string_view<Char, Traits>::size_type count ) noexcept : size_(count), value_(s) {} template <typename Char, typename Traits> constexpr basic_string_view<Char, Traits>::basic_string_view(const Char* s) : size_(helper_::length(s)), value_(s) {} template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator basic_string_view<Char, Traits>::begin() const noexcept { return const_iterator(value_, size_, 0, false); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator basic_string_view<Char, Traits>::cbegin() const noexcept { return const_iterator(value_, size_, 0, false); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator basic_string_view<Char, Traits>::end() const noexcept { return const_iterator(value_, size_, size_, false); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator basic_string_view<Char, Traits>::cend() const noexcept { return const_iterator(value_, size_, size_, false); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator basic_string_view<Char, Traits>::rbegin() const noexcept { return const_iterator(value_, size_, 0, true); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator basic_string_view<Char, Traits>::crbegin() const noexcept { return const_iterator(value_, size_, 0, true); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator basic_string_view<Char, Traits>::rend() const noexcept { return const_iterator(value_, size_, npos, true); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator basic_string_view<Char, Traits>::crend() const noexcept { return const_iterator(value_, size_, npos, true); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_reference basic_string_view<Char, Traits>::operator[]( typename basic_string_view<Char, Traits>::size_type pos ) const { return value_[pos]; } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_reference basic_string_view<Char, Traits>::at( basic_string_view::size_type pos ) const { return (pos < size_) ? value_[pos] : throw std::out_of_range("Index out of bounds"); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_reference basic_string_view<Char, Traits>::front() const { return this->operator[](0); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_reference basic_string_view<Char, Traits>::back() const { return this->operator[](size_ - 1); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_pointer basic_string_view<Char, Traits>::data() const noexcept { return value_; } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::size_type basic_string_view<Char, Traits>::size() const noexcept { return size_; } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::size_type basic_string_view<Char, Traits>::length() const noexcept { return size_; } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::size_type basic_string_view<Char, Traits>::max_size() const noexcept { return npos - 1; } template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::empty() const noexcept { return size_ == 0; } template <typename Char, typename Traits> typename basic_string_view<Char, Traits>::size_type basic_string_view<Char, Traits>::copy( Char* dest, basic_string_view::size_type count, basic_string_view::size_type pos ) const { size_t nchars = 0; const size_t chars_limit = size() - pos; const size_t max_chars = count < chars_limit ? count : chars_limit; if (pos >= size_) throw std::out_of_range("Index out of bounds"); for (nchars = 0; nchars < max_chars; ++nchars) dest[nchars] = value_[nchars + pos]; return nchars; } template <typename Char, typename Traits> constexpr basic_string_view<Char, Traits> basic_string_view<Char, Traits>::substr( basic_string_view::size_type pos, basic_string_view::size_type count ) const { return (pos < size_) ? count < size_ - pos ? basic_string_view(value_ + pos, count) : basic_string_view(value_ + pos, size_ - pos) : throw std::out_of_range("Index out of bounds"); } template <typename Char, typename Traits> constexpr int basic_string_view<Char, Traits>::compare(basic_string_view rhs) const { return compare_result_(Traits::compare(value_, rhs.value_, size_ < rhs.size_ ? size_ : rhs.size_), rhs.size_); } template <typename Char, typename Traits> constexpr int basic_string_view<Char, Traits>::compare( basic_string_view::size_type pos, basic_string_view::size_type count, basic_string_view rhs ) const { return substr(pos, count).compare(rhs); } template <typename Char, typename Traits> constexpr int basic_string_view<Char, Traits>::compare( basic_string_view::size_type pos1, basic_string_view::size_type count1, basic_string_view rhs, basic_string_view::size_type pos2, basic_string_view::size_type count2 ) const { return substr(pos1, count1).compare(rhs.substr(pos2, count2)); } template <typename Char, typename Traits> constexpr int basic_string_view<Char, Traits>::compare(const Char* s) const { return compare(basic_string_view(s)); } template <typename Char, typename Traits> constexpr int basic_string_view<Char, Traits>::compare( basic_string_view::size_type pos1, basic_string_view::size_type count1, const Char* s ) const { return substr(pos1, count1).compare(basic_string_view(s)); } template <typename Char, typename Traits> constexpr int basic_string_view<Char, Traits>::compare( basic_string_view::size_type pos1, basic_string_view::size_type count1, const Char* s, basic_string_view::size_type count2 ) const { return substr(pos1, count1).compare(basic_string_view(s, count2)); } template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::operator==(basic_string_view rhs) const { return compare(rhs) == 0; } template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::operator!=(basic_string_view rhs) const { return compare(rhs) != 0; } template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::operator<(basic_string_view rhs) const { return compare(rhs) < 0; } template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::operator<=(basic_string_view rhs) const { return compare(rhs) <= 0; } template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::operator>(basic_string_view rhs) const { return compare(rhs) > 0; } template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::operator>=(basic_string_view rhs) const { return compare(rhs) >= 0; } template <typename Char, typename Traits> constexpr int basic_string_view<Char, Traits>::compare_result_(int cmp, size_t rhs_size) const { return cmp == 0 ? size_ < rhs_size ? -1 : size_ > rhs_size ? 1 : 0 : cmp; } // // basic_string_view::const_iterator // template <typename Char, typename Traits> constexpr basic_string_view<Char, Traits>::const_iterator::const_iterator( const Char* value, basic_string_view::size_type size, basic_string_view::size_type pos, bool reverse ) noexcept : reverse_(reverse), size_(size), pos_(pos), value_(value) {} template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::const_iterator::operator==( basic_string_view::const_iterator rhs ) const noexcept { return pos_ == rhs.pos_; } template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::const_iterator::operator!=( basic_string_view::const_iterator rhs ) const noexcept { return pos_ != rhs.pos_; } template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::const_iterator::operator>=( basic_string_view::const_iterator rhs ) const noexcept { return pos_ >= rhs.pos_; } template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::const_iterator::operator>( basic_string_view::const_iterator rhs ) const noexcept { return pos_ > rhs.pos_; } template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::const_iterator::operator<=( basic_string_view::const_iterator rhs ) const noexcept { return pos_ <= rhs.pos_; } template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::const_iterator::operator<( basic_string_view::const_iterator rhs ) const noexcept { return pos_ < rhs.pos_; } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator basic_string_view<Char, Traits>::const_iterator::operator+( typename basic_string_view<Char, Traits>::size_type rhs ) const { return const_iterator(value_, size_, pos_ + rhs, reverse_); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator basic_string_view<Char, Traits>::const_iterator::operator-( typename basic_string_view<Char, Traits>::size_type rhs ) const { return const_iterator(value_, size_, pos_ - rhs, reverse_); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator& basic_string_view<Char, Traits>::const_iterator::operator+=( typename basic_string_view<Char, Traits>::size_type rhs ) { pos_ += rhs; return *this; } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator& basic_string_view<Char, Traits>::const_iterator::operator-=( typename basic_string_view<Char, Traits>::size_type rhs ) { pos_ -= rhs; return *this; } template <typename Char, typename Traits> constexpr const Char& basic_string_view<Char, Traits>::const_iterator::operator*() const { return value_[pos_]; } template <typename Char, typename Traits> constexpr const Char& basic_string_view<Char, Traits>::const_iterator::operator[]( typename basic_string_view<Char, Traits>::size_type rhs ) const { return value_[pos_ + rhs]; } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator& basic_string_view<Char, Traits>::const_iterator::operator++() { if (reverse_) { --pos_; } else { ++pos_; } return *this; } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator basic_string_view<Char, Traits>::const_iterator::operator++(int) { return const_iterator(value_, size_, reverse_ ? pos_-- : pos_++, reverse_); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator& basic_string_view<Char, Traits>::const_iterator::operator--() { if (reverse_) { ++pos_; } else { --pos_; } return *this; } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator basic_string_view<Char, Traits>::const_iterator::operator--(int) { return const_iterator(value_, size_, reverse_ ? pos_++ : pos_--, reverse_); } adl_END_ROOT_MODULE #endif #endif // adl__std__string_view__hpp__
33.831563
116
0.719847
flisboac
15f5fbbf52fa8d2cbc7eb0886eee9fcbd7631cba
967
cpp
C++
plugins/imageviewer2/src/imageviewer2.cpp
sellendk/megamol
0e4840b1897706c861946992ce3524bafab53352
[ "BSD-3-Clause" ]
null
null
null
plugins/imageviewer2/src/imageviewer2.cpp
sellendk/megamol
0e4840b1897706c861946992ce3524bafab53352
[ "BSD-3-Clause" ]
null
null
null
plugins/imageviewer2/src/imageviewer2.cpp
sellendk/megamol
0e4840b1897706c861946992ce3524bafab53352
[ "BSD-3-Clause" ]
null
null
null
/** * MegaMol * Copyright (c) 2009-2021, MegaMol Dev Team * All rights reserved. */ #include "mmcore/utility/plugins/AbstractPluginInstance.h" #include "mmcore/utility/plugins/PluginRegister.h" #include "imageviewer2/ImageRenderer.h" namespace megamol::imageviewer2 { class Imaggeviewer2PluginInstance : public megamol::core::utility::plugins::AbstractPluginInstance { REGISTERPLUGIN(Imaggeviewer2PluginInstance) public: Imaggeviewer2PluginInstance() : megamol::core::utility::plugins::AbstractPluginInstance("imageviewer2", "The imageviewer2 plugin."){}; ~Imaggeviewer2PluginInstance() override = default; // Registers modules and calls void registerClasses() override { // register modules this->module_descriptions.RegisterAutoDescription<megamol::imageviewer2::ImageRenderer>(); // register calls } }; } // namespace megamol::imageviewer2
30.21875
120
0.698035
sellendk
15f7e542004949e62ed8473a52c962fa9cfb8d32
3,450
cpp
C++
modules/task_3/pyatckin_n_integrals_rectangle/integrals_rectangle.cpp
Gurgen-Arm/pp_2021_autumn
ad549e49d765612c4544f34b04c9eb9432ac0dc7
[ "BSD-3-Clause" ]
null
null
null
modules/task_3/pyatckin_n_integrals_rectangle/integrals_rectangle.cpp
Gurgen-Arm/pp_2021_autumn
ad549e49d765612c4544f34b04c9eb9432ac0dc7
[ "BSD-3-Clause" ]
null
null
null
modules/task_3/pyatckin_n_integrals_rectangle/integrals_rectangle.cpp
Gurgen-Arm/pp_2021_autumn
ad549e49d765612c4544f34b04c9eb9432ac0dc7
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2021 Pyatckin Nikolai #include <math.h> #include <mpi.h> #include <random> #include <iostream> #include <algorithm> #include <functional> #include <vector> #include <utility> #include "../../../modules/task_3/pyatckin_n_integrals_rectangle/integrals_rectangle.h" double ParallelIntegral(std::function<double(const std::vector<double>)> func, std::vector <std::pair<double, double>> scope, const int num) { int dim = scope.size(); int num_rang; std::vector<double> local_scope(dim); std::vector<std::pair<double, double >> ranges(dim); int num_elem; int mrank; int numprocs, rank; MPI_Comm_size(MPI_COMM_WORLD, &numprocs); MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (numprocs < 4) { numprocs = 2 - numprocs % 2; mrank = numprocs; } else { numprocs = 4; mrank = 4; } ranges = scope; num_rang = num; num_elem = pow(num_rang, dim - 1); if (rank == 0) { for (int i = 0; i < dim; ++i) { local_scope[i] = (scope[i].second - scope[i].first) / num_rang; } } MPI_Bcast(&mrank, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(&num_elem, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(&num_rang, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(&local_scope[0], dim, MPI_DOUBLE, 0, MPI_COMM_WORLD); MPI_Bcast(&ranges[0], 2 * dim, MPI_DOUBLE, 0, MPI_COMM_WORLD); int rem = num_elem % numprocs; int count = num_elem / numprocs; std::vector<std::vector<double>> params(count); int tmp = 0; double sum = 0.0; if (rank < mrank) { if (rank < rem) { count++; tmp = rank * count; } else { tmp = rem * (count + 1) + (rank - rem) * count; } for (int i = 0; i < count; ++i) { int number = tmp + i; for (int j = 0; j < dim - 1; ++j) { int cef = number % num_rang; params[i].push_back(ranges[j].first + cef * local_scope[j] + local_scope[j] / 2); number /= num_rang; } } for (int i = 0; i < count; ++i) { for (int j = 0; j < num_rang; ++j) { params[i].push_back(ranges[dim - 1].first + j * local_scope[dim - 1] + local_scope[dim - 1] / 2); sum += func(params[i]); params[i].pop_back(); } } } double res = 0.0; MPI_Reduce(&sum, &res, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); for (int i = 0; i < dim; ++i) { res *= local_scope[i]; } return res; } double SeqIntegral(std::function<double(const std::vector<double>)> func, std::vector <std::pair<double, double>> scope, const int num) { int count = scope.size(); std::vector<double> local_scope(count); int64_t number = 1; for (int i = 0; i < count; ++i) { local_scope[i] = (scope[i].second - scope[i].first) / num; number *= num; } std::vector <double> params(count); double sum = 0.0; for (int i = 0; i < number; ++i) { int x = i; for (int j = 0; j < count; ++j) { int cef = x % num; params[j] = scope[j].first + cef * local_scope[j] + local_scope[j] / 2; x /= num; } sum += func(params); } for (int i = 0; i < count; ++i) { sum *= local_scope[i]; } return sum; }
30
87
0.526667
Gurgen-Arm
15f8d353eea57eae2457178605a9a659a97ae4e3
7,621
cpp
C++
src/TympanRemoteFormatter.cpp
jamescookmd/Tympan_Library
2d29cb8edbb281584668dd799f95eada11826b38
[ "MIT" ]
89
2017-03-25T19:27:07.000Z
2022-03-21T21:11:03.000Z
src/TympanRemoteFormatter.cpp
jamescookmd/Tympan_Library
2d29cb8edbb281584668dd799f95eada11826b38
[ "MIT" ]
43
2017-05-31T14:38:33.000Z
2022-03-29T09:34:58.000Z
src/TympanRemoteFormatter.cpp
jamescookmd/Tympan_Library
2d29cb8edbb281584668dd799f95eada11826b38
[ "MIT" ]
22
2017-03-07T22:15:59.000Z
2021-12-18T15:23:04.000Z
#include <TympanRemoteFormatter.h> String TR_Button::asString(void) { String s; //original method //s = "{'label':'" + label + "','cmd':'" + command + "','id':'" + id + "','width':'" + width + "'}"; //new method...don't waste time transmitting fields that don't exist s = "{"; if (label.length() > 0) s.concat("'label':'" + label + "',"); if (command.length() > 0) s.concat("'cmd':'" + command + "',"); if (id.length() > 0) s.concat("'id':'" + id + "',"); //if (width.length() > 0) s.concat("'width':'" + width + "'"); //no trailing comma s.concat("'width':'" + String(width) + "'"); //always have a width //if (s.endsWith(",")) s.remove(s.length()-1,1); //strip off trailing comma s.concat("}"); //close off the unit return s; } // //////////////////////////////////////////////////////////////////////////////////////////////////////// TR_Button* TR_Card::addButton(String label, String command, String id, int width) { //make a new button TR_Button *btn = new TR_Button(); if (btn==NULL) return btn; //return if we can't allocate it //link it to the previous button (linked list) TR_Button *prevLastButton = lastButton; if (prevLastButton != NULL) prevLastButton->nextButton = btn; //assign the new page to be the new last page lastButton = btn; nButtons++; //add the data btn->label = label; btn->prevButton = prevLastButton; btn->command = command; btn->id = id; btn->width = width; //we're done return btn; } TR_Button* TR_Card::getFirstButton(void) { TR_Button *btn = lastButton; if (btn == NULL) return NULL; //keep stepping back to find the first TR_Button *prev_btn = btn->prevButton; while (prev_btn != NULL) { btn = prev_btn; prev_btn = btn->prevButton; } return btn; } String TR_Card::asString(void) { String s; s = "{'name':'"+name+"'"; //write buttons TR_Button* btn = getFirstButton(); if (btn != NULL) { //write the first button s += ",'buttons':["; s += btn->asString(); //write other buttons TR_Button* next_button = btn->nextButton; while (next_button != NULL) { btn = next_button; s += ","; s += btn->asString(); next_button = btn->nextButton; } //finish the list s += "]"; } //close out s += "}"; return s; } // //////////////////////////////////////////////////////////////////////////////////////////////////////// TR_Card* TR_Page::addCard(String name) { //make a new card TR_Card *card = new TR_Card(); if (card==NULL) return card; //return if we can't allocate it //link it to the previous card (linked list) TR_Card *prevLastCard = lastCard; if (prevLastCard != NULL) prevLastCard->nextCard = card; //assign the new page to be the new last page lastCard = card; nCards++; //add the data card->name = name; card->prevCard = prevLastCard; //we're done return card; } TR_Card* TR_Page::getFirstCard(void) { TR_Card *card = lastCard; if (card == NULL) return NULL; //keep stepping back to find the first TR_Card *prev_card = card->prevCard; while (prev_card != NULL) { card = prev_card; prev_card = card->prevCard; } return card; } String TR_Page::asString(void) { String s; s = "{'title':'"+name+"'"; //write cards TR_Card* card = getFirstCard(); if (card != NULL) { //write first card s += ",'cards':["; s += card->asString(); //write additional cards TR_Card *next_card = card->nextCard; while (next_card != NULL) { card = next_card; s += ","; s += card->asString(); next_card = card->nextCard; } //finish the list s += "]"; } //close out s += "}"; return s; } // //////////////////////////////////////////////////////////////////////////////////////////////////////// TR_Page* TympanRemoteFormatter::addPage(String name) { //make a new page TR_Page *page = new TR_Page(); if (page==NULL) return page; //return if we can't allocate it //link it to the previous page (linked list) TR_Page *prevLastPage = lastPage; if (prevLastPage != NULL) prevLastPage->nextPage = page; //assign the new page to be the new last page lastPage = page; nCustomPages++; //add the data page->name = name; page->prevPage = prevLastPage; //we're done! return page; } void TympanRemoteFormatter::addPredefinedPage(String s) { if (predefPages.length()>0) { predefPages += ","; } predefPages += "'"+s+"'"; nPredefinedPages++; } TR_Page* TympanRemoteFormatter::getFirstPage(void) { TR_Page *page = lastPage; if (page == NULL) return NULL; //keep stepping back to find the first TR_Page *prev_page = page->prevPage; while (prev_page != NULL) { page = prev_page; prev_page = page->prevPage; } return page; } /* int TympanRemoteFormatter::c_str(char *c_str, int maxLen) { int dest=0, source=0; String s; s = String(F("JSON={'icon':'tympan.png',")); source = 0; while ((dest < maxLen) && (source < (int)s.length())) c_str[dest++] = s[source++]; // Add pages: if (nCustomPages > 0) { s = String("'pages':[") + pages[0].asString(); source = 0; while ((dest < maxLen) && (source < (int)s.length())) c_str[dest++] = s[source++]; } for (int i=1; i<nCustomPages; i++) { s = String(",") + pages[i].asString(); source = 0; while ((dest < maxLen) && (source < (int)s.length())) c_str[dest++] = s[source++]; } if (nCustomPages > 0) { s = String("]"); source = 0; while ((dest < maxLen) && (source < (int)s.length())) c_str[dest++] = s[source++]; } // Add predefined pages: if (predefPages.length()>1) { if (dest>0) { s = String(","); source = 0; while ((dest < maxLen) && (source < (int)s.length())) c_str[dest++] = s[source++]; } s = String(F("'prescription':{'type':'BoysTown','pages':[")) + predefPages + String("]}"); source = 0; while ((dest < maxLen) && (source < (int)s.length())) c_str[dest++] = s[source++]; } s = String("}"); source = 0; while ((dest < maxLen) && (source < (int)s.length())) c_str[dest++] = s[source++]; dest = min(dest,maxLen); c_str[dest] = '\0'; //null terminated return dest; } */ String TympanRemoteFormatter::asString(void) { String s; s = F("JSON={'icon':'tympan.png',"); // Add pages s += "'pages':["; //bool anyCustomPages = false; //we don't know yet TR_Page* page = getFirstPage(); if (page != NULL) { //anyCustomPages = true; //write the first page s += page->asString(); //add subsequent pages TR_Page* next_page = page->nextPage; while (next_page != NULL) { page = next_page; s += ","; s += page->asString(); next_page = page->nextPage; } } //close out the custom pages s += "]"; // Add predefined pages: if (predefPages.length()>1) { //if (s.length()>1) { s += ","; //} s += F("'prescription':{'type':'BoysTown','pages':[") + predefPages +"]}"; } //close out s += "}"; return s; } void TympanRemoteFormatter::asValidJSON(void) { String s; s = this->asString(); s.replace("'","\""); Serial.println(F("Pretty printed (a.k.a. valid json):")); Serial.println(s); } void TympanRemoteFormatter::deleteAllPages(void) { //loop through and delete each page that was created TR_Page *page = lastPage; while (page != NULL) { TR_Page *prev_page = page->prevPage; //look to the next loopo delete page; //delete the current page nCustomPages--; //decrement the count page = prev_page; //prepare for next loop if (page != NULL) page->nextPage = NULL; //there is no more next page lastPage = page; //update what the new lastPage is } //clear out the predefined pages predefPages = String(""); nPredefinedPages = 0; }
23.594427
107
0.583257
jamescookmd
15fc69abe3f37640a4c6717bcfc94f1fc05cfdbb
5,276
cpp
C++
source/systems/enemysystem.cpp
alohaeee/DungeonSlayer
b1a95031371b5f5b3be8f8d592a56140047e61da
[ "MIT" ]
41
2020-01-31T15:18:57.000Z
2022-03-12T05:48:21.000Z
source/systems/enemysystem.cpp
alohaeee/DungeonSlayer
b1a95031371b5f5b3be8f8d592a56140047e61da
[ "MIT" ]
2
2020-01-31T15:18:52.000Z
2022-02-16T12:21:45.000Z
source/systems/enemysystem.cpp
alohaeee/DungeonSlayer
b1a95031371b5f5b3be8f8d592a56140047e61da
[ "MIT" ]
4
2020-03-27T05:10:19.000Z
2021-02-22T09:18:34.000Z
#include "enemysystem.hpp" #include "../core.hpp" #include <queue> void EnemyCreate(Vector2D spawn) { auto enemy = registry.create(); registry.assign<Enemy>(enemy); auto &pos = registry.assign<Position>(enemy); pos.position = spawn; auto &rect = registry.assign<RectCollider>(enemy); auto &sprite = registry.assign<Sprite>(enemy); auto &speed = registry.assign<MovementSpeed>(enemy); [[maybe_unused]] auto &vel = registry.assign<Velocity>(enemy); registry.assign<Health>(enemy, 2); registry.assign<ParticleData>(enemy); registry.assign<Active>(enemy); speed.speed = 150; registry.assign<CollisionLayer>(enemy, LayersID::ENEMY); sprite.texture = textureCache.resource("spritesheet"); sprite.scale = {2, 2}; sprite.rect = spriteSheet[spriteSheet("zombie_idle").first->second]; sprite.layer = 2; sprite.isFliped = false; rect.rect.w = sprite.rect.w * sprite.scale.x(); rect.rect.h = sprite.rect.h * sprite.scale.y(); auto &animation = registry.assign<AnimationPool>(enemy); auto idle = spriteSheet.GetTypeFamily("zombie_idle"); auto run = spriteSheet.GetTypeFamily("zombie_run"); animation.data.emplace("idle", Animation{idle, 0.07f, 0, 0}); animation.data.emplace("run", Animation{run, 0.07f, 0, 0}); animation.current = "idle"; auto view = registry.create(); auto multiplier = registry.assign<View>(view); registry.assign<Active>(view); registry.assign<CollisionLayer>(view, LayersID::ENEMY); multiplier.multiplier = 12; registry.assign<Position>(view); auto &view_rect = registry.assign<RectCollider>(view); view_rect.rect.w = sprite.rect.w * sprite.scale.x() * multiplier.multiplier; view_rect.rect.h = sprite.rect.h * sprite.scale.y() * multiplier.multiplier; view_rect.rect.x = -view_rect.rect.w / 2 + sprite.rect.w * sprite.scale.x(); view_rect.rect.y = -view_rect.rect.h / 2 + sprite.rect.h * sprite.scale.y(); auto &parent = registry.assign<Hierarchy>(enemy); parent.child = view; auto &child = registry.assign<Hierarchy>(view); child.parent = enemy; } void UpdateView() { auto view = registry.view<Hierarchy, Position, RectCollider, View>(); view.each([](auto &hierarchy, auto &position, auto &rect, auto &view) { auto parent_pos = registry.get<Position>(hierarchy.parent); position.position.Set(parent_pos.position.x(), parent_pos.position.y()); }); } void EnemyCharging(const CollisionData &lhs, const CollisionData &rhs) { if (registry.has<View>(lhs.id) && registry.has<Player>(rhs.id)) { auto &&[player_pos, player] = registry.get<Position, Player>(rhs.id); auto parent = registry.get<Hierarchy>(lhs.id).parent; auto &&[enemy_pos, enemy_vel, enemy_speed, enemy] = registry.get<Position, Velocity, MovementSpeed, Enemy>(parent); enemy_vel.x = (player_pos.position.normalized()).x() * enemy_speed.speed; enemy_vel.y = (player_pos.position.normalized()).y() * enemy_speed.speed; if (enemy_pos.position.x() > player_pos.position.x()) { enemy_vel.x *= -1; } else { enemy_vel.x *= 1; } if (enemy_pos.position.y() > player_pos.position.y()) { enemy_vel.y *= -1; } else { enemy_vel.y *= 1; } enemy.isCharched = true; enemy.dt = 0; } } void EnemyWalking(const float dt) { auto view = registry.view<Enemy, Velocity, MovementSpeed, Active>(); view.each([dt](auto &enemy, auto &vel, auto &speed, const auto &) { if (enemy.dt > enemy.time) { if (vel.x || vel.y) { vel.x = 0; vel.y = 0; } else { auto result = std::rand() % 2; if (result) { result = std::rand() % 2; if (result) { vel.x = 0.5f * speed.speed; } else { vel.x = -0.5f * speed.speed; } } else { result = std::rand() % 2; if (result) { vel.y = 0.5f * speed.speed; } else { vel.y = -0.5f * speed.speed; } } } vel.y = 0; enemy.dt = 0; } enemy.dt += dt; }); } void HealthUpdate() { auto view = registry.view<Enemy, Health, Active, Position>(); for (auto &entt : view) { auto &health = view.get<Health>(entt); if (health.health <= 0) { auto &&[position, enemy] = view.get<Position, Enemy>(entt); position.position = Enemy::spawns[Enemy::currentSpawn]; Enemy::currentSpawn++; health.health = 2; if (Enemy::currentSpawn >= Enemy::MAX_SPAWNS) { Enemy::currentSpawn = 0; } } } }
30.674419
81
0.539803
alohaeee
15fe425b500e890081af3276130fa48b5feb2512
1,085
cpp
C++
Pagerank_viz/pagenode.cpp
Ybalrid/pagerank_stocha_4A
8f265ad70f5284374922ba7988baaf5c99085abd
[ "MIT" ]
null
null
null
Pagerank_viz/pagenode.cpp
Ybalrid/pagerank_stocha_4A
8f265ad70f5284374922ba7988baaf5c99085abd
[ "MIT" ]
null
null
null
Pagerank_viz/pagenode.cpp
Ybalrid/pagerank_stocha_4A
8f265ad70f5284374922ba7988baaf5c99085abd
[ "MIT" ]
null
null
null
#include "pagenode.h" PageNode::PageNode(QString accessUrl) : url(accessUrl), elipse(nullptr), urlTag(nullptr), active(false), rank(0) { } void PageNode::linkTo(PageNode *otherPage) { linkedPages.push_back(otherPage); qDebug() << "Page " << url << " has an hyperlink to " << otherPage->getUrl(); } QString PageNode::getUrl() { return url; } QGraphicsEllipseItem* PageNode::getVisualNode() { return elipse; } QGraphicsTextItem* PageNode::getUrlTag() { return urlTag; } void PageNode::setElipse(QGraphicsEllipseItem *e) { elipse = e; } void PageNode::setUrlTag(QGraphicsTextItem *t) { urlTag = t; } QVector<PageNode*> PageNode::getLinkedPagesVector() { return linkedPages; } void PageNode::setActive(bool activeState) { active = activeState; } bool PageNode::isActive() { return active; } void PageNode::resetRank() { rank = 0; } void PageNode::incraseRank() { rank++; } float PageNode::getNormalizedRank(float maxRank) { return 10.0f * (rank/maxRank); } float PageNode::getRank() { return rank; }
13.910256
80
0.668203
Ybalrid
15fedd99cf14f5ba20b3ebde86fb4f81c78b372f
3,082
cpp
C++
Magic-Name/main.cpp
KSCreator/General-Programs
b51cb9cc36e6eda72f3b402e278f25b512e9daa2
[ "MIT" ]
null
null
null
Magic-Name/main.cpp
KSCreator/General-Programs
b51cb9cc36e6eda72f3b402e278f25b512e9daa2
[ "MIT" ]
null
null
null
Magic-Name/main.cpp
KSCreator/General-Programs
b51cb9cc36e6eda72f3b402e278f25b512e9daa2
[ "MIT" ]
null
null
null
/* author : Keshav Sahu */ #include <cstdio> #include <cstring> #include <cctype> #include <cstdlib> using namespace std; void print(char c) { if(islower(c)) c = toupper(c); switch(c) { case 'A': printf("ooooo\no o\nooooo\no o\no o\n\n\n"); break; case 'B': printf("oooo \no o\nooooo\no o\noooo \n\n\n"); break; case 'C': printf(" oooo\no \no \no \n oooo\n\n\n"); break; case 'D': printf("oooo \n o o\n o o\n o o\noooo \n\n\n"); break; case 'E': printf("ooooo\no \nooooo\no \nooooo\n\n\n"); break; case 'F': printf("ooooo\no \nooooo\no \no \n\n\n"); break; case 'G': printf("ooooo\no o\no \no ooo\nooo o\n\n\n"); break; case 'H': printf("o o\no o\nooooo\no o\no o\n\n\n"); break; case 'I': printf(" o \n o \n o \n o \n o \n\n\n"); break; case 'J': printf(" oo \n o \n o \n o o \n ooo \n\n\n"); break; case 'K': printf(" o o\n o o \n oo \n o o \n o o\n\n\n"); break; case 'L': printf(" o \n o \n o \n o o\n oooo\n\n\n"); break; case 'M': printf(" o o \no o o\no o o\no o\no o\n\n\n"); break; case 'N': printf("o o\noo o\no o o\no oo\no o\n\n\n"); break; case 'O': printf("ooooo\no o\no o\no o\nooooo\n\n\n"); break; case 'P': printf("ooooo\no o\nooooo\no \no \n\n\n"); break; case 'Q': printf("oooo \no o \no o \noooo \n o\n\n\n"); break; case 'R': printf("ooooo\no o\noooo \no o \no o\n\n\n"); break; case 'S': printf("ooooo\no \nooooo\n o\nooooo\n\n\n"); break; case 'T': printf("ooooo\n o \n o \n o \n o \n\n\n"); break; case 'U': printf("o o\no o\no o\no o\n ooo \n\n\n"); break; case 'V': printf("o o\no o\no o\n o o \n o \n\n\n"); break; case 'W': printf("o o\no o\no o o\no o o\noo oo\n\n\n"); break; case 'X': printf("o o\n o o \n o \n o o \no o\n\n\n"); break; case 'Y': printf("o o\n o o \n o \n o \n o \n\n\n"); break; case 'Z': printf("ooooo\n o \n o \n o \nooooo\n\n\n"); break; case ' ': printf("\n\n\n\n\n\n\n"); break; default: printf("\n not \nsupported\ncharacter\n\n\n\n"); } } void print(char name[],int len) { for (int i = 0; i < len; i++) { print(name[i]); } } int main() { char name[20]; printf("Enter Your Name\n"); scanf("%[^\n]",name); int len = strlen(name); printf("View the magic\n\n\n"); print(name,len); system("pause"); return 0; }
24.656
58
0.41207
KSCreator
c600a2b7c9054ffe775bb57ef175a0f3f6e8ae76
11,795
cpp
C++
Src/Celbody/Moon/ELP82.cpp
Ybalrid/orbiter
7bed82f845ea8347f238011367e07007b0a24099
[ "MIT" ]
1,040
2021-07-27T12:12:06.000Z
2021-08-02T14:24:49.000Z
Src/Celbody/Moon/ELP82.cpp
Ybalrid/orbiter
7bed82f845ea8347f238011367e07007b0a24099
[ "MIT" ]
20
2021-07-27T12:25:22.000Z
2021-08-02T12:22:19.000Z
Src/Celbody/Moon/ELP82.cpp
Ybalrid/orbiter
7bed82f845ea8347f238011367e07007b0a24099
[ "MIT" ]
71
2021-07-27T14:19:49.000Z
2021-08-02T05:51:52.000Z
#include <math.h> #include <fstream> #include "OrbiterAPI.h" using namespace std; // #define INCLUDE_TIDAL_PERT // Uncomment this to add higher-order perturbation terms // (tidal, relativistic, solar eccentricity) // Warning: Using this can lead to inconsistencies since these // effects are not currently modelled in Orbiter's dynamic model. // =========================================================== // Global variables // =========================================================== typedef double SEQ3[3]; typedef double SEQ6[6]; static const double cpi = 3.141592653589793; static const double cpi2 = 2.0*cpi; static const double pis2 = cpi/2.0; static const double rad = 648000.0/cpi; static const double deg = cpi/180.0; static const double c1 = 60.0; static const double c2 = 3600.0; static const double ath = 384747.9806743165; static const double a0 = 384747.9806448954; static const double am = 0.074801329518; static const double alpha = 0.002571881335; static const double dtasm = 2.0*alpha/(3.0*am); static const double mjd2000 = 51544.5; // mjd->dj2000 offset static const double sc = 36525.0; static const double precess = 5029.0966/rad; static bool need_terms = true; // need to read terms? static const double def_prec = 1e-5; // default precision static double cur_prec = -1.0; // current precision static double delnu, dele, delg, delnp, delep; static double p1, p2, p3, p4, p5, q1, q2, q3, q4, q5; static double w[3][5], p[8][2], eart[5], peri[5], del[4][5], zeta[2]; static int nterm[3][12], nrang[3][12]; // current length of term sequences static SEQ6 *pc[3] = {0,0,0}; // main term sequences static SEQ3 *per[3] = {0,0,0}; // perturbation term sequences // =========================================================== // ELP82_init () // Set up invariant global parameters for ELP82 solver // =========================================================== void ELP82_init () { // Lunar arguments w[0][0] = (218.0+18.0/c1+59.95571/c2)*deg; w[1][0] = (83.0+21.0/c1+11.67475/c2)*deg; w[2][0] = (125.0+2.0/c1+40.39816/c2)*deg; eart[0] = (100.0+27.0/c1+59.22059/c2)*deg; peri[0] = (102.0+56.0/c1+14.42753/c2)*deg; w[0][1] = 1732559343.73604/rad; w[1][1] = 14643420.2632/rad; w[2][1] = -6967919.3622/rad; eart[1] = 129597742.2758/rad; peri[1] = 1161.2283/rad; w[0][2] = -5.8883/rad; w[1][2] = -38.2776/rad; w[2][2] = 6.3622/rad; eart[2] = -0.0202/rad; peri[2] = 0.5327/rad; w[0][3] = 0.6604e-2/rad; w[1][3] = -0.45047e-1/rad; w[2][3] = 0.7625e-2/rad; eart[3] = 0.9e-5/rad; peri[3] = -0.138e-3/rad; w[0][4] = -0.3169e-4/rad; w[1][4] = 0.21301e-3/rad; w[2][4] = -0.3586e-4/rad; eart[4] = 0.15e-6/rad; peri[4] = 0.0; // Planetary arguments p[0][0] = (252.0+15.0/c1+3.25986/c2)*deg; p[1][0] = (181.0+58.0/c1+47.28305/c2)*deg; p[2][0] = eart[0]; p[3][0] = (355.0+25.0/c1+59.78866/c2)*deg; p[4][0] = (34.0+21.0/c1+5.34212/c2)*deg; p[5][0] = (50.0+4.0/c1+38.89694/c2)*deg; p[6][0] = (314.0+3.0/c1+18.01841/c2)*deg; p[7][0] = (304.0+20.0/c1+55.19575/c2)*deg; p[0][1] = 538101628.68898/rad; p[1][1] = 210664136.43355/rad; p[2][1] = eart[1]; p[3][1] = 68905077.59284/rad; p[4][1] = 10925660.42861/rad; p[5][1] = 4399609.65932/rad; p[6][1] = 1542481.19393/rad; p[7][1] = 786550.32074/rad; // Corrections of the constants (fit to DE200/LE200) delnu = +0.55604/rad/w[0][1]; dele = +0.01789/rad; delg = -0.08066/rad; delnp = -0.06424/rad/w[0][1]; delep = -0.12879/rad; // Delaunay's arguments for (int i = 0; i < 5; i++) { del[0][i] = w[0][i] - eart[i]; del[3][i] = w[0][i] - w[2][i]; del[2][i] = w[0][i] - w[1][i]; del[1][i] = eart[i] - peri[i]; } del[0][0] = del[0][0] + cpi; zeta[0] = w[0][0]; zeta[1] = w[0][1] + precess; // Precession matrix p1 = 0.10180391e-4; p2 = 0.47020439e-6; p3 = -0.5417367e-9; p4 = -0.2507948e-11; p5 = 0.463486e-14; q1 = -0.113469002e-3; q2 = 0.12372674e-6; q3 = 0.1265417e-8; q4 = -0.1371808e-11; q5 = -0.320334e-14; } // =========================================================== // ELP82_exit () // Cleanup procedures // =========================================================== void ELP82_exit () { if (cur_prec >= 0.0) { for (int i = 0; i < 3; i++) { if (pc[i]) { delete []pc[i]; pc[i] = 0; } if (per[i]) { delete []per[i]; per[i] = 0; } } } cur_prec = -1.0; } // =========================================================== // ELP82_read () // Read the perturbation terms from file and store in global // parameters. The number of terms read depends on requested precision. // =========================================================== int ELP82_read (double prec) { // Term structure interfaces typedef struct { int ilu[4]; double coef[7]; } MainBin; typedef struct { int iz; int ilu[4]; double pha, x, per; } FigurBin; typedef struct { short ipla[11]; double pha, x, per; } PlanPerBin; // Check for existing terms if (cur_prec >= 0.0) { if (prec == cur_prec) return 0; // nothing to do for (int i = 0; i < 3; i++) { if (pc[i]) { delete []pc[i]; pc[i] = 0; } // remove existing terms if (per[i]) { delete []per[i]; per[i] = 0; } } } int ific, itab, m, mm, i, im, ir, k, ntot = 0, mtot = 0; double tgv, xx, y, pre[3], zone[6]; // Precision paremeters pre[0] = prec*rad; pre[1] = prec*rad; pre[2] = prec*ath; const char *datf = "Config\\Moon\\Data\\ELP82.dat"; ifstream ifs (datf); // term data stream if (!ifs) { oapiWriteLogError("ELP82: Data file not found: %s", datf); return -1; } // Read terms for main problem for (ific = 0; ific < 3; ific++) { ifs >> m; // number of terms available in sequence MainBin *block = new MainBin[m]; // temporary storage for terms for (ir = mm = 0; ir < m; ir++) { // read terms from file for (i = 0; i < 4; i++) ifs >> block[ir].ilu[i]; for (i = 0; i < 7; i++) ifs >> block[ir].coef[i]; if (fabs(block[ir].coef[0]) >= pre[ific]) mm++; // number of terms used } ntot += mm; mtot += m; if (mm) pc[ific] = new SEQ6[mm]; itab = 0; for (im = ir = 0; im < m; im++) { MainBin &lin = block[im]; xx = lin.coef[0]; if (fabs(xx) < pre[ific]) continue; tgv = lin.coef[1] + dtasm*lin.coef[5]; if (ific == 2) lin.coef[0] -= 2.0*lin.coef[0]*delnu/3.0; xx = lin.coef[0] + tgv*(delnp-am*delnu) + lin.coef[2]*delg + lin.coef[3]*dele + lin.coef[4]*delep; zone[0] = xx; for (k = 0; k <= 4; k++) { y = 0.0; for (i = 0; i < 4; i++) { y += lin.ilu[i]*del[i][k]; } zone[k+1] = y; } if (ific == 2) zone[1] += pis2; for (i = 0; i < 6; i++) pc[ific][ir][i] = zone[i]; ir++; } nterm[ific][0] = ir; nrang[ific][0] = 0; delete []block; } #ifdef INCLUDE_TIDAL_PERT int iv, j; // Read terms for tides, relativity, solar eccentricity (part 1) for (ific = 0; ific < 3; ific++) { iv = ific % 3; ifs >> m; FigurBin *block = new FigurBin[m]; for (ir = mm = 0; ir < m; ir++) { ifs >> block[ir].iz; for (i = 0; i < 4; i++) ifs >> block[ir].ilu[i]; ifs >> block[ir].pha >> block[ir].x >> block[ir].per; if (block[ir].x >= pre[iv]) mm++; } ntot += mm; mtot += m; if (mm) per[ific] = new SEQ3[mm]; itab = (ific/3) + 1; for (im = ir = 0; im < m; im++) { FigurBin &lin = block[im]; xx = lin.x; if (lin.x < pre[iv]) continue; zone[0] = xx; for (k = 0; k <= 1; k++) { y = (k ? lin.pha*deg : 0.0); y += lin.iz*zeta[k]; for (i = 0; i < 4; i++) y += lin.ilu[i]*del[i][k]; zone[k+1] = y; } j = nrang[iv][itab-1] + ir; for (i = 0; i < 3; i++) per[iv][i][j] = zone[i]; ir++; } nterm[iv][itab] = ir; nrang[iv][itab] = nrang[iv][itab-1] + nterm[iv][itab]; delete []block; } #endif // INCLUDE_TIDAL_PERT // Add: PlanetaryPerturbations // Add: FiguresTides oapiWriteLogV("ELP82: Precision %0.1le, Terms %d/%d", prec, ntot, mtot); need_terms = false; cur_prec = prec; return 0; } // =========================================================== // ELP82 () // Calculate lunar ephemeris using ELP2000-82 perturbation solutions // MS modifications: // - Time input is MJD instead of JD // - Added time derivatives (output in r[3] to r[5]) // =========================================================== int ELP82 (double mjd, double *r) { int k, iv, nt; double t[5]; double x, y, x1, x2, x3, pw, qw, ra, pwqw, pw2, qw2; double x_dot, y_dot, x1_dot, x2_dot, x3_dot, pw_dot, qw_dot; double ra_dot, pwqw_dot, pw2_dot, qw2_dot; double cosr0, sinr0, cosr1, sinr1; // Initialisation if (need_terms) ELP82_read (def_prec); // substitution of time t[0] = 1.0; t[1] = (mjd-mjd2000)/sc; t[2] = t[1]*t[1]; t[3] = t[2]*t[1]; t[4] = t[3]*t[1]; for (iv = 0; iv < 3; iv++) { r[iv] = r[iv+3] = 0.0; SEQ6 *pciv = pc[iv]; // main sequence (itab=0) for (nt = 0; nt < nterm[iv][0]; nt++) { x = pciv[nt][0]; x_dot = 0.0; y = pciv[nt][1]; y_dot = 0.0; for (k = 1; k <= 4; k++) { y += pciv[nt][k+1] * t[k]; y_dot += pciv[nt][k+1] * t[k-1] * k; } r[iv] += x*sin(y); r[iv+3] += x_dot*sin(y) + x*cos(y)*y_dot; } #ifdef INCLUDE_TIDAL_PERT int itab, j; // perturbation sequences (itab>0) for (itab = 1; itab < 2/*12*/; itab++) { for (nt = 0; nt < nterm[iv][itab]; nt++) { j = nrang[iv][itab-1] + nt; x = per[iv][0][j]; y = per[iv][1][j] + per[iv][2][j] * t[1]; if (itab == 2 || itab == 4 || itab == 6 || itab == 8) { x_dot = x; x *= t[1]; } if (itab == 11) { x_dot = x * t[1] * 2.0; x *= t[2]; } r[iv] += x*sin(y); r[iv+3] += x_dot*sin(y) + x*cos(y)*y_dot; } } #endif // INCLUDE_TIDAL_PERT } // Change of coordinates r[0] = r[0]/rad + w[0][0] + w[0][1]*t[1] + w[0][2]*t[2] + w[0][3]*t[3] + w[0][4]*t[4]; r[3] = r[3]/rad + w[0][1] + 2*w[0][2]*t[1] + 3*w[0][3]*t[2] + 4*w[0][4]*t[3]; r[1] = r[1]/rad; r[4] = r[4]/rad; r[2] = r[2]*a0/ath; r[5] = r[5]*a0/ath; cosr0 = cos(r[0]), sinr0 = sin(r[0]); cosr1 = cos(r[1]), sinr1 = sin(r[1]); x1 = r[2]*cosr1; x1_dot = r[5]*cosr1 - r[2]*sinr1*r[4]; x2 = x1*sinr0; x2_dot = x1_dot*sinr0 + x1*cosr0*r[3]; x1_dot = x1_dot*cosr0 - x1*sinr0*r[3]; x1 = x1*cosr0; x3 = r[2]*sinr1; x3_dot = r[5]*sinr1 + r[2]*cosr1*r[4]; pw = (p1+p2*t[1]+p3*t[2]+p4*t[3]+p5*t[4])*t[1]; pw_dot = p1 + 2*p2*t[1] + 3*p3*t[2] + 4*p4*t[3] + 5*p5*t[4]; qw = (q1+q2*t[1]+q3*t[2]+q4*t[3]+q5*t[4])*t[1]; qw_dot = q1 + 2*q2*t[1] + 3*q3*t[2] + 4*q4*t[3] + 5*q5*t[4]; ra = 2.0*sqrt(1-pw*pw-qw*qw); ra_dot = -4.0*(pw+qw)/ra; pwqw = 2.0*pw*qw; pwqw_dot = 2.0*(pw_dot*qw + pw*qw_dot); pw2 = 1-2.0*pw*pw; pw2_dot = -4.0*pw; qw2 = 1-2.0*qw*qw; qw2_dot = -4.0*qw; pw = pw*ra; pw_dot = pw_dot*ra + pw*ra_dot; qw = qw*ra; qw_dot = qw_dot*ra + qw*ra_dot; // at this point we swap y and z components to conform with orbiter convention // r[1] <-> r[2] and r[4] <-> r[5] r[0] = pw2*x1+pwqw*x2+pw*x3; r[3] = pw2_dot*x1 + pw2*x1_dot + pwqw_dot*x2 + pwqw*x2_dot + pw_dot*x3 + pw*x3_dot; r[2] = pwqw*x1+qw2*x2-qw*x3; r[5] = pwqw_dot*x1 + pwqw*x1_dot + qw2_dot*x2 + qw2*x2_dot - qw_dot*x3 - qw*x3_dot; r[1] = -pw*x1+qw*x2+(pw2+qw2-1)*x3; r[4] = -pw_dot*x1 - pw*x1_dot + qw_dot*x2 + qw*x2_dot + (pw2_dot+qw2_dot)*x3 + (pw2+qw2-1)*x3_dot; // ========= End of ELP82 code ========= // Below is conversion to Orbiter format // convert to m and m/s static double pscale = 1e3; static double vscale = 1e3/(86400.0*sc); r[0] *= pscale; r[1] *= pscale; r[2] *= pscale; r[3] *= vscale; r[4] *= vscale; r[5] *= vscale; return 0; }
27.303241
99
0.519118
Ybalrid
c60449d7a65fc4646ff830bb201ff8f7875eea77
2,357
cpp
C++
MORE CODING PLATFORMS/SPOJ/cot.cpp
Autoratch/CodeChef
6937e6b442e19df90a65f772939db9ab1a07a1b3
[ "Apache-2.0" ]
null
null
null
MORE CODING PLATFORMS/SPOJ/cot.cpp
Autoratch/CodeChef
6937e6b442e19df90a65f772939db9ab1a07a1b3
[ "Apache-2.0" ]
null
null
null
MORE CODING PLATFORMS/SPOJ/cot.cpp
Autoratch/CodeChef
6937e6b442e19df90a65f772939db9ab1a07a1b3
[ "Apache-2.0" ]
null
null
null
// https://www.spoj.com/problems/COT/ #include <bits/stdc++.h> using namespace std; const int N = 1.2e5; const int K = 20; int n,q; pair<int,int> res[N]; int id[N]; vector<int> adj[N]; struct node { int val,left,right; }tree[N*50]; int dp[K][N],lv[N]; int root[N],cnt; int clone(int idx){ tree[++cnt] = tree[idx]; return cnt; } void build(int l,int r,int idx) { cnt = max(cnt,idx); if(l==r) return; int m = (l+r)/2; tree[idx] = {0,idx*2,idx*2+1}; build(l,m,idx*2),build(m+1,r,idx*2+1); } int update(int l,int r,int idx,int x) { int now = clone(idx); tree[now].val++; if(l==r) return now; int m = (l+r)/2; if(x<=m) tree[now].left = update(l,m,tree[now].left,x); else tree[now].right = update(m+1,r,tree[now].right,x); return now; } int read(int l,int r,int aidx,int bidx,int pidx,int uidx,int k) { if(l==r) return l; int m = (l+r)/2; int tmp = tree[tree[aidx].left].val+tree[tree[bidx].left].val-tree[tree[pidx].left].val-tree[tree[uidx].left].val; if(k<=tmp) return read(l,m,tree[aidx].left,tree[bidx].left,tree[pidx].left,tree[uidx].left,k); else return read(m+1,r,tree[aidx].right,tree[bidx].right,tree[pidx].right,tree[uidx].right,k-tmp); } void dfs(int u,int p,int l) { root[u] = update(1,n,root[p],id[u]); dp[0][u] = p,lv[u] = l; for(int v : adj[u]) if(v!=p) dfs(v,u,l+1); } int lca(int a,int b) { if(lv[a]<lv[b]) swap(a,b); for(int i = K-1;i >= 0;i--) if(lv[dp[i][a]]>=lv[b]) a = dp[i][a]; if(a==b) return a; for(int i = K-1;i >= 0;i--) if(dp[i][a]!=dp[i][b]) a = dp[i][a],b = dp[i][b]; return dp[0][a]; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> q; for(int i = 1;i <= n;i++) cin >> res[i].first,res[i].second = i; for(int i = 0;i < n-1;i++) { int a,b; cin >> a >> b; adj[a].push_back(b); adj[b].push_back(a); } sort(res+1,res+n+1); for(int i = 1;i <= n;i++) id[res[i].second] = i; build(1,n,1); root[0] = 1; dfs(1,0,1); for(int i = 1;i < K;i++) for(int j = 1;j <= n;j++) dp[i][j] = dp[i-1][dp[i-1][j]]; while(q--) { int a,b,k; cin >> a >> b >> k; int l = lca(a,b); int tmp = read(1,n,root[a],root[b],root[l],root[dp[0][l]],k); cout << res[tmp].first << '\n'; } }
24.552083
119
0.518456
Autoratch
c60c8bff9e1ff6d3b43ff765aa2a409a62c1a729
1,634
cpp
C++
JAERO/zmq_audiosender.cpp
Roethenbach/JAERO
753a4409507a356489f3635b93dc16955c8cf01a
[ "MIT" ]
152
2015-12-02T01:38:42.000Z
2022-03-29T10:41:37.000Z
JAERO/zmq_audiosender.cpp
Roethenbach/JAERO
753a4409507a356489f3635b93dc16955c8cf01a
[ "MIT" ]
59
2015-12-02T02:11:24.000Z
2022-03-21T02:48:11.000Z
JAERO/zmq_audiosender.cpp
Roethenbach/JAERO
753a4409507a356489f3635b93dc16955c8cf01a
[ "MIT" ]
38
2015-12-07T16:24:03.000Z
2021-12-25T15:44:27.000Z
#include "zmq_audiosender.h" #include "zmq.h" #include <QDebug> ZMQAudioSender::ZMQAudioSender(QObject *parent) : QObject(parent) { zmqStatus = -1; context = zmq_ctx_new(); publisher = zmq_socket(context, ZMQ_PUB); int keepalive = 1; int keepalivecnt = 10; int keepaliveidle = 1; int keepaliveintrv = 1; zmq_setsockopt(publisher, ZMQ_TCP_KEEPALIVE,(void*)&keepalive, sizeof(ZMQ_TCP_KEEPALIVE)); zmq_setsockopt(publisher, ZMQ_TCP_KEEPALIVE_CNT,(void*)&keepalivecnt,sizeof(ZMQ_TCP_KEEPALIVE_CNT)); zmq_setsockopt(publisher, ZMQ_TCP_KEEPALIVE_IDLE,(void*)&keepaliveidle,sizeof(ZMQ_TCP_KEEPALIVE_IDLE)); zmq_setsockopt(publisher, ZMQ_TCP_KEEPALIVE_INTVL,(void*)&keepaliveintrv,sizeof(ZMQ_TCP_KEEPALIVE_INTVL)); } void ZMQAudioSender::Start(QString &address, QString &topic) { Stop(); // bind socket this->topic=topic; connected_url=address.toUtf8().constData(); zmqStatus=zmq_bind(publisher, connected_url.c_str() ); } void ZMQAudioSender::Stop() { if(zmqStatus == 0) { zmqStatus = zmq_disconnect(publisher, connected_url.c_str()); } } void ZMQAudioSender::Voiceslot(QByteArray &data, QString &hex) { std::string topic_text = topic.toUtf8().constData(); zmq_setsockopt(publisher, ZMQ_IDENTITY, topic_text.c_str(), topic_text.length()); if(data.length()!=0) { zmq_send(publisher, topic_text.c_str(), topic_text.length(), ZMQ_SNDMORE); zmq_send(publisher, data.data(), data.length(), 0 ); } zmq_send(publisher, topic_text.c_str(), 5, ZMQ_SNDMORE); zmq_send(publisher, hex.toStdString().c_str(), 6, 0 ); }
31.423077
110
0.709302
Roethenbach
c60fe3d4e0fd8982b78cc8624913bfd71ef4d7b9
1,054
hpp
C++
src/dp/lcs.hpp
today2098/algorithm
b180355635d3d1ea0a8c3dff40ae1c9bac636f95
[ "MIT" ]
null
null
null
src/dp/lcs.hpp
today2098/algorithm
b180355635d3d1ea0a8c3dff40ae1c9bac636f95
[ "MIT" ]
null
null
null
src/dp/lcs.hpp
today2098/algorithm
b180355635d3d1ea0a8c3dff40ae1c9bac636f95
[ "MIT" ]
null
null
null
#ifndef ALGORITHM_LCS_HPP #define ALGORITHM_LCS_HPP #include <algorithm> #include <string> #include <vector> namespace algorithm { // 最長共通部分列 (LCS:Longest Common Subsequence). O(|A|*|B|). template <class Class> Class lcs(const Class &a, const Class &b) { int an = a.size(), bn = b.size(); std::vector<std::vector<int> > dp(an + 1, std::vector<int>(bn + 1, 0)); // dp[i][j]:=(a[:i]とb[:j]のLCSの長さ). for(int i = 1; i <= an; ++i) for(int j = 1; j <= bn; ++j) { if(a[i - 1] == b[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1; else dp[i][j] = std::max(dp[i - 1][j], dp[i][j - 1]); } Class sub(dp[an][bn]); // sub[]:=(配列a, bのLCS). int i = an, j = bn, k = dp[an][bn]; while(k > 0) { if(a[i - 1] == b[j - 1]) { sub[k - 1] = a[i - 1]; i--, j--, k--; } else if(dp[i][j] == dp[i - 1][j]) { i--; } else { j--; } } return sub; } } // namespace algorithm #endif // ALGORITHM_LCS_HPP
26.35
111
0.44592
today2098
c61002540bab6c6d6a88589cba8f69b3771fa016
34,655
cpp
C++
renderer/scene.cpp
Svengali/Granite
90de56b405455ccf70deaa5befe762a2bbc7777e
[ "MIT" ]
null
null
null
renderer/scene.cpp
Svengali/Granite
90de56b405455ccf70deaa5befe762a2bbc7777e
[ "MIT" ]
null
null
null
renderer/scene.cpp
Svengali/Granite
90de56b405455ccf70deaa5befe762a2bbc7777e
[ "MIT" ]
null
null
null
/* Copyright (c) 2017-2020 Hans-Kristian Arntzen * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "scene.hpp" #include "transforms.hpp" #include "lights/lights.hpp" #include "simd.hpp" #include "task_composer.hpp" #include <float.h> using namespace std; namespace Granite { Scene::Scene() : spatials(pool.get_component_group<BoundedComponent, RenderInfoComponent, CachedSpatialTransformTimestampComponent>()), opaque(pool.get_component_group<RenderInfoComponent, RenderableComponent, CachedSpatialTransformTimestampComponent, OpaqueComponent>()), transparent(pool.get_component_group<RenderInfoComponent, RenderableComponent, CachedSpatialTransformTimestampComponent, TransparentComponent>()), positional_lights(pool.get_component_group<RenderInfoComponent, RenderableComponent, CachedSpatialTransformTimestampComponent, PositionalLightComponent>()), irradiance_affecting_positional_lights(pool.get_component_group<RenderInfoComponent, PositionalLightComponent, CachedSpatialTransformTimestampComponent, IrradianceAffectingComponent>()), static_shadowing(pool.get_component_group<RenderInfoComponent, RenderableComponent, CachedSpatialTransformTimestampComponent, CastsStaticShadowComponent>()), dynamic_shadowing(pool.get_component_group<RenderInfoComponent, RenderableComponent, CachedSpatialTransformTimestampComponent, CastsDynamicShadowComponent>()), render_pass_shadowing(pool.get_component_group<RenderPassComponent, RenderableComponent, CachedSpatialTransformTimestampComponent, CastsDynamicShadowComponent>()), backgrounds(pool.get_component_group<UnboundedComponent, RenderableComponent>()), cameras(pool.get_component_group<CameraComponent, CachedTransformComponent>()), directional_lights(pool.get_component_group<DirectionalLightComponent, CachedTransformComponent>()), volumetric_diffuse_lights(pool.get_component_group<VolumetricDiffuseLightComponent, CachedSpatialTransformTimestampComponent, RenderInfoComponent>()), per_frame_updates(pool.get_component_group<PerFrameUpdateComponent>()), per_frame_update_transforms(pool.get_component_group<PerFrameUpdateTransformComponent, RenderInfoComponent>()), environments(pool.get_component_group<EnvironmentComponent>()), render_pass_sinks(pool.get_component_group<RenderPassSinkComponent, RenderableComponent, CullPlaneComponent>()), render_pass_creators(pool.get_component_group<RenderPassComponent>()) { } Scene::~Scene() { // Makes shutdown way faster :) // We know ahead of time we're going to delete everything, // so reduce a lot of overhead by deleting right away. pool.reset_groups(); destroy_entities(entities); destroy_entities(queued_entities); } template <typename T> static void gather_visible_renderables(const Frustum &frustum, VisibilityList &list, const T &objects, size_t begin_index, size_t end_index) { for (size_t i = begin_index; i < end_index; i++) { auto &o = objects[i]; auto *transform = get_component<RenderInfoComponent>(o); auto *renderable = get_component<RenderableComponent>(o); auto *timestamp = get_component<CachedSpatialTransformTimestampComponent>(o); Util::Hasher h; h.u64(timestamp->cookie); h.u32(timestamp->last_timestamp); if (transform->transform) { if ((renderable->renderable->flags & RENDERABLE_FORCE_VISIBLE_BIT) != 0 || SIMD::frustum_cull(transform->world_aabb, frustum.get_planes())) { list.push_back({ renderable->renderable.get(), transform, h.get() }); } } else list.push_back({ renderable->renderable.get(), nullptr, h.get() }); } } void Scene::add_render_passes(RenderGraph &graph) { for (auto &pass : render_pass_creators) { auto *rpass = get_component<RenderPassComponent>(pass)->creator; rpass->add_render_passes(graph); } } void Scene::add_render_pass_dependencies(RenderGraph &graph, RenderPass &main_pass) { for (auto &pass : render_pass_creators) { auto *rpass = get_component<RenderPassComponent>(pass)->creator; rpass->setup_render_pass_dependencies(graph, main_pass); } } void Scene::set_render_pass_data(const RendererSuite *suite, const RenderContext *context) { for (auto &pass : render_pass_creators) { auto *rpass = get_component<RenderPassComponent>(pass)->creator; rpass->set_base_renderer(suite); rpass->set_base_render_context(context); rpass->set_scene(this); } } void Scene::bind_render_graph_resources(RenderGraph &graph) { for (auto &pass : render_pass_creators) { auto *rpass = get_component<RenderPassComponent>(pass)->creator; rpass->setup_render_pass_resources(graph); } } void Scene::refresh_per_frame(const RenderContext &context, TaskComposer &composer) { per_frame_update_transforms_sorted = per_frame_update_transforms; per_frame_updates_sorted = per_frame_updates; stable_sort(per_frame_update_transforms_sorted.begin(), per_frame_update_transforms_sorted.end(), [](auto &a, auto &b) -> bool { int order_a = get_component<PerFrameUpdateTransformComponent>(a)->dependency_order; int order_b = get_component<PerFrameUpdateTransformComponent>(b)->dependency_order; return order_a < order_b; }); stable_sort(per_frame_updates_sorted.begin(), per_frame_updates_sorted.end(), [](auto &a, auto &b) -> bool { int order_a = get_component<PerFrameUpdateComponent>(a)->dependency_order; int order_b = get_component<PerFrameUpdateComponent>(b)->dependency_order; return order_a < order_b; }); int dep = std::numeric_limits<int>::min(); for (auto &update : per_frame_update_transforms_sorted) { auto *comp = get_component<PerFrameUpdateTransformComponent>(update); assert(comp->dependency_order != std::numeric_limits<int>::min()); if (comp->dependency_order != dep) { composer.begin_pipeline_stage(); dep = comp->dependency_order; } auto *refresh = comp->refresh; auto *transform = get_component<RenderInfoComponent>(update); if (refresh) refresh->refresh(context, transform, composer); } dep = std::numeric_limits<int>::min(); for (auto &update : per_frame_updates_sorted) { auto *comp = get_component<PerFrameUpdateComponent>(update); assert(comp->dependency_order != std::numeric_limits<int>::min()); if (comp->dependency_order != dep) { composer.begin_pipeline_stage(); dep = comp->dependency_order; } auto *refresh = comp->refresh; if (refresh) refresh->refresh(context, composer); } composer.begin_pipeline_stage(); } EnvironmentComponent *Scene::get_environment() const { if (environments.empty()) return nullptr; else return get_component<EnvironmentComponent>(environments.front()); } EntityPool &Scene::get_entity_pool() { return pool; } void Scene::gather_unbounded_renderables(VisibilityList &list) const { for (auto &background : backgrounds) list.push_back({ get_component<RenderableComponent>(background)->renderable.get(), nullptr }); } void Scene::gather_visible_render_pass_sinks(const vec3 &camera_pos, VisibilityList &list) const { for (auto &sink : render_pass_sinks) { auto &plane = get_component<CullPlaneComponent>(sink)->plane; if (dot(vec4(camera_pos, 1.0f), plane) > 0.0f) list.push_back({get_component<RenderableComponent>(sink)->renderable.get(), nullptr}); } } void Scene::gather_visible_opaque_renderables(const Frustum &frustum, VisibilityList &list) const { gather_visible_renderables(frustum, list, opaque, 0, opaque.size()); } void Scene::gather_visible_opaque_renderables_subset(const Frustum &frustum, VisibilityList &list, unsigned index, unsigned num_indices) const { size_t start_index = (index * opaque.size()) / num_indices; size_t end_index = ((index + 1) * opaque.size()) / num_indices; gather_visible_renderables(frustum, list, opaque, start_index, end_index); } void Scene::gather_visible_transparent_renderables(const Frustum &frustum, VisibilityList &list) const { gather_visible_renderables(frustum, list, transparent, 0, transparent.size()); } void Scene::gather_visible_static_shadow_renderables(const Frustum &frustum, VisibilityList &list) const { gather_visible_renderables(frustum, list, static_shadowing, 0, static_shadowing.size()); } void Scene::gather_visible_transparent_renderables_subset(const Frustum &frustum, VisibilityList &list, unsigned index, unsigned num_indices) const { size_t start_index = (index * transparent.size()) / num_indices; size_t end_index = ((index + 1) * transparent.size()) / num_indices; gather_visible_renderables(frustum, list, transparent, start_index, end_index); } void Scene::gather_visible_static_shadow_renderables_subset(const Frustum &frustum, VisibilityList &list, unsigned index, unsigned num_indices) const { size_t start_index = (index * static_shadowing.size()) / num_indices; size_t end_index = ((index + 1) * static_shadowing.size()) / num_indices; gather_visible_renderables(frustum, list, static_shadowing, start_index, end_index); } void Scene::gather_visible_dynamic_shadow_renderables(const Frustum &frustum, VisibilityList &list) const { gather_visible_renderables(frustum, list, dynamic_shadowing, 0, dynamic_shadowing.size()); for (auto &object : render_pass_shadowing) list.push_back({ get_component<RenderableComponent>(object)->renderable.get(), nullptr }); } void Scene::gather_visible_dynamic_shadow_renderables_subset(const Frustum &frustum, VisibilityList &list, unsigned index, unsigned num_indices) const { size_t start_index = (index * dynamic_shadowing.size()) / num_indices; size_t end_index = ((index + 1) * dynamic_shadowing.size()) / num_indices; gather_visible_renderables(frustum, list, dynamic_shadowing, start_index, end_index); if (index == 0) for (auto &object : render_pass_shadowing) list.push_back({ get_component<RenderableComponent>(object)->renderable.get(), nullptr }); } static void gather_positional_lights(const Frustum &frustum, VisibilityList &list, const ComponentGroupVector< RenderInfoComponent, RenderableComponent, CachedSpatialTransformTimestampComponent, PositionalLightComponent> &positional, size_t start_index, size_t end_index) { for (size_t i = start_index; i < end_index; i++) { auto &o = positional[i]; auto *transform = get_component<RenderInfoComponent>(o); auto *renderable = get_component<RenderableComponent>(o); auto *timestamp = get_component<CachedSpatialTransformTimestampComponent>(o); Util::Hasher h; h.u64(timestamp->cookie); h.u32(timestamp->last_timestamp); if (transform->transform) { if (SIMD::frustum_cull(transform->world_aabb, frustum.get_planes())) list.push_back({ renderable->renderable.get(), transform, h.get() }); } else list.push_back({ renderable->renderable.get(), nullptr, h.get() }); } } static void gather_positional_lights(const Frustum &frustum, PositionalLightList &list, const ComponentGroupVector<RenderInfoComponent, RenderableComponent, CachedSpatialTransformTimestampComponent, PositionalLightComponent> &positional, size_t start_index, size_t end_index) { for (size_t i = start_index; i < end_index; i++) { auto &o = positional[i]; auto *transform = get_component<RenderInfoComponent>(o); auto *light = get_component<PositionalLightComponent>(o)->light; auto *timestamp = get_component<CachedSpatialTransformTimestampComponent>(o); Util::Hasher h; h.u64(timestamp->cookie); h.u32(timestamp->last_timestamp); if (transform->transform) { if (SIMD::frustum_cull(transform->world_aabb, frustum.get_planes())) list.push_back({ light, transform, h.get() }); } else list.push_back({ light, transform, h.get() }); } } void Scene::gather_visible_positional_lights(const Frustum &frustum, VisibilityList &list) const { gather_positional_lights(frustum, list, positional_lights, 0, positional_lights.size()); } void Scene::gather_irradiance_affecting_positional_lights(PositionalLightList &list) const { for (auto &light_tup : irradiance_affecting_positional_lights) { auto *transform = get_component<RenderInfoComponent>(light_tup); auto *light = get_component<PositionalLightComponent>(light_tup)->light; auto *timestamp = get_component<CachedSpatialTransformTimestampComponent>(light_tup); Util::Hasher h; h.u64(timestamp->cookie); h.u32(timestamp->last_timestamp); list.push_back({ light, transform, h.get() }); } } void Scene::gather_visible_positional_lights(const Frustum &frustum, PositionalLightList &list) const { gather_positional_lights(frustum, list, positional_lights, 0, positional_lights.size()); } void Scene::gather_visible_volumetric_diffuse_lights(const Frustum &frustum, VolumetricDiffuseLightList &list) const { for (auto &o : volumetric_diffuse_lights) { auto *transform = get_component<RenderInfoComponent>(o); auto *light = get_component<VolumetricDiffuseLightComponent>(o); if (light->light.get_volume_view()) { if (transform->transform) { if (SIMD::frustum_cull(transform->world_aabb, frustum.get_planes())) list.push_back({ light, transform }); } else list.push_back({ light, transform }); } } } void Scene::gather_visible_positional_lights_subset(const Frustum &frustum, VisibilityList &list, unsigned index, unsigned num_indices) const { size_t start_index = (index * positional_lights.size()) / num_indices; size_t end_index = ((index + 1) * positional_lights.size()) / num_indices; gather_positional_lights(frustum, list, positional_lights, start_index, end_index); } void Scene::gather_visible_positional_lights_subset(const Frustum &frustum, PositionalLightList &list, unsigned index, unsigned num_indices) const { size_t start_index = (index * positional_lights.size()) / num_indices; size_t end_index = ((index + 1) * positional_lights.size()) / num_indices; gather_positional_lights(frustum, list, positional_lights, start_index, end_index); } size_t Scene::get_opaque_renderables_count() const { return opaque.size(); } size_t Scene::get_transparent_renderables_count() const { return transparent.size(); } size_t Scene::get_static_shadow_renderables_count() const { return static_shadowing.size(); } size_t Scene::get_dynamic_shadow_renderables_count() const { return dynamic_shadowing.size(); } size_t Scene::get_positional_lights_count() const { return positional_lights.size(); } #if 0 static void log_node_transforms(const Scene::Node &node) { for (unsigned i = 0; i < node.cached_skin_transform.bone_world_transforms.size(); i++) { LOGI("Joint #%u:\n", i); const auto &ibp = node.cached_skin_transform.bone_world_transforms[i]; LOGI(" Transform:\n" " [%f, %f, %f, %f]\n" " [%f, %f, %f, %f]\n" " [%f, %f, %f, %f]\n" " [%f, %f, %f, %f]\n", ibp[0][0], ibp[1][0], ibp[2][0], ibp[3][0], ibp[0][1], ibp[1][1], ibp[2][1], ibp[3][1], ibp[0][2], ibp[1][2], ibp[2][2], ibp[3][2], ibp[0][3], ibp[1][3], ibp[2][3], ibp[3][3]); } } #endif void Scene::update_skinning(Node &node) { if (node.get_skin() && !node.get_skin()->cached_skin_transform.bone_world_transforms.empty()) { auto &skin = *node.get_skin(); auto len = node.get_skin()->skin.size(); assert(skin.skin.size() == skin.cached_skin_transform.bone_world_transforms.size()); //assert(node.get_skin().cached_skin.size() == node.cached_skin_transform.bone_normal_transforms.size()); for (size_t i = 0; i < len; i++) { SIMD::mul(skin.cached_skin_transform.bone_world_transforms[i], skin.cached_skin[i]->world_transform, skin.inverse_bind_poses[i]); //node.cached_skin_transform.bone_normal_transforms[i] = node.get_skin().cached_skin[i]->normal_transform; } //log_node_transforms(node); } } void Scene::dispatch_collect_children(TraversalState *state) { size_t count = state->pending_count; // If we have a lot of child nodes, they will be farmed out to separate traversal states. // The spill-over will be collected, and sub-batches will be dispatched from that, etc. Node *children[TraversalState::BatchSize]; size_t unbatched_child_count = 0; for (size_t i = 0; i < count; i++) { NodeUpdateState update_state; Node *pending; if (state->single_parent) { pending = state->pending_list[i].get(); update_state = update_node_state(*pending, state->single_parent_is_dirty); if (update_state.self) update_transform_tree_node(*pending, *state->single_parent_transform); } else { pending = state->pending[i]; update_state = update_node_state(*pending, state->parent_is_dirty[i]); if (update_state.self) update_transform_tree_node(*pending, *state->parent_transforms[i]); } if (!update_state.children) continue; bool parent_is_dirty = update_state.self; auto *input_childs = pending->get_children().data(); size_t child_count = pending->get_children().size(); const mat4 *transform = &pending->cached_transform.world_transform; size_t derived_batch_count = child_count / TraversalState::BatchSize; for (size_t batch = 0; batch < derived_batch_count; batch++) { auto *child_state = traversal_state_pool.allocate(); child_state->traversal_done_dependency = state->traversal_done_dependency; child_state->traversal_done_dependency->add_flush_dependency(); child_state->group = state->group; child_state->pending_count = TraversalState::BatchSize; child_state->pending_list = &input_childs[batch * TraversalState::BatchSize]; child_state->single_parent = true; child_state->single_parent_transform = transform; child_state->single_parent_is_dirty = parent_is_dirty; dispatch_per_node_work(child_state); } for (size_t j = derived_batch_count * TraversalState::BatchSize; j < child_count; j++) { children[unbatched_child_count] = input_childs[j].get(); state->parent_is_dirty[unbatched_child_count] = parent_is_dirty; state->parent_transforms[unbatched_child_count] = transform; unbatched_child_count++; if (unbatched_child_count == TraversalState::BatchSize) { auto *child_state = traversal_state_pool.allocate(); child_state->traversal_done_dependency = state->traversal_done_dependency; child_state->traversal_done_dependency->add_flush_dependency(); child_state->group = state->group; child_state->pending_count = TraversalState::BatchSize; memcpy(child_state->pending, children, sizeof(children)); memcpy(child_state->parent_is_dirty, state->parent_is_dirty, sizeof(state->parent_is_dirty)); memcpy(child_state->parent_transforms, state->parent_transforms, sizeof(state->parent_transforms)); dispatch_per_node_work(child_state); unbatched_child_count = 0; } } } state->pending_count = unbatched_child_count; memcpy(state->pending, children, unbatched_child_count * sizeof(*children)); } TaskGroupHandle Scene::dispatch_per_node_work(TraversalState *state) { auto dispatcher_task = state->group->create_task([this, state]() { while (state->pending_count != 0) dispatch_collect_children(state); state->traversal_done_dependency->release_flush_dependency(); traversal_state_pool.free(state); }); dispatcher_task->set_desc("parallel-node-transform-update"); return dispatcher_task; } static const mat4 identity_transform(1.0f); void Scene::update_transform_tree(TaskComposer &composer) { if (!root_node) return; auto &group = composer.begin_pipeline_stage(); auto traversal = traversal_state_pool.allocate(); traversal->traversal_done_dependency = composer.get_thread_group().create_task(); traversal->pending_count = 1; traversal->pending[0] = root_node.get(); traversal->parent_is_dirty[0] = false; traversal->parent_transforms[0] = &identity_transform; traversal->group = &composer.get_thread_group(); traversal->traversal_done_dependency->add_flush_dependency(); auto dispatch = dispatch_per_node_work(traversal); if (auto dep = composer.get_pipeline_stage_dependency()) composer.get_thread_group().add_dependency(*dispatch, *dep); composer.get_thread_group().add_dependency(group, *traversal->traversal_done_dependency); } Scene::NodeUpdateState Scene::update_node_state(Node &node, bool parent_is_dirty) { bool transform_dirty = node.get_and_clear_transform_dirty() || parent_is_dirty; bool child_transforms_dirty = node.get_and_clear_child_transform_dirty() || transform_dirty; return { transform_dirty, child_transforms_dirty }; } void Scene::update_transform_tree_node(Node &node, const mat4 &transform) { compute_model_transform(node.cached_transform.world_transform, node.transform.scale, node.transform.rotation, node.transform.translation, transform); if (auto *skinning = node.get_skin()) for (auto &child : skinning->skeletons) update_transform_tree(*child, node.cached_transform.world_transform, true); //compute_normal_transform(node.cached_transform.normal_transform, node.cached_transform.world_transform); update_skinning(node); node.update_timestamp(); } void Scene::update_transform_tree(Node &node, const mat4 &transform, bool parent_is_dirty) { auto state = update_node_state(node, parent_is_dirty); if (state.self) update_transform_tree_node(node, transform); if (state.children) for (auto &child : node.get_children()) update_transform_tree(*child, node.cached_transform.world_transform, state.self); } size_t Scene::get_cached_transforms_count() const { return spatials.size(); } void Scene::update_cached_transforms_subset(unsigned index, unsigned num_indices) { size_t begin_index = (spatials.size() * index) / num_indices; size_t end_index = (spatials.size() * (index + 1)) / num_indices; update_cached_transforms_range(begin_index, end_index); } void Scene::update_all_transforms() { update_transform_tree(); update_transform_listener_components(); update_cached_transforms_range(0, spatials.size()); } void Scene::update_transform_tree() { if (root_node) update_transform_tree(*root_node, mat4(1.0f), false); } void Scene::update_transform_listener_components() { // Update camera transforms. for (auto &c : cameras) { CameraComponent *cam; CachedTransformComponent *transform; tie(cam, transform) = c; cam->camera.set_transform(transform->transform->world_transform); } // Update directional light transforms. for (auto &light : directional_lights) { DirectionalLightComponent *l; CachedTransformComponent *transform; tie(l, transform) = light; // v = [0, 0, 1, 0]. l->direction = normalize(transform->transform->world_transform[2].xyz()); } for (auto &light : volumetric_diffuse_lights) { VolumetricDiffuseLightComponent *l; CachedSpatialTransformTimestampComponent *timestamp; RenderInfoComponent *transform; tie(l, timestamp, transform) = light; if (timestamp->last_timestamp != l->timestamp) { // This is a somewhat expensive operation, so timestamp it. // We only expect this to run once since diffuse volumes really // cannot freely move around the scene due to the semi-baked nature of it. auto texture_to_world = transform->transform->world_transform * translate(vec3(-0.5f)); auto world_to_texture = inverse(texture_to_world); world_to_texture = transpose(world_to_texture); texture_to_world = transpose(texture_to_world); for (int i = 0; i < 3; i++) { l->world_to_texture[i] = world_to_texture[i]; l->texture_to_world[i] = texture_to_world[i]; } l->timestamp = timestamp->last_timestamp; } } } void Scene::update_cached_transforms_range(size_t begin_range, size_t end_range) { for (size_t i = begin_range; i < end_range; i++) { auto &s = spatials[i]; BoundedComponent *aabb; RenderInfoComponent *cached_transform; CachedSpatialTransformTimestampComponent *timestamp; tie(aabb, cached_transform, timestamp) = s; if (timestamp->last_timestamp != *timestamp->current_timestamp) { if (cached_transform->transform) { if (cached_transform->skin_transform) { // TODO: Isolate the AABB per bone. cached_transform->world_aabb = AABB(vec3(FLT_MAX), vec3(-FLT_MAX)); for (auto &m : cached_transform->skin_transform->bone_world_transforms) SIMD::transform_and_expand_aabb(cached_transform->world_aabb, *aabb->aabb, m); } else { SIMD::transform_aabb(cached_transform->world_aabb, *aabb->aabb, cached_transform->transform->world_transform); } } timestamp->last_timestamp = *timestamp->current_timestamp; } } } Scene::NodeHandle Scene::create_node() { return Scene::NodeHandle(node_pool.allocate(this)); } void Scene::NodeDeleter::operator()(Node *node) { node->parent_scene->get_node_pool().free(node); } static void add_bone(Scene::NodeHandle *bones, uint32_t parent, const SceneFormats::Skin::Bone &bone) { bones[parent]->get_skin()->skeletons.push_back(bones[bone.index]); for (auto &child : bone.children) add_bone(bones, bone.index, child); } Scene::NodeHandle Scene::create_skinned_node(const SceneFormats::Skin &skin) { auto node = create_node(); vector<NodeHandle> bones; bones.reserve(skin.joint_transforms.size()); for (size_t i = 0; i < skin.joint_transforms.size(); i++) { bones.push_back(create_node()); bones[i]->transform.translation = skin.joint_transforms[i].translation; bones[i]->transform.scale = skin.joint_transforms[i].scale; bones[i]->transform.rotation = skin.joint_transforms[i].rotation; } node->set_skin(skinning_pool.allocate()); auto &node_skin = *node->get_skin(); node_skin.cached_skin_transform.bone_world_transforms.resize(skin.joint_transforms.size()); //node->cached_skin_transform.bone_normal_transforms.resize(skin.joint_transforms.size()); node_skin.skin.reserve(skin.joint_transforms.size()); node_skin.cached_skin.reserve(skin.joint_transforms.size()); node_skin.inverse_bind_poses.reserve(skin.joint_transforms.size()); for (size_t i = 0; i < skin.joint_transforms.size(); i++) { node_skin.cached_skin.push_back(&bones[i]->cached_transform); node_skin.skin.push_back(&bones[i]->transform); node_skin.inverse_bind_poses.push_back(skin.inverse_bind_pose[i]); } for (auto &skeleton : skin.skeletons) { node->get_skin()->skeletons.push_back(bones[skeleton.index]); for (auto &child : skeleton.children) add_bone(bones.data(), skeleton.index, child); } node_skin.skin_compat = skin.skin_compat; return node; } void Scene::Node::add_child(NodeHandle node) { assert(this != node.get()); assert(node->parent == nullptr); node->parent = this; // Force parents to be notified. node->cached_transform_dirty = false; node->invalidate_cached_transform(); children.push_back(node); } Scene::NodeHandle Scene::Node::remove_child(Node *node) { assert(node->parent == this); node->parent = nullptr; auto handle = node->reference_from_this(); // Force parents to be notified. node->cached_transform_dirty = false; node->invalidate_cached_transform(); auto itr = remove_if(begin(children), end(children), [&](const NodeHandle &h) { return node == h.get(); }); assert(itr != end(children)); children.erase(itr, end(children)); return handle; } Scene::NodeHandle Scene::Node::remove_node_from_hierarchy(Node *node) { if (node->parent) return node->parent->remove_child(node); else return Scene::NodeHandle(nullptr); } void Scene::Node::invalidate_cached_transform() { if (!cached_transform_dirty) { cached_transform_dirty = true; for (auto *p = parent; p && !p->any_child_transform_dirty; p = p->parent) p->any_child_transform_dirty = true; } } Entity *Scene::create_entity() { Entity *entity = pool.create_entity(); entities.insert_front(entity); return entity; } static std::atomic<uint64_t> transform_cookies; Entity *Scene::create_volumetric_diffuse_light(uvec3 resolution, Node *node) { Entity *entity = pool.create_entity(); entities.insert_front(entity); auto *light = entity->allocate_component<VolumetricDiffuseLightComponent>(); light->light.set_resolution(resolution); auto *transform = entity->allocate_component<RenderInfoComponent>(); auto *timestamp = entity->allocate_component<CachedSpatialTransformTimestampComponent>(); auto *bounded = entity->allocate_component<BoundedComponent>(); bounded->aabb = &VolumetricDiffuseLight::get_static_aabb(); if (node) { transform->transform = &node->cached_transform; timestamp->current_timestamp = node->get_timestamp_pointer(); } timestamp->cookie = transform_cookies.fetch_add(std::memory_order_relaxed); return entity; } Entity *Scene::create_light(const SceneFormats::LightInfo &light, Node *node) { Entity *entity = pool.create_entity(); entities.insert_front(entity); switch (light.type) { case SceneFormats::LightInfo::Type::Directional: { auto *dir = entity->allocate_component<DirectionalLightComponent>(); auto *transform = entity->allocate_component<CachedTransformComponent>(); transform->transform = &node->cached_transform; dir->color = light.color; break; } case SceneFormats::LightInfo::Type::Point: case SceneFormats::LightInfo::Type::Spot: { AbstractRenderableHandle renderable; if (light.type == SceneFormats::LightInfo::Type::Point) renderable = Util::make_handle<PointLight>(); else { renderable = Util::make_handle<SpotLight>(); auto &spot = static_cast<SpotLight &>(*renderable); spot.set_spot_parameters(light.inner_cone, light.outer_cone); } auto &positional = static_cast<PositionalLight &>(*renderable); positional.set_color(light.color); if (light.range > 0.0f) positional.set_maximum_range(light.range); entity->allocate_component<PositionalLightComponent>()->light = &positional; entity->allocate_component<RenderableComponent>()->renderable = renderable; auto *transform = entity->allocate_component<RenderInfoComponent>(); auto *timestamp = entity->allocate_component<CachedSpatialTransformTimestampComponent>(); timestamp->cookie = transform_cookies.fetch_add(1, std::memory_order_relaxed); if (node) { transform->transform = &node->cached_transform; timestamp->current_timestamp = node->get_timestamp_pointer(); } auto *bounded = entity->allocate_component<BoundedComponent>(); bounded->aabb = renderable->get_static_aabb(); break; } } return entity; } Entity *Scene::create_renderable(AbstractRenderableHandle renderable, Node *node) { Entity *entity = pool.create_entity(); entities.insert_front(entity); if (renderable->has_static_aabb()) { auto *transform = entity->allocate_component<RenderInfoComponent>(); auto *timestamp = entity->allocate_component<CachedSpatialTransformTimestampComponent>(); timestamp->cookie = transform_cookies.fetch_add(1, std::memory_order_relaxed); if (node) { transform->transform = &node->cached_transform; timestamp->current_timestamp = node->get_timestamp_pointer(); if (node->get_skin() && !node->get_skin()->cached_skin.empty()) transform->skin_transform = &node->get_skin()->cached_skin_transform; } auto *bounded = entity->allocate_component<BoundedComponent>(); bounded->aabb = renderable->get_static_aabb(); } else entity->allocate_component<UnboundedComponent>(); auto *render = entity->allocate_component<RenderableComponent>(); switch (renderable->get_mesh_draw_pipeline()) { case DrawPipeline::AlphaBlend: entity->allocate_component<TransparentComponent>(); break; default: entity->allocate_component<OpaqueComponent>(); if (renderable->has_static_aabb()) { // TODO: Find a way to make this smarter. entity->allocate_component<CastsStaticShadowComponent>(); entity->allocate_component<CastsDynamicShadowComponent>(); } break; } render->renderable = renderable; return entity; } void Scene::destroy_entities(Util::IntrusiveList<Entity> &entity_list) { auto itr = entity_list.begin(); while (itr != entity_list.end()) { auto *to_free = itr.get(); itr = entity_list.erase(itr); to_free->get_pool()->delete_entity(to_free); } } void Scene::remove_entities_with_component(ComponentType id) { // We know ahead of time we're going to delete everything, // so reduce a lot of overhead by deleting right away. pool.reset_groups_for_component_type(id); auto itr = entities.begin(); while (itr != entities.end()) { if (itr->has_component(id)) { auto *to_free = itr.get(); itr = entities.erase(itr); to_free->get_pool()->delete_entity(to_free); } else ++itr; } } void Scene::destroy_queued_entities() { destroy_entities(queued_entities); } void Scene::destroy_entity(Entity *entity) { if (entity) { entities.erase(entity); entity->get_pool()->delete_entity(entity); } } void Scene::queue_destroy_entity(Entity *entity) { if (entity->mark_for_destruction()) { entities.erase(entity); queued_entities.insert_front(entity); } } }
33.909002
189
0.734872
Svengali
723e6aaad59bcfc5f04cde68e3bd5c4dda8fd5d8
1,145
cpp
C++
main/dashboard.cpp
lucasnunes/tcc_source
695610ec134d946694080fd2efae3f1dc41c2fa2
[ "Apache-2.0" ]
2
2019-01-08T12:51:04.000Z
2019-01-08T12:51:04.000Z
main/dashboard.cpp
lucasnunes/tcc_source
695610ec134d946694080fd2efae3f1dc41c2fa2
[ "Apache-2.0" ]
null
null
null
main/dashboard.cpp
lucasnunes/tcc_source
695610ec134d946694080fd2efae3f1dc41c2fa2
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2014 Lucas Nunes de Lima * * 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 "dashboard.hpp" #include "analog.hpp" #include "controller_io.hpp" #include <cstdlib> #include <string> #include <sstream> #include <cstdlib> namespace controller { namespace rest { std::string getValuesTo(const std::string& command, const std::string& param) { if(command == "inv_value") { int index = std::stoi(param); //Pin& pin = gpio::getPin(index); //pin.invertValue(); } return ""; } } }
26.627907
85
0.636681
lucasnunes
7241690856675888fdc257715c9d94e3c534ef4f
2,282
cpp
C++
codeforces/599E.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
3
2017-09-17T09:12:50.000Z
2018-04-06T01:18:17.000Z
codeforces/599E.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
codeforces/599E.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
#include <bits/stdc++.h> #define N 100020 #define ll long long using namespace std; inline int read(){ int x=0,f=1;char ch=getchar(); while(ch>'9'||ch<'0')ch=='-'&&(f=0)||(ch=getchar()); while(ch<='9'&&ch>='0')x=(x<<3)+(x<<1)+ch-'0',ch=getchar(); return f?x:-x; } ll dp[13][1<<13]; int ex[13], ey[13]; int ax[102], ay[102], az[102]; int n, m, q; bool mp[13][13]; inline bool in(int x, int s) { return s & (1 << x); } ll dfs(int u, int mask) { ll &res = dp[u][mask]; if (~res) return res; res = 0; mask ^= 1 << u; int pos = 0; while (pos < n) { if (in(pos, mask)) break; else ++ pos; } for (int submask = mask; submask; submask = (submask - 1) & mask) { if (in(pos, submask)) { int flag = 1, cnt = 0; for (int i = 1; i <= q; ++i) { if (az[i] == u && in(ax[i], submask) && in(ay[i], submask)) { flag = 0; break; } } for (int i = 1; i <= q; ++i) { if (in(az[i], submask) && (!in(ax[i], submask) || !in(ay[i], submask))) { flag = 0; break; } } for (int i = 1; i <= m; ++i) { if (ex[i] != u && ey[i] != u && (in(ex[i], submask) ^ in(ey[i], submask))) { flag = 0; break; } } int v = 0; for (int i = 0; i < n; ++i) { if (mp[u][i] && in(i, submask)) { ++cnt; v = i; } } if (!flag || cnt > 1) continue; if (cnt == 1) { res += dfs(v, submask) * dfs(u, mask ^ submask ^ (1 << u)); } else { for (v = 0; v < n; ++v) { if (in(v, submask)) { res += dfs(v, submask) * dfs(u, mask ^ submask ^ (1 << u)); } } } } } return res; } int main(int argc, char const *argv[]) { freopen("../tmp/.in", "r", stdin); n = read(), m = read(), q = read(); for (int i = 1; i <= m; ++i) { ex[i] = read() - 1; ey[i] = read() - 1; mp[ex[i]][ey[i]] = 1; mp[ey[i]][ex[i]] = 1; } for (int i = 1; i <= q; ++i) { ax[i] = read() - 1; ay[i] = read() - 1; az[i] = read() - 1; } memset(dp, -1, sizeof dp); for (int i = 0; i < n; ++i) { dp[i][1 << i] = 1; } printf("%lld\n", dfs(0, (1 << n) - 1)); return 0; }
23.285714
71
0.402279
swwind
724200aec014f9fed920f59d271ef751f882b96a
809
hpp
C++
src/model/Object.hpp
Vict0rynox/ft_retro
fe3ab75fb86406367837ba393e1c221133590bf4
[ "MIT" ]
null
null
null
src/model/Object.hpp
Vict0rynox/ft_retro
fe3ab75fb86406367837ba393e1c221133590bf4
[ "MIT" ]
null
null
null
src/model/Object.hpp
Vict0rynox/ft_retro
fe3ab75fb86406367837ba393e1c221133590bf4
[ "MIT" ]
null
null
null
// // Created by Victor Vasiliev on 11/4/17. // #ifndef FT_RETRO_OBJECT_HPP #define FT_RETRO_OBJECT_HPP #include <string> #include "Position.hpp" namespace Model { class Object { protected: const std::string name; Model::Position position; bool isDestroyed; bool isNotIntersection; public: Object(); virtual ~Object(); explicit Object(const std::string &name, Model::Position position); Object(const Object &rhs); Object&operator=(const Object &rhs); const Model::Position& getPosition() const; const std::string& getName() const; void setPosition(Model::Position &position); bool isDestroy(); void destroy(); bool isIntersect(const Object &object); void setNotIntersection(bool notIntersection); bool isIsNotIntersection() const; }; } #endif //FT_RETRO_OBJECT_HPP
21.289474
69
0.730532
Vict0rynox
72445ea49f2159927813b1208056f7637cc1251b
6,815
hpp
C++
src/EngineImpl/EngineObjectSerilization.hpp
cyf-gh/HoneyGame
2448f4574c6e1a847f1395d97a3186d79b499b22
[ "MIT" ]
3
2021-11-27T01:24:26.000Z
2021-12-31T07:17:38.000Z
src/EngineImpl/EngineObjectSerilization.hpp
cyf-gh/HGEngine
2448f4574c6e1a847f1395d97a3186d79b499b22
[ "MIT" ]
null
null
null
src/EngineImpl/EngineObjectSerilization.hpp
cyf-gh/HGEngine
2448f4574c6e1a847f1395d97a3186d79b499b22
[ "MIT" ]
1
2021-10-01T07:18:58.000Z
2021-10-01T07:18:58.000Z
#pragma once #include <Serialization.h> #include <Memory.h> #include "EngineImpl.h" #include "Scene.h" #include "Transform.hpp" #include "Animation.h" #include "Collision.h" #include "Timer.hpp" #include "RigidBody.h" namespace HGEngine { namespace V1SDL { class GameObjectFactory : HG::Memory::NonCopyable { public: template<typename _T> HG_INLINE static _T* CreateByJson( std::string& strJson, const bool isEnable, const char* strObjNewName = "", const char* strObjKey = "Obj" ) { rapidjson::Document d; d.Parse( strJson.c_str() ); if( d.HasParseError() ) { HG_LOG_FAILED( std::format( "Parse Error: {}", std::to_string( d.GetParseError() ) ).c_str() ); return nullptr; } _T* g = new _T(); HG::Serialization::Unmarshal( ( GameObject& ) *g, strObjKey, d[strObjKey], d ); if( strcmp( strObjNewName, "" ) != 0 ) { g->SetName( strObjNewName ); } auto ps = HGEngine::V1SDL::EngineImpl::GetEngine()->GetCurrentScene(); if( ps != nullptr ) { ps->AttachGameObject( g ); } if( isEnable ) { g->Enable(); } return g; } }; } } namespace HG { namespace Serialization { HG_MARSHAL_FULLSPEC( HGEngine::V1SDL::Transform ) { HG_MARSHAL_OBJECT_START; HG_MARSHAL_OBJECT_SETPROP( t.f64Angle ); HG_MARSHAL_OBJECT_SETPROP( t.tLocalPos ); HG_MARSHAL_OBJECT_SETPROP( t.tLocalRect ); HG_MARSHAL_OBJECT_SETPROP( t.tPosition ); HG_MARSHAL_OBJECT_SETPROP( t.tRect ); HG_MARSHAL_OBJECT_SETPROP( t.tRotateCenter ); HG_MARSHAL_OBJECT_END; } HG_UNMARSHAL_FULLSPEC( HGEngine::V1SDL::Transform ) { HG_UNMARSHAL_OBJECT_START; HG_UNMARSHAL_GETOBJ( t.f64Angle ); HG_UNMARSHAL_GETOBJ( t.tLocalPos ); HG_UNMARSHAL_GETOBJ( t.tLocalRect ); HG_UNMARSHAL_GETOBJ( t.tPosition ); HG_UNMARSHAL_GETOBJ( t.tRect ); HG_UNMARSHAL_GETOBJ( t.tRotateCenter ); HG_UNMARSHAL_OBJECT_END; } HG_MARSHAL_FULLSPEC( HGEngine::V1SDL::Animator2D::Frame ) { HG_MARSHAL_OBJECT_START; HG_MARSHAL_OBJECT_SETPROP( t.tPos ); HG_MARSHAL_OBJECT_SETPROP( t.tRect ); HG_MARSHAL_OBJECT_END; } HG_UNMARSHAL_FULLSPEC( HGEngine::V1SDL::Animator2D::Frame ) { HG_UNMARSHAL_OBJECT_START; HG_UNMARSHAL_GETOBJ( t.tPos ); HG_UNMARSHAL_GETOBJ( t.tRect ); HG_UNMARSHAL_OBJECT_END; } HG_MARSHAL_FULLSPEC( HGEngine::V1SDL::Animator2D ) { HG_MARSHAL_OBJECT_START; HG_MARSHAL_OBJECT_SETPROP( t.Col ); HG_MARSHAL_OBJECT_SETPROP( t.Row ); HG_MARSHAL_OBJECT_SETPROP( t.f32Interval ); HG_MARSHAL_OBJECT_SETPROP( t.IsIdle ); HG_MARSHAL_OBJECT_SETPROP( t.m_unIdleFrameIndex ); HG_MARSHAL_OBJECT_SETPROP( t.m_vecFrames ); HG_MARSHAL_OBJECT_END; } HG_UNMARSHAL_FULLSPEC( HGEngine::V1SDL::Animator2D ) { HG_UNMARSHAL_OBJECT_START; HG_UNMARSHAL_GETOBJ( t.Col ); HG_UNMARSHAL_GETOBJ( t.Row ); HG_UNMARSHAL_GETOBJ( t.f32Interval ); HG_UNMARSHAL_GETOBJ( t.IsIdle ); HG_UNMARSHAL_GETOBJ( t.m_unIdleFrameIndex ); HG_UNMARSHAL_GETOBJ( t.m_vecFrames ); HG_UNMARSHAL_OBJECT_END; } HG_MARSHAL_FULLSPEC( HGEngine::V1SDL::Timer ) { HG_MARSHAL_OBJECT_START; HG_MARSHAL_OBJECT_SETPROP( t.Active ); HG_MARSHAL_OBJECT_SETPROP( t.f32Delay ); HG_MARSHAL_OBJECT_SETPROP( t.f32DelayRest ); HG_MARSHAL_OBJECT_SETPROP( t.f32Elapsed ); HG_MARSHAL_OBJECT_SETPROP( t.f32ElpasedLoop ); HG_MARSHAL_OBJECT_SETPROP( t.f32Interval ); HG_MARSHAL_OBJECT_END; } HG_UNMARSHAL_FULLSPEC( HGEngine::V1SDL::Timer ) { HG_UNMARSHAL_OBJECT_START; HG_UNMARSHAL_GETOBJ( t.Active ); HG_UNMARSHAL_GETOBJ( t.f32Delay ); HG_UNMARSHAL_GETOBJ( t.f32DelayRest ); HG_UNMARSHAL_GETOBJ( t.f32Elapsed ); HG_UNMARSHAL_GETOBJ( t.f32ElpasedLoop ); HG_UNMARSHAL_GETOBJ( t.f32Interval ); HG_UNMARSHAL_OBJECT_END; } HG_MARSHAL_FULLSPEC( HGEngine::V1SDL::RigidBody ) { HG_MARSHAL_OBJECT_START; HG_MARSHAL_OBJECT_SETPROP( t.AngularDrag ); HG_MARSHAL_OBJECT_SETPROP( t.GravityDrag ); HG_MARSHAL_OBJECT_SETPROP( t.IsFrozen ); HG_MARSHAL_OBJECT_SETPROP( t.LinearDrag ); HG_MARSHAL_OBJECT_SETPROP( t.Mass ); HG_MARSHAL_OBJECT_SETPROP( t.Velocity ); HG_MARSHAL_OBJECT_END; } HG_UNMARSHAL_FULLSPEC( HGEngine::V1SDL::RigidBody ) { HG_UNMARSHAL_OBJECT_START; HG_UNMARSHAL_GETOBJ( t.AngularDrag ); HG_UNMARSHAL_GETOBJ( t.GravityDrag ); HG_UNMARSHAL_GETOBJ( t.IsFrozen ); HG_UNMARSHAL_GETOBJ( t.LinearDrag ); HG_UNMARSHAL_GETOBJ( t.Mass ); HG_UNMARSHAL_GETOBJ( t.Velocity ); HG_UNMARSHAL_OBJECT_END; } HG_MARSHAL_FULLSPEC( HGEngine::V1SDL::BoxCollision ) { HG_MARSHAL_OBJECT_START; HG_MARSHAL_OBJECT_SETPROP( t.Rect ); HG_MARSHAL_OBJECT_END; } HG_UNMARSHAL_FULLSPEC( HGEngine::V1SDL::BoxCollision ) { HG_UNMARSHAL_OBJECT_START; HG_UNMARSHAL_GETOBJ( t.Rect ); HG_UNMARSHAL_OBJECT_END; } HG_MARSHAL_FULLSPEC( HGEngine::V1SDL::GameObject ) { HG_MARSHAL_OBJECT_START; auto n = std::string( t.GetName() ); Marshal( n, "Name", writer ); Marshal( t.m_vecComponents, "Components", writer ); HG_MARSHAL_OBJECT_END; } HG_UNMARSHAL_FULLSPEC( HGEngine::V1SDL::GameObject ) { HG_UNMARSHAL_OBJECT_START; std::string Name; HG_UNMARSHAL_GETOBJ( Name ); t.SetName( Name.c_str() ); Unmarshal( t.m_vecComponents, "Components", d["Components"], rd ); for( auto& c : t.m_vecComponents ) { c->SetGameObject( &t ); } HG_UNMARSHAL_OBJECT_END; } #define HG_UNMARSHAL_COMPONENT( COMP_TYPE, NODE_NAME ) \ if( d.HasMember( NODE_NAME ) ) { \ t = new COMP_TYPE(NODE_NAME); \ Unmarshal( *static_cast< COMP_TYPE* >( t ), NODE_NAME, d[NODE_NAME], rd ); \ goto END; \ } #define HG_MARSHAL_GAMEOBJECTSETPROP( COMP_TYPE, NODE_NAME ) \ if( typeid( COMP_TYPE ).hash_code() == typeid( *t ).hash_code() ) { \ Marshal( *static_cast< COMP_TYPE* >( t ), NODE_NAME, writer ); \ } HG_MARSHAL_FULLSPEC( HG::HGComponent* ) { HG_MARSHAL_OBJECT_START; HG_MARSHAL_GAMEOBJECTSETPROP( HGEngine::V1SDL::Transform, "Transform" ); HG_MARSHAL_GAMEOBJECTSETPROP( HGEngine::V1SDL::Animator2D, "Animator2D" ); HG_MARSHAL_GAMEOBJECTSETPROP( HGEngine::V1SDL::RigidBody, "RigidBody" ); HG_MARSHAL_GAMEOBJECTSETPROP( HGEngine::V1SDL::BoxCollision, "BoxCollision" ); HG_MARSHAL_GAMEOBJECTSETPROP( HGEngine::V1SDL::Timer, "Timer" ); HG_MARSHAL_OBJECT_END; } HG_UNMARSHAL_FULLSPEC( HG::HGComponent* ) { HG_UNMARSHAL_OBJECT_START; HG_UNMARSHAL_COMPONENT( HGEngine::V1SDL::Transform, "Transform" ); HG_UNMARSHAL_COMPONENT( HGEngine::V1SDL::Animator2D, "Animator2D" ); HG_UNMARSHAL_COMPONENT( HGEngine::V1SDL::RigidBody, "RigidBody" ); HG_UNMARSHAL_COMPONENT( HGEngine::V1SDL::BoxCollision, "BoxCollision" ); HG_UNMARSHAL_OBJECT_END; } HG_MARSHAL_FULLSPEC( SDL_Color ) { HG_MARSHAL_OBJECT_START; HG_MARSHAL_SETOBJ( t.a ); HG_MARSHAL_SETOBJ( t.r ); HG_MARSHAL_SETOBJ( t.g ); HG_MARSHAL_SETOBJ( t.b ); HG_MARSHAL_OBJECT_END; } HG_UNMARSHAL_FULLSPEC( SDL_Color ) { HG_UNMARSHAL_OBJECT_START; HG_UNMARSHAL_GETOBJ( t.a ); HG_UNMARSHAL_GETOBJ( t.r ); HG_UNMARSHAL_GETOBJ( t.g ); HG_UNMARSHAL_GETOBJ( t.b ); HG_UNMARSHAL_OBJECT_END; } } }
29.375
144
0.759208
cyf-gh
724da682e8d7cd313ec97c14438a25c420bf930b
5,838
cpp
C++
src/nvilidar_node.cpp
nvilidar/nvilidar_ros
dc03c44e581cb328f6dbdd23f63344c0e6a73d4b
[ "BSD-3-Clause" ]
null
null
null
src/nvilidar_node.cpp
nvilidar/nvilidar_ros
dc03c44e581cb328f6dbdd23f63344c0e6a73d4b
[ "BSD-3-Clause" ]
1
2021-11-22T06:44:48.000Z
2021-12-09T02:53:01.000Z
src/nvilidar_node.cpp
nvilidar/nvilidar_ros
dc03c44e581cb328f6dbdd23f63344c0e6a73d4b
[ "BSD-3-Clause" ]
null
null
null
#include "ros/ros.h" #include <vector> #include <iostream> #include <string.h> #include "sensor_msgs/LaserScan.h" #include "nvilidar_process.h" #include "nvilidar_def.h" using namespace nvilidar; #define ROSVerision "1.0.8" int main(int argc, char * argv[]) { ros::init(argc, argv, "nvilidar_node"); printf(" _ ___ _______ _ _____ _____ _____ \n"); printf("| \\ | \\ \\ / /_ _| | |_ _| __ \\ /\\ | __ \\\n"); printf("| \\| |\\ \\ / / | | | | | | | | | | / \\ | |__) |\n"); printf("| . ` | \\ \\/ / | | | | | | | | | |/ /\\ \\ | _ / \n"); printf("| |\\ | \\ / _| |_| |____ _| |_| |__| / ____ \\| | \\ \\\n"); printf("|_| \\_| \\/ |_____|______|_____|_____/_/ \\_\\_| \\ \\\n"); printf("\n"); fflush(stdout); ros::NodeHandle nh; ros::Publisher scan_pub = nh.advertise<sensor_msgs::LaserScan>("scan", 1000); ros::NodeHandle nh_private("~"); Nvilidar_UserConfigTypeDef cfg; bool use_socket = false; //默认不用socket //读取雷达配置 从rviz文件内 如果里面有配置对应参数 则走里面的数据。如果没有,则直接取函数第3个默认参数配置信息 nh_private.param<std::string>("serialport_name", cfg.serialport_name, "dev/nvilidar"); nh_private.param<int>("serialport_baud", cfg.serialport_baud, 921600); nh_private.param<std::string>("ip_addr", cfg.ip_addr, "192.168.1.200"); nh_private.param<int>("lidar_udp_port", cfg.lidar_udp_port, 8100); nh_private.param<int>("config_tcp_port", cfg.config_tcp_port, 8200); nh_private.param<std::string>("frame_id", cfg.frame_id, "laser_frame"); nh_private.param<bool>("resolution_fixed", cfg.resolution_fixed, true); nh_private.param<bool>("auto_reconnect", cfg.auto_reconnect, false); nh_private.param<bool>("reversion", cfg.reversion, false); nh_private.param<bool>("inverted", cfg.inverted, false); nh_private.param<double>("angle_max", cfg.angle_max , 180.0); nh_private.param<double>("angle_min", cfg.angle_min , -180.0); nh_private.param<double>("range_max", cfg.range_max , 64.0); nh_private.param<double>("range_min", cfg.range_min , 0.0); nh_private.param<double>("aim_speed", cfg.aim_speed , 10.0); nh_private.param<int>("sampling_rate", cfg.sampling_rate, 10000); nh_private.param<bool>("sensitive", cfg.sensitive, false); nh_private.param<int>("tailing_level", cfg.tailing_level, 6); nh_private.param<double>("angle_offset", cfg.angle_offset, 0.0); nh_private.param<bool>("apd_change_flag", cfg.apd_change_flag, false); nh_private.param<int>("apd_value", cfg.apd_value, 500); nh_private.param<bool>("single_channel", cfg.single_channel, false); nh_private.param<std::string>("ignore_array_string", cfg.ignore_array_string, ""); //过滤参数 nh_private.param<bool>("filter_jump_enable", cfg.filter_jump_enable, true); nh_private.param<int>("filter_jump_value_min", cfg.filter_jump_value_min, 3); nh_private.param<int>("filter_jump_value_max", cfg.filter_jump_value_max, 50); //更新数据 用网络或者串口 #if 1 nvilidar::LidarProcess laser(USE_SERIALPORT,cfg.serialport_name,cfg.serialport_baud); #else nvilidar::LidarProcess laser(USE_SOCKET,cfg.ip_addr, cfg.lidar_udp_port); #endif //根据配置 重新加载参数 laser.LidarReloadPara(cfg); ROS_INFO("[NVILIDAR INFO] Now NVILIDAR ROS SDK VERSION:%s .......", ROSVerision); //初始化 变量定义 bool ret = laser.LidarInitialialize(); if (ret) { //启动雷达 ret = laser.LidarTurnOn(); if (!ret) { ROS_ERROR("Failed to start Scan!!!"); } } else { ROS_ERROR("Error initializing NVILIDAR Comms and Status!!!"); } ros::Rate rate(50); LidarScan scan; while (ret && ros::ok()) { if(laser.LidarSamplingProcess(scan)) { if(scan.points.size() > 0) { sensor_msgs::LaserScan scan_msg; ros::Time start_scan_time; start_scan_time.sec = scan.stamp/1000000000ul; start_scan_time.nsec = scan.stamp%1000000000ul; scan_msg.header.stamp = start_scan_time; scan_msg.header.frame_id = cfg.frame_id; scan_msg.angle_min =(scan.config.min_angle); scan_msg.angle_max = (scan.config.max_angle); scan_msg.angle_increment = (scan.config.angle_increment); scan_msg.scan_time = scan.config.scan_time; scan_msg.time_increment = scan.config.time_increment; scan_msg.range_min = (scan.config.min_range); scan_msg.range_max = (scan.config.max_range); int size = (scan.config.max_angle - scan.config.min_angle)/ scan.config.angle_increment + 1; scan_msg.ranges.resize(size); scan_msg.intensities.resize(size); for(int i=0; i < scan.points.size(); i++) { int index = std::ceil((scan.points[i].angle - scan.config.min_angle)/scan.config.angle_increment); if(index >=0 && index < size) { scan_msg.ranges[index] = scan.points[i].range; scan_msg.intensities[index] = scan.points[i].intensity; } } scan_pub.publish(scan_msg); } else { ROS_WARN("Lidar Data Invalid!"); } } else //未收到数据 超过15次 则报错 { ROS_ERROR("Failed to get Lidar Data!"); break; } ros::spinOnce(); rate.sleep(); } laser.LidarTurnOff(); printf("[NVILIDAR INFO] Now NVILIDAR is stopping .......\n"); laser.LidarCloseHandle(); return 0; }
41.112676
118
0.585988
nvilidar
72552a27087650526330ce8bc4cddfc193cba1fd
6,282
cpp
C++
samples/old/sample_condens_tracking.cpp
gtmtg/cvdrone
ef736dc7a2a1a806f7cea4088268e439e53c1f33
[ "BSD-3-Clause" ]
1
2015-01-04T16:22:31.000Z
2015-01-04T16:22:31.000Z
cvdrone/samples/old/sample_condens_tracking.cpp
MLHCoderTeam/ARDrone
b7b51a2e8c172944c04e7b64bb792b68931e6d3f
[ "MIT" ]
null
null
null
cvdrone/samples/old/sample_condens_tracking.cpp
MLHCoderTeam/ARDrone
b7b51a2e8c172944c04e7b64bb792b68931e6d3f
[ "MIT" ]
1
2018-02-28T17:29:35.000Z
2018-02-28T17:29:35.000Z
#include "ardrone/ardrone.h" #include "opencv2/legacy/legacy.hpp" #include "opencv2/legacy/compat.hpp" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char **argv) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { printf("Failed to initialize.\n"); return -1; } // Particle filter CvConDensation *con = cvCreateConDensation(4, 0, 3000); // Setup CvMat *lowerBound = cvCreateMat(4, 1, CV_32FC1); CvMat *upperBound = cvCreateMat(4, 1, CV_32FC1); cvmSet(lowerBound, 0, 0, 0); cvmSet(lowerBound, 1, 0, 0); cvmSet(lowerBound, 2, 0, -10); cvmSet(lowerBound, 3, 0, -10); cvmSet(upperBound, 0, 0, ardrone.getImage()->width); cvmSet(upperBound, 1, 0, ardrone.getImage()->height); cvmSet(upperBound, 2, 0, 10); cvmSet(upperBound, 3, 0, 10); // Initialize particle filter cvConDensInitSampleSet(con, lowerBound, upperBound); // Linear system con->DynamMatr[0] = 1.0; con->DynamMatr[1] = 0.0; con->DynamMatr[2] = 1.0; con->DynamMatr[3] = 0.0; con->DynamMatr[4] = 0.0; con->DynamMatr[5] = 1.0; con->DynamMatr[6] = 0.0; con->DynamMatr[7] = 1.0; con->DynamMatr[8] = 0.0; con->DynamMatr[9] = 0.0; con->DynamMatr[10] = 1.0; con->DynamMatr[11] = 0.0; con->DynamMatr[12] = 0.0; con->DynamMatr[13] = 0.0; con->DynamMatr[14] = 0.0; con->DynamMatr[15] = 1.0; // Noises cvRandInit(&(con->RandS[0]), -25, 25, (int)cvGetTickCount()); cvRandInit(&(con->RandS[1]), -25, 25, (int)cvGetTickCount()); cvRandInit(&(con->RandS[2]), -5, 5, (int)cvGetTickCount()); cvRandInit(&(con->RandS[3]), -5, 5, (int)cvGetTickCount()); // Thresholds int minH = 0, maxH = 255; int minS = 0, maxS = 255; int minV = 0, maxV = 255; // Create a window cvNamedWindow("binalized"); cvCreateTrackbar("H max", "binalized", &maxH, 255); cvCreateTrackbar("H min", "binalized", &minH, 255); cvCreateTrackbar("S max", "binalized", &maxS, 255); cvCreateTrackbar("S min", "binalized", &minS, 255); cvCreateTrackbar("V max", "binalized", &maxV, 255); cvCreateTrackbar("V min", "binalized", &minV, 255); cvResizeWindow("binalized", 0, 0); // Main loop while (1) { // Key input int key = cvWaitKey(1); if (key == 0x1b) break; // Update if (!ardrone.update()) break; // Get an image IplImage *image = ardrone.getImage(); // HSV image IplImage *hsv = cvCloneImage(image); cvCvtColor(image, hsv, CV_RGB2HSV_FULL); // Binalized image IplImage *binalized = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1); // Binalize CvScalar lower = cvScalar(minH, minS, minV); CvScalar upper = cvScalar(maxH, maxS, maxV); cvInRangeS(hsv, lower, upper, binalized); // Show result cvShowImage("binalized", binalized); // De-noising cvMorphologyEx(binalized, binalized, NULL, NULL, CV_MOP_CLOSE); // Detect contours CvSeq *contour = NULL, *maxContour = NULL; CvMemStorage *contourStorage = cvCreateMemStorage(); cvFindContours(binalized, contourStorage, &contour, sizeof(CvContour), CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); // Find largest contour double max_area = 0.0; while (contour) { double area = fabs(cvContourArea(contour)); if ( area > max_area) { maxContour = contour; max_area = area; } contour = contour->h_next; } // Object detected if (maxContour) { // Draw a contour cvZero(binalized); cvDrawContours(binalized, maxContour, cvScalarAll(255), cvScalarAll(255), 0, CV_FILLED); // Calculate the moments CvMoments moments; cvMoments(binalized, &moments, 1); int my = (int)(moments.m01/moments.m00); int mx = (int)(moments.m10/moments.m00); cvCircle(image, cvPoint(mx, my), 10, CV_RGB(255,0,0)); // Calculate confidences for (int i = 0; i < con->SamplesNum; i++) { // Sample points float x = (con->flSamples[i][0]); float y = (con->flSamples[i][1]); // Valid sample point if (x > 0 && x < image->width && y > 0 && y < image->height) { // Assume as gauss distribution double sigma = 50.0; double dist = hypot(x - mx, y - my); // Distance to moment con->flConfidence[i] = 1.0 / (sqrt (2.0 * CV_PI) * sigma) * expf (-dist*dist / (2.0 * sigma*sigma)); } else con->flConfidence[i] = 0.0; cvCircle(image, cvPointFrom32f(cvPoint2D32f(x, y)), 3, CV_RGB(0,128,con->flConfidence[i] * 50000)); } } // Update phase cvConDensUpdateByTime(con); // Sum of positions and confidences for calcurate weighted mean value double sumX = 0, sumY = 0, sumConf = 0; for (int i = 0; i < con->SamplesNum; i++) { sumX += con->flConfidence[i] * con->flSamples[i][0]; sumY += con->flConfidence[i] * con->flSamples[i][1]; sumConf += con->flConfidence[i]; } // Estimated value if (sumConf > 0.0) { float x = sumX / sumConf; float y = sumY / sumConf; cvCircle(image, cvPointFrom32f(cvPoint2D32f(x, y)), 10, CV_RGB(0,255,0)); } // Display the image cvShowImage("camera", image); // Release memories cvReleaseImage(&hsv); cvReleaseImage(&binalized); cvReleaseMemStorage(&contourStorage); } // Release the particle filter cvReleaseMat(&lowerBound); cvReleaseMat(&upperBound); cvReleaseConDensation(&con); // See you ardrone.close(); return 0; }
35.094972
121
0.550143
gtmtg
725848bbef08765ee3c2fd3a438ff55a57a816d3
314
cpp
C++
src/HttpException.cpp
Andreev-Sergey/diadocsdk-cpp
01d9fa2b90bc6f42ef3d9c20f29207b3a5bf6eda
[ "MIT" ]
7
2016-05-31T17:37:54.000Z
2022-01-17T14:28:18.000Z
src/HttpException.cpp
Andreev-Sergey/diadocsdk-cpp
01d9fa2b90bc6f42ef3d9c20f29207b3a5bf6eda
[ "MIT" ]
22
2017-02-07T09:34:02.000Z
2021-09-06T08:08:34.000Z
src/HttpException.cpp
Andreev-Sergey/diadocsdk-cpp
01d9fa2b90bc6f42ef3d9c20f29207b3a5bf6eda
[ "MIT" ]
23
2016-06-07T06:11:47.000Z
2020-10-06T13:00:21.000Z
#include "StdAfx.h" #include "HttpException.h" HttpException::HttpException(const std::string& message, DWORD statusCode, const std::string& serverMessage) : std::runtime_error(message + ": " + serverMessage) , StatusCode(statusCode) , ServerMessage(serverMessage) { } HttpException::~HttpException(void) { }
22.428571
108
0.751592
Andreev-Sergey
725a6fee179a041420c62fba2778f9c48875c24f
885
cpp
C++
plugin_III/game_III/COneSheet.cpp
gta-chaos-mod/plugin-sdk
e3bf176337774a2afc797a47825f81adde78e899
[ "Zlib" ]
368
2015-01-01T21:42:00.000Z
2022-03-29T06:22:22.000Z
plugin_III/game_III/COneSheet.cpp
SteepCheat/plugin-sdk
a17c5d933cb8b06e4959b370092828a6a7aa00ef
[ "Zlib" ]
89
2016-05-08T06:42:36.000Z
2022-03-29T06:49:09.000Z
plugin_III/game_III/COneSheet.cpp
SteepCheat/plugin-sdk
a17c5d933cb8b06e4959b370092828a6a7aa00ef
[ "Zlib" ]
179
2015-02-03T23:41:17.000Z
2022-03-26T08:27:16.000Z
/* Plugin-SDK (Grand Theft Auto 3) source file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #include "COneSheet.h" PLUGIN_SOURCE_FILE int addrof(COneSheet::AddToList) = ADDRESS_BY_VERSION(0x512650, 0x512860, 0x5127F0); int gaddrof(COneSheet::AddToList) = GLOBAL_ADDRESS_BY_VERSION(0x512650, 0x512860, 0x5127F0); void COneSheet::AddToList(COneSheet *list) { plugin::CallMethodDynGlobal<COneSheet *, COneSheet *>(gaddrof(COneSheet::AddToList), this, list); } int addrof(COneSheet::RemoveFromList) = ADDRESS_BY_VERSION(0x512670, 0x512880, 0x512810); int gaddrof(COneSheet::RemoveFromList) = GLOBAL_ADDRESS_BY_VERSION(0x512670, 0x512880, 0x512810); void COneSheet::RemoveFromList() { plugin::CallMethodDynGlobal<COneSheet *>(gaddrof(COneSheet::RemoveFromList), this); }
36.875
101
0.769492
gta-chaos-mod
725a8de4df3ddf457f4cb88bfedb7bda0b6cadcc
4,830
cpp
C++
gbEmu/src/Gb.cpp
Mesiow/gbEmu
fe73b1a919517a34d30dd7a439efffbe68d8644a
[ "MIT" ]
2
2021-04-27T00:54:47.000Z
2021-06-07T13:41:25.000Z
gbEmu/src/Gb.cpp
Mesiow/gbEmu
fe73b1a919517a34d30dd7a439efffbe68d8644a
[ "MIT" ]
null
null
null
gbEmu/src/Gb.cpp
Mesiow/gbEmu
fe73b1a919517a34d30dd7a439efffbe68d8644a
[ "MIT" ]
null
null
null
#include "../include/Gb.h" namespace gbEmu { Gb::Gb() :mmu(), cpu(&mmu), ppu(&mmu), joypad(&mmu) { mmu.connectJoypad(&joypad); //cart.load("roms/Kirby's Dream Land.gb"); //cart.load("roms/Pokemon Red.gb"); //cart.load("roms/SUPERMAR.gbc"); //cart.load("roms/Dr. Mario.gb"); //cart.load("roms/Tetris.gb"); //cart.load("roms/ZELDA.gbc"); //cart.load("roms/fairylake.gb"); //cart.load("roms/Tennis.gb"); //Tests //cart.load("test_roms/02-interrupts.gb"); cart.load("test_roms/ppu/dmg-acid2.gb"); //cart.load("test_roms/ppu/bg_m9800_d8800.gb"); //cart.load("test_roms/numism.gb"); //cart.load("test_roms/statcount.gb"); //cart.load("test_roms/cpu_instrs.gb"); //cart.load("test_roms/mbc/mbc1/bits_mode.gb"); //cart.load("test_roms/instr_timing.gb"); //cart.load("test_roms/mem_timing.gb"); mmu.loadBios("roms/DMG_ROM.GB"); mmu.loadCartridge(&cart); ppu.init(); } void Gb::update(float dt) { s32 cycles_this_frame = 0; //each scanline takes 456 t cycles. //There are 154 scanlines per frame. //(456 * 154) = 70224(maxCycles) while (cycles_this_frame < maxCycles) { s32 cycle = cpu.clock(); cycles_this_frame += cycle; cpu.handleTimer(cycle); ppu.update(cycles_this_frame); cpu.handleInterrupts(); } ppu.bufferPixels(); /* if (dt < delayTime) { std::this_thread::sleep_for(std::chrono::duration<float, std::milli>(delayTime - dt)); }*/ } void Gb::render(sf::RenderTarget& target) { ppu.render(target); } void Gb::handleEvents(sf::Event& ev) { handleKeyReleased(ev); handleKeyPressed(ev); } void Gb::handleKeyReleased(sf::Event& ev) { if (ev.type == sf::Event::KeyReleased) { if (ev.key.code == sf::Keyboard::Right) { joypad.keyReleased(Key::ArrowRight); } } if (ev.type == sf::Event::KeyReleased) { if (ev.key.code == sf::Keyboard::Left) { joypad.keyReleased(Key::ArrowLeft); } } if (ev.type == sf::Event::KeyReleased) { if (ev.key.code == sf::Keyboard::Up) { joypad.keyReleased(Key::ArrowUp); } } if (ev.type == sf::Event::KeyReleased) { if (ev.key.code == sf::Keyboard::Down) { joypad.keyReleased(Key::ArrowDown); } } if (ev.type == sf::Event::KeyReleased) { if (ev.key.code == sf::Keyboard::S) { joypad.keyReleased(Key::S); } } if (ev.type == sf::Event::KeyReleased) { if (ev.key.code == sf::Keyboard::A) { joypad.keyReleased(Key::A); } } if (ev.type == sf::Event::KeyReleased) { if (ev.key.code == sf::Keyboard::LShift) { joypad.keyReleased(Key::LShift); } } if (ev.type == sf::Event::KeyReleased) { if (ev.key.code == sf::Keyboard::Enter) { joypad.keyReleased(Key::Enter); } } } void Gb::handleKeyPressed(sf::Event& ev) { if (ev.type == sf::Event::KeyPressed) { if (ev.key.code == sf::Keyboard::Right) { joypad.keyPressed(Key::ArrowRight); } } if (ev.type == sf::Event::KeyPressed) { if (ev.key.code == sf::Keyboard::Left) { joypad.keyPressed(Key::ArrowLeft); } } if (ev.type == sf::Event::KeyPressed) { if (ev.key.code == sf::Keyboard::Up) { joypad.keyPressed(Key::ArrowUp); } } if (ev.type == sf::Event::KeyPressed) { if (ev.key.code == sf::Keyboard::Down) { joypad.keyPressed(Key::ArrowDown); } } if (ev.type == sf::Event::KeyPressed) { if (ev.key.code == sf::Keyboard::S) { joypad.keyPressed(Key::S); } } if (ev.type == sf::Event::KeyPressed) { if (ev.key.code == sf::Keyboard::A) { joypad.keyPressed(Key::A); } } if (ev.type == sf::Event::KeyPressed) { if (ev.key.code == sf::Keyboard::LShift) { joypad.keyPressed(Key::LShift); } } if (ev.type == sf::Event::KeyPressed) { if (ev.key.code == sf::Keyboard::Enter) { joypad.keyPressed(Key::Enter); } } } }
28.75
68
0.478882
Mesiow
725b571610b47c931e2d3339b7b584a39cd9c48d
383
hpp
C++
include/experimental/status_value.hpp
jwakely/std-make
f09d052983ace70cf371bb8ddf78d4f00330bccd
[ "BSL-1.0" ]
105
2015-01-24T13:26:41.000Z
2022-02-18T15:36:53.000Z
include/experimental/status_value.hpp
jwakely/std-make
f09d052983ace70cf371bb8ddf78d4f00330bccd
[ "BSL-1.0" ]
37
2015-09-04T06:57:10.000Z
2021-09-09T18:01:44.000Z
include/experimental/status_value.hpp
jwakely/std-make
f09d052983ace70cf371bb8ddf78d4f00330bccd
[ "BSL-1.0" ]
23
2015-01-27T11:09:18.000Z
2021-10-04T02:23:30.000Z
// 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) // // (C) Copyright 2019 Vicente J. Botet Escriba #ifndef JASEL_EXPERIMENTAL_STATUS_VALUE_HPP #define JASEL_EXPERIMENTAL_STATUS_VALUE_HPP #include <experimental/fundamental/v3/status_value/status_value.hpp> #endif // header
29.461538
68
0.793734
jwakely
7265ba91a6d32c39d10da1194ee098b04f73e398
532
cpp
C++
practice/linked_list/reverse_ll.cpp
sidgairo18/Programming-Practice
348ad38452fa9fa7b7302161455d3b3f697734da
[ "MIT" ]
2
2018-06-26T09:52:14.000Z
2018-07-12T15:02:01.000Z
practice/linked_list/reverse_ll.cpp
sidgairo18/Programming-Practice
348ad38452fa9fa7b7302161455d3b3f697734da
[ "MIT" ]
null
null
null
practice/linked_list/reverse_ll.cpp
sidgairo18/Programming-Practice
348ad38452fa9fa7b7302161455d3b3f697734da
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // a recursive version // it is more elegant // struct Node { int data; struct Node *next; } // Should reverse list and return new head. struct Node* reverseList(struct Node *head) { // code here // return head of reversed list if(head->next == NULL) return head; struct Node* temp = head->next; struct Node* new_head = reverseList(head->next); temp->next = head; head->next = NULL; return new_head; } int main(){ return 0; }
15.647059
52
0.62218
sidgairo18
726be744b2811e53c76fd038f580d4111cf5e1c4
756
cpp
C++
src/util/util_env.cpp
ChaosInitiative/dxvk-native
516c0a44b82d4b3d5000762594e0424eb383b9dd
[ "Zlib" ]
3
2020-12-20T08:53:33.000Z
2022-01-20T16:46:39.000Z
src/util/util_env.cpp
ChaosInitiative/dxvk-native
516c0a44b82d4b3d5000762594e0424eb383b9dd
[ "Zlib" ]
null
null
null
src/util/util_env.cpp
ChaosInitiative/dxvk-native
516c0a44b82d4b3d5000762594e0424eb383b9dd
[ "Zlib" ]
null
null
null
#include "util_env.h" namespace dxvk::env { #ifndef DXVK_NATIVE constexpr char dirSlash = '\\'; #else constexpr char dirSlash = '/'; #endif std::string getEnvVar(const char* name) { #ifdef DXVK_NATIVE char* result = std::getenv(name); return (result) ? result : ""; #else std::vector<WCHAR> result; result.resize(MAX_PATH + 1); DWORD len = ::GetEnvironmentVariableW(str::tows(name).c_str(), result.data(), MAX_PATH); result.resize(len); return str::fromws(result.data()); #endif } std::string getExeName() { std::string fullPath = getExePath(); auto n = fullPath.find_last_of(dirSlash); return (n != std::string::npos) ? fullPath.substr(n + 1) : fullPath; } }
18.9
92
0.616402
ChaosInitiative
726d09348dc66999cbe9d81150f434b8a8db666f
5,942
cpp
C++
GUI/control.cpp
MasterLufier/FT800-FT813
9297b7bfb26d7fe7b0f032b9d8145b3af975ac09
[ "MIT" ]
null
null
null
GUI/control.cpp
MasterLufier/FT800-FT813
9297b7bfb26d7fe7b0f032b9d8145b3af975ac09
[ "MIT" ]
null
null
null
GUI/control.cpp
MasterLufier/FT800-FT813
9297b7bfb26d7fe7b0f032b9d8145b3af975ac09
[ "MIT" ]
null
null
null
#include "control.h" namespace FTGUI { Button::Button(string label, Widget * parent) : Rectangle(parent) { m_name = "Button"; m_label = new Label(label, this); m_label->setHorizontalAlignment(Label::HCenter); m_label->setVerticalAlignment(Label::VCenter); m_label->setColor(m_theme->onPrimary()); if(m_parent->name() == "ButtonGroup") { setCheckable(true); } setGeometry(m_x, m_y, m_width, m_height); } void Button::setGeometry(int32_t x, int32_t y, uint16_t width, uint16_t height) { m_label->setGeometry(width / 2 - 1, height / 2 - 1, width, height); Widget::setGeometry(x, y, width, height); if(m_checker) { m_checker->setWidth(m_width - m_width / 5); m_checker->setX(m_width / 10); m_checker->setHeight(m_height / 12); m_checker->setY(m_height - m_checker->height()); } } void Button::setLabel(string text) { m_label->setText(text); } bool Button::pressed() const { return m_pressed; } void Button::setPressed(bool pressed) { m_pressed = pressed; if(pressed) setColor(theme()->primaryLight()); else setColor(theme()->primary()); if(m_visible) update(); } bool Button::touchPressed(int16_t x, int16_t y) { if(!m_enabled) return false; if(Widget::touchPressed(x, y)) { setPressed(true); return true; } return false; } bool Button::touchReleased(int16_t x, int16_t y, int16_t accelerationX, int16_t accelerationY) { if(!m_enabled) return false; if(Widget::touchReleased(x, y, accelerationX, accelerationY)) { if(!m_pressed) return true; setPressed(false); return true; } if(!m_pressed) return false; setPressed(false); return false; } bool Button::checkable() const { return m_checkable; } void Button::setCheckable(bool checkable) { m_checkable = checkable; if(m_checkable) { if(!m_checker) m_checker = new Rectangle(this); m_checker->setWidth(m_width - m_width / 5); m_checker->setX(m_width / 10); m_checker->setHeight(m_height / 12); m_checker->setColor(Main::LightGrey); m_checker->setY(m_height - m_checker->height()); } else { delete m_checker; } } bool Button::checked() const { return m_checked; } void Button::setChecked(bool checked) { if(!m_checkable) return; m_checked = checked; if(m_checked) { m_checker->setColor(Main::Error); } else { m_checker->setColor(Main::LightGrey); } if(m_visible) update(); } bool Button::enabled() const { return m_enabled; } void Button::setEnabled(bool enabled) { m_enabled = enabled; if(m_enabled) { setColor(theme()->primary()); m_label->setColor(theme()->onPrimary()); } else { setColor(Main::LightGrey); m_label->setColor(Main::Dark); } if(m_visible) update(); } void ButtonGroup::addWidget(Widget * widget) { // if(widget->name() != "Button") // { // error("Button group can contain only button as children \n"); // return; // } Widget::addWidget(widget); m_widgetAdded = true; } void ButtonGroup::show() { if(m_widgetAdded) { for(uint16_t i = 0; i < m_container.size(); ++i) { auto w = childAt(i); w->setCheckable(true); if(i == 0) w->setChecked(true); w->onReleased([&, in = i]() { if(m_index == in) return; this->setIndex(in); }); } m_widgetAdded = false; setGeometry(m_x, m_y, m_width, m_height); } Widget::show(); } void ButtonGroup::setGeometry(int32_t x, int32_t y, uint16_t width, uint16_t height) { Widget::setGeometry(x, y, width, height); uint16_t fWidth = (m_width / m_container.size()) - /*(m_container.size() * m_padding) -*/ m_padding; for(uint16_t i = 0; i < m_container.size(); ++i) { this->childAt(i)->setGeometry((i * (fWidth + m_padding)) + (m_padding / 2), 0, fWidth, m_height); } } uint16_t ButtonGroup::index() const { return m_index; } void ButtonGroup::setIndex(const uint16_t & index) { if(index == m_index) return; this->childAt(m_index)->setChecked(false); m_index = index; this->childAt(m_index)->setChecked(true); if(m_onIndexChanged) m_onIndexChanged->operator()(m_index); } uint8_t ButtonGroup::padding() const { return m_padding; } void ButtonGroup::setPadding(const uint8_t & padding) { m_padding = padding; } void ButtonGroup::setRadius(uint8_t radius) { for(uint16_t i = 0; i < m_container.size(); ++i) { childAt(i)->setRadius(radius); } } float RangeController::min() const { return m_min; } void RangeController::setMin(float min) { m_min = min; m_range = m_max - m_min; } float RangeController::max() const { return m_max; } void RangeController::setMax(float max) { m_max = max; m_range = m_max - m_min; } float RangeController::value() const { return m_value; } void RangeController::setValue(float value) { m_value = value; m_onValueChanged->operator()(value); //TODO: Move update from here to global level update function update(); } } // namespace FTGUI
21.070922
83
0.551498
MasterLufier
726e1a8ee51fb97176e7fc711d90dfa8c7e9a528
279
hpp
C++
WICWIU_src/Utils.hpp
KwonYeseong/WICWIU_stamp
690c3f194e507b59510229ed12a16f759235342c
[ "Apache-2.0" ]
3
2019-03-03T10:39:20.000Z
2020-08-10T12:45:06.000Z
WICWIU_src/Utils.hpp
yoondonghwee/WICWIU
2c515108985abf91802dd02a423be94afc883b2e
[ "Apache-2.0" ]
null
null
null
WICWIU_src/Utils.hpp
yoondonghwee/WICWIU
2c515108985abf91802dd02a423be94afc883b2e
[ "Apache-2.0" ]
null
null
null
#ifndef UTILS_H_ #define UTILS_H_ value #ifdef __CUDNN__ #define MAX_CUDA_DEVICE 32 int GetCurrentCudaDevice(); void GetKernelParameters(int totalThread, int *pNoBlock, int *pThreadsPerBlock, int blockSize = 128); #endif // ifdef __CUDNN__ #endif // ifndef UTILS_H_
17.4375
101
0.763441
KwonYeseong
7271e994bcf6bfa9176fa08e62727f15d22d8b51
2,026
cpp
C++
src/Reader/IniConfigReader.cpp
fcaillaud/SARAH
ca79c7d9449cf07eec9d5cc13293ec0c128defc1
[ "MIT" ]
null
null
null
src/Reader/IniConfigReader.cpp
fcaillaud/SARAH
ca79c7d9449cf07eec9d5cc13293ec0c128defc1
[ "MIT" ]
null
null
null
src/Reader/IniConfigReader.cpp
fcaillaud/SARAH
ca79c7d9449cf07eec9d5cc13293ec0c128defc1
[ "MIT" ]
null
null
null
#include "IniConfigReader.hpp" namespace Sarah { namespace IO { IniConfigReader::IniConfigReader(std::string p_filePath): BaseReader(p_filePath) { } bool IniConfigReader::Read() { unsigned int vNumLine = 0; boost::smatch vMatches; const boost::regex vSectRegex("\\s*\\[.+\\]\\s*"); std::string vLine; std::string vCurrentSection = "undefined"; std::vector<std::string> vPropertyLine; std::string vPropertyName, vPropertyValue; while(GetLine(vLine)) { vNumLine++; //Si la ligne n'est pas un commentaire (# .... ou ; ....) if( ! (gu::IsComments(vLine, '#') || gu::IsComments(vLine, ';')) ) { if(boost::regex_match(vLine, vMatches, vSectRegex)) { if(vMatches.size() == 1) { vCurrentSection = gu::WithoutChar(gu::WithoutChar(vMatches[0], ']'), '['); vCurrentSection = gu::WithoutFrontSpace(gu::WithoutBackSpace(vCurrentSection)); m_config.insert(std::pair<std::string, Section>(vCurrentSection, Section())); } else { msg::Msg_Spe(msg::MSG_FLAG_ENUM::ERROR, "Error in IniConfigReader.Read : Line ", vNumLine, " -> Wrong Syntax in Section Declaration"); exit(-1); } } else { vLine = gu::WithoutComments(gu::WithoutComments(vLine, '#'), ';'); vPropertyLine = gu::Split(vLine, '='); if(vPropertyLine.size() == 2) { vPropertyName = gu::WithoutFrontSpace(gu::WithoutBackSpace(vPropertyLine[0])); vPropertyValue = gu::WithoutFrontSpace(gu::WithoutBackSpace(vPropertyLine[1])); m_config[vCurrentSection].insert(std::pair<std::string, std::string>(vPropertyName, vPropertyValue)); } else { //TODO : peut être gérer quand même l'erreur au lieu d'exit msg::Msg_Spe(msg::MSG_FLAG_ENUM::ERROR, "Error in IniConfigReader.Read : Line ", vNumLine, " -> Wrong Syntax in Property Declaration"); exit(-1); } } } } return HasSucceed(); } IniConfigReader::Config IniConfigReader::GetConfig() const { return m_config; } } }
25.974359
141
0.63771
fcaillaud
72724c64c69adc56877a8001b9e6686ba46a87a2
1,379
cpp
C++
src/Text.cpp
JohnBobSmith/SpaceyRocks
3ee95fbdd11f2f7c972b869931cce6c426c878d0
[ "MIT" ]
1
2019-04-19T05:08:25.000Z
2019-04-19T05:08:25.000Z
src/Text.cpp
JohnBobSmith/SpaceyRocks
3ee95fbdd11f2f7c972b869931cce6c426c878d0
[ "MIT" ]
null
null
null
src/Text.cpp
JohnBobSmith/SpaceyRocks
3ee95fbdd11f2f7c972b869931cce6c426c878d0
[ "MIT" ]
null
null
null
#include "Resources.h" #include "Text.h" #include "G_Miscfuncandvar.h" Text::Text() { //Screen dimensions G_Miscfuncandvar gmiscfuncandvar; //Load our font blockFont.loadFromFile( PKGDATADIR "/fonts/ehsmb.ttf"); //Load our game over text gameOverText.setFont(blockFont); gameOverText.setString("Game Over"); gameOverText.setCharacterSize(110); gameOverText.setColor(sf::Color::Red); gameOverText.setStyle(sf::Text::Regular); //Center the text on screen gameOverText.setPosition(gmiscfuncandvar.screenWidth / 8, gmiscfuncandvar.screenHeight / 3); //Load our victory/win text winText.setFont(blockFont); winText.setString("You WIN!!"); winText.setCharacterSize(110); winText.setColor(sf::Color::Green); winText.setStyle(sf::Text::Regular); //Center the text on screen winText.setPosition(gmiscfuncandvar.screenWidth / 8, gmiscfuncandvar.screenHeight / 3); //Load our "Space bar to start" text spaceTostartText.setFont(blockFont); spaceTostartText.setString("Space bar to start"); spaceTostartText.setCharacterSize(55); spaceTostartText.setColor(sf::Color::Yellow); spaceTostartText.setStyle(sf::Text::Regular); //Position this text just below our win/loss text spaceTostartText.setPosition(gmiscfuncandvar.screenWidth / 8, gmiscfuncandvar.screenHeight / 2); }
31.340909
100
0.725163
JohnBobSmith
72725dd87581dfa00f6c62f946932c03bf3f3fd3
1,937
cpp
C++
src/point_cloud_assembler_srv.cpp
StratomInc/laser_assembler
25640f99d043b37e34310e5e0194496b8cc55895
[ "Apache-2.0" ]
null
null
null
src/point_cloud_assembler_srv.cpp
StratomInc/laser_assembler
25640f99d043b37e34310e5e0194496b8cc55895
[ "Apache-2.0" ]
null
null
null
src/point_cloud_assembler_srv.cpp
StratomInc/laser_assembler
25640f99d043b37e34310e5e0194496b8cc55895
[ "Apache-2.0" ]
1
2021-04-08T15:03:40.000Z
2021-04-08T15:03:40.000Z
// Copyright 2018 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <string> #include "laser_assembler/base_assembler_srv.hpp" namespace laser_assembler { /** * \brief Maintains a history of incremental point clouds (usually from laser scans) and generates a point cloud upon request * \todo Clean up the doxygen part of this header * params * * (Several params are inherited from BaseAssemblerSrv) */ class PointCloudAssemblerSrv : public BaseAssemblerSrv<sensor_msgs::msg::PointCloud> { public: PointCloudAssemblerSrv() { } ~PointCloudAssemblerSrv() { } unsigned int GetPointsInScan(const sensor_msgs::msg::PointCloud & scan) { return scan.points.size(); } void ConvertToCloud( const string & fixed_frame_id, const sensor_msgs::PointCloud & scan_in, sensor_msgs::PointCloud & cloud_out) { tf_->transformPointCloud(fixed_frame_id, scan_in, cloud_out); } private: }; } // namespace laser_assembler int main(int argc, char ** argv) { ros::init(argc, argv, "point_cloud_assembler"); ros::NodeHandle n; RCLCPP_WARN(n_->get_logger(), "The point_cloud_assembler_srv is deprecated. Please switch to " "using the laser_scan_assembler. Documentation is available at " "http://www.ros.org/wiki/laser_assembler"); laser_assembler::PointCloudAssemblerSrv pc_assembler; pc_assembler.start(); ros::spin(); return 0; }
29.348485
125
0.740836
StratomInc
727886d722fca616a9c4ac7ed4292cd9bd757a94
225
cpp
C++
tests/main.cpp
arthurchaloin/indie
84fa7f0864c54e4b35620235ca4e852d7b85fffd
[ "MIT" ]
null
null
null
tests/main.cpp
arthurchaloin/indie
84fa7f0864c54e4b35620235ca4e852d7b85fffd
[ "MIT" ]
null
null
null
tests/main.cpp
arthurchaloin/indie
84fa7f0864c54e4b35620235ca4e852d7b85fffd
[ "MIT" ]
null
null
null
/* ** EPITECH PROJECT, 2017 ** indie ** File description: ** A file for indie - Paul Laffitte */ #include <gtest/gtest.h> int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
13.235294
38
0.671111
arthurchaloin
727b41d53150f4cc5c2a53a47e5bd2c77ebe1c83
477
cpp
C++
build/b4-e6-2d-e0-5c-5d/user_app.cpp
chp-lab/nx2003-kidbright
1660fccae722f61b56194cb44857c3e724e4c159
[ "MIT" ]
null
null
null
build/b4-e6-2d-e0-5c-5d/user_app.cpp
chp-lab/nx2003-kidbright
1660fccae722f61b56194cb44857c3e724e4c159
[ "MIT" ]
null
null
null
build/b4-e6-2d-e0-5c-5d/user_app.cpp
chp-lab/nx2003-kidbright
1660fccae722f61b56194cb44857c3e724e4c159
[ "MIT" ]
null
null
null
#include <Arduino.h> #include <WiFi.h> #include <WiFiClient.h> #include <WiFiAP.h> #include <WebServer.h> #include <NX2003BUZZER.h> NX2003BUZZER music = NX2003BUZZER(); void setup() { music.begin(); } void loop() { music.song((std::vector<int>{262,523,220,440,233,466,-1,-1,175,349,147,294,156,311,-1,-1,175,349,147,294,156,311,-1,-1,175,349,147,294,156,311,-1,-1,311,277,294,277,311,311,208,196,277,262,370,349,165,466,440,415,311,247,233,220,208}),250); }
19.08
244
0.668763
chp-lab
727b96770131694f5aa981bbc58a6a8113311d46
261
cpp
C++
judges/codeforces/exercises/anton_and_letters.cpp
eduardonunes2525/competitive-programming
0f6bdc573b4d03d1ed20a2b77ec5388dca1ee47b
[ "MIT" ]
null
null
null
judges/codeforces/exercises/anton_and_letters.cpp
eduardonunes2525/competitive-programming
0f6bdc573b4d03d1ed20a2b77ec5388dca1ee47b
[ "MIT" ]
1
2018-10-17T11:53:02.000Z
2018-10-17T11:54:42.000Z
judges/codeforces/exercises/anton_and_letters.cpp
eduardonunes2525/competitive-programming
0f6bdc573b4d03d1ed20a2b77ec5388dca1ee47b
[ "MIT" ]
1
2018-10-17T12:14:04.000Z
2018-10-17T12:14:04.000Z
#include<bits/stdc++.h> using namespace std; int main(){ string s; getline(cin, s); set<char> st; for(auto c : s) if((c >= 97 and c<= 122) or (c >= 65 and c<= 90)) st.insert(c); cout << st.size() << "\n"; return 0; }
16.3125
57
0.482759
eduardonunes2525
727ea4f7adc197c7824460b9f2a8fcb17a618b5a
6,269
hh
C++
dune/xt/grid/grids.hh
dune-community/dune-xt-grid
3453f6619fabc016beaf32409627fec8712f3ef9
[ "BSD-2-Clause" ]
2
2016-04-04T08:06:07.000Z
2020-02-08T04:10:38.000Z
dune/xt/grid/grids.hh
dune-community/dune-xt-grid
3453f6619fabc016beaf32409627fec8712f3ef9
[ "BSD-2-Clause" ]
77
2016-01-24T22:11:21.000Z
2020-03-25T08:30:31.000Z
dune/xt/grid/grids.hh
dune-community/dune-xt-grid
3453f6619fabc016beaf32409627fec8712f3ef9
[ "BSD-2-Clause" ]
4
2016-11-08T10:12:44.000Z
2020-02-08T04:10:41.000Z
// This file is part of the dune-xt-grid project: // https://github.com/dune-community/dune-xt-grid // Copyright 2009-2018 dune-xt-grid developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2016 - 2018) // René Fritze (2017 - 2018) // TiKeil (2018) // Tobias Leibner (2016) #ifndef DUNE_XT_GRID_GRIDS_HH #define DUNE_XT_GRID_GRIDS_HH #include <boost/tuple/tuple.hpp> #if HAVE_ALBERTA # include <dune/xt/common/disable_warnings.hh> # include <dune/grid/albertagrid.hh> # include <dune/xt/common/reenable_warnings.hh> #endif #if HAVE_DUNE_ALUGRID # include <dune/alugrid/grid.hh> #endif #if HAVE_DUNE_SPGRID # include <dune/grid/spgrid.hh> # include <dune/grid/spgrid/dgfparser.hh> #endif #if HAVE_DUNE_UGGRID || HAVE_UG # include <dune/grid/uggrid.hh> #endif #include <dune/grid/onedgrid.hh> #include <dune/grid/yaspgrid.hh> // this is used by other headers typedef Dune::OneDGrid ONED_1D; typedef Dune::YaspGrid<1, Dune::EquidistantOffsetCoordinates<double, 1>> YASP_1D_EQUIDISTANT_OFFSET; typedef Dune::YaspGrid<2, Dune::EquidistantOffsetCoordinates<double, 2>> YASP_2D_EQUIDISTANT_OFFSET; typedef Dune::YaspGrid<3, Dune::EquidistantOffsetCoordinates<double, 3>> YASP_3D_EQUIDISTANT_OFFSET; typedef Dune::YaspGrid<4, Dune::EquidistantOffsetCoordinates<double, 4>> YASP_4D_EQUIDISTANT_OFFSET; #if HAVE_DUNE_ALUGRID typedef Dune::ALUGrid<2, 2, Dune::simplex, Dune::conforming> ALU_2D_SIMPLEX_CONFORMING; typedef Dune::ALUGrid<2, 2, Dune::simplex, Dune::nonconforming> ALU_2D_SIMPLEX_NONCONFORMING; typedef Dune::ALUGrid<2, 2, Dune::cube, Dune::nonconforming> ALU_2D_CUBE; typedef Dune::ALUGrid<3, 3, Dune::simplex, Dune::conforming> ALU_3D_SIMPLEX_CONFORMING; typedef Dune::ALUGrid<3, 3, Dune::simplex, Dune::nonconforming> ALU_3D_SIMPLEX_NONCONFORMING; typedef Dune::ALUGrid<3, 3, Dune::cube, Dune::nonconforming> ALU_3D_CUBE; #endif #if HAVE_DUNE_UGGRID || HAVE_UG typedef Dune::UGGrid<2> UG_2D; typedef Dune::UGGrid<3> UG_3D; #endif #if HAVE_ALBERTA typedef Dune::AlbertaGrid<2, 2> ALBERTA_2D; typedef Dune::AlbertaGrid<3, 3> ALBERTA_3D; #endif namespace Dune { namespace XT { namespace Grid { namespace internal { // To give better error messages, required below. template <size_t d> class ThereIsNoSimplexGridAvailableInDimension {}; } // namespace internal /** * \note Alberta grids are missing here on purpose, these cannot be handled automatically very well. */ using Available1dGridTypes = boost::tuple<ONED_1D, YASP_1D_EQUIDISTANT_OFFSET>; /** * \note Alberta grids are missing here on purpose, these cannot be handled automatically very well. */ using Available2dGridTypes = boost::tuple<YASP_2D_EQUIDISTANT_OFFSET #if HAVE_DUNE_ALUGRID , ALU_2D_SIMPLEX_CONFORMING, ALU_2D_SIMPLEX_NONCONFORMING, ALU_2D_CUBE #endif #if HAVE_DUNE_UGGRID || HAVE_UG , UG_2D #endif >; /** * \note Alberta grids are missing here on purpose, these cannot be handled automatically very well. */ using Available3dGridTypes = boost::tuple<YASP_3D_EQUIDISTANT_OFFSET #if HAVE_DUNE_ALUGRID , ALU_3D_SIMPLEX_CONFORMING, ALU_3D_SIMPLEX_NONCONFORMING, ALU_3D_CUBE #endif #if HAVE_DUNE_UGGRID || HAVE_UG , UG_3D #endif >; /** * \note Alberta grids are missing here on purpose, these cannot be handled automatically very well. * \todo Find a tuple implementation which allows for more than 10 elements! */ using AvailableGridTypes = boost::tuple<ONED_1D, /*YASP_1D_EQUIDISTANT_OFFSET,*/ YASP_2D_EQUIDISTANT_OFFSET, YASP_3D_EQUIDISTANT_OFFSET #if HAVE_DUNE_ALUGRID , ALU_2D_SIMPLEX_CONFORMING, /*ALU_2D_SIMPLEX_NONCONFORMING,*/ ALU_2D_CUBE, ALU_3D_SIMPLEX_CONFORMING, /*ALU_3D_SIMPLEX_NONCONFORMING,*/ ALU_3D_CUBE #endif #if HAVE_DUNE_UGGRID || HAVE_UG , UG_2D, UG_3D #endif >; } // namespace Grid } // namespace XT } // namespace Dune using SIMPLEXGRID_1D = ONED_1D; using SIMPLEXGRID_2D = #if HAVE_DUNE_ALUGRID ALU_2D_SIMPLEX_CONFORMING; #elif HAVE_DUNE_UGGRID || HAVE_UG UG_2D; #else Dune::XT::Grid::internal::ThereIsNoSimplexGridAvailableInDimension<2>; #endif using SIMPLEXGRID_3D = #if HAVE_DUNE_ALUGRID ALU_3D_SIMPLEX_CONFORMING; #elif HAVE_DUNE_UGGRID || HAVE_UG UG_3D; #else Dune::XT::Grid::internal::ThereIsNoSimplexGridAvailableInDimension<3>; #endif using CUBEGRID_1D = ONED_1D; using CUBEGRID_2D = YASP_2D_EQUIDISTANT_OFFSET; using CUBEGRID_3D = YASP_3D_EQUIDISTANT_OFFSET; #if HAVE_DUNE_ALUGRID || HAVE_DUNE_UGGRID || HAVE_UG # define SIMPLEXGRID_2D_AVAILABLE 1 # define SIMPLEXGRID_3D_AVAILABLE 1 #else # define SIMPLEXGRID_2D_AVAILABLE 0 # define SIMPLEXGRID_3D_AVAILABLE 0 #endif using GRID_1D = ONED_1D; using GRID_2D = #if SIMPLEXGRID_2D_AVAILABLE SIMPLEXGRID_2D; #else YASP_2D_EQUIDISTANT_OFFSET; #endif using GRID_3D = #if SIMPLEXGRID_3D_AVAILABLE SIMPLEXGRID_3D; #else YASP_3D_EQUIDISTANT_OFFSET; #endif #endif // DUNE_XT_GRID_GRIDS_HH
31.984694
100
0.63471
dune-community
7282ae0314a78ba4f7b08e35c668c741d77384ab
3,510
cc
C++
cpp/23/23b.cc
ckennelly/advent-of-code-2020
c0ff6bb50b74873f6cc74aa432438a9e1d6aac06
[ "Apache-2.0" ]
null
null
null
cpp/23/23b.cc
ckennelly/advent-of-code-2020
c0ff6bb50b74873f6cc74aa432438a9e1d6aac06
[ "Apache-2.0" ]
null
null
null
cpp/23/23b.cc
ckennelly/advent-of-code-2020
c0ff6bb50b74873f6cc74aa432438a9e1d6aac06
[ "Apache-2.0" ]
null
null
null
#include <algorithm> #include <cmath> #include <cstdio> #include <iostream> #include <map> #include <regex> #include <set> #include <string> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/strings/ascii.h" #include "absl/strings/numbers.h" #include "absl/strings/match.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/str_split.h" #include "absl/types/optional.h" std::string readAll() { std::stringstream buffer; buffer << std::cin.rdbuf(); return buffer.str(); } int64_t doGame(absl::string_view line) { std::list<int> cups; absl::flat_hash_map<int, std::list<int>::iterator> cup_labels; int max_cup = INT_MIN; for (auto c : line) { int cup = c - '0'; auto it = cups.insert(cups.end(), cup); bool success = cup_labels.emplace(cup, it).second; assert(success); (void) success; max_cup = std::max(max_cup, cup); } assert(max_cup == cups.size()); for (int i = max_cup + 1; i <= 1000000; i++) { auto it = cups.insert(cups.end(), i); bool success = cup_labels.emplace(i, it).second; assert(success); (void) success; } assert(cups.size() == 1000000); assert(cup_labels.size() == 1000000); max_cup = 1000000; for (int move = 0; move < 10 * 1000 * 1000; move++) { const size_t old_size = cups.size(); const int current_label = cups.front(); cups.erase(cups.begin()); int destination_cup = current_label; std::array<int, 3> picked_up; auto pickup_it = cups.begin(); for (int i = 0; i < 3; i++) { picked_up[i] = *pickup_it; pickup_it = cups.erase(pickup_it); } do { destination_cup--; if (destination_cup == 0) { destination_cup = max_cup; } if (destination_cup != picked_up[0] && destination_cup != picked_up[1] && destination_cup != picked_up[2]) { break; } } while (true); // The vector looks like: // [clockwise of current cup] ... [destination] [ picked up] ... current_label auto label_it = cup_labels.find(destination_cup); assert(*label_it->second == destination_cup); assert(label_it != cup_labels.end()); auto insert_loc = label_it->second; for (auto v : picked_up) { ++insert_loc; insert_loc = cups.insert(insert_loc, v); cup_labels[v] = insert_loc; } cup_labels[current_label] = cups.insert(cups.end(), current_label); assert(cups.size() == old_size); (void) old_size; } auto it = cup_labels.find(1); assert(it != cup_labels.end()); auto cup_it = it->second; assert(*cup_it == 1); int64_t product = 1; for (int i = 0; i < 2; i++) { ++cup_it; if (cup_it == cups.end()) { cup_it == cups.begin(); } product *= static_cast<int64_t>(*cup_it); } absl::FPrintF(stderr, "input %s => product %d\n", line, product); return product; } int main(int argc, char **argv) { std::vector<std::string> lines = absl::StrSplit(readAll(), "\n", absl::SkipEmpty()); assert(lines.size() == 1); assert(doGame("389125467") == 149245887792); absl::PrintF("%d\n", doGame(lines[0])); }
27.421875
86
0.567806
ckennelly
728589903c6585c21588bc3609b009f31c6e32df
572
hpp
C++
src/score/Score.hpp
rectoria/cpp_arcade
72bff5ec97f90dcc05ff4079f7ba30d5af9fb147
[ "MIT" ]
null
null
null
src/score/Score.hpp
rectoria/cpp_arcade
72bff5ec97f90dcc05ff4079f7ba30d5af9fb147
[ "MIT" ]
null
null
null
src/score/Score.hpp
rectoria/cpp_arcade
72bff5ec97f90dcc05ff4079f7ba30d5af9fb147
[ "MIT" ]
null
null
null
/* ** EPITECH PROJECT, 2018 ** cpp_arcade ** File description: ** */ #ifndef SCORE_HPP #define SCORE_HPP #define SAVE_EXTENSION ".log" #define SAVE_PATH "./.save/" namespace Arcade{ class Score { public: Score(); ~Score(); public: void addGame(std::string &); std::map<std::string, std::string> getGameStats(std::string &); int getPlayerScore(std::string &, std::string &); void writeStats(std::string); void setScore(std::string &, std::string &, unsigned); private: std::map<std::string, std::map<std::string, std::string>> _stats; }; } #endif
17.875
67
0.664336
rectoria
7289002d01f4f9da506733556e686207fe86f0a4
765
cpp
C++
FootCommander.cpp
OmerK25/CPP-WarGame
641921f65781ed2ee28b153012e0b8926696db11
[ "MIT" ]
null
null
null
FootCommander.cpp
OmerK25/CPP-WarGame
641921f65781ed2ee28b153012e0b8926696db11
[ "MIT" ]
null
null
null
FootCommander.cpp
OmerK25/CPP-WarGame
641921f65781ed2ee28b153012e0b8926696db11
[ "MIT" ]
1
2020-06-08T17:12:48.000Z
2020-06-08T17:12:48.000Z
#include <vector> #include "FootCommander.hpp" #include <iostream> void FootCommander::act(vector<vector<Soldier *>> &board, pair<int, int> location) { FootSoldier::act(board, location); act_as_commander(board, location); } void FootCommander::act_as_commander(vector<vector<Soldier *>> &board, pair<int, int> location) { for (int i = 0; i < board.size(); i++) { for (int j = 0; j < board[i].size(); j++) { Soldier *maybeFoot = board[i][j]; if (maybeFoot != nullptr && maybeFoot->_player() == _player()) { if (dynamic_cast<FootSoldier *>(maybeFoot) && !(dynamic_cast<FootCommander *>(maybeFoot))) maybeFoot->act(board, {i, j}); } } } }
30.6
106
0.56732
OmerK25
729697e6b1993a884f83d7e0d5953ac6d1b49f91
347
cpp
C++
code/source/common/events/KeyPressEvent.cpp
StuntHacks/infinite-dungeons
b462dd27c4e0f7285940e45d086b5d022fea23df
[ "MIT" ]
null
null
null
code/source/common/events/KeyPressEvent.cpp
StuntHacks/infinite-dungeons
b462dd27c4e0f7285940e45d086b5d022fea23df
[ "MIT" ]
null
null
null
code/source/common/events/KeyPressEvent.cpp
StuntHacks/infinite-dungeons
b462dd27c4e0f7285940e45d086b5d022fea23df
[ "MIT" ]
null
null
null
#include "common/events/KeyPressEvent.hpp" namespace id { namespace events { KeyPressEvent::KeyPressEvent(int keyCode, State state) : id::events::PressEvent(state), m_keyCode(keyCode) { /* do nothing */ } int KeyPressEvent::getKeyCode() { return m_keyCode; } } /* events */ } /* id */
24.785714
64
0.587896
StuntHacks
729a52697d4cad565ddcd4deffc2f0a061ac9ee4
1,813
cpp
C++
Mesh.cpp
rabinadk1/learnopengl
66e5a26af5e63aebc7274efc051f05a99211f5a9
[ "MIT" ]
5
2020-03-06T10:01:28.000Z
2020-05-06T07:57:20.000Z
Mesh.cpp
rabinadk1/learnopengl
66e5a26af5e63aebc7274efc051f05a99211f5a9
[ "MIT" ]
1
2020-03-06T02:51:50.000Z
2020-03-06T04:33:30.000Z
Mesh.cpp
rabinadk1/learnopengl
66e5a26af5e63aebc7274efc051f05a99211f5a9
[ "MIT" ]
29
2020-03-05T15:15:24.000Z
2021-07-21T07:05:00.000Z
#include "Mesh.hpp" #include "VertexBufferLayout.hpp" #include "Renderer.hpp" Mesh::Mesh(std::vector<Vertex> &vertices, std::vector<uint> &indices, const std::unordered_map<std::string, Texture> &texturesLoaded, std::vector<std::string> &textures) : m_TexturesLoaded(texturesLoaded), m_Vertices(vertices), m_Indices(indices), m_Textures(textures), m_VA(), m_IB(&indices[0], indices.size()), /* NOTE: Address of Vector and the address of first element of vector are different. Also, sizeof(<vector>) is the size of the vector not containing data */ m_VB(&vertices[0], sizeof(Vertex) * vertices.size()) { SetupMesh(); } void Mesh::SetupMesh() const { VertexBufferLayout layout; // For Vertex Positions layout.Push<float>(3); //For Vertex Normals layout.Push<float>(3); // For Vertex Texture Coords layout.Push<float>(2); // For Vertex Tangent layout.Push<float>(3); // For Vertex Bitangent layout.Push<float>(3); m_VA.AddBuffer(m_VB, layout); } void Mesh::Draw(Shader &shader) const { // bind appropriate textures uint diffuseNr = 1; uint specularNr = 1; for (uint i = 0; i < m_Textures.size(); ++i) { const Texture &texture = m_TexturesLoaded.find(m_Textures[i])->second; // retrieve texture number (the N in diffuse_textureN) std::string number; const std::string &textureType = texture.GetType(); if (textureType == "diffuse") number = std::to_string(diffuseNr++); else if (textureType == "specular") number = std::to_string(specularNr++); // transfer unsigned int to stream else continue; shader.SetUniform(("u_Material." + textureType + number).c_str(), static_cast<int>(i)); texture.Bind(i); } // Draw mesh Renderer::Draw(m_VA, m_IB); }
26.275362
169
0.66299
rabinadk1
729bb991876d772189dc4e027fe93c7d6d13e33f
887
cpp
C++
src/il/processing/il-processing.cpp
noct-lang/noct-bootstrap
6fd5ef91feda665dc3f1d8f5dca6403512ac44be
[ "0BSD" ]
1
2019-07-01T02:02:40.000Z
2019-07-01T02:02:40.000Z
src/il/processing/il-processing.cpp
noct-lang/noct-bootstrap
6fd5ef91feda665dc3f1d8f5dca6403512ac44be
[ "0BSD" ]
null
null
null
src/il/processing/il-processing.cpp
noct-lang/noct-bootstrap
6fd5ef91feda665dc3f1d8f5dca6403512ac44be
[ "0BSD" ]
null
null
null
#include "il-processing.hpp" #include <type_traits> #include "common/logger.hpp" #include "il-pass.hpp" #include "passes/misc/il-clean-pass.hpp" #include "passes/misc/il-dependency-pass.hpp" #include "passes/misc/il-marker-pass.hpp" namespace Noctis { template<typename T, typename... Args> void ILProcessing::RunPass(ILModule& mod, const Args&... args) { static_assert(std::is_base_of_v<ILPass, T>, ""); T pass{ args... }; pass.Process(mod); } void ILProcessing::Process(ILModule& module) { g_Logger.Log("-- IL PROCESSING\n"); Timer timer(true); RunPass<ILDependencyPass>(module); RunPass<ILMarkerPass>(module); RunPass<ILBlockMergePass>(module); RunPass<ILRemoveGotoOnlyPass>(module); RunPass<ILRemoveUntouchableBlockPass>(module); timer.Stop(); g_Logger.Log("-- TOOK %s\n", timer.GetSMSFormat().c_str()); } }
25.342857
64
0.683202
noct-lang
729d54b118a8e70c51384c2bd381bbb94f2f72e3
1,877
cpp
C++
PAT/PAT Advanced/c++/1034.cpp
Accelerator404/Algorithm-Demonstration
e40a499c23a56d363c743c76ac967d9c4247a4be
[ "Apache-2.0" ]
1
2019-09-18T23:45:27.000Z
2019-09-18T23:45:27.000Z
PAT/PAT Advanced/c++/1034.cpp
Accelerator404/Algorithm-Demonstration
e40a499c23a56d363c743c76ac967d9c4247a4be
[ "Apache-2.0" ]
null
null
null
PAT/PAT Advanced/c++/1034.cpp
Accelerator404/Algorithm-Demonstration
e40a499c23a56d363c743c76ac967d9c4247a4be
[ "Apache-2.0" ]
1
2019-09-18T23:45:28.000Z
2019-09-18T23:45:28.000Z
#include <cstdio> #include <iostream> #include <map> #include <functional> #include <string> #include <vector> using namespace std; //PAT Advanced Level 1034 Head of a Gang /* 直接用两个map进行姓名与int ID的转换 * DFS遍历连通分量,某连通分量满足条件,即为结果之一,此处存入以帮主名称为key的map中 */ map<int,string> hashToName; map<string,int> nameToHash; map<string,int> gangs; int personID = 1,K; int hashID(string s){ if(nameToHash.find(s) == nameToHash.end()){ nameToHash[s] = personID; hashToName[personID] = s; personID++; return personID - 1; } else{ return nameToHash[s]; } } int G[2005][2005],weight[2005]; bool visited[2005]; void dfs(int u,int & head,int & numMember,int & totalWeight){ visited[u] = true; numMember++; if(weight[u] > weight[head]) head = u; for(int v = 1;v < personID;v++){ //如果uv联通,将权重计入该连通分量后封死uv通路 if(G[u][v] > 0){ totalWeight += G[u][v]; G[u][v] = G[v][u] = 0; if(!visited[v]) dfs(v,head,numMember,totalWeight); } } } int main() { int N; cin >> N >> K; for(int i = 0;i < N;i++){ string str1,str2; int w; cin >> str1 >> str2 >> w; int ID1 = hashID(str1),ID2 = hashID(str2); weight[ID1] += w; weight[ID2] += w; G[ID1][ID2] += w; G[ID2][ID1] += w; } for(int i = 1; i < personID;i++){ if(!visited[i]){ int head = i,numMember = 0,totalWeight = 0; dfs(i,head,numMember,totalWeight); if(numMember > 2 && totalWeight > K){ //map内部自带对key排序 gangs[hashToName[head]] = numMember; } } } cout << gangs.size() << endl; for(auto it = gangs.begin();it != gangs.end();it++){ cout << it->first << ' ' << it->second << endl; } return 0; }
23.759494
61
0.520511
Accelerator404
729d5f6617baedc2e5768926b22c2ebaa0aa66bd
1,070
cpp
C++
Casino_Inc/Source/Casino_Inc/Data/CI_WeigthedInteractionChance.cpp
matthieu1345/CasinoInc
3f6db9038c191fb5037219dbd8db5c7041b8292e
[ "Apache-2.0" ]
1
2019-11-22T14:52:37.000Z
2019-11-22T14:52:37.000Z
Casino_Inc/Source/Casino_Inc/Data/CI_WeigthedInteractionChance.cpp
matthieu1345/CasinoInc
3f6db9038c191fb5037219dbd8db5c7041b8292e
[ "Apache-2.0" ]
1
2019-11-21T03:58:03.000Z
2019-11-21T03:58:03.000Z
Casino_Inc/Source/Casino_Inc/Data/CI_WeigthedInteractionChance.cpp
matthieu1345/CasinoInc
3f6db9038c191fb5037219dbd8db5c7041b8292e
[ "Apache-2.0" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "CI_WeigthedInteractionChance.h" #include "DebugMacros.h" void FWeightedInteractionResult::OnPostDataImport(const UDataTable* InDataTable, const FName InRowName, TArray<FString>& OutCollectedImportProblems) { int totalChance = 0; for (auto node : InDataTable->GetRowMap()) { totalChance += ((FWeightedInteractionResult*)node.Value)->chance; } percentageChange = (1.0f / totalChance) * chance; } void FInteractionResult::RecalculateChance() { if (!IsValid(values)) return; totalChance = 0; for (auto node : values->GetRowMap()) { totalChance += ((FWeightedInteractionResult*)node.Value)->chance; } } FWeightedInteractionResult FInteractionResult::GetRandom() { int element = FMath::RandRange(0, totalChance); int counter = 0; for (auto node : values->GetRowMap()) { counter += ((FWeightedInteractionResult*)node.Value)->chance; if (counter >= element) return *(FWeightedInteractionResult*)node.Value; } return FWeightedInteractionResult(); }
22.765957
103
0.742991
matthieu1345
72a0ff04140f5f16d2ba92bbd273d3c65cd303f6
4,430
cpp
C++
solver/solver.cpp
ale64bit/kaktusat
afaac943079665184f900f318e7ac901619269dc
[ "MIT" ]
1
2021-11-17T13:43:12.000Z
2021-11-17T13:43:12.000Z
solver/solver.cpp
ale64bit/kaktusat
afaac943079665184f900f318e7ac901619269dc
[ "MIT" ]
null
null
null
solver/solver.cpp
ale64bit/kaktusat
afaac943079665184f900f318e7ac901619269dc
[ "MIT" ]
null
null
null
#include "solver.h" #include <set> #include <sstream> namespace solver { // A prefix used for temporary variables, which can't be used in ordinary // variables. static constexpr char kTmpSep = '$'; Var::Var(int x) : x(x) { CHECK(x > 0) << "variable representation must be positive, got x=" << x; } bool Var::operator==(const Var &that) const { return this->x == that.x; } bool Var::operator!=(const Var &that) const { return this->x != that.x; } bool Var::operator<(const Var &that) const { return this->x < that.x; } Var::operator Lit() const { return Lit(2 * x); } Lit Var::operator~() const { return Lit(2 * x + 1); } Lit::Lit(int l) : l(l) { CHECK(l > 0) << "literal representation must be positive, got l=" << l; } bool Lit::operator==(const Lit &that) const { return this->l == that.l; } bool Lit::operator!=(const Lit &that) const { return this->l != that.l; } bool Lit::operator<(const Lit &that) const { return this->l < that.l; } Lit Lit::operator~() const { return Lit(l ^ 1); } Var Lit::V() const { return Var(l >> 1); } Solver::Solver() : n_(0), tmpID_(0) {} Var Solver::NewTempVar(std::string prefix) { CHECK(prefix.find(kTmpSep) == std::string::npos) << "variable prefixes are not allowed to contain '" << kTmpSep << "'"; while (nameToVar_.count(prefix + kTmpSep + std::to_string(tmpID_))) { ++tmpID_; } std::string name = prefix + kTmpSep + std::to_string(tmpID_++); name_.push_back(name); ++n_; Var x(n_); nameToVar_.emplace(name, x); isTemp_.emplace_back(true); return x; } Var Solver::NewVar(std::string name) { CHECK(name.find(kTmpSep) == std::string::npos) << "variable names are not allowed to contain '" << kTmpSep << "'"; CHECK(!name.empty()) << "variable name cannot be empty"; CHECK(nameToVar_.count(name) == 0) << "duplicate variable name '" << name << "'"; name_.push_back(name); ++n_; Var x(n_); nameToVar_.emplace(name, x); isTemp_.emplace_back(false); return x; } Var Solver::NewOrGetVar(std::string name) { if (nameToVar_.count(name)) { return nameToVar_.at(name); } else { return NewVar(name); } } Var Solver::GetVar(std::string name) const { CHECK(nameToVar_.count(name) > 0) << "unknown variable name '" << name << "'"; return nameToVar_.at(name); } const std::vector<std::string> &Solver::GetVarNames() const { return name_; } const std::vector<std::vector<Lit>> &Solver::GetClauses() const { return clauses_; } std::string Solver::NameOf(Var x) const { return name_[x.ID() - 1]; } bool Solver::IsTemp(Var x) const { return isTemp_[x.ID() - 1]; } void Solver::AddClause(std::vector<Lit> c) { clauses_.emplace_back(c); } void Solver::Reset() { n_ = 0; name_.clear(); clauses_.clear(); nameToVar_.clear(); tmpID_ = 0; } bool Solver::Verify(const std::vector<Lit> &solution, std::string *errMsg) const { std::vector<bool> used(2 * n_ + 2, false); for (auto lit : solution) { if (used[lit.ID()] || used[(~lit).ID()]) { if (errMsg) { *errMsg = "literal used multiple times: " + ToString(lit.V()); } return false; } used[lit.ID()] = true; } for (auto clause : clauses_) { bool ok = false; for (auto lit : clause) { if (used[lit.ID()]) { ok = true; break; } } if (!ok) { if (errMsg) { *errMsg = "clause left unsatisfied: " + ToString(clause); } return false; } } return true; } std::string Solver::ToString(Var x) const { return name_[x.ID() - 1]; } std::string Solver::ToString(Lit l) const { std::string s = NameOf(l.V()); return (l != l.V()) ? "¬" + s : s; } std::string Solver::ToString(const std::vector<Lit> &lits, std::string sep, bool raw) const { std::stringstream out; bool first = true; for (auto l : lits) { if (!first) { out << sep; } first = false; if (raw) { out << (l.IsNeg() ? "-" : "") << l.V().ID(); } else { out << ToString(l); } } return out.str(); } std::string Solver::ToString() const { std::stringstream out; bool first = true; for (auto c : clauses_) { if (!first) { out << " ∧ "; } first = false; out << "("; for (size_t i = 0; i < c.size(); ++i) { if (i > 0) { out << " ∨ "; } out << ToString(c[i]); } out << ")"; } return out.str(); } } // namespace solver
26.058824
80
0.579684
ale64bit
72a1453d5fb959c8f97b29e4110a2ca2154389b5
2,091
cc
C++
flare/base/object_pool/ref_counted_test.cc
LiuYuHui/flare
f92cb6132e79ef2809fc0291a4923097ec84c248
[ "CC-BY-3.0", "BSD-2-Clause", "BSD-3-Clause" ]
2
2021-05-29T04:04:17.000Z
2022-02-04T05:33:17.000Z
flare/base/object_pool/ref_counted_test.cc
LiuYuHui/flare
f92cb6132e79ef2809fc0291a4923097ec84c248
[ "CC-BY-3.0", "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
flare/base/object_pool/ref_counted_test.cc
LiuYuHui/flare
f92cb6132e79ef2809fc0291a4923097ec84c248
[ "CC-BY-3.0", "BSD-2-Clause", "BSD-3-Clause" ]
1
2022-02-17T10:13:04.000Z
2022-02-17T10:13:04.000Z
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the // License at // // https://opensource.org/licenses/BSD-3-Clause // // 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 "flare/base/object_pool/ref_counted.h" #include <thread> #include "thirdparty/googletest/gtest/gtest.h" #include "flare/testing/main.h" using namespace std::literals; namespace flare { struct RefCounted1 : object_pool::RefCounted<RefCounted1> { RefCounted1() { ++instances; } ~RefCounted1() { --instances; } inline static int instances = 0; }; template <> struct PoolTraits<RefCounted1> { static constexpr auto kType = PoolType::ThreadLocal; static constexpr auto kLowWaterMark = 0; static constexpr auto kHighWaterMark = 128; static constexpr auto kMaxIdle = 100ms; }; TEST(ObjectPoolRefCounted, All) { auto tid = std::this_thread::get_id(); auto pp = object_pool::GetRefCounted<RefCounted1>(); { auto p = object_pool::GetRefCounted<RefCounted1>(); ASSERT_EQ(2, RefCounted1::instances); auto p2 = p; ASSERT_EQ(2, RefCounted1::instances); } { ASSERT_EQ(2, RefCounted1::instances); // Not destroyed yet. auto p = object_pool::GetRefCounted<RefCounted1>(); ASSERT_EQ(2, RefCounted1::instances); auto p2 = p; ASSERT_EQ(2, RefCounted1::instances); } // `this_fiber::SleepFor` WON'T work, object pools are bound to thread. std::this_thread::sleep_for(200ms); pp.Reset(); // To trigger cache washout. ASSERT_EQ(tid, std::this_thread::get_id()); // The last one freed is kept alive by the pool. ASSERT_EQ(1, RefCounted1::instances); } } // namespace flare FLARE_TEST_MAIN
30.304348
80
0.721186
LiuYuHui
72b0cb8382a022bcf2e5df7bc50664890e0baf2b
25,212
cpp
C++
p/validador/Measurer.cpp
jose-lp/docker-ie0521
e2c471bdc79fd94cb6dca4fe0cecc3ab2a649d7d
[ "MIT" ]
null
null
null
p/validador/Measurer.cpp
jose-lp/docker-ie0521
e2c471bdc79fd94cb6dca4fe0cecc3ab2a649d7d
[ "MIT" ]
null
null
null
p/validador/Measurer.cpp
jose-lp/docker-ie0521
e2c471bdc79fd94cb6dca4fe0cecc3ab2a649d7d
[ "MIT" ]
null
null
null
#include "Measurer.h" using namespace std; Measurer::Measurer() { cm = 1.0; cf = 1.0; cs = 1.0; misses = 0; false_positives = 0; missmatches = 0; false_negatives = 0; gt_objects = 0; tk_objects = 0; missmatch_error = 0; detection_error = 0; report_level = BASIC_LEVEL; motp_error=0.0; motp_matches = 0; precision = 0; recall = 0; accuracy = 0; f1measure = 0; true_negatives = 0; true_positives = 0; mota = 0.0; motp = 0.0; start_frame = 0; stop_frame = 999999; mota_mean = 0.0; motp_mean = 0.0; mota_variance = 0.0; motp_mean = 0.0; } Measurer::Measurer(std::map<std::string,double> constants) { cm = constants["miss"]; cf = constants["false"]; cs = constants["mismatch"]; report_level = constants["report_level"]; missmatch_error = constants["mismatch_error"]; detection_error = constants["detection_error"]; motp_error = constants["motp_error"]; start_frame = constants["start_frame"]; stop_frame = constants["stop_frame"]; misses = 0; false_positives = 0; missmatches = 0; false_negatives = 0; gt_objects = 0; tk_objects = 0; motp_matches = 0; precision = 0; recall = 0; accuracy = 0; f1measure = 0; true_negatives = 0; true_positives = 0; mota = 0.0; motp = 0.0; } double Measurer::MeasureMota(map<int, vector< TrackPoint >> manotados, map<int, vector< TrackPoint >> mrastreados) { cout << "Analyzing tracking results for MOTA..." << endl; map<int, vector< TrackPoint >>::iterator ItmAnotados,ItmRastreados; std::vector<int> gt_frames; int fnumber = -1; for (ItmAnotados = manotados.begin(); ItmAnotados != manotados.end(); ItmAnotados++) { for (ItmRastreados = mrastreados.begin(); ItmRastreados != mrastreados.end(); ItmRastreados++) { if(ItmRastreados->first == ItmRastreados->first){///We have a match on the frame numbers vector< TrackPoint > datos_anotados, datos_rastreados; datos_anotados = ItmAnotados->second; datos_rastreados = ItmRastreados->second; vector<TrackPoint>::iterator ItAnotados,ItRastreados; for (ItAnotados = datos_anotados.begin(); ItAnotados != datos_anotados.end(); ItAnotados++, gt_objects++) { for (ItRastreados = datos_rastreados.begin(); ItRastreados != datos_rastreados.end(); ItRastreados++) { ///Determine the misses if(*ItRastreados==*ItAnotados){ ///Determine missmatches if((ItRastreados->point.x > ItAnotados->point.x+missmatch_error) || (ItRastreados->point.x < ItAnotados->point.x-missmatch_error) || (ItRastreados->point.y > ItAnotados->point.y+missmatch_error) || (ItRastreados->point.y < ItAnotados->point.y-missmatch_error)) missmatches++; else true_positives++; break; } else if (*ItRastreados==datos_rastreados.back()){///Llegue al ultimo y no se encontro //cout << "Miss of player "<< ItAnotados->label << " on frame " << ItRastreados->frame_number << endl; misses++; } } ///Create a list of the gt frame numbers if(ItAnotados->frame_number != fnumber){ gt_frames.push_back(ItAnotados->frame_number); fnumber = ItAnotados->frame_number; } } ///Count track objects only on gt frames for(unsigned int gtc =0; gtc<gt_frames.size();gtc++){ int gtfnumber = gt_frames[gtc]; for (ItRastreados = datos_rastreados.begin(); ItRastreados != datos_rastreados.end(); ItRastreados++) { if(gtfnumber==ItRastreados->frame_number) tk_objects++; } } }///if son el mismo frame number } } //false_positives = tk_objects - gt_objects; false_positives = (tk_objects>=gt_objects) ? (tk_objects - gt_objects):(0); //false_negatives = gt_objects - tk_objects; false_negatives = (gt_objects >= tk_objects) ? (gt_objects - tk_objects):(0); missmatches=missmatches/2; precision = true_positives/(true_positives+false_positives); recall = true_positives/(true_positives+false_negatives); f1measure = 2 * (precision * recall)/(precision + recall); cout << "Misses = " << misses << endl; cout << "Ture positive = " << true_positives << endl; cout << "False positives = " << false_positives << endl; cout << "False negatives = " << false_negatives << endl; cout << "Missmatches = " << missmatches << endl; cout << "Total analyzed frames = " << gt_frames.size() << endl; cout << "Total ground truth objects = " << gt_objects << endl; mota = 1 - (cm * misses + cf * false_positives + cs * missmatches)/gt_objects; return mota; } double Measurer::MeasureMota(vector< TrackPoint > anotados, vector< TrackPoint > rastreados) { cout << "Analyzing tracking results for MOTA..." << endl; ///Sort trackpoints by frame number std::sort(anotados.begin(), anotados.end()); std::sort(rastreados.begin(), rastreados.end()); vector<TrackPoint>::iterator ItAnotados,ItRastreados; std::vector<int> gt_frames; int fnumber = -1; bool found1,found2,found3,found4; for (ItAnotados = anotados.begin(); ItAnotados != anotados.end(); ItAnotados++) { if(ItAnotados->frame_number>=start_frame && ItAnotados->frame_number<=stop_frame){ gt_objects++; found1 = FALSE; found2 = FALSE; found3 = FALSE; for (ItRastreados = rastreados.begin(); ItRastreados != rastreados.end(); ItRastreados++) { if((ItRastreados->frame_number>=start_frame) && (ItRastreados->frame_number<=stop_frame) && (found1 == FALSE)) { ///Determine the missmatches if(*ItRastreados==*ItAnotados){ //cout << "The player with id " << ItRastreados->label << " found on frame " << ItRastreados->frame_number << endl; ///Determine missmatches if((ItRastreados->point.x > ItAnotados->point.x+missmatch_error) || (ItRastreados->point.x < ItAnotados->point.x-missmatch_error) || (ItRastreados->point.y > ItAnotados->point.y+missmatch_error) || (ItRastreados->point.y < ItAnotados->point.y-missmatch_error)) missmatches++; //else //true_positives++; found1 = TRUE; //cout << "Found player "<< ItAnotados->label << " on frame " << ItAnotados->frame_number << endl; } else if (ItRastreados==rastreados.end()-1){///Determine the misses //cout << "Miss of player "<< ItAnotados->label << " on frame " << ItAnotados->frame_number << endl; misses++; found1 = FALSE; } ///Search for FN - Cuando esta en el GT pero no en el SUT if((ItAnotados->frame_number == ItRastreados->frame_number) && (found2 == FALSE)){ if((ItAnotados->point.x < ItRastreados->point.x+detection_error) && (ItAnotados->point.x > ItRastreados->point.x-detection_error) && (ItAnotados->point.y < ItRastreados->point.y+detection_error) && (ItAnotados->point.y > ItRastreados->point.y-detection_error)) found2 = TRUE; ///Found a coincidence else{ //cout << "found posible player "<< ItAnotados->label << " on frame " << ItAnotados->frame_number << endl; found2 = FALSE; } } ///Search for TP - Cuando esta en el GT y en el SUT if((ItAnotados->frame_number == ItRastreados->frame_number) && (found3 == FALSE)){ if((ItRastreados->point.x < ItAnotados->point.x+detection_error) && (ItRastreados->point.x > ItAnotados->point.x-detection_error) && (ItRastreados->point.y < ItAnotados->point.y+detection_error) && (ItRastreados->point.y > ItAnotados->point.y-detection_error)) found3 = TRUE; ///Found a TP } } } if(found2 == FALSE){ //cout << "False negative of player "<< ItAnotados->label << " on frame " << ItAnotados->frame_number << endl; false_negatives++; } if(found3 == TRUE){ //cout << "True positive of player "<< ItAnotados->label << " on frame " << ItAnotados->frame_number << endl; true_positives++; } ///Create a list of the gt frame numbers if(ItAnotados->frame_number != fnumber){ gt_frames.push_back(ItAnotados->frame_number); fnumber = ItAnotados->frame_number; } } } /* ///Count track objects only on gt frames for(unsigned int gtc =0; gtc<gt_frames.size();gtc++){ int gtfnumber = gt_frames[gtc]; for (ItRastreados = rastreados.begin(); ItRastreados != rastreados.end(); ItRastreados++) { if(ItRastreados->frame_number>=start_frame && ItRastreados->frame_number<=stop_frame) { if(gtfnumber==ItRastreados->frame_number) tk_objects++; } } } */ ///Search for FP - Cuando esta en el SUT y no en el GT for (ItRastreados = rastreados.begin(); ItRastreados != rastreados.end(); ItRastreados++) { if((ItRastreados->frame_number>=start_frame) && (ItRastreados->frame_number<=stop_frame)) { tk_objects++; found4 = FALSE; for (ItAnotados = anotados.begin(); ItAnotados != anotados.end(); ItAnotados++) { if(ItAnotados->frame_number>=start_frame && ItAnotados->frame_number<=stop_frame){ ///Search for FP if((ItRastreados->frame_number == ItAnotados->frame_number) && (found4 == FALSE)){ if((ItRastreados->point.x < ItAnotados->point.x+detection_error) && (ItRastreados->point.x > ItAnotados->point.x-detection_error) && (ItRastreados->point.y < ItAnotados->point.y+detection_error) && (ItRastreados->point.y > ItAnotados->point.y-detection_error)) found4 = TRUE; ///El SUT esta en el GT } } } if(found4 == FALSE){ //cout << "False positive of player "<< ItRastreados->label << " on frame " << ItRastreados->frame_number << endl; false_positives++; } } } //false_positives = (tk_objects>=gt_objects) ? (tk_objects - gt_objects):(0); missmatches=missmatches/2.0; precision = true_positives/(true_positives+false_positives); recall = true_positives/(true_positives+false_negatives); f1measure = 2.0 * (precision * recall)/(precision + recall); cout << "Total ground truth objects = " << gt_objects << endl; cout << "Total SUT objects = " << tk_objects << endl; cout << "Misses = " << misses << endl; cout << "True positive = " << true_positives << endl; cout << "False positives = " << false_positives << endl; cout << "False negatives = " << false_negatives << endl; cout << "Missmatches = " << missmatches << endl; cout << "Total analyzed frames = " << gt_frames.size() << endl; mota = 1.0 - (cm * misses + cf * false_positives + cs * missmatches)/gt_objects; cout << "Finish with MOTA..." << endl; return mota; } double Measurer::MeasureMota(vector< TrackPoint > anotados, vector< TrackPoint > rastreados, int tid) { ///Sort trackpoints by frame number std::sort(anotados.begin(), anotados.end()); std::sort(rastreados.begin(), rastreados.end()); std::vector<int> gt_frames; if(tid == 0){ cout << "Analyzing tracking results for MOTA..." << endl; vector<TrackPoint>::iterator ItAnotados,ItRastreados; int fnumber = -1; bool found1,found2,found3; for (ItAnotados = anotados.begin(); ItAnotados != anotados.end(); ItAnotados++) { if(ItAnotados->frame_number>=start_frame && ItAnotados->frame_number<=stop_frame){ gt_objects++; found1 = FALSE; found2 = FALSE; found3 = FALSE; for (ItRastreados = rastreados.begin(); ItRastreados != rastreados.end(); ItRastreados++) { if((ItRastreados->frame_number>=start_frame) && (ItRastreados->frame_number<=stop_frame) && (found1 == FALSE)) { ///Determine the missmatches if(*ItRastreados==*ItAnotados){ //cout << "The player with id " << ItRastreados->label << " found on frame " << ItRastreados->frame_number << endl; ///Determine missmatches if((ItRastreados->point.x > ItAnotados->point.x+missmatch_error) || (ItRastreados->point.x < ItAnotados->point.x-missmatch_error) || (ItRastreados->point.y > ItAnotados->point.y+missmatch_error) || (ItRastreados->point.y < ItAnotados->point.y-missmatch_error)) missmatches++; //else //true_positives++; found1 = TRUE; //cout << "Found player "<< ItAnotados->label << " on frame " << ItAnotados->frame_number << endl; } else if (ItRastreados==rastreados.end()-1){///Determine the misses //cout << "Miss of player "<< ItAnotados->label << " on frame " << ItAnotados->frame_number << endl; misses++; found1 = FALSE; } ///Search for FN - Cuando esta en el GT pero no en el SUT if((ItAnotados->frame_number == ItRastreados->frame_number) && (found2 == FALSE)){ if((ItAnotados->point.x < ItRastreados->point.x+detection_error) && (ItAnotados->point.x > ItRastreados->point.x-detection_error) && (ItAnotados->point.y < ItRastreados->point.y+detection_error) && (ItAnotados->point.y > ItRastreados->point.y-detection_error)) found2 = TRUE; ///Found a coincidence else{ //cout << "found posible player "<< ItAnotados->label << " on frame " << ItAnotados->frame_number << endl; found2 = FALSE; } } ///Search for TP - Cuando esta en el GT y en el SUT if((ItAnotados->frame_number == ItRastreados->frame_number) && (found3 == FALSE)){ if((ItRastreados->point.x < ItAnotados->point.x+detection_error) && (ItRastreados->point.x > ItAnotados->point.x-detection_error) && (ItRastreados->point.y < ItAnotados->point.y+detection_error) && (ItRastreados->point.y > ItAnotados->point.y-detection_error)) found3 = TRUE; ///Found a TP } } } if(found2 == FALSE){ //cout << "False negative of player "<< ItAnotados->label << " on frame " << ItAnotados->frame_number << endl; false_negatives++; } if(found3 == TRUE){ //cout << "True positive of player "<< ItAnotados->label << " on frame " << ItAnotados->frame_number << endl; true_positives++; } ///Create a list of the gt frame numbers if(ItAnotados->frame_number != fnumber){ gt_frames.push_back(ItAnotados->frame_number); fnumber = ItAnotados->frame_number; } } } cout << "Finish with MOTA on thread " << tid << endl; }///tid=0 ///Search for FP - Cuando esta en el SUT y no en el GT if(tid==1){ vector<TrackPoint>::iterator ItAnotados,ItRastreados; bool found4; for (ItRastreados = rastreados.begin(); ItRastreados != rastreados.end(); ItRastreados++) { if((ItRastreados->frame_number>=start_frame) && (ItRastreados->frame_number<=stop_frame)) { tk_objects++; found4 = FALSE; for (ItAnotados = anotados.begin(); ItAnotados != anotados.end(); ItAnotados++) { if(ItAnotados->frame_number>=start_frame && ItAnotados->frame_number<=stop_frame){ ///Search for FP if((ItRastreados->frame_number == ItAnotados->frame_number) && (found4 == FALSE)){ if((ItRastreados->point.x < ItAnotados->point.x+detection_error) && (ItRastreados->point.x > ItAnotados->point.x-detection_error) && (ItRastreados->point.y < ItAnotados->point.y+detection_error) && (ItRastreados->point.y > ItAnotados->point.y-detection_error)) found4 = TRUE; ///El SUT esta en el GT } } } if(found4 == FALSE){ //cout << "False positive of player "<< ItRastreados->label << " on frame " << ItRastreados->frame_number << endl; false_positives++; } } } cout << "Finish with MOTA on thread " << tid << endl; }///tid = 1 #pragma omp barrier //false_positives = (tk_objects>=gt_objects) ? (tk_objects - gt_objects):(0); missmatches=missmatches/2.0; precision = true_positives/(true_positives+false_positives); recall = true_positives/(true_positives+false_negatives); f1measure = 2.0 * (precision * recall)/(precision + recall); cout << "Total ground truth objects = " << gt_objects << endl; cout << "Total SUT objects" << tk_objects << endl; cout << "Misses = " << misses << endl; cout << "True positive = " << true_positives << endl; cout << "False positives = " << false_positives << endl; cout << "False negatives = " << false_negatives << endl; cout << "Missmatches = " << missmatches << endl; cout << "Total analyzed frames = " << gt_frames.size() << endl; mota = 1.0 - (cm * misses + cf * false_positives + cs * missmatches)/gt_objects; cout << "Finish with MOTA..." << endl; return mota; } double Measurer::MeasureMota_old(vector< TrackPoint > anotados, vector< TrackPoint > rastreados) { cout << "Analyzing tracking results for MOTA..." << endl; ///Sort trackpoints by frame number std::sort(anotados.begin(), anotados.end()); std::sort(rastreados.begin(), rastreados.end()); vector<TrackPoint>::iterator ItAnotados,ItRastreados; std::vector<int> gt_frames; int fnumber = -1; bool found; for (ItAnotados = anotados.begin(); ItAnotados != anotados.end(); ItAnotados++) { if(ItAnotados->frame_number>=start_frame && ItAnotados->frame_number<=stop_frame){ gt_objects++; found = FALSE; for (ItRastreados = rastreados.begin(); ItRastreados != rastreados.end(); ItRastreados++) { if((ItRastreados->frame_number>=start_frame) && (ItRastreados->frame_number<=stop_frame) && (found == FALSE)) { ///Determine the misses if(*ItRastreados==*ItAnotados){ //cout << "The player with id " << ItRastreados->label << " found on frame " << ItRastreados->frame_number << endl; ///Determine missmatches if((ItRastreados->point.x > ItAnotados->point.x+missmatch_error) || (ItRastreados->point.x < ItAnotados->point.x-missmatch_error) || (ItRastreados->point.y > ItAnotados->point.y+missmatch_error) || (ItRastreados->point.y < ItAnotados->point.y-missmatch_error)) missmatches++; else true_positives++; found = TRUE; //cout << "Found player "<< ItAnotados->label << " on frame " << ItAnotados->frame_number << endl; } //else if (*ItRastreados==rastreados.back()){ else if (ItRastreados==rastreados.end()-1){ //cout << "Miss of player "<< ItAnotados->label << " on frame " << ItAnotados->frame_number << endl; misses++; found = FALSE; } } ///Search for FP } ///Create a list of the gt frame numbers if(ItAnotados->frame_number != fnumber){ gt_frames.push_back(ItAnotados->frame_number); fnumber = ItAnotados->frame_number; } } } ///Count track objects only on gt frames for(unsigned int gtc =0; gtc<gt_frames.size();gtc++){ int gtfnumber = gt_frames[gtc]; for (ItRastreados = rastreados.begin(); ItRastreados != rastreados.end(); ItRastreados++) { if(ItRastreados->frame_number>=start_frame && ItRastreados->frame_number<=stop_frame) { if(gtfnumber==ItRastreados->frame_number) tk_objects++; } } } //gt_objects = anotados.size(); //tk_objects = rastreados.size(); //false_positives = tk_objects - gt_objects; false_positives = (tk_objects>=gt_objects) ? (tk_objects - gt_objects):(0); //false_negatives = gt_objects - tk_objects; false_negatives = (gt_objects >= tk_objects) ? (gt_objects - tk_objects):(0); missmatches=missmatches/2.0; precision = true_positives/(true_positives+false_positives); recall = true_positives/(true_positives+false_negatives); f1measure = 2.0 * (precision * recall)/(precision + recall); cout << "Total ground truth objects = " << gt_objects << endl; cout << "Total SUT objects" << tk_objects << endl; cout << "Misses = " << misses << endl; cout << "True positive = " << true_positives << endl; cout << "False positives = " << false_positives << endl; cout << "False negatives = " << false_negatives << endl; cout << "Missmatches = " << missmatches << endl; cout << "Total analyzed frames = " << gt_frames.size() << endl; mota = 1.0 - (cm * misses + cf * false_positives + cs * missmatches)/gt_objects; return mota; } double Measurer::MeasureMotp(vector< TrackPoint > anotados, vector< TrackPoint > rastreados) { cout << "Analyzing tracking results for MOTP..." << endl; ///Sort trackpoints by frame number std::sort(anotados.begin(), anotados.end()); std::sort(rastreados.begin(), rastreados.end()); vector<TrackPoint>::iterator ItAnotados,ItRastreados; //Change this for a binary search!!! double distance_error = 0.0; for (ItAnotados = anotados.begin(); ItAnotados != anotados.end(); ItAnotados++) { if(ItAnotados->frame_number>=start_frame && ItAnotados->frame_number<=stop_frame){ for (ItRastreados = rastreados.begin(); ItRastreados != rastreados.end(); ItRastreados++) { if(ItRastreados->frame_number>=start_frame && ItRastreados->frame_number<=stop_frame) { if(*ItRastreados==*ItAnotados){ motp_matches++; ///Obtain euclidian distance double x = (double) (ItAnotados->point.x - ItRastreados->point.x); double y = (double) (ItAnotados->point.y - ItRastreados->point.y); double dist; dist = pow(x, 2) + pow(y, 2); dist = sqrt(dist); dist = (dist-motp_error>=0.0) ? (dist-motp_error):(0.0); distance_error=distance_error+dist; break; } } } } } motp = distance_error/motp_matches; cout << "Finish with MOTP..." << endl; return motp; } void Measurer::SaveResults(std::string report_file,std::string input_file,std::string annotation_file) { cout<< "Saving results to " << report_file << " ... " << endl; ofstream rfile; rfile.open (report_file); rfile <<"--- Resulting report ---" << endl; rfile << "\n- Input files -" << endl; rfile <<"Tracking file: " << input_file << endl; rfile <<"GT file: " << annotation_file << endl; rfile <<"\n- Configuration parameters -" << endl; rfile <<"Miss constant = " << cm << endl; rfile <<"False positive constant = " << cf << endl; rfile <<"Missmatch constant = " << cs << endl; rfile <<"Precision error = " << motp_error << endl; rfile <<"Mismatch error = " << missmatch_error << endl; rfile <<"Detection error = " << detection_error << endl; rfile <<"\n- Metrics values -" << endl; if(report_level == BASIC_LEVEL){ int space = 12; rfile << std::setw(space) << "F1" << std::setw(space) << "MOTA" << std::setw(space) << "MOTP" << endl; rfile << std::setw(space) << to_string_with_precision(f1measure) << std::setw(space) << to_string_with_precision((double)mota*100.0) + "\%" << std::setw(space) << to_string_with_precision(motp) + " px" << endl; } else if(report_level == FULL_LEVEL){ int space = 12; rfile << std::setw(space) << "GTobj" << std::setw(space) << "SUTobj" << std::setw(space) << "FP" << std::setw(space) << "FN" << std::setw(space) << "TP" << std::setw(space) << "Rcll" << std::setw(space) << "Prcn" << std::setw(space) << "F1" << endl; rfile << std::setw(space) << to_string_with_precision(gt_objects,0) << std::setw(space) << to_string_with_precision(tk_objects,0) << std::setw(space) << to_string_with_precision((double)false_positives/(double)tk_objects*100.0) + "\%" << std::setw(space) << to_string_with_precision((double)false_negatives/(double)gt_objects*100.0) + "\%" << std::setw(space) << to_string_with_precision((double)true_positives/(double)gt_objects*100.0) + "\%" << std::setw(space) << to_string_with_precision(recall) << std::setw(space) << to_string_with_precision(precision) << std::setw(space) << to_string_with_precision(f1measure) << endl; } else if(report_level == FULLP_LEVEL){ int space = 12; rfile << std::setw(space) << "GTobj" << std::setw(space) << "SUTobj" << std::setw(space) << "FP" << std::setw(space) << "FN" << std::setw(space) << "TP" << std::setw(space) << "MS" << std::setw(space) << "MSM" << std::setw(space) << "Rcll" << std::setw(space) << "Prcn" << std::setw(space) << "F1" << std::setw(space) << "MOTA" << std::setw(space) << "MOTP" << endl; rfile << std::setw(space) << to_string_with_precision(gt_objects,0) << std::setw(space) << to_string_with_precision(tk_objects,0) << std::setw(space) << to_string_with_precision((double)false_positives/(double)tk_objects*100.0) + "\%" << std::setw(space) << to_string_with_precision((double)false_negatives/(double)gt_objects*100.0) + "\%" << std::setw(space) << to_string_with_precision((double)true_positives/(double)gt_objects*100.0) + "\%" << std::setw(space) << to_string_with_precision((double)misses/(double)gt_objects*100.0) + "\%" << std::setw(space) << to_string_with_precision((double)missmatches/(double)gt_objects*100.0) + "\%" << std::setw(space) << to_string_with_precision(recall) << std::setw(space) << to_string_with_precision(precision) << std::setw(space) << to_string_with_precision(f1measure) << std::setw(space) << to_string_with_precision((double)mota*100.0) + "\%" << std::setw(space) << to_string_with_precision(motp) + " px" << endl; } } double Measurer::CalculateMean(vector< double > data) { double sum=0.0; double mean=0.0; for(unsigned int i=0; i<data.size();i++) sum += data[i]; mean = sum/data.size(); return mean; } double Measurer::CalculateVariance(vector< double > data) { double sum=0.0; double mean=0.0; double variance=0.0; for(unsigned int i=0; i<data.size();i++) sum += data[i]; mean = sum/data.size(); for(unsigned int j=0; j<data.size();j++) variance += pow(data[j] - mean, 2); variance=variance/data.size(); return variance; } Measurer::~Measurer() { }
37.855856
120
0.65096
jose-lp
72b50511dccafe526b02a66a55caac71c7d0084d
1,283
hpp
C++
src/common/types.hpp
marcesengel/realm-js
74b06e0f2aec8526056ccae1da6056e521853a44
[ "Apache-1.1" ]
null
null
null
src/common/types.hpp
marcesengel/realm-js
74b06e0f2aec8526056ccae1da6056e521853a44
[ "Apache-1.1" ]
null
null
null
src/common/types.hpp
marcesengel/realm-js
74b06e0f2aec8526056ccae1da6056e521853a44
[ "Apache-1.1" ]
null
null
null
//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #pragma once namespace realm { namespace js { namespace types { /* * Common idiom that covers Realm and JavaScript. */ enum Type { NotImplemented = -100, Object = 16, // We translate TypedLink (16) -> Object Undefined = -2, Null = -1, Integer = 0, Boolean = 1, String = 2, Binary = 4, Mixed = 6, Timestamp = 8, Float = 9, Double = 10, Decimal = 11, Link = 12, LinkList = 13, ObjectId = 15, UUID = 17, }; } // namespace types } // namespace js } // namespace realm
24.207547
76
0.577553
marcesengel
72b5c8d1c96cba94634aa99a07bac06bec91d2dd
2,347
cpp
C++
src/absolutePoseEstimation/rotationAveraging/RelativePosesG2oFormat.cpp
leoneed03/reconstrutor
5e6417ed2b090617202cad1a10010141e4ce6615
[ "MIT" ]
null
null
null
src/absolutePoseEstimation/rotationAveraging/RelativePosesG2oFormat.cpp
leoneed03/reconstrutor
5e6417ed2b090617202cad1a10010141e4ce6615
[ "MIT" ]
1
2021-05-21T15:52:37.000Z
2021-05-24T11:34:46.000Z
src/absolutePoseEstimation/rotationAveraging/RelativePosesG2oFormat.cpp
leoneed03/reconstrutor
5e6417ed2b090617202cad1a10010141e4ce6615
[ "MIT" ]
null
null
null
// // Copyright (c) Leonid Seniukov. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. // #include "absolutePoseEstimation/rotationAveraging/RelativePosesG2oFormat.h" namespace gdr { RelativePosesG2oFormat::RelativePosesG2oFormat(const std::vector<RotationMeasurement> &relativeRotationsToSet) : relativeRotations(relativeRotationsToSet) {} std::ostream &operator<<(std::ostream &os, const RelativePosesG2oFormat &rotationsG2o) { assert(!rotationsG2o.relativeRotations.empty()); int minIndex = std::numeric_limits<int>::max() / 2; int maxIndex = -1; for (const auto &relativeRotation: rotationsG2o.relativeRotations) { int indexFromDestination = relativeRotation.getIndexFromDestination(); int indexToToBeTransformed = relativeRotation.getIndexToToBeTransformed(); if (indexFromDestination >= indexToToBeTransformed) { continue; } minIndex = std::min(minIndex, indexFromDestination); maxIndex = std::max(maxIndex, indexToToBeTransformed); } assert(minIndex == 0); assert(minIndex < maxIndex); for (int i = 0; i <= maxIndex; ++i) { std::string s1 = "VERTEX_SE3:QUAT "; std::string s2 = std::to_string(i) + " 0.000000 0.000000 0.000000 0.0 0.0 0.0 1.0\n"; os << s1 + s2; } std::string noise = " 10000.000000 0.000000 0.000000 0.000000 0.000000 0.000000 10000.000000 0.000000 0.000000 0.000000 0.000000 10000.000000 0.000000 0.000000 0.000000 10000.000000 0.000000 0.000000 10000.000000 0.000000 10000.000000"; for (const auto &relativeRotation: rotationsG2o.relativeRotations) { int indexFromDestination = relativeRotation.getIndexFromDestination(); int indexToToBeTransformed = relativeRotation.getIndexToToBeTransformed(); if (indexFromDestination >= indexToToBeTransformed) { continue; } os << "EDGE_SE3:QUAT " << indexFromDestination << ' ' << indexToToBeTransformed << ' '; os << 0.0 << ' ' << 0.0 << ' ' << 0.0 << ' ' << relativeRotation.getRotationSO3() << ' '; os << noise << std::endl; } return os; } }
39.116667
256
0.63187
leoneed03
72ba34c8d2c1cfa6e90221f37fb0f58e013976b9
1,748
hpp
C++
include/lol/def/GameflowLcdsGameDTO.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
1
2020-07-22T11:14:55.000Z
2020-07-22T11:14:55.000Z
include/lol/def/GameflowLcdsGameDTO.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
null
null
null
include/lol/def/GameflowLcdsGameDTO.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
4
2018-12-01T22:48:21.000Z
2020-07-22T11:14:56.000Z
#pragma once #include "../base_def.hpp" namespace lol { struct GameflowLcdsGameDTO { uint64_t id; int32_t mapId; std::string gameState; std::string queueTypeName; std::string gameMode; int32_t gameTypeConfigId; int32_t maxNumPlayers; std::string gameType; int32_t spectatorDelay; std::vector<json> teamOne; std::vector<json> teamTwo; std::vector<json> playerChampionSelections; }; inline void to_json(json& j, const GameflowLcdsGameDTO& v) { j["id"] = v.id; j["mapId"] = v.mapId; j["gameState"] = v.gameState; j["queueTypeName"] = v.queueTypeName; j["gameMode"] = v.gameMode; j["gameTypeConfigId"] = v.gameTypeConfigId; j["maxNumPlayers"] = v.maxNumPlayers; j["gameType"] = v.gameType; j["spectatorDelay"] = v.spectatorDelay; j["teamOne"] = v.teamOne; j["teamTwo"] = v.teamTwo; j["playerChampionSelections"] = v.playerChampionSelections; } inline void from_json(const json& j, GameflowLcdsGameDTO& v) { v.id = j.at("id").get<uint64_t>(); v.mapId = j.at("mapId").get<int32_t>(); v.gameState = j.at("gameState").get<std::string>(); v.queueTypeName = j.at("queueTypeName").get<std::string>(); v.gameMode = j.at("gameMode").get<std::string>(); v.gameTypeConfigId = j.at("gameTypeConfigId").get<int32_t>(); v.maxNumPlayers = j.at("maxNumPlayers").get<int32_t>(); v.gameType = j.at("gameType").get<std::string>(); v.spectatorDelay = j.at("spectatorDelay").get<int32_t>(); v.teamOne = j.at("teamOne").get<std::vector<json>>(); v.teamTwo = j.at("teamTwo").get<std::vector<json>>(); v.playerChampionSelections = j.at("playerChampionSelections").get<std::vector<json>>(); } }
38
92
0.641304
Maufeat
72bb0a2fd8801002cb62f7ce5aefc2cdd705d356
71,100
cpp
C++
Source/source/mob_script_action.cpp
shantonusen/Pikifen
5a90f804fdf78bfd198eb838200a7aaf6d7ea842
[ "MIT" ]
null
null
null
Source/source/mob_script_action.cpp
shantonusen/Pikifen
5a90f804fdf78bfd198eb838200a7aaf6d7ea842
[ "MIT" ]
null
null
null
Source/source/mob_script_action.cpp
shantonusen/Pikifen
5a90f804fdf78bfd198eb838200a7aaf6d7ea842
[ "MIT" ]
null
null
null
/* * Copyright (c) Andre 'Espyo' Silva 2013. * The following source file belongs to the open-source project Pikifen. * Please read the included README and LICENSE files for more information. * Pikmin is copyright (c) Nintendo. * * === FILE DESCRIPTION === * Mob script action classes and * related functions. */ #include <algorithm> #include "mob_script_action.h" #include "functions.h" #include "game.h" #include "mobs/group_task.h" #include "mobs/scale.h" #include "mobs/tool.h" #include "utils/string_utils.h" using std::set; /* ---------------------------------------------------------------------------- * Creates a new, empty mob action. */ mob_action::mob_action() : type(MOB_ACTION_UNKNOWN), code(nullptr), extra_load_logic(nullptr) { } /* ---------------------------------------------------------------------------- * Creates a new, empty mob action call, of a certain type. * type: * Type of mob action call. */ mob_action_call::mob_action_call(MOB_ACTION_TYPES type) : action(nullptr), code(nullptr), parent_event(MOB_EV_UNKNOWN), mt(nullptr) { for(size_t a = 0; a < game.mob_actions.size(); ++a) { if(game.mob_actions[a].type == type) { action = &(game.mob_actions[a]); break; } } } /* ---------------------------------------------------------------------------- * Creates a new mob action call that is meant to run custom code. * code: * The function to run. */ mob_action_call::mob_action_call(custom_action_code code): action(nullptr), code(code), parent_event(MOB_EV_UNKNOWN), mt(nullptr) { for(size_t a = 0; a < game.mob_actions.size(); ++a) { if(game.mob_actions[a].type == MOB_ACTION_UNKNOWN) { action = &(game.mob_actions[a]); break; } } } /* ---------------------------------------------------------------------------- * Loads a mob action call from a data node. * dn: * The data node. * mt: * Mob type this action's fsm belongs to. */ bool mob_action_call::load_from_data_node(data_node* dn, mob_type* mt) { action = NULL; this->mt = mt; //First, get the name and arguments. vector<string> words = split(dn->name); for(size_t w = 0; w < words.size(); ++w) { words[w] = trim_spaces(words[w]); } string name = words[0]; if(!words.empty()) { words.erase(words.begin()); } //Find the corresponding action. for(size_t a = 0; a < game.mob_actions.size(); ++a) { if(game.mob_actions[a].type == MOB_ACTION_UNKNOWN) continue; if(game.mob_actions[a].name == name) { action = &(game.mob_actions[a]); } } if(!action) { log_error("Unknown script action name \"" + name + "\"!", dn); return false; } //Check if there are too many or too few arguments. size_t mandatory_parameters = action->parameters.size(); if(mandatory_parameters > 0) { if(action->parameters[mandatory_parameters - 1].is_extras) { mandatory_parameters--; } } if(words.size() < mandatory_parameters) { log_error( "The \"" + action->name + "\" action needs " + i2s(mandatory_parameters) + " arguments, but this call only " "has " + i2s(words.size()) + "! You're missing the \"" + action->parameters[words.size()].name + "\" parameter.", dn ); return false; } if(mandatory_parameters == action->parameters.size()) { if(words.size() > action->parameters.size()) { log_error( "The \"" + action->name + "\" action only needs " + i2s(action->parameters.size()) + " arguments, but this call " "has " + i2s(words.size()) + "!", dn ); return false; } } //Fetch the arguments, and check if any of them are not allowed. for(size_t w = 0; w < words.size(); ++w) { size_t param_nr = std::min(w, action->parameters.size() - 1); bool is_var = (words[w][0] == '$' && words[w].size() > 1); if(is_var && words[w].size() >= 2 && words[w][1] == '$') { //Two '$' in a row means it's meant to use a literal '$'. is_var = false; words[w].erase(words[w].begin()); } if(is_var) { if(action->parameters[param_nr].force_const) { log_error( "Argument #" + i2s(w) + " (\"" + words[w] + "\") is a " "variable, but the parameter \"" + action->parameters[param_nr].name + "\" can only be " "constant!", dn ); return false; } words[w].erase(words[w].begin()); //Remove the '$'. if(words[w].empty()) { log_error( "Argument #" + i2s(w) + " is trying to use a variable " "with no name!", dn ); return false; } } args.push_back(words[w]); arg_is_var.push_back(is_var); } //If this action needs extra parsing, do it now. if(action->extra_load_logic) { bool success = action->extra_load_logic(*this); if(!custom_error.empty()) { log_error(custom_error, dn); } return success; } return true; } /* ---------------------------------------------------------------------------- * Runs an action. * Return value is only used by the "if" actions, to indicate their * evaluation result. * m: * The mob. * custom_data_1: * Custom argument #1 to pass to the code. * custom_data_2: * Custom argument #2 to pass to the code. */ bool mob_action_call::run( mob* m, void* custom_data_1, void* custom_data_2 ) { //Custom code (i.e. instead of text-based script, use actual C++ code). if(code) { code(m, custom_data_1, custom_data_2); return false; } mob_action_run_data data(m, this); //Fill the arguments. Fetch values from variables if needed. data.args = args; for(size_t a = 0; a < args.size(); ++a) { if(arg_is_var[a]) { data.args[a] = m->vars[args[a]]; } } data.custom_data_1 = custom_data_1; data.custom_data_2 = custom_data_2; action->code(data); return data.return_value; } /* ---------------------------------------------------------------------------- * Loading code for the arachnorb logic plan mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::arachnorb_plan_logic(mob_action_call &call) { if(call.args[0] == "home") { call.args[0] = i2s(MOB_ACTION_ARACHNORB_PLAN_LOGIC_HOME); } else if(call.args[0] == "forward") { call.args[0] = i2s(MOB_ACTION_ARACHNORB_PLAN_LOGIC_FORWARD); } else if(call.args[0] == "cw_turn") { call.args[0] = i2s(MOB_ACTION_ARACHNORB_PLAN_LOGIC_CW_TURN); } else if(call.args[0] == "ccw_turn") { call.args[0] = i2s(MOB_ACTION_ARACHNORB_PLAN_LOGIC_CCW_TURN); } else { report_enum_error(call, 0); return false; } return true; } /* ---------------------------------------------------------------------------- * Loading code for the calculation mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::calculate(mob_action_call &call) { if(call.args[2] == "+") { call.args[2] = i2s(MOB_ACTION_SET_VAR_SUM); } else if(call.args[2] == "-") { call.args[2] = i2s(MOB_ACTION_SET_VAR_SUBTRACT); } else if(call.args[2] == "*") { call.args[2] = i2s(MOB_ACTION_SET_VAR_MULTIPLY); } else if(call.args[2] == "/") { call.args[2] = i2s(MOB_ACTION_SET_VAR_DIVIDE); } else if(call.args[2] == "%") { call.args[2] = i2s(MOB_ACTION_SET_VAR_MODULO); } else { report_enum_error(call, 2); return false; } return true; } /* ---------------------------------------------------------------------------- * Loading code for the focus mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::focus(mob_action_call &call) { if(call.args[0] == "link") { call.args[0] = i2s(MOB_ACTION_FOCUS_LINK); } else if(call.args[0] == "parent") { call.args[0] = i2s(MOB_ACTION_FOCUS_PARENT); } else if(call.args[0] == "trigger") { call.args[0] = i2s(MOB_ACTION_FOCUS_TRIGGER); } else { report_enum_error(call, 0); return false; } return true; } /* ---------------------------------------------------------------------------- * Loading code for the info getting script actions. * call: * Mob action call that called this. */ bool mob_action_loaders::get_info(mob_action_call &call) { if(call.args[1] == "angle") { call.args[1] = i2s(MOB_ACTION_GET_INFO_ANGLE); } else if(call.args[1] == "body_part") { call.args[1] = i2s(MOB_ACTION_GET_INFO_BODY_PART); } else if(call.args[1] == "chomped_pikmin") { call.args[1] = i2s(MOB_ACTION_GET_INFO_CHOMPED_PIKMIN); } else if(call.args[1] == "day_minutes") { call.args[1] = i2s(MOB_ACTION_GET_INFO_DAY_MINUTES); } else if(call.args[1] == "field_pikmin") { call.args[1] = i2s(MOB_ACTION_GET_INFO_FIELD_PIKMIN); } else if(call.args[1] == "focus_distance") { call.args[1] = i2s(MOB_ACTION_GET_INFO_FOCUS_DISTANCE); } else if(call.args[1] == "frame_signal") { call.args[1] = i2s(MOB_ACTION_GET_INFO_FRAME_SIGNAL); } else if(call.args[1] == "group_task_power") { call.args[1] = i2s(MOB_ACTION_GET_INFO_GROUP_TASK_POWER); } else if(call.args[1] == "hazard") { call.args[1] = i2s(MOB_ACTION_GET_INFO_HAZARD); } else if(call.args[1] == "health") { call.args[1] = i2s(MOB_ACTION_GET_INFO_HEALTH); } else if(call.args[1] == "latched_pikmin") { call.args[1] = i2s(MOB_ACTION_GET_INFO_LATCHED_PIKMIN); } else if(call.args[1] == "latched_pikmin_weight") { call.args[1] = i2s(MOB_ACTION_GET_INFO_LATCHED_PIKMIN_WEIGHT); } else if(call.args[1] == "message") { call.args[1] = i2s(MOB_ACTION_GET_INFO_MESSAGE); } else if(call.args[1] == "message_sender") { call.args[1] = i2s(MOB_ACTION_GET_INFO_MESSAGE_SENDER); } else if(call.args[1] == "mob_category") { call.args[1] = i2s(MOB_ACTION_GET_INFO_MOB_CATEGORY); } else if(call.args[1] == "mob_type") { call.args[1] = i2s(MOB_ACTION_GET_INFO_MOB_TYPE); } else if(call.args[1] == "other_body_part") { call.args[1] = i2s(MOB_ACTION_GET_INFO_OTHER_BODY_PART); } else if(call.args[1] == "x") { call.args[1] = i2s(MOB_ACTION_GET_INFO_X); } else if(call.args[1] == "y") { call.args[1] = i2s(MOB_ACTION_GET_INFO_Y); } else if(call.args[1] == "z") { call.args[1] = i2s(MOB_ACTION_GET_INFO_Z); } else if(call.args[1] == "weight") { call.args[1] = i2s(MOB_ACTION_GET_INFO_WEIGHT); } else { report_enum_error(call, 1); return false; } return true; } /* ---------------------------------------------------------------------------- * Loading code for the hold focused mob mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::hold_focus(mob_action_call &call) { size_t p_nr = call.mt->anims.find_body_part(call.args[0]); if(p_nr == INVALID) { call.custom_error = "Unknown body part \"" + call.args[0] + "\"!"; return false; } call.args[0] = i2s(p_nr); return true; } /* ---------------------------------------------------------------------------- * Loading code for the "if" mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::if_function(mob_action_call &call) { if(call.args[1] == "=") { call.args[1] = i2s(MOB_ACTION_IF_OP_EQUAL); } else if(call.args[1] == "!=") { call.args[1] = i2s(MOB_ACTION_IF_OP_NOT); } else if(call.args[1] == "<") { call.args[1] = i2s(MOB_ACTION_IF_OP_LESS); } else if(call.args[1] == ">") { call.args[1] = i2s(MOB_ACTION_IF_OP_MORE); } else if(call.args[1] == "<=") { call.args[1] = i2s(MOB_ACTION_IF_OP_LESS_E); } else if(call.args[1] == ">=") { call.args[1] = i2s(MOB_ACTION_IF_OP_MORE_E); } else { report_enum_error(call, 1); return false; } return true; } /* ---------------------------------------------------------------------------- * Loading code for the move to target mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::move_to_target(mob_action_call &call) { if(call.args[0] == "arachnorb_foot_logic") { call.args[0] = i2s(MOB_ACTION_MOVE_ARACHNORB_FOOT_LOGIC); } else if(call.args[0] == "away_from_focused_mob") { call.args[0] = i2s(MOB_ACTION_MOVE_AWAY_FROM_FOCUSED_MOB); } else if(call.args[0] == "focused_mob") { call.args[0] = i2s(MOB_ACTION_MOVE_FOCUSED_MOB); } else if(call.args[0] == "focused_mob_position") { call.args[0] = i2s(MOB_ACTION_MOVE_FOCUSED_MOB_POS); } else if(call.args[0] == "home") { call.args[0] = i2s(MOB_ACTION_MOVE_HOME); } else if(call.args[0] == "linked_mob_average") { call.args[0] = i2s(MOB_ACTION_MOVE_LINKED_MOB_AVERAGE); } else { report_enum_error(call, 0); return false; } return true; } /* ---------------------------------------------------------------------------- * Loading code for the status reception mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::receive_status(mob_action_call &call) { if(game.status_types.find(call.args[0]) == game.status_types.end()) { call.custom_error = "Unknown status effect \"" + call.args[0] + "\"!"; return false; } return true; } /* ---------------------------------------------------------------------------- * Loading code for the status removal mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::remove_status(mob_action_call &call) { if(game.status_types.find(call.args[0]) == game.status_types.end()) { call.custom_error = "Unknown status effect \"" + call.args[0] + "\"!"; return false; } return true; } /* ---------------------------------------------------------------------------- * Reports an error of an unknown enum value. * call: * Mob action call that called this. * arg_nr: * Index number of the argument that is an enum. */ void mob_action_loaders::report_enum_error( mob_action_call &call, const size_t arg_nr ) { size_t param_nr = std::min(arg_nr, call.action->parameters.size() - 1); call.custom_error = "The parameter \"" + call.action->parameters[param_nr].name + "\" " "does not know what the value \"" + call.args[arg_nr] + "\" means!"; } /* ---------------------------------------------------------------------------- * Loading code for the animation setting mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::set_animation(mob_action_call &call) { size_t a_pos = call.mt->anims.find_animation(call.args[0]); if(a_pos == INVALID) { call.custom_error = "Unknown animation \"" + call.args[0] + "\"!"; return false; } call.args[0] = i2s(a_pos); for(size_t a = 1; a < call.args.size(); ++a) { if(call.args[a] == "no_restart") { call.args[a] = i2s(MOB_ACTION_SET_ANIMATION_NO_RESTART); } else { call.args[a] = "0"; } } return true; } /* ---------------------------------------------------------------------------- * Loading code for the far reach setting mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::set_far_reach(mob_action_call &call) { for(size_t r = 0; r < call.mt->reaches.size(); ++r) { if(call.mt->reaches[r].name == call.args[0]) { call.args[0] = i2s(r); return true; } } call.custom_error = "Unknown reach \"" + call.args[0] + "\"!"; return false; } /* ---------------------------------------------------------------------------- * Loading code for the holdable setting mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::set_holdable(mob_action_call &call) { for(size_t a = 0; a < call.args.size(); ++a) { if(call.args[a] == "pikmin") { call.args[a] = i2s(HOLDABLE_BY_PIKMIN); } else if(call.args[a] == "enemies") { call.args[a] = i2s(HOLDABLE_BY_ENEMIES); } else { report_enum_error(call, a); return false; } } return true; } /* ---------------------------------------------------------------------------- * Loading code for the near reach setting mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::set_near_reach(mob_action_call &call) { for(size_t r = 0; r < call.mt->reaches.size(); ++r) { if(call.mt->reaches[r].name == call.args[0]) { call.args[0] = i2s(r); return true; } } call.custom_error = "Unknown reach \"" + call.args[0] + "\"!"; return false; } /* ---------------------------------------------------------------------------- * Loading code for the team setting mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::set_team(mob_action_call &call) { size_t team_nr = string_to_team_nr(call.args[0]); if(team_nr == INVALID) { report_enum_error(call, 0); return false; } call.args[0] = i2s(team_nr); return true; } /* ---------------------------------------------------------------------------- * Loading code for the spawning mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::spawn(mob_action_call &call) { for(size_t s = 0; s < call.mt->spawns.size(); ++s) { if(call.mt->spawns[s].name == call.args[0]) { call.args[0] = i2s(s); return true; } } call.custom_error = "Unknown spawn info block \"" + call.args[0] + "\"!"; return false; } /* ---------------------------------------------------------------------------- * Loading code for the z stabilization mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::stabilize_z(mob_action_call &call) { if(call.args[0] == "lowest") { call.args[0] = i2s(MOB_ACTION_STABILIZE_Z_LOWEST); } else if(call.args[0] == "highest") { call.args[0] = i2s(MOB_ACTION_STABILIZE_Z_HIGHEST); } else { report_enum_error(call, 0); return false; } return true; } /* ---------------------------------------------------------------------------- * Loading code for the chomping start mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::start_chomping(mob_action_call &call) { for(size_t s = 1; s < call.args.size(); ++s) { size_t p_nr = call.mt->anims.find_body_part(call.args[s]); if(p_nr == INVALID) { call.custom_error = "Unknown body part \"" + call.args[s] + "\"!"; return false; } call.args[s] = i2s(p_nr); } return true; } /* ---------------------------------------------------------------------------- * Loading code for the particle start mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::start_particles(mob_action_call &call) { if( game.custom_particle_generators.find(call.args[0]) == game.custom_particle_generators.end() ) { call.custom_error = "Unknown particle generator \"" + call.args[0] + "\"!"; return false; } return true; } /* ---------------------------------------------------------------------------- * Loading code for the turn to target mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::turn_to_target(mob_action_call &call) { if(call.args[0] == "arachnorb_head_logic") { call.args[0] = i2s(MOB_ACTION_TURN_ARACHNORB_HEAD_LOGIC); } else if(call.args[0] == "focused_mob") { call.args[0] = i2s(MOB_ACTION_TURN_FOCUSED_MOB); } else if(call.args[0] == "home") { call.args[0] = i2s(MOB_ACTION_TURN_HOME); } else { report_enum_error(call, 0); return false; } return true; } /* ---------------------------------------------------------------------------- * Creates a new mob action parameter struct. * name: * Name of the parameter. * type: * Type of parameter. * force_const: * If true, this must be a constant value. If false, it can also be a var. * is_extras: * If true, this is an array of them (minimum amount 0). */ mob_action_param::mob_action_param( const string &name, const MOB_ACTION_PARAM_TYPE type, const bool force_const, const bool is_extras ): name(name), type(type), force_const(force_const), is_extras(is_extras) { } /* ---------------------------------------------------------------------------- * Creates a new mob action run data struct. * m: * The mob responsible. * call: * Mob action call that called this. */ mob_action_run_data::mob_action_run_data(mob* m, mob_action_call* call) : m(m), call(call), custom_data_1(nullptr), custom_data_2(nullptr), return_value(false) { } /* ---------------------------------------------------------------------------- * Code for the health addition mob script action. * data: * Data about the action call. */ void mob_action_runners::add_health(mob_action_run_data &data) { data.m->set_health(true, false, s2f(data.args[0])); } /* ---------------------------------------------------------------------------- * Code for the arachnorb logic plan mob script action. * data: * Data about the action call. */ void mob_action_runners::arachnorb_plan_logic(mob_action_run_data &data) { data.m->arachnorb_plan_logic(s2i(data.args[0])); } /* ---------------------------------------------------------------------------- * Code for the calculation mob script action. * data: * Data about the action call. */ void mob_action_runners::calculate(mob_action_run_data &data) { float lhs = s2f(data.args[1]); size_t op = s2i(data.args[2]); float rhs = s2f(data.args[3]); float result = 0; switch(op) { case MOB_ACTION_SET_VAR_SUM: { result = lhs + rhs; break; } case MOB_ACTION_SET_VAR_SUBTRACT: { result = lhs - rhs; break; } case MOB_ACTION_SET_VAR_MULTIPLY: { result = lhs * rhs; break; } case MOB_ACTION_SET_VAR_DIVIDE: { if(rhs == 0) { result = 0; } else { result = lhs / rhs; } break; } case MOB_ACTION_SET_VAR_MODULO: { if(rhs == 0) { result = 0; } else { result = fmod(lhs, rhs); } break; } } data.m->vars[data.args[0]] = f2s(result); } /* ---------------------------------------------------------------------------- * Code for the deletion mob script action. * data: * Data about the action call. */ void mob_action_runners::delete_function(mob_action_run_data &data) { data.m->to_delete = true; } /* ---------------------------------------------------------------------------- * Code for the liquid draining mob script action. * data: * Data about the action call. */ void mob_action_runners::drain_liquid(mob_action_run_data &data) { sector* s_ptr = get_sector(data.m->pos, NULL, true); if(!s_ptr) return; vector<sector*> sectors_to_drain; s_ptr->get_neighbor_sectors_conditionally( [] (sector * s) -> bool { for(size_t h = 0; h < s->hazards.size(); ++h) { if(s->hazards[h]->associated_liquid) { return true; } } if(s->type == SECTOR_TYPE_BRIDGE) { return true; } if(s->type == SECTOR_TYPE_BRIDGE_RAIL) { return true; } return false; }, sectors_to_drain ); for(size_t s = 0; s < sectors_to_drain.size(); ++s) { sectors_to_drain[s]->draining_liquid = true; sectors_to_drain[s]->liquid_drain_left = LIQUID_DRAIN_DURATION; } } /* ---------------------------------------------------------------------------- * Code for the death finish mob script action. * data: * Data about the action call. */ void mob_action_runners::finish_dying(mob_action_run_data &data) { data.m->finish_dying(); } /* ---------------------------------------------------------------------------- * Code for the focus mob script action. * data: * Data about the action call. */ void mob_action_runners::focus(mob_action_run_data &data) { size_t t = s2i(data.args[0]); switch(t) { case MOB_ACTION_FOCUS_LINK: { if(!data.m->links.empty()) { data.m->focus_on_mob(data.m->links[0]); } break; } case MOB_ACTION_FOCUS_PARENT: { if(data.m->parent) { data.m->focus_on_mob(data.m->parent->m); } break; } case MOB_ACTION_FOCUS_TRIGGER: { if( data.call->parent_event == MOB_EV_OBJECT_IN_REACH || data.call->parent_event == MOB_EV_OPPONENT_IN_REACH || data.call->parent_event == MOB_EV_THROWN_PIKMIN_LANDED || data.call->parent_event == MOB_EV_TOUCHED_OBJECT || data.call->parent_event == MOB_EV_TOUCHED_OPPONENT ) { data.m->focus_on_mob((mob*) (data.custom_data_1)); } else if( data.call->parent_event == MOB_EV_RECEIVE_MESSAGE ) { data.m->focus_on_mob((mob*) (data.custom_data_2)); } break; } } } /* ---------------------------------------------------------------------------- * Code for the follow path randomly mob script action. * data: * Data about the action call. */ void mob_action_runners::follow_path_randomly(mob_action_run_data &data) { string label; if(data.args.size() >= 1) { label = data.args[0]; } //We need to decide what the final stop is going to be. //First, get all eligible stops. vector<path_stop*> choices; if(label.empty()) { //If there's no label, then any stop is eligible. choices.insert( choices.end(), game.cur_area_data.path_stops.begin(), game.cur_area_data.path_stops.end() ); } else { //If there's a label, it'd be nice to only pick stops that have SOME //connection to the label. Checking the stop's outgoing links is //the best we can do, as to not overengineer or hurt performance. for(size_t s = 0; s < game.cur_area_data.path_stops.size(); ++s) { path_stop* s_ptr = game.cur_area_data.path_stops[s]; for(size_t l = 0; l < s_ptr->links.size(); ++l) { if(s_ptr->links[l]->label == label) { choices.push_back(s_ptr); break; } } } } //Pick a stop from the choices at random, but make sure we don't //pick a stop that the mob is practically on already. path_stop* final_stop = NULL; size_t tries = 0; if(!choices.empty()) { while(!final_stop && tries < 5) { size_t c = randomi(0, choices.size() - 1); if( dist(choices[c]->pos, data.m->pos) > chase_info_struct::DEF_TARGET_DISTANCE ) { final_stop = choices[c]; break; } tries++; } } //Go! Though if something went wrong, make it follow a path to nowhere, //so it can emit the MOB_EV_REACHED_DESTINATION event, and hopefully //make it clear that there was an error. data.m->follow_path( final_stop ? final_stop->pos : data.m->pos, true, data.m->get_base_speed(), chase_info_struct::DEF_TARGET_DISTANCE, true, label ); } /* ---------------------------------------------------------------------------- * Code for the follow path to absolute mob script action. * data: * Data about the action call. */ void mob_action_runners::follow_path_to_absolute(mob_action_run_data &data) { float x = s2f(data.args[0]); float y = s2f(data.args[1]); string label; if(data.args.size() >= 3) { label = data.args[2]; } data.m->follow_path( point(x, y), true, data.m->get_base_speed(), chase_info_struct::DEF_TARGET_DISTANCE, true, label ); } /* ---------------------------------------------------------------------------- * Code for the angle obtaining mob script action. * data: * Data about the action call. */ void mob_action_runners::get_angle(mob_action_run_data &data) { float center_x = s2f(data.args[1]); float center_y = s2f(data.args[2]); float focus_x = s2f(data.args[3]); float focus_y = s2f(data.args[4]); float angle = get_angle(point(center_x, center_y), point(focus_x, focus_y)); angle = rad_to_deg(angle); data.m->vars[data.args[0]] = f2s(angle); } /* ---------------------------------------------------------------------------- * Code for the mob script action for getting chomped. * data: * Data about the action call. */ void mob_action_runners::get_chomped(mob_action_run_data &data) { if(data.call->parent_event == MOB_EV_HITBOX_TOUCH_EAT) { ((mob*) (data.custom_data_1))->chomp( data.m, (hitbox*) (data.custom_data_2) ); } } /* ---------------------------------------------------------------------------- * Code for the coordinate from angle obtaining mob script action. * data: * Data about the action call. */ void mob_action_runners::get_coordinates_from_angle(mob_action_run_data &data) { float angle = s2f(data.args[2]); angle = deg_to_rad(angle); float magnitude = s2f(data.args[3]); point p = angle_to_coordinates(angle, magnitude); data.m->vars[data.args[0]] = f2s(p.x); data.m->vars[data.args[1]] = f2s(p.y); } /* ---------------------------------------------------------------------------- * Code for the distance obtaining mob script action. * data: * Data about the action call. */ void mob_action_runners::get_distance(mob_action_run_data &data) { float center_x = s2f(data.args[1]); float center_y = s2f(data.args[2]); float focus_x = s2f(data.args[3]); float focus_y = s2f(data.args[4]); data.m->vars[data.args[0]] = f2s( dist(point(center_x, center_y), point(focus_x, focus_y)).to_float() ); } /* ---------------------------------------------------------------------------- * Code for the floor Z obtaining mob script action. * data: * Data about the action call. */ void mob_action_runners::get_floor_z(mob_action_run_data &data) { float x = s2f(data.args[1]); float y = s2f(data.args[2]); sector* s = get_sector(point(x, y), NULL, true); data.m->vars[data.args[0]] = f2s(s ? s->z : 0); } /* ---------------------------------------------------------------------------- * Code for the info obtaining mob script action. * data: * Data about the action call. */ void mob_action_runners::get_focus_info(mob_action_run_data &data) { get_info_runner(data, data.m->focused_mob); } /* ---------------------------------------------------------------------------- * Code for the focused mob var getting script action. * data: * Data about the action call. */ void mob_action_runners::get_focus_var(mob_action_run_data &data) { if(!data.m->focused_mob) return; data.m->vars[data.args[0]] = data.m->focused_mob->vars[data.args[1]]; } /* ---------------------------------------------------------------------------- * Code for the info obtaining mob script action. * data: * Data about the action call. */ void mob_action_runners::get_info(mob_action_run_data &data) { get_info_runner(data, data.m); } /* ---------------------------------------------------------------------------- * Code for the decimal number randomization mob script action. * data: * Data about the action call. */ void mob_action_runners::get_random_decimal(mob_action_run_data &data) { data.m->vars[data.args[0]] = f2s(randomf(s2f(data.args[1]), s2f(data.args[2]))); } /* ---------------------------------------------------------------------------- * Code for the integer number randomization mob script action. * data: * Data about the action call. */ void mob_action_runners::get_random_int(mob_action_run_data &data) { data.m->vars[data.args[0]] = i2s(randomi(s2i(data.args[1]), s2i(data.args[2]))); } /* ---------------------------------------------------------------------------- * Code for the hold focused mob mob script action. * data: * Data about the action call. */ void mob_action_runners::hold_focus(mob_action_run_data &data) { if(data.m->focused_mob) { data.m->hold( data.m->focused_mob, s2i(data.args[0]), 0.0f, 0.0f, false, HOLD_ROTATION_METHOD_COPY_HOLDER ); } } /* ---------------------------------------------------------------------------- * Code for the "if" mob script action. * data: * Data about the action call. */ void mob_action_runners::if_function(mob_action_run_data &data) { string lhs = data.args[0]; size_t op = s2i(data.args[1]); string rhs = vector_tail_to_string(data.args, 2); switch(op) { case MOB_ACTION_IF_OP_EQUAL: { if(is_number(lhs)) { data.return_value = (s2f(lhs) == s2f(rhs)); } else { data.return_value = (lhs == rhs); } break; } case MOB_ACTION_IF_OP_NOT: { if(is_number(lhs)) { data.return_value = (s2f(lhs) != s2f(rhs)); } else { data.return_value = (lhs != rhs); } break; } case MOB_ACTION_IF_OP_LESS: { data.return_value = (s2f(lhs) < s2f(rhs)); break; } case MOB_ACTION_IF_OP_MORE: { data.return_value = (s2f(lhs) > s2f(rhs)); break; } case MOB_ACTION_IF_OP_LESS_E: { data.return_value = (s2f(lhs) <= s2f(rhs)); break; } case MOB_ACTION_IF_OP_MORE_E: { data.return_value = (s2f(lhs) >= s2f(rhs)); break; } } } /* ---------------------------------------------------------------------------- * Code for the link with focus mob script action. * data: * Data about the action call. */ void mob_action_runners::link_with_focus(mob_action_run_data &data) { if(!data.m->focused_mob) { return; } for(size_t l = 0; l < data.m->links.size(); ++l) { if(data.m->links[l] == data.m->focused_mob) { //Already linked. return; } } data.m->links.push_back(data.m->focused_mob); } /* ---------------------------------------------------------------------------- * Code for the load focused mob memory mob script action. * data: * Data about the action call. */ void mob_action_runners::load_focus_memory(mob_action_run_data &data) { if(data.m->focused_mob_memory.empty()) { return; } data.m->focus_on_mob(data.m->focused_mob_memory[s2i(data.args[0])]); } /* ---------------------------------------------------------------------------- * Code for the move to absolute coordinates mob script action. * data: * Data about the action call. */ void mob_action_runners::move_to_absolute(mob_action_run_data &data) { float x = s2f(data.args[0]); float y = s2f(data.args[1]); float z = data.args.size() > 2 ? s2f(data.args[2]) : data.m->z; data.m->chase(point(x, y), z); } /* ---------------------------------------------------------------------------- * Code for the move to relative coordinates mob script action. * data: * Data about the action call. */ void mob_action_runners::move_to_relative(mob_action_run_data &data) { float x = s2f(data.args[0]); float y = s2f(data.args[1]); float z = (data.args.size() > 2 ? s2f(data.args[2]) : 0); point p = rotate_point(point(x, y), data.m->angle); data.m->chase(data.m->pos + p, data.m->z + z); } /* ---------------------------------------------------------------------------- * Code for the move to target mob script action. * data: * Data about the action call. */ void mob_action_runners::move_to_target(mob_action_run_data &data) { size_t t = s2i(data.args[0]); switch(t) { case MOB_ACTION_MOVE_AWAY_FROM_FOCUSED_MOB: { if(data.m->focused_mob) { float a = get_angle(data.m->pos, data.m->focused_mob->pos); point offset = point(2000, 0); offset = rotate_point(offset, a + TAU / 2.0); data.m->chase(data.m->pos + offset, data.m->z); } else { data.m->stop_chasing(); } break; } case MOB_ACTION_MOVE_FOCUSED_MOB: { if(data.m->focused_mob) { data.m->chase(&data.m->focused_mob->pos, &data.m->focused_mob->z); } else { data.m->stop_chasing(); } break; } case MOB_ACTION_MOVE_FOCUSED_MOB_POS: { if(data.m->focused_mob) { data.m->chase(data.m->focused_mob->pos, data.m->focused_mob->z); } else { data.m->stop_chasing(); } break; } case MOB_ACTION_MOVE_HOME: { data.m->chase(data.m->home, data.m->z); break; } case MOB_ACTION_MOVE_ARACHNORB_FOOT_LOGIC: { data.m->arachnorb_foot_move_logic(); break; } case MOB_ACTION_MOVE_LINKED_MOB_AVERAGE: { if(data.m->links.empty()) { return; } point des; for(size_t l = 0; l < data.m->links.size(); ++l) { des += data.m->links[l]->pos; } des = des / data.m->links.size(); data.m->chase(des, data.m->z); break; } } } /* ---------------------------------------------------------------------------- * Code for the release order mob script action. * data: * Data about the action call. */ void mob_action_runners::order_release(mob_action_run_data &data) { if(data.m->holder.m) { data.m->holder.m->fsm.run_event(MOB_EV_RELEASE_ORDER, NULL, NULL); } } /* ---------------------------------------------------------------------------- * Code for the sound playing mob script action. * data: * Data about the action call. */ void mob_action_runners::play_sound(mob_action_run_data &data) { } /* ---------------------------------------------------------------------------- * Code for the text printing mob script action. * data: * Data about the action call. */ void mob_action_runners::print(mob_action_run_data &data) { string text = vector_tail_to_string(data.args, 0); print_info( "[DEBUG PRINT] " + data.m->type->name + " says:\n" + text, 10.0f ); } /* ---------------------------------------------------------------------------- * Code for the status reception mob script action. * data: * Data about the action call. */ void mob_action_runners::receive_status(mob_action_run_data &data) { data.m->apply_status_effect(game.status_types[data.args[0]], false); } /* ---------------------------------------------------------------------------- * Code for the release mob script action. * data: * Data about the action call. */ void mob_action_runners::release(mob_action_run_data &data) { data.m->release_chomped_pikmin(); } /* ---------------------------------------------------------------------------- * Code for the release stored mobs mob script action. * data: * Data about the action call. */ void mob_action_runners::release_stored_mobs(mob_action_run_data &data) { for(size_t m = 0; m < game.states.gameplay->mobs.all.size(); ++m) { mob* m_ptr = game.states.gameplay->mobs.all[m]; if(m_ptr->stored_inside_another == data.m) { data.m->release(m_ptr); m_ptr->stored_inside_another = NULL; m_ptr->time_alive = 0.0f; } } } /* ---------------------------------------------------------------------------- * Code for the status removal mob script action. * data: * Data about the action call. */ void mob_action_runners::remove_status(mob_action_run_data &data) { for(size_t s = 0; s < data.m->statuses.size(); ++s) { if(data.m->statuses[s].type->name == data.args[0]) { data.m->statuses[s].to_delete = true; } } } /* ---------------------------------------------------------------------------- * Code for the save focused mob memory mob script action. * data: * Data about the action call. */ void mob_action_runners::save_focus_memory(mob_action_run_data &data) { if(!data.m->focused_mob) { return; } data.m->focused_mob_memory[s2i(data.args[0])] = data.m->focused_mob; } /* ---------------------------------------------------------------------------- * Code for the focused mob message sending mob script action. * data: * Data about the action call. */ void mob_action_runners::send_message_to_focus(mob_action_run_data &data) { if(!data.m->focused_mob) return; data.m->send_message(data.m->focused_mob, data.args[0]); } /* ---------------------------------------------------------------------------- * Code for the linked mob message sending mob script action. * data: * Data about the action call. */ void mob_action_runners::send_message_to_links(mob_action_run_data &data) { for(size_t l = 0; l < data.m->links.size(); ++l) { if(data.m->links[l] == data.m) continue; data.m->send_message(data.m->links[l], data.args[0]); } } /* ---------------------------------------------------------------------------- * Code for the nearby mob message sending mob script action. * data: * Data about the action call. */ void mob_action_runners::send_message_to_nearby(mob_action_run_data &data) { float d = s2f(data.args[0]); for(size_t m2 = 0; m2 < game.states.gameplay->mobs.all.size(); ++m2) { if(game.states.gameplay->mobs.all[m2] == data.m) { continue; } if(dist(data.m->pos, game.states.gameplay->mobs.all[m2]->pos) > d) { continue; } data.m->send_message( game.states.gameplay->mobs.all[m2], data.args[1] ); } } /* ---------------------------------------------------------------------------- * Code for the animation setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_animation(mob_action_run_data &data) { bool must_restart = ( data.args.size() > 1 && s2i(data.args[1]) == MOB_ACTION_SET_ANIMATION_NO_RESTART ); data.m->set_animation(s2i(data.args[0]), false, !must_restart); } /* ---------------------------------------------------------------------------- * Code for the block paths setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_can_block_paths(mob_action_run_data &data) { data.m->set_can_block_paths(s2b(data.args[0])); } /* ---------------------------------------------------------------------------- * Code for the far reach setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_far_reach(mob_action_run_data &data) { data.m->far_reach = s2i(data.args[0]); } /* ---------------------------------------------------------------------------- * Code for the flying setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_flying(mob_action_run_data &data) { data.m->can_move_in_midair = s2b(data.args[0]); } /* ---------------------------------------------------------------------------- * Code for the gravity setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_gravity(mob_action_run_data &data) { data.m->gravity_mult = s2f(data.args[0]); } /* ---------------------------------------------------------------------------- * Code for the health setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_health(mob_action_run_data &data) { data.m->set_health(false, false, s2f(data.args[0])); } /* ---------------------------------------------------------------------------- * Code for the height setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_height(mob_action_run_data &data) { data.m->height = s2f(data.args[0]); if(data.m->type->walkable) { //Update the Z of mobs standing on top of it. for(size_t m = 0; m < game.states.gameplay->mobs.all.size(); ++m) { mob* m2_ptr = game.states.gameplay->mobs.all[m]; if(m2_ptr->standing_on_mob == data.m) { m2_ptr->z = data.m->z + data.m->height; } } } } /* ---------------------------------------------------------------------------- * Code for the hiding setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_hiding(mob_action_run_data &data) { data.m->hide = s2b(data.args[0]); } /* ---------------------------------------------------------------------------- * Code for the holdable setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_holdable(mob_action_run_data &data) { if(typeid(*(data.m)) == typeid(tool)) { size_t flags = 0; for(size_t i = 0; i < data.args.size(); ++i) { flags |= s2i(data.args[i]); } ((tool*) (data.m))->holdability_flags = flags; } } /* ---------------------------------------------------------------------------- * Code for the huntable setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_huntable(mob_action_run_data &data) { data.m->is_huntable = s2b(data.args[0]); } /* ---------------------------------------------------------------------------- * Code for the limb animation setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_limb_animation(mob_action_run_data &data) { if(!data.m->parent) { return; } if(!data.m->parent->limb_anim.anim_db) { return; } size_t a = data.m->parent->limb_anim.anim_db->find_animation(data.args[0]); if(a == INVALID) { return; } data.m->parent->limb_anim.cur_anim = data.m->parent->limb_anim.anim_db->animations[a]; data.m->parent->limb_anim.start(); } /* ---------------------------------------------------------------------------- * Code for the near reach setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_near_reach(mob_action_run_data &data) { data.m->near_reach = s2i(data.args[0]); } /* ---------------------------------------------------------------------------- * Code for the radius setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_radius(mob_action_run_data &data) { data.m->radius = s2f(data.args[0]); } /* ---------------------------------------------------------------------------- * Code for the sector scroll setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_sector_scroll(mob_action_run_data &data) { sector* s_ptr = get_sector(data.m->pos, NULL, true); if(!s_ptr) return; s_ptr->scroll.x = s2f(data.args[0]); s_ptr->scroll.y = s2f(data.args[1]); } /* ---------------------------------------------------------------------------- * Code for the shadow visibility setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_shadow_visibility(mob_action_run_data &data) { data.m->show_shadow = s2b(data.args[0]); } /* ---------------------------------------------------------------------------- * Code for the state setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_state(mob_action_run_data &data) { data.m->fsm.set_state( s2i(data.args[0]), data.custom_data_1, data.custom_data_2 ); } /* ---------------------------------------------------------------------------- * Code for the tangible setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_tangible(mob_action_run_data &data) { data.m->tangible = s2b(data.args[0]); } /* ---------------------------------------------------------------------------- * Code for the team setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_team(mob_action_run_data &data) { data.m->team = s2i(data.args[0]); } /* ---------------------------------------------------------------------------- * Code for the timer setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_timer(mob_action_run_data &data) { data.m->set_timer(s2f(data.args[0])); } /* ---------------------------------------------------------------------------- * Code for the var setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_var(mob_action_run_data &data) { data.m->set_var(data.args[0], data.args[1]); } /* ---------------------------------------------------------------------------- * Code for the show message from var mob script action. * data: * Data about the action call. */ void mob_action_runners::show_message_from_var(mob_action_run_data &data) { start_message(data.m->vars[data.args[0]], NULL); } /* ---------------------------------------------------------------------------- * Code for the spawning mob script action. * data: * Data about the action call. */ void mob_action_runners::spawn(mob_action_run_data &data) { data.m->spawn(&data.m->type->spawns[s2i(data.args[0])]); } /* ---------------------------------------------------------------------------- * Code for the z stabilization mob script action. * data: * Data about the action call. */ void mob_action_runners::stabilize_z(mob_action_run_data &data) { if(data.m->links.empty()) { return; } float best_match_z = data.m->links[0]->z; size_t t = s2i(data.args[0]); for(size_t l = 1; l < data.m->links.size(); ++l) { switch(t) { case MOB_ACTION_STABILIZE_Z_HIGHEST: { if(data.m->links[l]->z > best_match_z) { best_match_z = data.m->links[l]->z; } break; } case MOB_ACTION_STABILIZE_Z_LOWEST: { if(data.m->links[l]->z < best_match_z) { best_match_z = data.m->links[l]->z; } break; } } } data.m->z = best_match_z + s2f(data.args[1]); } /* ---------------------------------------------------------------------------- * Code for the chomping start mob script action. * data: * Data about the action call. */ void mob_action_runners::start_chomping(mob_action_run_data &data) { data.m->chomp_max = s2i(data.args[0]); data.m->chomp_body_parts.clear(); for(size_t p = 1; p < data.args.size(); ++p) { data.m->chomp_body_parts.push_back(s2i(data.args[p])); } } /* ---------------------------------------------------------------------------- * Code for the dying start mob script action. * data: * Data about the action call. */ void mob_action_runners::start_dying(mob_action_run_data &data) { data.m->start_dying(); } /* ---------------------------------------------------------------------------- * Code for the height effect start mob script action. * data: * Data about the action call. */ void mob_action_runners::start_height_effect(mob_action_run_data &data) { data.m->start_height_effect(); } /* ---------------------------------------------------------------------------- * Code for the particle start mob script action. * data: * Data about the action call. */ void mob_action_runners::start_particles(mob_action_run_data &data) { float offset_x = 0; float offset_y = 0; float offset_z = 0; if(data.args.size() > 1) offset_x = s2f(data.args[1]); if(data.args.size() > 2) offset_y = s2f(data.args[2]); if(data.args.size() > 3) offset_z = s2f(data.args[3]); particle_generator pg = game.custom_particle_generators[data.args[0]]; pg.id = MOB_PARTICLE_GENERATOR_SCRIPT; pg.follow_mob = data.m; pg.follow_angle = &data.m->angle; pg.follow_pos_offset = point(offset_x, offset_y); pg.follow_z_offset = offset_z; pg.reset(); data.m->particle_generators.push_back(pg); } /* ---------------------------------------------------------------------------- * Code for the stopping mob script action. * data: * Data about the action call. */ void mob_action_runners::stop(mob_action_run_data &data) { data.m->stop_chasing(); data.m->stop_turning(); data.m->stop_following_path(); } /* ---------------------------------------------------------------------------- * Code for the chomp stopping mob script action. * data: * Data about the action call. */ void mob_action_runners::stop_chomping(mob_action_run_data &data) { data.m->chomp_max = 0; data.m->chomp_body_parts.clear(); } /* ---------------------------------------------------------------------------- * Code for the height effect stopping mob script action. * data: * Data about the action call. */ void mob_action_runners::stop_height_effect(mob_action_run_data &data) { data.m->stop_height_effect(); } /* ---------------------------------------------------------------------------- * Code for the particle stopping mob script action. * data: * Data about the action call. */ void mob_action_runners::stop_particles(mob_action_run_data &data) { data.m->remove_particle_generator(MOB_PARTICLE_GENERATOR_SCRIPT); } /* ---------------------------------------------------------------------------- * Code for the vertical stopping mob script action. * data: * Data about the action call. */ void mob_action_runners::stop_vertically(mob_action_run_data &data) { data.m->speed_z = 0; } /* ---------------------------------------------------------------------------- * Code for the focus storing mob script action. * data: * Data about the action call. */ void mob_action_runners::store_focus_inside(mob_action_run_data &data) { if(data.m->focused_mob) { if(!data.m->focused_mob->stored_inside_another) { data.m->hold( data.m->focused_mob, INVALID, 0.0f, 0.0f, false, HOLD_ROTATION_METHOD_NEVER ); data.m->focused_mob->stored_inside_another = data.m; } } } /* ---------------------------------------------------------------------------- * Code for the swallow mob script action. * data: * Data about the action call. */ void mob_action_runners::swallow(mob_action_run_data &data) { data.m->swallow_chomped_pikmin(s2i(data.args[1])); } /* ---------------------------------------------------------------------------- * Code for the swallow all mob script action. * data: * Data about the action call. */ void mob_action_runners::swallow_all(mob_action_run_data &data) { data.m->swallow_chomped_pikmin(data.m->chomping_mobs.size()); } /* ---------------------------------------------------------------------------- * Code for the teleport to absolute coordinates mob script action. * data: * Data about the action call. */ void mob_action_runners::teleport_to_absolute(mob_action_run_data &data) { data.m->stop_chasing(); data.m->chase( point(s2f(data.args[0]), s2f(data.args[1])), s2f(data.args[2]), CHASE_FLAG_TELEPORT ); } /* ---------------------------------------------------------------------------- * Code for the teleport to relative coordinates mob script action. * data: * Data about the action call. */ void mob_action_runners::teleport_to_relative(mob_action_run_data &data) { data.m->stop_chasing(); point p = rotate_point( point(s2f(data.args[0]), s2f(data.args[1])), data.m->angle ); data.m->chase( data.m->pos + p, data.m->z + s2f(data.args[2]), CHASE_FLAG_TELEPORT ); } /* ---------------------------------------------------------------------------- * Code for the throw focused mob mob script action. * data: * Data about the action call. */ void mob_action_runners::throw_focus(mob_action_run_data &data) { if(!data.m->focused_mob) { return; } if(data.m->focused_mob->holder.m == data.m) { data.m->release(data.m->focused_mob); } float max_height = s2f(data.args[3]); if(max_height == 0.0f) { //We just want to drop it, not throw it. return; } data.m->start_height_effect(); calculate_throw( data.m->focused_mob->pos, data.m->focused_mob->z, point(s2f(data.args[0]), s2f(data.args[1])), s2f(data.args[2]), max_height, GRAVITY_ADDER, &data.m->focused_mob->speed, &data.m->focused_mob->speed_z, NULL ); } /* ---------------------------------------------------------------------------- * Code for the turn to an absolute angle mob script action. * data: * Data about the action call. */ void mob_action_runners::turn_to_absolute(mob_action_run_data &data) { if(data.args.size() == 1) { //Turn to an absolute angle. data.m->face(deg_to_rad(s2f(data.args[0])), NULL); } else { //Turn to some absolute coordinates. float x = s2f(data.args[0]); float y = s2f(data.args[1]); data.m->face(get_angle(data.m->pos, point(x, y)), NULL); } } /* ---------------------------------------------------------------------------- * Code for the turn to a relative angle mob script action. * data: * Data about the action call. */ void mob_action_runners::turn_to_relative(mob_action_run_data &data) { if(data.args.size() == 1) { //Turn to a relative angle. data.m->face(data.m->angle + deg_to_rad(s2f(data.args[0])), NULL); } else { //Turn to some relative coordinates. float x = s2f(data.args[0]); float y = s2f(data.args[1]); point p = rotate_point(point(x, y), data.m->angle); data.m->face(get_angle(data.m->pos, data.m->pos + p), NULL); } } /* ---------------------------------------------------------------------------- * Code for the turn to target mob script action. * data: * Data about the action call. */ void mob_action_runners::turn_to_target(mob_action_run_data &data) { size_t t = s2i(data.args[0]); switch(t) { case MOB_ACTION_TURN_ARACHNORB_HEAD_LOGIC: { data.m->arachnorb_head_turn_logic(); break; } case MOB_ACTION_TURN_FOCUSED_MOB: { if(data.m->focused_mob) { data.m->face(0, &data.m->focused_mob->pos); } break; } case MOB_ACTION_TURN_HOME: { data.m->face(get_angle(data.m->pos, data.m->home), NULL); break; } } } /* ---------------------------------------------------------------------------- * Confirms if the "if", "else", "end_if", "goto", and "label" actions in * a given vector of actions are all okay, and there are no mismatches, like * for instance, an "else" without an "if". * Also checks if there are actions past a "set_state" action. * If everything is okay, returns true. If not, throws errors to the * error log and returns false. * actions: * The vector of actions to check. * dn: * Data node from where these actions came. */ bool assert_actions( const vector<mob_action_call*> &actions, data_node* dn ) { //Check if the "if"-related actions are okay. int if_level = 0; for(size_t a = 0; a < actions.size(); ++a) { switch(actions[a]->action->type) { case MOB_ACTION_IF: { if_level++; break; } case MOB_ACTION_ELSE: { if(if_level == 0) { log_error( "Found an \"else\" action without a matching " "\"if\" action!", dn ); return false; } break; } case MOB_ACTION_END_IF: { if(if_level == 0) { log_error( "Found an \"end_if\" action without a matching " "\"if\" action!", dn ); return false; } if_level--; break; } } } if(if_level > 0) { log_error( "Some \"if\" actions don't have a matching \"end_if\" action!", dn ); return false; } //Check if the "goto"-related actions are okay. set<string> labels; for(size_t a = 0; a < actions.size(); ++a) { if(actions[a]->action->type == MOB_ACTION_LABEL) { string name = actions[a]->args[0]; if(labels.find(name) != labels.end()) { log_error( "There are multiple labels called \"" + name + "\"!", dn ); return false; } labels.insert(name); } } for(size_t a = 0; a < actions.size(); ++a) { if(actions[a]->action->type == MOB_ACTION_GOTO) { string name = actions[a]->args[0]; if(labels.find(name) == labels.end()) { log_error( "There is no label called \"" + name + "\", even though " "there are \"goto\" actions that need it!", dn ); return false; } } } //Check if there are actions after a "set_state" action. bool passed_set_state = false; for(size_t a = 0; a < actions.size(); ++a) { switch(actions[a]->action->type) { case MOB_ACTION_SET_STATE: { passed_set_state = true; break; } case MOB_ACTION_ELSE: { passed_set_state = false; break; } case MOB_ACTION_END_IF: { passed_set_state = false; break; } case MOB_ACTION_LABEL: { passed_set_state = false; break; } default: { if(passed_set_state) { log_error( "There is an action \"" + actions[a]->action->name + "\" " "placed after a \"set_state\" action, which means it will " "never get run! Make sure you didn't mean to call it " "before the \"set_state\" action.", dn ); return false; } break; } } } return true; } /* ---------------------------------------------------------------------------- * A general function for get_info actions. * data: * The action's data. * target_mob: * The mob to get the info from, if applicable. */ void get_info_runner(mob_action_run_data &data, mob* target_mob) { if(target_mob == NULL) { return; } string* var = &(data.m->vars[data.args[0]]); size_t t = s2i(data.args[1]); switch(t) { case MOB_ACTION_GET_INFO_ANGLE: { *var = f2s(rad_to_deg(target_mob->angle)); break; } case MOB_ACTION_GET_INFO_BODY_PART: { if( data.call->parent_event == MOB_EV_HITBOX_TOUCH_A_N || data.call->parent_event == MOB_EV_HITBOX_TOUCH_N_A || data.call->parent_event == MOB_EV_HITBOX_TOUCH_N_N || data.call->parent_event == MOB_EV_DAMAGE ) { *var = ( (hitbox_interaction*)(data.custom_data_1) )->h1->body_part_name; } else if( data.call->parent_event == MOB_EV_TOUCHED_OBJECT || data.call->parent_event == MOB_EV_TOUCHED_OPPONENT || data.call->parent_event == MOB_EV_THROWN_PIKMIN_LANDED ) { *var = target_mob->get_closest_hitbox( ((mob*)(data.custom_data_1))->pos, INVALID, NULL )->body_part_name; } break; } case MOB_ACTION_GET_INFO_CHOMPED_PIKMIN: { *var = i2s(target_mob->chomping_mobs.size()); break; } case MOB_ACTION_GET_INFO_DAY_MINUTES: { *var = i2s(game.states.gameplay->day_minutes); break; } case MOB_ACTION_GET_INFO_FIELD_PIKMIN: { *var = i2s(game.states.gameplay->mobs.pikmin_list.size()); break; } case MOB_ACTION_GET_INFO_FOCUS_DISTANCE: { if(target_mob->focused_mob) { float d = dist(target_mob->pos, target_mob->focused_mob->pos).to_float(); *var = f2s(d); } break; } case MOB_ACTION_GET_INFO_FRAME_SIGNAL: { if(data.call->parent_event == MOB_EV_FRAME_SIGNAL) { *var = i2s(*((size_t*)(data.custom_data_1))); } break; } case MOB_ACTION_GET_INFO_GROUP_TASK_POWER: { if(target_mob->type->category->id == MOB_CATEGORY_GROUP_TASKS) { *var = f2s(((group_task*) target_mob)->get_power()); } break; } case MOB_ACTION_GET_INFO_HAZARD: { if( data.call->parent_event == MOB_EV_TOUCHED_HAZARD || data.call->parent_event == MOB_EV_LEFT_HAZARD ) { *var = ((hazard*) data.custom_data_1)->name; } break; } case MOB_ACTION_GET_INFO_HEALTH: { *var = i2s(target_mob->health); break; } case MOB_ACTION_GET_INFO_LATCHED_PIKMIN: { *var = i2s(target_mob->get_latched_pikmin_amount()); break; } case MOB_ACTION_GET_INFO_LATCHED_PIKMIN_WEIGHT: { *var = i2s(target_mob->get_latched_pikmin_weight()); break; } case MOB_ACTION_GET_INFO_MESSAGE: { if(data.call->parent_event == MOB_EV_RECEIVE_MESSAGE) { *var = *((string*)(data.custom_data_1)); } break; } case MOB_ACTION_GET_INFO_MESSAGE_SENDER: { if(data.call->parent_event == MOB_EV_RECEIVE_MESSAGE) { *var = ((mob*)(data.custom_data_2))->type->name; } break; } case MOB_ACTION_GET_INFO_MOB_CATEGORY: { if( data.call->parent_event == MOB_EV_TOUCHED_OBJECT || data.call->parent_event == MOB_EV_TOUCHED_OPPONENT || data.call->parent_event == MOB_EV_OBJECT_IN_REACH || data.call->parent_event == MOB_EV_OPPONENT_IN_REACH ) { *var = ((mob*)(data.custom_data_1))->type->category->name; } break; } case MOB_ACTION_GET_INFO_MOB_TYPE: { if( data.call->parent_event == MOB_EV_TOUCHED_OBJECT || data.call->parent_event == MOB_EV_TOUCHED_OPPONENT || data.call->parent_event == MOB_EV_OBJECT_IN_REACH || data.call->parent_event == MOB_EV_OPPONENT_IN_REACH || data.call->parent_event == MOB_EV_THROWN_PIKMIN_LANDED ) { *var = ((mob*)(data.custom_data_1))->type->name; } break; } case MOB_ACTION_GET_INFO_OTHER_BODY_PART: { if( data.call->parent_event == MOB_EV_HITBOX_TOUCH_A_N || data.call->parent_event == MOB_EV_HITBOX_TOUCH_N_A || data.call->parent_event == MOB_EV_HITBOX_TOUCH_N_N || data.call->parent_event == MOB_EV_DAMAGE ) { *var = ( (hitbox_interaction*)(data.custom_data_1) )->h2->body_part_name; } else if( data.call->parent_event == MOB_EV_TOUCHED_OBJECT || data.call->parent_event == MOB_EV_TOUCHED_OPPONENT || data.call->parent_event == MOB_EV_THROWN_PIKMIN_LANDED ) { *var = ((mob*)(data.custom_data_1))->get_closest_hitbox( target_mob->pos, INVALID, NULL )->body_part_name; } break; } case MOB_ACTION_GET_INFO_X: { *var = f2s(target_mob->pos.x); break; } case MOB_ACTION_GET_INFO_Y: { *var = f2s(target_mob->pos.y); break; } case MOB_ACTION_GET_INFO_Z: { *var = f2s(target_mob->z); break; } case MOB_ACTION_GET_INFO_WEIGHT: { if(target_mob->type->category->id == MOB_CATEGORY_SCALES) { scale* s_ptr = (scale*)(target_mob); *var = i2s(s_ptr->calculate_cur_weight()); } break; } } } /* ---------------------------------------------------------------------------- * Loads the actions to be run when the mob initializes. * mt: * The type of mob the actions are going to. * node: * The data node. * actions: * Vector of actions to be filled. */ void load_init_actions( mob_type* mt, data_node* node, vector<mob_action_call*>* actions ) { for(size_t a = 0; a < node->get_nr_of_children(); ++a) { mob_action_call* new_a = new mob_action_call(); if(new_a->load_from_data_node(node->get_child(a), mt)) { actions->push_back(new_a); } else { delete new_a; } } assert_actions(*actions, node); }
30.515021
80
0.522714
shantonusen
72c1b748ab5c3dfc784d038e4eeea1cce78b47e5
623
cpp
C++
hostsampleapp/uwp/Common/PerceptionTypes.cpp
sereilly/MixedReality-HolographicRemoting-Samples
d6ff35e13a5edda41e074b355bf82e875ab24e4a
[ "MIT" ]
null
null
null
hostsampleapp/uwp/Common/PerceptionTypes.cpp
sereilly/MixedReality-HolographicRemoting-Samples
d6ff35e13a5edda41e074b355bf82e875ab24e4a
[ "MIT" ]
null
null
null
hostsampleapp/uwp/Common/PerceptionTypes.cpp
sereilly/MixedReality-HolographicRemoting-Samples
d6ff35e13a5edda41e074b355bf82e875ab24e4a
[ "MIT" ]
null
null
null
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "../pch.h" // -- important: preserve order of these two includes (initguid before PerceptionTypes)! #include <initguid.h> #include "PerceptionTypes.h" // --
32.789474
89
0.566613
sereilly
72c1e2a0e1b07c400d95eb0841381aae9b6d107c
4,264
hpp
C++
librt/include/material.hpp
julitopower/RayTracingWeekend
0b9035f596fe33b39eb8a476a729a01dfecd2a1e
[ "MIT" ]
1
2018-12-22T00:12:10.000Z
2018-12-22T00:12:10.000Z
librt/include/material.hpp
julitopower/RayTracingWeekend
0b9035f596fe33b39eb8a476a729a01dfecd2a1e
[ "MIT" ]
null
null
null
librt/include/material.hpp
julitopower/RayTracingWeekend
0b9035f596fe33b39eb8a476a729a01dfecd2a1e
[ "MIT" ]
1
2019-04-09T12:51:49.000Z
2019-04-09T12:51:49.000Z
#ifndef MATERIAL_HPP #define MATERIAL_HPP #include <map> #include <memory> #include <string> #include <vector.hpp> #include <texture.hpp> namespace rt { class Hit; class Ray; /*! * \brief Abstract representation of a material that can be associated with * a object. Material is also used to decorate a Hit. */ class Material { public: /*! * \brief Scatter an incoming Ray using Hit information, and attenuation vector * * \param ray The incoming Ray * \param hit Information about the intersection between the Ray and a Hitable * \param attenuation Vector representing the attenuation factor to be applied to each color * \param scattered Output parameter. Ray generated by the scatter calculation * \return */ virtual bool scatter(const Ray& ray, const Hit& hit, Vector3f& attenuation, Ray& scattered) const = 0; virtual Vector3f emmitted() const { return {0,0,0}; } virtual ~Material(){}; }; class Light : public Material { public: Light(const Vector3f& color) : color_{color} {} bool scatter(const Ray& ray, const Hit& rec, Vector3f& attenuation, Ray& scattered) const final override { return false; } Vector3f emmitted() const final override { return color_; } private: Vector3f color_; }; /*! * \brief A non reflecting material */ class Lambertian : public Material { public: /*! * \brief Construct a new Lambertian material with the given attenuation vector */ explicit Lambertian(Texture* a) : albedo_{a} {} /* * Generate a scattered Ray in a random direction. Given an intersection point a * nd a normal with unit length, the scattered ray is calculated by moving the * intersection point in the direction of the normal, for the length of the * normal, and then moving it along a unit vector in a random direction. */ bool scatter(const Ray& ray, const Hit& rec, Vector3f& attenuation, Ray& scattered) const final override; private: Texture* albedo_; }; class Metal : public Material { public: explicit Metal(const Vector3f& a) : albedo_{a}{} bool scatter(const Ray& ray, const Hit& rec, Vector3f& attenuation, Ray& scattered) const final override; private: Vector3f albedo_; }; /*! * \brief A non reflecting material */ class Dielectric : public Material { public: /*! * \brief Construct a new Lambertian material with the given attenuation vector */ explicit Dielectric(float ri) : ref_idx_{ri} {} /* * Generate a scattered Ray in a random direction. Given an intersection point a * nd a normal with unit length, the scattered ray is calculated by moving the * intersection point in the direction of the normal, for the length of the * normal, and then moving it along a unit vector in a random direction. */ bool scatter(const Ray& ray, const Hit& rec, Vector3f& attenuation, Ray& scattered) const final override; private: float ref_idx_; }; class MaterialRegistry { public: MaterialRegistry() = default; void register_lambertian(const std::string& name, Texture* attenuation); void register_metal(const std::string& name, const Vector3f& attenuation); void register_dielectric(const std::string& name, float ref_idx); void register_light(const std::string& name, const Vector3f& color); Material* get(const std::string& name); Material* generate_lambertial(rt::TextureRegistry& textures) { random_.push_back(std::make_unique<Lambertian>(textures.random_color())); return random_.back().get(); } Material* generate_metal() { auto dis = std::uniform_real_distribution<float>{0.0, 1.0}; std::random_device device; random_.push_back( std::make_unique<Metal>(rt::Vector3f{0.5f * (1 + dis(device)), 0.5f * (1 + dis(device)), 0.5f * dis(device)})); return random_.back().get(); } Material* generate_dielectric() { random_.push_back(std::make_unique<Dielectric>(1.5)); return random_.back().get(); } private: std::map<std::string, std::unique_ptr<Material>> registry_; std::vector<std::unique_ptr<Material>> random_; }; } // namespace rt #endif // MATERIAL_HPP
25.842424
94
0.681989
julitopower
72c8b0e1c3c67a575cea76d95ca253c44ac1feeb
392
hpp
C++
include/cgl/map.hpp
sdragonx/cgl
d8d45d3a3930bc8f3d0851371760742fda4733b8
[ "MIT" ]
1
2020-12-30T06:35:47.000Z
2020-12-30T06:35:47.000Z
include/cgl/map.hpp
sdragonx/cgl
d8d45d3a3930bc8f3d0851371760742fda4733b8
[ "MIT" ]
null
null
null
include/cgl/map.hpp
sdragonx/cgl
d8d45d3a3930bc8f3d0851371760742fda4733b8
[ "MIT" ]
null
null
null
/* Copyright (c) 2005-2020 sdragonx (mail:[email protected]) map.hpp 2018-10-20 08:57:26 */ #ifndef MAP_HPP_20181020085726 #define MAP_HPP_20181020085726 #include <cgl/std/map/cmap.hpp> #include <cgl/std/map/dual_map.hpp> #include <cgl/std/map/idmap.hpp> #include <cgl/std/map/hashmap.hpp> namespace cgl{ }//end namespace cgl #endif //MAP_HPP_20181020085726
17.818182
62
0.709184
sdragonx
72d034f5d0523280715e05e1f3aeedad78e97678
1,972
cpp
C++
src/catamorph/interpreters/variable_ordering.cpp
geisserf/lemon-dd
e7518886ce7dc5960f16d799c8ff6450ea67e7ae
[ "BSL-1.0" ]
2
2018-10-26T11:21:13.000Z
2020-06-04T11:31:03.000Z
src/catamorph/interpreters/variable_ordering.cpp
geisserf/lemon-dd
e7518886ce7dc5960f16d799c8ff6450ea67e7ae
[ "BSL-1.0" ]
10
2018-11-28T08:55:51.000Z
2018-12-04T09:15:17.000Z
src/catamorph/interpreters/variable_ordering.cpp
geisserf/lemon-dd
e7518886ce7dc5960f16d799c8ff6450ea67e7ae
[ "BSL-1.0" ]
null
null
null
#include "variable_ordering.h" #include "../../parser.h" #include "dependencies.h" #include <iomanip> #include <iostream> #include <stack> ASTNode::ASTNode() : value("{}"), topo_order(-1), variable(false) {} ASTNode::ASTNode(double value) : value(std::to_string(value)), topo_order(0), variable(false) {} ASTNode::ASTNode(const std::string &value) : value(value), topo_order(0), variable(true) {} ASTNode::ASTNode(const std::string &value, const std::vector<ASTNode> &children) : value(value), variable(false) { // Children are sorted according to their topo order this->children = children; std::sort(this->children.begin(), this->children.end(), [](const ASTNode &x, const ASTNode &y) { return x.get_topo_order() < y.get_topo_order(); }); // Last child has highest topo value if (this->children.empty()) { topo_order = 0; } else { topo_order = this->children[children.size() - 1].get_topo_order() + 1; } } Ordering VariableOrdering::get_fan_in_ordering(const Expression &expr) { size_t num_supp_vars = Dependency::dependencies(expr).size(); auto node = create_ast(expr); Ordering var_order; std::stack<ASTNode> Q; std::vector<ASTNode> children; Q.push(node); while (!Q.empty()) { ASTNode cur = Q.top(); Q.pop(); if (var_order.size() == num_supp_vars) return var_order; // Is variable root node and not already contained in var_order if (cur.is_variable() && std::find(var_order.begin(), var_order.end(), cur.get_value()) == var_order.end()) { var_order.push_back(cur.get_value()); } children = cur.get_children(); // Children are already sorted by their topo order => push on stack for (size_t i = 0; i < children.size(); ++i) { Q.push(children[i]); } } return var_order; }
29.432836
80
0.60497
geisserf
72db594e5f5b029db43a3c22f46144f096f92012
2,749
cxx
C++
Readers/DXFReader/vtkDXFBlock.cxx
ObjectivitySRC/PVGPlugins
5e24150262af751159d719cc810620d1770f2872
[ "BSD-2-Clause" ]
4
2016-01-21T21:45:43.000Z
2021-07-31T19:24:09.000Z
Readers/DXFReader/vtkDXFBlock.cxx
ObjectivitySRC/PVGPlugins
5e24150262af751159d719cc810620d1770f2872
[ "BSD-2-Clause" ]
null
null
null
Readers/DXFReader/vtkDXFBlock.cxx
ObjectivitySRC/PVGPlugins
5e24150262af751159d719cc810620d1770f2872
[ "BSD-2-Clause" ]
6
2015-08-31T06:21:03.000Z
2021-07-31T19:24:10.000Z
// By: Eric Daoust && Matthew Livingstone #include "vtkDXFBlock.h" #include <vtksys/ios/sstream> #include "vtkObjectFactory.h" #include "vtkPolyData.h" #include "vtkCollection.h" #include "vtkTransform.h" #include "vtkTransformFilter.h" vtkCxxRevisionMacro(vtkDXFBlock, "$Revision: 1 $"); vtkStandardNewMacro(vtkDXFBlock); vtkDXFBlock::vtkDXFBlock() { this->blockScale = new double[3]; this->blockScale[0] = this->blockScale[1] = this->blockScale[2] = 1.0; this->blockTransform = new double[3]; this->blockTransform[0] = this->blockTransform[1] = this->blockTransform[2] = 0.0; this->parentLayer = ""; this->drawBlock = false; this->blockPropertyValue = 0; } vtkDXFBlock::~vtkDXFBlock() { if ( this->blockScale ) { delete[] this->blockScale; } if ( this->blockTransform ) { delete[] this->blockTransform; } } void vtkDXFBlock::PrintSelf(ostream& os, vtkIndent indent) { //TODO: complete this method this->Superclass::PrintSelf(os,indent); } void vtkDXFBlock::CopyFrom(vtkDXFBlock* block) { this->name = block->getName(); // Point/Cell Data this->pointPoints->DeepCopy(block->getPointPoints()); this->pointCells->DeepCopy(block->getPointCells()); this->linePoints->DeepCopy(block->getLinePoints()); this->lineCells->DeepCopy(block->getLineCells()); this->polyLinePoints->DeepCopy(block->getPolyLinePoints()); this->polyLineCells->DeepCopy(block->getPolyLineCells()); this->lwPolyLinePoints->DeepCopy(block->getLWPolyLinePoints()); this->lwPolyLineCells->DeepCopy(block->getLWPolyLineCells()); this->surfPoints->DeepCopy(block->getSurfPoints()); this->surfCells->DeepCopy(block->getSurfCells()); this->solidPoints->DeepCopy(block->getSolidPoints()); this->solidCells->DeepCopy(block->getSolidCells()); this->arcPoints->DeepCopy(block->getArcPoints()); this->arcCells->DeepCopy(block->getArcCells()); for(int textItem = 0; textItem < block->getText()->GetNumberOfItems(); textItem++) { this->textList->AddItem(vtkPolyData::SafeDownCast(block->getText()->GetItemAsObject(textItem))); } for(int circleItem = 0; circleItem < block->getCircles()->GetNumberOfItems(); circleItem++) { this->circleList->AddItem(vtkPolyData::SafeDownCast(block->getCircles()->GetItemAsObject(circleItem))); } // Properties this->pointProps->DeepCopy(block->getPointProps()); this->lineProps->DeepCopy(block->getLineProps()); this->polyLineProps->DeepCopy(block->getPolyLineProps()); this->lwPolyLineProps->DeepCopy(block->getLWPolyLineProps()); this->surfProps->DeepCopy(block->getSurfProps()); this->solidProps->DeepCopy(block->getSolidProps()); this->arcProps->DeepCopy(block->getArcProps()); this->circleProps->DeepCopy( block->getCircleProps() ); this->textProps->DeepCopy(block->getTextProps()); }
31.965116
105
0.734085
ObjectivitySRC
72e0f706f4400101306f7b0a889f95cec8db7696
4,905
hpp
C++
libraries/ThreadAPI/include/thread/Thread.hpp
StratifyLabs/API
ca0bf670653b78da43ad416cd1c5e977c8549eeb
[ "MIT" ]
7
2020-12-15T14:27:02.000Z
2022-03-23T12:00:13.000Z
libraries/ThreadAPI/include/thread/Thread.hpp
StratifyLabs/API
ca0bf670653b78da43ad416cd1c5e977c8549eeb
[ "MIT" ]
null
null
null
libraries/ThreadAPI/include/thread/Thread.hpp
StratifyLabs/API
ca0bf670653b78da43ad416cd1c5e977c8549eeb
[ "MIT" ]
1
2021-01-06T14:51:51.000Z
2021-01-06T14:51:51.000Z
// Copyright 2011-2021 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md #ifndef THREADAPI_THREAD_THREAD_HPP #define THREADAPI_THREAD_THREAD_HPP #include <pthread.h> #include <csignal> #include "Sched.hpp" #include "chrono/ClockTime.hpp" namespace thread { class Thread : public api::ExecutionContext { public: enum class DetachState { joinable = PTHREAD_CREATE_JOINABLE, detached = PTHREAD_CREATE_DETACHED }; using Policy = Sched::Policy; enum class IsInherit { no = PTHREAD_EXPLICIT_SCHED, yes = PTHREAD_INHERIT_SCHED }; enum class ContentionScope { system = PTHREAD_SCOPE_SYSTEM, process = PTHREAD_SCOPE_PROCESS }; using Scope = ContentionScope; typedef void *(*function_t)(void *); class Attributes : public api::ExecutionContext { public: Attributes(); ~Attributes(); Attributes &set_stack_size(size_t value); API_NO_DISCARD int get_stack_size() const; Attributes &set_detach_state(DetachState value); Attributes& set_joinable(){ return set_detach_state(DetachState::joinable); } Attributes& set_detached(){ return set_detach_state(DetachState::detached); } API_NO_DISCARD DetachState get_detach_state() const; Attributes &set_inherit_sched(IsInherit value); API_NO_DISCARD IsInherit get_inherit_sched() const; Attributes &set_scope(ContentionScope value); API_NO_DISCARD ContentionScope get_scope() const; Attributes &set_sched_policy(Sched::Policy value); Attributes &set_sched_priority(int priority); API_NO_DISCARD Sched::Policy get_sched_policy() const; API_NO_DISCARD int get_sched_priority() const; private: friend class Thread; pthread_attr_t m_pthread_attr{}; }; class Construct { API_ACCESS_FUNDAMENTAL(Construct, function_t, function, nullptr); API_ACCESS_FUNDAMENTAL(Construct, void *, argument, nullptr); }; Thread() = default; // don't allow making copies Thread(const Thread &thread) = delete; Thread &operator=(const Thread &thread) = delete; // allow moving threads Thread &operator=(Thread &&a) noexcept { swap(std::move(a)); return *this; } Thread(Thread &&a) noexcept { swap(std::move(a)); } Thread &&move() { return std::move(*this); } explicit Thread(const Construct &options); Thread(const Attributes &attributes, const Construct &options); Thread(const Attributes &attributes, void * argument, function_t thread_function){ construct(attributes, Construct().set_argument(argument).set_function(thread_function)); } Thread(void * argument, function_t thread_function){ construct(Attributes(), Construct().set_argument(argument).set_function(thread_function)); } ~Thread(); /*! \details Gets the ID of the thread. */ API_NO_DISCARD pthread_t id() const { return m_id; } /*! \details Returns true if the thread has a valid id. * * If create() has not been called, this will return false. * If there was an error creating the thread, this will * also return false; * */ API_NO_DISCARD bool is_valid() const; enum class CancelType { deferred = PTHREAD_CANCEL_DEFERRED, asynchronous = PTHREAD_CANCEL_ASYNCHRONOUS }; static CancelType set_cancel_type(CancelType cancel_type); enum class CancelState { enable = PTHREAD_CANCEL_ENABLE, disable = PTHREAD_CANCEL_DISABLE }; Thread &set_sched_parameters(Sched::Policy policy, int priority); API_NO_DISCARD Sched::Policy get_sched_policy() const; API_NO_DISCARD int get_sched_priority() const; static CancelState set_cancel_state(CancelState cancel_state); const Thread &cancel() const; Thread &cancel() { return API_CONST_CAST_SELF(Thread, cancel); } API_NO_DISCARD bool is_running() const; API_NO_DISCARD static pthread_t self() { return pthread_self(); } const Thread &kill(int signal_number) const { API_RETURN_VALUE_IF_ERROR(*this); API_SYSTEM_CALL("", pthread_kill(id(), signal_number)); return *this; } Thread &join(void **value = nullptr); API_NO_DISCARD bool is_joinable() const { return m_state == State::joinable; } //API_NO_DISCARD const api::Error *execution_context_error() const { // return m_execution_context_error; //} private: enum class State { null = 0, completed, error, joinable, detached }; const api::Error *m_execution_context_error = nullptr; volatile State m_state = State::null; pthread_t m_id = #if defined __link {}; #else 0; #endif void swap(Thread &&a) { std::swap(m_id, a.m_id); std::swap(m_state, a.m_state); std::swap(m_execution_context_error, a.m_execution_context_error); } void construct(const Attributes & attributes, const Construct & options); static void *handle_thread(void *args); int get_sched_parameters(int &policy, int &priority) const; }; } // namespace thread #endif /* THREADAPI_THREAD_THREAD_HPP */
27.711864
94
0.723547
StratifyLabs
72e664d59e9416fe65c76d37c3f3c0acf8e3d9c9
925
cpp
C++
arc058_b/Main.cpp
s-shirayama/AtCoder
8bb777af516a6a24ce88a5b9f2c22bf4fc7cd3c8
[ "MIT" ]
null
null
null
arc058_b/Main.cpp
s-shirayama/AtCoder
8bb777af516a6a24ce88a5b9f2c22bf4fc7cd3c8
[ "MIT" ]
null
null
null
arc058_b/Main.cpp
s-shirayama/AtCoder
8bb777af516a6a24ce88a5b9f2c22bf4fc7cd3c8
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define REP(i, n, s) for (int i = (s); i < (n); i++) using namespace std; typedef long long int LL; typedef long double LD; const int MOD = 1e9 + 7; const int MAXN = 1e5 * 2; int nPn[MAXN]; int _pow(int a, int k) { int res = 1; while (k) { // k%1 == 1 if (k & 1) res = LL(res) * a % MOD; a = LL(a) * a % MOD; // k /= 2; k >>= 1; } return res; } int nCr(int n, int r) { // /= A -> *= A^M-2 return LL(nPn[n]) * _pow(LL(nPn[n-r]) * nPn[r] % MOD, MOD - 2) % MOD; } int calc(int h1, int w1, int h2, int w2) { return nCr((h2 - h1) + (w2 - w1), (h2 - h1)); } int main() { int H, W, A, B; scanf("%d %d %d %d", &H, &W, &A, &B); nPn[0] = 1; REP(i, MAXN+1, 1) nPn[i] = LL(i) * nPn[i-1] % MOD; int h = H - A, w = B + 1; int res = 0; while (h >= 1 && w <= W) { res = (LL(res) + LL(calc(1, 1, h, w)) * calc(h, w, H, W)) % MOD; h--, w++; } printf("%d\n", res); return 0; }
18.877551
70
0.473514
s-shirayama
72e6ac7c3343ed61d78d3d0aed0ebeb440d1e052
475
cpp
C++
object oriented programming/modifystring.cpp
ayaankhan98/C-Progamming_basics
0aba46dfe91986e30151bed54eaa7f66d0486c5e
[ "MIT" ]
null
null
null
object oriented programming/modifystring.cpp
ayaankhan98/C-Progamming_basics
0aba46dfe91986e30151bed54eaa7f66d0486c5e
[ "MIT" ]
null
null
null
object oriented programming/modifystring.cpp
ayaankhan98/C-Progamming_basics
0aba46dfe91986e30151bed54eaa7f66d0486c5e
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; int main() { string s1("Quick! Send for count Graystone"); string s2("Lord"); string s3("Don't "); s1.erase(0,7); s1.replace(9,5,s2); s1.replace(0,1,"S"); s1.insert(0,s3); s1.erase(s1.size()-1,1); s1.append(3,'!'); int x = s1.find(' '); while(x<s1.size()) { s1.replace(x,1,"/"); x = s1.find(' '); } cout<<"s1 : "<<s1<<endl; return 0; }
16.964286
49
0.501053
ayaankhan98
72e90d8b8b5de0630ade54589234bb59d05d640e
1,335
cc
C++
src/web_server/capabilities/contest_entry_token.cc
varqox/sim
b115a4e858dda1288917243e511751b835c28482
[ "MIT" ]
12
2017-11-05T21:02:58.000Z
2022-03-28T23:11:51.000Z
src/web_server/capabilities/contest_entry_token.cc
varqox/sim
b115a4e858dda1288917243e511751b835c28482
[ "MIT" ]
11
2017-01-05T18:11:41.000Z
2019-11-01T12:40:55.000Z
src/web_server/capabilities/contest_entry_token.cc
krzyk240/sim
b115a4e858dda1288917243e511751b835c28482
[ "MIT" ]
6
2016-12-25T11:22:34.000Z
2020-10-20T16:03:51.000Z
#include "src/web_server/capabilities/contest_entry_token.hh" #include "sim/contest_users/contest_user.hh" #include "sim/users/user.hh" #include "src/web_server/capabilities/contest.hh" #include "src/web_server/web_worker/context.hh" #include <cstdlib> using sim::contest_users::ContestUser; using sim::users::User; namespace web_server::capabilities { ContestEntryToken contest_entry_token_for( ContestEntryTokenKind token_kind, const decltype(web_worker::Context::session)& session, const Contest& caps_contest, std::optional<decltype(sim::contest_users::ContestUser::mode)> contest_user_mode) noexcept { bool is_admin = session and session->user_type == User::Type::ADMIN; bool is_contest_moderator = caps_contest.node.view and (is_admin or is_one_of(contest_user_mode, ContestUser::Mode::OWNER, ContestUser::Mode::MODERATOR)); switch (token_kind) { case ContestEntryTokenKind::NORMAL: case ContestEntryTokenKind::SHORT: return ContestEntryToken{ .view = is_contest_moderator, .create = is_contest_moderator, .regen = is_contest_moderator, .delete_ = is_contest_moderator, .use = true, .view_contest_name = true, }; } std::abort(); } } // namespace web_server::capabilities
34.230769
95
0.708614
varqox
6393debf02672a7ecfceb92fc78d0d84d766458d
3,388
hpp
C++
includes/nt/directories/dir_relocs.hpp
archercreat/linux-pe
902f744424b70979d401a9274afd579bceea104a
[ "BSD-3-Clause" ]
140
2020-01-16T19:04:33.000Z
2022-03-10T02:54:01.000Z
includes/nt/directories/dir_relocs.hpp
archercreat/linux-pe
902f744424b70979d401a9274afd579bceea104a
[ "BSD-3-Clause" ]
4
2021-02-28T12:02:46.000Z
2022-02-14T01:41:57.000Z
includes/nt/directories/dir_relocs.hpp
archercreat/linux-pe
902f744424b70979d401a9274afd579bceea104a
[ "BSD-3-Clause" ]
38
2020-01-16T01:48:08.000Z
2022-03-12T16:52:20.000Z
// Copyright (c) 2020 Can Boluk // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holder nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #pragma once #include "../../img_common.hpp" #include "../data_directories.hpp" #pragma pack(push, WIN_STRUCT_PACKING) namespace win { enum reloc_type_id : uint16_t { rel_based_absolute = 0, rel_based_high = 1, rel_based_low = 2, rel_based_high_low = 3, rel_based_high_adj = 4, rel_based_ia64_imm64 = 9, rel_based_dir64 = 10, }; struct reloc_entry_t { uint16_t offset : 12; reloc_type_id type : 4; }; static_assert( sizeof( reloc_entry_t ) == 2, "Enum bitfield is not supported." ); struct reloc_block_t { uint32_t base_rva; uint32_t size_block; reloc_entry_t entries[ VAR_LEN ]; inline reloc_block_t* next() { return ( reloc_block_t* ) ( ( char* ) this + this->size_block ); } inline const reloc_block_t* next() const { return const_cast< reloc_block_t* >( this )->next(); } inline size_t num_entries() const { return ( reloc_entry_t* ) next() - &entries[ 0 ]; } inline reloc_entry_t* begin() { return &entries[ 0 ]; } inline const reloc_entry_t* begin() const { return &entries[ 0 ]; } inline reloc_entry_t* end() { return ( reloc_entry_t* ) next(); } inline const reloc_entry_t* end() const { return ( const reloc_entry_t* ) next(); } }; struct reloc_directory_t { reloc_block_t first_block; }; template<bool x64> struct directory_type<directory_id::directory_entry_basereloc, x64, void> { using type = reloc_directory_t; }; }; #pragma pack(pop)
44.578947
133
0.64876
archercreat
63945dfd7cbd7ec71bf405d89c81af3192f1e088
9,273
cpp
C++
src/RTCCertificate.cpp
paullouisageneau/librtcdcpp
62695f7fc11b3401e2f8266abeaa556c05536373
[ "BSD-3-Clause" ]
5
2018-01-16T17:02:20.000Z
2020-05-14T11:33:47.000Z
src/RTCCertificate.cpp
paullouisageneau/librtcdcpp
62695f7fc11b3401e2f8266abeaa556c05536373
[ "BSD-3-Clause" ]
null
null
null
src/RTCCertificate.cpp
paullouisageneau/librtcdcpp
62695f7fc11b3401e2f8266abeaa556c05536373
[ "BSD-3-Clause" ]
2
2019-08-14T12:04:05.000Z
2020-03-23T07:11:04.000Z
/** * Copyright (c) 2017, Andrew Gault, Nick Chadwick and Guillaume Egles. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. */ /** * Simple wrapper around GnuTLS or OpenSSL Certs. */ #include "rtcdcpp/RTCCertificate.hpp" #include <cassert> #include <ctime> #ifdef USE_GNUTLS #include <gnutls/crypto.h> namespace rtcdcpp { using namespace std; static void check_gnutls(int ret, const std::string &message = "GnuTLS error") { if(ret != GNUTLS_E_SUCCESS) throw std::runtime_error(message + ": " + gnutls_strerror(ret)); } static gnutls_certificate_credentials_t *create_creds() { auto pcreds = new gnutls_certificate_credentials_t; check_gnutls(gnutls_certificate_allocate_credentials(pcreds)); return pcreds; } static void delete_creds(gnutls_certificate_credentials_t *pcreds) { gnutls_certificate_free_credentials(*pcreds); delete pcreds; } RTCCertificate RTCCertificate::GenerateCertificate(std::string common_name, int days) { gnutls_x509_crt_t crt; gnutls_x509_privkey_t privkey; check_gnutls(gnutls_x509_crt_init(&crt)); check_gnutls(gnutls_x509_privkey_init(&privkey)); try { const unsigned int bits = gnutls_sec_param_to_pk_bits(GNUTLS_PK_RSA, GNUTLS_SEC_PARAM_HIGH); check_gnutls(gnutls_x509_privkey_generate(privkey, GNUTLS_PK_RSA, bits, 0), "Unable to generate key pair"); gnutls_x509_crt_set_activation_time(crt, std::time(NULL) - 3600); gnutls_x509_crt_set_expiration_time(crt, std::time(NULL) + days*24*3600); gnutls_x509_crt_set_version(crt, 1); gnutls_x509_crt_set_key(crt, privkey); gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COMMON_NAME, 0, common_name.data(), common_name.size()); const size_t serialSize = 16; char serial[serialSize]; gnutls_rnd(GNUTLS_RND_NONCE, serial, serialSize); gnutls_x509_crt_set_serial(crt, serial, serialSize); check_gnutls(gnutls_x509_crt_sign2(crt, crt, privkey, GNUTLS_DIG_SHA256, 0), "Unable to auto-sign certificate"); return RTCCertificate(crt, privkey); } catch(...) { gnutls_x509_crt_deinit(crt); gnutls_x509_privkey_deinit(privkey); throw; } } std::string RTCCertificate::GenerateFingerprint(gnutls_x509_crt_t crt) { const size_t bufSize = 32; unsigned char buf[bufSize]; size_t len = bufSize; check_gnutls(gnutls_x509_crt_get_fingerprint(crt, GNUTLS_DIG_SHA256, buf, &len), "X509 fingerprint error"); int offset = 0; char fp[SHA256_FINGERPRINT_SIZE]; std::memset(fp, 0, SHA256_FINGERPRINT_SIZE); for (unsigned int i = 0; i < len; ++i) { snprintf(fp + offset, 4, "%02X:", buf[i]); offset += 3; } fp[offset - 1] = '\0'; return std::string(fp); } RTCCertificate::RTCCertificate(std::string crt_pem, std::string key_pem) : creds_(create_creds(), delete_creds) { gnutls_datum_t crt_datum; crt_datum.data = (unsigned char*)crt_pem.data(); crt_datum.size = crt_pem.size(); gnutls_datum_t key_datum; key_datum.data = (unsigned char*)key_pem.data(); key_datum.size = key_pem.size(); check_gnutls(gnutls_certificate_set_x509_key_mem(*creds_, &crt_datum, &key_datum, GNUTLS_X509_FMT_PEM), "Unable to import PEM"); gnutls_x509_crt_t *crt_list = NULL; unsigned int crt_list_size = 0; check_gnutls(gnutls_certificate_get_x509_crt(*creds_, 0, &crt_list, &crt_list_size)); assert(crt_list_size == 1); try { fingerprint_ = GenerateFingerprint(crt_list[0]); } catch(...) { gnutls_x509_crt_deinit(crt_list[0]); gnutls_free(crt_list); throw; } gnutls_x509_crt_deinit(crt_list[0]); gnutls_free(crt_list); } RTCCertificate::RTCCertificate(gnutls_x509_crt_t crt, gnutls_x509_privkey_t privkey) : creds_(create_creds(), delete_creds), fingerprint_(GenerateFingerprint(crt)) { check_gnutls(gnutls_certificate_set_x509_key(*creds_, &crt, 1, privkey), "Unable to set certificate and key pair in credentials"); gnutls_x509_crt_deinit(crt); gnutls_x509_privkey_deinit(privkey); } } #else #include <openssl/pem.h> namespace rtcdcpp { using namespace std; static std::shared_ptr<X509> GenerateX509(std::shared_ptr<EVP_PKEY> evp_pkey, const std::string &common_name, int days) { std::shared_ptr<X509> null_result; std::shared_ptr<X509> x509(X509_new(), X509_free); std::shared_ptr<BIGNUM> serial_number(BN_new(), BN_free); std::shared_ptr<X509_NAME> name(X509_NAME_new(), X509_NAME_free); if (!x509 || !serial_number || !name) { return null_result; } if (!X509_set_pubkey(x509.get(), evp_pkey.get())) { return null_result; } if (!BN_pseudo_rand(serial_number.get(), 64, 0, 0)) { return null_result; } ASN1_INTEGER *asn1_serial_number = X509_get_serialNumber(x509.get()); if (!asn1_serial_number) { return null_result; } if (!BN_to_ASN1_INTEGER(serial_number.get(), asn1_serial_number)) { return null_result; } if (!X509_set_version(x509.get(), 0L)) { return null_result; } if (!X509_NAME_add_entry_by_NID(name.get(), NID_commonName, MBSTRING_UTF8, (unsigned char *)common_name.c_str(), -1, -1, 0)) { return null_result; } if (!X509_set_subject_name(x509.get(), name.get()) || !X509_set_issuer_name(x509.get(), name.get())) { return null_result; } if (!X509_gmtime_adj(X509_get_notBefore(x509.get()), 0) || !X509_gmtime_adj(X509_get_notAfter(x509.get()), days * 24 * 3600)) { return null_result; } if (!X509_sign(x509.get(), evp_pkey.get(), EVP_sha1())) { return null_result; } return x509; } RTCCertificate RTCCertificate::GenerateCertificate(std::string common_name, int days) { std::shared_ptr<EVP_PKEY> pkey(EVP_PKEY_new(), EVP_PKEY_free); RSA *rsa = RSA_new(); std::shared_ptr<BIGNUM> exponent(BN_new(), BN_free); if (!pkey || !rsa || !exponent) { throw std::runtime_error("GenerateCertificate: !pkey || !rsa || !exponent"); } if (!BN_set_word(exponent.get(), 0x10001) || !RSA_generate_key_ex(rsa, 2048, exponent.get(), NULL) || !EVP_PKEY_assign_RSA(pkey.get(), rsa)) { throw std::runtime_error("GenerateCertificate: Error generating key"); } auto cert = GenerateX509(pkey, common_name, days); if (!cert) { throw std::runtime_error("GenerateCertificate: Error in GenerateX509"); } return RTCCertificate(cert, pkey); } std::string RTCCertificate::GenerateFingerprint(X509 *x509) { unsigned int len; unsigned char buf[EVP_MAX_MD_SIZE] = {0}; if (!X509_digest(x509, EVP_sha256(), buf, &len)) { throw std::runtime_error("GenerateFingerprint(): X509_digest error"); } if (len != 32) { throw std::runtime_error("GenerateFingerprint(): unexpected fingerprint size"); } int offset = 0; char fp[SHA256_FINGERPRINT_SIZE]; memset(fp, 0, SHA256_FINGERPRINT_SIZE); for (unsigned int i = 0; i < len; ++i) { snprintf(fp + offset, 4, "%02X:", buf[i]); offset += 3; } fp[offset - 1] = '\0'; return std::string(fp); } RTCCertificate::RTCCertificate(std::string crt_pem, std::string key_pem) { /* x509 */ BIO *bio = BIO_new(BIO_s_mem()); BIO_write(bio, crt_pem.c_str(), (int)crt_pem.length()); x509_ = std::shared_ptr<X509>(PEM_read_bio_X509(bio, nullptr, 0, 0), X509_free); BIO_free(bio); if (!x509_) { throw std::invalid_argument("Could not read certificate PEM"); } /* evp_pkey */ bio = BIO_new(BIO_s_mem()); BIO_write(bio, key_pem.c_str(), (int)key_pem.length()); evp_pkey_ = std::shared_ptr<EVP_PKEY>(PEM_read_bio_PrivateKey(bio, nullptr, 0, 0), EVP_PKEY_free); BIO_free(bio); if (!evp_pkey_) { throw std::invalid_argument("Could not read key PEM"); } fingerprint_ = GenerateFingerprint(x509_.get()); } RTCCertificate::RTCCertificate(std::shared_ptr<X509> x509, std::shared_ptr<EVP_PKEY> evp_pkey) : x509_(x509), evp_pkey_(evp_pkey), fingerprint_(GenerateFingerprint(x509_.get())) {} } #endif
33.476534
144
0.725116
paullouisageneau
639854d7b48cc15d2b9d44282e84ec6ac63bbf07
3,923
cpp
C++
project2D/Asteroid.cpp
CEbbinghaus/Asteroids
8bcac70c25602ef3fcf5edd699a0b630b2f8d40a
[ "MIT" ]
null
null
null
project2D/Asteroid.cpp
CEbbinghaus/Asteroids
8bcac70c25602ef3fcf5edd699a0b630b2f8d40a
[ "MIT" ]
null
null
null
project2D/Asteroid.cpp
CEbbinghaus/Asteroids
8bcac70c25602ef3fcf5edd699a0b630b2f8d40a
[ "MIT" ]
null
null
null
#include "Asteroid.h" #include "Asteroids.h" void Asteroid::update(float deltaTime){ //transform.Position += velocity * (speed * deltaTime); if (transform.Position.x < 0)transform.Position.x = Master::application->GetWindowWidth(); if (transform.Position.x > Master::application->GetWindowWidth())transform.Position.x = 0; if (transform.Position.y < 0)transform.Position.y = Master::application->GetWindowHeight(); if (transform.Position.y > Master::application->GetWindowHeight())transform.Position.y = 0; /*if (transform.Position.x + radius < 0)transform.Position.x = Master::application->GetWindowWidth() + radius; if (transform.Position.x - radius > Master::application->GetWindowWidth())transform.Position.x = -radius; if (transform.Position.y + radius < 0)transform.Position.y = Master::application->GetWindowHeight() + radius; if (transform.Position.y - radius > Master::application->GetWindowHeight())transform.Position.y = -radius; */ transform.Rotation += rotationVelocity * deltaTime; } void Asteroid::draw(aie::Renderer2D& renderer){ if(!points.length)return; float radOffset = (M_PI * 2) / (float)points.length; float lastRadius = points[points.length - 1]; for(auto [PRadius, Index] : points){ Vector3 prev = Vector3(radius * *PRadius * sinf(Index * radOffset), radius * *PRadius * cosf(Index * radOffset), 1.0f); --Index; Vector3 next = Vector3(radius * lastRadius * sinf(Index * radOffset), radius * lastRadius * cosf(Index * radOffset), 1.0f); prev = transform.GetGlobalTransform() * prev; next = transform.GetGlobalTransform() * next; renderer.DrawLine(prev.x, prev.y, next.x, next.y); //float xPos = transform.globalTransform.Pos.x + radius * *PRadius * sinf(Index * radOffset); //float yPos = transform.globalTransform.Pos.y + radius * *PRadius * cosf(Index * radOffset); //float PxPos = transform.globalTransform.Pos.x + radius * lastRadius * sinf(--Index * radOffset); //float PyPos = transform.globalTransform.Pos.y + radius * lastRadius * cosf(Index * radOffset); //renderer.DrawLine(PxPos, PyPos, xPos, yPos); lastRadius = *PRadius; } } void Asteroid::OnCollision(GameObject& other){ if (other.id == (char)Object::bullet) { int amount = 0; switch (size){ case 3: amount = Random.get<int>(2, 5); break; case 2: amount = Random.get<int>(0, 2); break; } float RadianOffset = Random.get<float>(0, M_PI * 2); float RadianAmount = (M_PI * 2) / amount; for (int i = 0; i < amount; ++i) { float finalRotation = RadianOffset + RadianAmount * i; Vector2 direction = Vector2(sinf(finalRotation), cosf(finalRotation)); Vector2 currentPosition = *(Vector2*)(&(transform.GetGlobalTransform().Pos)); Asteroid* a = new Asteroid(size - 1, direction, currentPosition + direction * Random.get<float>(radius / 2, radius)); Asteroids::instance->activeAsteroids.push(a); } Asteroids::instance->score += (100 * size); Asteroids::instance->activeAsteroids.remove(this); Master::DeleteObject(this); } } Asteroid::Asteroid(int a_size, Vector2 dir, Vector2 pos) : GameObject({new CircleCollider(*this, Vector2(1.0f, 1.0f), 10), new Rigidbody(*this, dir)}){ rotationVelocity = Random.get<float>(0.0f, 0.3f); id = (char)Object::asteroid; CircleCollider* c = GetComponent<CircleCollider>(); if(c) c->layerMask = Layer::default | Layer::one; size = a_size; speed = ((4 - size) * Asteroids::instance->level + 1) * 20; GetComponent<Rigidbody>()->velocity = speed * dir; float min = (float)size * 40.0f; GetComponent<CircleCollider>()->radius = radius = Random.get<float>(min, min * 1.3); // velocity = dir; transform.Position = pos; int minP = 3 * size; int maxP = 4 * size; int amount = Random.get<int>(minP, maxP); for(int i = 0; i < amount; i++){ points.push(Random.get<float>(0.3f, 1.0f)); } } Asteroid::~Asteroid(){ //Asteroids::instance->activeAsteroids.remove(this); }
37.361905
151
0.691053
CEbbinghaus
639f6b0646b7ec1e43748ed81bf38ff250644cf8
30,697
cpp
C++
src/mascgl-3/draw_basics.cpp
jmlien/lightbender
510f1971614930e2d75911d23a97b1ba77426074
[ "MIT" ]
null
null
null
src/mascgl-3/draw_basics.cpp
jmlien/lightbender
510f1971614930e2d75911d23a97b1ba77426074
[ "MIT" ]
null
null
null
src/mascgl-3/draw_basics.cpp
jmlien/lightbender
510f1971614930e2d75911d23a97b1ba77426074
[ "MIT" ]
1
2021-04-18T20:58:52.000Z
2021-04-18T20:58:52.000Z
#include "draw_basics.h" #define DEBUG 0 Camera camera; Shader shader; //----------------------------------------------------------------------------- // // GL/GUI initialization and setup // //----------------------------------------------------------------------------- GLFWwindow* initGLcontext(mascgl_workspace& workspace, string title, GLFWerrorfun errfun, GLFWkeyfun keyfun, GLFWmousebuttonfun mousefun, GLFWcursorposfun cursorfun) { glfwSetErrorCallback(errfun);// error_callback); // Initialise GLFW if (!glfwInit()) { cerr << "! Error: Failed to initialize GLFW" << endl; return NULL; } glfwWindowHint(GLFW_SAMPLES, 4); #ifdef _WIN32 glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #else glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif // // Open a window and create its OpenGL context // title += ": "; title += workspace.env_filename; GLFWwindow* window = glfwCreateWindow(workspace.image_w, workspace.image_h, title.c_str(), NULL, NULL); if (window == NULL){ cerr << "! Error: Failed to open a GLFW window" << endl; glfwTerminate(); return NULL; } glfwMakeContextCurrent(window); // // Initialize GLEW // glewExperimental = true; // Needed for core profile #if ( (defined(__MACH__)) && (defined(__APPLE__)) ) //nothing glewInit(); #else if (glewInit() != GLEW_OK) { cerr << "! Error: Failed to initialize GLEW" << endl; return NULL; } #endif // // set call back functions... // glfwSetKeyCallback(window, keyfun); glfwSetMouseButtonCallback(window, mousefun); glfwSetCursorPosCallback(window, cursorfun); //set camera position camera.setCameraPosX((float)workspace.COM[0]); camera.setCameraPosY((float)workspace.COM[1]); camera.setCameraPosZ(workspace.R*2.1f); camera.init(window); //tell workspace to create basic textures... workspace.createDefaultTextures(); //load textures from files for (list<object3D*>::iterator i = workspace.models.begin(); i != workspace.models.end(); i++) { object3D * obj = *i; //load textures if (!obj->color_texture_filename.empty()) { obj->color_texture = new Texture(); if (obj->color_texture->loadTexture(obj->color_texture_filename.c_str()) == false) { cerr << "! Error: Failed to load texture:" << obj->color_texture_filename << endl; return nullptr; } } if (!obj->normalmap_texture_filename.empty()) { obj->normalmap_texture = new Texture(); if (obj->normalmap_texture->loadTexture(obj->normalmap_texture_filename.c_str()) == false) { cerr << "! Error: Failed to load texture:" << obj->normalmap_texture_filename << endl; return nullptr; } } }//end for i return window; } void setupLight(mascgl_workspace& workspace, Shader& shader) { //Let's have light! for (list<light*>::iterator i = workspace.lights.begin(); i != workspace.lights.end(); i++) { light* li = *i; float pos[] = { (float)li->pos[0], (float)li->pos[1], (float)li->pos[2], 1.0f }; float diffuse[] = { (float)li->mat_color[0], (float)li->mat_color[1], (float)li->mat_color[2], 1.0f }; float specular[] = { (float)li->mat_specular[0], (float)li->mat_specular[1], (float)li->mat_specular[2], 1.0f }; float ambient[] = { (float)li->ambient[0], (float)li->ambient[1], (float)li->ambient[2], 1.0f }; glUniform3fv(shader.value("light.pos"), 1, pos); glUniform4fv(shader.value("light.diffuse"), 1, diffuse); glUniform4fv(shader.value("light.specular"), 1, specular); glUniform4fv(shader.value("light.ambient"), 1, ambient); glUniform1f(shader.value("light.att_const"), (float)li->att_const); glUniform1f(shader.value("light.att_linear"), (float)li->att_linear); //only the first light will be used... break; } //-------------------------------------------------- } void setupGLflags() { // transparent glShadeModel(GL_SMOOTH); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_LINE_SMOOTH); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); //glEnable(GL_NORMALIZE); glClearColor(1.0, 1.0, 1.0, 1.0); glEnable(GL_CULL_FACE); } //----------------------------------------------------------------------------- // // functions for rendering depth map // //----------------------------------------------------------------------------- //create view/projection matrix from the given light void createVPfromLight(mascgl_workspace& workspace, light * mylight, glm::mat4& depthProjectionMatrix, glm::mat4& depthViewMatrix) { //setup model, view, projection matrix for light space const Point3d& lp = mylight->pos; //light position const Point3d& lookat = mylight->lookat; //look at position float dist = Vector3d(lp - lookat).norm(); float dim = workspace.R; //mathtool::Point3d lp = mylight->pos; //light position //const mathtool::Point3d& lookat = mylight->lookat; //look at position //Vector3d viewdir = (mylight->pos - lookat).normalize()*workspace.R; //lp = lookat + viewdir; //float dist = viewdir.norm(); //float dim = workspace.R; if (mylight->type == light::SPOT_LIGHT) depthProjectionMatrix = glm::perspective(45.0, 1.0, mylight->znear, mylight->zfar); if (mylight->type == light::POINT_LIGHT) depthProjectionMatrix = glm::perspective(45.0, 1.0, mylight->znear, mylight->zfar); else depthProjectionMatrix = glm::ortho<float>(-dim, dim, -dim, dim, 0, dist + dim * 2); depthViewMatrix = glm::lookAt(toglm(lp), toglm(lookat), glm::vec3(0, 1, 0)); } //create view/projection matrix from the given light void createVPfromLight(mascgl_workspace& workspace, light * mylight, glm::mat4& depthVP) { glm::mat4 depthProjectionMatrix, depthViewMatrix; createVPfromLight(workspace, mylight, depthProjectionMatrix, depthViewMatrix); depthVP = depthProjectionMatrix * depthViewMatrix; } GLuint renderDepth(mascgl_workspace& workspace, glm::mat4& depthVP, vector<M_buffers>& buffers) { // --------------------------------------------- // Render to Texture // --------------------------------------------- // The framebuffer, which regroups 0, 1, or more textures, and 0 or 1 depth buffer. GLuint FramebufferName = 0; glGenFramebuffers(1, &FramebufferName); glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName); // Depth texture. Slower than a depth buffer, but you can sample it later in your shader //this is for depth GLuint depthTexture = 0; glGenTextures(1, &depthTexture); glBindTexture(GL_TEXTURE_2D, depthTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, workspace.image_w, workspace.image_h, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE); //for depth { glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthTexture, 0); // No color output in the bound framebuffer, only depth. glDrawBuffer(GL_NONE); glReadBuffer(GL_NONE); } // Always check that our framebuffer is ok if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { cerr << "! Error: glCheckFramebufferStatus failed" << endl; exit(-1); } //------------------------------------------------ //depth shader Shader depth_shader; depth_shader.init("shaders/renderDepth.vert", "shaders/renderDepth.frag"); depth_shader.addvarible("depthMVP"); //------------------------------------------------ //------------------------------------------------------------------------------------- // Render to our framebuffer //------------------------------------------------------------------------------------- glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName); glViewport(0, 0, workspace.image_w, workspace.image_h); // Render on the whole framebuffer, complete from the lower left corner to the upper right // We don't use bias in the shader, but instead we draw back faces, // which are already separated from the front faces by a small distance // (if your geometry is made this way) glEnable(GL_CULL_FACE); glCullFace(GL_BACK); // Cull back-facing triangles -> draw only front-facing triangles //------------------------------------------------------------------------------------- // // // render depth... // // // Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); depth_shader.bind(); // //draw meshes // for (vector<M_buffers>::iterator i = buffers.begin(); i != buffers.end(); i++) { if (i->m == NULL) continue; //bind texture here... model & M = *(i->m); //compute depthMVP from depthVP glm::mat4 depthMVP = depthVP*toglm(M.getCurrentTransform()); // Send our transformation to the currently bound shader, // in the "MVP" uniform glUniformMatrix4fv(depth_shader.value("depthMVP"), 1, GL_FALSE, &depthMVP[0][0]); // // 1st attribute buffer : vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, i->vertexbuffer); glVertexAttribPointer( 0, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // Index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, i->trielementbuffer); // Draw the triangles ! glDrawElements( GL_TRIANGLES, // mode M.t_size * 3, // count GL_UNSIGNED_INT, // type (void*)0 // element array buffer offset ); glDisableVertexAttribArray(0); } //TODO: we should draw spheres here as well... // depth_shader.unbind(); //SAVED IMAGE TO FILE //this is for depth #if DEBUG { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, depthTexture); float * img = new float[workspace.image_w*workspace.image_h]; glGetTexImage(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, GL_FLOAT, img); char id[1024]; sprintf(id, "%0d", (int)time(NULL)); string filename = "depth_"; filename = filename + id + ".ppm"; save2file(filename.c_str(), workspace.image_w, workspace.image_h, img); delete[] img; } #endif //DEBUG //reset back... glDeleteFramebuffers(1, &FramebufferName); glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, workspace.image_w, workspace.image_h); return depthTexture; } GLuint renderDepth(mascgl_workspace& workspace, glm::mat4& depthVP, M_buffers& buffer) { if (buffer.m == NULL) return -1; // --------------------------------------------- // Render to Texture // --------------------------------------------- // The framebuffer, which regroups 0, 1, or more textures, and 0 or 1 depth buffer. GLuint FramebufferName = 0; glGenFramebuffers(1, &FramebufferName); glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName); // Depth texture. Slower than a depth buffer, but you can sample it later in your shader //this is for depth GLuint depthTexture = 0; glGenTextures(1, &depthTexture); glBindTexture(GL_TEXTURE_2D, depthTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, workspace.image_w, workspace.image_h, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE); //for depth { glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthTexture, 0); // No color output in the bound framebuffer, only depth. glDrawBuffer(GL_NONE); glReadBuffer(GL_NONE); } // Always check that our framebuffer is ok if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { cerr << "! Error: glCheckFramebufferStatus failed" << endl; exit(-1); } //------------------------------------------------ //depth shader Shader depth_shader; depth_shader.init("shaders/renderDepth.vert", "shaders/renderDepth.frag"); depth_shader.addvarible("depthMVP"); //------------------------------------------------ //------------------------------------------------------------------------------------- // Render to our framebuffer //------------------------------------------------------------------------------------- glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName); glViewport(0, 0, workspace.image_w, workspace.image_h); // Render on the whole framebuffer, complete from the lower left corner to the upper right // We don't use bias in the shader, but instead we draw back faces, // which are already separated from the front faces by a small distance // (if your geometry is made this way) glEnable(GL_CULL_FACE); glCullFace(GL_BACK); // Cull back-facing triangles -> draw only front-facing triangles //------------------------------------------------------------------------------------- // // // render depth... // // // Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); depth_shader.bind(); // //draw meshes // //bind texture here... model & M = *(buffer.m); //compute depthMVP from depthVP glm::mat4 depthMVP = depthVP*toglm(M.getCurrentTransform()); // Send our transformation to the currently bound shader, // in the "MVP" uniform glUniformMatrix4fv(depth_shader.value("depthMVP"), 1, GL_FALSE, &depthMVP[0][0]); // // 1st attribute buffer : vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, buffer.vertexbuffer); glVertexAttribPointer( 0, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // Index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer.trielementbuffer); // Draw the triangles ! glDrawElements( GL_TRIANGLES, // mode M.t_size * 3, // count GL_UNSIGNED_INT, // type (void*)0 // element array buffer offset ); glDisableVertexAttribArray(0); //TODO: we should draw spheres here as well... // depth_shader.unbind(); //SAVED IMAGE TO FILE //this is for depth #if DEBUG { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, depthTexture); float * img = new float[workspace.image_w*workspace.image_h]; glGetTexImage(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, GL_FLOAT, img); char id[1024]; sprintf(id, "%0d", (int)time(NULL)); string filename = "depth_"; filename = filename + id + ".ppm"; save2file(filename.c_str(), workspace.image_w, workspace.image_h, img); filename = filename + id + ".dds"; int save_result = SOIL_save_image(filename.c_str(), SOIL_SAVE_TYPE_DDS, workspace.image_w, workspace.image_h, 3, img); delete[] img; } #endif //reset back... glDeleteFramebuffers(1, &FramebufferName); glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, workspace.image_w, workspace.image_h); return depthTexture; } GLuint renderShadow(mascgl_workspace& workspace, glm::mat4& depthVP, GLuint depthTexture, vector<M_buffers>& buffers) { // //prepare framebuffer for shadow rendering... // --------------------------------------------- // Render to Texture // --------------------------------------------- // The framebuffer, which regroups 0, 1, or more textures, and 0 or 1 depth buffer. // GLuint FramebufferName = 0; glGenFramebuffers(1, &FramebufferName); glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName); // shadow texture. // this is for color GLuint colorTexture; glGenTextures(1, &colorTexture); glBindTexture(GL_TEXTURE_2D, colorTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, workspace.image_w, workspace.image_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); //for color glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, colorTexture, 0); // Set the list of draw buffers. GLenum DrawBuffers[1] = { GL_COLOR_ATTACHMENT0 }; glDrawBuffers(1, DrawBuffers); // "1" is the size of DrawBuffers // The depth buffer (this block of code is necessary...) GLuint depthrenderbuffer; glGenRenderbuffers(1, &depthrenderbuffer); glBindRenderbuffer(GL_RENDERBUFFER, depthrenderbuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, workspace.image_w, workspace.image_h); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthrenderbuffer); // Always check that our framebuffer is ok if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { cerr << "! Error: glCheckFramebufferStatus failed" << endl; exit(-1); } //bind this frame buffer glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName); glViewport(0, 0, workspace.image_w, workspace.image_h); //------------------------------------------------ //load shadow only shader Shader shadow_shader; shadow_shader.init("shaders/pointlight_shadow_only.vert", "shaders/pointlight_shadow_only.frag"); //get uniform variables shadow_shader.addvarible("MVP"); shadow_shader.addvarible("V"); shadow_shader.addvarible("M"); shadow_shader.addvarible("MV3x3"); shadow_shader.addvarible("DepthBiasMVP"); shadow_shader.addvarible("shadowMap"); //------------------------------------------------ //draw shadow //----------------------------------------------------------------------- // // draw to FramebufferName... // setup model, view, projection matrix // //----------------------------------------------------------------------- // Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shadow_shader.bind(); //let's look at the scene from the light (but near the bbox) light * mylight = workspace.lights.front(); mathtool::Point3d lp = mylight->pos; //light position const mathtool::Point3d& lookat = mylight->lookat; //look at position Vector3d viewdir = (mylight->pos - lookat).normalize()*workspace.R; lp = lookat + viewdir; float dist = viewdir.norm(); float dim = workspace.R; glm::mat4 ProjectionMatrix = glm::ortho<float>(-dim, dim, -dim, dim, 0, dist + workspace.R * 2); glm::mat4 ViewMatrix = glm::lookAt(toglm(lp), toglm(lookat), glm::vec3(0, 1, 0)); //glm::mat4 ProjectionMatrix, ViewMatrix; //createVPfromLight(mylight, ProjectionMatrix, ViewMatrix); //bind shadow texture... glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, depthTexture); glUniform1i(shadow_shader.value("shadowMap"), 0); //here we draw walls only bool wallonly = true; bool texture = false; drawMesh(workspace, shadow_shader, ProjectionMatrix, ViewMatrix, depthVP, buffers, wallonly, texture); //done.... shadow_shader.unbind(); //unbind this frame buffer glDeleteFramebuffers(1, &FramebufferName); glDeleteRenderbuffers(1, &depthrenderbuffer); glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, workspace.image_w, workspace.image_h); return colorTexture; } //----------------------------------------------------------------------------- // // Load and render individual model and shpere // //----------------------------------------------------------------------------- //load the given model M into GL buffers M_buffers loadModelBuffers(model& M) { M_buffers buffers; buffers.m = &M; //get positions of each vertex { std::vector<glm::vec3> indexed_vertices; indexed_vertices.reserve(M.v_size); for (unsigned int i = 0; i < M.v_size; i++) { vertex& v = M.vertices[i]; glm::vec3 pos = toglm(v.p); indexed_vertices.push_back(pos); } glGenBuffers(1, &buffers.vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, buffers.vertexbuffer); glBufferData(GL_ARRAY_BUFFER, indexed_vertices.size() * sizeof(glm::vec3), &indexed_vertices[0], GL_STATIC_DRAW); } //get normals of each vertex { std::vector<glm::vec3> indexed_normals; indexed_normals.reserve(M.v_size); for (unsigned int i = 0; i < M.v_size; i++) { vertex& v = M.vertices[i]; glm::vec3 normal = toglm(v.n); indexed_normals.push_back(normal); } glGenBuffers(1, &buffers.normalbuffer); glBindBuffer(GL_ARRAY_BUFFER, buffers.normalbuffer); glBufferData(GL_ARRAY_BUFFER, indexed_normals.size() * sizeof(glm::vec3), &indexed_normals[0], GL_STATIC_DRAW); } //get tangent of each vertex { std::vector<glm::vec3> tangents; tangents.reserve(M.v_size); for (unsigned int i = 0; i < M.v_size; i++) { vertex& v = M.vertices[i]; glm::vec3 tangent = toglm(v.t); tangents.push_back(tangent); } glGenBuffers(1, &buffers.tangentbuffer); glBindBuffer(GL_ARRAY_BUFFER, buffers.tangentbuffer); glBufferData(GL_ARRAY_BUFFER, tangents.size() * sizeof(glm::vec3), &tangents[0], GL_STATIC_DRAW); } //get bitangent of each vertex { std::vector<glm::vec3> bitangents; bitangents.reserve(M.v_size); for (unsigned int i = 0; i < M.v_size; i++) { vertex& v = M.vertices[i]; glm::vec3 bitangent = toglm(v.b); bitangents.push_back(bitangent); } glGenBuffers(1, &buffers.bitangentbuffer); glBindBuffer(GL_ARRAY_BUFFER, buffers.bitangentbuffer); glBufferData(GL_ARRAY_BUFFER, bitangents.size() * sizeof(glm::vec3), &bitangents[0], GL_STATIC_DRAW); } //get UV of each vertex { std::vector<glm::vec2> UVs; for (unsigned int i = 0; i < M.v_size; i++) { vertex& v = M.vertices[i]; glm::vec2 uv(v.uv[0], v.uv[1]); UVs.push_back(uv); } glGenBuffers(1, &buffers.uvbuffer); glBindBuffer(GL_ARRAY_BUFFER, buffers.uvbuffer); glBufferData(GL_ARRAY_BUFFER, UVs.size() * sizeof(glm::vec2), &UVs[0], GL_STATIC_DRAW); } // // find indices for each triangle vertex // { //std::vector<uint> indices; std::vector<unsigned int> indices; int vindex = 0; for (unsigned int i = 0; i < M.t_size; i++) { triangle & tri = M.tris[i]; for (short d = 0; d < 3; d++) { indices.push_back((unsigned int)tri.v[d]); } }//end for i // Generate a buffer for the indices as well glGenBuffers(1, &buffers.trielementbuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers.trielementbuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW); } return buffers; } void drawMesh(mascgl_workspace& workspace, M_buffers& buffer, Shader& shader, glm::mat4& projection, glm::mat4& view, glm::mat4& depthVP, bool wall_only, bool show_texture) { if (buffer.m == NULL) return; unsigned int texture_location = shader.value("color_texture"); if (texture_location != UINT_MAX) { glActiveTexture(GL_TEXTURE1); glUniform1i(texture_location, 1); } //draw meshes //bind texture here... model & M = *(buffer.m); //setup transforms glm::mat4 ModelMatrix = toglm(M.getCurrentTransform()); glm::mat4 ModelViewMatrix = view * ModelMatrix; glm::mat3 ModelView3x3Matrix = glm::mat3(ModelViewMatrix); glm::mat4 MVP = projection * view * ModelMatrix; glm::mat4 depthMVP = depthVP * ModelMatrix; //matrix to map points into light space // Send our transformation to the currently bound shader, // in the "MVP" uniform glUniformMatrix4fv(shader.value("MVP"), 1, GL_FALSE, &MVP[0][0]); glUniformMatrix4fv(shader.value("M"), 1, GL_FALSE, &ModelMatrix[0][0]); glUniformMatrix4fv(shader.value("V"), 1, GL_FALSE, &view[0][0]); glUniformMatrix3fv(shader.value("MV3x3"), 1, GL_FALSE, &ModelView3x3Matrix[0][0]); glUniformMatrix4fv(shader.value("DepthBiasMVP"), 1, GL_FALSE, &depthMVP[0][0]); // if (show_texture && texture_location != UINT_MAX) { if (M.color_texture != NULL) { //M.color_texture->bind(shader.id(), "color_texture", GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, M.color_texture->getTextureID()); } else { //workspace.texture_white.bind(shader.id(), "color_texture", GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, workspace.texture_white.getTextureID()); } } //check if matrial is defined.... if (shader.value("material.diffuse") != UINT_MAX) { float diffuse[] = { (float)M.mat_color[0], (float)M.mat_color[1], (float)M.mat_color[2], 1.0f }; float specular[] = { (float)M.mat_specular[0], (float)M.mat_specular[1], (float)M.mat_specular[2], 1.0f }; float emission[] = { (float)M.mat_emission[0], (float)M.mat_emission[1], (float)M.mat_emission[2], 1.0f }; glUniform4fv(shader.value("material.diffuse"), 1, diffuse); glUniform4fv(shader.value("material.specular"), 1, specular); glUniform4fv(shader.value("material.emission"), 1, emission); glUniform1f(shader.value("material.shininess"), M.mat_shininess); } shader.validateProgram(); // // 1st attribute buffer : vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, buffer.vertexbuffer); glVertexAttribPointer( 0, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // 2nd attribute buffer : UVs glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, buffer.uvbuffer); glVertexAttribPointer( 1, // attribute 2, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // 3rd attribute buffer : normals glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, buffer.normalbuffer); glVertexAttribPointer( 2, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // 4th attribute buffer : tangents glEnableVertexAttribArray(3); glBindBuffer(GL_ARRAY_BUFFER, buffer.tangentbuffer); glVertexAttribPointer( 3, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // 5th attribute buffer : bitangents glEnableVertexAttribArray(4); glBindBuffer(GL_ARRAY_BUFFER, buffer.bitangentbuffer); glVertexAttribPointer( 4, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // Index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer.trielementbuffer); // Draw the triangles ! glDrawElements( GL_TRIANGLES, // mode M.t_size * 3, // count GL_UNSIGNED_INT, // type (void*)0 // element array buffer offset ); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); glDisableVertexAttribArray(3); glDisableVertexAttribArray(4); } void drawMesh(mascgl_workspace& workspace, Shader& shader, glm::mat4& projection, glm::mat4& view, glm::mat4& depthVP, vector<M_buffers>& buffers, bool wall_only, bool show_texture) { unsigned int texture_location = shader.value("color_texture"); if (texture_location != UINT_MAX) { glActiveTexture(GL_TEXTURE1); glUniform1i(texture_location, 1); } //draw meshes for (vector<M_buffers>::iterator i = buffers.begin(); i != buffers.end(); i++) { if (wall_only && workspace.is_wall(i->m) == false) continue; //not a wall and only wall should be rendered... //if (shadow_caster_only && i->m->cast_shadow == false && workspace.is_wall(i->m) == false) continue;//this model does not cast shadow, so ignore drawMesh(workspace, *i, shader, projection, view, depthVP, wall_only, show_texture); } } //----------------------------------------------------------------------------- // // Save texture or image to file // //----------------------------------------------------------------------------- //save rendered image to file void save2file(const std::string& filename, int w, int h, unsigned char * img) { FILE *f = fopen(filename.c_str(), "w"); // Write image to PPM file. fprintf(f, "P3\n%d %d\n%d\n", w, h, 255); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { int id = ((h - i - 1)*w + j) * 3; fprintf(f, "%d %d %d ", (int)img[id], (int)img[id + 1], (int)img[id + 2]); } } fclose(f); } //save depth image to file void save2file(const std::string& filename, int w, int h, float * img) { FILE *f = fopen(filename.c_str(), "w"); // Write image to PPM file. fprintf(f, "P3\n%d %d\n%d\n", w, h, 255); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { int id = ((h - i - 1)*w + j); int depth = toInt(img[id]); fprintf(f, "%d %d %d ", depth, depth, depth); } } fclose(f); }
32.177149
182
0.624621
jmlien
63a33cdfce5815ae624ad6c75e3e6fcfd6355de9
5,549
cc
C++
src/cxx/testbed/testbed.cc
emily33901/Argon
3c06ee562027540702114d0efacb6b12c767a921
[ "MIT" ]
19
2018-11-22T23:02:22.000Z
2022-02-13T22:26:19.000Z
src/cxx/testbed/testbed.cc
josh33901/Argon
3c06ee562027540702114d0efacb6b12c767a921
[ "MIT" ]
2
2019-03-20T11:42:27.000Z
2020-07-16T12:43:04.000Z
src/cxx/testbed/testbed.cc
josh33901/Argon
3c06ee562027540702114d0efacb6b12c767a921
[ "MIT" ]
1
2019-09-09T10:48:12.000Z
2019-09-09T10:48:12.000Z
#include "testbed.hh" #ifdef _MSC_VER const char *steam_path = "steamclient.dll"; #else const char *steam_path = "./libsteamclient.so"; #endif #define check_null(var) \ if (!var) { \ printf(#var " is null!\n"); \ return false; \ } bool load_steam_dll() { #ifdef _MSC_VER auto handle = LoadLibrary(steam_path); if (handle == nullptr) { printf("Unable to load steam from steam_path\n"); return false; } steam::create_interface = (CreateInterfaceFn)GetProcAddress(handle, "CreateInterface"); steam::get_next_callback = (GetCallbackFn)GetProcAddress(handle, "Steam_BGetCallback"); steam::free_last_callback = (FreeCallbackFn)GetProcAddress(handle, "Steam_FreeLastCallback"); #else auto handle = dlopen(steam_path, RTLD_NOW); if (handle == nullptr) { char *error = dlerror(); printf("Unable to load steam from steam_path\n"); printf("Error: %s\n", error); return false; } steam::create_interface = (CreateInterfaceFn)dlsym(handle, "CreateInterface"); steam::get_next_callback = (GetCallbackFn)dlsym(handle, "Steam_BGetCallback"); steam::free_last_callback = (FreeCallbackFn)dlsym(handle, "Steam_FreeLastCallback"); #endif check_null(steam::create_interface); check_null(steam::get_next_callback); check_null(steam::free_last_callback); return true; } bool get_steam_interfaces() { steam::engine = (IClientEngine005 *)steam::create_interface("CLIENTENGINE_INTERFACE_VERSION005"); steam::client = (ISteamClient017 *)steam::create_interface("SteamClient017"); check_null(steam::client); check_null(steam::engine); steam::pipe_handle = 0; steam::user_handle = 0; steam::user_handle = steam::engine->CreateLocalUser(&steam::pipe_handle, k_EAccountTypeIndividual); check_null(steam::pipe_handle); check_null(steam::user_handle); if (!steam::engine->IsValidHSteamUserPipe(steam::pipe_handle, steam::user_handle)) { printf("'valid' (non zero) user and pipe handle are not valid!\nThis is probably a bug.\n"); return false; } steam::user = (IClientUser001 *)steam::engine->GetIClientUser( steam::user_handle, steam::pipe_handle, "CLIENTUSER_INTERFACE_VERSION001"); steam::client_friends = (IClientFriends001 *)steam::engine->GetIClientFriends( steam::user_handle, steam::pipe_handle, "CLIENTFRIENDS_INTERFACE_VERSION001"); steam::steam_friends = (ISteamFriends015 *)steam::client->GetISteamFriends( steam::user_handle, steam::pipe_handle, "SteamFriends015"); check_null(steam::user); check_null(steam::steam_friends); check_null(steam::client_friends); return true; } #undef check_null bool run_tests() { // We need a way of checking the output of a test // To see whether it succeeded or failed printf("\n\nMapped Tests!\n\n"); // Use GetISteamUtils as it gets with pipe but no user auto mapped_test = (IMappedTest001 *)steam::client->GetISteamUtils(steam::pipe_handle, "MappedTest001"); int a = 3; int b = 3; int c = 10; auto res = mapped_test->PointerTest(&a, &b, &c); if (a == 4 && b == 5 && c == 6 && res == 15) { printf("PointerTest succeeded\n"); } else { printf("PointerTest failed\n"); printf("Expected 4, 5, 6, 15\n" "Got %d, %d, %d, %d\n", a, b, c, res); } char buffer[1024]; memset(buffer, 0, sizeof(buffer)); strcpy(buffer, "OverrideMe"); int bytes_wrote = mapped_test->BufferTest(buffer, 1024); if (bytes_wrote == 13 && strcmp(buffer, "OverrideMe") == 0) { printf("BufferTest succeeded\n"); } else { printf("BufferTest failed\n"); printf("Expected '13 characters', 13\n" "Got '%s', %d\n", buffer, bytes_wrote); } MappedTestStruct s; memset(&s, 0x11, sizeof(MappedTestStruct)); mapped_test->TestStruct(&s, sizeof(MappedTestStruct)); printf("StructTest: Testing struct alignment in buffers\n"); printf("%hhx %x %x %hhx %llx\n", s.a, s.b, s.c, s.d, s.e); printf("\n\nMapped tests finished\n\n"); return true; } void login_to_steam() { char username[128]; char password[128]; printf("Enter your username: "); scanf("%128s", username); printf("Enter your password: "); scanf("%128s", password); steam::user->LogOnWithPassword(username, password); } #include "listener.hh" int main(int argc, const char **argv) { if (!load_steam_dll()) { printf("Unable to load the steam dll from %s\n", steam_path); return 1; } if (!get_steam_interfaces()) { printf("Unable to get steam interfaces\n"); return 1; } ListenerRegister::register_all(); login_to_steam(); while (true) { steam::process_callbacks(); sleep(1); } getc(stdin); return 0; } // #pragma pack(push, 4) // struct packing_helper { // uint8 byte_a; // uint16 align_16; // uint8 byte_b; // uint32 align_32; // uint8 byte_c; // uint64 align_64; // }; // enum class packing_test { // a = offsetof(packing_helper, align_16) - offsetof(packing_helper, byte_a), // b = offsetof(packing_helper, align_32) - offsetof(packing_helper, byte_b), // c = offsetof(packing_helper, align_64) - offsetof(packing_helper, byte_c), // }; // #pragma pack(pop)
27.470297
108
0.633628
emily33901
63a5586719e42571233ea047d1fd02428db1a4b7
314
cpp
C++
DSAA2/TestStackAr.cpp
crosslife/DSAA
03472db6e61582187192073b6ea4649b6195222b
[ "MIT" ]
5
2017-03-30T23:23:08.000Z
2020-11-08T00:34:46.000Z
DSAA2/TestStackAr.cpp
crosslife/DSAA
03472db6e61582187192073b6ea4649b6195222b
[ "MIT" ]
null
null
null
DSAA2/TestStackAr.cpp
crosslife/DSAA
03472db6e61582187192073b6ea4649b6195222b
[ "MIT" ]
1
2019-04-12T13:17:31.000Z
2019-04-12T13:17:31.000Z
#include <iostream.h> #include "StackAr.h" int main( ) { Stack<int> s; for( int i = 0; i < 10; i++ ) s.push( i ); while( !s.isEmpty( ) ) cout << s.topAndPop( ) << endl; return 0; }
19.625
47
0.328025
crosslife
63a8693bdd8f506c846a79bdf7dcbe1c097fe50b
8,914
cpp
C++
planb_hw/src/hardware_node.cpp
liunx/planb_ros2
a9417a9699626f007752a3706d2b26c364075a92
[ "Apache-2.0" ]
null
null
null
planb_hw/src/hardware_node.cpp
liunx/planb_ros2
a9417a9699626f007752a3706d2b26c364075a92
[ "Apache-2.0" ]
null
null
null
planb_hw/src/hardware_node.cpp
liunx/planb_ros2
a9417a9699626f007752a3706d2b26c364075a92
[ "Apache-2.0" ]
null
null
null
#include <thread> #include <mraa.hpp> #include "planb_hw/hardware_node.hpp" #include "planb_common/common.hpp" using namespace std::chrono_literals; using std::placeholders::_1; HardwareNode::HardwareNode(const rclcpp::NodeOptions &options) : Node("hardware", options), status_("OFF") { std::string dev_path = this->declare_parameter("dev_path", "/dev/ttyS5"); int baud = this->declare_parameter("baud", 115200); serial_init(dev_path, baud); pub_status_ = this->create_publisher<std_msgs::msg::String>("/planb/hardware/status", 1); sub_cmd_ = this->create_subscription<planb_interfaces::msg::Cmd>( "/planb/hardware/cmd", 1, std::bind(&HardwareNode::cmd_callback, this, _1)); sub_robot_ = this->create_subscription<planb_interfaces::msg::Robot>( "/planb/hardware/robot", 1, std::bind(&HardwareNode::robot_callback, this, _1)); } HardwareNode::~HardwareNode() { uint8_t cmd[16] = {0xFF, 0xFF, 0xF0, 0xF0}; uart_->write((char *)cmd, 16); uart_->close(); } void HardwareNode::serial_init(std::string &dev_path, const int baud) { uart_ = std::make_shared<mraa::Uart>(dev_path); if (uart_->setBaudRate(baud) != mraa::SUCCESS) { RCLCPP_ERROR(this->get_logger(), "Error setting parity on UART"); return; } if (uart_->setMode(8, mraa::UART_PARITY_NONE, 1) != mraa::SUCCESS) { RCLCPP_ERROR(this->get_logger(), "Error setting parity on UART"); return; } if (uart_->setFlowcontrol(false, false) != mraa::SUCCESS) { RCLCPP_ERROR(this->get_logger(), "Error setting flow control UART"); return; } uint8_t cmd[16] = {0xFF, 0xFF, 0xF1, 0xF1}; uart_->write((char *)cmd, 16); } void HardwareNode::publish_status(const std::string &status) { std_msgs::msg::String msg; msg.data = status; status_ = status; pub_status_->publish(std::move(msg)); } void HardwareNode::turn_on() { publish_status("ON"); } void HardwareNode::turn_off() { publish_status("OFF"); } void HardwareNode::cmd_callback(const planb_interfaces::msg::Cmd &msg) { switch (msg.cmd) { case planb::CMD_TURN_ON: turn_on(); break; case planb::CMD_TURN_OFF: turn_off(); break; default: break; } } void HardwareNode::normal_mode(const planb_interfaces::msg::Robot &msg) { // servos uint8_t angle = (uint8_t)(90 + msg.servo.angle); if (msg.servo.left_front > 0) control_data_[0] = angle; if (msg.servo.left_tail > 0) control_data_[1] = angle; if (msg.servo.right_front > 0) control_data_[2] = angle; if (msg.servo.right_tail > 0) control_data_[3] = angle; // motors uint8_t motors[6] = { msg.motor.left_front, msg.motor.left_middle, msg.motor.left_tail, msg.motor.right_front, msg.motor.right_middle, msg.motor.right_tail}; uint8_t accel = (uint8_t)abs(msg.motor.accel); for (int i = 0; i < 6; i++) { if (motors[i] <= 0) continue; if (msg.motor.accel < 0) { control_data_[4 + 2 * i] = 0; control_data_[4 + 2 * i + 1] = accel; } else if (msg.motor.accel > 0) { control_data_[4 + 2 * i] = accel; control_data_[4 + 2 * i + 1] = 0; } else { control_data_[4 + 2 * i] = 0; control_data_[4 + 2 * i + 1] = 0; } } tx_data(); } void HardwareNode::accel_circle(const int accel) { // motors uint8_t _accel = (uint8_t)abs(accel); for (int i = 0; i < 3; i++) { if (accel < 0) { control_data_[4 + 2 * i] = 0; control_data_[4 + 2 * i + 1] = _accel; } else if (accel > 0) { control_data_[4 + 2 * i] = _accel; control_data_[4 + 2 * i + 1] = 0; } else { control_data_[4 + 2 * i] = 0; control_data_[4 + 2 * i + 1] = 0; } } for (int i = 3; i < 6; i++) { if (accel < 0) { control_data_[4 + 2 * i] = _accel; control_data_[4 + 2 * i + 1] = 0; } else if (accel > 0) { control_data_[4 + 2 * i] = 0; control_data_[4 + 2 * i + 1] = _accel; } else { control_data_[4 + 2 * i] = 0; control_data_[4 + 2 * i + 1] = 0; } } } void HardwareNode::circle_mode(const planb_interfaces::msg::Robot &msg) { // servos uint8_t angle = (uint8_t)std::round(std::atan(d1 / d2) * 180 / PI); control_data_[0] = 90 + angle; control_data_[1] = 90 - angle; control_data_[2] = 90 - angle; control_data_[3] = 90 + angle; // motors if (msg.motor.accel > 0) accel_circle(100); else if (msg.motor.accel < 0) accel_circle(-100); tx_data(); std::this_thread::sleep_for(30ms); accel_circle(msg.motor.accel); tx_data(); } void HardwareNode::accel_arckerman(const int accel) { // motors uint8_t _accel = (uint8_t)abs(accel); std::vector<uint8_t> accels; if (accel < 0) accels = calc_accel((float)angle_, _accel, true); else accels = calc_accel((float)angle_, _accel, false); for (int i = 0; i < 6; i++) { if (accel < 0) { control_data_[4 + 2 * i] = 0; control_data_[4 + 2 * i + 1] = accels[i]; } else if (accel > 0) { control_data_[4 + 2 * i] = accels[i]; control_data_[4 + 2 * i + 1] = 0; } else { control_data_[4 + 2 * i] = 0; control_data_[4 + 2 * i + 1] = 0; } } } void HardwareNode::arckerman_mode(const planb_interfaces::msg::Robot &msg) { // servos std::vector<uint8_t> angles; uint8_t angle = (uint8_t)abs(msg.servo.angle); if (msg.servo.angle < 0) angles = calc_angles(angle, true); else angles = calc_angles(angle, false); control_data_[0] = angles[0]; control_data_[1] = angles[1]; control_data_[2] = angles[2]; control_data_[3] = angles[3]; // motors if (msg.motor.accel > 0) accel_arckerman(100); else if (msg.motor.accel < 0) accel_arckerman(-100); tx_data(); std::this_thread::sleep_for(30ms); accel_arckerman(msg.motor.accel); tx_data(); } void HardwareNode::robot_callback(const planb_interfaces::msg::Robot &msg) { if (msg.mode == 0) { normal_mode(msg); } else if (msg.mode == 1) { circle_mode(msg); } else if (msg.mode == 2) { arckerman_mode(msg); } else { RCLCPP_INFO(this->get_logger(), "Uknown mode: %d!", msg.mode); } } std::vector<uint8_t> HardwareNode::calc_angles(float angle, bool direct_left) { if (angle == 0.0) return {90, 90, 90, 90}; float radius = std::round(d1 + d3 / std::tan(angle * PI / 180)); std::vector<uint8_t> angles; float a1 = std::round(std::atan(d3 / (d1 + radius)) * 180 / PI); float a2 = std::round(std::atan(d2 / (d1 + radius)) * 180 / PI); float a3 = std::round(std::atan(d3 / (radius - d1)) * 180 / PI); float a4 = std::round(std::atan(d2 / (radius - d1)) * 180 / PI); if (direct_left) return {(uint8_t)(90.0 - a1), (uint8_t)(90.0 + a2), (uint8_t)(90.0 - a3), (uint8_t)(90.0 + a4)}; else return {(uint8_t)(90.0 + a1), (uint8_t)(90.0 - a2), (uint8_t)(90.0 + a3), (uint8_t)(90.0 - a4)}; } std::vector<uint8_t> HardwareNode::calc_accel(float angle, uint8_t accel, bool direct_left) { if (angle == 0.0) return {accel, accel, accel, accel, accel, accel}; float radius = std::round(d1 + d3 / std::tan(angle * PI / 180)); std::vector<uint8_t> accels; uint8_t v1 = std::round(accel * std::sqrt(std::pow(d3, 2.0) + std::pow(d1 + radius, 2.0)) / (radius + d4)); uint8_t v2 = accel; uint8_t v3 = std::round(accel * std::sqrt(std::pow(d2, 2.0) + std::pow(d1 + radius, 2.0)) / (radius + d4)); uint8_t v4 = std::round(accel * std::sqrt(std::pow(d3, 2.0) + std::pow(radius - d1, 2.0)) / (radius + d4)); uint8_t v5 = std::round(accel * (radius - d4) / (radius + d4)); uint8_t v6 = std::round(accel * std::sqrt(std::pow(d2, 2.0) + std::pow(radius - d1, 2.0)) / (radius + d4)); if (direct_left) accels = {v4, v5, v6, v1, v2, v3}; else accels = {v1, v2, v3, v4, v5, v6}; float _max = *std::max_element(accels.begin(), accels.end()); if (_max > 100.0) { float rate = 100.0 / _max; for (int i = 0; i < 6; i++) { accels[i] = std::round(accels[i] * rate); } } return accels; } void HardwareNode::tx_data() { uart_->write((char *)control_data_, 16); }
26.688623
111
0.549697
liunx
63aa566999727b89505e2fb7aa8885bb737cb75f
581
cc
C++
tests/application/test_bitmap_application.cc
wujiazheng2020/simple_stl
f04ccd049a92e463bde4c34fed67679fb5822eb9
[ "MIT" ]
6
2021-08-31T04:44:50.000Z
2022-03-10T15:15:29.000Z
tests/application/test_bitmap_application.cc
wujiazheng2020/simple_stl
f04ccd049a92e463bde4c34fed67679fb5822eb9
[ "MIT" ]
null
null
null
tests/application/test_bitmap_application.cc
wujiazheng2020/simple_stl
f04ccd049a92e463bde4c34fed67679fb5822eb9
[ "MIT" ]
null
null
null
/* * Copyright 2021 Jiazheng Wu * * FileName: test_bitmap_algorithm.cc * * Author: Jiazheng Wu * Email: [email protected] * Licensed under the MIT License */ #include <glog/logging.h> #include <gtest/gtest.h> #include <vector> #include "simple_stl/application/bitmap_application/calculate_prime.h" static const std::vector<int> prime_vec = sstl::CalculatePrimeBelowN<10000>(); TEST(BIT_MAP, BitMapBasic) { for (uint i = 1; i < prime_vec.size(); ++i) { std::cout << prime_vec[i] << " "; if (i % 15 == 0) { std::cout << std::endl; } } }
20.034483
70
0.652324
wujiazheng2020
63af9a26133a8a77a2a5f5b3af040bd8c56ba66f
621
cpp
C++
src/common/factorial.cpp
ull-esit-sistemas-operativos/ssoo-ejemplos
f59d606f45fd3cc05b605472db0dd90d3f209b71
[ "CC0-1.0" ]
1
2021-12-29T12:44:43.000Z
2021-12-29T12:44:43.000Z
src/common/factorial.cpp
ull-esit-sistemas-operativos/ssoo-ejemplos
f59d606f45fd3cc05b605472db0dd90d3f209b71
[ "CC0-1.0" ]
null
null
null
src/common/factorial.cpp
ull-esit-sistemas-operativos/ssoo-ejemplos
f59d606f45fd3cc05b605472db0dd90d3f209b71
[ "CC0-1.0" ]
null
null
null
// factorial.cpp - Funciones comunes a los ejemplos del factorial. // #include <iostream> #include "factorial.hpp" int get_user_input() { std::cout << "[PADRE] Introduzca un número: "; std::cout.flush(); int number; std::cin >> number; return number; } int calculate_factorial(int number) { std::cout << "[HIJO] Calculando..."; std::cout.flush(); int factorial = 1; for ( int i = 2; i <= number; i++ ) { factorial = factorial * i; std::cout << '.'; std::cout.flush(); } std::cout << '\n'; std::cout.flush(); return factorial; }
16.783784
66
0.553945
ull-esit-sistemas-operativos
63afc7a75dea3a330af51fc7926b3a22e2060645
15,712
cc
C++
mysql_sys/my_error.cc
realnickel/mysql-connector-odbc
cd3aad7a64a2c6bf58c6b04e0a63026bbacc8189
[ "Artistic-1.0-Perl" ]
null
null
null
mysql_sys/my_error.cc
realnickel/mysql-connector-odbc
cd3aad7a64a2c6bf58c6b04e0a63026bbacc8189
[ "Artistic-1.0-Perl" ]
null
null
null
mysql_sys/my_error.cc
realnickel/mysql-connector-odbc
cd3aad7a64a2c6bf58c6b04e0a63026bbacc8189
[ "Artistic-1.0-Perl" ]
null
null
null
/* Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. Without limiting anything contained in the foregoing, this file, which is part of C Driver for MySQL (Connector/C), is also subject to the Universal FOSS Exception, version 1.0, a copy of which can be found at http://oss.oracle.com/licenses/universal-foss-exception. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** @file mysys/my_error.cc */ #include <errno.h> #include <stdarg.h> #ifdef __linux__ #include <features.h> #endif #include <stdio.h> #include <string.h> #include <sys/types.h> #include "m_ctype.h" #include "m_string.h" #include "my_base.h" #include "my_dbug.h" #include "my_inttypes.h" #include "my_loglevel.h" #include "my_sys.h" #include "mysql/service_mysql_alloc.h" #include "my_handler_errors.h" #include "mysys_priv.h" #include "mysys_err.h" #include "mysql_strings/mb_wc.h" /* Max length of a error message. Should be kept in sync with MYSQL_ERRMSG_SIZE. */ #define ERRMSGSIZE (512) /* Define some external variables for error handling */ /* WARNING! my_error family functions have to be used according following rules: - if message has no parameters, use my_message(ER_CODE, ER(ER_CODE), MYF(N)) - if message has parameters and is registered: my_error(ER_CODE, MYF(N), ...) - for free-form messages use my_printf_error(ER_CODE, format, MYF(N), ...) These three send their messages using error_handler_hook, which normally means we'll send them to the client if we have one, or to error-log / stderr otherwise. */ /* Message texts are registered into a linked list of 'my_err_head' structs. Each struct contains (1.) a pointer to a function that returns C character strings with '\0' termination (2.) the error number for the first message in the array (array index 0) (3.) the error number for the last message in the array (array index (last - first)). The function may return NULL pointers and pointers to empty strings. Both kinds will be translated to "Unknown error %d.", if my_error() is called with a respective error number. The list of header structs is sorted in increasing order of error numbers. Negative error numbers are allowed. Overlap of error numbers is not allowed. Not registered error numbers will be translated to "Unknown error %d.". */ static struct my_err_head { struct my_err_head *meh_next; /* chain link */ const char *(*get_errmsg)(int); /* returns error message format */ int meh_first; /* error number matching array slot 0 */ int meh_last; /* error number matching last slot */ } my_errmsgs_globerrs = {NULL, get_global_errmsg, EE_ERROR_FIRST, EE_ERROR_LAST}; static struct my_err_head *my_errmsgs_list = &my_errmsgs_globerrs; /** Get a string describing a system or handler error. thread-safe. @param buf a buffer in which to return the error message @param len the size of the aforementioned buffer @param nr the error number @retval buf always buf. for signature compatibility with strerror(3). */ char *my_strerror(char *buf, size_t len, int nr) { char *msg = NULL; buf[0] = '\0'; /* failsafe */ /* These (handler-) error messages are shared by perror, as required by the principle of least surprise. */ if ((nr >= HA_ERR_FIRST) && (nr <= HA_ERR_LAST)) msg = (char *)handler_error_messages[nr - HA_ERR_FIRST]; if (msg != NULL) strmake(buf, msg, len - 1); else { /* On Windows, do things the Windows way. On a system that supports both the GNU and the XSI variant, use whichever was configured (GNU); if this choice is not advertised, use the default (POSIX/XSI). Testing for __GNUC__ is not sufficient to determine whether this choice exists. */ #if defined(_WIN32) strerror_s(buf, len, nr); if (thr_winerr() != 0) { /* If error code is EINVAL, and Windows Error code has been set, we append the Windows error code to the message. */ if (nr == EINVAL) { char tmp_buff[256]; snprintf(tmp_buff, sizeof(tmp_buff), " [OS Error Code : 0x%x]", thr_winerr()); strcat_s(buf, len, tmp_buff); } set_thr_winerr(0); } #elif ((defined _POSIX_C_SOURCE && (_POSIX_C_SOURCE >= 200112L)) || \ (defined _XOPEN_SOURCE && (_XOPEN_SOURCE >= 600))) && \ !defined _GNU_SOURCE strerror_r(nr, buf, len); /* I can build with or without GNU */ #elif defined(__GLIBC__) && defined(_GNU_SOURCE) char *r = strerror_r(nr, buf, len); if (r != buf) /* Want to help, GNU? */ strmake(buf, r, len - 1); /* Then don't. */ #else strerror_r(nr, buf, len); #endif } /* strerror() return values are implementation-dependent, so let's be pragmatic. */ if (!buf[0] || !strcmp(buf, "No error information")) strmake(buf, "Unknown error", len - 1); return buf; } /** @brief Get an error format string from one of the my_error_register()ed sets @note NULL values are possible even within a registered range. @param nr Errno @retval NULL if no message is registered for this error number @retval str C-string */ const char *my_get_err_msg(int nr) { const char *format; struct my_err_head *meh_p; /* Search for the range this error is in. */ for (meh_p = my_errmsgs_list; meh_p; meh_p = meh_p->meh_next) if (nr <= meh_p->meh_last) break; /* If we found the range this error number is in, get the format string. If the string is empty, or a NULL pointer, or if we're out of return, we return NULL. */ if (!(format = (meh_p && (nr >= meh_p->meh_first)) ? meh_p->get_errmsg(nr) : NULL) || !*format) return NULL; return format; } /** Fill in and print a previously registered error message. @note Goes through the (sole) function registered in error_handler_hook @param nr error number @param MyFlags Flags @param ... variable list matching that error format string */ void my_error(int nr, myf MyFlags, ...) { const char *format; char ebuff[ERRMSGSIZE]; DBUG_ENTER("my_error"); DBUG_PRINT("my", ("nr: %d MyFlags: %d errno: %d", nr, MyFlags, errno)); if (!(format = my_get_err_msg(nr))) (void)snprintf(ebuff, sizeof(ebuff), "Unknown error %d", nr); else { va_list args; va_start(args, MyFlags); (void)vsnprintf(ebuff, sizeof(ebuff), format, args); va_end(args); } /* Since this function is an error function, it will frequently be given values that are too long (and thus truncated on byte boundaries, not code point or grapheme boundaries), values that are binary, etc.. Go through and replace every malformed UTF-8 byte with a question mark, so that the result is safe to send to the client and makes sense to read for the user. */ for (char *ptr = ebuff, *end = ebuff + strlen(ebuff); ptr != end;) { my_wc_t ignored; int len = my_mb_wc_utf8mb4(&ignored, pointer_cast<const uchar *>(ptr), pointer_cast<const uchar *>(end)); if (len > 0) { ptr += len; } else { *ptr++ = '?'; } } (*error_handler_hook)(nr, ebuff, MyFlags); DBUG_VOID_RETURN; } /** Print an error message. @note Goes through the (sole) function registered in error_handler_hook @param error error number @param format format string @param MyFlags Flags @param ... variable list matching that error format string */ void my_printf_error(uint error, const char *format, myf MyFlags, ...) { va_list args; char ebuff[ERRMSGSIZE]; DBUG_ENTER("my_printf_error"); DBUG_PRINT("my", ("nr: %d MyFlags: %d errno: %d Format: %s", error, MyFlags, errno, format)); va_start(args, MyFlags); (void)vsnprintf(ebuff, sizeof(ebuff), format, args); va_end(args); (*error_handler_hook)(error, ebuff, MyFlags); DBUG_VOID_RETURN; } /** Print an error message. @note Goes through the (sole) function registered in error_handler_hook @param error error number @param format format string @param MyFlags Flags @param ap variable list matching that error format string */ void my_printv_error(uint error, const char *format, myf MyFlags, va_list ap) { char ebuff[ERRMSGSIZE]; DBUG_ENTER("my_printv_error"); DBUG_PRINT("my", ("nr: %d MyFlags: %d errno: %d format: %s", error, MyFlags, errno, format)); (void)vsnprintf(ebuff, sizeof(ebuff), format, ap); (*error_handler_hook)(error, ebuff, MyFlags); DBUG_VOID_RETURN; } /** Print an error message. @note Goes through the (sole) function registered in error_handler_hook @param error error number @param str error message @param MyFlags Flags */ void my_message(uint error, const char *str, myf MyFlags) { (*error_handler_hook)(error, str, MyFlags); } /** Register error messages for use with my_error(). The function is expected to return addresses to NUL-terminated C character strings. NULL pointers and empty strings ("") are allowed. These will be mapped to "Unknown error" when my_error() is called with a matching error number. This function registers the error numbers 'first' to 'last'. No overlapping with previously registered error numbers is allowed. @param get_errmsg function that returns error messages @param first error number of first message in the array @param last error number of last message in the array @retval 0 OK @retval != 0 Error */ int my_error_register(const char *(*get_errmsg)(int), int first, int last) { struct my_err_head *meh_p; struct my_err_head **search_meh_pp; /* Allocate a new header structure. */ if (!(meh_p = (struct my_err_head *)my_malloc( key_memory_my_err_head, sizeof(struct my_err_head), MYF(MY_WME)))) return 1; meh_p->get_errmsg = get_errmsg; meh_p->meh_first = first; meh_p->meh_last = last; /* Search for the right position in the list. */ for (search_meh_pp = &my_errmsgs_list; *search_meh_pp; search_meh_pp = &(*search_meh_pp)->meh_next) { if ((*search_meh_pp)->meh_last > first) break; } /* Error numbers must be unique. No overlapping is allowed. */ if (*search_meh_pp && ((*search_meh_pp)->meh_first <= last)) { my_free(meh_p); return 1; } /* Insert header into the chain. */ meh_p->meh_next = *search_meh_pp; *search_meh_pp = meh_p; return 0; } /** Unregister formerly registered error messages. This function unregisters the error numbers 'first' to 'last'. These must have been previously registered by my_error_register(). 'first' and 'last' must exactly match the registration. If a matching registration is present, the header is removed from the list. @param first error number of first message @param last error number of last message @retval true Error, no such number range registered. @retval false OK */ bool my_error_unregister(int first, int last) { struct my_err_head *meh_p; struct my_err_head **search_meh_pp; /* Search for the registration in the list. */ for (search_meh_pp = &my_errmsgs_list; *search_meh_pp; search_meh_pp = &(*search_meh_pp)->meh_next) { if (((*search_meh_pp)->meh_first == first) && ((*search_meh_pp)->meh_last == last)) break; } if (!*search_meh_pp) return true; /* Remove header from the chain. */ meh_p = *search_meh_pp; *search_meh_pp = meh_p->meh_next; /* Free the header. */ my_free(meh_p); return false; } /** Unregister all formerly registered error messages. This function unregisters all error numbers that previously have been previously registered by my_error_register(). All headers are removed from the list; the messages themselves are not released here as they may be static. */ void my_error_unregister_all(void) { struct my_err_head *cursor, *saved_next; for (cursor = my_errmsgs_globerrs.meh_next; cursor != NULL; cursor = saved_next) { /* We need this ptr, but we're about to free its container, so save it. */ saved_next = cursor->meh_next; my_free(cursor); } my_errmsgs_globerrs.meh_next = NULL; /* Freed in first iteration above. */ my_errmsgs_list = &my_errmsgs_globerrs; } /** Issue a message locally (i.e. on the same host the program is running on, don't transmit to a client). This is the default value for local_message_hook, and therefore the default printer for my_message_local(). mysys users should not call this directly, but go through my_message_local() instead. This printer prepends an Error/Warning/Note label to the string, then prints it to stderr using my_message_stderr(). Since my_message_stderr() appends a '\n', the format string should not end in a newline. @param ll log level: (ERROR|WARNING|INFORMATION)_LEVEL the printer may use these to filter for verbosity @param format a format string a la printf. Should not end in '\n' @param args parameters to go with that format string */ void my_message_local_stderr(enum loglevel ll, const char *format, va_list args) { char buff[1024]; size_t len; DBUG_ENTER("my_message_local_stderr"); len = snprintf( buff, sizeof(buff), "[%s] ", (ll == ERROR_LEVEL ? "ERROR" : ll == WARNING_LEVEL ? "Warning" : "Note")); vsnprintf(buff + len, sizeof(buff) - len, format, args); my_message_stderr(0, buff, MYF(0)); DBUG_VOID_RETURN; } /** Issue a message locally (i.e. on the same host the program is running on, don't transmit to a client). This goes through local_message_hook, i.e. by default, it calls my_message_local_stderr() which prepends an Error/Warning/Note label to the string, then prints it to stderr using my_message_stderr(). More advanced programs can use their own printers; mysqld for instance uses its own error log facilities which prepend an ISO 8601 / RFC 3339 compliant timestamp etc. @param ll log level: (ERROR|WARNING|INFORMATION)_LEVEL the printer may use these to filter for verbosity @param format a format string a la printf. Should not end in '\n'. @param ... parameters to go with that format string */ void my_message_local(enum loglevel ll, const char *format, ...) { va_list args; DBUG_ENTER("local_print_error"); va_start(args, format); (*local_message_hook)(ll, format, args); va_end(args); DBUG_VOID_RETURN; }
32.196721
80
0.683745
realnickel
63b37238c7561064e42e89fb02b622a4a442839d
344
cpp
C++
Array Ques Missing Value.cpp
priyamittal15/Leetcode_Solutions
21cb9c09e053425dba66acd62240399b1a35fba0
[ "Apache-2.0" ]
1
2022-01-28T08:07:32.000Z
2022-01-28T08:07:32.000Z
Array Ques Missing Value.cpp
priyamittal15/Leetcode_Solutions
21cb9c09e053425dba66acd62240399b1a35fba0
[ "Apache-2.0" ]
null
null
null
Array Ques Missing Value.cpp
priyamittal15/Leetcode_Solutions
21cb9c09e053425dba66acd62240399b1a35fba0
[ "Apache-2.0" ]
1
2022-03-16T14:46:09.000Z
2022-03-16T14:46:09.000Z
#include<iostream> using namespace std; int main(void){ int arr[]={0,-9,1,3,-4,5}; int n=6; int res[n]; for(int i=0;i<n;i++){ if(arr[i]>=0){ res[i]=arr[i]; } else{ } } for(int i=0;i<n;i++){ cout<<res[i]; } for(int i=0;i<n;i++){ if(res[i+1]-res[i]==2){ cout<<i; } } }
11.096774
28
0.418605
priyamittal15
63b3c2a04fa9aeed198000f8618eff88bc84b5d6
3,974
cxx
C++
tests/mlio-test/test_recordio_protobuf_reader.cxx
rizwangilani/ml-io
d9572227281168139c4e99d79a6d2ebc83323a61
[ "Apache-2.0" ]
null
null
null
tests/mlio-test/test_recordio_protobuf_reader.cxx
rizwangilani/ml-io
d9572227281168139c4e99d79a6d2ebc83323a61
[ "Apache-2.0" ]
2
2020-04-08T01:37:44.000Z
2020-04-14T20:14:07.000Z
tests/mlio-test/test_recordio_protobuf_reader.cxx
rizwangilani/ml-io
d9572227281168139c4e99d79a6d2ebc83323a61
[ "Apache-2.0" ]
null
null
null
#include <gtest/gtest.h> #include <mlio.h> namespace mlio { class test_recordio_protobuf_reader : public ::testing::Test { protected: test_recordio_protobuf_reader() = default; ~test_recordio_protobuf_reader() override; protected: std::string const resources_path_ = "../resources/recordio/"; std::string const complete_records_path_ = resources_path_ + "complete_records.pr"; std::string const split_records_path_ = resources_path_ + "split_records.pr"; std::string const corrupt_split_records_path_ = resources_path_ + "corrupted_split_records.pr"; }; test_recordio_protobuf_reader::~test_recordio_protobuf_reader() = default; TEST_F(test_recordio_protobuf_reader, test_complete_records_path) { mlio::data_reader_params prm{}; prm.dataset.emplace_back( mlio::make_intrusive<mlio::file>(complete_records_path_)); prm.batch_size = 1; auto reader = mlio::make_intrusive<mlio::recordio_protobuf_reader>(prm); for (int i = 0; i < 2; i++) { mlio::intrusive_ptr<mlio::example> exm; while ((exm = reader->read_example()) != nullptr) { } reader->reset(); } EXPECT_TRUE(true); } TEST_F(test_recordio_protobuf_reader, test_split_records_path) { mlio::initialize(); mlio::data_reader_params prm{}; prm.dataset.emplace_back( mlio::make_intrusive<mlio::file>(split_records_path_)); prm.batch_size = 1; auto reader = mlio::make_intrusive<mlio::recordio_protobuf_reader>(prm); for (int i = 0; i < 2; i++) { mlio::intrusive_ptr<mlio::example> exm; while ((exm = reader->read_example()) != nullptr) { } reader->reset(); } EXPECT_TRUE(true); } TEST_F(test_recordio_protobuf_reader, test_corrupt_split_records_patH) { mlio::initialize(); // Check that the third record is corrupt. mlio::data_reader_params prm{}; prm.dataset.emplace_back( mlio::make_intrusive<mlio::file>(corrupt_split_records_path_)); prm.batch_size = 10; prm.num_prefetched_batches = 1; std::string error_substring = "The record 13 in the data store"; auto reader = mlio::make_intrusive<mlio::recordio_protobuf_reader>(prm); mlio::intrusive_ptr<mlio::example> exm; // Try to read batch, should fail due to corrupt record try { exm = reader->read_example(); FAIL() << "Expected corrupt error exception on 3rd record."; } catch (data_reader_error const &corrupt_record_err) { EXPECT_TRUE( std::string(corrupt_record_err.what()).find(error_substring) != std::string::npos) << "Error thrown:" + std::string(corrupt_record_err.what()); } catch (...) { FAIL() << "Expected corrupt error exception, not a different error."; } // Try to read batch, should fail again try { exm = reader->read_example(); FAIL() << "Expected corrupt error exception on 3rd record."; } catch (data_reader_error const &corrupt_record_err) { EXPECT_TRUE( std::string(corrupt_record_err.what()).find(error_substring) != std::string::npos) << "Error thrown:" + std::string(corrupt_record_err.what()); } catch (...) { FAIL() << "Expected corrupt error exception, not a different error."; } // Reset reader, expecting same results. reader->reset(); // Try to read batch, should fail again try { exm = reader->read_example(); FAIL() << "Expected corrupt error exception on 3rd record."; } catch (data_reader_error const &corrupt_record_err) { EXPECT_TRUE( std::string(corrupt_record_err.what()).find(error_substring) != std::string::npos) << "Error thrown:" + std::string(corrupt_record_err.what()); } catch (...) { FAIL() << "Expected corrupt error exception, not a different error."; } } } // namespace mlio
31.539683
77
0.648968
rizwangilani
63b55ef9ccd3d06015dda8bc64ec37466375fc61
10,669
cpp
C++
src/device_info_win32.cpp
semenovf/pfs-multimedia
78e2ea9dfe89d2f84d583f768ca35f183773d859
[ "MIT" ]
null
null
null
src/device_info_win32.cpp
semenovf/pfs-multimedia
78e2ea9dfe89d2f84d583f768ca35f183773d859
[ "MIT" ]
null
null
null
src/device_info_win32.cpp
semenovf/pfs-multimedia
78e2ea9dfe89d2f84d583f768ca35f183773d859
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2021 Vladislav Trifochkin // // This file is part of [multimedia-lib](https://github.com/semenovf/multimedia-lib) library. // // Changelog: // 2021.08.07 Initial version. //////////////////////////////////////////////////////////////////////////////// #include "pfs/multimedia/audio.hpp" #include <mmdeviceapi.h> #include <strmif.h> // ICreateDevEnum #include <functiondiscoverykeys_devpkey.h> // PROPERTYKEY #include <vector> #include <cwchar> namespace pfs { namespace multimedia { namespace audio { // Avoid warning: // warning C4996: 'wcsrtombs': This function or variable may be unsafe. // Consider using wcsrtombs_s instead. To disable // deprecation, use _CRT_SECURE_NO_WARNINGS. See online // help for details. #pragma warning(disable: 4996) static std::string convert_wide (LPCWSTR wstr) { std::mbstate_t state = std::mbstate_t(); std::size_t len = 1 + std::wcsrtombs(nullptr, & wstr, 0, & state); std::string result(len, '\x0'); std::wcsrtombs(& result[0], & wstr, len, & state); return result; } class IMMDeviceEnumerator_initializer { HRESULT hrCoInit {S_FALSE}; IMMDeviceEnumerator ** ppEnumerator {nullptr}; private: void finalize () { if (ppEnumerator && *ppEnumerator) { (*ppEnumerator)->Release(); *ppEnumerator = nullptr; ppEnumerator = nullptr; } if (SUCCEEDED(hrCoInit)) { CoUninitialize(); hrCoInit = S_FALSE; } } public: IMMDeviceEnumerator_initializer (IMMDeviceEnumerator ** pp) : ppEnumerator(pp) { if (pp) { bool success {false}; // Mandatory call to call CoCreateInstance() later hrCoInit = CoInitialize(nullptr); if (SUCCEEDED(hrCoInit)) { // https://docs.microsoft.com/en-gb/windows/win32/coreaudio/mmdevice-api const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator); const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator); auto hr = CoCreateInstance(CLSID_MMDeviceEnumerator , nullptr , CLSCTX_ALL // CLSCTX_INPROC_SERVER , IID_IMMDeviceEnumerator , reinterpret_cast<void **>(ppEnumerator)); if (SUCCEEDED(hr)) { success = true; } else { // Possible errors: // REGDB_E_CLASSNOTREG - A specified class is not registered in the // registration database. Also can indicate that the type of server // you requested in the CLSCTX enumeration is not registered or the // values for the server types in the registry are corrupt. // E_NOINTERFACE - The specified class does not implement the requested // interface, or the controlling IUnknown does not expose the // requested interface. // There might be error handling here ; } } if (!success) finalize(); } } ~IMMDeviceEnumerator_initializer () { finalize(); } }; class IMMDeviceCollection_initializer { IMMDeviceCollection ** ppEndpoints {nullptr}; private: void finalize () { if (ppEndpoints && *ppEndpoints) { (*ppEndpoints)->Release(); *ppEndpoints = nullptr; ppEndpoints = nullptr; } } public: IMMDeviceCollection_initializer (IMMDeviceCollection ** pp , IMMDeviceEnumerator * pEnumerator , device_mode mode) : ppEndpoints(pp) { if (pEnumerator && pp) { bool success {false}; EDataFlow data_flow = (mode == device_mode::output) ? eRender : eCapture; // https://docs.microsoft.com/en-us/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdeviceenumerator-enumaudioendpoints auto hr = pEnumerator->EnumAudioEndpoints(data_flow , DEVICE_STATE_ACTIVE , ppEndpoints); if (SUCCEEDED(hr)) { success = true; } else { // There might be error handling here // NOTE! But there is no apparent reason for the error. ; } if (!success) finalize(); } } ~IMMDeviceCollection_initializer () { finalize(); } }; class IMMDevice_guard { IMMDevice ** ppDevice {nullptr}; public: IMMDevice_guard (IMMDevice ** pp) : ppDevice(pp) {} ~IMMDevice_guard () { if (ppDevice && *ppDevice) { (*ppDevice)->Release(); *ppDevice = nullptr; ppDevice = nullptr; } } }; static bool device_info_helper (IMMDevice * pEndpoint, device_info & di) { bool result = false; if (pEndpoint) { IPropertyStore * pProps = nullptr; // Get the endpoint ID string. // https://docs.microsoft.com/en-us/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdevice-getid LPWSTR pwszID = nullptr; auto hr = pEndpoint->GetId(& pwszID); if (SUCCEEDED(hr)) { hr = pEndpoint->OpenPropertyStore(STGM_READ, & pProps); if (SUCCEEDED(hr)) { PROPVARIANT varName; // Initialize container for property value. PropVariantInit(& varName); // Get the endpoint's friendly-name property. hr = pProps->GetValue(PKEY_Device_FriendlyName, & varName); if (SUCCEEDED(hr)) { di.name = convert_wide(pwszID); di.readable_name = convert_wide(varName.pwszVal); PropVariantClear(& varName); result = true; } else { // pProps->GetValue() // There might be error handling here ; } if (pProps) { pProps->Release(); pProps = nullptr; } } else { // pEndpoint->OpenPropertyStore() // There might be error handling here // NOTE! But there is no apparent reason for the error. ; } } else { // pEndpoint->GetId() // There might be error handling here ; } if (pwszID) { CoTaskMemFree(pwszID); pwszID = nullptr; } } else { // There might be error handling here // E_INVALIDARG - Parameter 'device_index' is not a valid device number. ; } if (pEndpoint) { pEndpoint->Release(); pEndpoint = nullptr; } return result; } // Default source/input device static device_info default_device_helper (device_mode mode) { device_info result; IMMDeviceEnumerator * pEnumerator = nullptr; IMMDeviceEnumerator_initializer enumerator_initializer {& pEnumerator}; if (pEnumerator) { IMMDevice * pEndpoint = nullptr; EDataFlow data_flow = (mode == device_mode::output) ? eRender : eCapture; // https://docs.microsoft.com/en-us/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdeviceenumerator-getdefaultaudioendpoint auto hr = pEnumerator->GetDefaultAudioEndpoint(data_flow, eConsole, & pEndpoint); IMMDevice_guard endpoint_guard {& pEndpoint}; if (SUCCEEDED(hr) && pEndpoint) { if (!device_info_helper(pEndpoint, result)) { result = device_info{}; } } } return result; } // Default source/input device PFS_MULTIMEDIA_DLL_API device_info default_input_device () { return default_device_helper(device_mode::input); } // Default sink/ouput device PFS_MULTIMEDIA_DLL_API device_info default_output_device () { return default_device_helper(device_mode::output); } // https://docs.microsoft.com/en-us/windows/win32/coreaudio/device-properties PFS_MULTIMEDIA_DLL_API std::vector<device_info> fetch_devices (device_mode mode) { std::vector<device_info> result; IMMDeviceEnumerator * pEnumerator = nullptr; IMMDeviceEnumerator_initializer enumerator_initializer {& pEnumerator}; if (pEnumerator) { IMMDeviceCollection * pEndpoints = nullptr; IMMDeviceCollection_initializer endpoints_initializer {& pEndpoints, pEnumerator, mode}; if (pEndpoints) { // https://docs.microsoft.com/en-us/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdevicecollection-getcount UINT count = 0; auto hr = pEndpoints->GetCount(& count); if (SUCCEEDED(hr)) { for (UINT device_index = 0; device_index < count; device_index++) { IMMDevice * pEndpoint = nullptr; // https://docs.microsoft.com/en-us/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdevicecollection-item hr = pEndpoints->Item(static_cast<UINT>(device_index), & pEndpoint); IMMDevice_guard endpoint_guard {& pEndpoint}; if (SUCCEEDED(hr) && pEndpoint) { device_info di; if (device_info_helper(pEndpoint, di)) { result.push_back(std::move(di)); } } else { // There might be error handling here // E_INVALIDARG - Parameter 'device_index' is not a valid device number. ; } } } else { // pEndpoints->GetCount() // There might be error handling here // NOTE! But there is no apparent reason for the error. ; } } } return result; } }}} // namespace pfs::multimedia::audio
32.330303
133
0.532571
semenovf
63be27dd8421f94288ac74948f854c7984304875
2,048
cpp
C++
src/Particle/ParticleModule/ModuleSizeOverLifetime.cpp
Jino42/stf
f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db
[ "Unlicense" ]
null
null
null
src/Particle/ParticleModule/ModuleSizeOverLifetime.cpp
Jino42/stf
f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db
[ "Unlicense" ]
null
null
null
src/Particle/ParticleModule/ModuleSizeOverLifetime.cpp
Jino42/stf
f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db
[ "Unlicense" ]
null
null
null
#include "ModuleSizeOverLifetime.hpp" #include <iostream> #include "Cl/ClProgram.hpp" #include "OpenCGL_Tools.hpp" #include "Cl/ClKernel.hpp" #include "Particle/PaticleEmitter/AParticleEmitter.hpp" ModuleSizeOverLifetime::ModuleSizeOverLifetime(AParticleEmitter &emitter) : AParticleModule(emitter), gpuBufferModuleParam_(ClContext::Get().context, CL_MEM_READ_WRITE, sizeof(ModuleParamSizeOverLifetime)) { ClProgram::Get().addProgram(pathKernel_ / "Size.cl"); cpuBufferModuleParam_.size.rangeMin = 0.0f; cpuBufferModuleParam_.size.rangeMax = 10.0f; kernelUpdate_.setKernel(emitter_, "sizeUpdate"); kernelUpdate_.setArgsGPUBuffers(eParticleBuffer::kData); } void ModuleSizeOverLifetime::init() { if (debug_) printf("%s\n", __FUNCTION_NAME__); queue_.getQueue().enqueueWriteBuffer(gpuBufferModuleParam_, CL_TRUE, 0, sizeof(ModuleParamSizeOverLifetime), &cpuBufferModuleParam_); } void ModuleSizeOverLifetime::update(float deltaTime) { if (!isActive_) return; if (debug_) printf("%s\n", __FUNCTION_NAME__); queue_.getQueue().enqueueWriteBuffer(gpuBufferModuleParam_, CL_TRUE, 0, sizeof(ModuleParamSizeOverLifetime), &cpuBufferModuleParam_); kernelUpdate_.beginAndSetUpdatedArgs(gpuBufferModuleParam_); OpenCGL::RunKernelWithMem(queue_.getQueue(), kernelUpdate_, emitter_.getParticleOCGL_BufferData().mem, cl::NullRange, cl::NDRange(nbParticleMax_)); } void ModuleSizeOverLifetime::reload() { if (debug_) printf("%s\n", __FUNCTION_NAME__); gpuBufferModuleParam_ = cl::Buffer(ClContext::Get().context, CL_MEM_READ_WRITE, sizeof(ModuleParamSizeOverLifetime)); init(); } float &ModuleSizeOverLifetime::getSizeMin() { return cpuBufferModuleParam_.size.rangeMin; } float &ModuleSizeOverLifetime::getSizeMax() { return cpuBufferModuleParam_.size.rangeMax; } void ModuleSizeOverLifetime::setSizeMin(float min) { cpuBufferModuleParam_.size.rangeMin = min; } void ModuleSizeOverLifetime::setSizeMax(float max) { cpuBufferModuleParam_.size.rangeMax = max; }
34.133333
151
0.773926
Jino42
63bf359fb22d9e50326c8fc5e0c033aa560ea18d
6,368
cpp
C++
src/getting_started/07_transforms.cpp
clsrfish/learnogl
3e1cc42a595dd12779268ba587ef68fa4991e1f5
[ "Apache-2.0" ]
null
null
null
src/getting_started/07_transforms.cpp
clsrfish/learnogl
3e1cc42a595dd12779268ba587ef68fa4991e1f5
[ "Apache-2.0" ]
null
null
null
src/getting_started/07_transforms.cpp
clsrfish/learnogl
3e1cc42a595dd12779268ba587ef68fa4991e1f5
[ "Apache-2.0" ]
null
null
null
#include <glad/glad.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <stb_image.h> #include "../gl/shader.h" #include "../utils/log.h" #include "../gl/gl_utils.h" namespace getting_started { namespace transforms { float vertices[] = { // ---- 位置 ---- ---- 颜色 ---- - 纹理坐标 - 0.5f, 0.5f, 0.0f, 1.0f, 1.0f, // 右上 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, // 右下 -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, // 左下 -0.5f, 0.5f, 0.0f, 0.0f, 1.0f // 左上 }; unsigned short indices[] = { 0, 1, 3, // 第一个三角形 1, 2, 3}; // 第二个三角形 int main() { LOG_I(__FILENAME__); glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #if defined(__APPLE__) glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE); #endif GLFWwindow *window = glfwCreateWindow(800, 600, __FILENAME__, nullptr, nullptr); if (window == nullptr) { LOG_E("Failed to create GLFW window"); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { LOG_E("Failed to initialize GLAD loader"); glfwTerminate(); return -1; } else { printGLInfo(); } glViewport(0, 0, 800, 600); glfwSetFramebufferSizeCallback(window, [](GLFWwindow *, int w, int h) { glViewport(0, 0, w, h); }); unsigned int VAO; glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); unsigned int EBO; glGenBuffers(1, &EBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); unsigned int VBO; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 5, (void *)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 5, (void *)(sizeof(float) * 3)); glEnableVertexAttribArray(1); glBindVertexArray(0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); unsigned int containerTex; glGenTextures(1, &containerTex); glBindTexture(GL_TEXTURE_2D, containerTex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); int width, height, channels; unsigned char *data = stbi_load("assets/container.jpg", &width, &height, &channels, 0); if (data == nullptr) { LOG_E("Failed to load image: %s", "assets/container.jpg"); glfwTerminate(); return -1; } glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); stbi_image_free(data); unsigned int faceTex; glGenTextures(1, &faceTex); glBindTexture(GL_TEXTURE_2D, faceTex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); data = stbi_load("assets/awesomeface.png", &width, &height, &channels, 0); if (data == nullptr) { LOG_E("Failed to load image: %s", "assets/awesomeface.png"); glfwTerminate(); return -1; } glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); stbi_image_free(data); data = nullptr; auto shader = new Shader("shaders/getting_started/07/shader.vs", "shaders/getting_started/07/shader.fs"); while (!glfwWindowShouldClose(window)) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) { LOG_I("Escape pressed, exiting."); glfwSetWindowShouldClose(window, GLFW_TRUE); } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); if (!shader->Use()) { break; } glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, containerTex); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, faceTex); shader->SetInt("texture0", 0); shader->SetInt("texture1", 1); glm::mat4 trans = glm::mat4(1.0f); trans = glm::translate(trans, glm::vec3(0.5f, -0.5f, 0.0f)); trans = glm::rotate(trans, static_cast<float>(glfwGetTime()), glm::vec3(0.0f, 0.0f, 1.0f)); shader->SetMatrix4("uTransform", glm::value_ptr(trans)); glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void *)0); glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return 0; } } // namespace transforms } // namespace getting_started
39.308642
117
0.555905
clsrfish
63cefda5d102285b3898bed6274add241a813239
7,775
cpp
C++
tests/TestCircularBuffer.cpp
sarahkw/swgetf0
b3cae9290ed90063c98a9e770482de2c5944ec0e
[ "Apache-2.0" ]
5
2017-01-01T19:36:10.000Z
2019-11-07T03:40:32.000Z
tests/TestCircularBuffer.cpp
hobakurafuto/swgetf0
b3cae9290ed90063c98a9e770482de2c5944ec0e
[ "Apache-2.0" ]
null
null
null
tests/TestCircularBuffer.cpp
hobakurafuto/swgetf0
b3cae9290ed90063c98a9e770482de2c5944ec0e
[ "Apache-2.0" ]
1
2018-06-04T02:27:14.000Z
2018-06-04T02:27:14.000Z
/* Copyright 2014 Sarah Wong 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 "gtest/gtest.h" #include "gmock/gmock.h" #include "../CircularBuffer.h" using namespace testing; namespace { class TestCircularBuffer : public ::testing::Test { protected: TestCircularBuffer() : m_cb3(3), m_cb0(0) {} void SetUp() override {} void TearDown() override {} CircularBuffer<int> m_cb3; CircularBuffer<int> m_cb0; }; } TEST_F(TestCircularBuffer, ReadEmptyBuffer) { ASSERT_TRUE(m_cb3.begin() == m_cb3.end()); ASSERT_EQ(m_cb3.size(), 0); } TEST_F(TestCircularBuffer, ReadWithoutLoop) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.push_back(3); ASSERT_THAT(m_cb3, ElementsAre(1, 2, 3)); ASSERT_EQ(m_cb3.size(), 3); } TEST_F(TestCircularBuffer, ReadLoop) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.push_back(3); m_cb3.push_back(4); m_cb3.push_back(5); ASSERT_THAT(m_cb3, ElementsAre(3, 4, 5)); ASSERT_EQ(m_cb3.size(), 3); } TEST_F(TestCircularBuffer, ReadLoopTwiceWithIteratorWrite) { const int values[] = {1, 2, 3, 4, 5, 6, 7}; for (auto value : values) { m_cb3.push_back(value); } ASSERT_THAT(m_cb3, ElementsAre(5, 6, 7)); ASSERT_EQ(m_cb3.size(), 3); } TEST_F(TestCircularBuffer, ZeroWorkingSet) { ASSERT_TRUE(m_cb0.begin() == m_cb0.end()); m_cb0.push_back(0); ASSERT_TRUE(m_cb0.begin() == m_cb0.end()); } TEST_F(TestCircularBuffer, ExpandBlank) { m_cb3.resize(6); ASSERT_THAT(m_cb3, ElementsAre()); } TEST_F(TestCircularBuffer, ExpandNotFull) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.resize(6); ASSERT_THAT(m_cb3, ElementsAre(1, 2)); } TEST_F(TestCircularBuffer, ExpandFull) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.push_back(3); m_cb3.resize(6); ASSERT_THAT(m_cb3, ElementsAre(0, 0, 0, 1, 2, 3)); } TEST_F(TestCircularBuffer, ExpandOverflow1) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.push_back(3); m_cb3.push_back(4); m_cb3.resize(6); ASSERT_THAT(m_cb3, ElementsAre(0, 0, 0, 2, 3, 4)); } TEST_F(TestCircularBuffer, ExpandOverflow2) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.push_back(3); m_cb3.push_back(4); m_cb3.push_back(5); m_cb3.push_back(6); m_cb3.resize(6); ASSERT_THAT(m_cb3, ElementsAre(0, 0, 0, 4, 5, 6)); // Make sure it still works afterwards m_cb3.push_back(7); m_cb3.push_back(8); m_cb3.push_back(9); ASSERT_THAT(m_cb3, ElementsAre(4, 5, 6, 7, 8, 9)); m_cb3.push_back(10); ASSERT_THAT(m_cb3, ElementsAre(5, 6, 7, 8, 9, 10)); } TEST_F(TestCircularBuffer, ShrinkAllEmpty) { m_cb3.resize(0); ASSERT_THAT(m_cb3, ElementsAre()); ASSERT_EQ(m_cb3.size(), 0); // Use after m_cb3.push_back(0); ASSERT_THAT(m_cb3, ElementsAre()); ASSERT_EQ(m_cb3.size(), 0); } TEST_F(TestCircularBuffer, ShrinkAllFull) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.push_back(3); m_cb3.resize(0); ASSERT_EQ(m_cb3.size(), 0); ASSERT_THAT(m_cb3, ElementsAre()); m_cb3.push_back(3); ASSERT_EQ(m_cb3.size(), 0); ASSERT_THAT(m_cb3, ElementsAre()); } TEST_F(TestCircularBuffer, ShrinkAllOverflow) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.push_back(3); m_cb3.push_back(4); m_cb3.resize(0); ASSERT_EQ(m_cb3.size(), 0); ASSERT_THAT(m_cb3, ElementsAre()); m_cb3.push_back(3); ASSERT_EQ(m_cb3.size(), 0); ASSERT_THAT(m_cb3, ElementsAre()); } TEST_F(TestCircularBuffer, ShrinkAllPartial) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.resize(0); ASSERT_EQ(m_cb3.size(), 0); ASSERT_THAT(m_cb3, ElementsAre()); m_cb3.push_back(3); ASSERT_EQ(m_cb3.size(), 0); ASSERT_THAT(m_cb3, ElementsAre()); } TEST_F(TestCircularBuffer, ShrinkPartialEmpty) { m_cb3.resize(1); ASSERT_THAT(m_cb3, ElementsAre()); ASSERT_EQ(m_cb3.size(), 0); // Use after m_cb3.push_back(0); ASSERT_THAT(m_cb3, ElementsAre(0)); ASSERT_EQ(m_cb3.size(), 1); } TEST_F(TestCircularBuffer, ShrinkPartialNotFullNoLoss) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.resize(2); ASSERT_THAT(m_cb3, ElementsAre(1, 2)); ASSERT_EQ(m_cb3.size(), 2); // Use after m_cb3.push_back(3); ASSERT_THAT(m_cb3, ElementsAre(2, 3)); ASSERT_EQ(m_cb3.size(), 2); m_cb3.push_back(4); ASSERT_THAT(m_cb3, ElementsAre(3, 4)); ASSERT_EQ(m_cb3.size(), 2); } TEST_F(TestCircularBuffer, ShrinkPartialNotFullWithLoss) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.resize(1); ASSERT_THAT(m_cb3, ElementsAre(2)); ASSERT_EQ(m_cb3.size(), 1); // Use after m_cb3.push_back(3); m_cb3.push_back(4); m_cb3.push_back(5); ASSERT_THAT(m_cb3, ElementsAre(5)); ASSERT_EQ(m_cb3.size(), 1); m_cb3.push_back(6); m_cb3.push_back(7); ASSERT_THAT(m_cb3, ElementsAre(7)); ASSERT_EQ(m_cb3.size(), 1); } TEST_F(TestCircularBuffer, ShrinkPartialFull) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.push_back(3); m_cb3.resize(1); ASSERT_THAT(m_cb3, ElementsAre(3)); ASSERT_EQ(m_cb3.size(), 1); // Use after m_cb3.push_back(4); m_cb3.push_back(5); ASSERT_THAT(m_cb3, ElementsAre(5)); ASSERT_EQ(m_cb3.size(), 1); } TEST_F(TestCircularBuffer, ShrinkPartialOverflow) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.push_back(3); m_cb3.push_back(4); m_cb3.resize(2); ASSERT_EQ(m_cb3.size(), 2); ASSERT_THAT(m_cb3, ElementsAre(3, 4)); m_cb3.push_back(5); ASSERT_EQ(m_cb3.size(), 2); ASSERT_THAT(m_cb3, ElementsAre(4, 5)); m_cb3.push_back(6); ASSERT_EQ(m_cb3.size(), 2); ASSERT_THAT(m_cb3, ElementsAre(5, 6)); } TEST_F(TestCircularBuffer, ShrinkPartialOverflow2) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.push_back(3); m_cb3.push_back(4); m_cb3.push_back(5); m_cb3.resize(1); ASSERT_EQ(m_cb3.size(), 1); ASSERT_THAT(m_cb3, ElementsAre(5)); m_cb3.push_back(7); ASSERT_EQ(m_cb3.size(), 1); ASSERT_THAT(m_cb3, ElementsAre(7)); m_cb3.push_back(8); ASSERT_EQ(m_cb3.size(), 1); ASSERT_THAT(m_cb3, ElementsAre(8)); } TEST_F(TestCircularBuffer, ShrinkExpandFull) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.push_back(3); m_cb3.resize(1); m_cb3.resize(2); ASSERT_THAT(m_cb3, ElementsAre(0, 3)); ASSERT_EQ(m_cb3.size(), 2); } TEST_F(TestCircularBuffer, ShrinkExpandFullWrap) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.push_back(3); m_cb3.push_back(4); m_cb3.push_back(5); m_cb3.resize(1); m_cb3.resize(3); ASSERT_EQ(m_cb3.size(), 3); ASSERT_THAT(m_cb3, ElementsAre(0, 0, 5)); } TEST_F(TestCircularBuffer, ShrinkExpandNotFull) { m_cb3.push_back(1); m_cb3.resize(2); m_cb3.resize(3); ASSERT_THAT(m_cb3, ElementsAre(1)); ASSERT_EQ(m_cb3.size(), 1); } TEST_F(TestCircularBuffer, ShrinkExpandNotFullBecomeFull) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.resize(2); ASSERT_EQ(m_cb3.size(), 2); m_cb3.resize(3); ASSERT_EQ(m_cb3.size(), 3); ASSERT_THAT(m_cb3, ElementsAre(0, 1, 2)); } TEST_F(TestCircularBuffer, ExpandZeroSize) { m_cb0.push_back(1); m_cb0.resize(3); ASSERT_THAT(m_cb0, ElementsAre(0, 0, 0)); ASSERT_EQ(m_cb0.size(), 3); // Still works? m_cb0.push_back(2); ASSERT_THAT(m_cb0, ElementsAre(0, 0, 2)); ASSERT_EQ(m_cb0.size(), 3); m_cb0.push_back(3); m_cb0.push_back(4); m_cb0.push_back(5); ASSERT_THAT(m_cb0, ElementsAre(3, 4, 5)); ASSERT_EQ(m_cb0.size(), 3); }
20.900538
74
0.696206
sarahkw
63cff69a8ca44a68d1fbd5e7db83195bf6335ee8
128,979
hpp
C++
test/TestChemicalChaste.hpp
OSS-Lab/ChemChaste
d32c36afa1cd870512fee3cba0753d5c6faf8109
[ "BSD-3-Clause" ]
null
null
null
test/TestChemicalChaste.hpp
OSS-Lab/ChemChaste
d32c36afa1cd870512fee3cba0753d5c6faf8109
[ "BSD-3-Clause" ]
null
null
null
test/TestChemicalChaste.hpp
OSS-Lab/ChemChaste
d32c36afa1cd870512fee3cba0753d5c6faf8109
[ "BSD-3-Clause" ]
null
null
null
#ifndef TESTCHEMICALCHASTE_HPP_ #define TESTCHEMICALCHASTE_HPP_ // chaste includes #include <cxxtest/TestSuite.h> #include "UblasIncludes.hpp" #include "AbstractCellBasedTestSuite.hpp" #include "CheckpointArchiveTypes.hpp" #include "PetscSetupAndFinalize.hpp" #include "SmartPointers.hpp" // general includes #include <iostream> #include <fstream> #include <string> #include <vector> #include <tuple> #include <cmath> // chemical includes #include "AbstractChemical.hpp" #include "AbstractDiffusiveChemical.hpp" #include "AbstractChemistry.hpp" #include "AbstractDiffusiveChemistry.hpp" // reaction-diffusion includes #include "AbstractReaction.hpp" #include "AbstractReversibleReaction.hpp" #include "AbstractReactionSystem.hpp" #include "MassActionReaction.hpp" #include "AbstractReactionSystemFromFile.hpp" #include "ReactionTypeDatabase.hpp" // chaste PdeOde includes #include "HoneycombMeshGenerator.hpp" #include "EulerIvpOdeSolver.hpp" #include "LinearParabolicPdeSystemWithCoupledOdeSystemSolver.hpp" #include "BoundaryConditionsContainer.hpp" #include "ConstBoundaryCondition.hpp" #include "OutputFileHandler.hpp" #include "RandomNumberGenerator.hpp" #include "TrianglesMeshReader.hpp" // custom pdeOde includes #include "PdeSchnackenbergCoupledPdeOdeSystem.hpp" #include "OdeSchnackenbergCoupledPdeOdeSystem.hpp" #include "PdeConsumerProducer.hpp" #include "OdeConsumerProducer.hpp" #include "AbstractChemicalOdeSystem.hpp" #include "AbstractChemicalOdeForCoupledPdeSystem.hpp" // CHASTE Spheroid includes #include "SimpleOxygenBasedCellCycleModel.hpp" #include "WildTypeCellMutationState.hpp" #include "StemCellProliferativeType.hpp" #include "CellwiseSourceEllipticPde.hpp" #include "ConstBoundaryCondition.hpp" #include "EllipticGrowingDomainPdeModifier.hpp" #include "OffLatticeSimulation.hpp" #include "GeneralisedLinearSpringForce.hpp" #include "SchnackenbergCoupledPdeSystem.hpp" class TestChemicalChaste : public AbstractCellBasedTestSuite { public: void TestChemicalClass() { std::cout<<"-----------------------------"<<std::endl; std::cout<<"Chemical"<<std::endl; AbstractChemical *p_chemical = new AbstractChemical("A"); AbstractDiffusiveChemical *p_chemical_diffusive = new AbstractDiffusiveChemical("B"); p_chemical_diffusive -> AddDiffusiveDomain("test",1.0); std::cout<<"Name: "<<p_chemical ->GetChemicalName() <<std::endl; std::cout<<"Type: "<<p_chemical ->GetChemicalType() <<std::endl; std::cout<<"Name: "<<p_chemical_diffusive ->GetChemicalName() <<std::endl; std::cout<<"Type: "<<p_chemical_diffusive ->GetChemicalType() <<std::endl; std::cout<<"Diffusivity: "<<p_chemical_diffusive ->GetDiffusiveDomainVector()[0] <<std::endl; // vectorise the pointers std::cout<<"Chemical vector"<<std::endl; std::vector<AbstractChemical*> p_chemicalVector; // implicit upcasting p_chemicalVector.push_back(p_chemical); p_chemicalVector.push_back(p_chemical_diffusive); std::cout<<p_chemicalVector[0] -> GetChemicalType() <<std::endl; std::cout<<p_chemicalVector[1] -> GetChemicalType() <<std::endl; // get the diffusive value for [1] std::cout<<"dynamic casting"<<std::endl; AbstractDiffusiveChemical *p_chemical_diffusive_2 = dynamic_cast<AbstractDiffusiveChemical*>(p_chemicalVector[1]); std::cout<<p_chemical_diffusive_2 -> GetChemicalDiffusivityVector()[0] <<std::endl; } void TestChemistryClass() { std::cout<<"-----------------------------"<<std::endl; std::cout<<"Abstract chemistry"<<std::endl; unsigned Number_of_species =2; std::vector<std::string> ChemicalNames = {"U", "V"}; std::vector<double> DiffusionRates = {1.0, 2.0}; std::vector<bool> IsDiffusing = {true, true}; std::vector<std::string> DiffusionDomains = {"Bulk", "Bulk"}; AbstractChemistry* p_chemistry = new AbstractChemistry(); for(unsigned species=0; species<Number_of_species; species++) { AbstractChemical *p_chemical = new AbstractChemical(ChemicalNames[species]); p_chemistry -> AddChemical(p_chemical); } std::vector<std::string> ChemNames = p_chemistry -> GetChemicalNames(); std::cout<<"Chemical names: "<<std::endl; for(unsigned i=0; i<Number_of_species; i++) { std::cout<<ChemNames[i]<<std::endl; } std::cout<<"Abstract diffusive chemistry"<<std::endl; std::vector<std::string> ChemicalNamesDiffusive = {"Ud", "Vd"}; AbstractDiffusiveChemistry* p_diffusive_chemistry = new AbstractDiffusiveChemistry(); for(unsigned species=0; species<Number_of_species; species++) { AbstractDiffusiveChemical *p_chemical = new AbstractDiffusiveChemical(ChemicalNamesDiffusive[species]); p_chemical -> AddDiffusiveDomain(DiffusionDomains[species],DiffusionRates[species]); p_diffusive_chemistry -> AddChemical(p_chemical); } std::cout<<"Chemical diffusivities: "<<std::endl; for(unsigned i=0; i<Number_of_species; i++) { std::cout<<p_diffusive_chemistry -> GetChemicalNamesByIndex(i)<<std::endl; std::cout<<p_diffusive_chemistry -> GetDiffusivityVectorByIndex(i)[0]<<std::endl; } std::cout<<"Add chemistries"<<std::endl; // upcast AbstractDiffusiveChemistry to AbstractChemistry // maybe need to template this function? currently add to the highest class to avoid object splicing AbstractChemistry *p_newChemistry = dynamic_cast<AbstractChemistry*>(p_diffusive_chemistry); p_chemistry -> AddChemistry(p_newChemistry); std::vector<std::string> ChemistryNames = p_chemistry -> GetChemicalNames(); for(unsigned i=0; i<Number_of_species; i++) { std::cout<<ChemistryNames[i]<<std::endl; } std::cout<<"Add diffusive chemistries"<<std::endl; // upcast AbstractDiffusiveChemistry to AbstractChemistry // maybe need to template this function? currently add to the highest class to avoid object splicing AbstractDiffusiveChemistry *p_newDiffusiveChemistry = new AbstractDiffusiveChemistry(); std::vector<std::string> NewChemicalNamesDiffusive = {"Ud", "Y"}; std::vector<double> NewDiffusionRates = {3,4}; for(unsigned species=0; species<Number_of_species; species++) { AbstractDiffusiveChemical *p_chemical = new AbstractDiffusiveChemical(NewChemicalNamesDiffusive[species]); p_chemical -> AddDiffusiveDomain(DiffusionDomains[species],NewDiffusionRates[species]); p_newDiffusiveChemistry -> AddChemical(p_chemical); //shouldn't add the first species Ud as is a duplicate of name and domain } p_diffusive_chemistry -> AddChemistry(p_newDiffusiveChemistry); std::cout<<"Number of chemicals: "<<p_diffusive_chemistry ->GetNumberChemicals()<<std::endl; std::cout<<"Number of diffusive chemicals: "<<p_diffusive_chemistry ->GetNumberDiffusiveChemicals()<<std::endl; for(unsigned i=0; i<4; i++) { std::cout<<p_diffusive_chemistry -> GetChemicalNamesByIndex(i)<<std::endl; std::cout<<p_diffusive_chemistry -> GetDiffusivityValueByChemicalName(p_diffusive_chemistry -> GetChemicalNamesByIndex(i))<<std::endl; } } void TestReactionClass() { std::cout<<"-----------------------------"<<std::endl; std::cout<<"Chemical information"<<std::endl; unsigned Number_of_species =2; std::vector<std::string> ChemicalNames = {"U", "V"}; std::vector<double> DiffusionRates = {1.0, 2.0}; std::vector<bool> IsDiffusing = {true, true}; std::vector<std::string> DiffusionDomains = {"Bulk", "Bulk"}; std::cout<<"Form chemical vector"<<std::endl; std::vector<AbstractChemical*> p_chemicalVector; for(unsigned species=0; species<Number_of_species; species++) { if(IsDiffusing[species]) { // use the diffusive chemical root AbstractDiffusiveChemical *p_chemical = new AbstractDiffusiveChemical(ChemicalNames[species]); p_chemical -> AddDiffusiveDomain(DiffusionDomains[species],DiffusionRates[species]); p_chemicalVector.push_back(p_chemical); }else{ // use the non-diffusive chemical root AbstractChemical *p_chemical = new AbstractChemical(ChemicalNames[species]); p_chemicalVector.push_back(p_chemical); } } // check iterating through the chemical vector works, need dynamic casting of the iterator for (std::vector<AbstractChemical*>::iterator chem_iter = p_chemicalVector.begin(); chem_iter != p_chemicalVector.end(); ++chem_iter) { std::string ChemicalName = "NA"; double Diffusivity = 0.0; std::string Domain = "None"; AbstractChemical *p_2 = dynamic_cast<AbstractChemical*>(*chem_iter); if( p_2 -> GetChemicalType() == "AbstractDiffusiveChemical") { AbstractDiffusiveChemical *p_chemical = dynamic_cast<AbstractDiffusiveChemical*>(*chem_iter); ChemicalName = p_chemical -> GetChemicalName(); Diffusivity = p_chemical -> GetChemicalDiffusivityVector()[0]; Domain = p_chemical -> GetDiffusiveDomainVector()[0]; } std::cout<<"Name: "<<ChemicalName<<std::endl; std::cout<<"Diffusivity: "<<Diffusivity<<std::endl; std::cout<<"Domain: "<<Domain<<std::endl; delete p_2; } std::cout<<"Schnackenberg Chemistry"<<std::endl; // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 AbstractChemistry* p_system_chemistry = new AbstractChemistry(); std::vector<AbstractChemical*> p_substrates_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_3 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_3 = std::vector<AbstractChemical*>(); std::vector<unsigned> stoich_substrates_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_3 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_3 = std::vector<unsigned>(); // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 AbstractChemical *p_chemical_U = new AbstractChemical("U"); p_system_chemistry -> AddChemical(p_chemical_U); // add U to reactions p_substrates_1.push_back(p_chemical_U); stoich_substrates_1.push_back(2); p_products_1.push_back(p_chemical_U); stoich_products_1.push_back(3); p_products_2.push_back(p_chemical_U); stoich_products_2.push_back(1); AbstractChemical *p_chemical_V = new AbstractChemical("V"); p_system_chemistry -> AddChemical(p_chemical_V); // add U to reactions p_substrates_1.push_back(p_chemical_V); stoich_substrates_1.push_back(1); p_products_3.push_back(p_chemical_V); stoich_products_3.push_back(1); double reaction_1_rate = 0.1; double reaction_2_forward_rate = 0.1; double reaction_2_reverse_rate = 0.2; double reaction_3_rate = 0.3; AbstractReaction* p_reaction_1 = new AbstractReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,reaction_1_rate); AbstractReversibleReaction* p_reaction_2 = new AbstractReversibleReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,reaction_2_forward_rate, reaction_2_reverse_rate); AbstractReaction* p_reaction_3 = new AbstractReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,reaction_3_rate); // concentration vector std::vector<double> concentration_vector= {1.0,1.0}; std::vector<double> change_concentration_vector= {0.0,0.0}; std::cout<<"Starting conditions"<<std::endl; std::cout<<"Concentration (U,V): "<<concentration_vector[0]<<" "<<concentration_vector[1]<<std::endl; std::cout<<"Concentration change (U,V): "<<change_concentration_vector[0]<<" "<<change_concentration_vector[1]<<std::endl; std::cout<<"============================"<<std::endl; std::cout<<"r1: 2U + V -> 3U forwardRate = "<<reaction_1_rate<<std::endl; change_concentration_vector= {0.0,0.0}; p_reaction_1 -> React(p_system_chemistry,concentration_vector,change_concentration_vector); //concentration_vector[0] = concentration_vector[0] + change_concentration_vector[0]; //concentration_vector[1] = concentration_vector[1] + change_concentration_vector[1]; std::cout<<"Concentration (U,V): "<<concentration_vector[0]<<" "<<concentration_vector[1]<<std::endl; std::cout<<"Concentration change (U,V): "<<change_concentration_vector[0]<<" "<<change_concentration_vector[1]<<std::endl; std::cout<<"============================"<<std::endl; std::cout<<"r2: 0 <-> U forwardRate = "<<reaction_2_forward_rate<<" reverseRate = "<<reaction_2_reverse_rate<<std::endl; change_concentration_vector= {0.0,0.0}; p_reaction_2 -> React(p_system_chemistry,concentration_vector,change_concentration_vector); //concentration_vector[0] = concentration_vector[0] + change_concentration_vector[0]; //concentration_vector[1] = concentration_vector[1] + change_concentration_vector[1]; std::cout<<"Concentration (U,V): "<<concentration_vector[0]<<" "<<concentration_vector[1]<<std::endl; std::cout<<"Concentration change (U,V): "<<change_concentration_vector[0]<<" "<<change_concentration_vector[1]<<std::endl; std::cout<<"============================"<<std::endl; std::cout<<"r3: 0 -> V forwardRate = "<<reaction_3_rate<<std::endl; change_concentration_vector= {0.0,0.0}; p_reaction_3 -> React(p_system_chemistry,concentration_vector,change_concentration_vector); //concentration_vector[0] = concentration_vector[0] + change_concentration_vector[0]; //concentration_vector[1] = concentration_vector[1] + change_concentration_vector[1]; std::cout<<"Concentration (U,V): "<<concentration_vector[0]<<" "<<concentration_vector[1]<<std::endl; std::cout<<"Concentration change (U,V): "<<change_concentration_vector[0]<<" "<<change_concentration_vector[1]<<std::endl; // form reaction system std::cout<<"Form reaction system: "<<std::endl; concentration_vector= {1.0,1.0}; change_concentration_vector= {0.0,0.0}; std::vector<AbstractReaction*> p_reaction_vector_1; p_reaction_vector_1.push_back(p_reaction_1); AbstractReactionSystem* p_reaction_system_1 = new AbstractReactionSystem(p_system_chemistry, p_reaction_vector_1); p_reaction_system_1 -> ReactSystem(concentration_vector,change_concentration_vector); std::cout<<"============================"<<std::endl; std::cout<<"r1: 2U + V -> 3U forwardRate = "<<reaction_1_rate<<std::endl; std::cout<<"Concentration (U,V): "<<concentration_vector[0]<<" "<<concentration_vector[1]<<std::endl; std::cout<<"Concentration change (U,V): "<<change_concentration_vector[0]<<" "<<change_concentration_vector[1]<<std::endl; // form mixed reaction system (AbstractReaction, AbstractReversibleReaction, AbstractReaction) concentration_vector= {1.0,1.0}; change_concentration_vector= {0.0,0.0}; std::vector<AbstractReaction*> p_reaction_vector_2; p_reaction_vector_2.push_back(p_reaction_1); p_reaction_vector_2.push_back(p_reaction_2); p_reaction_vector_2.push_back(p_reaction_3); AbstractReactionSystem* p_reaction_system_2 = new AbstractReactionSystem(p_system_chemistry, p_reaction_vector_2); p_reaction_system_2 -> ReactSystem(concentration_vector,change_concentration_vector); std::cout<<"Concentration (U,V): "<<concentration_vector[0]<<" "<<concentration_vector[1]<<std::endl; std::cout<<"Concentration change (U,V): "<<change_concentration_vector[0]<<" "<<change_concentration_vector[1]<<std::endl; for(unsigned i=0; i<p_reaction_system_2 -> GetNumberOfReactions(); i++) { std::cout<<"Reaction type: "<<i<<" "<< p_reaction_system_2 -> GetReactionByIndex(i) -> GetReactionType()<<std::endl; } } void TestMassActionReactionClass() { std::cout<<"-----------------------------"<<std::endl; AbstractChemistry* p_system_chemistry = new AbstractChemistry(); std::vector<AbstractChemical*> p_substrates_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_3 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_3 = std::vector<AbstractChemical*>(); std::vector<unsigned> stoich_substrates_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_3 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_3 = std::vector<unsigned>(); // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 AbstractChemical *p_chemical_U = new AbstractChemical("U"); p_system_chemistry -> AddChemical(p_chemical_U); // add U to reactions p_substrates_1.push_back(p_chemical_U); stoich_substrates_1.push_back(2); p_products_1.push_back(p_chemical_U); stoich_products_1.push_back(3); p_products_2.push_back(p_chemical_U); stoich_products_2.push_back(1); AbstractChemical *p_chemical_V = new AbstractChemical("V"); p_system_chemistry -> AddChemical(p_chemical_V); // add U to reactions p_substrates_1.push_back(p_chemical_V); stoich_substrates_1.push_back(1); p_products_3.push_back(p_chemical_V); stoich_products_3.push_back(1); double reaction_1_rate = 0.1; double reaction_2_forward_rate = 0.1; double reaction_2_reverse_rate = 0.2; double reaction_3_rate = 0.3; MassActionReaction* p_reaction_1 = new MassActionReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,false,false,reaction_1_rate); MassActionReaction* p_reaction_2 = new MassActionReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,false, true, reaction_2_forward_rate, reaction_2_reverse_rate); MassActionReaction* p_reaction_3 = new MassActionReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,false, false,reaction_3_rate); // concentration vector std::vector<double> concentration_vector= {1.0,1.0}; std::vector<double> change_concentration_vector= {0.0,0.0}; std::cout<<"Mass action kinetics"<<std::endl; std::cout<<"Starting conditions"<<std::endl; std::cout<<"Concentration (U,V): "<<concentration_vector[0]<<" "<<concentration_vector[1]<<std::endl; std::cout<<"Concentration change (U,V): "<<change_concentration_vector[0]<<" "<<change_concentration_vector[1]<<std::endl; std::cout<<"============================"<<std::endl; std::cout<<"r1: 2U + V -> 3U forwardRate = "<<reaction_1_rate<<std::endl; change_concentration_vector= {0.0,0.0}; p_reaction_1 -> React(p_system_chemistry,concentration_vector,change_concentration_vector); std::cout<<"Concentration (U,V): "<<concentration_vector[0]<<" "<<concentration_vector[1]<<std::endl; std::cout<<"Concentration change (U,V): "<<change_concentration_vector[0]<<" "<<change_concentration_vector[1]<<std::endl; std::cout<<"============================"<<std::endl; std::cout<<"r2: 0 <-> U forwardRate = "<<reaction_2_forward_rate<<" reverseRate = "<<reaction_2_reverse_rate<<std::endl; change_concentration_vector= {0.0,0.0}; p_reaction_2 -> React(p_system_chemistry,concentration_vector,change_concentration_vector); std::cout<<"Concentration (U,V): "<<concentration_vector[0]<<" "<<concentration_vector[1]<<std::endl; std::cout<<"Concentration change (U,V): "<<change_concentration_vector[0]<<" "<<change_concentration_vector[1]<<std::endl; std::cout<<"============================"<<std::endl; std::cout<<"r3: 0 -> V forwardRate = "<<reaction_3_rate<<std::endl; change_concentration_vector= {0.0,0.0}; p_reaction_3 -> React(p_system_chemistry,concentration_vector,change_concentration_vector); std::cout<<"Concentration (U,V): "<<concentration_vector[0]<<" "<<concentration_vector[1]<<std::endl; std::cout<<"Concentration change (U,V): "<<change_concentration_vector[0]<<" "<<change_concentration_vector[1]<<std::endl; // form mixed mass action reaction system std::cout<<"============================"<<std::endl; std::cout<<"Form mass action reaction sysstem"<<std::endl; std::cout<<"============================"<<std::endl; concentration_vector= {1.0,1.0}; change_concentration_vector= {0.0,0.0}; std::vector<AbstractReaction*> p_mass_action_reaction_vector; p_mass_action_reaction_vector.push_back(p_reaction_1); p_mass_action_reaction_vector.push_back(p_reaction_2); p_mass_action_reaction_vector.push_back(p_reaction_3); AbstractReactionSystem* p_mass_action_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_mass_action_reaction_vector); p_mass_action_reaction_system -> ReactSystem(concentration_vector,change_concentration_vector); std::cout<<"Concentration (U,V): "<<concentration_vector[0]<<" "<<concentration_vector[1]<<std::endl; std::cout<<"Concentration change (U,V): "<<change_concentration_vector[0]<<" "<<change_concentration_vector[1]<<std::endl; for(unsigned i=0; i<p_mass_action_reaction_system -> GetNumberOfReactions(); i++) { std::cout<<"Reaction type: "<<i<<" "<< p_mass_action_reaction_system -> GetReactionByIndex(i) -> GetReactionType()<<std::endl; } } void TestSpatialPdeOdeSolver() { /* std::cout<<"SchnackenbergCoupledPdeOdeSystem"<<std::endl; // system properties const unsigned probDim =2; const unsigned spaceDim=2; const unsigned elementDim=2; std::vector<double> initValues = {2.0, 0.75}; std::vector<double> bcValues = {2.0, 0.75}; // mesh HoneycombMeshGenerator generator(10, 10, 0); MutableMesh<elementDim,spaceDim>* p_mesh = generator.GetMesh(); // Process Boundary Conditions std::cout<<"Process Boundary Conditions"<<std::endl; BoundaryConditionsContainer<elementDim,spaceDim,probDim> bcc; std::vector<bool> areNeumannBoundaryConditions(probDim, false); std::vector<ConstBoundaryCondition<spaceDim>*> vectorConstBCs; for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++){ vectorConstBCs.push_back(new ConstBoundaryCondition<spaceDim>(bcValues[pdeDim])); } for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { if(areNeumannBoundaryConditions[pdeDim]==false) { for (TetrahedralMesh<elementDim,spaceDim>::BoundaryNodeIterator node_iter = p_mesh->GetBoundaryNodeIteratorBegin(); node_iter != p_mesh->GetBoundaryNodeIteratorEnd(); ++node_iter) { bcc.AddDirichletBoundaryCondition(*node_iter, vectorConstBCs[pdeDim], pdeDim); } }else{ for (TetrahedralMesh<elementDim,spaceDim>::BoundaryElementIterator boundary_iter = p_mesh->GetBoundaryElementIteratorBegin(); boundary_iter != p_mesh->GetBoundaryElementIteratorEnd(); boundary_iter++) { bcc.AddNeumannBoundaryCondition(*boundary_iter, vectorConstBCs[pdeDim], pdeDim); } } } std::cout<<"Initial conditions"<<std::endl; // initial conditions std::vector<double> init_conds(probDim*p_mesh->GetNumNodes()); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { // set as being a random perturbation about the boundary values for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { // serialised for nodes init_conds[probDim*i + pdeDim] = fabs(initValues[pdeDim] + RandomNumberGenerator::Instance()->ranf()); } } // PETSc Vec std::cout<<"PETSc Vec"<<std::endl; Vec initial_condition = PetscTools::CreateVec(init_conds); // pde system std::cout<<"Pde"<<std::endl; PdeSchnackenbergCoupledPdeOdeSystem<elementDim, spaceDim, probDim> pde(1e-4, 1e-2); // coupled ode system std::cout<<"Ode loop"<<std::endl; std::vector<AbstractOdeSystemForCoupledPdeSystem*> odeSystem; for (unsigned i=0; i<p_mesh->GetNumNodes(); i++){ // number of ode system objects must match the number of nodes, i.e the individual odes may be multi-dimensional if(i==22 || i==77) { odeSystem.push_back(new OdeSchnackenbergCoupledPdeOdeSystem(0.1, 0.2, 0.3, 0.1)); }else if(i==27 || i==72) { odeSystem.push_back(new OdeSchnackenbergCoupledPdeOdeSystem(0.1, 0.2, 0.3, 0.1)); }else{ odeSystem.push_back(new OdeSchnackenbergCoupledPdeOdeSystem(0.1, 0.2, 0.3, 0.1)); } } std::cout<<"Number odesAtNodes: "<<p_mesh->GetNumNodes()<<std::endl; // used the explicitly defined EulerIvpOdeSolver rather than the default defined BackwardEuler method //EulerIvpOdeSolver euler_solver; boost::shared_ptr<EulerIvpOdeSolver> p_solver(new EulerIvpOdeSolver); std::cout<<"Solver"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver(p_mesh, &pde, &bcc, odeSystem, p_solver); // solver properties double t_end = 10; solver.SetTimes(0, t_end); solver.SetTimeStep(1e-2); solver.SetSamplingTimeStep(1e-2); solver.SetOutputDirectory("TestVectorisedSchnackenbergOutput_correct_ks"); solver.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; // clean PetscTools::Destroy(initial_condition); */ } void TestSpatialConsumerProducerSolver() { /* std::cout<<"ConsumerProducer"<<std::endl; // reaction system involving two species, A and B // 0 -> A rateConstant = k1 // B -> 0 rateConstant = k2 // A <-> B rateConstantForward = k3 rateConstantReverse = k_3 // A diffuses at rate Da // B diffuses at rate Db // nodal ode of the form: OdeConsumerProducer(k1, k2, k3, k4) // with nodes 22, 27, 72, 77 selected forming corners of a square domain offset from the boundary double Da = 1e-1; double Db = 5e-2; // system properties const unsigned probDim =2; const unsigned spaceDim=2; const unsigned elementDim=2; std::vector<double> initValues = {0, 0}; std::vector<double> bcValues = {0, 0}; // mesh HoneycombMeshGenerator generator(10, 10, 0); MutableMesh<elementDim,spaceDim>* p_mesh = generator.GetMesh(); // Process Boundary Conditions std::cout<<"Process Boundary Conditions"<<std::endl; BoundaryConditionsContainer<elementDim,spaceDim,probDim> bcc; std::vector<bool> areNeumannBoundaryConditions(probDim, false); std::vector<ConstBoundaryCondition<spaceDim>*> vectorConstBCs; for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++){ vectorConstBCs.push_back(new ConstBoundaryCondition<spaceDim>(bcValues[pdeDim])); } for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { if(areNeumannBoundaryConditions[pdeDim]==false) { for (TetrahedralMesh<elementDim,spaceDim>::BoundaryNodeIterator node_iter = p_mesh->GetBoundaryNodeIteratorBegin(); node_iter != p_mesh->GetBoundaryNodeIteratorEnd(); ++node_iter) { bcc.AddDirichletBoundaryCondition(*node_iter, vectorConstBCs[pdeDim], pdeDim); } }else{ for (TetrahedralMesh<elementDim,spaceDim>::BoundaryElementIterator boundary_iter = p_mesh->GetBoundaryElementIteratorBegin(); boundary_iter != p_mesh->GetBoundaryElementIteratorEnd(); boundary_iter++) { bcc.AddNeumannBoundaryCondition(*boundary_iter, vectorConstBCs[pdeDim], pdeDim); } } } std::cout<<"Initial conditions"<<std::endl; // initial conditions std::vector<double> init_conds(probDim*p_mesh->GetNumNodes()); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { // set as being a random perturbation about the boundary values for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { // serialised for nodes init_conds[probDim*i + pdeDim] = initValues[pdeDim] ;//fabs(initValues[pdeDim] + RandomNumberGenerator::Instance()->ranf()); } } // PETSc Vec std::cout<<"PETSc Vec"<<std::endl; Vec initial_condition = PetscTools::CreateVec(init_conds); // pde system std::cout<<"Pde"<<std::endl; PdeConsumerProducer<elementDim, spaceDim, probDim> pde(Da, Db); // coupled ode system std::cout<<"Ode loop"<<std::endl; std::vector<AbstractOdeSystemForCoupledPdeSystem*> odeSystem; for (unsigned i=0; i<p_mesh->GetNumNodes(); i++){ // number of ode system objects must match the number of nodes, i.e the individual odes may be multi-dimensional if(i==22) { odeSystem.push_back(new OdeConsumerProducer(1, 0, 0, 0)); }else if(i==77) { odeSystem.push_back(new OdeConsumerProducer(0, 1, 0, 0)); }else{ odeSystem.push_back(new OdeConsumerProducer(0, 0, 0.1, 0)); } } std::cout<<"Number odesAtNodes: "<<p_mesh->GetNumNodes()<<std::endl; // used the explicitly defined EulerIvpOdeSolver rather than the default defined BackwardEuler method //EulerIvpOdeSolver euler_solver; boost::shared_ptr<EulerIvpOdeSolver> p_solver(new EulerIvpOdeSolver); std::cout<<"Solver"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver(p_mesh, &pde, &bcc, odeSystem, p_solver); // solver properties double t_end = 10; solver.SetTimes(0, t_end); solver.SetTimeStep(1e-2); solver.SetSamplingTimeStep(1e-2); solver.SetOutputDirectory("TestConsumerProducerOutput_1"); solver.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; // clean PetscTools::Destroy(initial_condition); */ } void TestChemicalOde() { /* std::cout<<"Mass action kinetics of Schnackenberg using the AbstractChemicalOdeSystem Class"<<std::endl; std::cout<<"-----------------------------"<<std::endl; // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 AbstractChemistry* p_system_chemistry = new AbstractChemistry(); std::vector<AbstractChemical*> p_substrates_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_3 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_3 = std::vector<AbstractChemical*>(); std::vector<unsigned> stoich_substrates_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_3 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_3 = std::vector<unsigned>(); AbstractChemical *p_chemical_U = new AbstractChemical("U"); p_system_chemistry -> AddChemical(p_chemical_U); // add U to reactions p_substrates_1.push_back(p_chemical_U); stoich_substrates_1.push_back(2); p_products_1.push_back(p_chemical_U); stoich_products_1.push_back(3); p_products_2.push_back(p_chemical_U); stoich_products_2.push_back(1); AbstractChemical *p_chemical_V = new AbstractChemical("V"); p_system_chemistry -> AddChemical(p_chemical_V); // add U to reactions p_substrates_1.push_back(p_chemical_V); stoich_substrates_1.push_back(1); p_products_3.push_back(p_chemical_V); stoich_products_3.push_back(1); double reaction_1_rate = 0.1; double reaction_2_forward_rate = 0.1; double reaction_2_reverse_rate = 2; double reaction_3_rate = 0.3; AbstractReaction* p_reaction_1 = new AbstractReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,reaction_1_rate); AbstractReversibleReaction* p_reaction_2 = new AbstractReversibleReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,reaction_2_forward_rate, reaction_2_reverse_rate); AbstractReaction* p_reaction_3 = new AbstractReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,reaction_3_rate); std::vector<AbstractReaction*> p_reaction_vector; p_reaction_vector.push_back(p_reaction_1); p_reaction_vector.push_back(p_reaction_2); p_reaction_vector.push_back(p_reaction_3); MassActionReaction* p_Mass_action_reaction_1 = new MassActionReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,false,false,reaction_1_rate); MassActionReaction* p_Mass_action_reaction_2 = new MassActionReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,false, true, reaction_2_forward_rate, reaction_2_reverse_rate); MassActionReaction* p_Mass_action_reaction_3 = new MassActionReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,false, false,reaction_3_rate); std::vector<AbstractReaction*> p_mass_action_reaction_vector; p_mass_action_reaction_vector.push_back(p_Mass_action_reaction_1); p_mass_action_reaction_vector.push_back(p_Mass_action_reaction_2); p_mass_action_reaction_vector.push_back(p_Mass_action_reaction_3); AbstractReactionSystem* p_mass_action_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_mass_action_reaction_vector); AbstractChemicalOdeSystem chemicalOde(p_mass_action_reaction_system); EulerIvpOdeSolver euler_solver; std::vector<double> initial_condition = {1.0, 1.0}; OdeSolution solutions = euler_solver.Solve(&chemicalOde, initial_condition, 0, 1, 0.01, 0.1); for (unsigned i=0; i<solutions.rGetTimes().size(); i++) { std::cout << solutions.rGetTimes()[i] << " " << solutions.rGetSolutions()[i][0] << " " << solutions.rGetSolutions()[i][1]<< "\n"; } */ } void TestChemicalOdePde() { std::cout<<"Mass action kinetics of Schnackenberg using the AbstractChemicalOdeSystem Class"<<std::endl; std::cout<<"-----------------------------"<<std::endl; // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 AbstractChemistry* p_system_chemistry = new AbstractChemistry(); std::vector<AbstractChemical*> p_substrates_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_3 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_3 = std::vector<AbstractChemical*>(); std::vector<unsigned> stoich_substrates_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_3 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_3 = std::vector<unsigned>(); AbstractChemical *p_chemical_U = new AbstractChemical("U"); p_system_chemistry -> AddChemical(p_chemical_U); // add U to reactions p_substrates_1.push_back(p_chemical_U); stoich_substrates_1.push_back(2); p_products_1.push_back(p_chemical_U); stoich_products_1.push_back(3); p_products_2.push_back(p_chemical_U); stoich_products_2.push_back(1); AbstractChemical *p_chemical_V = new AbstractChemical("V"); p_system_chemistry -> AddChemical(p_chemical_V); // add V to reactions p_substrates_1.push_back(p_chemical_V); stoich_substrates_1.push_back(1); p_products_3.push_back(p_chemical_V); stoich_products_3.push_back(1); // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 double reaction_1_rate = 1.0; double reaction_2_forward_rate = 0.5; double reaction_2_reverse_rate = 2.2; double reaction_3_rate = 1.5; AbstractReaction* p_reaction_1 = new AbstractReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,reaction_1_rate); AbstractReversibleReaction* p_reaction_2 = new AbstractReversibleReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,reaction_2_forward_rate, reaction_2_reverse_rate); AbstractReaction* p_reaction_3 = new AbstractReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,reaction_3_rate); std::vector<AbstractReaction*> p_reaction_vector; p_reaction_vector.push_back(p_reaction_1); p_reaction_vector.push_back(p_reaction_2); p_reaction_vector.push_back(p_reaction_3); //AbstractReactionSystem* p_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_reaction_vector); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); MassActionReaction* p_mass_action_reaction_1 = new MassActionReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,false,false,reaction_1_rate); MassActionReaction* p_mass_action_reaction_2 = new MassActionReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,false, true, reaction_2_forward_rate, reaction_2_reverse_rate); MassActionReaction* p_mass_action_reaction_3 = new MassActionReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,false, false,reaction_3_rate); std::vector<AbstractReaction*> p_mass_action_reaction_vector; p_mass_action_reaction_vector.push_back(p_mass_action_reaction_1); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_2); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_3); AbstractReactionSystem* p_mass_action_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_mass_action_reaction_vector); // form ode system std::cout<<"SchnackenbergCoupledPdeOdeSystem -As AbstractChemicalODeSystem"<<std::endl; // system properties const unsigned probDim =2; const unsigned spaceDim=2; const unsigned elementDim=2; std::vector<double> initValues = {2.0, 0.75}; std::vector<double> bcValues = {0.0, 0.0}; // mesh HoneycombMeshGenerator generator(10, 10, 0); MutableMesh<elementDim,spaceDim>* p_mesh = generator.GetMesh(); // Process Boundary Conditions std::cout<<"Process Boundary Conditions"<<std::endl; BoundaryConditionsContainer<elementDim,spaceDim,probDim> bcc; std::vector<bool> areNeumannBoundaryConditions(probDim, true); std::vector<ConstBoundaryCondition<spaceDim>*> vectorConstBCs; for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++){ vectorConstBCs.push_back(new ConstBoundaryCondition<spaceDim>(bcValues[pdeDim])); } for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { if(areNeumannBoundaryConditions[pdeDim]==false) { for (TetrahedralMesh<elementDim,spaceDim>::BoundaryNodeIterator node_iter = p_mesh->GetBoundaryNodeIteratorBegin(); node_iter != p_mesh->GetBoundaryNodeIteratorEnd(); ++node_iter) { bcc.AddDirichletBoundaryCondition(*node_iter, vectorConstBCs[pdeDim], pdeDim); } }else{ for (TetrahedralMesh<elementDim,spaceDim>::BoundaryElementIterator boundary_iter = p_mesh->GetBoundaryElementIteratorBegin(); boundary_iter != p_mesh->GetBoundaryElementIteratorEnd(); boundary_iter++) { bcc.AddNeumannBoundaryCondition(*boundary_iter, vectorConstBCs[pdeDim], pdeDim); } } } std::cout<<"Initial conditions"<<std::endl; // initial conditions std::vector<double> init_conds(probDim*p_mesh->GetNumNodes()); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { // set as being a random perturbation about the boundary values for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { // serialised for nodes init_conds[probDim*i + pdeDim] = fabs(initValues[pdeDim] + RandomNumberGenerator::Instance()->ranf()); } } // PETSc Vec std::cout<<"PETSc Vec"<<std::endl; Vec initial_condition = PetscTools::CreateVec(init_conds); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); // coupled ode system std::cout<<"Ode loop"<<std::endl; std::vector<AbstractOdeSystemForCoupledPdeSystem*> odeSystem; for (unsigned i=0; i<p_mesh->GetNumNodes(); i++){ // number of ode system objects must match the number of nodes, i.e the individual odes may be multi-dimensional odeSystem.push_back(new AbstractChemicalOdeForCoupledPdeSystem(p_mass_action_reaction_system)); } std::cout<<"Number odesAtNodes: "<<p_mesh->GetNumNodes()<<std::endl; // pde system std::cout<<"Pde"<<std::endl; PdeSchnackenbergCoupledPdeOdeSystem<elementDim, spaceDim, probDim> pde(odeSystem[0],1e-4, 1e-2 ); // used the explicitly defined EulerIvpOdeSolver rather than the default defined BackwardEuler method //EulerIvpOdeSolver euler_solver; boost::shared_ptr<EulerIvpOdeSolver> p_solver(new EulerIvpOdeSolver); std::cout<<"Solver"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver(p_mesh, &pde, &bcc,odeSystem,p_solver); // solver properties double t_end = 10; solver.SetTimes(0, t_end); solver.SetTimeStep(1e-2); solver.SetSamplingTimeStep(1e-2); solver.SetOutputDirectory("TestAbstractChemicalOdeOutput_groupMeeting"); solver.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; // clean PetscTools::Destroy(initial_condition); } void TestReactionSystemFromFile() { /* std::cout<<"Reaction system from file"<<std::endl; std::cout<<"-----------------------------"<<std::endl; AbstractReaction* p_reaction = new AbstractReaction(); std::cout<<"Before cast reaction type: "<<p_reaction -> GetReactionType()<<std::endl; ReactionTablet(p_reaction,"MassActionReaction"); std::cout<<"After cast reaction type: "<<p_reaction -> GetReactionType()<<std::endl; std::cout<<"-----------------------------"<<std::endl; std::string reactionFilename = "/home/chaste/projects/ChemicalChaste/src/Data/SchnackenbergReactionFile.txt"; //std::string reactionFilename = "/home/chaste/projects/ChemicalChaste/src/Data/SchnackenbergReactionFileMixed.txt"; AbstractReactionSystemFromFile* p_file_reaction_system = new AbstractReactionSystemFromFile(reactionFilename); std::cout<<"Mass action kinetics of Schnackenberg using the AbstractChemicalOdeSystem Class"<<std::endl; std::cout<<"-----------------------------"<<std::endl; // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 AbstractChemistry* p_system_chemistry = new AbstractChemistry(); std::vector<AbstractChemical*> p_substrates_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_3 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_3 = std::vector<AbstractChemical*>(); std::vector<unsigned> stoich_substrates_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_3 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_3 = std::vector<unsigned>(); AbstractChemical *p_chemical_U = new AbstractChemical("U"); p_system_chemistry -> AddChemical(p_chemical_U); // add U to reactions p_substrates_1.push_back(p_chemical_U); stoich_substrates_1.push_back(2); p_products_1.push_back(p_chemical_U); stoich_products_1.push_back(3); p_products_2.push_back(p_chemical_U); stoich_products_2.push_back(1); AbstractChemical *p_chemical_V = new AbstractChemical("V"); p_system_chemistry -> AddChemical(p_chemical_V); // add U to reactions p_substrates_1.push_back(p_chemical_V); stoich_substrates_1.push_back(1); p_products_3.push_back(p_chemical_V); stoich_products_3.push_back(1); double reaction_1_rate = 0.1; double reaction_2_forward_rate = 0.1; double reaction_2_reverse_rate = 0.2; double reaction_3_rate = 0.3; AbstractReaction* p_reaction_1 = new AbstractReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,reaction_1_rate); AbstractReversibleReaction* p_reaction_2 = new AbstractReversibleReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,reaction_2_forward_rate, reaction_2_reverse_rate); AbstractReaction* p_reaction_3 = new AbstractReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,reaction_3_rate); std::vector<AbstractReaction*> p_reaction_vector; p_reaction_vector.push_back(p_reaction_1); p_reaction_vector.push_back(p_reaction_2); p_reaction_vector.push_back(p_reaction_3); MassActionReaction* p_Mass_action_reaction_1 = new MassActionReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,false,false,reaction_1_rate); MassActionReaction* p_Mass_action_reaction_2 = new MassActionReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,false, true, reaction_2_forward_rate, reaction_2_reverse_rate); MassActionReaction* p_Mass_action_reaction_3 = new MassActionReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,false, false,reaction_3_rate); std::vector<AbstractReaction*> p_mass_action_reaction_vector; p_mass_action_reaction_vector.push_back(p_Mass_action_reaction_1); p_mass_action_reaction_vector.push_back(p_Mass_action_reaction_2); p_mass_action_reaction_vector.push_back(p_Mass_action_reaction_3); AbstractReactionSystem* p_mass_action_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_mass_action_reaction_vector); std::cout<<"--------------------------------------"<<std::endl; std::cout<<"Test the reaction systems for equality"<<std::endl; std::cout<<"--------------------------------------"<<std::endl; std::cout<<"-----------------------------"<<std::endl; std::cout<<"System from file"<<std::endl; std::cout<<"-----------------------------"<<std::endl; std::cout<<"Read out reaction details: "<<std::endl; std::cout<<"-----------------------------"<<std::endl; std::cout<<"Number of reactions: "<<p_file_reaction_system -> GetNumberOfReactions()<<std::endl; for(unsigned i=0; i<p_file_reaction_system -> GetNumberOfReactions(); i++) { std::cout<<"Reaction: "<<i<<" "<< p_file_reaction_system -> GetReactionByIndex(i) -> GetReactionType()<<std::endl; std::cout<<"Reaction: "<<i<<" "<< dynamic_cast<MassActionReaction*>(p_file_reaction_system -> GetReactionByIndex(i)) -> GetForwardReactionRateConstant()<<std::endl; std::cout<<"Reaction: "<<i<<" "<< dynamic_cast<MassActionReaction*>(p_file_reaction_system -> GetReactionByIndex(i)) -> GetReverseReactionRateConstant()<<std::endl; } std::vector<std::string> chemNames = p_file_reaction_system-> GetSystemChemistry() -> GetChemicalNames(); std::cout<<"System chemical names:"<<std::endl; for(unsigned i=0; i<chemNames.size();i++) { std::cout<<chemNames[i]<<std::endl; } for(unsigned i=0; i<p_file_reaction_system-> GetNumberOfReactions(); i++ ) { AbstractReaction* p_reaction = p_file_reaction_system-> GetReactionByIndex(i); std::cout<<"Reaction type: "<<p_reaction ->GetReactionType()<<std::endl; for(unsigned j=0; j<p_reaction -> GetNumberOfSubstrates(); j++) { std::cout<<"Substrate: "<<p_reaction -> GetSubstratesByIndex(j) -> GetChemicalName()<<" Stoich: "<<p_reaction ->GetStoichSubstratesByIndex(j)<<std::endl; } for(unsigned j=0; j<p_reaction -> GetNumberOfProducts(); j++) { std::cout<<"Product: "<<p_reaction -> GetProductsByIndex(j) -> GetChemicalName()<<" Stoich: "<<p_reaction ->GetStoichProductsByIndex(j)<<std::endl; } } std::cout<<"-----------------------------"<<std::endl; std::cout<<"Hard coded system"<<std::endl; std::cout<<"-----------------------------"<<std::endl; std::cout<<"Read out reaction details: "<<std::endl; std::cout<<"-----------------------------"<<std::endl; std::cout<<"Number of reactions: "<<p_mass_action_reaction_system -> GetNumberOfReactions()<<std::endl; for(unsigned i=0; i<p_mass_action_reaction_system -> GetNumberOfReactions(); i++) { std::cout<<"Reaction: "<<i<<" "<< p_mass_action_reaction_system -> GetReactionByIndex(i) -> GetReactionType()<<std::endl; std::cout<<"Reaction: "<<i<<" "<< dynamic_cast<MassActionReaction*>(p_mass_action_reaction_system -> GetReactionByIndex(i)) -> GetForwardReactionRateConstant()<<std::endl; std::cout<<"Reaction: "<<i<<" "<< dynamic_cast<MassActionReaction*>(p_mass_action_reaction_system -> GetReactionByIndex(i)) -> GetReverseReactionRateConstant()<<std::endl; } std::vector<std::string> chemNames_hard_coded = p_mass_action_reaction_system-> GetSystemChemistry() -> GetChemicalNames(); std::cout<<"System chemical names:"<<std::endl; for(unsigned i=0; i<chemNames_hard_coded.size();i++) { std::cout<<chemNames_hard_coded[i]<<std::endl; } for(unsigned i=0; i<p_mass_action_reaction_system-> GetNumberOfReactions(); i++ ) { AbstractReaction* p_reaction = p_mass_action_reaction_system-> GetReactionByIndex(i); std::cout<<"Reaction type: "<<p_reaction ->GetReactionType()<<std::endl; for(unsigned j=0; j<p_reaction -> GetNumberOfSubstrates(); j++) { std::cout<<"Substrate: "<<p_reaction -> GetSubstratesByIndex(j) -> GetChemicalName()<<" Stoich: "<<p_reaction ->GetStoichSubstratesByIndex(j)<<std::endl; } for(unsigned j=0; j<p_reaction -> GetNumberOfProducts(); j++) { std::cout<<"Product: "<<p_reaction -> GetProductsByIndex(j) -> GetChemicalName()<<" Stoich: "<<p_reaction ->GetStoichProductsByIndex(j)<<std::endl; } } std::cout<<"-----------------------------"<<std::endl; std::cout<<"Run the reaction ODE system "<<std::endl; std::cout<<"-----------------------------"<<std::endl; AbstractChemicalOdeSystem chemicalOde(p_mass_action_reaction_system); EulerIvpOdeSolver euler_solver; std::vector<double> initial_condition = {1.0, 1.0}; OdeSolution solutions = euler_solver.Solve(&chemicalOde, initial_condition, 0, 1, 0.1, 0.1); for (unsigned i=0; i<solutions.rGetTimes().size(); i++) { std::cout << solutions.rGetTimes()[i] << " " << solutions.rGetSolutions()[i][0] << " " << solutions.rGetSolutions()[i][1]<< "\n"; } std::cout<<"-----------------------------"<<std::endl; std::cout<<"Run the file reaction system "<<std::endl; std::cout<<"-----------------------------"<<std::endl; // implicit upcast AbstractReactionSystemFromFile to AbstractReactionSystem AbstractChemicalOdeSystem chemical_ode_file(p_file_reaction_system); std::vector<double> initial_condition_file = {1.0, 1.0}; EulerIvpOdeSolver euler_solver_file; OdeSolution solutions_file = euler_solver_file.Solve(&chemical_ode_file, initial_condition_file, 0, 1, 0.1, 0.1); for (unsigned i=0; i<solutions_file.rGetTimes().size(); i++) { std::cout << solutions_file.rGetTimes()[i] << " " << solutions_file.rGetSolutions()[i][0] << " " << solutions_file.rGetSolutions()[i][1]<< "\n"; } */ } void TestPdeFromFile() { /* std::cout<<"ConsumerProducerFromFile"<<std::endl; // reaction system involving two species, A and B // 0 -> A rateConstant = k1 // B -> 0 rateConstant = k2 // A <-> B rateConstantForward = k3 rateConstantReverse = k_3 // A diffuses at rate Da // B diffuses at rate Db // nodal ode of the form: OdeConsumerProducer(k1, k2, k3, k4) // with nodes 22, 27, 72, 77 selected forming corners of a square domain offset from the boundary double Da = 1e-1; double Db = 5e-2; // system properties const unsigned probDim =2; const unsigned spaceDim=2; const unsigned elementDim=2; std::vector<double> initValues = {0, 0}; std::vector<double> bcValues = {0, 0}; // mesh HoneycombMeshGenerator generator(10, 10, 0); MutableMesh<elementDim,spaceDim>* p_mesh = generator.GetMesh(); // Process Boundary Conditions std::cout<<"Process Boundary Conditions"<<std::endl; BoundaryConditionsContainer<elementDim,spaceDim,probDim> bcc; std::vector<bool> areNeumannBoundaryConditions(probDim, false); std::vector<ConstBoundaryCondition<spaceDim>*> vectorConstBCs; for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++){ vectorConstBCs.push_back(new ConstBoundaryCondition<spaceDim>(bcValues[pdeDim])); } for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { if(areNeumannBoundaryConditions[pdeDim]==false) { for (TetrahedralMesh<elementDim,spaceDim>::BoundaryNodeIterator node_iter = p_mesh->GetBoundaryNodeIteratorBegin(); node_iter != p_mesh->GetBoundaryNodeIteratorEnd(); ++node_iter) { bcc.AddDirichletBoundaryCondition(*node_iter, vectorConstBCs[pdeDim], pdeDim); } }else{ for (TetrahedralMesh<elementDim,spaceDim>::BoundaryElementIterator boundary_iter = p_mesh->GetBoundaryElementIteratorBegin(); boundary_iter != p_mesh->GetBoundaryElementIteratorEnd(); boundary_iter++) { bcc.AddNeumannBoundaryCondition(*boundary_iter, vectorConstBCs[pdeDim], pdeDim); } } } std::cout<<"Initial conditions"<<std::endl; // initial conditions std::vector<double> init_conds(probDim*p_mesh->GetNumNodes()); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { // set as being a random perturbation about the boundary values for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { // serialised for nodes init_conds[probDim*i + pdeDim] = initValues[pdeDim] ;//fabs(initValues[pdeDim] + RandomNumberGenerator::Instance()->ranf()); } } // PETSc Vec std::cout<<"PETSc Vec"<<std::endl; Vec initial_condition = PetscTools::CreateVec(init_conds); // pde system std::cout<<"Pde"<<std::endl; PdeConsumerProducer<elementDim, spaceDim, probDim> pde(Da, Db); // coupled ode system std::cout<<"Ode loop"<<std::endl; std::vector<AbstractOdeSystemForCoupledPdeSystem*> odeSystem; for (unsigned i=0; i<p_mesh->GetNumNodes(); i++){ // number of ode system objects must match the number of nodes, i.e the individual odes may be multi-dimensional if(i==22) { odeSystem.push_back(new OdeConsumerProducer(1, 0, 0, 0)); }else if(i==77) { odeSystem.push_back(new OdeConsumerProducer(0, 1, 0, 0)); }else{ odeSystem.push_back(new OdeConsumerProducer(0, 0, 0.1, 0)); } } // 0 -> A rateConstant = k1 // B -> 0 rateConstant = k2 // A <-> B rateConstantForward = k3 rateConstantReverse = k_3 // A diffuses at rate Da // B diffuses at rate Db std::cout<<"Number odesAtNodes: "<<p_mesh->GetNumNodes()<<std::endl; // used the explicitly defined EulerIvpOdeSolver rather than the default defined BackwardEuler method //EulerIvpOdeSolver euler_solver; boost::shared_ptr<EulerIvpOdeSolver> p_solver(new EulerIvpOdeSolver); std::cout<<"Solver"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver(p_mesh, &pde, &bcc, odeSystem, p_solver); // solver properties double t_end = 10; solver.SetTimes(0, t_end); solver.SetTimeStep(1e-2); solver.SetSamplingTimeStep(1e-2); solver.SetOutputDirectory("TestConsumerProducerOutputFromFile"); solver.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; // clean PetscTools::Destroy(initial_condition); */ } void TestCHASTESpheroidTutorial() { /* EXIT_IF_PARALLEL; HoneycombMeshGenerator generator(10, 10, 0); MutableMesh<2,2>* p_mesh = generator.GetMesh(); std::vector<CellPtr> cells; MAKE_PTR(WildTypeCellMutationState, p_state); MAKE_PTR(StemCellProliferativeType, p_stem_type); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { SimpleOxygenBasedCellCycleModel* p_model = new SimpleOxygenBasedCellCycleModel; p_model->SetDimension(2); CellPtr p_cell(new Cell(p_state, p_model)); p_cell->SetCellProliferativeType(p_stem_type); p_model->SetStemCellG1Duration(8.0); p_model->SetTransitCellG1Duration(8.0); double birth_time = - RandomNumberGenerator::Instance()->ranf() * ( p_model->GetStemCellG1Duration() + p_model->GetSG2MDuration() ); p_cell->SetBirthTime(birth_time); cells.push_back(p_cell); } MeshBasedCellPopulation<2> cell_population(*p_mesh, cells); MAKE_PTR_ARGS(CellwiseSourceEllipticPde<2>, p_pde, (cell_population, -0.03)); MAKE_PTR_ARGS(ConstBoundaryCondition<2>, p_bc, (1.0)); bool is_neumann_bc = false; MAKE_PTR_ARGS(EllipticGrowingDomainPdeModifier<2>, p_pde_modifier, (p_pde, p_bc, is_neumann_bc)); p_pde_modifier->SetDependentVariableName("oxygen"); OffLatticeSimulation<2> simulator(cell_population); simulator.AddSimulationModifier(p_pde_modifier); simulator.SetOutputDirectory("SpheroidTutorial"); simulator.SetEndTime(1.0); MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force); p_linear_force->SetCutOffLength(3); simulator.AddForce(p_linear_force); simulator.Solve(); */ } void TestChemicalSpheroid() { /* std::vector<double> initValues = {2.0, 0.75}; std::vector<double> bcValues = {2.0, 0.75}; // mesh HoneycombMeshGenerator generator(100, 100, 0); MutableMesh<2,2>* p_mesh = generator.GetMesh(); SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.1, 0.2, 0.3, 0.1); BoundaryConditionsContainer<2,2,2> bcc; ConstBoundaryCondition<2>* p_bc_for_u = new ConstBoundaryCondition<2>(2.0); ConstBoundaryCondition<2>* p_bc_for_v = new ConstBoundaryCondition<2>(0.75); for (TetrahedralMesh<2,2>::BoundaryNodeIterator node_iter = p_mesh->GetBoundaryNodeIteratorBegin(); node_iter != p_mesh->GetBoundaryNodeIteratorEnd(); ++node_iter) { bcc.AddDirichletBoundaryCondition(*node_iter, p_bc_for_u, 0); bcc.AddDirichletBoundaryCondition(*node_iter, p_bc_for_v, 1); } LinearParabolicPdeSystemWithCoupledOdeSystemSolver<2,2,2> solver(p_mesh, &pde, &bcc); double t_end = 10; solver.SetTimes(0, t_end); solver.SetTimeStep(1e-2); solver.SetSamplingTimeStep(1e-2); solver.SetOutputDirectory("TestSchnackenbergSystemOnHoneycombMesh"); std::vector<double> init_conds(2*p_mesh->GetNumNodes()); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { init_conds[2*i] = fabs(2.0 + RandomNumberGenerator::Instance()->ranf()); init_conds[2*i + 1] = fabs(0.75 + RandomNumberGenerator::Instance()->ranf()); } Vec initial_condition = PetscTools::CreateVec(init_conds); solver.SetInitialCondition(initial_condition); solver.SolveAndWriteResultsToFile(); PetscTools::Destroy(initial_condition); */ } void TestChemicalSpheroidPAPER() { std::vector<double> initValues = {2.0, 0.75}; std::vector<double> bcValues = {2.0, 0.75}; // mesh HoneycombMeshGenerator generator(3, 3, 0); MutableMesh<2,2>* p_mesh = generator.GetMesh(); SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); BoundaryConditionsContainer<2,2,2> bcc; ConstBoundaryCondition<2>* p_bc_for_u = new ConstBoundaryCondition<2>(2.0); ConstBoundaryCondition<2>* p_bc_for_v = new ConstBoundaryCondition<2>(0.75); for (TetrahedralMesh<2,2>::BoundaryNodeIterator node_iter = p_mesh->GetBoundaryNodeIteratorBegin(); node_iter != p_mesh->GetBoundaryNodeIteratorEnd(); ++node_iter) { bcc.AddDirichletBoundaryCondition(*node_iter, p_bc_for_u, 0); bcc.AddDirichletBoundaryCondition(*node_iter, p_bc_for_v, 1); } LinearParabolicPdeSystemWithCoupledOdeSystemSolver<2,2,2> solver(p_mesh, &pde, &bcc); double t_end = 10; solver.SetTimes(0, t_end); solver.SetTimeStep(1e-2); solver.SetSamplingTimeStep(1e-2); solver.SetOutputDirectory("TestSchnackenbergSystemOnHoneycombMesh_paper_test"); std::vector<double> init_conds(2*p_mesh->GetNumNodes()); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { init_conds[2*i] = fabs(2.0 + RandomNumberGenerator::Instance()->ranf()); init_conds[2*i + 1] = fabs(0.75 + RandomNumberGenerator::Instance()->ranf()); } Vec initial_condition = PetscTools::CreateVec(init_conds); solver.SetInitialCondition(initial_condition); solver.SolveAndWriteResultsToFile(); PetscTools::Destroy(initial_condition); } void TestSpectatorDependentReactionClass() { /* std::cout<<"--------------------------------------"<<std::endl; std::cout<<"Test Spectator dependent reaction class"<<std::endl; std::cout<<"--------------------------------------"<<std::endl; std::string reactionFilename = "/home/chaste/projects/ChemicalChaste/src/Data/SpectatorReactionFile.txt"; AbstractReactionSystemFromFile* p_file_reaction_system = new AbstractReactionSystemFromFile(reactionFilename); std::cout<<"-----------------------------"<<std::endl; std::cout<<"System from file"<<std::endl; std::cout<<"-----------------------------"<<std::endl; std::cout<<"Read out reaction details: "<<std::endl; std::cout<<"-----------------------------"<<std::endl; std::cout<<"Number of reactions: "<<p_file_reaction_system -> GetNumberOfReactions()<<std::endl; for(unsigned i=0; i<p_file_reaction_system -> GetNumberOfReactions(); i++) { std::cout<<"Reaction: "<<i<<" "<< p_file_reaction_system -> GetReactionByIndex(i) -> GetReactionType()<<std::endl; std::cout<<"Number of spectators: "<<i<<" "<< dynamic_cast<SpectatorDependentReaction*>(p_file_reaction_system -> GetReactionByIndex(i)) -> GetNumberOfSpectators()<<std::endl; } std::vector<std::string> chemNames = p_file_reaction_system-> GetSystemChemistry() -> GetChemicalNames(); std::cout<<"System chemical names:"<<std::endl; for(unsigned i=0; i<chemNames.size();i++) { std::cout<<chemNames[i]<<std::endl; } for(unsigned i=0; i<p_file_reaction_system-> GetNumberOfReactions(); i++ ) { AbstractReaction* p_reaction = p_file_reaction_system-> GetReactionByIndex(i); std::cout<<"Reaction type: "<<p_reaction ->GetReactionType()<<std::endl; for(unsigned j=0; j<p_reaction -> GetNumberOfSubstrates(); j++) { std::cout<<"Substrate: "<<p_reaction -> GetSubstratesByIndex(j) -> GetChemicalName()<<" Stoich: "<<p_reaction ->GetStoichSubstratesByIndex(j)<<std::endl; } for(unsigned j=0; j<p_reaction -> GetNumberOfProducts(); j++) { std::cout<<"Product: "<<p_reaction -> GetProductsByIndex(j) -> GetChemicalName()<<" Stoich: "<<p_reaction ->GetStoichProductsByIndex(j)<<std::endl; } } std::cout<<"-----------------------------"<<std::endl; std::cout<<"Run the file reaction system "<<std::endl; std::cout<<"-----------------------------"<<std::endl; // implicit upcast AbstractReactionSystemFromFile to AbstractReactionSystem AbstractChemicalOdeSystem chemical_ode_file(p_file_reaction_system); // read in the order Alpha, Beta, A, B, C // order speceis occurance in reaction system, then order of spectator species when duplicates removed std::vector<double> initial_condition = {1.0, 1.0,1.0,1.0,0.0}; // initial_condition = {1.0, 1.0,1.0,1.0,0.0}, in order Alpha, Beta, A, B, C // C set to 0.0 makes reaction 1 have zero rate, reaction 0 occurs at coanstant rate, while reaction 2 has variable rate EulerIvpOdeSolver euler_solver_file; OdeSolution solutions_file = euler_solver_file.Solve(&chemical_ode_file, initial_condition, 0, 1, 0.1, 0.1); for (unsigned i=0; i<solutions_file.rGetTimes().size(); i++) { std::cout << "Time: "<<solutions_file.rGetTimes()[i] << " " << solutions_file.rGetSolutions()[i][0] << " " << solutions_file.rGetSolutions()[i][1]<< " " << solutions_file.rGetSolutions()[i][2]<< "\n"; } */ } void TestChemicalOdePdeConvergence() { /* std::cout<<"Mass action kinetics of Schnackenberg using the AbstractChemicalOdeSystem Class"<<std::endl; std::cout<<"-----------------------------"<<std::endl; // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 AbstractChemistry* p_system_chemistry = new AbstractChemistry(); std::vector<AbstractChemical*> p_substrates_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_3 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_3 = std::vector<AbstractChemical*>(); std::vector<unsigned> stoich_substrates_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_3 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_3 = std::vector<unsigned>(); AbstractChemical *p_chemical_U = new AbstractChemical("U"); p_system_chemistry -> AddChemical(p_chemical_U); // add U to reactions p_substrates_1.push_back(p_chemical_U); stoich_substrates_1.push_back(2); p_products_1.push_back(p_chemical_U); stoich_products_1.push_back(3); p_products_2.push_back(p_chemical_U); stoich_products_2.push_back(1); AbstractChemical *p_chemical_V = new AbstractChemical("V"); p_system_chemistry -> AddChemical(p_chemical_V); // add V to reactions p_substrates_1.push_back(p_chemical_V); stoich_substrates_1.push_back(1); p_products_3.push_back(p_chemical_V); stoich_products_3.push_back(1); // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 double reaction_1_rate = 1.0; double reaction_2_forward_rate = 0.5; double reaction_2_reverse_rate = 2.2; double reaction_3_rate = 1.5; AbstractReaction* p_reaction_1 = new AbstractReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,reaction_1_rate); AbstractReversibleReaction* p_reaction_2 = new AbstractReversibleReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,reaction_2_forward_rate, reaction_2_reverse_rate); AbstractReaction* p_reaction_3 = new AbstractReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,reaction_3_rate); std::vector<AbstractReaction*> p_reaction_vector; p_reaction_vector.push_back(p_reaction_1); p_reaction_vector.push_back(p_reaction_2); p_reaction_vector.push_back(p_reaction_3); //AbstractReactionSystem* p_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_reaction_vector); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); MassActionReaction* p_mass_action_reaction_1 = new MassActionReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,false,false,reaction_1_rate); MassActionReaction* p_mass_action_reaction_2 = new MassActionReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,false, true, reaction_2_forward_rate, reaction_2_reverse_rate); MassActionReaction* p_mass_action_reaction_3 = new MassActionReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,false, false,reaction_3_rate); std::vector<AbstractReaction*> p_mass_action_reaction_vector; p_mass_action_reaction_vector.push_back(p_mass_action_reaction_1); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_2); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_3); AbstractReactionSystem* p_mass_action_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_mass_action_reaction_vector); // form ode system std::cout<<"SchnackenbergCoupledPdeOdeSystem -As AbstractChemicalODeSystem"<<std::endl; // system properties const unsigned probDim =2; const unsigned spaceDim=2; const unsigned elementDim=2; std::vector<double> initValues = {2.0, 0.75}; std::vector<double> bcValues = {0.0, 0.0}; // mesh HoneycombMeshGenerator generator(10, 10, 0); MutableMesh<elementDim,spaceDim>* p_mesh = generator.GetMesh(); // Process Boundary Conditions std::cout<<"Process Boundary Conditions"<<std::endl; BoundaryConditionsContainer<elementDim,spaceDim,probDim> bcc; std::vector<bool> areNeumannBoundaryConditions(probDim, true); std::vector<ConstBoundaryCondition<spaceDim>*> vectorConstBCs; for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++){ vectorConstBCs.push_back(new ConstBoundaryCondition<spaceDim>(bcValues[pdeDim])); } for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { if(areNeumannBoundaryConditions[pdeDim]==false) { for (TetrahedralMesh<elementDim,spaceDim>::BoundaryNodeIterator node_iter = p_mesh->GetBoundaryNodeIteratorBegin(); node_iter != p_mesh->GetBoundaryNodeIteratorEnd(); ++node_iter) { bcc.AddDirichletBoundaryCondition(*node_iter, vectorConstBCs[pdeDim], pdeDim); } }else{ for (TetrahedralMesh<elementDim,spaceDim>::BoundaryElementIterator boundary_iter = p_mesh->GetBoundaryElementIteratorBegin(); boundary_iter != p_mesh->GetBoundaryElementIteratorEnd(); boundary_iter++) { bcc.AddNeumannBoundaryCondition(*boundary_iter, vectorConstBCs[pdeDim], pdeDim); } } } std::cout<<"Initial conditions"<<std::endl; // initial conditions std::vector<double> init_conds(probDim*p_mesh->GetNumNodes()); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { // set as being a random perturbation about the boundary values for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { // serialised for nodes init_conds[probDim*i + pdeDim] = fabs(initValues[pdeDim] + RandomNumberGenerator::Instance()->ranf()); } } // PETSc Vec std::cout<<"PETSc Vec"<<std::endl; Vec initial_condition = PetscTools::CreateVec(init_conds); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); // coupled ode system std::cout<<"Ode loop"<<std::endl; std::vector<AbstractOdeSystemForCoupledPdeSystem*> odeSystem; for (unsigned i=0; i<p_mesh->GetNumNodes(); i++){ // number of ode system objects must match the number of nodes, i.e the individual odes may be multi-dimensional odeSystem.push_back(new AbstractChemicalOdeForCoupledPdeSystem(p_mass_action_reaction_system)); } std::cout<<"Number odesAtNodes: "<<p_mesh->GetNumNodes()<<std::endl; // pde system std::cout<<"Pde"<<std::endl; PdeSchnackenbergCoupledPdeOdeSystem<elementDim, spaceDim, probDim> pde(odeSystem[0],1e-4, 1e-2 ); // used the explicitly defined EulerIvpOdeSolver rather than the default defined BackwardEuler method //EulerIvpOdeSolver euler_solver; boost::shared_ptr<EulerIvpOdeSolver> p_solver(new EulerIvpOdeSolver); double t_end = 10; std::cout<<"Solver 1"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver1(p_mesh, &pde, &bcc,odeSystem,p_solver); // solver properties solver1.SetTimes(0, t_end); solver1.SetTimeStep(1e-1); solver1.SetSamplingTimeStep(1e-1); solver1.SetOutputDirectory("TestAbstractChemicalOdeOutput_groupMeeting_1e-1"); solver1.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver1.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; std::cout<<"Solver 2"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver2(p_mesh, &pde, &bcc,odeSystem,p_solver); solver2.SetTimes(0, t_end); solver2.SetTimeStep(1e-2); solver2.SetSamplingTimeStep(1e-2); solver2.SetOutputDirectory("TestAbstractChemicalOdeOutput_groupMeeting_1e-2"); solver2.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver2.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; std::cout<<"Solver 3"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver3(p_mesh, &pde, &bcc,odeSystem,p_solver); // solver properties solver3.SetTimes(0, t_end); solver3.SetTimeStep(1e-3); solver3.SetSamplingTimeStep(1e-3); solver3.SetOutputDirectory("TestAbstractChemicalOdeOutput_groupMeeting_1e-3"); solver3.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver3.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; std::cout<<"Solver 4"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver4(p_mesh, &pde, &bcc,odeSystem,p_solver); solver4.SetTimes(0, t_end); solver4.SetTimeStep(1e-4); solver4.SetSamplingTimeStep(1e-4); solver4.SetOutputDirectory("TestAbstractChemicalOdeOutput_groupMeeting_1e-4"); solver4.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver4.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; std::cout<<"Solver 5"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver5(p_mesh, &pde, &bcc,odeSystem,p_solver); // solver properties solver5.SetTimes(0, t_end); solver5.SetTimeStep(1e-5); solver5.SetSamplingTimeStep(1e-5); solver5.SetOutputDirectory("TestAbstractChemicalOdeOutput_groupMeeting_1e-5"); solver5.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver5.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; std::cout<<"Solver 6"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver6(p_mesh, &pde, &bcc,odeSystem,p_solver); solver6.SetTimes(0, t_end); solver6.SetTimeStep(1e-6); solver6.SetSamplingTimeStep(1e-6); solver6.SetOutputDirectory("TestAbstractChemicalOdeOutput_groupMeeting_1e-6"); solver6.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver6.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; // clean PetscTools::Destroy(initial_condition); */ } void TestChemicalOdePdeParameters() { std::cout<<"Mass action kinetics of Schnackenberg using the AbstractChemicalOdeSystem Class"<<std::endl; std::cout<<"-----------------------------"<<std::endl; // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 AbstractChemistry* p_system_chemistry = new AbstractChemistry(); std::vector<AbstractChemical*> p_substrates_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_3 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_3 = std::vector<AbstractChemical*>(); std::vector<unsigned> stoich_substrates_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_3 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_3 = std::vector<unsigned>(); AbstractChemical *p_chemical_U = new AbstractChemical("U"); p_system_chemistry -> AddChemical(p_chemical_U); // add U to reactions p_substrates_1.push_back(p_chemical_U); stoich_substrates_1.push_back(2); p_products_1.push_back(p_chemical_U); stoich_products_1.push_back(3); p_products_2.push_back(p_chemical_U); stoich_products_2.push_back(1); AbstractChemical *p_chemical_V = new AbstractChemical("V"); p_system_chemistry -> AddChemical(p_chemical_V); // add V to reactions p_substrates_1.push_back(p_chemical_V); stoich_substrates_1.push_back(1); p_products_3.push_back(p_chemical_V); stoich_products_3.push_back(1); // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 double reaction_1_rate = 0.1; double reaction_2_forward_rate = 0.1; double reaction_2_reverse_rate = 0.2; double reaction_3_rate = 0.3; AbstractReaction* p_reaction_1 = new AbstractReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,reaction_1_rate); AbstractReversibleReaction* p_reaction_2 = new AbstractReversibleReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,reaction_2_forward_rate, reaction_2_reverse_rate); AbstractReaction* p_reaction_3 = new AbstractReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,reaction_3_rate); std::vector<AbstractReaction*> p_reaction_vector; p_reaction_vector.push_back(p_reaction_1); p_reaction_vector.push_back(p_reaction_2); p_reaction_vector.push_back(p_reaction_3); //AbstractReactionSystem* p_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_reaction_vector); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); MassActionReaction* p_mass_action_reaction_1 = new MassActionReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,false,false,reaction_1_rate); MassActionReaction* p_mass_action_reaction_2 = new MassActionReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,false, true, reaction_2_forward_rate, reaction_2_reverse_rate); MassActionReaction* p_mass_action_reaction_3 = new MassActionReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,false, false,reaction_3_rate); std::vector<AbstractReaction*> p_mass_action_reaction_vector; p_mass_action_reaction_vector.push_back(p_mass_action_reaction_1); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_2); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_3); AbstractReactionSystem* p_mass_action_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_mass_action_reaction_vector); // form ode system std::cout<<"SchnackenbergCoupledPdeOdeSystem -As AbstractChemicalODeSystem"<<std::endl; // system properties const unsigned probDim =2; const unsigned spaceDim=2; const unsigned elementDim=2; std::vector<double> initValues = {2.0, 0.75}; std::vector<double> bcValues = {0.0, 0.0}; // mesh HoneycombMeshGenerator generator(10, 10, 0); MutableMesh<elementDim,spaceDim>* p_mesh = generator.GetMesh(); // Process Boundary Conditions std::cout<<"Process Boundary Conditions"<<std::endl; BoundaryConditionsContainer<elementDim,spaceDim,probDim> bcc; std::vector<bool> areNeumannBoundaryConditions(probDim, true); std::vector<ConstBoundaryCondition<spaceDim>*> vectorConstBCs; for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++){ vectorConstBCs.push_back(new ConstBoundaryCondition<spaceDim>(bcValues[pdeDim])); } for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { if(areNeumannBoundaryConditions[pdeDim]==false) { for (TetrahedralMesh<elementDim,spaceDim>::BoundaryNodeIterator node_iter = p_mesh->GetBoundaryNodeIteratorBegin(); node_iter != p_mesh->GetBoundaryNodeIteratorEnd(); ++node_iter) { bcc.AddDirichletBoundaryCondition(*node_iter, vectorConstBCs[pdeDim], pdeDim); } }else{ for (TetrahedralMesh<elementDim,spaceDim>::BoundaryElementIterator boundary_iter = p_mesh->GetBoundaryElementIteratorBegin(); boundary_iter != p_mesh->GetBoundaryElementIteratorEnd(); boundary_iter++) { bcc.AddNeumannBoundaryCondition(*boundary_iter, vectorConstBCs[pdeDim], pdeDim); } } } std::cout<<"Initial conditions"<<std::endl; // initial conditions std::vector<double> init_conds(probDim*p_mesh->GetNumNodes()); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { // set as being a random perturbation about the boundary values for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { // serialised for nodes init_conds[probDim*i + pdeDim] = fabs(initValues[pdeDim] + RandomNumberGenerator::Instance()->ranf()); } } // PETSc Vec std::cout<<"PETSc Vec"<<std::endl; Vec initial_condition = PetscTools::CreateVec(init_conds); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); // coupled ode system std::cout<<"Ode loop"<<std::endl; std::vector<AbstractOdeSystemForCoupledPdeSystem*> odeSystem; for (unsigned i=0; i<p_mesh->GetNumNodes(); i++){ // number of ode system objects must match the number of nodes, i.e the individual odes may be multi-dimensional odeSystem.push_back(new AbstractChemicalOdeForCoupledPdeSystem(p_mass_action_reaction_system)); } std::cout<<"Number odesAtNodes: "<<p_mesh->GetNumNodes()<<std::endl; // pde system std::cout<<"Pde"<<std::endl; PdeSchnackenbergCoupledPdeOdeSystem<elementDim, spaceDim, probDim> pde(odeSystem[0],1e-4, 1e-2 ); // used the explicitly defined EulerIvpOdeSolver rather than the default defined BackwardEuler method //EulerIvpOdeSolver euler_solver; boost::shared_ptr<EulerIvpOdeSolver> p_solver(new EulerIvpOdeSolver); std::cout<<"Solver"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver(p_mesh, &pde, &bcc,odeSystem,p_solver); // solver properties double t_end = 10; solver.SetTimes(0, t_end); solver.SetTimeStep(1e-2); solver.SetSamplingTimeStep(1e-2); solver.SetOutputDirectory("TestAbstractChemicalOdeOutput_groupMeeting_params1"); solver.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; // clean PetscTools::Destroy(initial_condition); } void TestChemicalOdePdeParameters2() { std::cout<<"Mass action kinetics of Schnackenberg using the AbstractChemicalOdeSystem Class"<<std::endl; std::cout<<"-----------------------------"<<std::endl; // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 AbstractChemistry* p_system_chemistry = new AbstractChemistry(); std::vector<AbstractChemical*> p_substrates_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_3 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_3 = std::vector<AbstractChemical*>(); std::vector<unsigned> stoich_substrates_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_3 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_3 = std::vector<unsigned>(); AbstractChemical *p_chemical_U = new AbstractChemical("U"); p_system_chemistry -> AddChemical(p_chemical_U); // add U to reactions p_substrates_1.push_back(p_chemical_U); stoich_substrates_1.push_back(2); p_products_1.push_back(p_chemical_U); stoich_products_1.push_back(3); p_products_2.push_back(p_chemical_U); stoich_products_2.push_back(1); AbstractChemical *p_chemical_V = new AbstractChemical("V"); p_system_chemistry -> AddChemical(p_chemical_V); // add V to reactions p_substrates_1.push_back(p_chemical_V); stoich_substrates_1.push_back(1); p_products_3.push_back(p_chemical_V); stoich_products_3.push_back(1); // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 double reaction_1_rate = 0.2; double reaction_2_forward_rate = 0.2; double reaction_2_reverse_rate = 0.4; double reaction_3_rate = 0.6; AbstractReaction* p_reaction_1 = new AbstractReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,reaction_1_rate); AbstractReversibleReaction* p_reaction_2 = new AbstractReversibleReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,reaction_2_forward_rate, reaction_2_reverse_rate); AbstractReaction* p_reaction_3 = new AbstractReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,reaction_3_rate); std::vector<AbstractReaction*> p_reaction_vector; p_reaction_vector.push_back(p_reaction_1); p_reaction_vector.push_back(p_reaction_2); p_reaction_vector.push_back(p_reaction_3); //AbstractReactionSystem* p_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_reaction_vector); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); MassActionReaction* p_mass_action_reaction_1 = new MassActionReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,false,false,reaction_1_rate); MassActionReaction* p_mass_action_reaction_2 = new MassActionReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,false, true, reaction_2_forward_rate, reaction_2_reverse_rate); MassActionReaction* p_mass_action_reaction_3 = new MassActionReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,false, false,reaction_3_rate); std::vector<AbstractReaction*> p_mass_action_reaction_vector; p_mass_action_reaction_vector.push_back(p_mass_action_reaction_1); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_2); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_3); AbstractReactionSystem* p_mass_action_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_mass_action_reaction_vector); // form ode system std::cout<<"SchnackenbergCoupledPdeOdeSystem -As AbstractChemicalODeSystem"<<std::endl; // system properties const unsigned probDim =2; const unsigned spaceDim=2; const unsigned elementDim=2; std::vector<double> initValues = {2.0, 0.75}; std::vector<double> bcValues = {0.0, 0.0}; // mesh HoneycombMeshGenerator generator(10, 10, 0); MutableMesh<elementDim,spaceDim>* p_mesh = generator.GetMesh(); // Process Boundary Conditions std::cout<<"Process Boundary Conditions"<<std::endl; BoundaryConditionsContainer<elementDim,spaceDim,probDim> bcc; std::vector<bool> areNeumannBoundaryConditions(probDim, true); std::vector<ConstBoundaryCondition<spaceDim>*> vectorConstBCs; for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++){ vectorConstBCs.push_back(new ConstBoundaryCondition<spaceDim>(bcValues[pdeDim])); } for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { if(areNeumannBoundaryConditions[pdeDim]==false) { for (TetrahedralMesh<elementDim,spaceDim>::BoundaryNodeIterator node_iter = p_mesh->GetBoundaryNodeIteratorBegin(); node_iter != p_mesh->GetBoundaryNodeIteratorEnd(); ++node_iter) { bcc.AddDirichletBoundaryCondition(*node_iter, vectorConstBCs[pdeDim], pdeDim); } }else{ for (TetrahedralMesh<elementDim,spaceDim>::BoundaryElementIterator boundary_iter = p_mesh->GetBoundaryElementIteratorBegin(); boundary_iter != p_mesh->GetBoundaryElementIteratorEnd(); boundary_iter++) { bcc.AddNeumannBoundaryCondition(*boundary_iter, vectorConstBCs[pdeDim], pdeDim); } } } std::cout<<"Initial conditions"<<std::endl; // initial conditions std::vector<double> init_conds(probDim*p_mesh->GetNumNodes()); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { // set as being a random perturbation about the boundary values for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { // serialised for nodes init_conds[probDim*i + pdeDim] = fabs(initValues[pdeDim] + RandomNumberGenerator::Instance()->ranf()); } } // PETSc Vec std::cout<<"PETSc Vec"<<std::endl; Vec initial_condition = PetscTools::CreateVec(init_conds); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); // coupled ode system std::cout<<"Ode loop"<<std::endl; std::vector<AbstractOdeSystemForCoupledPdeSystem*> odeSystem; for (unsigned i=0; i<p_mesh->GetNumNodes(); i++){ // number of ode system objects must match the number of nodes, i.e the individual odes may be multi-dimensional odeSystem.push_back(new AbstractChemicalOdeForCoupledPdeSystem(p_mass_action_reaction_system)); } std::cout<<"Number odesAtNodes: "<<p_mesh->GetNumNodes()<<std::endl; // pde system std::cout<<"Pde"<<std::endl; PdeSchnackenbergCoupledPdeOdeSystem<elementDim, spaceDim, probDim> pde(odeSystem[0],1e-4, 1e-2 ); // used the explicitly defined EulerIvpOdeSolver rather than the default defined BackwardEuler method //EulerIvpOdeSolver euler_solver; boost::shared_ptr<EulerIvpOdeSolver> p_solver(new EulerIvpOdeSolver); std::cout<<"Solver"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver(p_mesh, &pde, &bcc,odeSystem,p_solver); // solver properties double t_end = 10; solver.SetTimes(0, t_end); solver.SetTimeStep(1e-2); solver.SetSamplingTimeStep(1e-2); solver.SetOutputDirectory("TestAbstractChemicalOdeOutput_groupMeeting_params2"); solver.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; // clean PetscTools::Destroy(initial_condition); } void TestChemicalOdePdeParameters3() { std::cout<<"Mass action kinetics of Schnackenberg using the AbstractChemicalOdeSystem Class"<<std::endl; std::cout<<"-----------------------------"<<std::endl; // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 AbstractChemistry* p_system_chemistry = new AbstractChemistry(); std::vector<AbstractChemical*> p_substrates_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_3 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_3 = std::vector<AbstractChemical*>(); std::vector<unsigned> stoich_substrates_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_3 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_3 = std::vector<unsigned>(); AbstractChemical *p_chemical_U = new AbstractChemical("U"); p_system_chemistry -> AddChemical(p_chemical_U); // add U to reactions p_substrates_1.push_back(p_chemical_U); stoich_substrates_1.push_back(2); p_products_1.push_back(p_chemical_U); stoich_products_1.push_back(3); p_products_2.push_back(p_chemical_U); stoich_products_2.push_back(1); AbstractChemical *p_chemical_V = new AbstractChemical("V"); p_system_chemistry -> AddChemical(p_chemical_V); // add V to reactions p_substrates_1.push_back(p_chemical_V); stoich_substrates_1.push_back(1); p_products_3.push_back(p_chemical_V); stoich_products_3.push_back(1); // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 double reaction_1_rate = 0.3; double reaction_2_forward_rate = 0.3; double reaction_2_reverse_rate = 0.6; double reaction_3_rate = 0.9; AbstractReaction* p_reaction_1 = new AbstractReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,reaction_1_rate); AbstractReversibleReaction* p_reaction_2 = new AbstractReversibleReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,reaction_2_forward_rate, reaction_2_reverse_rate); AbstractReaction* p_reaction_3 = new AbstractReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,reaction_3_rate); std::vector<AbstractReaction*> p_reaction_vector; p_reaction_vector.push_back(p_reaction_1); p_reaction_vector.push_back(p_reaction_2); p_reaction_vector.push_back(p_reaction_3); //AbstractReactionSystem* p_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_reaction_vector); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); MassActionReaction* p_mass_action_reaction_1 = new MassActionReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,false,false,reaction_1_rate); MassActionReaction* p_mass_action_reaction_2 = new MassActionReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,false, true, reaction_2_forward_rate, reaction_2_reverse_rate); MassActionReaction* p_mass_action_reaction_3 = new MassActionReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,false, false,reaction_3_rate); std::vector<AbstractReaction*> p_mass_action_reaction_vector; p_mass_action_reaction_vector.push_back(p_mass_action_reaction_1); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_2); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_3); AbstractReactionSystem* p_mass_action_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_mass_action_reaction_vector); // form ode system std::cout<<"SchnackenbergCoupledPdeOdeSystem -As AbstractChemicalODeSystem"<<std::endl; // system properties const unsigned probDim =2; const unsigned spaceDim=2; const unsigned elementDim=2; std::vector<double> initValues = {2.0, 0.75}; std::vector<double> bcValues = {0.0, 0.0}; // mesh HoneycombMeshGenerator generator(10, 10, 0); MutableMesh<elementDim,spaceDim>* p_mesh = generator.GetMesh(); // Process Boundary Conditions std::cout<<"Process Boundary Conditions"<<std::endl; BoundaryConditionsContainer<elementDim,spaceDim,probDim> bcc; std::vector<bool> areNeumannBoundaryConditions(probDim, true); std::vector<ConstBoundaryCondition<spaceDim>*> vectorConstBCs; for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++){ vectorConstBCs.push_back(new ConstBoundaryCondition<spaceDim>(bcValues[pdeDim])); } for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { if(areNeumannBoundaryConditions[pdeDim]==false) { for (TetrahedralMesh<elementDim,spaceDim>::BoundaryNodeIterator node_iter = p_mesh->GetBoundaryNodeIteratorBegin(); node_iter != p_mesh->GetBoundaryNodeIteratorEnd(); ++node_iter) { bcc.AddDirichletBoundaryCondition(*node_iter, vectorConstBCs[pdeDim], pdeDim); } }else{ for (TetrahedralMesh<elementDim,spaceDim>::BoundaryElementIterator boundary_iter = p_mesh->GetBoundaryElementIteratorBegin(); boundary_iter != p_mesh->GetBoundaryElementIteratorEnd(); boundary_iter++) { bcc.AddNeumannBoundaryCondition(*boundary_iter, vectorConstBCs[pdeDim], pdeDim); } } } std::cout<<"Initial conditions"<<std::endl; // initial conditions std::vector<double> init_conds(probDim*p_mesh->GetNumNodes()); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { // set as being a random perturbation about the boundary values for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { // serialised for nodes init_conds[probDim*i + pdeDim] = fabs(initValues[pdeDim] + RandomNumberGenerator::Instance()->ranf()); } } // PETSc Vec std::cout<<"PETSc Vec"<<std::endl; Vec initial_condition = PetscTools::CreateVec(init_conds); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); // coupled ode system std::cout<<"Ode loop"<<std::endl; std::vector<AbstractOdeSystemForCoupledPdeSystem*> odeSystem; for (unsigned i=0; i<p_mesh->GetNumNodes(); i++){ // number of ode system objects must match the number of nodes, i.e the individual odes may be multi-dimensional odeSystem.push_back(new AbstractChemicalOdeForCoupledPdeSystem(p_mass_action_reaction_system)); } std::cout<<"Number odesAtNodes: "<<p_mesh->GetNumNodes()<<std::endl; // pde system std::cout<<"Pde"<<std::endl; PdeSchnackenbergCoupledPdeOdeSystem<elementDim, spaceDim, probDim> pde(odeSystem[0],1e-4, 1e-2 ); // used the explicitly defined EulerIvpOdeSolver rather than the default defined BackwardEuler method //EulerIvpOdeSolver euler_solver; boost::shared_ptr<EulerIvpOdeSolver> p_solver(new EulerIvpOdeSolver); std::cout<<"Solver"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver(p_mesh, &pde, &bcc,odeSystem,p_solver); // solver properties double t_end = 10; solver.SetTimes(0, t_end); solver.SetTimeStep(1e-2); solver.SetSamplingTimeStep(1e-2); solver.SetOutputDirectory("TestAbstractChemicalOdeOutput_groupMeeting_params3"); solver.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; // clean PetscTools::Destroy(initial_condition); } void TestChemicalOdePdeDiffusion4() { std::cout<<"Mass action kinetics of Schnackenberg using the AbstractChemicalOdeSystem Class"<<std::endl; std::cout<<"-----------------------------"<<std::endl; // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 AbstractChemistry* p_system_chemistry = new AbstractChemistry(); std::vector<AbstractChemical*> p_substrates_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_3 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_3 = std::vector<AbstractChemical*>(); std::vector<unsigned> stoich_substrates_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_3 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_3 = std::vector<unsigned>(); AbstractChemical *p_chemical_U = new AbstractChemical("U"); p_system_chemistry -> AddChemical(p_chemical_U); // add U to reactions p_substrates_1.push_back(p_chemical_U); stoich_substrates_1.push_back(2); p_products_1.push_back(p_chemical_U); stoich_products_1.push_back(3); p_products_2.push_back(p_chemical_U); stoich_products_2.push_back(1); AbstractChemical *p_chemical_V = new AbstractChemical("V"); p_system_chemistry -> AddChemical(p_chemical_V); // add V to reactions p_substrates_1.push_back(p_chemical_V); stoich_substrates_1.push_back(1); p_products_3.push_back(p_chemical_V); stoich_products_3.push_back(1); // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 double reaction_1_rate = 0.3; double reaction_2_forward_rate = 0.3; double reaction_2_reverse_rate = 0.6; double reaction_3_rate = 0.9; AbstractReaction* p_reaction_1 = new AbstractReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,reaction_1_rate); AbstractReversibleReaction* p_reaction_2 = new AbstractReversibleReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,reaction_2_forward_rate, reaction_2_reverse_rate); AbstractReaction* p_reaction_3 = new AbstractReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,reaction_3_rate); std::vector<AbstractReaction*> p_reaction_vector; p_reaction_vector.push_back(p_reaction_1); p_reaction_vector.push_back(p_reaction_2); p_reaction_vector.push_back(p_reaction_3); //AbstractReactionSystem* p_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_reaction_vector); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); MassActionReaction* p_mass_action_reaction_1 = new MassActionReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,false,false,reaction_1_rate); MassActionReaction* p_mass_action_reaction_2 = new MassActionReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,false, true, reaction_2_forward_rate, reaction_2_reverse_rate); MassActionReaction* p_mass_action_reaction_3 = new MassActionReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,false, false,reaction_3_rate); std::vector<AbstractReaction*> p_mass_action_reaction_vector; p_mass_action_reaction_vector.push_back(p_mass_action_reaction_1); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_2); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_3); AbstractReactionSystem* p_mass_action_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_mass_action_reaction_vector); // form ode system std::cout<<"SchnackenbergCoupledPdeOdeSystem -As AbstractChemicalODeSystem"<<std::endl; // system properties const unsigned probDim =2; const unsigned spaceDim=2; const unsigned elementDim=2; std::vector<double> initValues = {2.0, 0.75}; std::vector<double> bcValues = {0.0, 0.0}; // mesh HoneycombMeshGenerator generator(10, 10, 0); MutableMesh<elementDim,spaceDim>* p_mesh = generator.GetMesh(); // Process Boundary Conditions std::cout<<"Process Boundary Conditions"<<std::endl; BoundaryConditionsContainer<elementDim,spaceDim,probDim> bcc; std::vector<bool> areNeumannBoundaryConditions(probDim, true); std::vector<ConstBoundaryCondition<spaceDim>*> vectorConstBCs; for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++){ vectorConstBCs.push_back(new ConstBoundaryCondition<spaceDim>(bcValues[pdeDim])); } for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { if(areNeumannBoundaryConditions[pdeDim]==false) { for (TetrahedralMesh<elementDim,spaceDim>::BoundaryNodeIterator node_iter = p_mesh->GetBoundaryNodeIteratorBegin(); node_iter != p_mesh->GetBoundaryNodeIteratorEnd(); ++node_iter) { bcc.AddDirichletBoundaryCondition(*node_iter, vectorConstBCs[pdeDim], pdeDim); } }else{ for (TetrahedralMesh<elementDim,spaceDim>::BoundaryElementIterator boundary_iter = p_mesh->GetBoundaryElementIteratorBegin(); boundary_iter != p_mesh->GetBoundaryElementIteratorEnd(); boundary_iter++) { bcc.AddNeumannBoundaryCondition(*boundary_iter, vectorConstBCs[pdeDim], pdeDim); } } } std::cout<<"Initial conditions"<<std::endl; // initial conditions std::vector<double> init_conds(probDim*p_mesh->GetNumNodes()); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { // set as being a random perturbation about the boundary values for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { // serialised for nodes init_conds[probDim*i + pdeDim] = fabs(initValues[pdeDim] + RandomNumberGenerator::Instance()->ranf()); } } // PETSc Vec std::cout<<"PETSc Vec"<<std::endl; Vec initial_condition = PetscTools::CreateVec(init_conds); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); // coupled ode system std::cout<<"Ode loop"<<std::endl; std::vector<AbstractOdeSystemForCoupledPdeSystem*> odeSystem; for (unsigned i=0; i<p_mesh->GetNumNodes(); i++){ // number of ode system objects must match the number of nodes, i.e the individual odes may be multi-dimensional odeSystem.push_back(new AbstractChemicalOdeForCoupledPdeSystem(p_mass_action_reaction_system)); } std::cout<<"Number odesAtNodes: "<<p_mesh->GetNumNodes()<<std::endl; // pde system std::cout<<"Pde"<<std::endl; PdeSchnackenbergCoupledPdeOdeSystem<elementDim, spaceDim, probDim> pde(odeSystem[0],1e-3, 1e-1 ); // used the explicitly defined EulerIvpOdeSolver rather than the default defined BackwardEuler method //EulerIvpOdeSolver euler_solver; boost::shared_ptr<EulerIvpOdeSolver> p_solver(new EulerIvpOdeSolver); std::cout<<"Solver"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver(p_mesh, &pde, &bcc,odeSystem,p_solver); // solver properties double t_end = 10; solver.SetTimes(0, t_end); solver.SetTimeStep(1e-2); solver.SetSamplingTimeStep(1e-2); solver.SetOutputDirectory("TestAbstractChemicalOdeOutput_groupMeeting_diffusion1e-31e-1 "); solver.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; // clean PetscTools::Destroy(initial_condition); } void TestChemicalOdePdeDiffusion3() { std::cout<<"Mass action kinetics of Schnackenberg using the AbstractChemicalOdeSystem Class"<<std::endl; std::cout<<"-----------------------------"<<std::endl; // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 AbstractChemistry* p_system_chemistry = new AbstractChemistry(); std::vector<AbstractChemical*> p_substrates_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_3 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_3 = std::vector<AbstractChemical*>(); std::vector<unsigned> stoich_substrates_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_3 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_3 = std::vector<unsigned>(); AbstractChemical *p_chemical_U = new AbstractChemical("U"); p_system_chemistry -> AddChemical(p_chemical_U); // add U to reactions p_substrates_1.push_back(p_chemical_U); stoich_substrates_1.push_back(2); p_products_1.push_back(p_chemical_U); stoich_products_1.push_back(3); p_products_2.push_back(p_chemical_U); stoich_products_2.push_back(1); AbstractChemical *p_chemical_V = new AbstractChemical("V"); p_system_chemistry -> AddChemical(p_chemical_V); // add V to reactions p_substrates_1.push_back(p_chemical_V); stoich_substrates_1.push_back(1); p_products_3.push_back(p_chemical_V); stoich_products_3.push_back(1); // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 double reaction_1_rate = 0.3; double reaction_2_forward_rate = 0.3; double reaction_2_reverse_rate = 0.6; double reaction_3_rate = 0.9; AbstractReaction* p_reaction_1 = new AbstractReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,reaction_1_rate); AbstractReversibleReaction* p_reaction_2 = new AbstractReversibleReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,reaction_2_forward_rate, reaction_2_reverse_rate); AbstractReaction* p_reaction_3 = new AbstractReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,reaction_3_rate); std::vector<AbstractReaction*> p_reaction_vector; p_reaction_vector.push_back(p_reaction_1); p_reaction_vector.push_back(p_reaction_2); p_reaction_vector.push_back(p_reaction_3); //AbstractReactionSystem* p_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_reaction_vector); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); MassActionReaction* p_mass_action_reaction_1 = new MassActionReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,false,false,reaction_1_rate); MassActionReaction* p_mass_action_reaction_2 = new MassActionReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,false, true, reaction_2_forward_rate, reaction_2_reverse_rate); MassActionReaction* p_mass_action_reaction_3 = new MassActionReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,false, false,reaction_3_rate); std::vector<AbstractReaction*> p_mass_action_reaction_vector; p_mass_action_reaction_vector.push_back(p_mass_action_reaction_1); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_2); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_3); AbstractReactionSystem* p_mass_action_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_mass_action_reaction_vector); // form ode system std::cout<<"SchnackenbergCoupledPdeOdeSystem -As AbstractChemicalODeSystem"<<std::endl; // system properties const unsigned probDim =2; const unsigned spaceDim=2; const unsigned elementDim=2; std::vector<double> initValues = {2.0, 0.75}; std::vector<double> bcValues = {0.0, 0.0}; // mesh HoneycombMeshGenerator generator(10, 10, 0); MutableMesh<elementDim,spaceDim>* p_mesh = generator.GetMesh(); // Process Boundary Conditions std::cout<<"Process Boundary Conditions"<<std::endl; BoundaryConditionsContainer<elementDim,spaceDim,probDim> bcc; std::vector<bool> areNeumannBoundaryConditions(probDim, true); std::vector<ConstBoundaryCondition<spaceDim>*> vectorConstBCs; for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++){ vectorConstBCs.push_back(new ConstBoundaryCondition<spaceDim>(bcValues[pdeDim])); } for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { if(areNeumannBoundaryConditions[pdeDim]==false) { for (TetrahedralMesh<elementDim,spaceDim>::BoundaryNodeIterator node_iter = p_mesh->GetBoundaryNodeIteratorBegin(); node_iter != p_mesh->GetBoundaryNodeIteratorEnd(); ++node_iter) { bcc.AddDirichletBoundaryCondition(*node_iter, vectorConstBCs[pdeDim], pdeDim); } }else{ for (TetrahedralMesh<elementDim,spaceDim>::BoundaryElementIterator boundary_iter = p_mesh->GetBoundaryElementIteratorBegin(); boundary_iter != p_mesh->GetBoundaryElementIteratorEnd(); boundary_iter++) { bcc.AddNeumannBoundaryCondition(*boundary_iter, vectorConstBCs[pdeDim], pdeDim); } } } std::cout<<"Initial conditions"<<std::endl; // initial conditions std::vector<double> init_conds(probDim*p_mesh->GetNumNodes()); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { // set as being a random perturbation about the boundary values for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { // serialised for nodes init_conds[probDim*i + pdeDim] = fabs(initValues[pdeDim] + RandomNumberGenerator::Instance()->ranf()); } } // PETSc Vec std::cout<<"PETSc Vec"<<std::endl; Vec initial_condition = PetscTools::CreateVec(init_conds); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); // coupled ode system std::cout<<"Ode loop"<<std::endl; std::vector<AbstractOdeSystemForCoupledPdeSystem*> odeSystem; for (unsigned i=0; i<p_mesh->GetNumNodes(); i++){ // number of ode system objects must match the number of nodes, i.e the individual odes may be multi-dimensional odeSystem.push_back(new AbstractChemicalOdeForCoupledPdeSystem(p_mass_action_reaction_system)); } std::cout<<"Number odesAtNodes: "<<p_mesh->GetNumNodes()<<std::endl; // pde system std::cout<<"Pde"<<std::endl; PdeSchnackenbergCoupledPdeOdeSystem<elementDim, spaceDim, probDim> pde(odeSystem[0],1e-2, 1 ); // used the explicitly defined EulerIvpOdeSolver rather than the default defined BackwardEuler method //EulerIvpOdeSolver euler_solver; boost::shared_ptr<EulerIvpOdeSolver> p_solver(new EulerIvpOdeSolver); std::cout<<"Solver"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver(p_mesh, &pde, &bcc,odeSystem,p_solver); // solver properties double t_end = 10; solver.SetTimes(0, t_end); solver.SetTimeStep(1e-2); solver.SetSamplingTimeStep(1e-2); solver.SetOutputDirectory("TestAbstractChemicalOdeOutput_groupMeeting_diffusion1e-21e-0 "); solver.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; // clean PetscTools::Destroy(initial_condition); } }; #endif
48.37922
212
0.656184
OSS-Lab
63d2dbb37e19b9e98ee0d5ce0dc7cc453047432c
432
cpp
C++
src/3rdPartyLib/EASTL.cpp
SapphireEngine/Engine
bf5a621ac45d76a2635b804c0d8b023f1114d8f5
[ "MIT" ]
2
2020-02-03T04:58:17.000Z
2021-03-13T06:03:52.000Z
src/3rdPartyLib/EASTL.cpp
SapphireEngine/Engine
bf5a621ac45d76a2635b804c0d8b023f1114d8f5
[ "MIT" ]
null
null
null
src/3rdPartyLib/EASTL.cpp
SapphireEngine/Engine
bf5a621ac45d76a2635b804c0d8b023f1114d8f5
[ "MIT" ]
null
null
null
#include "define.h" #include <EASTL/EAStdC/EAMemory.cpp> #include <EASTL/EAStdC/EASprintf.cpp> #include <EASTL/MemoryTracking.cpp> #include <EASTL/allocator_forge.cpp> #include <EASTL/assert.cpp> #include <EASTL/fixed_pool.cpp> #include <EASTL/hashtable.cpp> #include <EASTL/intrusive_list.cpp> #include <EASTL/numeric_limits.cpp> #include <EASTL/red_black_tree.cpp> #include <EASTL/string.cpp> #include <EASTL/thread_support.cpp>
28.8
37
0.784722
SapphireEngine
63d4d437895d91607a767b9af49b58f1abe98e8a
15,529
cpp
C++
src/FeatureMatcher.cpp
charlie-lee/slam_demo
0bb6cc6d20c6a728eea502a61456f83881144e59
[ "MIT" ]
null
null
null
src/FeatureMatcher.cpp
charlie-lee/slam_demo
0bb6cc6d20c6a728eea502a61456f83881144e59
[ "MIT" ]
null
null
null
src/FeatureMatcher.cpp
charlie-lee/slam_demo
0bb6cc6d20c6a728eea502a61456f83881144e59
[ "MIT" ]
null
null
null
/** * @file FeatureMatcher.cpp * @brief Implementation of feature matcher class in SLAM system. * @author Charlie Li * @date 2019.10.22 */ #include "FeatureMatcher.hpp" #include <map> #include <memory> #include <vector> #include <opencv2/core.hpp> #include <opencv2/features2d.hpp> #include "Config.hpp" #include "FrameBase.hpp" #include "MapPoint.hpp" #include "Utility.hpp" namespace SLAM_demo { using cv::Mat; using std::make_shared; using std::map; using std::shared_ptr; using std::vector; FeatureMatcher::FeatureMatcher(float thDistMatchMax, bool bUseLoweRatioTest, float thRatioTest, float thAngMatchMax, int thDistDescMax) : mThDistMatchMax(thDistMatchMax), mbUseLoweRatioTest(bUseLoweRatioTest), mThRatioTest(thRatioTest), mThAngMatchMax(thAngMatchMax), mThDistDescMax(thDistDescMax) { // initialize feature matcher if (mbUseLoweRatioTest) { // FLANN-based matcher & use Lowe's ratio test //mpFeatMatcher = make_shared<cv::FlannBasedMatcher>( // cv::makePtr<cv::flann::LshIndexParams>(12, 20, 2)); mpFeatMatcher = cv::BFMatcher::create(cv::NORM_HAMMING, false); } else { // use symmetric test mpFeatMatcher = cv::BFMatcher::create(cv::NORM_HAMMING, true); } } std::vector<cv::DMatch> FeatureMatcher::match2Dto2D( const std::shared_ptr<FrameBase>& pF2, const std::shared_ptr<FrameBase>& pF1) const { unsigned nBestMatches = mbUseLoweRatioTest ? 2 : 1; vector<vector<cv::DMatch>> vvMatches21; mpFeatMatcher->knnMatch(pF2->descriptors(), // query pF1->descriptors(), // train vvMatches21, nBestMatches); // number of best matches return filterMatchResult(vvMatches21, pF2, pF1); } std::vector<cv::DMatch> FeatureMatcher::match2Dto2DCustom( const std::shared_ptr<FrameBase>& pF2, const std::shared_ptr<FrameBase>& pF1) const { vector<cv::DMatch> vMatches21; vector<cv::KeyPoint> vKpts2 = pF2->keypoints(); vMatches21.reserve(vKpts2.size()); // traverse each keypoint in frame 2 for its match in frame 1 for (unsigned i = 0; i < vKpts2.size(); ++i) { const cv::KeyPoint& kpt2 = vKpts2[i]; float angle = kpt2.angle; Mat desc2 = pF2->descriptor(i); vector<int> vKptIndices = pF1->featuresInRange( Mat(kpt2.pt), angle, mThDistMatchMax, mThAngMatchMax); // traverse each keypoint index and get best match int nBestIdx1 = -1; // for frame 1 int nBestDist = 256; int nBestDist2nd = 256; for (const int& kptIdx : vKptIndices) { Mat desc1 = pF1->descriptor(kptIdx); int nDist = hammingDistance(desc2, desc1); if (nDist < nBestDist) { nBestDist2nd = nBestDist; nBestDist = nDist; nBestIdx1 = kptIdx; } } if (nBestIdx1 < 0 || nBestDist > mThDistDescMax) { continue; } // Lowe's ratio test if (static_cast<float>(nBestDist) >= mThRatioTest * nBestDist2nd) { continue; } // construct cv::DMatch object cv::DMatch match21(i, nBestIdx1, static_cast<float>(nBestDist)); vMatches21.push_back(match21); } return vMatches21; } std::vector<cv::DMatch> FeatureMatcher::match2Dto3D( const std::shared_ptr<FrameBase>& pF2, const std::shared_ptr<FrameBase>& pF1, bool bBindMPts) const { unsigned nBestMatches = mbUseLoweRatioTest ? 2 : 1; // get matching mask map<int, shared_ptr<MapPoint>> mpMPts1 = pF1->getMPtsMap(); //const vector<cv::KeyPoint>& vKpts1 = pF1->keypoints(); //const vector<cv::KeyPoint>& vKpts2 = pF2->keypoints(); //vector<int> vIdxKpts1; //vIdxKpts1.reserve(mpMPts1.size()); //for (const auto& pair : mpMPts1) { // vIdxKpts1.push_back(pair.first); //} //Mat mask = getMatchMask2Dto3D(vIdxKpts1, vKpts2.size(), vKpts1.size()); vector<bool> vbMPtsValid(pF1->keypoints().size(), false); for (const auto& pair : mpMPts1) { vbMPtsValid[pair.first] = true; } // feature matching with mask (partial query set and full train set) vector<vector<cv::DMatch>> vvMatches21; mpFeatMatcher->knnMatch(pF2->descriptors(), // query pF1->descriptors(), // train vvMatches21, nBestMatches, //mask, true); // mask is not functioning!!! cv::noArray(), false); vector<cv::DMatch> vMatches21 = filterMatchResult(vvMatches21, pF2, pF1, vbMPtsValid); // update map point data on current frame (pF2) if (bBindMPts) { for (const auto& match21 : vMatches21) { shared_ptr<MapPoint> pMPt = pF1->mappoint(match21.trainIdx); pF2->bindMPt(pMPt, match21.queryIdx); } } return vMatches21; } std::vector<cv::DMatch> FeatureMatcher::match2Dto3D( const std::shared_ptr<FrameBase>& pF2, const std::vector<std::shared_ptr<MapPoint>>& vpMPts, bool bBindMPts) const { unsigned nBestMatches = mbUseLoweRatioTest ? 2 : 1; // get all descriptors Mat descXws; for (const auto& pMPt : vpMPts) { descXws.push_back(pMPt->descriptor()); } if (descXws.empty()) { return vector<cv::DMatch>(); } // feature matching with mask (partial query set and full train set) vector<vector<cv::DMatch>> vvMatches21; mpFeatMatcher->knnMatch(pF2->descriptors(), // query descXws, // train vvMatches21, nBestMatches); vector<cv::DMatch> vMatches21 = filterMatchResult(vvMatches21, pF2, vpMPts); // update map point data on current frame (pF2) if (bBindMPts) { for (const auto& match21 : vMatches21) { shared_ptr<MapPoint> pMPt = vpMPts[match21.trainIdx]; pF2->bindMPt(pMPt, match21.queryIdx); } } return vMatches21; } std::vector<cv::DMatch> FeatureMatcher::match2Dto3DCustom( const std::shared_ptr<FrameBase>& pF2, const std::shared_ptr<FrameBase>& pF1, bool bBindMPts) const { vector<cv::DMatch> vMatches21; map<int, shared_ptr<MapPoint>> mpMPts1 = pF1->getMPtsMap(); vMatches21.reserve(mpMPts1.size()); // traverse each 3D point for its 2D match for (const auto& pair : mpMPts1) { const shared_ptr<MapPoint>& pMPt = pair.second; Mat x = pF2->coordWorld2Img(pMPt->X3D()); // skip out-of-border reprojected points if (!Utility::is2DPtInBorder(x)) { continue; } float angle = pMPt->angle(); Mat desc1 = pMPt->descriptor(); vector<int> vKptIndices = pF2->featuresInRange( x, angle, mThDistMatchMax, mThAngMatchMax); // traverse each keypoint index and get best match int nBestIdx2 = -1; // for frame 2 int nBestDist = 256; int nBestDist2nd = 256; for (const int& kptIdx : vKptIndices) { Mat desc2 = pF2->descriptor(kptIdx); int nDist = hammingDistance(desc2, desc1); if (nDist < nBestDist) { nBestDist2nd = nBestDist; nBestDist = nDist; nBestIdx2 = kptIdx; } } if (nBestIdx2 < 0 || nBestDist > mThDistDescMax) { continue; } // Lowe's ratio test if (static_cast<float>(nBestDist) >= mThRatioTest * nBestDist2nd) { continue; } // construct cv::DMatch object int nIdx1 = pair.first; // frame 1 cv::DMatch match21(nBestIdx2, nIdx1, static_cast<float>(nBestDist)); vMatches21.push_back(match21); } // update map point data on current frame (pF2) if (bBindMPts) { for (const auto& match21 : vMatches21) { shared_ptr<MapPoint> pMPt = pF1->mappoint(match21.trainIdx); pF2->bindMPt(pMPt, match21.queryIdx); } } return vMatches21; } std::vector<cv::DMatch> FeatureMatcher::match2Dto3DCustom( const std::shared_ptr<FrameBase>& pF2, const std::vector<std::shared_ptr<MapPoint>>& vpMPts, bool bBindMPts) const { vector<cv::DMatch> vMatches21; int nMPts = vpMPts.size(); vMatches21.reserve(nMPts); // traverse each 3D point for its 2D match for (int i = 0; i < nMPts; ++i) { const auto& pMPt = vpMPts[i]; Mat x = pF2->coordWorld2Img(pMPt->X3D()); // skip out-of-border reprojected points if (!Utility::is2DPtInBorder(x)) { continue; } float angle = pMPt->angle(); Mat desc1 = pMPt->descriptor(); vector<int> vKptIndices = pF2->featuresInRange( x, angle, mThDistMatchMax, mThAngMatchMax); // traverse each keypoint index and get best match int nBestIdx2 = -1; // for frame 2 int nBestDist = 256; int nBestDist2nd = 256; for (const int& kptIdx : vKptIndices) { Mat desc2 = pF2->descriptor(kptIdx); int nDist = hammingDistance(desc2, desc1); if (nDist < nBestDist) { nBestDist2nd = nBestDist; nBestDist = nDist; nBestIdx2 = kptIdx; } } if (nBestIdx2 < 0 || nBestDist > mThDistDescMax) { continue; } // Lowe's ratio test if (static_cast<float>(nBestDist) >= mThRatioTest * nBestDist2nd) { continue; } // construct cv::DMatch object int nIdx1 = i; // frame 1 cv::DMatch match21(nBestIdx2, nIdx1, static_cast<float>(nBestDist)); vMatches21.push_back(match21); } // update map point data on current frame (pF2) if (bBindMPts) { for (const auto& match21 : vMatches21) { shared_ptr<MapPoint> pMPt = vpMPts[match21.trainIdx]; pF2->bindMPt(pMPt, match21.queryIdx); } } return vMatches21; } std::vector<cv::DMatch> FeatureMatcher::filterMatchResult( const std::vector<std::vector<cv::DMatch>>& vvMatches21, const std::shared_ptr<FrameBase>& pF2, const std::shared_ptr<FrameBase>& pF1, const std::vector<bool>& vbMask1) const { vector<cv::DMatch> vMatches21; vMatches21.reserve(vvMatches21.size()); unsigned nBestMatches = mbUseLoweRatioTest ? 2 : 1; const vector<cv::KeyPoint>& vKpts1 = pF1->keypoints(); const vector<cv::KeyPoint>& vKpts2 = pF2->keypoints(); bool b2Dto2DCase = vbMask1.empty() ? true : false; for (unsigned i = 0; i < vvMatches21.size(); ++i) { // skip invalid matching result if (vvMatches21[i].size() != nBestMatches) { continue; } // skip null map point if (!b2Dto2DCase && !vbMask1[vvMatches21[i][0].trainIdx]) { continue; } // Lowe's ratio test if (nBestMatches == 2 && vvMatches21[i][0].distance >= mThRatioTest * vvMatches21[i][1].distance) { continue; } // filter out-of-border matches const cv::Point2f& pt1 = vKpts1[vvMatches21[i][0].trainIdx].pt; const cv::Point2f& pt2 = vKpts2[vvMatches21[i][0].queryIdx].pt; if (!Utility::is2DPtInBorder(Mat(pt1)) && !Utility::is2DPtInBorder(Mat(pt2))) { continue; } // filter matches whose dist between (reprojected) 2D point in view 1 // and 2D point in view 2 is larger than a threshold Mat x1; if (b2Dto2DCase) { x1 = Mat(pt1); } else { const shared_ptr<MapPoint> pMPt = pF1->mappoint(vvMatches21[i][0].trainIdx); assert(pMPt); x1 = pF1->coordWorld2Img(pMPt->X3D()); } Mat x2 = Mat(pt2); Mat xDiff = x1 - x2; float xDistSq = xDiff.dot(xDiff); if (xDistSq > mThDistMatchMax * mThDistMatchMax) { continue; } vMatches21.push_back(vvMatches21[i][0]); } return vMatches21; } std::vector<cv::DMatch> FeatureMatcher::filterMatchResult( const std::vector<std::vector<cv::DMatch>>& vvMatches21, const std::shared_ptr<FrameBase>& pF2, const std::vector<std::shared_ptr<MapPoint>>& vpMPts) const { vector<cv::DMatch> vMatches21; vMatches21.reserve(vvMatches21.size()); unsigned nBestMatches = mbUseLoweRatioTest ? 2 : 1; const vector<cv::KeyPoint>& vKpts2 = pF2->keypoints(); for (unsigned i = 0; i < vvMatches21.size(); ++i) { // skip invalid matching result if (vvMatches21[i].size() != nBestMatches) { continue; } // Lowe's ratio test if (nBestMatches == 2 && vvMatches21[i][0].distance >= mThRatioTest * vvMatches21[i][1].distance) { continue; } // filter out-of-border matches const shared_ptr<MapPoint>& pMPt = vpMPts[vvMatches21[i][0].trainIdx]; Mat x1 = pF2->coordWorld2Img(pMPt->X3D()); const cv::Point2f& pt1 = cv::Point2f(x1.at<float>(0), x1.at<float>(1)); const cv::Point2f& pt2 = vKpts2[vvMatches21[i][0].queryIdx].pt; if (!Utility::is2DPtInBorder(Mat(pt1)) && !Utility::is2DPtInBorder(Mat(pt2))) { continue; } // filter matches whose dist between (reprojected) 2D point in view 1 // and 2D point in view 2 is larger than a threshold Mat x2 = Mat(pt2); Mat xDiff = x1 - x2; float xDistSq = xDiff.dot(xDiff); if (xDistSq > mThDistMatchMax * mThDistMatchMax) { continue; } vMatches21.push_back(vvMatches21[i][0]); } return vMatches21; } cv::Mat FeatureMatcher::getMatchMask2Dto3D(const std::vector<int>& vIdxKpts1, int nKpts2, int nKpts1) const { Mat mask; // {row = vIdxKpts1.size(), col = nNumKpts2, type = CV_8UC1} int idx = 0; int nMPts = vIdxKpts1.size(); for (int i = 0; i < nKpts1; ++i) { bool bAllowMatching = false; if (idx == nMPts) { // last kpt index traversed bAllowMatching = false; } else { if (i < vIdxKpts1[idx]) { // less than nearest kpt index bAllowMatching = false; } else { // kpt index with map point bound bAllowMatching = true; } } // add one row to the transpose of mask if (bAllowMatching) { mask.push_back(Mat::ones(1, nKpts2, CV_8UC1)); ++idx; } else { mask.push_back(Mat::zeros(1, nKpts2, CV_8UC1)); } } mask = mask.t(); assert(mask.rows == nKpts2 && mask.cols == nKpts1); return mask; } int FeatureMatcher::hammingDistance(const cv::Mat& a, const cv::Mat& b) const { // Bit set count operation from const int* pa = a.ptr<int32_t>(); const int* pb = b.ptr<int32_t>(); int nDist = 0; for(int i = 0; i < 8; i++, pa++, pb++) { unsigned int v = *pa ^ *pb; v = v - ((v >> 1) & 0x55555555); v = (v & 0x33333333) + ((v >> 2) & 0x33333333); nDist += (((v + (v >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24; } return nDist; } } // namespace SLAM_demo
36.198135
79
0.58072
charlie-lee
63e18aab313c11a3524d142c4f0b1cbba7d1e49e
3,390
cpp
C++
CppP4rhSln/10/querymain.cpp
blacop/CppPR
a76574ee83000d898d989aab96eac4ac746244fa
[ "MIT" ]
1
2017-04-01T06:57:30.000Z
2017-04-01T06:57:30.000Z
gnu_files/10/querymain.cc
hongmi/cpp-primer-4-exercises
98ddb98b41d457a1caa525d246dfb7453be0c8d2
[ "MIT" ]
null
null
null
gnu_files/10/querymain.cc
hongmi/cpp-primer-4-exercises
98ddb98b41d457a1caa525d246dfb7453be0c8d2
[ "MIT" ]
1
2022-01-25T15:51:34.000Z
2022-01-25T15:51:34.000Z
/* * This file contains code from "C++ Primer, Fourth Edition", by Stanley B. * Lippman, Jose Lajoie, and Barbara E. Moo, and is covered under the * copyright and warranty notices given in that book: * * "Copyright (c) 2005 by Objectwrite, Inc., Jose Lajoie, and Barbara E. Moo." * * * "The authors and publisher have taken care in the preparation of this book, * but make no expressed or implied warranty of any kind and assume no * responsibility for errors or omissions. No liability is assumed for * incidental or consequential damages in connection with or arising out of the * use of the information or programs contained herein." * * Permission is granted for this code to be used for educational purposes in * association with the book, given proper citation if and when posted or * reproduced.Any commercial use of this code requires the explicit written * permission of the publisher, Addison-Wesley Professional, a division of * Pearson Education, Inc. Send your request for permission, stating clearly * what code you would like to use, and in what specific way, to the following * address: * * Pearson Education, Inc. * Rights and Contracts Department * 75 Arlington Street, Suite 300 * Boston, MA 02216 * Fax: (617) 848-7047 */ #include "TextQuery.h" #include <string> #include <vector> #include <map> #include <set> #include <iostream> #include <fstream> #include <cctype> #include <cstring> #include <cstdlib> using std::set; using std::string; using std::map; using std::vector; using std::cerr; using std::cout; using std::cin; using std::ifstream; using std::endl; string make_plural(size_t, const string&, const string&); ifstream& open_file(ifstream&, const string&); void print_results(const set<TextQuery::line_no>& locs, const string& sought, const TextQuery &file) { // if the word was found, then print count and all occurrences typedef set<TextQuery::line_no> line_nums; line_nums::size_type size = locs.size(); cout << "\n" << sought << " occurs " << size << " " << make_plural(size, "time", "s") << endl; // print each line in which the word appeared line_nums::const_iterator it = locs.begin(); for ( ; it != locs.end(); ++it) { cout << "\t(line " // don't confound user with text lines starting at 0 << (*it) + 1 << ") " << file.text_line(*it) << endl; } } // program takes single argument specifying the file to query int main(int argc, char **argv) { // open the file from which user will query words ifstream infile; if (argc < 2 || !open_file(infile, argv[1])) { cerr << "No input file!" << endl; return EXIT_FAILURE; } TextQuery tq; tq.read_file(infile); // builds query map // iterate with the user: prompt for a word to find and print results // loop indefinitely; the loop exit is inside the while while (true) { cout << "enter word to look for, or q to quit: "; string s; cin >> s; // stop if hit eof on input or a 'q' is entered if (!cin || s == "q") break; // get the set of line numbers on which this word appears set<TextQuery::line_no> locs = tq.run_query(s); // print count and all occurrences, if any print_results(locs, s, tq); } return 0; }
32.596154
79
0.657227
blacop
63eb7f8c7b92d5f5920e96694250197b72c0a9c1
4,333
cpp
C++
remodet_repository_wdh_part/src/caffe/pose/pose_image_loader.cpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
remodet_repository_wdh_part/src/caffe/pose/pose_image_loader.cpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
remodet_repository_wdh_part/src/caffe/pose/pose_image_loader.cpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
#include "caffe/tracker/bounding_box.hpp" #include "caffe/pose/pose_image_loader.hpp" namespace caffe { using std::vector; using std::string; template <typename Dtype> void PoseImageLoader<Dtype>::LoadImage(const int image_num, cv::Mat* image) { const MetaData<Dtype>& annotation = annotations_[image_num]; const string& image_file = annotation.img_path; *image = cv::imread(image_file.c_str()); if (!image->data) { LOG(FATAL) << "Could not open or find image: " << image_file; return; } } template <typename Dtype> void PoseImageLoader<Dtype>::LoadAnnotation(const int image_num, cv::Mat* image, MetaData<Dtype>* meta) { const MetaData<Dtype>& annotation = annotations_[image_num]; const string& image_file = annotation.img_path; *image = cv::imread(image_file.c_str()); if (!image->data) { LOG(FATAL) << "Could not open or find image: " << image_file; return; } *meta = annotation; } template <typename Dtype> void PoseImageLoader<Dtype>::ShowImages() { for (int i = 0; i < annotations_.size(); ++i) { cv::Mat image; LoadImage(i, &image); cv::namedWindow("Imageshow", cv::WINDOW_AUTOSIZE); cv::imshow("Imageshow", image); cv::waitKey(0); } } template <typename Dtype> void PoseImageLoader<Dtype>::ShowAnnotations(const bool show_bbox) { for (int i = 0; i < annotations_.size(); ++i) { cv::Mat image; drawAnnotations(i, show_bbox, &image); cv::namedWindow("ImageShow", cv::WINDOW_AUTOSIZE); cv::imshow("ImageShow", image); cv::waitKey(0); } } template <typename Dtype> void PoseImageLoader<Dtype>::ShowAnnotationsRand(const bool show_bbox) { while (true) { const int image_num = rand() % annotations_.size(); cv::Mat image; drawAnnotations(image_num, show_bbox, &image); cv::namedWindow("ImageShow", cv::WINDOW_AUTOSIZE); cv::imshow("ImageShow", image); cv::waitKey(0); } } template <typename Dtype> void PoseImageLoader<Dtype>::Saving(const std::string& output_folder, const bool show_bbox) { for (int i = 0; i < annotations_.size(); ++i) { cv::Mat image; drawAnnotations(i, show_bbox, &image); // save int delim_pos = annotations_[i].img_path.find_last_of("/"); const string& file_name = annotations_[i].img_path.substr(delim_pos+1, annotations_[i].img_path.length()); const string& output_file = output_folder + "/" + file_name; LOG(INFO) << "saving image: " << file_name; imwrite(output_file, image); } } template <typename Dtype> void PoseImageLoader<Dtype>::merge_from(const PoseImageLoader<Dtype>* dst) { const std::vector<MetaData<Dtype> >& dst_annos = dst->get_annotations(); if (dst_annos.size() == 0) return; for (int i = 0; i < dst_annos.size(); ++i) { annotations_.push_back(dst_annos[i]); } LOG(INFO) << "Add " << dst_annos.size() << " Images."; } template <typename Dtype> void PoseImageLoader<Dtype>::drawAnnotations(const int image_num, const bool show_bbox, cv::Mat* dst_image) { cv::Mat image; MetaData<Dtype> meta; LoadAnnotation(image_num, &image, &meta); *dst_image = image.clone(); // 绘制 if (show_bbox) { // 绿色box drawbox(meta, dst_image); } // 红色关节点 drawkps(meta, dst_image); } template <typename Dtype> void PoseImageLoader<Dtype>::drawbox(const MetaData<Dtype>& meta, cv::Mat* image_out) { // bbox const BoundingBox<Dtype>& bbox = meta.bbox; bbox.Draw(0,255,0,image_out); // bbox of others for (int i = 0; i < meta.bbox_others.size(); ++i) { const BoundingBox<Dtype>& bbox_op = meta.bbox_others[i]; bbox_op.Draw(0,255,0,image_out); } } template <typename Dtype> void PoseImageLoader<Dtype>::drawkps(const MetaData<Dtype>& meta, cv::Mat* image_out) { const int num_kps = meta.joint_self.joints.size(); // draw self for(int i = 0; i < num_kps; i++) { if(meta.joint_self.isVisible[i] <= 1) circle(*image_out, meta.joint_self.joints[i], 5, CV_RGB(255,0,0), -1); } // joints of others for(int p = 0; p < meta.numOtherPeople; p++) { for(int i = 0; i < num_kps; i++) { if(meta.joint_others[p].isVisible[i] <= 1) circle(*image_out, meta.joint_others[p].joints[i], 5, CV_RGB(255,0,0), -1); } } } INSTANTIATE_CLASS(PoseImageLoader); }
31.172662
110
0.654512
UrwLee
63f6fa2c9f29c616e55147f84b272e01aedd2d6c
607
cpp
C++
DemoLib2/net/netmessages/NetSetPauseMessage.cpp
PazerOP/DemoLib2
7377f87654ce9bf6487d6b7ce7050cec8e76894e
[ "MIT" ]
14
2018-07-02T19:09:18.000Z
2022-01-12T12:35:43.000Z
DemoLib2/net/netmessages/NetSetPauseMessage.cpp
PazerOP/DemoLib2
7377f87654ce9bf6487d6b7ce7050cec8e76894e
[ "MIT" ]
1
2018-12-27T20:22:06.000Z
2020-01-04T03:27:31.000Z
DemoLib2/net/netmessages/NetSetPauseMessage.cpp
PazerOP/DemoLib2
7377f87654ce9bf6487d6b7ce7050cec8e76894e
[ "MIT" ]
1
2021-05-17T01:03:38.000Z
2021-05-17T01:03:38.000Z
#include "NetSetPauseMessage.hpp" #include "BitIO/BitIOReader.hpp" #include "BitIO/BitIOWriter.hpp" #include "net/worldstate/WorldState.hpp" void NetSetPauseMessage::GetDescription(std::ostream& description) const { description << "svc_SetPause: " << (m_Paused ? "paused" : "unpaused"); } void NetSetPauseMessage::ApplyWorldState(WorldState& world) const { world.m_Paused = m_Paused; } void NetSetPauseMessage::ReadElementInternal(BitIOReader& reader) { m_Paused = reader.ReadBit("is paused?"); } void NetSetPauseMessage::WriteElementInternal(BitIOWriter& writer) const { writer.Write(m_Paused); }
23.346154
72
0.771005
PazerOP
63fdac942da04b00c862c9de13d84239334be3d7
1,446
cpp
C++
avs_dx/DxVisuals/Threads/RenderThreadImpl.cpp
Const-me/vis_avs_dx
da1fd9f4323d7891dea233147e6ae16790ad9ada
[ "MIT" ]
33
2019-01-28T03:32:17.000Z
2022-02-12T18:17:26.000Z
avs_dx/DxVisuals/Threads/RenderThreadImpl.cpp
visbot/vis_avs_dx
03e55f8932a97ad845ff223d3602ff2300c3d1d4
[ "MIT" ]
2
2019-11-18T17:54:58.000Z
2020-07-21T18:11:21.000Z
avs_dx/DxVisuals/Threads/RenderThreadImpl.cpp
Const-me/vis_avs_dx
da1fd9f4323d7891dea233147e6ae16790ad9ada
[ "MIT" ]
5
2019-02-16T23:00:11.000Z
2022-03-27T15:22:10.000Z
#include "stdafx.h" #include "RenderThreadImpl.h" #include "AvsThreads.h" #include "effects.h" #include "Resources/staticResources.h" #include "Effects/Video/MF/mfStatic.h" #include "Render/Profiler.h" #include <Interop/deviceCreation.h> #include "Transition.h" RenderThreadImpl::RenderThreadImpl( winampVisModule * pModule ) : RenderThread( pModule ) { } RenderThreadImpl::~RenderThreadImpl() { logShutdown( "~RenderThreadImpl #1" ); // This will call the GUI thread to destroy rendering and profiler windows, so we can cleanup D3D device and associated resources. // Some resources, notably the video engine, have thread affinity, they must be released before MfShutdown() and CoUninitialize() calls. // Besides, we want to be sure the GUI thread will no longer present these frames, doing that after resources are released would prolly crash Winamp. RenderWindow::instance().shutdown(); logShutdown( "~RenderThreadImpl, #2" ); destroyAllEffects(); destroyTransitionInstance(); StaticResources::destroy(); mfShutdown(); gpuProfiler().shutdown(); destroyDevice(); comUninitialize(); logShutdown( "~RenderThreadImpl #3" ); } HRESULT RenderThreadImpl::initialize() { return RenderThread::startup(); } CSize getRenderSize(); HRESULT RenderThreadImpl::run() { while( !shouldQuit() ) { RenderThread::renderFrame(); const float fps = m_fps.update(); RenderThread::updateStats( getRenderSize(), fps ); } return S_OK; }
27.807692
150
0.750346
Const-me
63ff97d65ed29764176ac3d1376b2812f72af305
8,453
cpp
C++
Source/Lutefisk3D/Scene/ObjectAnimation.cpp
Lutefisk3D/lutefisk3d
d2132b82003427511df0167f613905191b006eb5
[ "Apache-2.0" ]
2
2018-04-14T19:05:23.000Z
2020-05-10T22:42:12.000Z
Source/Lutefisk3D/Scene/ObjectAnimation.cpp
Lutefisk3D/lutefisk3d
d2132b82003427511df0167f613905191b006eb5
[ "Apache-2.0" ]
4
2015-06-19T22:32:07.000Z
2017-04-05T06:01:50.000Z
Source/Lutefisk3D/Scene/ObjectAnimation.cpp
nemerle/lutefisk3d
d2132b82003427511df0167f613905191b006eb5
[ "Apache-2.0" ]
1
2015-12-27T15:36:10.000Z
2015-12-27T15:36:10.000Z
// // Copyright (c) 2008-2017 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "ObjectAnimation.h" #include "Lutefisk3D/Core/Context.h" #include "SceneEvents.h" #include "ValueAnimation.h" #include "ValueAnimationInfo.h" #include "Lutefisk3D/Resource/XMLFile.h" #include "Lutefisk3D/Resource/JSONFile.h" namespace Urho3D { //instantiate the template template class LUTEFISK3D_EXPORT SharedPtr<ObjectAnimation>; const char* wrapModeNames[] = { "Loop", "Once", "Clamp", nullptr }; ObjectAnimation::ObjectAnimation(Context* context) : Resource(context) { } /// Register object factory. void ObjectAnimation::RegisterObject(Context* context) { context->RegisterFactory<ObjectAnimation>(); } /// Load resource from stream. May be called from a worker thread. Return true if successful. bool ObjectAnimation::BeginLoad(Deserializer& source) { XMLFile xmlFile(context_); if (!xmlFile.Load(source)) return false; return LoadXML(xmlFile.GetRoot()); } /// Save resource. Return true if successful. bool ObjectAnimation::Save(Serializer& dest) const { XMLFile xmlFile(context_); XMLElement rootElem = xmlFile.CreateRoot("objectanimation"); if (!SaveXML(rootElem)) return false; return xmlFile.Save(dest); } /// Load from XML data. Return true if successful. bool ObjectAnimation::LoadXML(const XMLElement& source) { attributeAnimationInfos_.clear(); XMLElement animElem; animElem = source.GetChild("attributeanimation"); while (animElem) { QString name = animElem.GetAttribute("name"); SharedPtr<ValueAnimation> animation(new ValueAnimation(context_)); if (!animation->LoadXML(animElem)) return false; QString wrapModeString = animElem.GetAttribute("wrapmode"); WrapMode wrapMode = WM_LOOP; for (int i = 0; i <= WM_CLAMP; ++i) { if (wrapModeString == wrapModeNames[i]) { wrapMode = (WrapMode)i; break; } } float speed = animElem.GetFloat("speed"); AddAttributeAnimation(name, animation, wrapMode, speed); animElem = animElem.GetNext("attributeanimation"); } return true; } /// Save as XML data. Return true if successful. bool ObjectAnimation::SaveXML(XMLElement& dest) const { for (auto elem=attributeAnimationInfos_.begin(),fin=attributeAnimationInfos_.end(); elem != fin; ++elem) { XMLElement animElem = dest.CreateChild("attributeanimation"); animElem.SetAttribute("name", MAP_KEY(elem)); const ValueAnimationInfo* info = MAP_VALUE(elem); if (!info->GetAnimation()->SaveXML(animElem)) return false; animElem.SetAttribute("wrapmode", wrapModeNames[info->GetWrapMode()]); animElem.SetFloat("speed", info->GetSpeed()); } return true; } /// Load from JSON data. Return true if successful. bool ObjectAnimation::LoadJSON(const JSONValue& source) { attributeAnimationInfos_.clear(); JSONValue attributeAnimationsValue = source.Get("attributeanimations"); if (attributeAnimationsValue.IsNull()) return true; if (!attributeAnimationsValue.IsObject()) return true; const JSONObject& attributeAnimationsObject = attributeAnimationsValue.GetObject(); for (const auto & ob : attributeAnimationsObject) { QString name = ELEMENT_KEY(ob); JSONValue value = ELEMENT_VALUE(ob); SharedPtr<ValueAnimation> animation(new ValueAnimation(context_)); if (!animation->LoadJSON(value)) return false; QString wrapModeString = value.Get("wrapmode").GetString(); WrapMode wrapMode = WM_LOOP; for (int i = 0; i <= WM_CLAMP; ++i) { if (wrapModeString == wrapModeNames[i]) { wrapMode = (WrapMode)i; break; } } float speed = value.Get("speed").GetFloat(); AddAttributeAnimation(name, animation, wrapMode, speed); } return true; } /// Save as JSON data. Return true if successful. bool ObjectAnimation::SaveJSON(JSONValue& dest) const { JSONValue attributeAnimationsValue; for (auto &elem : attributeAnimationInfos_) { JSONValue animValue; animValue.Set("name", ELEMENT_KEY(elem)); const ValueAnimationInfo* info = ELEMENT_VALUE(elem); if (!info->GetAnimation()->SaveJSON(animValue)) return false; animValue.Set("wrapmode", wrapModeNames[info->GetWrapMode()]); animValue.Set("speed", (float) info->GetSpeed()); attributeAnimationsValue.Set(ELEMENT_KEY(elem), animValue); } dest.Set("attributeanimations", attributeAnimationsValue); return true; } /// Add attribute animation, attribute name can in following format: "attribute" or "#0/#1/attribute" or ""#0/#1/@component#1/attribute. void ObjectAnimation::AddAttributeAnimation(const QString& name, ValueAnimation* attributeAnimation, WrapMode wrapMode, float speed) { if (attributeAnimation == nullptr) return; attributeAnimation->SetOwner(this); attributeAnimationInfos_[name] = new ValueAnimationInfo(attributeAnimation, wrapMode, speed); attributeAnimationAdded(this,name); } /// Remove attribute animation, attribute name can in following format: "attribute" or "#0/#1/attribute" or ""#0/#1/@component#1/attribute. void ObjectAnimation::RemoveAttributeAnimation(const QString& name) { HashMap<QString, SharedPtr<ValueAnimationInfo> >::iterator i = attributeAnimationInfos_.find(name); if (i != attributeAnimationInfos_.end()) { attributeAnimationRemoved(this,name); MAP_VALUE(i)->GetAnimation()->SetOwner(nullptr); attributeAnimationInfos_.erase(i); } } /// Remove attribute animation. void ObjectAnimation::RemoveAttributeAnimation(ValueAnimation* attributeAnimation) { if (attributeAnimation == nullptr) return; for (auto i = attributeAnimationInfos_.begin(); i != attributeAnimationInfos_.end(); ++i) { if (MAP_VALUE(i)->GetAnimation() == attributeAnimation) { attributeAnimationRemoved(this,MAP_KEY(i)); attributeAnimation->SetOwner(nullptr); attributeAnimationInfos_.erase(i); return; } } } /// Return attribute animation by name. ValueAnimation* ObjectAnimation::GetAttributeAnimation(const QString& name) const { ValueAnimationInfo* info = GetAttributeAnimationInfo(name); return info != nullptr ? info->GetAnimation() : nullptr; } /// Return attribute animation wrap mode by name. WrapMode ObjectAnimation::GetAttributeAnimationWrapMode(const QString& name) const { ValueAnimationInfo* info = GetAttributeAnimationInfo(name); return info != nullptr ? info->GetWrapMode() : WM_LOOP; } /// Return attribute animation speed by name. float ObjectAnimation::GetAttributeAnimationSpeed(const QString& name) const { ValueAnimationInfo* info = GetAttributeAnimationInfo(name); return info != nullptr ? info->GetSpeed() : 1.0f; } /// Return attribute animation info by name. ValueAnimationInfo* ObjectAnimation::GetAttributeAnimationInfo(const QString& name) const { auto i = attributeAnimationInfos_.find(name); if (i != attributeAnimationInfos_.end()) return MAP_VALUE(i); return nullptr; } }
33.543651
139
0.694428
Lutefisk3D
1201d06b481652931f5eaf2080b47e5a67662579
1,121
cpp
C++
codeforces/CF681/B_Saving_the_City.cpp
anandj123/gcpdemo
96ef4c64047b16f397369c71ace74daa7d43acec
[ "MIT" ]
null
null
null
codeforces/CF681/B_Saving_the_City.cpp
anandj123/gcpdemo
96ef4c64047b16f397369c71ace74daa7d43acec
[ "MIT" ]
null
null
null
codeforces/CF681/B_Saving_the_City.cpp
anandj123/gcpdemo
96ef4c64047b16f397369c71ace74daa7d43acec
[ "MIT" ]
null
null
null
#include<iostream> #include<string> #include<vector> #include<algorithm> #include<cmath> #include<numeric> using namespace std; #define debug(x) cerr << #x << " : " << x << "\n" #define REP(i,a,b) for(int i=a; i<b;++i) #define endl "\n" typedef vector<int> vi; typedef vector< vector<int> > vvi; int INF = 1e9; void calculate(int a, int b, string s) { int len = s.length(); vector<int> dp1(len,0); vector<int> dp2(len,0); // debug(s); // debug(len); int first = a; REP(i,0,len){ //debug(dp1[i-1]); //debug(dp2[i-1]); if(s[i] == '1') { dp1[i] = min((i>0?dp1[i-1]:0) + a, (i>0?dp1[i-1]:0) + (i>0?dp2[i-1]:0)+first); dp2[i] = 0; first = 0; } else { dp1[i] = (i>0?dp1[i-1]:0); dp2[i] = (i>0?dp2[i-1]:0)+ b; } // debug(dp1[i]); // debug(dp2[i]); // debug(i); } cout << dp1[len-1] << endl; } int main() { int T; cin >> T; while(T-- > 0){ int a, b; string s; cin >> a >> b >> s; calculate(a,b,s); } }
20.381818
90
0.447814
anandj123
120399d65cfd059b7bfc2de6649deb58867c33f7
822
cpp
C++
src/libs/qlib/qdmbuffer.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
null
null
null
src/libs/qlib/qdmbuffer.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
null
null
null
src/libs/qlib/qdmbuffer.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
1
2021-01-03T16:16:47.000Z
2021-01-03T16:16:47.000Z
/* * QDMBuffer - definition/implementation * NOTES: * - Tiny wrapper around DMbuffer concept * (C) 28-02-99 MarketGraph/RVG */ #include <qlib/dmbuffer.h> //#include <dmedia/dm_buffer.h> #include <dmedia/dm_params.h> #include <qlib/debug.h> DEBUG_ENABLE #define DMCHK(s,e)\ if((e)!=DM_SUCCESS)QShowDMErrors(s) //if((s)!=DM_SUCCESS)qerr("DM failure: %s",e) /** HELP **/ QDMBuffer::QDMBuffer(DMbuffer buf) { dmbuffer=buf; } QDMBuffer::~QDMBuffer() { } bool QDMBuffer::Attach() { QASSERT_F(dmbuffer); #ifndef WIN32 dmBufferAttach(dmbuffer); #endif return TRUE; } bool QDMBuffer::Free() { QASSERT_F(dmbuffer); #ifndef WIN32 dmBufferFree(dmbuffer); #endif return TRUE; } int QDMBuffer::GetSize() { QASSERT_0(dmbuffer); #ifdef WIN32 return 0; #else return dmBufferGetSize(dmbuffer); #endif }
14.678571
47
0.694647
3dhater
120569b970efd97f4310316d282266bc0dda77d1
22,816
cpp
C++
mp/src/game/server/coven_apc.cpp
rendenba/source-sdk-2013
4a0314391b01a2450788e0d4ee0926a05f3af8b0
[ "Unlicense" ]
null
null
null
mp/src/game/server/coven_apc.cpp
rendenba/source-sdk-2013
4a0314391b01a2450788e0d4ee0926a05f3af8b0
[ "Unlicense" ]
null
null
null
mp/src/game/server/coven_apc.cpp
rendenba/source-sdk-2013
4a0314391b01a2450788e0d4ee0926a05f3af8b0
[ "Unlicense" ]
null
null
null
#include "cbase.h" #include "vphysics/constraints.h" #include "coven_apc.h" #include "hl2mp_gamerules.h" #include "covenlib.h" extern ConVar coven_debug_visual; extern ConVar sv_coven_refuel_distance; Vector CCoven_APC::wheelOffset[] = { Vector(80, -50, -32), Vector(-72, -50, -32), Vector(80, 50, -32), Vector(-72, 50, -32) }; QAngle CCoven_APC::wheelOrientation[] = { QAngle(0, -90, 0), QAngle(0, -90, 0), QAngle(0, 90, 0), QAngle(0, 90, 0) }; int CCoven_APC::wheelDirection[] = { -1, -1, 1, 1 }; float CCoven_APC::m_flWheelDiameter = 64.6f; float CCoven_APC::m_flWheelRadius = CCoven_APC::m_flWheelDiameter / 2.0f; float CCoven_APC::m_flWheelBase = (CCoven_APC::wheelOffset[0] - CCoven_APC::wheelOffset[1]).Length2D(); float CCoven_APC::m_flWheelTrack = (CCoven_APC::wheelOffset[0] - CCoven_APC::wheelOffset[2]).Length2D(); LINK_ENTITY_TO_CLASS(coven_prop_physics, CCoven_APCProp); CCoven_APCProp::CCoven_APCProp() { m_pParent = NULL; } void CCoven_APCProp::Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) { if (m_pParent) { if (pActivator->IsPlayer()) { CHL2MP_Player *pHL2Player = ToHL2MPPlayer(pActivator); if (pHL2Player->HasStatus(COVEN_STATUS_HAS_GAS)) { if (pHL2Player->IsPerformingDeferredAction()) pHL2Player->CancelDeferredAction(); CovenItemInfo_t *info = GetCovenItemData(COVEN_ITEM_GASOLINE); pHL2Player->QueueDeferredAction(COVEN_ACTION_REFUEL, (info->iFlags & ITEM_FLAG_MOVEMENT_CANCEL) > 0, info->flUseTime, true, this, sv_coven_refuel_distance.GetFloat()); pHL2Player->EmitSound(info->aSounds[COVEN_SND_START]); } else pHL2Player->EmitSound("HL2Player.UseDeny"); } } } int CCoven_APCProp::ObjectCaps(void) { if (m_pParent) return BaseClass::ObjectCaps() | FCAP_IMPULSE_USE; return 0; } LINK_ENTITY_TO_CLASS(coven_apc, CCoven_APC); CCoven_APC::CCoven_APC() { Q_memset(m_pWheels, NULL, sizeof(m_pWheels)); m_pBody = NULL; m_bPlayingSound = m_bRunning = m_bPlayingSiren = false; m_angTurningAngle.Init(); m_flTurningAngle = 0.0f; m_iGoalNode = -1; m_iGoalCheckpoint = -1; m_flMaxSpeed = 0.0f; m_iFuel = m_iFuelUpAmount = 0; m_vecFrontAxelPosition.Init(); m_flSoundSwitch = m_flSoundSirenSwitch = 0.0f; m_hLeftLampGlow = NULL; m_hRightLampGlow = NULL; } void CCoven_APC::Precache(void) { PrecacheModel("models/props_junk/rock001a.mdl"); PrecacheModel(COVEN_APC_GLOW_SPRITE); PrecacheScriptSound("ATV_engine_start"); PrecacheScriptSound("ATV_engine_stop"); PrecacheScriptSound("ATV_engine_idle"); PrecacheScriptSound("TimerLow"); BaseClass::Precache(); } void CCoven_APC::Spawn(void) { Precache(); SetModel("models/props_junk/rock001a.mdl"); AddEffects(EF_NODRAW); SetSolid(SOLID_VPHYSICS); AddSolidFlags(FSOLID_NOT_SOLID); SetAbsOrigin(GetAbsOrigin() + Vector(0, 0, CCoven_APC::m_flWheelDiameter)); BaseClass::Spawn(); m_iHealth = 100; m_iFuel = 0; for (int i = 0; i < 4; i++) { m_pWheels[i] = CCoven_APCPart::CreateAPCPart(this, "models/props_vehicles/apc_tire001.mdl", CCoven_APC::wheelOffset[i], CCoven_APC::wheelOrientation[i], CCoven_APC::m_flWheelRadius, COLLISION_GROUP_VEHICLE_WHEEL); m_pWheels[i]->Spawn(); m_pWheels[i]->AttachPhysics(); m_pWheels[i]->MoveToCorrectLocation(); } m_pBody = CCoven_APCPart::CreateAPCPart(this, "models/props_vehicles/apc001.mdl", Vector(0, 0, 0), QAngle(0, -90, 0), CCoven_APC::m_flWheelRadius + 32, COLLISION_GROUP_VEHICLE, true); m_pBody->Spawn(); m_pBody->AttachPhysics(); m_pBody->MoveToCorrectLocation(); m_flSpeed = 0.0f; Activate(); SetThink(&CCoven_APC::MakeSolid); SetNextThink(gpGlobals->curtime + 0.1f); ToggleLights(false); ResetLocation(); MoveForward(); } void CCoven_APC::UpdateLightPosition(void) { Vector forward(0, 0, 0), right(0, 0, 0), up(0, 0, 0); QAngle angles = m_pBody->GetAbsAngles(); float roll = -angles.z; angles.z = -angles.x; angles.x = roll; angles -= m_pBody->GetOffsetAngle(); AngleVectors(angles, &forward, &right, &up); float size = random->RandomFloat(1.5f, 2.0f); int bright = size * 127; m_hLeftLampGlow->SetAbsOrigin(GetAbsOrigin() + 143.0f * forward + 42.0f * right + 21.0f * up); m_hLeftLampGlow->SetBrightness(bright, 0.1f); m_hLeftLampGlow->SetScale(size, 0.1f); m_hRightLampGlow->SetAbsOrigin(GetAbsOrigin() + 143.0f * forward - 42.0f * right + 21.0f * up); m_hRightLampGlow->SetScale(size, 0.1f); m_hRightLampGlow->SetBrightness(bright, 0.1f); } void CCoven_APC::ToggleLights(bool bToggle) { if (m_hLeftLampGlow == NULL) { m_hLeftLampGlow = CSprite::SpriteCreate(COVEN_APC_GLOW_SPRITE, GetLocalOrigin(), false); if (m_hLeftLampGlow) { m_hLeftLampGlow->SetTransparency(kRenderWorldGlow, 255, 255, 255, 128, kRenderFxNoDissipation); m_hLeftLampGlow->SetBrightness(0); } } if (m_hRightLampGlow == NULL) { m_hRightLampGlow = CSprite::SpriteCreate(COVEN_APC_GLOW_SPRITE, GetLocalOrigin(), false); if (m_hRightLampGlow) { m_hRightLampGlow->SetTransparency(kRenderWorldGlow, 255, 255, 255, 128, kRenderFxNoDissipation); m_hRightLampGlow->SetBrightness(0); } } if (bToggle) { m_hLeftLampGlow->SetColor(255, 255, 255); m_hRightLampGlow->SetColor(255, 255, 255); m_hLeftLampGlow->SetBrightness(180, 0.1f); m_hRightLampGlow->SetBrightness(180, 0.1f); m_hLeftLampGlow->SetScale(0.8f, 0.1f); m_hRightLampGlow->SetScale(0.8f, 0.1f); } else { m_hLeftLampGlow->SetColor(255, 255, 255); m_hRightLampGlow->SetColor(255, 255, 255); m_hLeftLampGlow->SetScale(0.1f, 0.1f); m_hRightLampGlow->SetScale(0.1f, 0.1f); m_hLeftLampGlow->SetBrightness(0, 0.1f); m_hRightLampGlow->SetBrightness(0, 0.1f); } } void CCoven_APC::MakeSolid(void) { for (int i = 0; i < 4; i++) { m_pWheels[i]->MakeSolid(); } m_pBody->MakeSolid(); SetThink(NULL); } void CCoven_APC::APCThink(void) { if (HasValidGoal() && HasReachedCurrentGoal()) { //Msg("Reached node: %d\n", m_iGoalNode); if (m_iGoalNode == m_iGoalCheckpoint) HL2MPRules()->ReachedCheckpoint(m_iGoalCheckpoint); m_iGoalNode++; if (m_iGoalNode >= HL2MPRules()->hAPCNet.Count()) { SetThink(NULL); return; } } if (m_iFuel > 0) { if (m_flSpeed < m_flMaxSpeed) m_flSpeed += m_flMaxSpeed / 6.0f; } SetNextThink(gpGlobals->curtime + 0.1f); if (HasValidGoal()) { if (coven_debug_visual.GetBool()) NDebugOverlay::Cross3D(HL2MPRules()->hAPCNet[m_iGoalNode]->location, -Vector(12, 12, 12), Vector(12, 12, 12), 0, 255, 0, false, 0.5f); Vector directionDifference = HL2MPRules()->hAPCNet[m_iGoalNode]->location - GetAbsOrigin(); QAngle ang(0, 0, 0), curAngles = GetAbsAngles(); VectorAngles(directionDifference, ang); float dir = AngleNormalize(curAngles.y - ang.y); if (dir < -1.0f) TurnLeft(dir); else if (dir > 1.0f) TurnRight(dir); else m_flTurningAngle = 0.0f; //Msg("%f %f - %f %f - %f - %f %f - %d\n", curAngles.y, ang.y, m_angTurningAngle.y, m_flTurningAngle, dir, m_flSpeed, m_flMaxSpeed, m_iFuel); } //Msg("%f %f - %f %f - %d\n", m_angTurningAngle.y, m_flTurningAngle, m_flSpeed, m_flMaxSpeed, m_iFuel); MoveForward(); if (m_bPlayingSiren && gpGlobals->curtime > m_flSoundSirenSwitch) { #ifdef WIN32 m_flSoundSirenSwitch = gpGlobals->curtime + GetSoundDuration("TimerLow", NULL); #else m_flSoundSirenSwitch = gpGlobals->curtime + 3.687438f; #endif StopSound("TimerLow"); EmitSound("TimerLow"); } if (m_bPlayingSound && gpGlobals->curtime > m_flSoundSwitch) { #ifdef WIN32 m_flSoundSwitch = gpGlobals->curtime + GetSoundDuration("ATV_engine_idle", NULL); #else m_flSoundSwitch = gpGlobals->curtime + 4.316735f; #endif StopSound("ATV_engine_start"); StopSound("ATV_engine_idle"); EmitSound("ATV_engine_idle"); } if (m_iFuel == 0) { if (m_bPlayingSound) { StopSound("ATV_engine_start"); StopSound("ATV_engine_idle"); EmitSound("ATV_engine_stop"); m_bPlayingSound = m_bRunning = false; ToggleLights(false); } if (m_flSpeed > 0.0f) m_flSpeed -= m_flMaxSpeed / 14.0f; else { m_flSpeed = 0.0f; SetThink(NULL); } } else m_iFuel--; } void CCoven_APC::UpdateOnRemove(void) { if (m_hLeftLampGlow != NULL) { UTIL_Remove(m_hLeftLampGlow); m_hLeftLampGlow = NULL; } if (m_hRightLampGlow != NULL) { UTIL_Remove(m_hRightLampGlow); m_hRightLampGlow = NULL; } BaseClass::UpdateOnRemove(); } bool CCoven_APC::HasValidGoal(void) { return m_iGoalNode < HL2MPRules()->hAPCNet.Count() && m_iGoalNode >= 0; } bool CCoven_APC::HasReachedCurrentGoal(void) { return (GetAbsOrigin() - HL2MPRules()->hAPCNet[m_iGoalNode]->location).Length2D() < 24.0f; } void CCoven_APC::SetGoal(int iGoalNode) { m_iGoalNode = iGoalNode; } void CCoven_APC::SetCheckpoint(int iGoalCheckpoint) { m_iGoalCheckpoint = iGoalCheckpoint; } void CCoven_APC::SetMaxSpeed(float flMaxSpeed) { m_flMaxSpeed = flMaxSpeed; } void CCoven_APC::SetFuelUp(int iFuelUp) { m_iFuelUpAmount = iFuelUp; } void CCoven_APC::StartSiren(void) { if (!m_bPlayingSiren) { m_bPlayingSiren = true; EmitSound("TimerLow"); #ifdef WIN32 m_flSoundSirenSwitch = gpGlobals->curtime + GetSoundDuration("TimerLow", NULL); #else m_flSoundSirenSwitch = gpGlobals->curtime + 3.687438f; #endif } } void CCoven_APC::StopSiren(void) { if (m_bPlayingSiren) { m_bPlayingSiren = false; StopSound("TimerLow"); m_flSoundSirenSwitch = 0.0f; } } const Vector &CCoven_APC::GetFrontAxelPosition(void) { if (gpGlobals->tickcount != m_vecTick) { m_vecTick = gpGlobals->tickcount; Vector forward(0, 0, 0); AngleVectors(GetAbsAngles(), &forward); m_vecFrontAxelPosition = GetAbsOrigin() + forward * CCoven_APC::wheelOffset[FRONT_PASSENGER].x; } return m_vecFrontAxelPosition; } //flMagnitude is negative void CCoven_APC::TurnLeft(float flMagnitude) { if (m_angTurningAngle.y > -COVEN_APC_MAX_TURNING_VALUE && m_angTurningAngle.y > flMagnitude) { if (m_angTurningAngle.y < -1.0f || m_angTurningAngle.y > 0.0f) m_flTurningAngle = max(m_flTurningAngle - 1.0f, -COVEN_APC_MAX_TURN_ACCEL); else m_flTurningAngle = -1.0f; m_angTurningAngle.y += m_flTurningAngle; } else m_flTurningAngle = 0.0f; } //flMagnitude is positive void CCoven_APC::TurnRight(float flMagnitude) { if (m_angTurningAngle.y < COVEN_APC_MAX_TURNING_VALUE && m_angTurningAngle.y < flMagnitude) { if (m_angTurningAngle.y > 1.0f || m_angTurningAngle.y < 0.0f) m_flTurningAngle = min(m_flTurningAngle + 1.0f, COVEN_APC_MAX_TURN_ACCEL); else m_flTurningAngle = 1.0f; m_angTurningAngle.y += m_flTurningAngle; } else m_flTurningAngle = 0.0f; } void CCoven_APC::MoveForward(void) { WheelLocation_t lowestWheel = FRONT_PASSENGER; WheelLocation_t highestWheel = FRONT_PASSENGER; Vector vecFloorPosition[4]; Vector vecDesiredPosition[5]; QAngle angDesiredAngles[5]; if (m_angTurningAngle.y == 0.0f) { Vector forward; AngleVectors(GetAbsAngles(), &forward); for (int i = 0; i < 4; i++) { vecDesiredPosition[i] = m_pWheels[i]->GetAbsOrigin() + forward * m_flSpeed; float roll = GetAbsAngles().z; angDesiredAngles[i] = m_pWheels[i]->GetAbsAngles(); angDesiredAngles[i].x = 0; angDesiredAngles[i] += QAngle(roll * CCoven_APC::wheelDirection[i], 0, WheelDegreesTraveled(m_flSpeed) * CCoven_APC::wheelDirection[i]); } angDesiredAngles[4] = GetAbsAngles(); vecDesiredPosition[4] = GetAbsOrigin() + forward * m_flSpeed; } else { float alpha = m_angTurningAngle.y; //Right turn WheelLocation_t steeringWheel = FRONT_PASSENGER; float direction = 1.0f; //Left turn if (alpha < 0.0f) { direction = -1.0f; steeringWheel = FRONT_DRIVER; } //float r = CCoven_APC::m_flWheelBase / tan(M_PI * alpha / 180.0f); //rear wheel radius float R = CCoven_APC::m_flWheelBase / sin(M_PI * alpha / 180.0f); //front wheel radius float beata = -m_flSpeed / R; //radians QAngle angleToCenter = m_pWheels[steeringWheel]->GetAbsAngles(); angleToCenter.x = angleToCenter.z = 0; Vector dirToCenter(0, 0, 0); AngleVectors(angleToCenter, &dirToCenter); Vector O = m_pWheels[steeringWheel]->GetAbsOrigin() - CCoven_APC::wheelDirection[steeringWheel] * R * dirToCenter; //Msg("%f %f %f %f\n", beata, R, (m_pWheels[0]->GetAbsOrigin() - m_pWheels[2]->GetAbsOrigin()).Length2D(), m_pWheels[0]->GetAbsAngles().y - m_pWheels[2]->GetAbsAngles().y); for (int i = 0; i < 4; i++) { vecDesiredPosition[i] = m_pWheels[i]->GetAbsOrigin(); VectorRotate2DPoint(m_pWheels[i]->GetAbsOrigin(), O, beata, &vecDesiredPosition[i], true); QAngle oldAng = m_pWheels[i]->GetAbsAngles(); Vector newDir; newDir = direction * CCoven_APC::wheelDirection[i] * (vecDesiredPosition[i] - O); angDesiredAngles[i].Init(); VectorAngles(newDir, angDesiredAngles[i]); float roll = GetAbsAngles().z; //float pitch = GetAbsAngles().x; angDesiredAngles[i].z = oldAng.z; if (i == steeringWheel) angDesiredAngles[i].y -= m_flTurningAngle; angDesiredAngles[i] += QAngle(roll * CCoven_APC::wheelDirection[i], 0, WheelDegreesTraveled(m_flSpeed) * CCoven_APC::wheelDirection[i]); } if (coven_debug_visual.GetBool()) NDebugOverlay::Cross3D(O, -Vector(12, 12, 12), Vector(12, 12, 12), 0, 0, 255, true, 1.0f); Vector dir(0, 0, 0), newDir(0, 0, 0); VectorRotate2DPoint(m_pBody->GetAbsOrigin(), O, beata, &vecDesiredPosition[4], true); AngleVectors(GetAbsAngles(), &dir); VectorRotate2D(dir, beata, &newDir, true); VectorAngles(newDir, angDesiredAngles[4]); angDesiredAngles[4].x = AngleNormalize(angDesiredAngles[4].x); angDesiredAngles[4].y = AngleNormalize(angDesiredAngles[4].y); //Msg("DEBUG: %f %f %f\n", dir.z, newDir.z, beata); } for (int i = 0; i < 4; i++) { trace_t tr; //BB: TODO: we need to trace a hull here! UTIL_TraceLine(vecDesiredPosition[i], vecDesiredPosition[i] + Vector(0, 0, -500), MASK_ALL, m_pWheels[i]->GetProp(), COLLISION_GROUP_WEAPON, &tr); if (tr.DidHit()) vecFloorPosition[i] = tr.endpos; else vecFloorPosition[i].Init(); if (vecFloorPosition[i].z < vecFloorPosition[lowestWheel].z) lowestWheel = (WheelLocation_t)i; if (vecFloorPosition[i].z > vecFloorPosition[highestWheel].z) highestWheel = (WheelLocation_t)i; } if (lowestWheel != highestWheel) { //Pitch = highest point of highest direction - lowest point of other direction float highest = vecDesiredPosition[highestWheel].z; float lowestP = vecDesiredPosition[CCoven_APC::AdjacentWheel(highestWheel)].z; float pitchRadians = atan((highest - lowestP) / CCoven_APC::m_flWheelBase); if (highestWheel == FRONT_DRIVER || highestWheel == FRONT_PASSENGER) pitchRadians = -pitchRadians; //Roll = highest point of highest side - lowest point of other side. float lowestR = vecDesiredPosition[CCoven_APC::OppositeWheel(highestWheel)].z; float rollRadians = atan((highest - lowestR) / CCoven_APC::m_flWheelTrack); if (highestWheel >= FRONT_DRIVER) rollRadians = -rollRadians; angDesiredAngles[4].x = AngleNormalize(pitchRadians * 180.0f / M_PI); angDesiredAngles[4].z = AngleNormalize(rollRadians * 180.0f / M_PI); WheelLocation_t oppositeWheel = CCoven_APC::AdjacentWheel(CCoven_APC::OppositeWheel(highestWheel)); vecDesiredPosition[oppositeWheel].z = vecDesiredPosition[highestWheel].z - lowestP - lowestR; //NDebugOverlay::Cross3D(vecDesiredPosition[highestWheel], -Vector(12, 12, 12), Vector(12, 12, 12), 255, 0, 0, false, 0.5f); //NDebugOverlay::Cross3D(vecDesiredPosition[lowestWheel], -Vector(12, 12, 12), Vector(12, 12, 12), 0, 255, 0, false, 0.5f); } //Msg("APC Pitch: %f\n", angDesiredAngles[4].x); for (int i = 0; i < 4; i++) { vecDesiredPosition[i].z = vecFloorPosition[i].z + m_pWheels[i]->RestHeight(); m_pWheels[i]->MoveTo(&vecDesiredPosition[i], &angDesiredAngles[i]); } float midZ = vecDesiredPosition[lowestWheel].z + (vecDesiredPosition[highestWheel].z - vecDesiredPosition[lowestWheel].z) / 2.0f + CCoven_APC::m_flWheelRadius; vecDesiredPosition[4].z = midZ; SetAbsAngles(angDesiredAngles[4]); SetAbsOrigin(vecDesiredPosition[4]); float roll = -angDesiredAngles[4].z; angDesiredAngles[4].z = -angDesiredAngles[4].x + random->RandomFloat(-0.5f, 0.5f); angDesiredAngles[4].x = roll + random->RandomFloat(-0.5f, 0.5f); angDesiredAngles[4] += m_pBody->GetOffsetAngle(); m_pBody->MoveTo(&vecDesiredPosition[4], &angDesiredAngles[4]); //Msg("Body Pitch: %f\n", angDesiredAngles[4].x); if (m_bRunning) UpdateLightPosition(); } bool CCoven_APC::IsRunning(void) { return m_bRunning || m_flSpeed > 0.0f; } void CCoven_APC::ResetLocation(void) { for (int i = 0; i < 4; i++) { QAngle ang = GetAbsAngles(); float roll = ang.z; //float pitch = ang.x; ang.x = ang.z = 0; if (i == FRONT_DRIVER || i == FRONT_PASSENGER) ang += m_angTurningAngle; ang += m_pWheels[i]->GetOffsetAngle() + QAngle(roll * CCoven_APC::wheelDirection[i], 0, m_pWheels[i]->GetAbsAngles().z + WheelDegreesTraveled(m_flSpeed) * CCoven_APC::wheelDirection[i]); Vector vec = GetAbsOrigin() + CCoven_APC::wheelOffset[i]; Vector rotated = vec; VectorRotate2DPoint(vec, GetAbsOrigin(), GetAbsAngles().y, &rotated); m_pWheels[i]->MoveTo(&rotated, &ang); } Vector bodyLocation = GetAbsOrigin(); QAngle bodyAngles = GetAbsAngles() + QAngle(0, -90, 0); m_pBody->MoveTo(&bodyLocation, &bodyAngles); } void CCoven_APC::StartUp(void) { if (!m_bRunning) { if (!m_bPlayingSound) { m_bPlayingSound = true; EmitSound("ATV_engine_start"); //BB: GetSoundDuration does not appear to work for Linux SRCDS! Linux will need a hardcoded timestamp! FIX THIS THROUGHOUT THIS FILE! #ifdef WIN32 m_flSoundSwitch = gpGlobals->curtime + GetSoundDuration("ATV_engine_Start", NULL); #else m_flSoundSwitch = gpGlobals->curtime + 6.151132f; #endif SetThink(&CCoven_APC::APCThink); SetNextThink(gpGlobals->curtime + 0.2f); } m_bRunning = true; ToggleLights(true); } m_iFuel += m_iFuelUpAmount; } int CCoven_APC::CurrentGoal(void) { return m_iGoalNode; } int CCoven_APC::CurrentCheckpoint(void) { return m_iGoalCheckpoint; } WheelLocation_t CCoven_APC::OppositeWheel(WheelLocation_t wheel) { if (wheel > REAR_PASSENGER) return (WheelLocation_t)(wheel - 2); return (WheelLocation_t)(wheel + 2); } WheelLocation_t CCoven_APC::AdjacentWheel(WheelLocation_t wheel) { if (wheel == FRONT_PASSENGER) return REAR_PASSENGER; if (wheel == REAR_PASSENGER) return FRONT_PASSENGER; if (wheel == FRONT_DRIVER) return REAR_DRIVER; return FRONT_DRIVER; } LINK_ENTITY_TO_CLASS(coven_apc_part, CCoven_APCPart); CCoven_APCPart::CCoven_APCPart() { m_pConstraint = NULL; m_hAPC = NULL; m_vecOffset.Init(); m_angOffset.Init(); m_flRestHeight = 0.0f; } CCoven_APCPart::~CCoven_APCPart() { if (m_pConstraint) { physenv->DestroyConstraint(m_pConstraint); m_pConstraint = NULL; } } CCoven_APCPart *CCoven_APCPart::CreateAPCPart(CCoven_APC *pParentAPC, char *szModelName, const Vector &vecOffset, const QAngle &angOffset, float flRestHeight, Collision_Group_t collisionGroup, bool bMakeUsable) { CCoven_APCPart *pPart = (CCoven_APCPart *)CBaseEntity::Create("coven_apc_part", pParentAPC->GetAbsOrigin(), pParentAPC->GetAbsAngles()); if (!pPart) return NULL; pPart->m_hAPC = pParentAPC; pPart->m_vecOffset = vecOffset; pPart->m_angOffset = angOffset; pPart->m_flRestHeight = flRestHeight; pPart->m_pPart = dynamic_cast< CCoven_APCProp * >(CreateEntityByName("coven_prop_physics")); if (pPart->m_pPart) { Vector location = pParentAPC->GetAbsOrigin(); QAngle orientation = pParentAPC->GetAbsAngles(); char buf[512]; // Pass in standard key values Q_snprintf(buf, sizeof(buf), "%.10f %.10f %.10f", location.x, location.y, location.z); pPart->m_pPart->KeyValue("origin", buf); Q_snprintf(buf, sizeof(buf), "%.10f %.10f %.10f", orientation.x, orientation.y, orientation.z); pPart->m_pPart->KeyValue("angles", buf); pPart->m_pPart->KeyValue("model", szModelName); pPart->m_pPart->KeyValue("fademindist", "-1"); pPart->m_pPart->KeyValue("fademaxdist", "0"); pPart->m_pPart->KeyValue("fadescale", "1"); pPart->m_pPart->KeyValue("inertiaScale", "1.0"); pPart->m_pPart->KeyValue("physdamagescale", "0.1"); pPart->m_pPart->Precache(); pPart->m_pPart->SetCollisionGroup(collisionGroup); pPart->m_pPart->Spawn(); pPart->m_pPart->Activate(); pPart->m_pPart->AddSolidFlags(FSOLID_NOT_SOLID); } if (bMakeUsable) pPart->m_pPart->m_pParent = pPart; pPart->AddSolidFlags(FSOLID_NOT_SOLID); // Disable movement on the root, we'll move this thing manually. pPart->VPhysicsInitShadow(false, false); pPart->SetMoveType(MOVETYPE_NONE); return pPart; } void CCoven_APCPart::MakeSolid(void) { m_pPart->RemoveSolidFlags(FSOLID_NOT_SOLID); } Vector CCoven_APCPart::GetOffsetPosition(void) { Vector offset = m_vecOffset; if (m_vecOffset != vec3_origin) { float sine = 0.0f; float cosine = 0.0f; SinCos(m_hAPC->GetAbsAngles().y / 180.0f * M_PI, &sine, &cosine); offset.x = cosine * m_vecOffset.x - sine * m_vecOffset.y; offset.y = sine * m_vecOffset.x + cosine * m_vecOffset.y; } return offset; } QAngle CCoven_APCPart::GetOffsetAngle(void) { return m_angOffset; } float CCoven_APCPart::RestHeight(void) { return m_flRestHeight; } void CCoven_APCPart::MoveTo(const Vector *vec, const QAngle *ang) { if (vec != NULL) SetAbsOrigin(*vec); if (ang != NULL) SetAbsAngles(*ang); if (vec != NULL || ang != NULL) UpdatePhysicsShadowToCurrentPosition(0.1f); } void CCoven_APCPart::UpdatePosition(void) { if (m_hAPC != NULL) { SetAbsOrigin(m_hAPC->GetAbsOrigin() + GetOffsetPosition()); UpdatePhysicsShadowToCurrentPosition(0.1f); } } void CCoven_APCPart::Spawn(void) { Precache(); SetModel("models/props_junk/rock001a.mdl"); AddEffects(EF_NODRAW); SetSolid(SOLID_VPHYSICS); AddSolidFlags(FSOLID_NOT_SOLID); BaseClass::Spawn(); } void CCoven_APCPart::Precache(void) { PrecacheModel("models/props_junk/rock001a.mdl"); BaseClass::Precache(); } void CCoven_APCPart::DropToFloor(void) { trace_t tr; UTIL_TraceLine(GetAbsOrigin(), GetAbsOrigin() + Vector(0, 0, -500), MASK_ALL, m_pPart, COLLISION_GROUP_PLAYER, &tr); if (tr.DidHit()) { SetAbsOrigin(tr.endpos + Vector(0, 0, m_flRestHeight)); } } void CCoven_APCPart::MoveToCorrectLocation(void) { if (m_hAPC != NULL) { Vector location = m_hAPC->GetAbsOrigin() + GetOffsetPosition(); QAngle angles = m_hAPC->GetAbsAngles() + m_angOffset; Teleport(&location, &angles, NULL); UpdatePhysicsShadowToCurrentPosition(0); } } void CCoven_APCPart::AttachPhysics(void) { if (!m_pConstraint) { IPhysicsObject *pPartPhys = m_pPart->VPhysicsGetObject(); IPhysicsObject *pShadowPhys = VPhysicsGetObject(); constraint_fixedparams_t fixed; fixed.Defaults(); fixed.InitWithCurrentObjectState(pShadowPhys, pPartPhys); fixed.constraint.Defaults(); m_pConstraint = physenv->CreateFixedConstraint(pShadowPhys, pPartPhys, NULL, fixed); } }
28.627353
215
0.720678
rendenba
1205ece7c57ad787c5c14ffb91a7cecf8190cb6f
2,612
hpp
C++
include/Nazara/Graphics/UberShader.hpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
include/Nazara/Graphics/UberShader.hpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
include/Nazara/Graphics/UberShader.hpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
// Copyright (C) 2022 Jérôme "Lynix" Leclercq ([email protected]) // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_GRAPHICS_UBERSHADER_HPP #define NAZARA_GRAPHICS_UBERSHADER_HPP #include <Nazara/Prerequisites.hpp> #include <Nazara/Core/Algorithm.hpp> #include <Nazara/Core/Bitset.hpp> #include <Nazara/Core/Signal.hpp> #include <Nazara/Graphics/Config.hpp> #include <Nazara/Renderer/RenderPipeline.hpp> #include <Nazara/Shader/ShaderModuleResolver.hpp> #include <Nazara/Shader/Ast/Module.hpp> #include <unordered_map> namespace Nz { class ShaderModule; class NAZARA_GRAPHICS_API UberShader { public: struct Config; struct Option; using ConfigCallback = std::function<void(Config& config, const std::vector<RenderPipelineInfo::VertexBufferData>& vertexBuffers)>; UberShader(ShaderStageTypeFlags shaderStages, std::string moduleName); UberShader(ShaderStageTypeFlags shaderStages, ShaderModuleResolver& moduleResolver, std::string moduleName); UberShader(ShaderStageTypeFlags shaderStages, ShaderAst::ModulePtr shaderModule); ~UberShader() = default; inline ShaderStageTypeFlags GetSupportedStages() const; const std::shared_ptr<ShaderModule>& Get(const Config& config); inline bool HasOption(const std::string& optionName, Pointer<const Option>* option = nullptr) const; inline void UpdateConfig(Config& config, const std::vector<RenderPipelineInfo::VertexBufferData>& vertexBuffers); inline void UpdateConfigCallback(ConfigCallback callback); struct Config { std::unordered_map<UInt32, ShaderAst::ConstantValue> optionValues; }; struct ConfigEqual { inline bool operator()(const Config& lhs, const Config& rhs) const; }; struct ConfigHasher { inline std::size_t operator()(const Config& config) const; }; struct Option { UInt32 hash; }; NazaraSignal(OnShaderUpdated, UberShader* /*uberShader*/); private: ShaderAst::ModulePtr Validate(const ShaderAst::Module& module, std::unordered_map<std::string, Option>* options); NazaraSlot(ShaderModuleResolver, OnModuleUpdated, m_onShaderModuleUpdated); std::unordered_map<Config, std::shared_ptr<ShaderModule>, ConfigHasher, ConfigEqual> m_combinations; std::unordered_map<std::string, Option> m_optionIndexByName; ShaderAst::ModulePtr m_shaderModule; ConfigCallback m_configCallback; ShaderStageTypeFlags m_shaderStages; }; } #include <Nazara/Graphics/UberShader.inl> #endif // NAZARA_GRAPHICS_UBERSHADER_HPP
31.46988
134
0.769525
jayrulez
1209463f60ad0473a1d6a2ec3e539fa200001bd5
876
cpp
C++
dos/dos_memmgr_test.cpp
wwiv/door86c
bfdc6408bf632da74a1e58d97da3257d715f3f6e
[ "Apache-2.0" ]
1
2021-11-04T03:13:25.000Z
2021-11-04T03:13:25.000Z
dos/dos_memmgr_test.cpp
wwiv/door86c
bfdc6408bf632da74a1e58d97da3257d715f3f6e
[ "Apache-2.0" ]
null
null
null
dos/dos_memmgr_test.cpp
wwiv/door86c
bfdc6408bf632da74a1e58d97da3257d715f3f6e
[ "Apache-2.0" ]
null
null
null
#include <gtest/gtest.h> #include "cpu/memory.h" #include "dos/dos.h" #include <cstdlib> #include <cstdint> #include <iostream> using namespace door86::cpu; using namespace door86::dos; class DosMemMgrTest : public testing::Test { public: DosMemMgrTest() : mm(&m, 0x1000, 0x7000) {} Memory m{1 << 20}; DosMemoryManager mm; }; TEST_F(DosMemMgrTest, Smoke) { ASSERT_EQ(1, mm.blocks().size()); const auto o = mm.allocate(0x2000); ASSERT_TRUE(o.has_value()); ASSERT_EQ(0x1000, o.value()); const auto o2 = mm.allocate(0x5001); ASSERT_FALSE(o2.has_value()); } TEST_F(DosMemMgrTest, Tail) { mm.strategy(DosMemoryManager::fit_strategy_t::last); ASSERT_EQ(1, mm.blocks().size()); const auto o = mm.allocate(0x2000); ASSERT_TRUE(o.has_value()); ASSERT_EQ(0x5000, o.value()); const auto o2 = mm.allocate(0x5001); ASSERT_FALSE(o2.has_value()); }
21.365854
54
0.691781
wwiv
1211f6335d41fc83efb6404e4b78a6d0da338d77
6,636
hpp
C++
c++17_features.hpp
ralphtandetzky/cpp_utils
3adfed125db6fccd7478385544b96ceecdf435e7
[ "MIT" ]
3
2018-01-04T18:07:32.000Z
2021-09-01T14:19:43.000Z
c++17_features.hpp
ralphtandetzky/cpp_utils
3adfed125db6fccd7478385544b96ceecdf435e7
[ "MIT" ]
null
null
null
c++17_features.hpp
ralphtandetzky/cpp_utils
3adfed125db6fccd7478385544b96ceecdf435e7
[ "MIT" ]
null
null
null
/** @file This file defines features available from C++17 onwards. * * The features are defined in the cu namespace instead of the std namespace. * When moving to C++17 just remove this header from the project, * in order to keep you project clean. This should require only a bit of * refactoring by replacing the respective @c cu:: by @c std::. * * @author Ralph Tandetzky */ #pragma once #include <cstddef> #include <type_traits> #include <utility> #ifdef __has_include // Check if __has_include is present # if __has_include(<optional>) // Check for a standard library # include <optional> # elif __has_include(<experimental/optional>) // Check for an experimental version # include <experimental/optional> # elif __has_include(<boost/optional.hpp>) // Try with an external library # include <boost/optional.hpp> # else // Not found at all # error "Missing <optional>" # endif #else # error "Compiler does not support __has_include" #endif namespace cu { //using std::experimental::optional; // #include <optional> // // std::optional<T> #if __has_include(<optional>) // Check for a standard library using std::optional; using std::nullopt; #elif __has_include(<experimental/optional>) // Check for an experimental version using std::experimental::optional; using std::experimental::nullopt; #elif __has_include(<boost/optional.hpp>) // Try with an external library using boost::optional; using boost::nullopt; #endif // #include <iterator> // // std::size() template <typename Container> constexpr auto size( const Container& container ) -> decltype(container.size()) { return container.size(); } template <typename T, std::size_t N> constexpr std::size_t size( const T (&)[N] ) noexcept { return N; } // #include <functional> // // std::invoke() namespace detail { template <typename T> struct is_reference_wrapper : std::false_type {}; template <typename U> struct is_reference_wrapper<std::reference_wrapper<U>> : std::true_type {}; template <typename Base, typename T, typename Derived, typename... Args> auto INVOKE(T Base::*pmf, Derived&& ref, Args&&... args) noexcept(noexcept((std::forward<Derived>(ref).*pmf)(std::forward<Args>(args)...))) -> typename std::enable_if<std::is_function<T>::value && std::is_base_of<Base, typename std::decay<Derived>::type>::value, decltype((std::forward<Derived>(ref).*pmf)(std::forward<Args>(args)...))>::type { return (std::forward<Derived>(ref).*pmf)(std::forward<Args>(args)...); } template <typename Base, typename T, typename RefWrap, typename... Args> auto INVOKE(T Base::*pmf, RefWrap&& ref, Args&&... args) noexcept(noexcept((ref.get().*pmf)(std::forward<Args>(args)...))) -> typename std::enable_if<std::is_function<T>::value && is_reference_wrapper<typename std::decay<RefWrap>::type>::value, decltype((ref.get().*pmf)(std::forward<Args>(args)...))>::type { return (ref.get().*pmf)(std::forward<Args>(args)...); } template <typename Base, typename T, typename Pointer, typename... Args> auto INVOKE(T Base::*pmf, Pointer&& ptr, Args&&... args) noexcept(noexcept(((*std::forward<Pointer>(ptr)).*pmf)(std::forward<Args>(args)...))) -> typename std::enable_if<std::is_function<T>::value && !is_reference_wrapper<typename std::decay<Pointer>::type>::value && !std::is_base_of<Base, typename std::decay<Pointer>::type>::value, decltype(((*std::forward<Pointer>(ptr)).*pmf)(std::forward<Args>(args)...))>::type { return ((*std::forward<Pointer>(ptr)).*pmf)(std::forward<Args>(args)...); } template <typename Base, typename T, typename Derived> auto INVOKE(T Base::*pmd, Derived&& ref) noexcept(noexcept(std::forward<Derived>(ref).*pmd)) -> typename std::enable_if<!std::is_function<T>::value && std::is_base_of<Base, typename std::decay<Derived>::type>::value, decltype(std::forward<Derived>(ref).*pmd)>::type { return std::forward<Derived>(ref).*pmd; } template <typename Base, typename T, typename RefWrap> auto INVOKE(T Base::*pmd, RefWrap&& ref) noexcept(noexcept(ref.get().*pmd)) -> typename std::enable_if<!std::is_function<T>::value && is_reference_wrapper<typename std::decay<RefWrap>::type>::value, decltype(ref.get().*pmd)>::type { return ref.get().*pmd; } template <typename Base, typename T, typename Pointer> auto INVOKE(T Base::*pmd, Pointer&& ptr) noexcept(noexcept((*std::forward<Pointer>(ptr)).*pmd)) -> typename std::enable_if<!std::is_function<T>::value && !is_reference_wrapper<typename std::decay<Pointer>::type>::value && !std::is_base_of<Base, typename std::decay<Pointer>::type>::value, decltype((*std::forward<Pointer>(ptr)).*pmd)>::type { return (*std::forward<Pointer>(ptr)).*pmd; } template <typename F, typename... Args> auto INVOKE(F&& f, Args&&... args) noexcept(noexcept(std::forward<F>(f)(std::forward<Args>(args)...))) -> typename std::enable_if<!std::is_member_pointer<typename std::decay<F>::type>::value, decltype(std::forward<F>(f)(std::forward<Args>(args)...))>::type { return std::forward<F>(f)(std::forward<Args>(args)...); } } // namespace detail template< typename F, typename... ArgTypes > auto invoke(F&& f, ArgTypes&&... args) // exception specification for QoI noexcept(noexcept(detail::INVOKE(std::forward<F>(f), std::forward<ArgTypes>(args)...))) -> decltype(detail::INVOKE(std::forward<F>(f), std::forward<ArgTypes>(args)...)) { return detail::INVOKE(std::forward<F>(f), std::forward<ArgTypes>(args)...); } // #include <tuple> // // std::apply() #ifdef I #define CU_OLD_I_DEF I #undef I #endif namespace detail { template <typename F, typename Tuple, std::size_t... I> constexpr decltype(auto) apply_impl( F&& f, Tuple&& t, std::index_sequence<I...> ) { return cu::invoke(std::forward<F>(f), std::get<I>(std::forward<Tuple>(t))...); } } // namespace detail #ifdef CU_OLD_I_DEF #define I CU_OLD_I_DEF #undef CU_OLD_I_DEF #endif template <typename F, typename Tuple> constexpr decltype(auto) apply(F&& f, Tuple&& t) { return detail::apply_impl(std::forward<F>(f), std::forward<Tuple>(t), std::make_index_sequence<std::tuple_size<std::decay_t<Tuple>>{}>{}); } } // namespace cu
35.111111
97
0.639693
ralphtandetzky
1213e79b24fde59bab9ba2136fa2cd41bb928072
1,599
cpp
C++
sscanf/src/tests/test_group_specifiers.cpp
dzoj/ultra_balkan_alpha-master.github.io
f2c1835f2ad2a97436197956de62ef3a43ef7dff
[ "MIT" ]
null
null
null
sscanf/src/tests/test_group_specifiers.cpp
dzoj/ultra_balkan_alpha-master.github.io
f2c1835f2ad2a97436197956de62ef3a43ef7dff
[ "MIT" ]
null
null
null
sscanf/src/tests/test_group_specifiers.cpp
dzoj/ultra_balkan_alpha-master.github.io
f2c1835f2ad2a97436197956de62ef3a43ef7dff
[ "MIT" ]
null
null
null
#include "../specifiers/group_specifiers.h" TEST(AltGroup1, { AltGroup gg; return gg.ReadToken(S"(ii|dd)") == OK && *CUR == '\0'; }) TEST(AltGroup2, { AltGroup gg; gg.ReadToken(S"(ii|xh)");ss s; return dynamic_cast<ss &>(s << gg).str() == "(ii|xh)"; }) TEST(AltGroup4, { AltGroup gg; if (gg.ReadToken(S"(ii|dd|cc|xx)") != OK) return false; int i = 0; for (auto b = gg.Begin(), e = gg.End(); b != e; ++b) ++i; return i == 4 && gg.CountChildren() == 4; }) TEST(AltGroup5, { AltGroup gg; if (gg.ReadToken(S"(ii|dd|cc|xx|dd|dd|dd)") != OK) return false; int i = 0; for (auto b = gg.Begin(), e = gg.End(); b != e; ++b) { ++i; if ((*b)->CountChildren() != 2) return false; } return i == 7 && gg.CountChildren() == 7; }) TEST(AltGroup6, { AltGroup gg; if (gg.ReadToken(S"(ii)") != OK) return false; int i = 0; for (auto b = gg.Begin(), e = gg.End(); b != e; ++b) ++i; return i == 1 && gg.CountChildren() == 1; }) TEST(GlobGroup1, { AltGroup gg(false); return gg.ReadToken(S"ii|dd") == OK && *CUR == '\0'; }) TEST(GlobGroup2, { AltGroup gg(false); return gg.ReadToken(S"ii|") == ERROR_NO_CHILDREN; }) TEST(GlobGroup3, { AltGroup gg(false); return gg.ReadToken(S"|dd") == ERROR_NO_CHILDREN; }) TEST(GlobGroup6, { AltGroup gg(false); return gg.ReadToken(S"I(5)") == OK; }) TEST(GlobGroup7, { AltGroup gg(false); return gg.ReadToken(S"I(q)") == ERROR_NAN; }) TEST(GlobGroup4, { AltGroup gg(false); return gg.ReadToken(S"ii|D(5)|cc| H(11)n") == OK && *CUR == '\0'; }) TEST(GlobGroup5, { AltGroup gg(false); gg.ReadToken(S"ii|xh");ss s; return dynamic_cast<ss &>(s << gg).str() == "ii|xh"; })
79.95
164
0.600375
dzoj
12151e08bf4ed73e3b693e21e4ca4b2a2d2fbce6
487
hpp
C++
src/constants.hpp
yhamdoud/engine
0e1e589be4eb3b50ac21f0d166a2c76f576fdeb7
[ "MIT" ]
4
2021-08-29T09:34:22.000Z
2022-01-27T00:24:52.000Z
src/constants.hpp
yhamdoud/engine
0e1e589be4eb3b50ac21f0d166a2c76f576fdeb7
[ "MIT" ]
null
null
null
src/constants.hpp
yhamdoud/engine
0e1e589be4eb3b50ac21f0d166a2c76f576fdeb7
[ "MIT" ]
null
null
null
#pragma once #include <filesystem> namespace engine { using uint = unsigned int; const uint invalid_texture_id = 0; const uint invalid_shader_id = 0; const uint default_frame_buffer_id = 0; const std::filesystem::path resources_path{"../resources"}; const std::filesystem::path textures_path{resources_path / "textures"}; const std::filesystem::path shaders_path{resources_path / "shaders"}; const std::filesystem::path models_path{resources_path / "models"}; } // namespace engine
25.631579
71
0.770021
yhamdoud
121b7e8b1b6fcbfc5a8b1f76d56796ba6082586e
5,295
cpp
C++
test/geometry/polygon.cpp
teyrana/quadtree
4172ad2f2e36414caebf80013a3d32e6df200945
[ "MIT" ]
null
null
null
test/geometry/polygon.cpp
teyrana/quadtree
4172ad2f2e36414caebf80013a3d32e6df200945
[ "MIT" ]
1
2019-08-24T17:31:50.000Z
2019-08-24T17:31:50.000Z
test/geometry/polygon.cpp
teyrana/quadtree
4172ad2f2e36414caebf80013a3d32e6df200945
[ "MIT" ]
null
null
null
#include <iostream> #include <memory> #include <vector> #include "gtest/gtest.h" #include "geometry/polygon.hpp" #include "geometry/layout.hpp" using std::vector; using Eigen::Vector2d; using terrain::geometry::Polygon; using terrain::geometry::Layout; namespace terrain::geometry { TEST(PolygonTest, DefaultConfiguration) { const Polygon shape; const auto& points = shape.points; ASSERT_TRUE(points[0].isApprox(Vector2d(0,0))); ASSERT_TRUE(points[1].isApprox(Vector2d(1,0))); ASSERT_TRUE(points[2].isApprox(Vector2d(1,1))); ASSERT_TRUE(points[3].isApprox(Vector2d(0,1))); } TEST(PolygonTest, LoadList_5Point) { // Note: this polygen is configured as CW: // it will be enclosed, and reversed, internally Polygon shape( {{ 3, 4}, { 5,11}, {12, 8}, { 9, 5}, { 5, 6}}); // DEBUG // shape.write_yaml(std::cerr, " "); ASSERT_EQ( shape[0], Vector2d( 3, 4)); ASSERT_EQ( shape[1], Vector2d( 5, 6)); ASSERT_EQ( shape[2], Vector2d( 9, 5)); ASSERT_EQ( shape[3], Vector2d( 12, 8)); ASSERT_EQ( shape[4], Vector2d( 5, 11)); ASSERT_EQ( shape[5], Vector2d( 3, 4)); } TEST(PolygonTest, LoadList_DiamondRhombus) { Polygon shape({{1,0},{0,1},{-1,0},{0,-1}}); // // DEBUG // shape.write_yaml(std::cerr, " "); ASSERT_EQ( shape[0], Vector2d(1,0) ); ASSERT_EQ( shape[1], Vector2d(0,1) ); ASSERT_EQ( shape[2], Vector2d(-1,0) ); ASSERT_EQ( shape[3], Vector2d(0,-1) ); ASSERT_EQ( shape[4], Vector2d(1,0) ); } TEST(PolygonTest, MakeLayout) { Polygon bounds; Polygon shape( {{ 5, 6}, { 9, 5}, {12, 8}, { 5,11}, { 3, 4}, { 5, 6}} ); const double precision = 0.5; const Layout& layout = shape.make_layout(precision); // ====== ====== Preconditions ====== ====== EXPECT_DOUBLE_EQ(layout.get_precision(), 1.0); EXPECT_DOUBLE_EQ(layout.get_x(), 8); EXPECT_DOUBLE_EQ(layout.get_y(), 8); EXPECT_DOUBLE_EQ(layout.get_width(), 16); EXPECT_EQ(layout.get_dimension(), 16); EXPECT_EQ(layout.get_size(), 256); EXPECT_FALSE( layout.contains({ -1., -1.}) ); EXPECT_FALSE( layout.contains({ -2., -2.}) ); EXPECT_EQ( layout.rhash(0.1, 0.1), 0); EXPECT_EQ( layout.rhash(1.1, 0.1), 1); EXPECT_EQ( layout.rhash(0.1, 1.1), 16); EXPECT_EQ( layout.rhash(1.1, 1.1), 17); ASSERT_EQ( layout.rhash(2., 0.), 2); ASSERT_EQ( layout.rhash(3., 0.), 3); ASSERT_EQ( layout.rhash(2., 1.), 18); ASSERT_EQ( layout.rhash(3., 1.), 19); } // TEST(PolygonTest, InBoundingBoxByX) { // BoundaryPolygon bounds; // bounds.setParam("margin", "20."); // bounds.setParam("priority_function", "linear"); // bounds.setParam("points", "-200,-200: 200,-200: 200,200: -200,200"); // // ====== ====== Preconditions ====== ====== // ASSERT_DOUBLE_EQ(bounds.min.x, -200); // ASSERT_DOUBLE_EQ(bounds.max.x, 200); // ASSERT_DOUBLE_EQ(bounds.min.y, -200); // ASSERT_DOUBLE_EQ(bounds.max.y, 200); // ASSERT_DOUBLE_EQ(bounds.margin, 20); // ASSERT_DOUBLE_EQ(bounds.center[0], 0); // ASSERT_DOUBLE_EQ(bounds.center[1], 0); // ASSERT_TRUE(bounds.is_convex); // // ====== ====== Graphics Message Output ====== ====== // const string& poly2 = bounds.getBoundaryPolygonGraphics(true,"aqua"); // const string exp2("label=Boundary,active=true,pts={-200,-200:200,-200:200,200:-200,200:-200,-200},edge_color=aqua"); // ASSERT_EQ(poly2, exp2); // vector<TestPoint> test_cases; // test_cases.emplace_back( -205, 0, 1.00, 90); // test_cases.emplace_back( -201, 0, 1.00, 90); // test_cases.emplace_back( -200, 0, 1.00, 90); // test_cases.emplace_back( -199, 0, 0, 0); // test_cases.emplace_back( -190, 0, 0, 0); // test_cases.emplace_back( -181, 0, 0, 0); // test_cases.emplace_back( -180, 0, 0, 0); // test_cases.emplace_back( -179, 0, 0, 0); // test_cases.emplace_back( 0, 0, 0, 0); // test_cases.emplace_back( 179, 0, 0, 0); // test_cases.emplace_back( 180, 0, 0, 0); // test_cases.emplace_back( 181, 0, 0, 0); // test_cases.emplace_back( 190, 0, 0, 0); // test_cases.emplace_back( 199, 0, 0, 0); // test_cases.emplace_back( 200, 0, 1.00, 270); // test_cases.emplace_back( 201, 0, 1.00, 270); // // ===================================== // for( uint i=0; i < test_cases.size(); i++){ // const TestPoint& expect = test_cases[i]; // const PolarVector2D& actual = bounds.getHeadingDesiredBoundingBox(expect.x,expect.y); // ostringstream buf; // buf << "@@ x=" << expect.x << " y=" << expect.y; // buf << " => " << actual.magnitude << " \u2220 "<< actual.heading <<"\u00b0"; // const string& case_descriptor = buf.str(); // ASSERT_NEAR(actual.magnitude, expect.magnitude, 0.01) << case_descriptor; // ASSERT_NEAR(actual.heading, expect.heading, 0.1) << case_descriptor; // } // } }; // namespace terrain::geometry
33.942308
123
0.560151
teyrana
121fa1ada6dee2ae4c3e5240a755cf55391194b2
27,969
cpp
C++
src/q3bsp/Q3BspMap.cpp
suijingfeng/bsp_vulkan
8f96b164b30d6860e2a2861e1809bf693f0c8de0
[ "MIT" ]
2
2021-07-29T19:56:03.000Z
2021-09-13T12:06:06.000Z
src/q3bsp/Q3BspMap.cpp
suijingfeng/bsp_vulkan
8f96b164b30d6860e2a2861e1809bf693f0c8de0
[ "MIT" ]
null
null
null
src/q3bsp/Q3BspMap.cpp
suijingfeng/bsp_vulkan
8f96b164b30d6860e2a2861e1809bf693f0c8de0
[ "MIT" ]
null
null
null
#include "Q3BspMap.hpp" #include "Q3BspPatch.hpp" #include "../renderer/TextureManager.hpp" #include "../renderer/vulkan/CmdBuffer.hpp" #include "../renderer/vulkan/Pipeline.hpp" #include "../Math.hpp" #include "../Utils.hpp" #include <algorithm> #include <sstream> extern RenderContext g_renderContext; const int Q3BspMap::s_tesselationLevel = 10; // level of curved surface tesselation const float Q3BspMap::s_worldScale = 64.f; // scale down factor for the map Q3BspMap::~Q3BspMap() { delete[] entities.ents; delete[] visData.vecs; for (auto &it : m_patches) delete it; // release all allocated Vulkan resources vkDeviceWaitIdle(g_renderContext.device.logical); vk::destroyPipeline(g_renderContext.device, m_facesPipeline); vk::destroyPipeline(g_renderContext.device, m_patchPipeline); for (auto &it : m_renderBuffers.m_faceBuffers) { vkDestroyDescriptorPool(g_renderContext.device.logical, it.second.descriptor.pool, nullptr); vk::freeBuffer(g_renderContext.device, it.second.vertexBuffer); vk::freeBuffer(g_renderContext.device, it.second.indexBuffer); } for (auto &it : m_renderBuffers.m_patchBuffers) { for (auto &it2 : it.second) { vkDestroyDescriptorPool(g_renderContext.device.logical, it2.descriptor.pool, nullptr); vk::freeBuffer(g_renderContext.device, it2.vertexBuffer); vk::freeBuffer(g_renderContext.device, it2.indexBuffer); } } for (size_t i = 0; i < lightMaps.size(); ++i) { vk::releaseTexture(g_renderContext.device, m_lightmapTextures[i]); } delete[] m_lightmapTextures; vk::freeBuffer(g_renderContext.device, m_renderBuffers.uniformBuffer); vk::releaseTexture(g_renderContext.device, m_whiteTex); vk::freeCommandBuffers(g_renderContext.device, m_commandPool, m_commandBuffers); vk::destroyRenderPass(g_renderContext.device, m_renderPass); vkDestroyCommandPool(g_renderContext.device.logical, m_commandPool, nullptr); vkDestroyDescriptorSetLayout(g_renderContext.device.logical, m_dsLayout, nullptr); } void Q3BspMap::Init() { // regular faces are simple triangle lists, patches are drawn as triangle strips, so we need extra pipeline m_facesPipeline.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; m_patchPipeline.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; VK_VERIFY(vk::createRenderPass(g_renderContext.device, g_renderContext.swapChain, &m_renderPass)); VK_VERIFY(vk::createCommandPool(g_renderContext.device, &m_commandPool)); // build the swap chain g_renderContext.RecreateSwapChain(m_commandPool, m_renderPass); // stub missing texture used if original Quake assets are missing m_missingTex = TextureManager::GetInstance()->LoadTexture("../../res/missing.png", m_commandPool); // load textures LoadTextures(); // load lightmaps LoadLightmaps(); // create renderable faces and patches m_renderLeaves.reserve(leaves.size()); for (const auto &l : leaves) { m_renderLeaves.push_back(Q3LeafRenderable()); m_renderLeaves.back().visCluster = l.cluster; m_renderLeaves.back().firstFace = l.leafFace; m_renderLeaves.back().numFaces = l.n_leafFaces; // create a bounding box m_renderLeaves.back().boundingBoxVertices[0] = Math::Vector3f((float)l.mins.x, (float)l.mins.y, (float)l.mins.z); m_renderLeaves.back().boundingBoxVertices[1] = Math::Vector3f((float)l.mins.x, (float)l.mins.y, (float)l.maxs.z); m_renderLeaves.back().boundingBoxVertices[2] = Math::Vector3f((float)l.mins.x, (float)l.maxs.y, (float)l.mins.z); m_renderLeaves.back().boundingBoxVertices[3] = Math::Vector3f((float)l.mins.x, (float)l.maxs.y, (float)l.maxs.z); m_renderLeaves.back().boundingBoxVertices[4] = Math::Vector3f((float)l.maxs.x, (float)l.mins.y, (float)l.mins.z); m_renderLeaves.back().boundingBoxVertices[5] = Math::Vector3f((float)l.maxs.x, (float)l.mins.y, (float)l.maxs.z); m_renderLeaves.back().boundingBoxVertices[6] = Math::Vector3f((float)l.maxs.x, (float)l.maxs.y, (float)l.mins.z); m_renderLeaves.back().boundingBoxVertices[7] = Math::Vector3f((float)l.maxs.x, (float)l.maxs.y, (float)l.maxs.z); for (int i = 0; i < 8; ++i) { m_renderLeaves.back().boundingBoxVertices[i].m_x /= Q3BspMap::s_worldScale; m_renderLeaves.back().boundingBoxVertices[i].m_y /= Q3BspMap::s_worldScale; m_renderLeaves.back().boundingBoxVertices[i].m_z /= Q3BspMap::s_worldScale; } } m_renderFaces.reserve(faces.size()); // create a common descriptor set layout and vertex buffer info m_vbInfo.bindingDescriptions.push_back(vk::getBindingDescription(sizeof(Q3BspVertexLump))); m_vbInfo.attributeDescriptions.push_back(vk::getAttributeDescription(inVertex, VK_FORMAT_R32G32B32_SFLOAT, 0)); m_vbInfo.attributeDescriptions.push_back(vk::getAttributeDescription(inTexCoord, VK_FORMAT_R32G32_SFLOAT, sizeof(vec3f))); m_vbInfo.attributeDescriptions.push_back(vk::getAttributeDescription(inTexCoordLightmap, VK_FORMAT_R32G32_SFLOAT, sizeof(vec3f) + sizeof(vec2f))); CreateDescriptorSetLayout(); // single shared uniform buffer VK_VERIFY(vk::createUniformBuffer(g_renderContext.device, sizeof(UniformBufferObject), &m_renderBuffers.uniformBuffer)); int faceArrayIdx = 0; int patchArrayIdx = 0; for (const auto &f : faces) { m_renderFaces.push_back(Q3FaceRenderable()); //is it a patch? if (f.type == FaceTypePatch) { m_renderFaces.back().index = patchArrayIdx; CreatePatch(f); // generate Vulkan buffers for current patch CreateBuffersForPatch(patchArrayIdx); ++patchArrayIdx; } else { m_renderFaces.back().index = faceArrayIdx; // generate Vulkan buffers for current face CreateBuffersForFace(f, faceArrayIdx); } ++faceArrayIdx; m_renderFaces.back().type = f.type; } m_mapStats.totalVertices = vertices.size(); m_mapStats.totalFaces = faces.size(); m_mapStats.totalPatches = patchArrayIdx; RebuildPipelines(); VK_VERIFY(vk::createCommandBuffers(g_renderContext.device, m_commandPool, m_commandBuffers, g_renderContext.frameBuffers.size())); // set the scale-down uniform m_ubo.worldScaleFactor = 1.f / Q3BspMap::s_worldScale; printf("Q3BspMap::Init()\n"); } void Q3BspMap::OnRender() { // update uniform buffers m_ubo.ModelViewProjectionMatrix = g_renderContext.ModelViewProjectionMatrix; m_frustum.UpdatePlanes(); void *data; vmaMapMemory(g_renderContext.device.allocator, m_renderBuffers.uniformBuffer.allocation, &data); memcpy(data, &m_ubo, sizeof(m_ubo)); vmaUnmapMemory(g_renderContext.device.allocator, m_renderBuffers.uniformBuffer.allocation); // record new set of command buffers including only visible faces and patches RecordCommandBuffers(); // render visible faces VK_VERIFY(g_renderContext.Submit(m_commandBuffers)); } void Q3BspMap::OnWindowChanged() { g_renderContext.RecreateSwapChain(m_commandPool, m_renderPass); RebuildPipelines(); } // determine if a bsp cluster is visible from a given camera cluster bool Q3BspMap::ClusterVisible(int cameraCluster, int testCluster) const { if (!visData.vecs || (cameraCluster < 0)) { return true; } int idx = (cameraCluster * visData.sz_vecs) + (testCluster >> 3); return (visData.vecs[idx] & (1 << (testCluster & 7))) != 0; } // determine which bsp leaf camera resides in int Q3BspMap::FindCameraLeaf(const Math::Vector3f &cameraPosition) const { int leafIndex = 0; while (leafIndex >= 0) { // children.x - front node; children.y - back node if (PointPlanePos(planes[nodes[leafIndex].plane].normal.x, planes[nodes[leafIndex].plane].normal.y, planes[nodes[leafIndex].plane].normal.z, planes[nodes[leafIndex].plane].dist, cameraPosition) == Math::PointInFrontOfPlane) { leafIndex = nodes[leafIndex].children.x; } else { leafIndex = nodes[leafIndex].children.y; } } return ~leafIndex; } //Calculate which faces to draw given a camera position & view frustum void Q3BspMap::CalculateVisibleFaces(const Math::Vector3f &cameraPosition) { m_visibleFaces.clear(); m_visiblePatches.clear(); //calculate the camera leaf int cameraLeaf = FindCameraLeaf(cameraPosition * Q3BspMap::s_worldScale); int cameraCluster = m_renderLeaves[cameraLeaf].visCluster; //loop through the leaves for (const auto &rl : m_renderLeaves) { //if the leaf is not in the PVS - skip it if (!HasRenderFlag(Q3RenderSkipPVS) && !ClusterVisible(cameraCluster, rl.visCluster)) continue; //if this leaf does not lie in the frustum - skip it if (!HasRenderFlag(Q3RenderSkipFC) && !m_frustum.BoxInFrustum(rl.boundingBoxVertices)) continue; //loop through faces in this leaf and them to visibility set for(int j = 0; j < rl.numFaces; ++j) { int idx = leafFaces[rl.firstFace + j].face; Q3FaceRenderable *face = &m_renderFaces[leafFaces[rl.firstFace + j].face]; if (HasRenderFlag(Q3RenderSkipMissingTex) && !m_textures[faces[idx].texture]) continue; if ((face->type == FaceTypePolygon || face->type == FaceTypeMesh) && std::find(m_visibleFaces.begin(), m_visibleFaces.end(), face) == m_visibleFaces.end()) { m_visibleFaces.push_back(face); } if (face->type == FaceTypePatch && std::find(m_visiblePatches.begin(), m_visiblePatches.end(), idx) == m_visiblePatches.end()) { m_visiblePatches.push_back(idx); } } } m_mapStats.visibleFaces = m_visibleFaces.size(); m_mapStats.visiblePatches = m_visiblePatches.size(); } void Q3BspMap::ToggleRenderFlag(int flag) { m_renderFlags ^= flag; bool set = HasRenderFlag(flag); switch (flag) { case Q3RenderShowWireframe: m_facesPipeline.mode = set ? VK_POLYGON_MODE_LINE : VK_POLYGON_MODE_FILL; m_patchPipeline.mode = set ? VK_POLYGON_MODE_LINE : VK_POLYGON_MODE_FILL; RebuildPipelines(); break; case Q3RenderShowLightmaps: m_ubo.renderLightmaps = set ? 1 : 0; break; case Q3RenderUseLightmaps: m_ubo.useLightmaps = set ? 1 : 0; break; case Q3RenderAlphaTest: m_ubo.useAlphaTest = set ? 1 : 0; break; default: break; } } void Q3BspMap::LoadTextures() { int numTextures = header.direntries[Textures].length / sizeof(Q3BspTextureLump); m_textures.resize(numTextures); // load the textures from file (determine wheter it's a jpg or tga) for (const auto &f : faces) { if (m_textures[f.texture]) continue; std::string nameJPG = textures[f.texture].name; nameJPG.append(".jpg"); m_textures[f.texture] = TextureManager::GetInstance()->LoadTexture(nameJPG.c_str(), m_commandPool); if (m_textures[f.texture] == nullptr) { std::string nameTGA = textures[f.texture].name; nameTGA.append(".tga"); m_textures[f.texture] = TextureManager::GetInstance()->LoadTexture(nameTGA.c_str(), m_commandPool); if (m_textures[f.texture] == nullptr) { std::stringstream sstream; sstream << "Missing texture: " << nameTGA.c_str() << "\n"; LOG_MESSAGE(sstream.str().c_str()); } } } printf("LoadTextures()\n"); } void Q3BspMap::LoadLightmaps() { m_lightmapTextures = new vk::Texture[lightMaps.size()]; // optional: change gamma settings of the lightmaps (make them brighter) SetLightmapGamma(2.5f); // few GPUs support true 24bit textures, so we need to convert lightmaps to 32bit for Vulkan to work unsigned char rgba_lmap[128 * 128 * 4]; for (size_t i = 0; i < lightMaps.size(); ++i) { memset(rgba_lmap, 255, 128 * 128 * 4); for (int j = 0, k = 0; k < 128 * 128 * 3; j += 4, k += 3) memcpy(rgba_lmap + j, lightMaps[i].map + k, 3); // Create texture from bsp lightmap data vk::createTexture(g_renderContext.device, m_commandPool, &m_lightmapTextures[i], rgba_lmap, 128, 128); } // Create white texture for if no lightmap specified unsigned char white[] = { 255, 255, 255, 255 }; vk::createTexture(g_renderContext.device, m_commandPool, &m_whiteTex, white, 1, 1); printf("LoadLightmaps()\n"); } // tweak lightmap gamma settings void Q3BspMap::SetLightmapGamma(float gamma) { for (size_t i = 0; i < lightMaps.size(); ++i) { for (int j = 0; j < 128 * 128; ++j) { float r, g, b; r = lightMaps[i].map[j * 3 + 0]; g = lightMaps[i].map[j * 3 + 1]; b = lightMaps[i].map[j * 3 + 2]; r *= gamma / 255.0f; g *= gamma / 255.0f; b *= gamma / 255.0f; float scale = 1.0f; float temp; if (r > 1.0f && (temp = (1.0f / r)) < scale) scale = temp; if (g > 1.0f && (temp = (1.0f / g)) < scale) scale = temp; if (b > 1.0f && (temp = (1.0f / b)) < scale) scale = temp; scale *= 255.0f; r *= scale; g *= scale; b *= scale; lightMaps[i].map[j * 3 + 0] = (unsigned char)r; lightMaps[i].map[j * 3 + 1] = (unsigned char)g; lightMaps[i].map[j * 3 + 2] = (unsigned char)b; } } } // create a Q3Bsp curved surface void Q3BspMap::CreatePatch(const Q3BspFaceLump &f) { Q3BspPatch *newPatch = new Q3BspPatch; newPatch->textureIdx = f.texture; newPatch->lightmapIdx = f.lm_index; newPatch->width = f.size.x; newPatch->height = f.size.y; int numPatchesWidth = (newPatch->width - 1) >> 1; int numPatchesHeight = (newPatch->height - 1) >> 1; newPatch->quadraticPatches.resize(numPatchesWidth*numPatchesHeight); // generate biquadratic patches (components that make the curved surface) for (int y = 0; y < numPatchesHeight; ++y) { for (int x = 0; x < numPatchesWidth; ++x) { for (int row = 0; row < 3; ++row) { for (int col = 0; col < 3; ++col) { int patchIdx = y * numPatchesWidth + x; int cpIdx = row * 3 + col; newPatch->quadraticPatches[patchIdx].controlPoints[cpIdx] = vertices[f.vertex + (y * 2 * newPatch->width + x * 2) + row * newPatch->width + col]; } } newPatch->quadraticPatches[y * numPatchesWidth + x].Tesselate(Q3BspMap::s_tesselationLevel); } } m_patches.push_back(newPatch); } void Q3BspMap::RecordCommandBuffers() { for (size_t i = 0; i < m_commandBuffers.size(); ++i) { VkCommandBufferBeginInfo beginInfo = {}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; beginInfo.pInheritanceInfo = nullptr; VkResult result = vkBeginCommandBuffer(m_commandBuffers[i], &beginInfo); LOG_MESSAGE_ASSERT(result == VK_SUCCESS, "Could not begin command buffer: " << result); VkClearValue clearColors[2]; clearColors[0].color = { 0.f, 0.f, 0.f, 1.f }; clearColors[1].depthStencil = { 1.0f, 0 }; VkRenderPassBeginInfo renderBeginInfo = {}; renderBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderBeginInfo.renderPass = m_renderPass.renderPass; renderBeginInfo.framebuffer = g_renderContext.frameBuffers[i]; renderBeginInfo.renderArea.offset = { 0, 0 }; renderBeginInfo.renderArea.extent = g_renderContext.swapChain.extent; renderBeginInfo.clearValueCount = 2; renderBeginInfo.pClearValues = clearColors; vkCmdBeginRenderPass(m_commandBuffers[i], &renderBeginInfo, VK_SUBPASS_CONTENTS_INLINE); // queue standard faces vkCmdBindPipeline(m_commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_facesPipeline.pipeline); for (auto &f : m_visibleFaces) { FaceBuffers &fb = m_renderBuffers.m_faceBuffers[f->index]; VkBuffer vertexBuffers[] = { fb.vertexBuffer.buffer }; VkDeviceSize offsets[] = { 0 }; vkCmdBindVertexBuffers(m_commandBuffers[i], 0, 1, vertexBuffers, offsets); // quake 3 bsp requires uint32 for index type - 16 is too small vkCmdBindIndexBuffer(m_commandBuffers[i], fb.indexBuffer.buffer, 0, VK_INDEX_TYPE_UINT32); vkCmdBindDescriptorSets(m_commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_facesPipeline.layout, 0, 1, &fb.descriptor.set, 0, nullptr); vkCmdDrawIndexed(m_commandBuffers[i], fb.indexCount, 1, 0, 0, 0); } // queue patches vkCmdBindPipeline(m_commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_patchPipeline.pipeline); for (auto &pi : m_visiblePatches) { for (auto &p : m_renderBuffers.m_patchBuffers[pi]) { VkBuffer vertexBuffers[] = { p.vertexBuffer.buffer }; VkDeviceSize offsets[] = { 0 }; vkCmdBindVertexBuffers(m_commandBuffers[i], 0, 1, vertexBuffers, offsets); // quake 3 bsp requires uint32 for index type - 16 is too small vkCmdBindIndexBuffer(m_commandBuffers[i], p.indexBuffer.buffer, 0, VK_INDEX_TYPE_UINT32); vkCmdBindDescriptorSets(m_commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_patchPipeline.layout, 0, 1, &p.descriptor.set, 0, nullptr); vkCmdDrawIndexed(m_commandBuffers[i], p.indexCount, 1, 0, 0, 0); } } vkCmdEndRenderPass(m_commandBuffers[i]); result = vkEndCommandBuffer(m_commandBuffers[i]); LOG_MESSAGE_ASSERT(result == VK_SUCCESS, "Error recording command buffer: " << result); } } void Q3BspMap::RebuildPipelines() { vkDeviceWaitIdle(g_renderContext.device.logical); vk::destroyPipeline(g_renderContext.device, m_facesPipeline); vk::destroyPipeline(g_renderContext.device, m_patchPipeline); // todo: pipeline derivatives https://github.com/SaschaWillems/Vulkan/blob/master/examples/pipelines/pipelines.cpp const char *shaders[] = { "../../res/Basic_vert.spv", "../../res/Basic_frag.spv" }; VK_VERIFY(vk::createPipeline(g_renderContext.device, g_renderContext.swapChain, m_renderPass, m_dsLayout, &m_vbInfo, &m_facesPipeline, shaders)); VK_VERIFY(vk::createPipeline(g_renderContext.device, g_renderContext.swapChain, m_renderPass, m_dsLayout, &m_vbInfo, &m_patchPipeline, shaders)); } void Q3BspMap::CreateBuffersForFace(const Q3BspFaceLump &face, int idx) { if (face.type == FaceTypeBillboard) return; auto &faceBuffer = m_renderBuffers.m_faceBuffers[idx]; faceBuffer.descriptor.setLayout = m_dsLayout; faceBuffer.vertexCount = face.n_vertexes; faceBuffer.indexCount = face.n_meshverts; // vertex buffer and index buffer with staging buffer vk::createVertexBuffer(g_renderContext.device, m_commandPool, &(vertices[face.vertex].position), sizeof(Q3BspVertexLump) * face.n_vertexes, &faceBuffer.vertexBuffer); vk::createIndexBuffer(g_renderContext.device, m_commandPool, &meshVertices[face.meshvert], sizeof(Q3BspMeshVertLump) * face.n_meshverts, &faceBuffer.indexBuffer); // check if both the texture and lightmap exist and if not - replace them with missing/white texture stubs const vk::Texture *colorTex = m_textures[faces[idx].texture] ? *m_textures[faces[idx].texture] : *m_missingTex; const vk::Texture &lmap = faces[idx].lm_index >= 0 ? m_lightmapTextures[faces[idx].lm_index] : m_whiteTex; const vk::Texture *textureSet[2] = { colorTex, &lmap }; CreateDescriptor(textureSet, &faceBuffer.descriptor); } void Q3BspMap::CreateBuffersForPatch(int idx) { int numPatches = m_patches[idx]->quadraticPatches.size(); for (int i = 0; i < numPatches; i++) { // shorthand references so the code is easier to read auto *patch = m_patches[idx]; auto &biquadPatch = patch->quadraticPatches[i]; auto &patchBuffer = m_renderBuffers.m_patchBuffers[idx]; int numVerts = biquadPatch.m_vertices.size(); int tessLevel = biquadPatch.m_tesselationLevel; for (int row = 0; row < tessLevel; ++row) { FaceBuffers pb; pb.descriptor.setLayout = m_dsLayout; pb.vertexCount = numVerts; pb.indexCount = 2 * (tessLevel + 1); // vertex buffer and index buffer with staging buffer vk::createVertexBuffer(g_renderContext.device, m_commandPool, &biquadPatch.m_vertices[0].position, sizeof(Q3BspVertexLump) * numVerts, &pb.vertexBuffer); vk::createIndexBuffer(g_renderContext.device, m_commandPool, &biquadPatch.m_indices[row * 2 * (tessLevel + 1)], sizeof(Q3BspMeshVertLump) * 2 * (tessLevel + 1), &pb.indexBuffer); // check if both the texture and lightmap exist and if not - replace them with missing/white texture stubs const vk::Texture *colorTex = m_textures[patch->textureIdx] ? *m_textures[patch->textureIdx] : *m_missingTex; const vk::Texture &lmap = patch->lightmapIdx >= 0 ? m_lightmapTextures[patch->lightmapIdx] : m_whiteTex; // create Vulkan descriptor const vk::Texture *textureSet[] = { colorTex, &lmap }; CreateDescriptor(textureSet, &pb.descriptor); patchBuffer.emplace_back(pb); } } } void Q3BspMap::CreateDescriptorSetLayout() { VkDescriptorSetLayoutBinding uboLayoutBinding = {}; uboLayoutBinding.binding = 0; uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; uboLayoutBinding.descriptorCount = 1; uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; uboLayoutBinding.pImmutableSamplers = nullptr; VkDescriptorSetLayoutBinding samplerLayoutBinding = {}; samplerLayoutBinding.binding = 1; samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; samplerLayoutBinding.descriptorCount = 1; samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; samplerLayoutBinding.pImmutableSamplers = nullptr; VkDescriptorSetLayoutBinding lightmapSamplerLayoutBinding = {}; lightmapSamplerLayoutBinding.binding = 2; lightmapSamplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; lightmapSamplerLayoutBinding.descriptorCount = 1; lightmapSamplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; lightmapSamplerLayoutBinding.pImmutableSamplers = nullptr; VkDescriptorSetLayoutBinding bindings[] = { uboLayoutBinding, samplerLayoutBinding, lightmapSamplerLayoutBinding }; VkDescriptorSetLayoutCreateInfo layoutInfo = {}; layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; layoutInfo.bindingCount = 3; layoutInfo.pBindings = bindings; VK_VERIFY(vkCreateDescriptorSetLayout(g_renderContext.device.logical, &layoutInfo, nullptr, &m_dsLayout)); } void Q3BspMap::CreateDescriptor(const vk::Texture **textures, vk::Descriptor *descriptor) { // create descriptor pool VkDescriptorPoolSize poolSizes[3]; poolSizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; poolSizes[0].descriptorCount = 1; poolSizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; poolSizes[1].descriptorCount = 1; poolSizes[2].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; poolSizes[2].descriptorCount = 1; VkDescriptorPoolCreateInfo poolInfo = {}; poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; poolInfo.poolSizeCount = 3; poolInfo.pPoolSizes = poolSizes; poolInfo.maxSets = 1; VK_VERIFY(vkCreateDescriptorPool(g_renderContext.device.logical, &poolInfo, nullptr, &descriptor->pool)); // create descriptor set VK_VERIFY(vk::createDescriptorSet(g_renderContext.device, descriptor)); VkDescriptorBufferInfo bufferInfo = {}; bufferInfo.offset = 0; bufferInfo.buffer = m_renderBuffers.uniformBuffer.buffer; bufferInfo.range = sizeof(UniformBufferObject); VkDescriptorImageInfo imageInfo = {}; imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; imageInfo.imageView = textures[0]->imageView; imageInfo.sampler = textures[0]->sampler; VkDescriptorImageInfo lightmapInfo = {}; lightmapInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; lightmapInfo.imageView = textures[1]->imageView; lightmapInfo.sampler = textures[1]->sampler; VkWriteDescriptorSet descriptorWrites[3]; descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrites[0].dstSet = descriptor->set; descriptorWrites[0].dstBinding = 0; descriptorWrites[0].dstArrayElement = 0; descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; descriptorWrites[0].descriptorCount = 1; descriptorWrites[0].pBufferInfo = &bufferInfo; descriptorWrites[0].pImageInfo = nullptr; descriptorWrites[0].pTexelBufferView = nullptr; descriptorWrites[0].pNext = nullptr; descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrites[1].dstSet = descriptor->set; descriptorWrites[1].dstBinding = 1; descriptorWrites[1].dstArrayElement = 0; descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; descriptorWrites[1].descriptorCount = 1; descriptorWrites[1].pBufferInfo = nullptr; descriptorWrites[1].pImageInfo = &imageInfo; descriptorWrites[1].pTexelBufferView = nullptr; descriptorWrites[1].pNext = nullptr; descriptorWrites[2].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrites[2].dstSet = descriptor->set; descriptorWrites[2].dstBinding = 2; descriptorWrites[2].dstArrayElement = 0; descriptorWrites[2].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; descriptorWrites[2].descriptorCount = 1; descriptorWrites[2].pBufferInfo = nullptr; descriptorWrites[2].pImageInfo = &lightmapInfo; descriptorWrites[2].pTexelBufferView = nullptr; descriptorWrites[2].pNext = nullptr; vkUpdateDescriptorSets(g_renderContext.device.logical, 3, descriptorWrites, 0, nullptr); }
41.252212
156
0.653152
suijingfeng
1220881c38060cb1b2a19c4c26f39604e2d1edab
2,854
cpp
C++
tests/serialization_ext_std_chrono.cpp
victorstewart/bitsery
db884a0656a3aabb87da1ae6edf12629507f76a7
[ "MIT" ]
722
2017-08-22T06:07:02.000Z
2022-03-30T03:29:20.000Z
tests/serialization_ext_std_chrono.cpp
victorstewart/bitsery
db884a0656a3aabb87da1ae6edf12629507f76a7
[ "MIT" ]
85
2017-10-19T07:23:29.000Z
2022-03-02T06:54:10.000Z
tests/serialization_ext_std_chrono.cpp
victorstewart/bitsery
db884a0656a3aabb87da1ae6edf12629507f76a7
[ "MIT" ]
69
2017-08-28T06:38:07.000Z
2022-03-13T03:12:02.000Z
//MIT License // //Copyright (c) 2019 Mindaugas Vinkelis // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. #include <bitsery/ext/std_chrono.h> #include <gmock/gmock.h> #include "serialization_test_utils.h" using StdDuration = bitsery::ext::StdDuration; using StdTimePoint = bitsery::ext::StdTimePoint; using testing::Eq; TEST(SerializeExtensionStdChrono, IntegralDuration) { SerializationContext ctx1; using Hours = std::chrono::duration<int32_t, std::ratio<60>>; Hours data{43}; Hours res{}; ctx1.createSerializer().ext4b(data, StdDuration{}); ctx1.createDeserializer().ext4b(res, StdDuration{}); EXPECT_THAT(res, Eq(data)); } TEST(SerializeExtensionStdChrono, IntegralTimePoint) { SerializationContext ctx1; using Duration = std::chrono::duration<int64_t, std::milli>; using TP = std::chrono::time_point<std::chrono::system_clock, Duration>; TP data{Duration{243}}; TP res{}; ctx1.createSerializer().ext8b(data, StdTimePoint{}); ctx1.createDeserializer().ext8b(res, StdTimePoint{}); EXPECT_THAT(res, Eq(data)); } TEST(SerializeExtensionStdChrono, FloatDuration) { SerializationContext ctx1; using Hours = std::chrono::duration<float, std::ratio<60>>; Hours data{43.5f}; Hours res{}; ctx1.createSerializer().ext4b(data, StdDuration{}); ctx1.createDeserializer().ext4b(res, StdDuration{}); EXPECT_THAT(res, Eq(data)); } TEST(SerializeExtensionStdChrono, FloatTimePoint) { SerializationContext ctx1; using Duration = std::chrono::duration<double, std::milli>; using TP = std::chrono::time_point<std::chrono::system_clock, Duration>; TP data{Duration{243457.4}}; TP res{}; ctx1.createSerializer().ext8b(data, StdTimePoint{}); ctx1.createDeserializer().ext8b(res, StdTimePoint{}); EXPECT_THAT(res, Eq(data)); }
34.804878
80
0.734408
victorstewart
1220e5dc0ecb154d3c197288354a7640ae647746
4,554
cpp
C++
projects/InjectDLL/system/textures.cpp
LoadCake/OriWotwRandomizerClient
99812148b60aad77895bf4aa560128d0ff9b73eb
[ "MIT" ]
null
null
null
projects/InjectDLL/system/textures.cpp
LoadCake/OriWotwRandomizerClient
99812148b60aad77895bf4aa560128d0ff9b73eb
[ "MIT" ]
null
null
null
projects/InjectDLL/system/textures.cpp
LoadCake/OriWotwRandomizerClient
99812148b60aad77895bf4aa560128d0ff9b73eb
[ "MIT" ]
null
null
null
#include <system/textures.h> #include <Common/ext.h> #include <Il2CppModLoader/common.h> #include <Il2CppModLoader/il2cpp_helpers.h> #include <Il2CppModLoader/interception_macros.h> #include <utils\stb_image.h> #include <fstream> #include <string> #include <unordered_map> using namespace modloader; namespace textures { std::unordered_map<std::wstring, uint32_t> files; NAMED_IL2CPP_BINDING_OVERLOAD(UnityEngine, Texture2D, void, .ctor, ctor, (app::Texture2D* this_ptr, int width, int height, app::TextureFormat__Enum format, bool mip_chain, bool linear), (System:Int32, System:Int32, UnityEngine:TextureFormat, System:Boolean, System:Boolean)) IL2CPP_BINDING(UnityEngine, Texture2D, void, LoadRawTextureData, (app::Texture2D* this_ptr, void* data, int size)); IL2CPP_BINDING(UnityEngine, Texture2D, void, Apply, (app::Texture2D* this_ptr, bool update_mipmaps, bool no_longer_readable)); app::Texture2D* get_texture(std::wstring_view path) { try { auto separator = path.find(':', 0); if (separator == -1) { // Trace error return nullptr; } auto type = path.substr(0, separator); auto value = std::wstring(path.substr(separator + 1)); if (type == L"shard") { auto actual_value = static_cast<app::SpiritShardType__Enum>(std::stoi(value)); auto settings = il2cpp::get_class<app::SpiritShardSettings__Class>("", "SpiritShardSettings")->static_fields->Instance; auto item = il2cpp::invoke<app::SpiritShardIconsCollection_Icons__Boxed>(settings->fields.Icons, "GetValue", &actual_value); // TODO: add second selector. return item == nullptr ? nullptr : item->fields.InventoryIcon; } else if (type == L"ability") { auto actual_value = static_cast<app::AbilityType__Enum>(std::stoi(value)); auto settings = il2cpp::get_class<app::SpellSettings__Class>("", "SpellSettings")->static_fields->Instance; auto item = il2cpp::invoke<app::Texture2D>(settings->fields.CustomAbilityIcons, "GetValue", &actual_value); // TODO: add second selector. return item; } else if (type == L"spell") { auto actual_value = static_cast<app::EquipmentType__Enum>(std::stoi(value)); auto settings = il2cpp::get_class<app::SpellSettings__Class>("", "SpellSettings")->static_fields->Instance; auto item = il2cpp::invoke<app::SpellIconsCollection_Icons__Boxed>(settings->fields.Icons, "GetValue", &actual_value); // TODO: add second selector. return item == nullptr ? nullptr : item->fields.InventoryIcon; } else if (type == L"file") { auto it = files.find(value); if (it != files.end()) return reinterpret_cast<app::Texture2D*>(il2cpp::gchandle_target(it->second)); auto path = base_path + convert_wstring_to_string(value); replace_all(path, "/", "\\"); int x; int y; int n = 4; stbi_set_flip_vertically_on_load(true); unsigned char* data = stbi_load(path.c_str(), &x, &y, &n, STBI_rgb_alpha); if (data == nullptr) { modloader::warn("textures", format("failed to load texture %s (%s).", path.c_str(), stbi_failure_reason())); return nullptr; } auto texture = il2cpp::create_object<app::Texture2D>("UnityEngine", "Texture2D"); Texture2D::ctor(texture, x, y, app::TextureFormat__Enum_RGBA32, false, false); Texture2D::LoadRawTextureData(texture, data, x * y * n); Texture2D::Apply(texture, true, false); stbi_image_free(data); files[value] = il2cpp::gchandle_new(texture, false); return texture; } else { modloader::warn("textures", "unknown texture protocol used when loading texture."); return nullptr; } } catch (std::exception e) { modloader::warn("textures", format("Fatal error fetching texture (%s)", e.what())); return nullptr; } } }
43.371429
140
0.577514
LoadCake
12238f77a4457449517ef9c7dd13e7fa927f8434
47,151
hxx
C++
Modules/Registration/Common/include/itkMattesMutualInformationImageToImageMetric.hxx
CapeDrew/DCMTK-ITK
440bf8ed100445396912cfd0aa72f36d4cdefe0c
[ "Apache-2.0" ]
2
2015-06-19T07:18:36.000Z
2019-04-18T07:28:23.000Z
Modules/Registration/Common/include/itkMattesMutualInformationImageToImageMetric.hxx
CapeDrew/DCMTK-ITK
440bf8ed100445396912cfd0aa72f36d4cdefe0c
[ "Apache-2.0" ]
null
null
null
Modules/Registration/Common/include/itkMattesMutualInformationImageToImageMetric.hxx
CapeDrew/DCMTK-ITK
440bf8ed100445396912cfd0aa72f36d4cdefe0c
[ "Apache-2.0" ]
2
2017-05-02T07:18:49.000Z
2020-04-30T01:37:35.000Z
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __itkMattesMutualInformationImageToImageMetric_hxx #define __itkMattesMutualInformationImageToImageMetric_hxx #include "itkMattesMutualInformationImageToImageMetric.h" #include "itkImageRandomConstIteratorWithIndex.h" #include "itkImageRegionIterator.h" #include "itkImageIterator.h" #include "vnl/vnl_math.h" #include "itkStatisticsImageFilter.h" #include "vnl/vnl_vector.h" #include "vnl/vnl_c_vector.h" namespace itk { /** * Constructor */ template <class TFixedImage, class TMovingImage> MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::MattesMutualInformationImageToImageMetric() : // Initialize memory m_FixedImageMarginalPDF(NULL), m_MovingImageMarginalPDF(NULL), m_PRatioArray(), m_MetricDerivative(0), m_ThreaderMetricDerivative(NULL), // Initialize PDFs to NULL m_JointPDF(NULL), m_JointPDFBufferSize(0), m_JointPDFDerivatives(NULL), m_JointPDFDerivativesBufferSize(0), m_NumberOfHistogramBins(50), m_MovingImageNormalizedMin(0.0), m_FixedImageNormalizedMin(0.0), m_MovingImageTrueMin(0.0), m_MovingImageTrueMax(0.0), m_FixedImageBinSize(0.0), m_MovingImageBinSize(0.0), m_CubicBSplineKernel(NULL), m_CubicBSplineDerivativeKernel(NULL), // For multi-threading the metric m_ThreaderFixedImageMarginalPDF(NULL), m_ThreaderJointPDF(NULL), m_ThreaderJointPDFDerivatives(NULL), m_ThreaderJointPDFStartBin(NULL), m_ThreaderJointPDFEndBin(NULL), m_ThreaderJointPDFSum(NULL), m_JointPDFSum(0.0), m_UseExplicitPDFDerivatives(true), m_ImplicitDerivativesSecondPass(false) { this->SetComputeGradient(false); // don't use the default gradient for now this->m_WithinThreadPreProcess = true; this->m_WithinThreadPostProcess = false; this->m_ComputeGradient = false; } template <class TFixedImage, class TMovingImage> MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::~MattesMutualInformationImageToImageMetric() { if( m_FixedImageMarginalPDF != NULL ) { delete[] m_FixedImageMarginalPDF; } m_FixedImageMarginalPDF = NULL; if( m_MovingImageMarginalPDF != NULL ) { delete[] m_MovingImageMarginalPDF; } m_MovingImageMarginalPDF = NULL; if( m_ThreaderJointPDF != NULL ) { delete[] m_ThreaderJointPDF; } m_ThreaderJointPDF = NULL; if( m_ThreaderJointPDFDerivatives != NULL ) { delete[] m_ThreaderJointPDFDerivatives; } m_ThreaderJointPDFDerivatives = NULL; if( m_ThreaderFixedImageMarginalPDF != NULL ) { delete[] m_ThreaderFixedImageMarginalPDF; } m_ThreaderFixedImageMarginalPDF = NULL; if( m_ThreaderJointPDFStartBin != NULL ) { delete[] m_ThreaderJointPDFStartBin; } m_ThreaderJointPDFStartBin = NULL; if( m_ThreaderJointPDFEndBin != NULL ) { delete[] m_ThreaderJointPDFEndBin; } m_ThreaderJointPDFEndBin = NULL; if( m_ThreaderJointPDFSum != NULL ) { delete[] m_ThreaderJointPDFSum; } m_ThreaderJointPDFSum = NULL; if( this->m_ThreaderMetricDerivative != NULL ) { delete[] this->m_ThreaderMetricDerivative; } this->m_ThreaderMetricDerivative = NULL; } /** * Print out internal information about this class */ template <class TFixedImage, class TMovingImage> void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "NumberOfHistogramBins: "; os << this->m_NumberOfHistogramBins << std::endl; // Debugging information os << indent << "FixedImageNormalizedMin: "; os << this->m_FixedImageNormalizedMin << std::endl; os << indent << "MovingImageNormalizedMin: "; os << this->m_MovingImageNormalizedMin << std::endl; os << indent << "MovingImageTrueMin: "; os << this->m_MovingImageTrueMin << std::endl; os << indent << "MovingImageTrueMax: "; os << this->m_MovingImageTrueMax << std::endl; os << indent << "FixedImageBinSize: "; os << this->m_FixedImageBinSize << std::endl; os << indent << "MovingImageBinSize: "; os << this->m_MovingImageBinSize << std::endl; os << indent << "UseExplicitPDFDerivatives: "; os << this->m_UseExplicitPDFDerivatives << std::endl; os << indent << "ImplicitDerivativesSecondPass: "; os << this->m_ImplicitDerivativesSecondPass << std::endl; if( this->m_JointPDF.IsNotNull() ) { os << indent << "JointPDF: "; os << this->m_JointPDF << std::endl; } if( this->m_JointPDFDerivatives.IsNotNull() ) { os << indent << "JointPDFDerivatives: "; os << this->m_JointPDFDerivatives; } } /** * Initialize */ template <class TFixedImage, class TMovingImage> void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::Initialize(void) throw ( ExceptionObject ) { this->Superclass::Initialize(); this->Superclass::MultiThreadingInitialize(); { /** * Compute the minimum and maximum within the specified mask * region for creating the size of the 2D joint histogram. * Areas outside the masked region should be ignored * in computing the range of intensity values. */ this->m_FixedImageTrueMin = vcl_numeric_limits<typename TFixedImage::PixelType>::max(); this->m_FixedImageTrueMax = vcl_numeric_limits<typename TFixedImage::PixelType>::min(); this->m_MovingImageTrueMin = vcl_numeric_limits<typename TMovingImage::PixelType>::max(); this->m_MovingImageTrueMax = vcl_numeric_limits<typename TMovingImage::PixelType>::min(); // We need to make robust measures only over the requested mask region itk::ImageRegionConstIteratorWithIndex<TFixedImage> fi(this->m_FixedImage, this->m_FixedImage->GetBufferedRegion() ); while( !fi.IsAtEnd() ) { typename TFixedImage::PointType fixedSpacePhysicalPoint; this->m_FixedImage->TransformIndexToPhysicalPoint(fi.GetIndex(), fixedSpacePhysicalPoint); if( this->m_FixedImageMask.IsNull() // A null mask implies entire space is to be used. || this->m_FixedImageMask->IsInside(fixedSpacePhysicalPoint) ) { const typename TFixedImage::PixelType currValue = fi.Get(); m_FixedImageTrueMin = (m_FixedImageTrueMin < currValue) ? m_FixedImageTrueMin : currValue; m_FixedImageTrueMax = (m_FixedImageTrueMax > currValue) ? m_FixedImageTrueMax : currValue; } ++fi; } { itk::ImageRegionConstIteratorWithIndex<TMovingImage> mi(this->m_MovingImage, this->m_MovingImage->GetBufferedRegion() ); while( !mi.IsAtEnd() ) { typename TMovingImage::PointType movingSpacePhysicalPoint; this->m_MovingImage->TransformIndexToPhysicalPoint(mi.GetIndex(), movingSpacePhysicalPoint); if( this->m_MovingImageMask.IsNull() // A null mask implies entire space is to be used. || this->m_MovingImageMask->IsInside(movingSpacePhysicalPoint) ) { const typename TMovingImage::PixelType currValue = mi.Get(); m_MovingImageTrueMin = (m_MovingImageTrueMin < currValue) ? m_MovingImageTrueMin : currValue; m_MovingImageTrueMax = (m_MovingImageTrueMax > currValue) ? m_MovingImageTrueMax : currValue; } ++mi; } } } itkDebugMacro(" FixedImageMin: " << m_FixedImageTrueMin << " FixedImageMax: " << m_FixedImageTrueMax << std::endl); itkDebugMacro(" MovingImageMin: " << m_MovingImageTrueMin << " MovingImageMax: " << m_MovingImageTrueMax << std::endl); /** * Compute binsize for the histograms. * * The binsize for the image intensities needs to be adjusted so that * we can avoid dealing with boundary conditions using the cubic * spline as the Parzen window. We do this by increasing the size * of the bins so that the joint histogram becomes "padded" at the * borders. Because we are changing the binsize, * we also need to shift the minimum by the padded amount in order to * avoid minimum values filling in our padded region. * * Note that there can still be non-zero bin values in the padded region, * it's just that these bins will never be a central bin for the Parzen * window. * */ const int padding = 2; // this will pad by 2 bins m_FixedImageBinSize = ( m_FixedImageTrueMax - m_FixedImageTrueMin ) / static_cast<double>( m_NumberOfHistogramBins - 2 * padding ); m_FixedImageNormalizedMin = m_FixedImageTrueMin / m_FixedImageBinSize - static_cast<double>( padding ); m_MovingImageBinSize = ( m_MovingImageTrueMax - m_MovingImageTrueMin ) / static_cast<double>( m_NumberOfHistogramBins - 2 * padding ); m_MovingImageNormalizedMin = m_MovingImageTrueMin / m_MovingImageBinSize - static_cast<double>( padding ); itkDebugMacro("FixedImageNormalizedMin: " << m_FixedImageNormalizedMin); itkDebugMacro("MovingImageNormalizedMin: " << m_MovingImageNormalizedMin); itkDebugMacro("FixedImageBinSize: " << m_FixedImageBinSize); itkDebugMacro("MovingImageBinSize; " << m_MovingImageBinSize); /** * Allocate memory for the marginal PDF and initialize values * to zero. The marginal PDFs are stored as std::vector. */ if( m_FixedImageMarginalPDF != NULL ) { delete[] m_FixedImageMarginalPDF; } m_FixedImageMarginalPDF = new PDFValueType[m_NumberOfHistogramBins]; if( m_MovingImageMarginalPDF != NULL ) { delete[] m_MovingImageMarginalPDF; } m_MovingImageMarginalPDF = new PDFValueType[m_NumberOfHistogramBins]; /** * Allocate memory for the joint PDF and joint PDF derivatives. * The joint PDF and joint PDF derivatives are store as itk::Image. */ m_JointPDF = JointPDFType::New(); // Instantiate a region, index, size JointPDFRegionType jointPDFRegion; JointPDFIndexType jointPDFIndex; JointPDFSizeType jointPDFSize; JointPDFDerivativesRegionType jointPDFDerivativesRegion; // // Now allocate memory according to the user-selected method. // if( this->m_UseExplicitPDFDerivatives ) { // Deallocate the memory that may have been allocated for // previous runs of the metric. // and by allocating very small the static ones this->m_PRatioArray.SetSize(1, 1); // Not needed if m_UseExplicitPDFDerivatives this->m_MetricDerivative = DerivativeType(1); // Not needed if m_UseExplicitPDFDerivatives this->m_JointPDFDerivatives = JointPDFDerivativesType::New(); JointPDFDerivativesIndexType jointPDFDerivativesIndex; JointPDFDerivativesSizeType jointPDFDerivativesSize; // For the derivatives of the joint PDF define a region starting from // {0,0,0} // with size {m_NumberOfParameters,m_NumberOfHistogramBins, // m_NumberOfHistogramBins}. The dimension represents transform parameters, // fixed image parzen window index and moving image parzen window index, // respectively. jointPDFDerivativesIndex.Fill(0); jointPDFDerivativesSize[0] = this->m_NumberOfParameters; jointPDFDerivativesSize[1] = this->m_NumberOfHistogramBins; jointPDFDerivativesSize[2] = this->m_NumberOfHistogramBins; jointPDFDerivativesRegion.SetIndex(jointPDFDerivativesIndex); jointPDFDerivativesRegion.SetSize(jointPDFDerivativesSize); // Set the regions and allocate m_JointPDFDerivatives->SetRegions(jointPDFDerivativesRegion); m_JointPDFDerivatives->Allocate(); m_JointPDFDerivativesBufferSize = jointPDFDerivativesSize[0] * jointPDFDerivativesSize[1] * jointPDFDerivativesSize[2] * sizeof( JointPDFDerivativesValueType ); } else { // Deallocate the memory that may have been allocated for // previous runs of the metric. this->m_JointPDFDerivatives = NULL; // Not needed if m_UseExplicitPDFDerivatives=false /** Allocate memory for helper array that will contain the pRatios * for each bin of the joint histogram. This is part of the effort * for flattening the computation of the PDF Jacobians. */ this->m_PRatioArray.SetSize(this->m_NumberOfHistogramBins, this->m_NumberOfHistogramBins); this->m_MetricDerivative = DerivativeType( this->GetNumberOfParameters() ); } // For the joint PDF define a region starting from {0,0} // with size {m_NumberOfHistogramBins, m_NumberOfHistogramBins}. // The dimension represents fixed image parzen window index // and moving image parzen window index, respectively. jointPDFIndex.Fill(0); jointPDFSize.Fill(m_NumberOfHistogramBins); jointPDFRegion.SetIndex(jointPDFIndex); jointPDFRegion.SetSize(jointPDFSize); // Set the regions and allocate m_JointPDF->SetRegions(jointPDFRegion); { // By setting these values, the joint histogram physical locations will correspond to intensity values. typename JointPDFType::PointType origin; origin[0] = this->m_FixedImageTrueMin; origin[1] = this->m_MovingImageTrueMin; m_JointPDF->SetOrigin(origin); typename JointPDFType::SpacingType spacing; spacing[0] = this->m_FixedImageBinSize; spacing[1] = this->m_MovingImageBinSize; m_JointPDF->SetSpacing(spacing); } m_JointPDF->Allocate(); m_JointPDFBufferSize = jointPDFSize[0] * jointPDFSize[1] * sizeof( PDFValueType ); /** * Setup the kernels used for the Parzen windows. */ m_CubicBSplineKernel = CubicBSplineFunctionType::New(); m_CubicBSplineDerivativeKernel = CubicBSplineDerivativeFunctionType::New(); /** * Pre-compute the fixed image parzen window index for * each point of the fixed image sample points list. */ this->ComputeFixedImageParzenWindowIndices(this->m_FixedImageSamples); if( m_ThreaderFixedImageMarginalPDF != NULL ) { delete[] m_ThreaderFixedImageMarginalPDF; } // Assumes number of threads doesn't change between calls to Initialize m_ThreaderFixedImageMarginalPDF = new PDFValueType[( this->m_NumberOfThreads - 1 ) * m_NumberOfHistogramBins]; if( m_ThreaderJointPDF != NULL ) { delete[] m_ThreaderJointPDF; } m_ThreaderJointPDF = new typename JointPDFType::Pointer[this->m_NumberOfThreads - 1]; if( m_ThreaderJointPDFStartBin != NULL ) { delete[] m_ThreaderJointPDFStartBin; } m_ThreaderJointPDFStartBin = new int[this->m_NumberOfThreads]; if( m_ThreaderJointPDFEndBin != NULL ) { delete[] m_ThreaderJointPDFEndBin; } m_ThreaderJointPDFEndBin = new int[this->m_NumberOfThreads]; if( m_ThreaderJointPDFSum != NULL ) { delete[] m_ThreaderJointPDFSum; } m_ThreaderJointPDFSum = new double[this->m_NumberOfThreads]; const int binRange = m_NumberOfHistogramBins / this->m_NumberOfThreads; for( ThreadIdType threadID = 0; threadID < this->m_NumberOfThreads - 1; threadID++ ) { m_ThreaderJointPDF[threadID] = JointPDFType::New(); m_ThreaderJointPDF[threadID]->SetRegions(jointPDFRegion); m_ThreaderJointPDF[threadID]->Allocate(); m_ThreaderJointPDFStartBin[threadID] = threadID * binRange; m_ThreaderJointPDFEndBin[threadID] = ( threadID + 1 ) * binRange - 1; } m_ThreaderJointPDFStartBin[this->m_NumberOfThreads - 1] = ( this->m_NumberOfThreads - 1 ) * binRange; m_ThreaderJointPDFEndBin[this->m_NumberOfThreads - 1] = m_NumberOfHistogramBins - 1; // Release memory of arrays that may have been used for // previous executions of this metric with different settings // of the memory caching flags. if( m_ThreaderJointPDFDerivatives != NULL ) { delete[] m_ThreaderJointPDFDerivatives; } m_ThreaderJointPDFDerivatives = NULL; if( m_ThreaderMetricDerivative != NULL ) { delete[] m_ThreaderMetricDerivative; } m_ThreaderMetricDerivative = NULL; if( this->m_UseExplicitPDFDerivatives ) { m_ThreaderJointPDFDerivatives = new typename JointPDFDerivativesType::Pointer[this->m_NumberOfThreads - 1]; for( ThreadIdType threadID = 0; threadID < this->m_NumberOfThreads - 1; threadID++ ) { m_ThreaderJointPDFDerivatives[threadID] = JointPDFDerivativesType::New(); m_ThreaderJointPDFDerivatives[threadID]->SetRegions( jointPDFDerivativesRegion); m_ThreaderJointPDFDerivatives[threadID]->Allocate(); } } else { m_ThreaderMetricDerivative = new DerivativeType[this->m_NumberOfThreads - 1]; for( ThreadIdType threadID = 0; threadID < this->m_NumberOfThreads - 1; threadID++ ) { this->m_ThreaderMetricDerivative[threadID] = DerivativeType( this->GetNumberOfParameters() ); } } } /** * From the pre-computed samples, now * fill in the parzen window index locations */ template <class TFixedImage, class TMovingImage> void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::ComputeFixedImageParzenWindowIndices( FixedImageSampleContainer & samples) { const typename FixedImageSampleContainer::const_iterator end = samples.end(); for( typename FixedImageSampleContainer::iterator iter = samples.begin(); iter != end; ++iter ) { // Determine parzen window arguments (see eqn 6 of Mattes paper [2]). const double windowTerm = static_cast<double>( ( *iter ).value ) / m_FixedImageBinSize - m_FixedImageNormalizedMin; OffsetValueType pindex = static_cast<OffsetValueType>( windowTerm ); // Make sure the extreme values are in valid bins if( pindex < 2 ) { pindex = 2; } else { const OffsetValueType nindex = static_cast<OffsetValueType>( this->m_NumberOfHistogramBins ) - 3; if( pindex > nindex ) { pindex = nindex; } } ( *iter ).valueIndex = pindex; } } template <class TFixedImage, class TMovingImage> inline void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::GetValueThreadPreProcess(ThreadIdType threadID, bool withinSampleThread) const { this->Superclass::GetValueThreadPreProcess(threadID, withinSampleThread); if( threadID > 0 ) { memset(m_ThreaderJointPDF[threadID - 1]->GetBufferPointer(), 0, m_JointPDFBufferSize); memset( &( m_ThreaderFixedImageMarginalPDF[( threadID - 1 ) * m_NumberOfHistogramBins] ), 0, m_NumberOfHistogramBins * sizeof( PDFValueType ) ); } else { // zero-th thread uses the variables directly memset(m_JointPDF->GetBufferPointer(), 0, m_JointPDFBufferSize); memset( m_FixedImageMarginalPDF, 0, m_NumberOfHistogramBins * sizeof( PDFValueType ) ); } } template <class TFixedImage, class TMovingImage> inline bool MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::GetValueThreadProcessSample(ThreadIdType threadID, SizeValueType fixedImageSample, const MovingImagePointType & itkNotUsed(mappedPoint), double movingImageValue) const { /** * Compute this sample's contribution to the marginal and * joint distributions. * */ if( movingImageValue < m_MovingImageTrueMin ) { return false; } else if( movingImageValue > m_MovingImageTrueMax ) { return false; } // Determine parzen window arguments (see eqn 6 of Mattes paper [2]). const double movingImageParzenWindowTerm = movingImageValue / m_MovingImageBinSize - m_MovingImageNormalizedMin; // Same as floor OffsetValueType movingImageParzenWindowIndex = static_cast<OffsetValueType>( movingImageParzenWindowTerm ); if( movingImageParzenWindowIndex < 2 ) { movingImageParzenWindowIndex = 2; } else { const OffsetValueType nindex = static_cast<OffsetValueType>( this->m_NumberOfHistogramBins ) - 3; if( movingImageParzenWindowIndex > nindex ) { movingImageParzenWindowIndex = nindex; } } const unsigned int fixedImageParzenWindowIndex = this->m_FixedImageSamples[fixedImageSample].valueIndex; if( threadID > 0 ) { m_ThreaderFixedImageMarginalPDF[( threadID - 1 ) * m_NumberOfHistogramBins + fixedImageParzenWindowIndex] += 1; } else { m_FixedImageMarginalPDF[fixedImageParzenWindowIndex] += 1; } // Pointer to affected bin to be updated JointPDFValueType *pdfPtr; if( threadID > 0 ) { pdfPtr = m_ThreaderJointPDF[threadID - 1]->GetBufferPointer() + ( fixedImageParzenWindowIndex * m_ThreaderJointPDF[threadID - 1] ->GetOffsetTable()[1] ); } else { pdfPtr = m_JointPDF->GetBufferPointer() + ( fixedImageParzenWindowIndex * m_JointPDF->GetOffsetTable()[1] ); } // Move the pointer to the first affected bin int pdfMovingIndex = static_cast<int>( movingImageParzenWindowIndex ) - 1; pdfPtr += pdfMovingIndex; const int pdfMovingIndexMax = static_cast<int>( movingImageParzenWindowIndex ) + 2; double movingImageParzenWindowArg = static_cast<double>( pdfMovingIndex ) - movingImageParzenWindowTerm; while( pdfMovingIndex <= pdfMovingIndexMax ) { *( pdfPtr++ ) += static_cast<PDFValueType>( m_CubicBSplineKernel ->Evaluate( movingImageParzenWindowArg) ); movingImageParzenWindowArg += 1; ++pdfMovingIndex; } return true; } template <class TFixedImage, class TMovingImage> inline void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::GetValueThreadPostProcess( ThreadIdType threadID, bool itkNotUsed(withinSampleThread) ) const { const int maxI = m_NumberOfHistogramBins * ( m_ThreaderJointPDFEndBin[threadID] - m_ThreaderJointPDFStartBin[threadID] + 1 ); JointPDFValueType * const pdfPtrStart = m_JointPDF->GetBufferPointer() + ( m_ThreaderJointPDFStartBin[threadID] * m_JointPDF->GetOffsetTable()[1] ); const unsigned int tPdfPtrOffset = ( m_ThreaderJointPDFStartBin[threadID] * m_JointPDF->GetOffsetTable()[1] ); for( unsigned int t = 0; t < this->m_NumberOfThreads - 1; t++ ) { JointPDFValueType * pdfPtr = pdfPtrStart; JointPDFValueType const * tPdfPtr = m_ThreaderJointPDF[t]->GetBufferPointer() + tPdfPtrOffset; JointPDFValueType const * const tPdfPtrEnd = tPdfPtr + maxI; // for(i=0; i < maxI; i++) while( tPdfPtr < tPdfPtrEnd ) { *( pdfPtr++ ) += *( tPdfPtr++ ); } for( int i = m_ThreaderJointPDFStartBin[threadID]; i <= m_ThreaderJointPDFEndBin[threadID]; i++ ) { m_FixedImageMarginalPDF[i] += m_ThreaderFixedImageMarginalPDF[ ( t * m_NumberOfHistogramBins ) + i]; } } double jointPDFSum = 0.0; JointPDFValueType const * pdfPtr = pdfPtrStart; for( int i = 0; i < maxI; i++ ) { jointPDFSum += *( pdfPtr++ ); } if( threadID > 0 ) { m_ThreaderJointPDFSum[threadID - 1] = jointPDFSum; } else { m_JointPDFSum = jointPDFSum; } } template <class TFixedImage, class TMovingImage> typename MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::MeasureType MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::GetValue(const ParametersType & parameters) const { // Set up the parameters in the transform this->m_Transform->SetParameters(parameters); this->m_Parameters = parameters; // MUST BE CALLED TO INITIATE PROCESSING this->GetValueMultiThreadedInitiate(); // MUST BE CALLED TO INITIATE PROCESSING this->GetValueMultiThreadedPostProcessInitiate(); for( ThreadIdType threadID = 0; threadID < this->m_NumberOfThreads - 1; threadID++ ) { m_JointPDFSum += m_ThreaderJointPDFSum[threadID]; } if( m_JointPDFSum == 0.0 ) { itkExceptionMacro("Joint PDF summed to zero\n" << m_JointPDF ); } memset( m_MovingImageMarginalPDF, 0, m_NumberOfHistogramBins * sizeof( PDFValueType ) ); const double nFactor = 1.0 / m_JointPDFSum; JointPDFValueType *pdfPtr = m_JointPDF->GetBufferPointer(); double fixedPDFSum = 0.0; for( unsigned int i = 0; i < m_NumberOfHistogramBins; i++ ) { fixedPDFSum += m_FixedImageMarginalPDF[i]; PDFValueType * movingMarginalPtr = m_MovingImageMarginalPDF; for( unsigned int j = 0; j < m_NumberOfHistogramBins; j++ ) { *( pdfPtr ) *= nFactor; *( movingMarginalPtr++ ) += *( pdfPtr++ ); } } if( this->m_NumberOfPixelsCounted < this->m_NumberOfFixedImageSamples / 16 ) { itkExceptionMacro("Too many samples map outside moving image buffer: " << this->m_NumberOfPixelsCounted << " / " << this->m_NumberOfFixedImageSamples << std::endl); } // Normalize the fixed image marginal PDF if( fixedPDFSum == 0.0 ) { itkExceptionMacro("Fixed image marginal PDF summed to zero"); } for( unsigned int bin = 0; bin < m_NumberOfHistogramBins; bin++ ) { m_FixedImageMarginalPDF[bin] /= fixedPDFSum; } /** * Compute the metric by double summation over histogram. */ // Setup pointer to point to the first bin JointPDFValueType *jointPDFPtr = m_JointPDF->GetBufferPointer(); double sum = 0.0; for( unsigned int fixedIndex = 0; fixedIndex < m_NumberOfHistogramBins; ++fixedIndex ) { const double fixedImagePDFValue = m_FixedImageMarginalPDF[fixedIndex]; for( unsigned int movingIndex = 0; movingIndex < m_NumberOfHistogramBins; ++movingIndex, jointPDFPtr++ ) { const double movingImagePDFValue = m_MovingImageMarginalPDF[movingIndex]; const double jointPDFValue = *( jointPDFPtr ); // check for non-zero bin contribution if( jointPDFValue > 1e-16 && movingImagePDFValue > 1e-16 ) { const double pRatio = vcl_log(jointPDFValue / movingImagePDFValue); if( fixedImagePDFValue > 1e-16 ) { sum += jointPDFValue * ( pRatio - vcl_log(fixedImagePDFValue) ); } } // end if-block to check non-zero bin contribution } // end for-loop over moving index } // end for-loop over fixed index return static_cast<MeasureType>( -1.0 * sum ); } template <class TFixedImage, class TMovingImage> inline void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::GetValueAndDerivativeThreadPreProcess( ThreadIdType threadID, bool itkNotUsed(withinSampleThread) ) const { if( threadID > 0 ) { memset(m_ThreaderJointPDF[threadID - 1]->GetBufferPointer(), 0, m_JointPDFBufferSize); memset( &( m_ThreaderFixedImageMarginalPDF[( threadID - 1 ) * m_NumberOfHistogramBins] ), 0, m_NumberOfHistogramBins * sizeof( PDFValueType ) ); if( this->m_UseExplicitPDFDerivatives ) { memset(m_ThreaderJointPDFDerivatives[threadID - 1]->GetBufferPointer(), 0, m_JointPDFDerivativesBufferSize); } } else { memset(m_JointPDF->GetBufferPointer(), 0, m_JointPDFBufferSize); memset( m_FixedImageMarginalPDF, 0, m_NumberOfHistogramBins * sizeof( PDFValueType ) ); if( this->m_UseExplicitPDFDerivatives ) { memset(m_JointPDFDerivatives->GetBufferPointer(), 0, m_JointPDFDerivativesBufferSize); } } } template <class TFixedImage, class TMovingImage> inline bool MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::GetValueAndDerivativeThreadProcessSample(ThreadIdType threadID, SizeValueType fixedImageSample, const MovingImagePointType & itkNotUsed(mappedPoint), double movingImageValue, const ImageDerivativesType & movingImageGradientValue) const { /** * Compute this sample's contribution to the marginal * and joint distributions. * */ if( movingImageValue < m_MovingImageTrueMin ) { return false; } else if( movingImageValue > m_MovingImageTrueMax ) { return false; } unsigned int fixedImageParzenWindowIndex = this->m_FixedImageSamples[fixedImageSample].valueIndex; // Determine parzen window arguments (see eqn 6 of Mattes paper [2]). double movingImageParzenWindowTerm = movingImageValue / m_MovingImageBinSize - m_MovingImageNormalizedMin; OffsetValueType movingImageParzenWindowIndex = static_cast<OffsetValueType>( movingImageParzenWindowTerm ); // Make sure the extreme values are in valid bins if( movingImageParzenWindowIndex < 2 ) { movingImageParzenWindowIndex = 2; } else { const OffsetValueType nindex = static_cast<OffsetValueType>( this->m_NumberOfHistogramBins ) - 3; if( movingImageParzenWindowIndex > nindex ) { movingImageParzenWindowIndex = nindex; } } // Since a zero-order BSpline (box car) kernel is used for // the fixed image marginal pdf, we need only increment the // fixedImageParzenWindowIndex by value of 1.0. if( threadID > 0 ) { ++m_ThreaderFixedImageMarginalPDF[( threadID - 1 ) * m_NumberOfHistogramBins + fixedImageParzenWindowIndex]; } else { ++m_FixedImageMarginalPDF[fixedImageParzenWindowIndex]; } /** * The region of support of the parzen window determines which bins * of the joint PDF are effected by the pair of image values. * Since we are using a cubic spline for the moving image parzen * window, four bins are effected. The fixed image parzen window is * a zero-order spline (box car) and thus effects only one bin. * * The PDF is arranged so that moving image bins corresponds to the * zero-th (column) dimension and the fixed image bins corresponds * to the first (row) dimension. * */ // Pointer to affected bin to be updated JointPDFValueType *pdfPtr; if( threadID > 0 ) { pdfPtr = m_ThreaderJointPDF[threadID - 1] ->GetBufferPointer() + ( fixedImageParzenWindowIndex * m_NumberOfHistogramBins ); } else { pdfPtr = m_JointPDF->GetBufferPointer() + ( fixedImageParzenWindowIndex * m_NumberOfHistogramBins ); } // Move the pointer to the fist affected bin int pdfMovingIndex = static_cast<int>( movingImageParzenWindowIndex ) - 1; pdfPtr += pdfMovingIndex; const int pdfMovingIndexMax = static_cast<int>( movingImageParzenWindowIndex ) + 2; double movingImageParzenWindowArg = static_cast<double>( pdfMovingIndex ) - static_cast<double>( movingImageParzenWindowTerm ); while( pdfMovingIndex <= pdfMovingIndexMax ) { *( pdfPtr++ ) += static_cast<PDFValueType>( m_CubicBSplineKernel ->Evaluate( movingImageParzenWindowArg) ); if( this->m_UseExplicitPDFDerivatives || this->m_ImplicitDerivativesSecondPass ) { // Compute the cubicBSplineDerivative for later repeated use. const double cubicBSplineDerivativeValue = m_CubicBSplineDerivativeKernel->Evaluate(movingImageParzenWindowArg); // Compute PDF derivative contribution. this->ComputePDFDerivatives(threadID, fixedImageSample, pdfMovingIndex, movingImageGradientValue, cubicBSplineDerivativeValue); } movingImageParzenWindowArg += 1; ++pdfMovingIndex; } return true; } template <class TFixedImage, class TMovingImage> inline void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::GetValueAndDerivativeThreadPostProcess(ThreadIdType threadID, bool withinSampleThread) const { this->GetValueThreadPostProcess(threadID, withinSampleThread); if( this->m_UseExplicitPDFDerivatives ) { const unsigned int rowSize = this->m_NumberOfParameters * m_NumberOfHistogramBins; const unsigned int maxI = rowSize * ( m_ThreaderJointPDFEndBin[threadID] - m_ThreaderJointPDFStartBin[threadID] + 1 ); JointPDFDerivativesValueType *const pdfDPtrStart = m_JointPDFDerivatives->GetBufferPointer() + ( m_ThreaderJointPDFStartBin[threadID] * rowSize ); const unsigned int tPdfDPtrOffset = m_ThreaderJointPDFStartBin[threadID] * rowSize; for( unsigned int t = 0; t < this->m_NumberOfThreads - 1; t++ ) { JointPDFDerivativesValueType * pdfDPtr = pdfDPtrStart; JointPDFDerivativesValueType const *tPdfDPtr = m_ThreaderJointPDFDerivatives[t]->GetBufferPointer() + tPdfDPtrOffset; JointPDFDerivativesValueType const * const tPdfDPtrEnd = tPdfDPtr + maxI; // for(i = 0; i < maxI; i++) while( tPdfDPtr < tPdfDPtrEnd ) { *( pdfDPtr++ ) += *( tPdfDPtr++ ); } } const double nFactor = 1.0 / ( m_MovingImageBinSize * this->m_NumberOfPixelsCounted ); JointPDFDerivativesValueType * pdfDPtr = pdfDPtrStart; JointPDFDerivativesValueType const * const tPdfDPtrEnd = pdfDPtrStart + maxI; // for(int i = 0; i < maxI; i++) while( pdfDPtr < tPdfDPtrEnd ) { *( pdfDPtr++ ) *= nFactor; } } } /** * Get the both Value and Derivative Measure */ template <class TFixedImage, class TMovingImage> void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::GetValueAndDerivative(const ParametersType & parameters, MeasureType & value, DerivativeType & derivative) const { // Set output values to zero value = NumericTraits<MeasureType>::Zero; if( this->m_UseExplicitPDFDerivatives ) { // Set output values to zero if( derivative.GetSize() != this->m_NumberOfParameters ) { derivative = DerivativeType(this->m_NumberOfParameters); } memset( derivative.data_block(), 0, this->m_NumberOfParameters * sizeof( double ) ); } else { this->m_PRatioArray.Fill(0.0); this->m_MetricDerivative.Fill(NumericTraits<MeasureType>::Zero); for( ThreadIdType threadID = 0; threadID < this->m_NumberOfThreads - 1; threadID++ ) { this->m_ThreaderMetricDerivative[threadID].Fill(NumericTraits<MeasureType>::Zero); } this->m_ImplicitDerivativesSecondPass = false; } // Set up the parameters in the transform this->m_Transform->SetParameters(parameters); this->m_Parameters = parameters; // MUST BE CALLED TO INITIATE PROCESSING ON SAMPLES this->GetValueAndDerivativeMultiThreadedInitiate(); // CALL IF DOING THREADED POST PROCESSING this->GetValueAndDerivativeMultiThreadedPostProcessInitiate(); for( ThreadIdType threadID = 0; threadID < this->m_NumberOfThreads - 1; threadID++ ) { m_JointPDFSum += m_ThreaderJointPDFSum[threadID]; } if( m_JointPDFSum == 0.0 ) { itkExceptionMacro("Joint PDF summed to zero"); } memset( m_MovingImageMarginalPDF, 0, m_NumberOfHistogramBins * sizeof( PDFValueType ) ); double fixedPDFSum = 0.0; const double normalizationFactor = 1.0 / m_JointPDFSum; JointPDFValueType *pdfPtr = m_JointPDF->GetBufferPointer(); for( unsigned int i = 0; i < m_NumberOfHistogramBins; i++ ) { fixedPDFSum += m_FixedImageMarginalPDF[i]; PDFValueType * movingMarginalPtr = m_MovingImageMarginalPDF; for( unsigned int j = 0; j < m_NumberOfHistogramBins; j++ ) { *( pdfPtr ) *= normalizationFactor; *( movingMarginalPtr++ ) += *( pdfPtr++ ); } } if( this->m_NumberOfPixelsCounted < this->m_NumberOfFixedImageSamples / 16 ) { itkExceptionMacro("Too many samples map outside moving image buffer: " << this->m_NumberOfPixelsCounted << " / " << this->m_NumberOfFixedImageSamples << std::endl); } // Normalize the fixed image marginal PDF if( fixedPDFSum == 0.0 ) { itkExceptionMacro("Fixed image marginal PDF summed to zero"); } for( unsigned int bin = 0; bin < m_NumberOfHistogramBins; bin++ ) { m_FixedImageMarginalPDF[bin] /= fixedPDFSum; } /** * Compute the metric by double summation over histogram. */ // Setup pointer to point to the first bin JointPDFValueType *jointPDFPtr = m_JointPDF->GetBufferPointer(); // Initialize sum to zero double sum = 0.0; const double nFactor = 1.0 / ( m_MovingImageBinSize * this->m_NumberOfPixelsCounted ); for( unsigned int fixedIndex = 0; fixedIndex < m_NumberOfHistogramBins; ++fixedIndex ) { const double fixedImagePDFValue = m_FixedImageMarginalPDF[fixedIndex]; for( unsigned int movingIndex = 0; movingIndex < m_NumberOfHistogramBins; ++movingIndex, jointPDFPtr++ ) { const double movingImagePDFValue = m_MovingImageMarginalPDF[movingIndex]; const double jointPDFValue = *( jointPDFPtr ); // check for non-zero bin contribution if( jointPDFValue > 1e-16 && movingImagePDFValue > 1e-16 ) { const double pRatio = vcl_log(jointPDFValue / movingImagePDFValue); if( fixedImagePDFValue > 1e-16 ) { sum += jointPDFValue * ( pRatio - vcl_log(fixedImagePDFValue) ); } if( this->m_UseExplicitPDFDerivatives ) { // move joint pdf derivative pointer to the right position JointPDFValueType const * derivPtr = m_JointPDFDerivatives->GetBufferPointer() + ( fixedIndex * m_JointPDFDerivatives->GetOffsetTable()[2] ) + ( movingIndex * m_JointPDFDerivatives->GetOffsetTable()[1] ); for( unsigned int parameter = 0; parameter < this->m_NumberOfParameters; ++parameter, derivPtr++ ) { // Ref: eqn 23 of Thevenaz & Unser paper [3] derivative[parameter] -= ( *derivPtr ) * pRatio; } // end for-loop over parameters } else { this->m_PRatioArray[fixedIndex][movingIndex] = pRatio * nFactor; } } // end if-block to check non-zero bin contribution } // end for-loop over moving index } // end for-loop over fixed index if( !( this->m_UseExplicitPDFDerivatives ) ) { // Second pass: This one is done for accumulating the contributions // to the derivative array. // this->m_ImplicitDerivativesSecondPass = true; // // MUST BE CALLED TO INITIATE PROCESSING ON SAMPLES this->GetValueAndDerivativeMultiThreadedInitiate(); // CALL IF DOING THREADED POST PROCESSING this->GetValueAndDerivativeMultiThreadedPostProcessInitiate(); // Consolidate the contributions from each one of the threads to the total // derivative. for( unsigned int t = 0; t < this->m_NumberOfThreads - 1; t++ ) { DerivativeType const * const source = &( this->m_ThreaderMetricDerivative[t] ); for( unsigned int pp = 0; pp < this->m_NumberOfParameters; pp++ ) { this->m_MetricDerivative[pp] += ( *source )[pp]; } } derivative = this->m_MetricDerivative; } value = static_cast<MeasureType>( -1.0 * sum ); } /** * Get the match measure derivative */ template <class TFixedImage, class TMovingImage> void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::GetDerivative(const ParametersType & parameters, DerivativeType & derivative) const { MeasureType value; // call the combined version this->GetValueAndDerivative(parameters, value, derivative); } /** * Compute PDF derivatives contribution for each parameter */ template <class TFixedImage, class TMovingImage> void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::ComputePDFDerivatives(ThreadIdType threadID, unsigned int sampleNumber, int pdfMovingIndex, const ImageDerivativesType & movingImageGradientValue, double cubicBSplineDerivativeValue) const { // Update bins in the PDF derivatives for the current intensity pair // Could pre-compute JointPDFDerivativesValueType *derivPtr; double precomputedWeight = 0.0; const int pdfFixedIndex = this->m_FixedImageSamples[sampleNumber].valueIndex; DerivativeType *derivativeHelperArray = NULL; if( this->m_UseExplicitPDFDerivatives ) { if( threadID > 0 ) { derivPtr = m_ThreaderJointPDFDerivatives[threadID - 1]->GetBufferPointer() + ( pdfFixedIndex * m_JointPDFDerivatives->GetOffsetTable()[2] ) + ( pdfMovingIndex * m_JointPDFDerivatives->GetOffsetTable()[1] ); } else { derivPtr = m_JointPDFDerivatives->GetBufferPointer() + ( pdfFixedIndex * m_JointPDFDerivatives->GetOffsetTable()[2] ) + ( pdfMovingIndex * m_JointPDFDerivatives->GetOffsetTable()[1] ); } } else { derivPtr = 0; // Recover the precomputed weight for this specific PDF bin precomputedWeight = this->m_PRatioArray[pdfFixedIndex][pdfMovingIndex]; if( threadID > 0 ) { derivativeHelperArray = &( this->m_ThreaderMetricDerivative[threadID - 1] ); } else { derivativeHelperArray = &( this->m_MetricDerivative ); } } if( !this->m_TransformIsBSpline ) { /** * Generic version which works for all transforms. */ // Compute the transform Jacobian. // Should pre-compute typedef typename TransformType::JacobianType JacobianType; // Need to use one of the threader transforms if we're // not in thread 0. // // Use a raw pointer here to avoid the overhead of smart pointers. // For instance, Register and UnRegister have mutex locks around // the reference counts. TransformType *transform; if( threadID > 0 ) { transform = this->m_ThreaderTransform[threadID - 1]; } else { transform = this->m_Transform; } JacobianType jacobian; transform->ComputeJacobianWithRespectToParameters( this->m_FixedImageSamples[sampleNumber].point, jacobian); for( unsigned int mu = 0; mu < this->m_NumberOfParameters; mu++ ) { double innerProduct = 0.0; for( unsigned int dim = 0; dim < Superclass::FixedImageDimension; dim++ ) { innerProduct += jacobian[dim][mu] * movingImageGradientValue[dim]; } const double derivativeContribution = innerProduct * cubicBSplineDerivativeValue; if( this->m_UseExplicitPDFDerivatives ) { *( derivPtr ) -= derivativeContribution; ++derivPtr; } else { ( *derivativeHelperArray )[mu] += precomputedWeight * derivativeContribution; } } } else { const WeightsValueType *weights = NULL; const IndexValueType * indices = NULL; BSplineTransformWeightsType * weightsHelper = NULL; BSplineTransformIndexArrayType *indicesHelper = NULL; if( this->m_UseCachingOfBSplineWeights ) { // // If the transform is of type BSplineTransform, we can obtain // a speed up by only processing the affected parameters. Note that // these pointers are just pointing to pre-allocated rows of the caching // arrays. There is therefore, no need to free this memory. // weights = this->m_BSplineTransformWeightsArray[sampleNumber]; indices = this->m_BSplineTransformIndicesArray[sampleNumber]; } else { if( threadID > 0 ) { weightsHelper = &( this->m_ThreaderBSplineTransformWeights[threadID - 1] ); indicesHelper = &( this->m_ThreaderBSplineTransformIndices[threadID - 1] ); } else { weightsHelper = &( this->m_BSplineTransformWeights ); indicesHelper = &( this->m_BSplineTransformIndices ); } /** Get Jacobian at a point. A very specialized function just for BSplines */ this->m_BSplineTransform->ComputeJacobianFromBSplineWeightsWithRespectToPosition( this->m_FixedImageSamples[sampleNumber].point, *weightsHelper, *indicesHelper); } for( unsigned int dim = 0; dim < Superclass::FixedImageDimension; dim++ ) { for( unsigned int mu = 0; mu < this->m_NumBSplineWeights; mu++ ) { /* The array weights contains the Jacobian values in a 1-D array * (because for each parameter the Jacobian is non-zero in only 1 of the * possible dimensions) which is multiplied by the moving image * gradient. */ double innerProduct; int parameterIndex; if( this->m_UseCachingOfBSplineWeights ) { innerProduct = movingImageGradientValue[dim] * weights[mu]; parameterIndex = indices[mu] + this->m_BSplineParametersOffset[dim]; } else { innerProduct = movingImageGradientValue[dim] * ( *weightsHelper )[mu]; parameterIndex = ( *indicesHelper )[mu] + this->m_BSplineParametersOffset[dim]; } const double derivativeContribution = innerProduct * cubicBSplineDerivativeValue; if( this->m_UseExplicitPDFDerivatives ) { JointPDFValueType * const ptr = derivPtr + parameterIndex; *( ptr ) -= derivativeContribution; } else { ( *derivativeHelperArray )[parameterIndex] += precomputedWeight * derivativeContribution; } } // end mu for loop } // end dim for loop } // end if-block transform is BSpline } } // end namespace itk #endif
34.216981
121
0.672775
CapeDrew
12247c340acb0ba8f2462878f262227e9a4abad3
5,427
cpp
C++
libraries/C6502Cpu/CVanguardGame.cpp
porchio/arduino-mega-ict
dcc4b37cdbae2966d5736589bea776bf286df9ee
[ "BSD-2-Clause" ]
19
2016-01-14T10:54:07.000Z
2021-06-29T17:47:54.000Z
libraries/C6502Cpu/CVanguardGame.cpp
LabRat3K/arduino-mega-ict
b5f46ee41fc088c4ef80e3dcfb045685e6b89e94
[ "BSD-2-Clause" ]
11
2016-01-20T23:30:34.000Z
2021-05-22T18:06:55.000Z
libraries/C6502Cpu/CVanguardGame.cpp
LabRat3K/arduino-mega-ict
b5f46ee41fc088c4ef80e3dcfb045685e6b89e94
[ "BSD-2-Clause" ]
16
2016-01-03T18:29:09.000Z
2021-08-18T14:09:36.000Z
// // Copyright (c) 2020, Paul R. Swan // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR // TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #include "CVanguardGame.h" // 01 02 04 08 10 20 40 80 100 200 400 800 static const UINT16 s_romData2n_1[] = {0x6f,0xa9,0x9d,0x10,0x8e,0x8a,0x02,0x02,0xba,0x02,0x60,0xc9}; // 1 static const UINT16 s_romData2n_2[] = {0xc9,0x06,0x60,0x34,0x00,0x48,0x32,0x85,0x38,0x68,0x54,0xc9}; // 2 static const UINT16 s_romData2n_3[] = {0x29,0x03,0xbd,0x12,0x10,0x60,0xb0,0x90,0x51,0x51,0x51,0x4c}; // 3 static const UINT16 s_romData2n_4[] = {0x48,0x8a,0x98,0xb5,0xe6,0x50,0x20,0x68,0x5f,0xed,0x48,0x3b}; // 4 static const UINT16 s_romData2n_5[] = {0x7c,0xc2,0x86,0x02,0x62,0x08,0x0c,0x9e,0xf8,0x00,0x88,0x38}; // 5 static const UINT16 s_romData2n_6[] = {0x19,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x32}; // 6 static const UINT16 s_romData2n_7[] = {0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0xd4}; // 7 static const UINT16 s_romData2n_8[] = {0x01,0xd1,0xd1,0xd1,0xd7,0xd2,0xc9,0x30,0xc4,0x01,0x20,0x14}; // 8 // // Centuri Set 1 // static const ROM_REGION s_romRegionCenturiSet1[] PROGMEM = { // {NO_BANK_SWITCH, 0x4000, 0x1000, s_romData2n_1, 0x6a29e354, " 1 "}, // 1 {NO_BANK_SWITCH, 0x5000, 0x1000, s_romData2n_2, 0x302bba54, " 2 "}, // 2 {NO_BANK_SWITCH, 0x6000, 0x1000, s_romData2n_3, 0x424755f6, " 3 "}, // 3 {NO_BANK_SWITCH, 0x7000, 0x1000, s_romData2n_4, 0x770f9714, " 4 "}, // 4CN {NO_BANK_SWITCH, 0x8000, 0x1000, s_romData2n_5, 0x3445cba6, " 5 "}, // 5C {NO_BANK_SWITCH, 0x9000, 0x1000, s_romData2n_6, 0x0d5b47d0, " 6 "}, // 6 {NO_BANK_SWITCH, 0xA000, 0x1000, s_romData2n_7, 0x8549b8f8, " 7 "}, // 7 {NO_BANK_SWITCH, 0xB000, 0x1000, s_romData2n_8, 0x4b825bc8, " 8 "}, // 8CS {NO_BANK_SWITCH, 0xF000, 0x1000, s_romData2n_5, 0x3445cba6, " 5 "}, // 5C, mirror {0} }; // end of list // // German Set 1 // static const ROM_REGION s_romRegionGermanSet1[] PROGMEM = { // {NO_BANK_SWITCH, 0x4000, 0x1000, s_romData2n_1, 0x6a29e354, " 1 "}, // 1 {NO_BANK_SWITCH, 0x5000, 0x1000, s_romData2n_2, 0x302bba54, " 2 "}, // 2 {NO_BANK_SWITCH, 0x6000, 0x1000, s_romData2n_3, 0x424755f6, " 3 "}, // 3 {NO_BANK_SWITCH, 0x7000, 0x1000, s_romData2n_4, 0x4a82306a, " 4 "}, // 4G {NO_BANK_SWITCH, 0x8000, 0x1000, s_romData2n_5, 0xfde157d0, " 5 "}, // 5 {NO_BANK_SWITCH, 0x9000, 0x1000, s_romData2n_6, 0x0d5b47d0, " 6 "}, // 6 {NO_BANK_SWITCH, 0xA000, 0x1000, s_romData2n_7, 0x8549b8f8, " 7 "}, // 7 {NO_BANK_SWITCH, 0xB000, 0x1000, s_romData2n_8, 0xabe5fa3f, " 8 "}, // 8S {NO_BANK_SWITCH, 0xF000, 0x1000, s_romData2n_5, 0xfde157d0, " 5 "}, // 5, mirror {0} }; // end of list IGame* CVanguardGame::createInstanceCenturiSet1( ) { return (new CVanguardGame(s_romRegionCenturiSet1)); } IGame* CVanguardGame::createInstanceGermanSet1( ) { return (new CVanguardGame(s_romRegionGermanSet1)); } CVanguardGame::CVanguardGame( const ROM_REGION *romRegion ) : CVanguardBaseGame( romRegion ) { }
60.3
141
0.563663
porchio
1224e1747e7a6831bef92ba65de97dbd347696c1
14,568
hpp
C++
include/cps/Socket.hpp
clusterpoint/cpp-client-api
605825f0d46678c1ebdabb006bc0c138e4b0b7f3
[ "MIT" ]
1
2015-09-22T10:32:36.000Z
2015-09-22T10:32:36.000Z
include/cps/Socket.hpp
clusterpoint/cpp-client-api
605825f0d46678c1ebdabb006bc0c138e4b0b7f3
[ "MIT" ]
null
null
null
include/cps/Socket.hpp
clusterpoint/cpp-client-api
605825f0d46678c1ebdabb006bc0c138e4b0b7f3
[ "MIT" ]
null
null
null
#ifndef CPS_SOCKET_HPP_ #define CPS_SOCKET_HPP_ #include <string> #include <vector> #include "Exception.hpp" #include "Utils.hpp" #include "boost/bind.hpp" #include "boost/lambda/lambda.hpp" namespace CPS { #ifndef USE_HEADER_ONLY_ASIO #include "boost/asio.hpp" using namespace boost; #else #define ASIO_DISABLE_THREADS // To disable linking errors #include "asio.hpp" #endif class AbstractSocket { public: AbstractSocket(asio::io_service &io_service) : io_service(io_service), deadline(io_service), connected(false) { connectTimeout = 5; sendTimeout = 30; recieveTimeout = 60; // No deadline is required until the first socket operation is started. We // set the deadline to positive infinity so that the actor takes no action // until a specific deadline is set. deadline.expires_at(boost::posix_time::pos_infin); // Start the persistent actor that checks for deadline expiry. check_deadline(); } virtual ~AbstractSocket() { } virtual void connect(const std::string &host, int port) = 0; virtual std::vector<unsigned char> send(const std::string &data) = 0; virtual std::vector<unsigned char> read() = 0; bool isConnected() { return connected; } void check_deadline() { // Check whether the deadline has passed. We compare the deadline against // the current time since a new asynchronous operation may have moved the // deadline before this actor had a chance to run. if (deadline.expires_at() <= asio::deadline_timer::traits_type::now()) { // The deadline has passed. The socket is closed so that any outstanding // asynchronous operations are cancelled. This allows the blocked // connect(), read_line() or write_line() functions to return. error = asio::error::timed_out; handle_timer_expiration(); // There is no longer an active deadline. The expire is set to positive // infinity so that the actor takes no action until a new deadline is set. deadline.expires_at(boost::posix_time::pos_infin); } // Put the actor back::asio to sleep. deadline.async_wait(boost::bind(&AbstractSocket::check_deadline, this)); } virtual void handle_timer_expiration() { // Nothing to do here.. Should be overloaded in child classes } int connectTimeout; int sendTimeout; int recieveTimeout; protected: asio::io_service &io_service; asio::deadline_timer deadline; #ifndef USE_HEADER_ONLY_ASIO boost::system::error_code error; #else asio::error_code error; #endif bool connected; }; class TcpSocket: public AbstractSocket { public: TcpSocket(asio::io_service &io_service) : AbstractSocket(io_service), socket(io_service) { } virtual ~TcpSocket() { socket.close(); connected = false; } virtual void connect(const std::string &host, int port) { // Set a deadline for the asynchronous operation. deadline.expires_from_now(boost::posix_time::seconds(connectTimeout)); // Set up the variable that receives the result of the asynchronous // operation. The error code is set to would_block to signal that the // operation is incomplete. Asio guarantees that its asynchronous // operations will never fail with would_block, so any other value in // ec indicates completion. error = asio::error::would_block; asio::ip::tcp::resolver resolver(io_service); asio::ip::tcp::resolver::query query(host, Utils::toString(port)); endpoint_iterator = resolver.resolve(query); // Start the asynchronous operation itself. The boost::lambda function // object is used as a callback and will update the ec variable when the // operation completes. socket.async_connect(*endpoint_iterator, boost::lambda::var(error) = boost::lambda::_1); // Block until the asynchronous operation has completed. do io_service.run_one(); while (error == asio::error::would_block); // Determine whether a connection was successfully established. The // deadline actor may have had a chance to run and close our socket, even // though the connect operation notionally succeeded. Therefore we must // check whether the socket is still open before deciding if we succeeded // or failed. if (error || !socket.is_open()) { throw CPS::Exception("Could not connect. " + error.message()); } connected = true; } virtual std::vector<unsigned char> send(const std::string &data) { // Set a deadline for the asynchronous operation. deadline.expires_from_now(boost::posix_time::seconds(sendTimeout)); // Set up the variable that receives the result of the asynchronous // operation. The error code is set to would_block to signal that the // operation is incomplete. Asio guarantees that its asynchronous // operations will never fail with would_block, so any other value in // ec indicates completion. error = asio::error::would_block; // Start the asynchronous operation itself. The boost::lambda function // object is used as a callback and will update the ec variable when the // operation completes. asio::async_write(socket, asio::buffer(data, data.size()), boost::lambda::var(error) = boost::lambda::_1); // Block until the asynchronous operation has completed. do io_service.run_one(); while (error == asio::error::would_block); if (error || !socket.is_open()) { throw CPS::Exception("Could not send message. " + error.message()); } return read(); } virtual std::vector<unsigned char> read() { // Set a deadline for the asynchronous operation. deadline.expires_from_now(boost::posix_time::seconds(recieveTimeout)); // Set up the variable that receives the result of the asynchronous // operation. The error code is set to would_block to signal that the // operation is incomplete. Asio guarantees that its asynchronous // operations will never fail with would_block, so any other value in // ec indicates completion. error = asio::error::would_block; std::vector<unsigned char> reply(8); size_t len = 0, content_len = 0; socket.async_read_some(asio::buffer(reply), (boost::lambda::var(error) = boost::lambda::_1, boost::lambda::var(len) = boost::lambda::_2)); // Block until the asynchronous operation has completed. do io_service.run_one(); while (error == asio::error::would_block); if (error || !socket.is_open() || len != 8 || !(reply[0] == 0x09 && reply[1] == 0x09 && reply[2] == 0x00 && reply[3] == 0x00)) { throw CPS::Exception("Invalid header received. " + error.message()); } content_len = (reply[4]) | (reply[5] << 8) | (reply[6] << 16) | (reply[7] << 24); // Read rest of message error = asio::error::would_block; reply.clear(); reply.resize(content_len); asio::async_read(socket, asio::buffer(reply), (boost::lambda::var(error) = boost::lambda::_1, boost::lambda::var(len) = boost::lambda::_2)); // Block until the asynchronous operation has completed. do io_service.run_one(); while (error == asio::error::would_block); if (error || !socket.is_open() || len != content_len) { throw CPS::Exception("Could not read message. " + error.message()); } return reply; } void handle_timer_expiration() { socket.close(); connected = false; } protected: asio::ip::tcp::socket socket; asio::ip::tcp::resolver::iterator endpoint_iterator; }; #ifdef BOOST_ASIO_HAS_LOCAL_SOCKETS class UnixSocket: public AbstractSocket { public: UnixSocket(asio::io_service &io_service) : AbstractSocket(io_service), socket(io_service) { } virtual ~UnixSocket() { socket.close(); } virtual void connect(const std::string &host, int port) { asio::local::stream_protocol::endpoint ep(host); // Set a deadline for the asynchronous operation. deadline.expires_from_now(boost::posix_time::seconds(connectTimeout)); // Set up the variable that receives the result of the asynchronous // operation. The error code is set to would_block to signal that the // operation is incomplete. Asio guarantees that its asynchronous // operations will never fail with would_block, so any other value in // ec indicates completion. error = asio::error::would_block; // Start the asynchronous operation itself. The boost::lambda function // object is used as a callback and will update the ec variable when the // operation completes. socket.async_connect(ep, boost::lambda::var(error) = boost::lambda::_1); // Block until the asynchronous operation has completed. do io_service.run_one(); while (error == asio::error::would_block); // Determine whether a connection was successfully established. The // deadline actor may have had a chance to run and close our socket, even // though the connect operation notionally succeeded. Therefore we must // check whether the socket is still open before deciding if we succeeded // or failed. if (error || !socket.is_open()) { throw CPS::Exception("Could not connect. " + error.message()); } connected = true; } virtual std::vector<unsigned char> send(const std::string &data) { // Set a deadline for the asynchronous operation. deadline.expires_from_now(boost::posix_time::seconds(sendTimeout)); // Set up the variable that receives the result of the asynchronous // operation. The error code is set to would_block to signal that the // operation is incomplete. Asio guarantees that its asynchronous // operations will never fail with would_block, so any other value in // ec indicates completion. error = asio::error::would_block; // Start the asynchronous operation itself. The boost::lambda function // object is used as a callback and will update the ec variable when the // operation completes. asio::async_write(socket, asio::buffer(data, data.size()), boost::lambda::var(error) = boost::lambda::_1); // Block until the asynchronous operation has completed. do io_service.run_one(); while (error == asio::error::would_block); if (error || !socket.is_open()) { throw CPS::Exception("Could not send message. " + error.message()); } return read(); } virtual std::vector<unsigned char> read() { // Set a deadline for the asynchronous operation. deadline.expires_from_now(boost::posix_time::seconds(recieveTimeout)); // Set up the variable that receives the result of the asynchronous // operation. The error code is set to would_block to signal that the // operation is incomplete. Asio guarantees that its asynchronous // operations will never fail with would_block, so any other value in // ec indicates completion. error = asio::error::would_block; std::vector<unsigned char> reply(8); size_t len = 0, content_len = 0; socket.async_read_some(asio::buffer(reply), (boost::lambda::var(error) = boost::lambda::_1, boost::lambda::var(len) = boost::lambda::_2)); // Block until the asynchronous operation has completed. do io_service.run_one(); while (error == asio::error::would_block); if (error || !socket.is_open() || len != 8 || !(reply[0] == 0x09 && reply[1] == 0x09 && reply[2] == 0x00 && reply[3] == 0x00)) { throw CPS::Exception("Invalid header received. " + error.message()); } content_len = (reply[4]) | (reply[5] << 8) | (reply[6] << 16) | (reply[7] << 24); // Read rest of message error = asio::error::would_block; reply.clear(); reply.resize(content_len); asio::async_read(socket, asio::buffer(reply), (boost::lambda::var(error) = boost::lambda::_1, boost::lambda::var(len) = boost::lambda::_2)); // Block until the asynchronous operation has completed. do io_service.run_one(); while (error == asio::error::would_block); if (error || !socket.is_open() || len != content_len) { throw CPS::Exception("Could not read message. " + error.message()); } return reply; } void handle_timer_expiration() { socket.close(error); connected = false; } protected: asio::local::stream_protocol::socket socket; }; #endif class HttpSocket: public TcpSocket { public: HttpSocket(asio::io_service &io_service, const std::string &host, int port, const std::string &path) : TcpSocket(io_service) { this->host = host; this->port = port; this->path = path; } virtual ~HttpSocket() { } virtual void connect(const std::string &host, int port) { deadline.expires_from_now(boost::posix_time::seconds(connectTimeout)); error = asio::error::would_block; asio::ip::tcp::resolver resolver(io_service); asio::ip::tcp::resolver::query query(host, Utils::toString(port)); endpoint_iterator = resolver.resolve(query); socket.async_connect(*endpoint_iterator, boost::lambda::var(error) = boost::lambda::_1); do io_service.run_one(); while (error == asio::error::would_block); if (error || !socket.is_open()) { throw CPS::Exception("Could not connect. " + error.message()); } connected = true; } virtual std::vector<unsigned char> send(const std::string &data) { deadline.expires_from_now(boost::posix_time::seconds(sendTimeout)); error = asio::error::would_block; // Create post headers std::string header = ""; header += "POST " + path + " HTTP/1.0\r\n"; header += "Host: " + host + ":" + Utils::toString(port) + "\r\n"; header += "Content-Length: " + Utils::toString(data.size()) + "\r\n"; header += "Connection: close\r\n"; header += "\r\n"; // Send headers asio::async_write(socket, asio::buffer(header, header.size()), boost::lambda::var(error) = boost::lambda::_1); // Send data asio::async_write(socket, asio::buffer(data, data.size()), boost::lambda::var(error) = boost::lambda::_1); do io_service.run_one(); while (error == asio::error::would_block); if (error || !socket.is_open()) { throw CPS::Exception("Could not send message. " + error.message()); } return this->read(); } virtual std::vector<unsigned char> read() { asio::streambuf response; #ifndef USE_HEADER_ONLY_ASIO boost::system::error_code err; #else asio::error_code err; #endif std::vector <unsigned char> reply; int read = 0; bool past_header = false; while ((read = asio::read(socket, response, asio::transfer_at_least(1), err)) != 0) { char cbuf[response.size() + 1]; int rc = response.sgetn(cbuf, sizeof(cbuf)); if (past_header == false) { char *data; if ((data = strstr(cbuf, "\r\n\r\n")) != NULL) { reply.insert(reply.end(), data + 4, cbuf + rc); past_header = true; } } else { reply.insert(reply.end(), cbuf, cbuf + rc); } } if (err != asio::error::eof) BOOST_THROW_EXCEPTION(Exception("Problem reading from socket")); return reply; } public: std::string host; int port; std::string path; protected: asio::ip::tcp::resolver::iterator endpoint_iterator; }; } #endif //#ifndef CPS_SOCKET_HPP_
34.521327
112
0.705656
clusterpoint
1225fb25b18b3ca12ea5812dbd8dc4b07db48775
4,923
cpp
C++
unittests/core/test_sstring_view_archive.cpp
paulhuggett/pstore2
a0c663d10a2e2713fdf39ecdae1f9c1e96041f5c
[ "Apache-2.0" ]
11
2018-02-02T21:24:49.000Z
2020-12-11T04:06:03.000Z
unittests/core/test_sstring_view_archive.cpp
SNSystems/pstore
74e9dd960245d6bfc125af03ed964d8ad660a62d
[ "Apache-2.0" ]
63
2018-02-05T17:24:59.000Z
2022-03-22T17:26:28.000Z
unittests/core/test_sstring_view_archive.cpp
paulhuggett/pstore
067be94d87c87fce524c8d76c6f47c347d8f1853
[ "Apache-2.0" ]
5
2020-01-13T22:47:11.000Z
2021-05-14T09:31:15.000Z
//===- unittests/core/test_sstring_view_archive.cpp -----------------------===// //* _ _ _ * //* ___ ___| |_ _ __(_)_ __ __ _ __ _(_) _____ __ * //* / __/ __| __| '__| | '_ \ / _` | \ \ / / |/ _ \ \ /\ / / * //* \__ \__ \ |_| | | | | | | (_| | \ V /| | __/\ V V / * //* |___/___/\__|_| |_|_| |_|\__, | \_/ |_|\___| \_/\_/ * //* |___/ * //* _ _ * //* __ _ _ __ ___| |__ (_)_ _____ * //* / _` | '__/ __| '_ \| \ \ / / _ \ * //* | (_| | | | (__| | | | |\ V / __/ * //* \__,_|_| \___|_| |_|_| \_/ \___| * //* * //===----------------------------------------------------------------------===// // // Part of the pstore project, under the Apache License v2.0 with LLVM Exceptions. // See https://github.com/SNSystems/pstore/blob/master/LICENSE.txt for license // information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "pstore/core/sstring_view_archive.hpp" #include <vector> #include <gmock/gmock.h> #include "pstore/core/transaction.hpp" #include "pstore/core/db_archive.hpp" #include "pstore/support/assert.hpp" #include "empty_store.hpp" namespace { using shared_sstring_view = pstore::sstring_view<std::shared_ptr<char const>>; class SStringViewArchive : public EmptyStore { public: SStringViewArchive () : db_{this->file ()} { db_.set_vacuum_mode (pstore::database::vacuum_mode::disabled); } protected: pstore::database db_; pstore::address current_pos (pstore::transaction_base & t) const; std::vector<char> as_vector (pstore::typed_address<char> first, pstore::typed_address<char> last) const; static shared_sstring_view make_shared_sstring_view (char const * s); }; shared_sstring_view SStringViewArchive::make_shared_sstring_view (char const * s) { auto const length = std::strlen (s); auto ptr = std::shared_ptr<char> (new char[length], [] (char * p) { delete[] p; }); std::copy (s, s + length, ptr.get ()); return {ptr, length}; } pstore::address SStringViewArchive::current_pos (pstore::transaction_base & t) const { return t.allocate (0U, 1U); // allocate 0 bytes to get the current EOF. } std::vector<char> SStringViewArchive::as_vector (pstore::typed_address<char> first, pstore::typed_address<char> last) const { PSTORE_ASSERT (last >= first); if (last < first) { return {}; } // Get the chars within the specified address range. std::size_t const num_chars = last.absolute () - first.absolute (); auto ptr = db_.getro (first, num_chars); // Convert them to a vector so that they're easy to compare. return {ptr.get (), ptr.get () + num_chars}; } } // namespace TEST_F (SStringViewArchive, Empty) { auto str = make_shared_sstring_view (""); // Append 'str'' to the store (we don't need to have committed the transaction to be able to // access its contents). mock_mutex mutex; auto transaction = begin (db_, std::unique_lock<mock_mutex>{mutex}); auto const first = pstore::typed_address<char> (this->current_pos (transaction)); pstore::serialize::write (pstore::serialize::archive::make_writer (transaction), str); auto const last = pstore::typed_address<char> (this->current_pos (transaction)); EXPECT_THAT (as_vector (first, last), ::testing::ElementsAre ('\x1', '\x0')); // Now try reading it back and compare to the original string. { using namespace pstore::serialize; shared_sstring_view const actual = read<shared_sstring_view> (archive::database_reader{db_, first.to_address ()}); EXPECT_EQ (actual, ""); } } TEST_F (SStringViewArchive, WriteHello) { auto str = make_shared_sstring_view ("hello"); mock_mutex mutex; auto transaction = begin (db_, std::unique_lock<mock_mutex>{mutex}); auto const first = pstore::typed_address<char> (this->current_pos (transaction)); { auto writer = pstore::serialize::archive::make_writer (transaction); pstore::serialize::write (writer, str); } auto const last = pstore::typed_address<char> (this->current_pos (transaction)); EXPECT_THAT (as_vector (first, last), ::testing::ElementsAre ('\xb', '\x0', 'h', 'e', 'l', 'l', 'o')); { auto reader = pstore::serialize::archive::database_reader{db_, first.to_address ()}; shared_sstring_view const actual = pstore::serialize::read<shared_sstring_view> (reader); EXPECT_EQ (actual, "hello"); } }
41.369748
97
0.566118
paulhuggett
1226c5c4d2478de9e19e9e3aaa71303d0ea0d6ed
917
cpp
C++
src/FalconEngine/Core/GameEngineProfiler.cpp
Lywx/FalconEngine
c4d1fed789218d1994908b8dbbcd6c01961f9ef2
[ "MIT" ]
6
2017-04-17T12:34:57.000Z
2019-10-19T23:29:59.000Z
src/FalconEngine/Core/GameEngineProfiler.cpp
Lywx/FalconEngine
c4d1fed789218d1994908b8dbbcd6c01961f9ef2
[ "MIT" ]
null
null
null
src/FalconEngine/Core/GameEngineProfiler.cpp
Lywx/FalconEngine
c4d1fed789218d1994908b8dbbcd6c01961f9ef2
[ "MIT" ]
2
2019-12-30T08:28:04.000Z
2020-08-05T09:58:53.000Z
#include <FalconEngine/Core/GameEngineProfiler.h> namespace FalconEngine { /************************************************************************/ /* Public Members */ /************************************************************************/ void GameEngineProfiler::Destroy() { } void GameEngineProfiler::Initialize() { } double GameEngineProfiler::GetLastFrameElapsedMillisecond() const { return mLastFrameElapsedMillisecond; } double GameEngineProfiler::GetLastFrameFps() const { return mLastFrameFps; } double GameEngineProfiler::GetLastFrameUpdateTotalCount() const { return mLastFrameUpdateTotalCount; } double GameEngineProfiler::GetLastUpdateElapsedMillisecond() const { return mLastUpdateElapsedMillisecond; } double GameEngineProfiler::GetLastRenderElapsedMillisecond() const { return mLastRenderElapsedMillisecond; } }
18.34
74
0.623773
Lywx