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
108
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
67k
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
404a5034ecba99e99e1c9f17be9b6817e14a9a0d
798
cpp
C++
server/scada/__tests__/utilities/pTimeToTimestamp.test.cpp
kubasikora/ZPR-Projekt
511ab15fdb0df61cfa1437ee63ca2d9cea37e914
[ "MIT" ]
null
null
null
server/scada/__tests__/utilities/pTimeToTimestamp.test.cpp
kubasikora/ZPR-Projekt
511ab15fdb0df61cfa1437ee63ca2d9cea37e914
[ "MIT" ]
null
null
null
server/scada/__tests__/utilities/pTimeToTimestamp.test.cpp
kubasikora/ZPR-Projekt
511ab15fdb0df61cfa1437ee63ca2d9cea37e914
[ "MIT" ]
1
2020-11-03T09:38:27.000Z
2020-11-03T09:38:27.000Z
#define BOOST_TEST_DYN_LINK #ifdef __unix__ #include <boost/test/unit_test.hpp> #elif defined(_WIN32) || defined(WIN32) #include <boost/test/included/unit_test.hpp> #endif #include<string> #include<exception> #include<boost/date_time/posix_time/ptime.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/date_time/posix_time/posix_time_io.hpp> #include"utilities/utilities.hpp" BOOST_AUTO_TEST_SUITE( pTimeToTimestampTests ) BOOST_AUTO_TEST_CASE( convertsToTimestamp ) { std::string isoTime = "20020131T235959"; std::string expectedTimestamp = "2002-Jan-31 23:59:59"; boost::posix_time::ptime exampleTime(boost::posix_time::from_iso_string(isoTime)); BOOST_CHECK_EQUAL(zpr::pTimeToTimestamp(exampleTime), expectedTimestamp); } BOOST_AUTO_TEST_SUITE_END()
29.555556
86
0.793233
kubasikora
405095182f19760cbd10b85325d7b335f1d82316
72,695
cpp
C++
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_sysadmin_show_diag.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
17
2016-12-02T05:45:49.000Z
2022-02-10T19:32:54.000Z
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_sysadmin_show_diag.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
2
2017-03-27T15:22:38.000Z
2019-11-05T08:30:16.000Z
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_sysadmin_show_diag.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
11
2016-12-02T05:45:52.000Z
2019-11-07T08:28:17.000Z
#include <sstream> #include <iostream> #include <ydk/entity_util.hpp> #include "bundle_info.hpp" #include "generated_entity_lookup.hpp" #include "Cisco_IOS_XR_sysadmin_show_diag.hpp" using namespace ydk; namespace cisco_ios_xr { namespace Cisco_IOS_XR_sysadmin_show_diag { Diag::Diag() : default_(std::make_shared<Diag::Default>()) , fans(std::make_shared<Diag::Fans>()) , power_supply(std::make_shared<Diag::PowerSupply>()) , chassis(std::make_shared<Diag::Chassis>()) , summary(std::make_shared<Diag::Summary>()) , eeprom(std::make_shared<Diag::Eeprom>()) , detail(std::make_shared<Diag::Detail>()) { default_->parent = this; fans->parent = this; power_supply->parent = this; chassis->parent = this; summary->parent = this; eeprom->parent = this; detail->parent = this; yang_name = "diag"; yang_parent_name = "Cisco-IOS-XR-sysadmin-show-diag"; is_top_level_class = true; has_list_ancestor = false; } Diag::~Diag() { } bool Diag::has_data() const { if (is_presence_container) return true; return (default_ != nullptr && default_->has_data()) || (fans != nullptr && fans->has_data()) || (power_supply != nullptr && power_supply->has_data()) || (chassis != nullptr && chassis->has_data()) || (summary != nullptr && summary->has_data()) || (eeprom != nullptr && eeprom->has_data()) || (detail != nullptr && detail->has_data()); } bool Diag::has_operation() const { return is_set(yfilter) || (default_ != nullptr && default_->has_operation()) || (fans != nullptr && fans->has_operation()) || (power_supply != nullptr && power_supply->has_operation()) || (chassis != nullptr && chassis->has_operation()) || (summary != nullptr && summary->has_operation()) || (eeprom != nullptr && eeprom->has_operation()) || (detail != nullptr && detail->has_operation()); } std::string Diag::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "default") { if(default_ == nullptr) { default_ = std::make_shared<Diag::Default>(); } return default_; } if(child_yang_name == "fans") { if(fans == nullptr) { fans = std::make_shared<Diag::Fans>(); } return fans; } if(child_yang_name == "power-supply") { if(power_supply == nullptr) { power_supply = std::make_shared<Diag::PowerSupply>(); } return power_supply; } if(child_yang_name == "chassis") { if(chassis == nullptr) { chassis = std::make_shared<Diag::Chassis>(); } return chassis; } if(child_yang_name == "summary") { if(summary == nullptr) { summary = std::make_shared<Diag::Summary>(); } return summary; } if(child_yang_name == "eeprom") { if(eeprom == nullptr) { eeprom = std::make_shared<Diag::Eeprom>(); } return eeprom; } if(child_yang_name == "detail") { if(detail == nullptr) { detail = std::make_shared<Diag::Detail>(); } return detail; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(default_ != nullptr) { _children["default"] = default_; } if(fans != nullptr) { _children["fans"] = fans; } if(power_supply != nullptr) { _children["power-supply"] = power_supply; } if(chassis != nullptr) { _children["chassis"] = chassis; } if(summary != nullptr) { _children["summary"] = summary; } if(eeprom != nullptr) { _children["eeprom"] = eeprom; } if(detail != nullptr) { _children["detail"] = detail; } return _children; } void Diag::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Diag::set_filter(const std::string & value_path, YFilter yfilter) { } std::shared_ptr<ydk::Entity> Diag::clone_ptr() const { return std::make_shared<Diag>(); } std::string Diag::get_bundle_yang_models_location() const { return ydk_cisco_ios_xr_models_path; } std::string Diag::get_bundle_name() const { return "cisco_ios_xr"; } augment_capabilities_function Diag::get_augment_capabilities_function() const { return cisco_ios_xr_augment_lookup_tables; } std::map<std::pair<std::string, std::string>, std::string> Diag::get_namespace_identity_lookup() const { return cisco_ios_xr_namespace_identity_lookup; } bool Diag::has_leaf_or_child_of_name(const std::string & name) const { if(name == "default" || name == "fans" || name == "power-supply" || name == "chassis" || name == "summary" || name == "eeprom" || name == "detail") return true; return false; } Diag::Default::Default() : default_list(this, {"location"}) { yang_name = "default"; yang_parent_name = "diag"; is_top_level_class = false; has_list_ancestor = false; } Diag::Default::~Default() { } bool Diag::Default::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<default_list.len(); index++) { if(default_list[index]->has_data()) return true; } return false; } bool Diag::Default::has_operation() const { for (std::size_t index=0; index<default_list.len(); index++) { if(default_list[index]->has_operation()) return true; } return is_set(yfilter); } std::string Diag::Default::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/" << get_segment_path(); return path_buffer.str(); } std::string Diag::Default::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "default"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::Default::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::Default::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "default_list") { auto ent_ = std::make_shared<Diag::Default::DefaultList>(); ent_->parent = this; default_list.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Default::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : default_list.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Diag::Default::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Diag::Default::set_filter(const std::string & value_path, YFilter yfilter) { } bool Diag::Default::has_leaf_or_child_of_name(const std::string & name) const { if(name == "default_list") return true; return false; } Diag::Default::DefaultList::DefaultList() : location{YType::str, "location"} , default_data(std::make_shared<Diag::Default::DefaultList::DefaultData>()) { default_data->parent = this; yang_name = "default_list"; yang_parent_name = "default"; is_top_level_class = false; has_list_ancestor = false; } Diag::Default::DefaultList::~DefaultList() { } bool Diag::Default::DefaultList::has_data() const { if (is_presence_container) return true; return location.is_set || (default_data != nullptr && default_data->has_data()); } bool Diag::Default::DefaultList::has_operation() const { return is_set(yfilter) || ydk::is_set(location.yfilter) || (default_data != nullptr && default_data->has_operation()); } std::string Diag::Default::DefaultList::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/default/" << get_segment_path(); return path_buffer.str(); } std::string Diag::Default::DefaultList::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "default_list"; ADD_KEY_TOKEN(location, "location"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::Default::DefaultList::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (location.is_set || is_set(location.yfilter)) leaf_name_data.push_back(location.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::Default::DefaultList::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "default-data") { if(default_data == nullptr) { default_data = std::make_shared<Diag::Default::DefaultList::DefaultData>(); } return default_data; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Default::DefaultList::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(default_data != nullptr) { _children["default-data"] = default_data; } return _children; } void Diag::Default::DefaultList::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "location") { location = value; location.value_namespace = name_space; location.value_namespace_prefix = name_space_prefix; } } void Diag::Default::DefaultList::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "location") { location.yfilter = yfilter; } } bool Diag::Default::DefaultList::has_leaf_or_child_of_name(const std::string & name) const { if(name == "default-data" || name == "location") return true; return false; } Diag::Default::DefaultList::DefaultData::DefaultData() : default_out_list{YType::str, "default_out_list"} { yang_name = "default-data"; yang_parent_name = "default_list"; is_top_level_class = false; has_list_ancestor = true; } Diag::Default::DefaultList::DefaultData::~DefaultData() { } bool Diag::Default::DefaultList::DefaultData::has_data() const { if (is_presence_container) return true; for (auto const & leaf : default_out_list.getYLeafs()) { if(leaf.is_set) return true; } return false; } bool Diag::Default::DefaultList::DefaultData::has_operation() const { for (auto const & leaf : default_out_list.getYLeafs()) { if(is_set(leaf.yfilter)) return true; } return is_set(yfilter) || ydk::is_set(default_out_list.yfilter); } std::string Diag::Default::DefaultList::DefaultData::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "default-data"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::Default::DefaultList::DefaultData::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; auto default_out_list_name_datas = default_out_list.get_name_leafdata(); leaf_name_data.insert(leaf_name_data.end(), default_out_list_name_datas.begin(), default_out_list_name_datas.end()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::Default::DefaultList::DefaultData::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Default::DefaultList::DefaultData::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Diag::Default::DefaultList::DefaultData::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "default_out_list") { default_out_list.append(value); } } void Diag::Default::DefaultList::DefaultData::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "default_out_list") { default_out_list.yfilter = yfilter; } } bool Diag::Default::DefaultList::DefaultData::has_leaf_or_child_of_name(const std::string & name) const { if(name == "default_out_list") return true; return false; } Diag::Fans::Fans() : fans_list(this, {"location"}) { yang_name = "fans"; yang_parent_name = "diag"; is_top_level_class = false; has_list_ancestor = false; } Diag::Fans::~Fans() { } bool Diag::Fans::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<fans_list.len(); index++) { if(fans_list[index]->has_data()) return true; } return false; } bool Diag::Fans::has_operation() const { for (std::size_t index=0; index<fans_list.len(); index++) { if(fans_list[index]->has_operation()) return true; } return is_set(yfilter); } std::string Diag::Fans::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/" << get_segment_path(); return path_buffer.str(); } std::string Diag::Fans::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "fans"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::Fans::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::Fans::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "fans_list") { auto ent_ = std::make_shared<Diag::Fans::FansList>(); ent_->parent = this; fans_list.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Fans::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : fans_list.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Diag::Fans::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Diag::Fans::set_filter(const std::string & value_path, YFilter yfilter) { } bool Diag::Fans::has_leaf_or_child_of_name(const std::string & name) const { if(name == "fans_list") return true; return false; } Diag::Fans::FansList::FansList() : location{YType::str, "location"} , default_data(std::make_shared<Diag::Fans::FansList::DefaultData>()) { default_data->parent = this; yang_name = "fans_list"; yang_parent_name = "fans"; is_top_level_class = false; has_list_ancestor = false; } Diag::Fans::FansList::~FansList() { } bool Diag::Fans::FansList::has_data() const { if (is_presence_container) return true; return location.is_set || (default_data != nullptr && default_data->has_data()); } bool Diag::Fans::FansList::has_operation() const { return is_set(yfilter) || ydk::is_set(location.yfilter) || (default_data != nullptr && default_data->has_operation()); } std::string Diag::Fans::FansList::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/fans/" << get_segment_path(); return path_buffer.str(); } std::string Diag::Fans::FansList::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "fans_list"; ADD_KEY_TOKEN(location, "location"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::Fans::FansList::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (location.is_set || is_set(location.yfilter)) leaf_name_data.push_back(location.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::Fans::FansList::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "default-data") { if(default_data == nullptr) { default_data = std::make_shared<Diag::Fans::FansList::DefaultData>(); } return default_data; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Fans::FansList::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(default_data != nullptr) { _children["default-data"] = default_data; } return _children; } void Diag::Fans::FansList::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "location") { location = value; location.value_namespace = name_space; location.value_namespace_prefix = name_space_prefix; } } void Diag::Fans::FansList::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "location") { location.yfilter = yfilter; } } bool Diag::Fans::FansList::has_leaf_or_child_of_name(const std::string & name) const { if(name == "default-data" || name == "location") return true; return false; } Diag::Fans::FansList::DefaultData::DefaultData() : default_out_list{YType::str, "default_out_list"} { yang_name = "default-data"; yang_parent_name = "fans_list"; is_top_level_class = false; has_list_ancestor = true; } Diag::Fans::FansList::DefaultData::~DefaultData() { } bool Diag::Fans::FansList::DefaultData::has_data() const { if (is_presence_container) return true; for (auto const & leaf : default_out_list.getYLeafs()) { if(leaf.is_set) return true; } return false; } bool Diag::Fans::FansList::DefaultData::has_operation() const { for (auto const & leaf : default_out_list.getYLeafs()) { if(is_set(leaf.yfilter)) return true; } return is_set(yfilter) || ydk::is_set(default_out_list.yfilter); } std::string Diag::Fans::FansList::DefaultData::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "default-data"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::Fans::FansList::DefaultData::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; auto default_out_list_name_datas = default_out_list.get_name_leafdata(); leaf_name_data.insert(leaf_name_data.end(), default_out_list_name_datas.begin(), default_out_list_name_datas.end()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::Fans::FansList::DefaultData::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Fans::FansList::DefaultData::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Diag::Fans::FansList::DefaultData::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "default_out_list") { default_out_list.append(value); } } void Diag::Fans::FansList::DefaultData::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "default_out_list") { default_out_list.yfilter = yfilter; } } bool Diag::Fans::FansList::DefaultData::has_leaf_or_child_of_name(const std::string & name) const { if(name == "default_out_list") return true; return false; } Diag::PowerSupply::PowerSupply() : pwr_list(this, {"location"}) { yang_name = "power-supply"; yang_parent_name = "diag"; is_top_level_class = false; has_list_ancestor = false; } Diag::PowerSupply::~PowerSupply() { } bool Diag::PowerSupply::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<pwr_list.len(); index++) { if(pwr_list[index]->has_data()) return true; } return false; } bool Diag::PowerSupply::has_operation() const { for (std::size_t index=0; index<pwr_list.len(); index++) { if(pwr_list[index]->has_operation()) return true; } return is_set(yfilter); } std::string Diag::PowerSupply::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/" << get_segment_path(); return path_buffer.str(); } std::string Diag::PowerSupply::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "power-supply"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::PowerSupply::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::PowerSupply::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "pwr_list") { auto ent_ = std::make_shared<Diag::PowerSupply::PwrList>(); ent_->parent = this; pwr_list.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::PowerSupply::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : pwr_list.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Diag::PowerSupply::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Diag::PowerSupply::set_filter(const std::string & value_path, YFilter yfilter) { } bool Diag::PowerSupply::has_leaf_or_child_of_name(const std::string & name) const { if(name == "pwr_list") return true; return false; } Diag::PowerSupply::PwrList::PwrList() : location{YType::str, "location"} , default_data(std::make_shared<Diag::PowerSupply::PwrList::DefaultData>()) { default_data->parent = this; yang_name = "pwr_list"; yang_parent_name = "power-supply"; is_top_level_class = false; has_list_ancestor = false; } Diag::PowerSupply::PwrList::~PwrList() { } bool Diag::PowerSupply::PwrList::has_data() const { if (is_presence_container) return true; return location.is_set || (default_data != nullptr && default_data->has_data()); } bool Diag::PowerSupply::PwrList::has_operation() const { return is_set(yfilter) || ydk::is_set(location.yfilter) || (default_data != nullptr && default_data->has_operation()); } std::string Diag::PowerSupply::PwrList::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/power-supply/" << get_segment_path(); return path_buffer.str(); } std::string Diag::PowerSupply::PwrList::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "pwr_list"; ADD_KEY_TOKEN(location, "location"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::PowerSupply::PwrList::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (location.is_set || is_set(location.yfilter)) leaf_name_data.push_back(location.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::PowerSupply::PwrList::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "default-data") { if(default_data == nullptr) { default_data = std::make_shared<Diag::PowerSupply::PwrList::DefaultData>(); } return default_data; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::PowerSupply::PwrList::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(default_data != nullptr) { _children["default-data"] = default_data; } return _children; } void Diag::PowerSupply::PwrList::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "location") { location = value; location.value_namespace = name_space; location.value_namespace_prefix = name_space_prefix; } } void Diag::PowerSupply::PwrList::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "location") { location.yfilter = yfilter; } } bool Diag::PowerSupply::PwrList::has_leaf_or_child_of_name(const std::string & name) const { if(name == "default-data" || name == "location") return true; return false; } Diag::PowerSupply::PwrList::DefaultData::DefaultData() : default_out_list{YType::str, "default_out_list"} { yang_name = "default-data"; yang_parent_name = "pwr_list"; is_top_level_class = false; has_list_ancestor = true; } Diag::PowerSupply::PwrList::DefaultData::~DefaultData() { } bool Diag::PowerSupply::PwrList::DefaultData::has_data() const { if (is_presence_container) return true; for (auto const & leaf : default_out_list.getYLeafs()) { if(leaf.is_set) return true; } return false; } bool Diag::PowerSupply::PwrList::DefaultData::has_operation() const { for (auto const & leaf : default_out_list.getYLeafs()) { if(is_set(leaf.yfilter)) return true; } return is_set(yfilter) || ydk::is_set(default_out_list.yfilter); } std::string Diag::PowerSupply::PwrList::DefaultData::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "default-data"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::PowerSupply::PwrList::DefaultData::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; auto default_out_list_name_datas = default_out_list.get_name_leafdata(); leaf_name_data.insert(leaf_name_data.end(), default_out_list_name_datas.begin(), default_out_list_name_datas.end()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::PowerSupply::PwrList::DefaultData::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::PowerSupply::PwrList::DefaultData::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Diag::PowerSupply::PwrList::DefaultData::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "default_out_list") { default_out_list.append(value); } } void Diag::PowerSupply::PwrList::DefaultData::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "default_out_list") { default_out_list.yfilter = yfilter; } } bool Diag::PowerSupply::PwrList::DefaultData::has_leaf_or_child_of_name(const std::string & name) const { if(name == "default_out_list") return true; return false; } Diag::Chassis::Chassis() : chassis_cnt(std::make_shared<Diag::Chassis::ChassisCnt>()) , chassis_eeprom_cnt(std::make_shared<Diag::Chassis::ChassisEepromCnt>()) { chassis_cnt->parent = this; chassis_eeprom_cnt->parent = this; yang_name = "chassis"; yang_parent_name = "diag"; is_top_level_class = false; has_list_ancestor = false; } Diag::Chassis::~Chassis() { } bool Diag::Chassis::has_data() const { if (is_presence_container) return true; return (chassis_cnt != nullptr && chassis_cnt->has_data()) || (chassis_eeprom_cnt != nullptr && chassis_eeprom_cnt->has_data()); } bool Diag::Chassis::has_operation() const { return is_set(yfilter) || (chassis_cnt != nullptr && chassis_cnt->has_operation()) || (chassis_eeprom_cnt != nullptr && chassis_eeprom_cnt->has_operation()); } std::string Diag::Chassis::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/" << get_segment_path(); return path_buffer.str(); } std::string Diag::Chassis::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "chassis"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::Chassis::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::Chassis::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "chassis_cnt") { if(chassis_cnt == nullptr) { chassis_cnt = std::make_shared<Diag::Chassis::ChassisCnt>(); } return chassis_cnt; } if(child_yang_name == "chassis_eeprom_cnt") { if(chassis_eeprom_cnt == nullptr) { chassis_eeprom_cnt = std::make_shared<Diag::Chassis::ChassisEepromCnt>(); } return chassis_eeprom_cnt; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Chassis::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(chassis_cnt != nullptr) { _children["chassis_cnt"] = chassis_cnt; } if(chassis_eeprom_cnt != nullptr) { _children["chassis_eeprom_cnt"] = chassis_eeprom_cnt; } return _children; } void Diag::Chassis::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Diag::Chassis::set_filter(const std::string & value_path, YFilter yfilter) { } bool Diag::Chassis::has_leaf_or_child_of_name(const std::string & name) const { if(name == "chassis_cnt" || name == "chassis_eeprom_cnt") return true; return false; } Diag::Chassis::ChassisCnt::ChassisCnt() : chassis_list(this, {"location"}) { yang_name = "chassis_cnt"; yang_parent_name = "chassis"; is_top_level_class = false; has_list_ancestor = false; } Diag::Chassis::ChassisCnt::~ChassisCnt() { } bool Diag::Chassis::ChassisCnt::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<chassis_list.len(); index++) { if(chassis_list[index]->has_data()) return true; } return false; } bool Diag::Chassis::ChassisCnt::has_operation() const { for (std::size_t index=0; index<chassis_list.len(); index++) { if(chassis_list[index]->has_operation()) return true; } return is_set(yfilter); } std::string Diag::Chassis::ChassisCnt::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/chassis/" << get_segment_path(); return path_buffer.str(); } std::string Diag::Chassis::ChassisCnt::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "chassis_cnt"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::Chassis::ChassisCnt::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::Chassis::ChassisCnt::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "chassis_list") { auto ent_ = std::make_shared<Diag::Chassis::ChassisCnt::ChassisList>(); ent_->parent = this; chassis_list.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Chassis::ChassisCnt::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : chassis_list.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Diag::Chassis::ChassisCnt::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Diag::Chassis::ChassisCnt::set_filter(const std::string & value_path, YFilter yfilter) { } bool Diag::Chassis::ChassisCnt::has_leaf_or_child_of_name(const std::string & name) const { if(name == "chassis_list") return true; return false; } Diag::Chassis::ChassisCnt::ChassisList::ChassisList() : location{YType::str, "location"} , default_data(std::make_shared<Diag::Chassis::ChassisCnt::ChassisList::DefaultData>()) { default_data->parent = this; yang_name = "chassis_list"; yang_parent_name = "chassis_cnt"; is_top_level_class = false; has_list_ancestor = false; } Diag::Chassis::ChassisCnt::ChassisList::~ChassisList() { } bool Diag::Chassis::ChassisCnt::ChassisList::has_data() const { if (is_presence_container) return true; return location.is_set || (default_data != nullptr && default_data->has_data()); } bool Diag::Chassis::ChassisCnt::ChassisList::has_operation() const { return is_set(yfilter) || ydk::is_set(location.yfilter) || (default_data != nullptr && default_data->has_operation()); } std::string Diag::Chassis::ChassisCnt::ChassisList::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/chassis/chassis_cnt/" << get_segment_path(); return path_buffer.str(); } std::string Diag::Chassis::ChassisCnt::ChassisList::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "chassis_list"; ADD_KEY_TOKEN(location, "location"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::Chassis::ChassisCnt::ChassisList::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (location.is_set || is_set(location.yfilter)) leaf_name_data.push_back(location.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::Chassis::ChassisCnt::ChassisList::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "default-data") { if(default_data == nullptr) { default_data = std::make_shared<Diag::Chassis::ChassisCnt::ChassisList::DefaultData>(); } return default_data; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Chassis::ChassisCnt::ChassisList::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(default_data != nullptr) { _children["default-data"] = default_data; } return _children; } void Diag::Chassis::ChassisCnt::ChassisList::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "location") { location = value; location.value_namespace = name_space; location.value_namespace_prefix = name_space_prefix; } } void Diag::Chassis::ChassisCnt::ChassisList::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "location") { location.yfilter = yfilter; } } bool Diag::Chassis::ChassisCnt::ChassisList::has_leaf_or_child_of_name(const std::string & name) const { if(name == "default-data" || name == "location") return true; return false; } Diag::Chassis::ChassisCnt::ChassisList::DefaultData::DefaultData() : default_out_list{YType::str, "default_out_list"} { yang_name = "default-data"; yang_parent_name = "chassis_list"; is_top_level_class = false; has_list_ancestor = true; } Diag::Chassis::ChassisCnt::ChassisList::DefaultData::~DefaultData() { } bool Diag::Chassis::ChassisCnt::ChassisList::DefaultData::has_data() const { if (is_presence_container) return true; for (auto const & leaf : default_out_list.getYLeafs()) { if(leaf.is_set) return true; } return false; } bool Diag::Chassis::ChassisCnt::ChassisList::DefaultData::has_operation() const { for (auto const & leaf : default_out_list.getYLeafs()) { if(is_set(leaf.yfilter)) return true; } return is_set(yfilter) || ydk::is_set(default_out_list.yfilter); } std::string Diag::Chassis::ChassisCnt::ChassisList::DefaultData::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "default-data"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::Chassis::ChassisCnt::ChassisList::DefaultData::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; auto default_out_list_name_datas = default_out_list.get_name_leafdata(); leaf_name_data.insert(leaf_name_data.end(), default_out_list_name_datas.begin(), default_out_list_name_datas.end()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::Chassis::ChassisCnt::ChassisList::DefaultData::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Chassis::ChassisCnt::ChassisList::DefaultData::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Diag::Chassis::ChassisCnt::ChassisList::DefaultData::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "default_out_list") { default_out_list.append(value); } } void Diag::Chassis::ChassisCnt::ChassisList::DefaultData::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "default_out_list") { default_out_list.yfilter = yfilter; } } bool Diag::Chassis::ChassisCnt::ChassisList::DefaultData::has_leaf_or_child_of_name(const std::string & name) const { if(name == "default_out_list") return true; return false; } Diag::Chassis::ChassisEepromCnt::ChassisEepromCnt() : chassis_eeprom_list(this, {"location"}) { yang_name = "chassis_eeprom_cnt"; yang_parent_name = "chassis"; is_top_level_class = false; has_list_ancestor = false; } Diag::Chassis::ChassisEepromCnt::~ChassisEepromCnt() { } bool Diag::Chassis::ChassisEepromCnt::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<chassis_eeprom_list.len(); index++) { if(chassis_eeprom_list[index]->has_data()) return true; } return false; } bool Diag::Chassis::ChassisEepromCnt::has_operation() const { for (std::size_t index=0; index<chassis_eeprom_list.len(); index++) { if(chassis_eeprom_list[index]->has_operation()) return true; } return is_set(yfilter); } std::string Diag::Chassis::ChassisEepromCnt::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/chassis/" << get_segment_path(); return path_buffer.str(); } std::string Diag::Chassis::ChassisEepromCnt::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "chassis_eeprom_cnt"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::Chassis::ChassisEepromCnt::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::Chassis::ChassisEepromCnt::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "chassis_eeprom_list") { auto ent_ = std::make_shared<Diag::Chassis::ChassisEepromCnt::ChassisEepromList>(); ent_->parent = this; chassis_eeprom_list.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Chassis::ChassisEepromCnt::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : chassis_eeprom_list.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Diag::Chassis::ChassisEepromCnt::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Diag::Chassis::ChassisEepromCnt::set_filter(const std::string & value_path, YFilter yfilter) { } bool Diag::Chassis::ChassisEepromCnt::has_leaf_or_child_of_name(const std::string & name) const { if(name == "chassis_eeprom_list") return true; return false; } Diag::Chassis::ChassisEepromCnt::ChassisEepromList::ChassisEepromList() : location{YType::str, "location"} , eeprom_data(std::make_shared<Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData>()) { eeprom_data->parent = this; yang_name = "chassis_eeprom_list"; yang_parent_name = "chassis_eeprom_cnt"; is_top_level_class = false; has_list_ancestor = false; } Diag::Chassis::ChassisEepromCnt::ChassisEepromList::~ChassisEepromList() { } bool Diag::Chassis::ChassisEepromCnt::ChassisEepromList::has_data() const { if (is_presence_container) return true; return location.is_set || (eeprom_data != nullptr && eeprom_data->has_data()); } bool Diag::Chassis::ChassisEepromCnt::ChassisEepromList::has_operation() const { return is_set(yfilter) || ydk::is_set(location.yfilter) || (eeprom_data != nullptr && eeprom_data->has_operation()); } std::string Diag::Chassis::ChassisEepromCnt::ChassisEepromList::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/chassis/chassis_eeprom_cnt/" << get_segment_path(); return path_buffer.str(); } std::string Diag::Chassis::ChassisEepromCnt::ChassisEepromList::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "chassis_eeprom_list"; ADD_KEY_TOKEN(location, "location"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::Chassis::ChassisEepromCnt::ChassisEepromList::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (location.is_set || is_set(location.yfilter)) leaf_name_data.push_back(location.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::Chassis::ChassisEepromCnt::ChassisEepromList::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "eeprom-data") { if(eeprom_data == nullptr) { eeprom_data = std::make_shared<Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData>(); } return eeprom_data; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Chassis::ChassisEepromCnt::ChassisEepromList::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(eeprom_data != nullptr) { _children["eeprom-data"] = eeprom_data; } return _children; } void Diag::Chassis::ChassisEepromCnt::ChassisEepromList::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "location") { location = value; location.value_namespace = name_space; location.value_namespace_prefix = name_space_prefix; } } void Diag::Chassis::ChassisEepromCnt::ChassisEepromList::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "location") { location.yfilter = yfilter; } } bool Diag::Chassis::ChassisEepromCnt::ChassisEepromList::has_leaf_or_child_of_name(const std::string & name) const { if(name == "eeprom-data" || name == "location") return true; return false; } Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData::EepromData() : raw_list{YType::str, "raw_list"} { yang_name = "eeprom-data"; yang_parent_name = "chassis_eeprom_list"; is_top_level_class = false; has_list_ancestor = true; } Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData::~EepromData() { } bool Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData::has_data() const { if (is_presence_container) return true; for (auto const & leaf : raw_list.getYLeafs()) { if(leaf.is_set) return true; } return false; } bool Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData::has_operation() const { for (auto const & leaf : raw_list.getYLeafs()) { if(is_set(leaf.yfilter)) return true; } return is_set(yfilter) || ydk::is_set(raw_list.yfilter); } std::string Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "eeprom-data"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; auto raw_list_name_datas = raw_list.get_name_leafdata(); leaf_name_data.insert(leaf_name_data.end(), raw_list_name_datas.begin(), raw_list_name_datas.end()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "raw_list") { raw_list.append(value); } } void Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "raw_list") { raw_list.yfilter = yfilter; } } bool Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData::has_leaf_or_child_of_name(const std::string & name) const { if(name == "raw_list") return true; return false; } Diag::Summary::Summary() : summary_list(this, {"location"}) { yang_name = "summary"; yang_parent_name = "diag"; is_top_level_class = false; has_list_ancestor = false; } Diag::Summary::~Summary() { } bool Diag::Summary::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<summary_list.len(); index++) { if(summary_list[index]->has_data()) return true; } return false; } bool Diag::Summary::has_operation() const { for (std::size_t index=0; index<summary_list.len(); index++) { if(summary_list[index]->has_operation()) return true; } return is_set(yfilter); } std::string Diag::Summary::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/" << get_segment_path(); return path_buffer.str(); } std::string Diag::Summary::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "summary"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::Summary::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::Summary::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "summary_list") { auto ent_ = std::make_shared<Diag::Summary::SummaryList>(); ent_->parent = this; summary_list.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Summary::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : summary_list.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Diag::Summary::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Diag::Summary::set_filter(const std::string & value_path, YFilter yfilter) { } bool Diag::Summary::has_leaf_or_child_of_name(const std::string & name) const { if(name == "summary_list") return true; return false; } Diag::Summary::SummaryList::SummaryList() : location{YType::str, "location"} , summary_data(std::make_shared<Diag::Summary::SummaryList::SummaryData>()) { summary_data->parent = this; yang_name = "summary_list"; yang_parent_name = "summary"; is_top_level_class = false; has_list_ancestor = false; } Diag::Summary::SummaryList::~SummaryList() { } bool Diag::Summary::SummaryList::has_data() const { if (is_presence_container) return true; return location.is_set || (summary_data != nullptr && summary_data->has_data()); } bool Diag::Summary::SummaryList::has_operation() const { return is_set(yfilter) || ydk::is_set(location.yfilter) || (summary_data != nullptr && summary_data->has_operation()); } std::string Diag::Summary::SummaryList::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/summary/" << get_segment_path(); return path_buffer.str(); } std::string Diag::Summary::SummaryList::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "summary_list"; ADD_KEY_TOKEN(location, "location"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::Summary::SummaryList::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (location.is_set || is_set(location.yfilter)) leaf_name_data.push_back(location.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::Summary::SummaryList::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "summary-data") { if(summary_data == nullptr) { summary_data = std::make_shared<Diag::Summary::SummaryList::SummaryData>(); } return summary_data; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Summary::SummaryList::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(summary_data != nullptr) { _children["summary-data"] = summary_data; } return _children; } void Diag::Summary::SummaryList::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "location") { location = value; location.value_namespace = name_space; location.value_namespace_prefix = name_space_prefix; } } void Diag::Summary::SummaryList::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "location") { location.yfilter = yfilter; } } bool Diag::Summary::SummaryList::has_leaf_or_child_of_name(const std::string & name) const { if(name == "summary-data" || name == "location") return true; return false; } Diag::Summary::SummaryList::SummaryData::SummaryData() : summary_out_list{YType::str, "summary_out_list"} { yang_name = "summary-data"; yang_parent_name = "summary_list"; is_top_level_class = false; has_list_ancestor = true; } Diag::Summary::SummaryList::SummaryData::~SummaryData() { } bool Diag::Summary::SummaryList::SummaryData::has_data() const { if (is_presence_container) return true; for (auto const & leaf : summary_out_list.getYLeafs()) { if(leaf.is_set) return true; } return false; } bool Diag::Summary::SummaryList::SummaryData::has_operation() const { for (auto const & leaf : summary_out_list.getYLeafs()) { if(is_set(leaf.yfilter)) return true; } return is_set(yfilter) || ydk::is_set(summary_out_list.yfilter); } std::string Diag::Summary::SummaryList::SummaryData::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "summary-data"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::Summary::SummaryList::SummaryData::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; auto summary_out_list_name_datas = summary_out_list.get_name_leafdata(); leaf_name_data.insert(leaf_name_data.end(), summary_out_list_name_datas.begin(), summary_out_list_name_datas.end()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::Summary::SummaryList::SummaryData::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Summary::SummaryList::SummaryData::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Diag::Summary::SummaryList::SummaryData::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "summary_out_list") { summary_out_list.append(value); } } void Diag::Summary::SummaryList::SummaryData::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "summary_out_list") { summary_out_list.yfilter = yfilter; } } bool Diag::Summary::SummaryList::SummaryData::has_leaf_or_child_of_name(const std::string & name) const { if(name == "summary_out_list") return true; return false; } Diag::Eeprom::Eeprom() : eeprom_list(this, {"location"}) { yang_name = "eeprom"; yang_parent_name = "diag"; is_top_level_class = false; has_list_ancestor = false; } Diag::Eeprom::~Eeprom() { } bool Diag::Eeprom::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<eeprom_list.len(); index++) { if(eeprom_list[index]->has_data()) return true; } return false; } bool Diag::Eeprom::has_operation() const { for (std::size_t index=0; index<eeprom_list.len(); index++) { if(eeprom_list[index]->has_operation()) return true; } return is_set(yfilter); } std::string Diag::Eeprom::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/" << get_segment_path(); return path_buffer.str(); } std::string Diag::Eeprom::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "eeprom"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::Eeprom::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::Eeprom::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "eeprom_list") { auto ent_ = std::make_shared<Diag::Eeprom::EepromList>(); ent_->parent = this; eeprom_list.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Eeprom::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : eeprom_list.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Diag::Eeprom::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Diag::Eeprom::set_filter(const std::string & value_path, YFilter yfilter) { } bool Diag::Eeprom::has_leaf_or_child_of_name(const std::string & name) const { if(name == "eeprom_list") return true; return false; } Diag::Eeprom::EepromList::EepromList() : location{YType::str, "location"} , eeprom_data(std::make_shared<Diag::Eeprom::EepromList::EepromData>()) { eeprom_data->parent = this; yang_name = "eeprom_list"; yang_parent_name = "eeprom"; is_top_level_class = false; has_list_ancestor = false; } Diag::Eeprom::EepromList::~EepromList() { } bool Diag::Eeprom::EepromList::has_data() const { if (is_presence_container) return true; return location.is_set || (eeprom_data != nullptr && eeprom_data->has_data()); } bool Diag::Eeprom::EepromList::has_operation() const { return is_set(yfilter) || ydk::is_set(location.yfilter) || (eeprom_data != nullptr && eeprom_data->has_operation()); } std::string Diag::Eeprom::EepromList::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/eeprom/" << get_segment_path(); return path_buffer.str(); } std::string Diag::Eeprom::EepromList::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "eeprom_list"; ADD_KEY_TOKEN(location, "location"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::Eeprom::EepromList::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (location.is_set || is_set(location.yfilter)) leaf_name_data.push_back(location.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::Eeprom::EepromList::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "eeprom-data") { if(eeprom_data == nullptr) { eeprom_data = std::make_shared<Diag::Eeprom::EepromList::EepromData>(); } return eeprom_data; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Eeprom::EepromList::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(eeprom_data != nullptr) { _children["eeprom-data"] = eeprom_data; } return _children; } void Diag::Eeprom::EepromList::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "location") { location = value; location.value_namespace = name_space; location.value_namespace_prefix = name_space_prefix; } } void Diag::Eeprom::EepromList::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "location") { location.yfilter = yfilter; } } bool Diag::Eeprom::EepromList::has_leaf_or_child_of_name(const std::string & name) const { if(name == "eeprom-data" || name == "location") return true; return false; } Diag::Eeprom::EepromList::EepromData::EepromData() : raw_list{YType::str, "raw_list"} { yang_name = "eeprom-data"; yang_parent_name = "eeprom_list"; is_top_level_class = false; has_list_ancestor = true; } Diag::Eeprom::EepromList::EepromData::~EepromData() { } bool Diag::Eeprom::EepromList::EepromData::has_data() const { if (is_presence_container) return true; for (auto const & leaf : raw_list.getYLeafs()) { if(leaf.is_set) return true; } return false; } bool Diag::Eeprom::EepromList::EepromData::has_operation() const { for (auto const & leaf : raw_list.getYLeafs()) { if(is_set(leaf.yfilter)) return true; } return is_set(yfilter) || ydk::is_set(raw_list.yfilter); } std::string Diag::Eeprom::EepromList::EepromData::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "eeprom-data"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::Eeprom::EepromList::EepromData::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; auto raw_list_name_datas = raw_list.get_name_leafdata(); leaf_name_data.insert(leaf_name_data.end(), raw_list_name_datas.begin(), raw_list_name_datas.end()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::Eeprom::EepromList::EepromData::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Eeprom::EepromList::EepromData::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Diag::Eeprom::EepromList::EepromData::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "raw_list") { raw_list.append(value); } } void Diag::Eeprom::EepromList::EepromData::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "raw_list") { raw_list.yfilter = yfilter; } } bool Diag::Eeprom::EepromList::EepromData::has_leaf_or_child_of_name(const std::string & name) const { if(name == "raw_list") return true; return false; } Diag::Detail::Detail() : detail_list(this, {"location"}) { yang_name = "detail"; yang_parent_name = "diag"; is_top_level_class = false; has_list_ancestor = false; } Diag::Detail::~Detail() { } bool Diag::Detail::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<detail_list.len(); index++) { if(detail_list[index]->has_data()) return true; } return false; } bool Diag::Detail::has_operation() const { for (std::size_t index=0; index<detail_list.len(); index++) { if(detail_list[index]->has_operation()) return true; } return is_set(yfilter); } std::string Diag::Detail::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/" << get_segment_path(); return path_buffer.str(); } std::string Diag::Detail::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "detail"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::Detail::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::Detail::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "detail_list") { auto ent_ = std::make_shared<Diag::Detail::DetailList>(); ent_->parent = this; detail_list.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Detail::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : detail_list.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Diag::Detail::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Diag::Detail::set_filter(const std::string & value_path, YFilter yfilter) { } bool Diag::Detail::has_leaf_or_child_of_name(const std::string & name) const { if(name == "detail_list") return true; return false; } Diag::Detail::DetailList::DetailList() : location{YType::str, "location"} , detail_data(std::make_shared<Diag::Detail::DetailList::DetailData>()) { detail_data->parent = this; yang_name = "detail_list"; yang_parent_name = "detail"; is_top_level_class = false; has_list_ancestor = false; } Diag::Detail::DetailList::~DetailList() { } bool Diag::Detail::DetailList::has_data() const { if (is_presence_container) return true; return location.is_set || (detail_data != nullptr && detail_data->has_data()); } bool Diag::Detail::DetailList::has_operation() const { return is_set(yfilter) || ydk::is_set(location.yfilter) || (detail_data != nullptr && detail_data->has_operation()); } std::string Diag::Detail::DetailList::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/detail/" << get_segment_path(); return path_buffer.str(); } std::string Diag::Detail::DetailList::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "detail_list"; ADD_KEY_TOKEN(location, "location"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::Detail::DetailList::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (location.is_set || is_set(location.yfilter)) leaf_name_data.push_back(location.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::Detail::DetailList::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "detail-data") { if(detail_data == nullptr) { detail_data = std::make_shared<Diag::Detail::DetailList::DetailData>(); } return detail_data; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Detail::DetailList::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(detail_data != nullptr) { _children["detail-data"] = detail_data; } return _children; } void Diag::Detail::DetailList::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "location") { location = value; location.value_namespace = name_space; location.value_namespace_prefix = name_space_prefix; } } void Diag::Detail::DetailList::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "location") { location.yfilter = yfilter; } } bool Diag::Detail::DetailList::has_leaf_or_child_of_name(const std::string & name) const { if(name == "detail-data" || name == "location") return true; return false; } Diag::Detail::DetailList::DetailData::DetailData() : detail_out_list{YType::str, "detail_out_list"} { yang_name = "detail-data"; yang_parent_name = "detail_list"; is_top_level_class = false; has_list_ancestor = true; } Diag::Detail::DetailList::DetailData::~DetailData() { } bool Diag::Detail::DetailList::DetailData::has_data() const { if (is_presence_container) return true; for (auto const & leaf : detail_out_list.getYLeafs()) { if(leaf.is_set) return true; } return false; } bool Diag::Detail::DetailList::DetailData::has_operation() const { for (auto const & leaf : detail_out_list.getYLeafs()) { if(is_set(leaf.yfilter)) return true; } return is_set(yfilter) || ydk::is_set(detail_out_list.yfilter); } std::string Diag::Detail::DetailList::DetailData::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "detail-data"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Diag::Detail::DetailList::DetailData::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; auto detail_out_list_name_datas = detail_out_list.get_name_leafdata(); leaf_name_data.insert(leaf_name_data.end(), detail_out_list_name_datas.begin(), detail_out_list_name_datas.end()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Diag::Detail::DetailList::DetailData::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Detail::DetailList::DetailData::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Diag::Detail::DetailList::DetailData::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "detail_out_list") { detail_out_list.append(value); } } void Diag::Detail::DetailList::DetailData::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "detail_out_list") { detail_out_list.yfilter = yfilter; } } bool Diag::Detail::DetailList::DetailData::has_leaf_or_child_of_name(const std::string & name) const { if(name == "detail_out_list") return true; return false; } } }
27.165546
208
0.677337
CiscoDevNet
405834ee034967ffc7ca02159fc0ca568825fcd6
93,895
cpp
C++
src/systems/CollisionDetectionSystem.cpp
VaderY/reactphysics3d
6fe67640fbda3f7c0a50dc0fd88f4c940f9d9c7b
[ "Zlib" ]
null
null
null
src/systems/CollisionDetectionSystem.cpp
VaderY/reactphysics3d
6fe67640fbda3f7c0a50dc0fd88f4c940f9d9c7b
[ "Zlib" ]
null
null
null
src/systems/CollisionDetectionSystem.cpp
VaderY/reactphysics3d
6fe67640fbda3f7c0a50dc0fd88f4c940f9d9c7b
[ "Zlib" ]
null
null
null
/******************************************************************************** * ReactPhysics3D physics library, http://www.reactphysics3d.com * * Copyright (c) 2010-2020 Daniel Chappuis * ********************************************************************************* * * * This software is provided 'as-is', without any express or implied warranty. * * In no event will the authors be held liable for any damages arising from the * * use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not claim * * that you wrote the original software. If you use this software in a * * product, an acknowledgment in the product documentation would be * * appreciated but is not required. * * * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * * * 3. This notice may not be removed or altered from any source distribution. * * * ********************************************************************************/ // Libraries #include <reactphysics3d/systems/CollisionDetectionSystem.h> #include <reactphysics3d/engine/PhysicsWorld.h> #include <reactphysics3d/collision/OverlapCallback.h> #include <reactphysics3d/collision/shapes/BoxShape.h> #include <reactphysics3d/collision/shapes/ConcaveShape.h> #include <reactphysics3d/collision/ContactManifoldInfo.h> #include <reactphysics3d/constraint/ContactPoint.h> #include <reactphysics3d/body/RigidBody.h> #include <reactphysics3d/configuration.h> #include <reactphysics3d/collision/CollisionCallback.h> #include <reactphysics3d/collision/OverlapCallback.h> #include <reactphysics3d/collision/narrowphase/NarrowPhaseInfoBatch.h> #include <reactphysics3d/collision/ContactManifold.h> #include <reactphysics3d/utils/Profiler.h> #include <reactphysics3d/engine/EventListener.h> #include <reactphysics3d/collision/RaycastInfo.h> #include <reactphysics3d/containers/Pair.h> #include <cassert> #include <iostream> // We want to use the ReactPhysics3D namespace using namespace reactphysics3d; using namespace std; // Constructor CollisionDetectionSystem::CollisionDetectionSystem(PhysicsWorld* world, ColliderComponents& collidersComponents, TransformComponents& transformComponents, CollisionBodyComponents& collisionBodyComponents, RigidBodyComponents& rigidBodyComponents, MemoryManager& memoryManager, HalfEdgeStructure& triangleHalfEdgeStructure) : mMemoryManager(memoryManager), mCollidersComponents(collidersComponents), mRigidBodyComponents(rigidBodyComponents), mCollisionDispatch(mMemoryManager.getPoolAllocator()), mWorld(world), mNoCollisionPairs(mMemoryManager.getPoolAllocator()), mOverlappingPairs(mMemoryManager, mCollidersComponents, collisionBodyComponents, rigidBodyComponents, mNoCollisionPairs, mCollisionDispatch), mBroadPhaseOverlappingNodes(mMemoryManager.getHeapAllocator(), 32), mBroadPhaseSystem(*this, mCollidersComponents, transformComponents, rigidBodyComponents), mMapBroadPhaseIdToColliderEntity(memoryManager.getPoolAllocator()), mNarrowPhaseInput(mMemoryManager.getSingleFrameAllocator(), mOverlappingPairs), mPotentialContactPoints(mMemoryManager.getSingleFrameAllocator()), mPotentialContactManifolds(mMemoryManager.getSingleFrameAllocator()), mContactPairs1(mMemoryManager.getPoolAllocator()), mContactPairs2(mMemoryManager.getPoolAllocator()), mPreviousContactPairs(&mContactPairs1), mCurrentContactPairs(&mContactPairs2), mLostContactPairs(mMemoryManager.getSingleFrameAllocator()), mPreviousMapPairIdToContactPairIndex(mMemoryManager.getHeapAllocator()), mContactManifolds1(mMemoryManager.getPoolAllocator()), mContactManifolds2(mMemoryManager.getPoolAllocator()), mPreviousContactManifolds(&mContactManifolds1), mCurrentContactManifolds(&mContactManifolds2), mContactPoints1(mMemoryManager.getPoolAllocator()), mContactPoints2(mMemoryManager.getPoolAllocator()), mPreviousContactPoints(&mContactPoints1), mCurrentContactPoints(&mContactPoints2), mCollisionBodyContactPairsIndices(mMemoryManager.getSingleFrameAllocator()), mNbPreviousPotentialContactManifolds(0), mNbPreviousPotentialContactPoints(0), mTriangleHalfEdgeStructure(triangleHalfEdgeStructure) { #ifdef IS_RP3D_PROFILING_ENABLED mProfiler = nullptr; mCollisionDispatch.setProfiler(mProfiler); mOverlappingPairs.setProfiler(mProfiler); #endif } // Compute the collision detection void CollisionDetectionSystem::computeCollisionDetection() { RP3D_PROFILE("CollisionDetectionSystem::computeCollisionDetection()", mProfiler); // Compute the broad-phase collision detection computeBroadPhase(); // Compute the middle-phase collision detection computeMiddlePhase(mNarrowPhaseInput, true); // Compute the narrow-phase collision detection computeNarrowPhase(); } // Compute the broad-phase collision detection void CollisionDetectionSystem::computeBroadPhase() { RP3D_PROFILE("CollisionDetectionSystem::computeBroadPhase()", mProfiler); assert(mBroadPhaseOverlappingNodes.size() == 0); // Ask the broad-phase to compute all the shapes overlapping with the shapes that // have moved or have been added in the last frame. This call can only add new // overlapping pairs in the collision detection. mBroadPhaseSystem.computeOverlappingPairs(mMemoryManager, mBroadPhaseOverlappingNodes); // Create new overlapping pairs if necessary updateOverlappingPairs(mBroadPhaseOverlappingNodes); // Remove non overlapping pairs removeNonOverlappingPairs(); mBroadPhaseOverlappingNodes.clear(); } // Remove pairs that are not overlapping anymore void CollisionDetectionSystem::removeNonOverlappingPairs() { RP3D_PROFILE("CollisionDetectionSystem::removeNonOverlappingPairs()", mProfiler); // For each convex pairs for (uint64 i=0; i < mOverlappingPairs.mConvexPairs.size(); i++) { OverlappingPairs::ConvexOverlappingPair& overlappingPair = mOverlappingPairs.mConvexPairs[i]; // Check if we need to test overlap. If so, test if the two shapes are still overlapping. // Otherwise, we destroy the overlapping pair if (overlappingPair.needToTestOverlap) { if(mBroadPhaseSystem.testOverlappingShapes(overlappingPair.broadPhaseId1, overlappingPair.broadPhaseId2)) { overlappingPair.needToTestOverlap = false; } else { // If the two colliders of the pair were colliding in the previous frame if (overlappingPair.collidingInPreviousFrame) { // Create a new lost contact pair addLostContactPair(overlappingPair); } mOverlappingPairs.removePair(i, true); i--; } } } // For each concave pairs for (uint64 i=0; i < mOverlappingPairs.mConcavePairs.size(); i++) { OverlappingPairs::ConcaveOverlappingPair& overlappingPair = mOverlappingPairs.mConcavePairs[i]; // Check if we need to test overlap. If so, test if the two shapes are still overlapping. // Otherwise, we destroy the overlapping pair if (overlappingPair.needToTestOverlap) { if(mBroadPhaseSystem.testOverlappingShapes(overlappingPair.broadPhaseId1, overlappingPair.broadPhaseId2)) { overlappingPair.needToTestOverlap = false; } else { // If the two colliders of the pair were colliding in the previous frame if (overlappingPair.collidingInPreviousFrame) { // Create a new lost contact pair addLostContactPair(overlappingPair); } mOverlappingPairs.removePair(i, false); i--; } } } } // Add a lost contact pair (pair of colliders that are not in contact anymore) void CollisionDetectionSystem::addLostContactPair(OverlappingPairs::OverlappingPair& overlappingPair) { const uint32 collider1Index = mCollidersComponents.getEntityIndex(overlappingPair.collider1); const uint32 collider2Index = mCollidersComponents.getEntityIndex(overlappingPair.collider2); const Entity body1Entity = mCollidersComponents.mBodiesEntities[collider1Index]; const Entity body2Entity = mCollidersComponents.mBodiesEntities[collider2Index]; const bool isCollider1Trigger = mCollidersComponents.mIsTrigger[collider1Index]; const bool isCollider2Trigger = mCollidersComponents.mIsTrigger[collider2Index]; const bool isTrigger = isCollider1Trigger || isCollider2Trigger; // Create a lost contact pair ContactPair lostContactPair(overlappingPair.pairID, body1Entity, body2Entity, overlappingPair.collider1, overlappingPair.collider2, mLostContactPairs.size(), true, isTrigger, mMemoryManager.getHeapAllocator()); mLostContactPairs.add(lostContactPair); } // Take an array of overlapping nodes in the broad-phase and create new overlapping pairs if necessary void CollisionDetectionSystem::updateOverlappingPairs(const Array<Pair<int32, int32>>& overlappingNodes) { RP3D_PROFILE("CollisionDetectionSystem::updateOverlappingPairs()", mProfiler); // For each overlapping pair of nodes const uint32 nbOverlappingNodes = overlappingNodes.size(); for (uint32 i=0; i < nbOverlappingNodes; i++) { Pair<int32, int32> nodePair = overlappingNodes[i]; assert(nodePair.first != -1); assert(nodePair.second != -1); // Skip pairs with same overlapping nodes if (nodePair.first != nodePair.second) { // Get the two colliders const Entity collider1Entity = mMapBroadPhaseIdToColliderEntity[nodePair.first]; const Entity collider2Entity = mMapBroadPhaseIdToColliderEntity[nodePair.second]; const uint collider1Index = mCollidersComponents.getEntityIndex(collider1Entity); const uint collider2Index = mCollidersComponents.getEntityIndex(collider2Entity); // Get the two bodies const Entity body1Entity = mCollidersComponents.mBodiesEntities[collider1Index]; const Entity body2Entity = mCollidersComponents.mBodiesEntities[collider2Index]; // If the two colliders are from the same body, skip it if (body1Entity != body2Entity) { const uint32 nbEnabledColliderComponents = mCollidersComponents.getNbEnabledComponents(); const bool isBody1Enabled = collider1Index < nbEnabledColliderComponents; const bool isBody2Enabled = collider2Index < nbEnabledColliderComponents; bool isBody1Static = false; bool isBody2Static = false; uint32 rigidBody1Index, rigidBody2Index; if (mRigidBodyComponents.hasComponentGetIndex(body1Entity, rigidBody1Index)) { isBody1Static = mRigidBodyComponents.mBodyTypes[rigidBody1Index] == BodyType::STATIC; } if (mRigidBodyComponents.hasComponentGetIndex(body2Entity, rigidBody2Index)) { isBody2Static = mRigidBodyComponents.mBodyTypes[rigidBody2Index] == BodyType::STATIC; } const bool isBody1Active = isBody1Enabled && !isBody1Static; const bool isBody2Active = isBody2Enabled && !isBody2Static; if (isBody1Active || isBody2Active) { // Check if the bodies are in the set of bodies that cannot collide between each other // TODO OPTI : What not use the pairId here ?? const bodypair bodiesIndex = OverlappingPairs::computeBodiesIndexPair(body1Entity, body2Entity); if (!mNoCollisionPairs.contains(bodiesIndex)) { // Compute the overlapping pair ID const uint64 pairId = pairNumbers(std::max(nodePair.first, nodePair.second), std::min(nodePair.first, nodePair.second)); // Check if the overlapping pair already exists OverlappingPairs::OverlappingPair* overlappingPair = mOverlappingPairs.getOverlappingPair(pairId); if (overlappingPair == nullptr) { const unsigned short shape1CollideWithMaskBits = mCollidersComponents.mCollideWithMaskBits[collider1Index]; const unsigned short shape2CollideWithMaskBits = mCollidersComponents.mCollideWithMaskBits[collider2Index]; const unsigned short shape1CollisionCategoryBits = mCollidersComponents.mCollisionCategoryBits[collider1Index]; const unsigned short shape2CollisionCategoryBits = mCollidersComponents.mCollisionCategoryBits[collider2Index]; // Check if the collision filtering allows collision between the two shapes if ((shape1CollideWithMaskBits & shape2CollisionCategoryBits) != 0 && (shape1CollisionCategoryBits & shape2CollideWithMaskBits) != 0) { Collider* shape1 = mCollidersComponents.mColliders[collider1Index]; Collider* shape2 = mCollidersComponents.mColliders[collider2Index]; // Check that at least one collision shape is convex const bool isShape1Convex = shape1->getCollisionShape()->isConvex(); const bool isShape2Convex = shape2->getCollisionShape()->isConvex(); if (isShape1Convex || isShape2Convex) { // Add the new overlapping pair mOverlappingPairs.addPair(collider1Index, collider2Index, isShape1Convex && isShape2Convex); } } } else { // We do not need to test the pair for overlap because it has just been reported that they still overlap overlappingPair->needToTestOverlap = false; } } } } } } } // Compute the middle-phase collision detection void CollisionDetectionSystem::computeMiddlePhase(NarrowPhaseInput& narrowPhaseInput, bool needToReportContacts) { RP3D_PROFILE("CollisionDetectionSystem::computeMiddlePhase()", mProfiler); // Reserve memory for the narrow-phase input using cached capacity from previous frame narrowPhaseInput.reserveMemory(); // Remove the obsolete last frame collision infos and mark all the others as obsolete mOverlappingPairs.clearObsoleteLastFrameCollisionInfos(); // For each possible convex vs convex pair of bodies const uint64 nbConvexVsConvexPairs = mOverlappingPairs.mConvexPairs.size(); for (uint64 i=0; i < nbConvexVsConvexPairs; i++) { OverlappingPairs::ConvexOverlappingPair& overlappingPair = mOverlappingPairs.mConvexPairs[i]; assert(mCollidersComponents.getBroadPhaseId(overlappingPair.collider1) != -1); assert(mCollidersComponents.getBroadPhaseId(overlappingPair.collider2) != -1); assert(mCollidersComponents.getBroadPhaseId(overlappingPair.collider1) != mCollidersComponents.getBroadPhaseId(overlappingPair.collider2)); const Entity collider1Entity = overlappingPair.collider1; const Entity collider2Entity = overlappingPair.collider2; const uint collider1Index = mCollidersComponents.getEntityIndex(collider1Entity); const uint collider2Index = mCollidersComponents.getEntityIndex(collider2Entity); CollisionShape* collisionShape1 = mCollidersComponents.mCollisionShapes[collider1Index]; CollisionShape* collisionShape2 = mCollidersComponents.mCollisionShapes[collider2Index]; NarrowPhaseAlgorithmType algorithmType = overlappingPair.narrowPhaseAlgorithmType; const bool isCollider1Trigger = mCollidersComponents.mIsTrigger[collider1Index]; const bool isCollider2Trigger = mCollidersComponents.mIsTrigger[collider2Index]; const bool reportContacts = needToReportContacts && !isCollider1Trigger && !isCollider2Trigger; // No middle-phase is necessary, simply create a narrow phase info // for the narrow-phase collision detection narrowPhaseInput.addNarrowPhaseTest(overlappingPair.pairID, collider1Entity, collider2Entity, collisionShape1, collisionShape2, mCollidersComponents.mLocalToWorldTransforms[collider1Index], mCollidersComponents.mLocalToWorldTransforms[collider2Index], algorithmType, reportContacts, &overlappingPair.lastFrameCollisionInfo, mMemoryManager.getSingleFrameAllocator()); overlappingPair.collidingInCurrentFrame = false; } // For each possible convex vs concave pair of bodies const uint64 nbConcavePairs = mOverlappingPairs.mConcavePairs.size(); for (uint64 i=0; i < nbConcavePairs; i++) { OverlappingPairs::ConcaveOverlappingPair& overlappingPair = mOverlappingPairs.mConcavePairs[i]; assert(mCollidersComponents.getBroadPhaseId(overlappingPair.collider1) != -1); assert(mCollidersComponents.getBroadPhaseId(overlappingPair.collider2) != -1); assert(mCollidersComponents.getBroadPhaseId(overlappingPair.collider1) != mCollidersComponents.getBroadPhaseId(overlappingPair.collider2)); computeConvexVsConcaveMiddlePhase(overlappingPair, mMemoryManager.getSingleFrameAllocator(), narrowPhaseInput, needToReportContacts); overlappingPair.collidingInCurrentFrame = false; } } // Compute the middle-phase collision detection void CollisionDetectionSystem::computeMiddlePhaseCollisionSnapshot(Array<uint64>& convexPairs, Array<uint64>& concavePairs, NarrowPhaseInput& narrowPhaseInput, bool reportContacts) { RP3D_PROFILE("CollisionDetectionSystem::computeMiddlePhase()", mProfiler); // Reserve memory for the narrow-phase input using cached capacity from previous frame narrowPhaseInput.reserveMemory(); // Remove the obsolete last frame collision infos and mark all the others as obsolete mOverlappingPairs.clearObsoleteLastFrameCollisionInfos(); // For each possible convex vs convex pair of bodies const uint64 nbConvexPairs = convexPairs.size(); for (uint64 p=0; p < nbConvexPairs; p++) { const uint64 pairId = convexPairs[p]; const uint64 pairIndex = mOverlappingPairs.mMapConvexPairIdToPairIndex[pairId]; assert(pairIndex < mOverlappingPairs.mConvexPairs.size()); const Entity collider1Entity = mOverlappingPairs.mConvexPairs[pairIndex].collider1; const Entity collider2Entity = mOverlappingPairs.mConvexPairs[pairIndex].collider2; const uint collider1Index = mCollidersComponents.getEntityIndex(collider1Entity); const uint collider2Index = mCollidersComponents.getEntityIndex(collider2Entity); assert(mCollidersComponents.getBroadPhaseId(collider1Entity) != -1); assert(mCollidersComponents.getBroadPhaseId(collider2Entity) != -1); assert(mCollidersComponents.getBroadPhaseId(collider1Entity) != mCollidersComponents.getBroadPhaseId(collider2Entity)); CollisionShape* collisionShape1 = mCollidersComponents.mCollisionShapes[collider1Index]; CollisionShape* collisionShape2 = mCollidersComponents.mCollisionShapes[collider2Index]; NarrowPhaseAlgorithmType algorithmType = mOverlappingPairs.mConvexPairs[pairIndex].narrowPhaseAlgorithmType; // No middle-phase is necessary, simply create a narrow phase info // for the narrow-phase collision detection narrowPhaseInput.addNarrowPhaseTest(pairId, collider1Entity, collider2Entity, collisionShape1, collisionShape2, mCollidersComponents.mLocalToWorldTransforms[collider1Index], mCollidersComponents.mLocalToWorldTransforms[collider2Index], algorithmType, reportContacts, &mOverlappingPairs.mConvexPairs[pairIndex].lastFrameCollisionInfo, mMemoryManager.getSingleFrameAllocator()); } // For each possible convex vs concave pair of bodies const uint nbConcavePairs = concavePairs.size(); for (uint p=0; p < nbConcavePairs; p++) { const uint64 pairId = concavePairs[p]; const uint64 pairIndex = mOverlappingPairs.mMapConcavePairIdToPairIndex[pairId]; assert(mCollidersComponents.getBroadPhaseId(mOverlappingPairs.mConcavePairs[pairIndex].collider1) != -1); assert(mCollidersComponents.getBroadPhaseId(mOverlappingPairs.mConcavePairs[pairIndex].collider2) != -1); assert(mCollidersComponents.getBroadPhaseId(mOverlappingPairs.mConcavePairs[pairIndex].collider1) != mCollidersComponents.getBroadPhaseId(mOverlappingPairs.mConcavePairs[pairIndex].collider2)); computeConvexVsConcaveMiddlePhase(mOverlappingPairs.mConcavePairs[pairIndex], mMemoryManager.getSingleFrameAllocator(), narrowPhaseInput, reportContacts); } } // Compute the concave vs convex middle-phase algorithm for a given pair of bodies void CollisionDetectionSystem::computeConvexVsConcaveMiddlePhase(OverlappingPairs::ConcaveOverlappingPair& overlappingPair, MemoryAllocator& allocator, NarrowPhaseInput& narrowPhaseInput, bool reportContacts) { RP3D_PROFILE("CollisionDetectionSystem::computeConvexVsConcaveMiddlePhase()", mProfiler); const Entity collider1 = overlappingPair.collider1; const Entity collider2 = overlappingPair.collider2; const uint collider1Index = mCollidersComponents.getEntityIndex(collider1); const uint collider2Index = mCollidersComponents.getEntityIndex(collider2); Transform& shape1LocalToWorldTransform = mCollidersComponents.mLocalToWorldTransforms[collider1Index]; Transform& shape2LocalToWorldTransform = mCollidersComponents.mLocalToWorldTransforms[collider2Index]; Transform convexToConcaveTransform; // Collision shape 1 is convex, collision shape 2 is concave ConvexShape* convexShape; ConcaveShape* concaveShape; if (overlappingPair.isShape1Convex) { convexShape = static_cast<ConvexShape*>(mCollidersComponents.mCollisionShapes[collider1Index]); concaveShape = static_cast<ConcaveShape*>(mCollidersComponents.mCollisionShapes[collider2Index]); convexToConcaveTransform = shape2LocalToWorldTransform.getInverse() * shape1LocalToWorldTransform; } else { // Collision shape 2 is convex, collision shape 1 is concave convexShape = static_cast<ConvexShape*>(mCollidersComponents.mCollisionShapes[collider2Index]); concaveShape = static_cast<ConcaveShape*>(mCollidersComponents.mCollisionShapes[collider1Index]); convexToConcaveTransform = shape1LocalToWorldTransform.getInverse() * shape2LocalToWorldTransform; } assert(convexShape->isConvex()); assert(!concaveShape->isConvex()); assert(overlappingPair.narrowPhaseAlgorithmType != NarrowPhaseAlgorithmType::None); // Compute the convex shape AABB in the local-space of the convex shape AABB aabb; convexShape->computeAABB(aabb, convexToConcaveTransform); // Compute the concave shape triangles that are overlapping with the convex mesh AABB Array<Vector3> triangleVertices(allocator, 64); Array<Vector3> triangleVerticesNormals(allocator, 64); Array<uint> shapeIds(allocator, 64); concaveShape->computeOverlappingTriangles(aabb, triangleVertices, triangleVerticesNormals, shapeIds, allocator); assert(triangleVertices.size() == triangleVerticesNormals.size()); assert(shapeIds.size() == triangleVertices.size() / 3); assert(triangleVertices.size() % 3 == 0); assert(triangleVerticesNormals.size() % 3 == 0); const bool isCollider1Trigger = mCollidersComponents.mIsTrigger[collider1Index]; const bool isCollider2Trigger = mCollidersComponents.mIsTrigger[collider2Index]; reportContacts = reportContacts && !isCollider1Trigger && !isCollider2Trigger; CollisionShape* shape1; CollisionShape* shape2; if (overlappingPair.isShape1Convex) { shape1 = convexShape; } else { shape2 = convexShape; } // For each overlapping triangle const uint32 nbShapeIds = shapeIds.size(); for (uint32 i=0; i < nbShapeIds; i++) { // Create a triangle collision shape (the allocated memory for the TriangleShape will be released in the // destructor of the corresponding NarrowPhaseInfo. TriangleShape* triangleShape = new (allocator.allocate(sizeof(TriangleShape))) TriangleShape(&(triangleVertices[i * 3]), &(triangleVerticesNormals[i * 3]), shapeIds[i], mTriangleHalfEdgeStructure, allocator); #ifdef IS_RP3D_PROFILING_ENABLED // Set the profiler to the triangle shape triangleShape->setProfiler(mProfiler); #endif if (overlappingPair.isShape1Convex) { shape2 = triangleShape; } else { shape1 = triangleShape; } // Add a collision info for the two collision shapes into the overlapping pair (if not present yet) LastFrameCollisionInfo* lastFrameInfo = overlappingPair.addLastFrameInfoIfNecessary(shape1->getId(), shape2->getId()); // Create a narrow phase info for the narrow-phase collision detection narrowPhaseInput.addNarrowPhaseTest(overlappingPair.pairID, collider1, collider2, shape1, shape2, shape1LocalToWorldTransform, shape2LocalToWorldTransform, overlappingPair.narrowPhaseAlgorithmType, reportContacts, lastFrameInfo, allocator); } } // Execute the narrow-phase collision detection algorithm on batches bool CollisionDetectionSystem::testNarrowPhaseCollision(NarrowPhaseInput& narrowPhaseInput, bool clipWithPreviousAxisIfStillColliding, MemoryAllocator& allocator) { bool contactFound = false; // Get the narrow-phase collision detection algorithms for each kind of collision shapes SphereVsSphereAlgorithm* sphereVsSphereAlgo = mCollisionDispatch.getSphereVsSphereAlgorithm(); SphereVsCapsuleAlgorithm* sphereVsCapsuleAlgo = mCollisionDispatch.getSphereVsCapsuleAlgorithm(); CapsuleVsCapsuleAlgorithm* capsuleVsCapsuleAlgo = mCollisionDispatch.getCapsuleVsCapsuleAlgorithm(); SphereVsConvexPolyhedronAlgorithm* sphereVsConvexPolyAlgo = mCollisionDispatch.getSphereVsConvexPolyhedronAlgorithm(); CapsuleVsConvexPolyhedronAlgorithm* capsuleVsConvexPolyAlgo = mCollisionDispatch.getCapsuleVsConvexPolyhedronAlgorithm(); ConvexPolyhedronVsConvexPolyhedronAlgorithm* convexPolyVsConvexPolyAlgo = mCollisionDispatch.getConvexPolyhedronVsConvexPolyhedronAlgorithm(); // get the narrow-phase batches to test for collision for contacts NarrowPhaseInfoBatch& sphereVsSphereBatchContacts = narrowPhaseInput.getSphereVsSphereBatch(); NarrowPhaseInfoBatch& sphereVsCapsuleBatchContacts = narrowPhaseInput.getSphereVsCapsuleBatch(); NarrowPhaseInfoBatch& capsuleVsCapsuleBatchContacts = narrowPhaseInput.getCapsuleVsCapsuleBatch(); NarrowPhaseInfoBatch& sphereVsConvexPolyhedronBatchContacts = narrowPhaseInput.getSphereVsConvexPolyhedronBatch(); NarrowPhaseInfoBatch& capsuleVsConvexPolyhedronBatchContacts = narrowPhaseInput.getCapsuleVsConvexPolyhedronBatch(); NarrowPhaseInfoBatch& convexPolyhedronVsConvexPolyhedronBatchContacts = narrowPhaseInput.getConvexPolyhedronVsConvexPolyhedronBatch(); // Compute the narrow-phase collision detection for each kind of collision shapes (for contacts) if (sphereVsSphereBatchContacts.getNbObjects() > 0) { contactFound |= sphereVsSphereAlgo->testCollision(sphereVsSphereBatchContacts, 0, sphereVsSphereBatchContacts.getNbObjects(), allocator); } if (sphereVsCapsuleBatchContacts.getNbObjects() > 0) { contactFound |= sphereVsCapsuleAlgo->testCollision(sphereVsCapsuleBatchContacts, 0, sphereVsCapsuleBatchContacts.getNbObjects(), allocator); } if (capsuleVsCapsuleBatchContacts.getNbObjects() > 0) { contactFound |= capsuleVsCapsuleAlgo->testCollision(capsuleVsCapsuleBatchContacts, 0, capsuleVsCapsuleBatchContacts.getNbObjects(), allocator); } if (sphereVsConvexPolyhedronBatchContacts.getNbObjects() > 0) { contactFound |= sphereVsConvexPolyAlgo->testCollision(sphereVsConvexPolyhedronBatchContacts, 0, sphereVsConvexPolyhedronBatchContacts.getNbObjects(), clipWithPreviousAxisIfStillColliding, allocator); } if (capsuleVsConvexPolyhedronBatchContacts.getNbObjects() > 0) { contactFound |= capsuleVsConvexPolyAlgo->testCollision(capsuleVsConvexPolyhedronBatchContacts, 0, capsuleVsConvexPolyhedronBatchContacts.getNbObjects(), clipWithPreviousAxisIfStillColliding, allocator); } if (convexPolyhedronVsConvexPolyhedronBatchContacts.getNbObjects() > 0) { contactFound |= convexPolyVsConvexPolyAlgo->testCollision(convexPolyhedronVsConvexPolyhedronBatchContacts, 0, convexPolyhedronVsConvexPolyhedronBatchContacts.getNbObjects(), clipWithPreviousAxisIfStillColliding, allocator); } return contactFound; } // Process the potential contacts after narrow-phase collision detection void CollisionDetectionSystem::processAllPotentialContacts(NarrowPhaseInput& narrowPhaseInput, bool updateLastFrameInfo, Array<ContactPointInfo>& potentialContactPoints, Array<ContactManifoldInfo>& potentialContactManifolds, Array<ContactPair>* contactPairs) { assert(contactPairs->size() == 0); Map<uint64, uint> mapPairIdToContactPairIndex(mMemoryManager.getHeapAllocator(), mPreviousMapPairIdToContactPairIndex.size()); // get the narrow-phase batches to test for collision NarrowPhaseInfoBatch& sphereVsSphereBatch = narrowPhaseInput.getSphereVsSphereBatch(); NarrowPhaseInfoBatch& sphereVsCapsuleBatch = narrowPhaseInput.getSphereVsCapsuleBatch(); NarrowPhaseInfoBatch& capsuleVsCapsuleBatch = narrowPhaseInput.getCapsuleVsCapsuleBatch(); NarrowPhaseInfoBatch& sphereVsConvexPolyhedronBatch = narrowPhaseInput.getSphereVsConvexPolyhedronBatch(); NarrowPhaseInfoBatch& capsuleVsConvexPolyhedronBatch = narrowPhaseInput.getCapsuleVsConvexPolyhedronBatch(); NarrowPhaseInfoBatch& convexPolyhedronVsConvexPolyhedronBatch = narrowPhaseInput.getConvexPolyhedronVsConvexPolyhedronBatch(); // Process the potential contacts processPotentialContacts(sphereVsSphereBatch, updateLastFrameInfo, potentialContactPoints, potentialContactManifolds, mapPairIdToContactPairIndex, contactPairs); processPotentialContacts(sphereVsCapsuleBatch, updateLastFrameInfo, potentialContactPoints, potentialContactManifolds, mapPairIdToContactPairIndex, contactPairs); processPotentialContacts(capsuleVsCapsuleBatch, updateLastFrameInfo, potentialContactPoints, potentialContactManifolds, mapPairIdToContactPairIndex, contactPairs); processPotentialContacts(sphereVsConvexPolyhedronBatch, updateLastFrameInfo, potentialContactPoints, potentialContactManifolds, mapPairIdToContactPairIndex, contactPairs); processPotentialContacts(capsuleVsConvexPolyhedronBatch, updateLastFrameInfo, potentialContactPoints, potentialContactManifolds, mapPairIdToContactPairIndex, contactPairs); processPotentialContacts(convexPolyhedronVsConvexPolyhedronBatch, updateLastFrameInfo, potentialContactPoints, potentialContactManifolds, mapPairIdToContactPairIndex, contactPairs); } // Compute the narrow-phase collision detection void CollisionDetectionSystem::computeNarrowPhase() { RP3D_PROFILE("CollisionDetectionSystem::computeNarrowPhase()", mProfiler); MemoryAllocator& allocator = mMemoryManager.getSingleFrameAllocator(); // Swap the previous and current contacts arrays swapPreviousAndCurrentContacts(); mPotentialContactManifolds.reserve(mNbPreviousPotentialContactManifolds); mPotentialContactPoints.reserve(mNbPreviousPotentialContactPoints); // Test the narrow-phase collision detection on the batches to be tested testNarrowPhaseCollision(mNarrowPhaseInput, true, allocator); // Process all the potential contacts after narrow-phase collision processAllPotentialContacts(mNarrowPhaseInput, true, mPotentialContactPoints, mPotentialContactManifolds, mCurrentContactPairs); // Reduce the number of contact points in the manifolds reducePotentialContactManifolds(mCurrentContactPairs, mPotentialContactManifolds, mPotentialContactPoints); // Add the contact pairs to the bodies addContactPairsToBodies(); assert(mCurrentContactManifolds->size() == 0); assert(mCurrentContactPoints->size() == 0); } // Add the contact pairs to the corresponding bodies void CollisionDetectionSystem::addContactPairsToBodies() { const uint32 nbContactPairs = mCurrentContactPairs->size(); for (uint32 p=0 ; p < nbContactPairs; p++) { ContactPair& contactPair = (*mCurrentContactPairs)[p]; const bool isBody1Rigid = mRigidBodyComponents.hasComponent(contactPair.body1Entity); const bool isBody2Rigid = mRigidBodyComponents.hasComponent(contactPair.body2Entity); // Add the associated contact pair to both bodies of the pair (used to create islands later) if (isBody1Rigid) { mRigidBodyComponents.addContacPair(contactPair.body1Entity, p); } if (isBody2Rigid) { mRigidBodyComponents.addContacPair(contactPair.body2Entity, p); } // If at least of body is a CollisionBody if (!isBody1Rigid || !isBody2Rigid) { // Add the pair index to the array of pairs with CollisionBody mCollisionBodyContactPairsIndices.add(p); } } } // Compute the map from contact pairs ids to contact pair for the next frame void CollisionDetectionSystem::computeMapPreviousContactPairs() { mPreviousMapPairIdToContactPairIndex.clear(); const uint32 nbCurrentContactPairs = mCurrentContactPairs->size(); for (uint32 i=0; i < nbCurrentContactPairs; i++) { mPreviousMapPairIdToContactPairIndex.add(Pair<uint64, uint>((*mCurrentContactPairs)[i].pairId, i)); } } // Compute the narrow-phase collision detection for the testOverlap() methods. /// This method returns true if contacts are found. bool CollisionDetectionSystem::computeNarrowPhaseOverlapSnapshot(NarrowPhaseInput& narrowPhaseInput, OverlapCallback* callback) { RP3D_PROFILE("CollisionDetectionSystem::computeNarrowPhaseOverlapSnapshot()", mProfiler); MemoryAllocator& allocator = mMemoryManager.getPoolAllocator(); // Test the narrow-phase collision detection on the batches to be tested bool collisionFound = testNarrowPhaseCollision(narrowPhaseInput, false, allocator); if (collisionFound && callback != nullptr) { // Compute the overlapping colliders Array<ContactPair> contactPairs(allocator); Array<ContactPair> lostContactPairs(allocator); // Always empty in this case (snapshot) computeOverlapSnapshotContactPairs(narrowPhaseInput, contactPairs); // Report overlapping colliders OverlapCallback::CallbackData callbackData(contactPairs, lostContactPairs, false, *mWorld); (*callback).onOverlap(callbackData); } return collisionFound; } // Process the potential overlapping bodies for the testOverlap() methods void CollisionDetectionSystem::computeOverlapSnapshotContactPairs(NarrowPhaseInput& narrowPhaseInput, Array<ContactPair>& contactPairs) const { Set<uint64> setOverlapContactPairId(mMemoryManager.getHeapAllocator()); // get the narrow-phase batches to test for collision NarrowPhaseInfoBatch& sphereVsSphereBatch = narrowPhaseInput.getSphereVsSphereBatch(); NarrowPhaseInfoBatch& sphereVsCapsuleBatch = narrowPhaseInput.getSphereVsCapsuleBatch(); NarrowPhaseInfoBatch& capsuleVsCapsuleBatch = narrowPhaseInput.getCapsuleVsCapsuleBatch(); NarrowPhaseInfoBatch& sphereVsConvexPolyhedronBatch = narrowPhaseInput.getSphereVsConvexPolyhedronBatch(); NarrowPhaseInfoBatch& capsuleVsConvexPolyhedronBatch = narrowPhaseInput.getCapsuleVsConvexPolyhedronBatch(); NarrowPhaseInfoBatch& convexPolyhedronVsConvexPolyhedronBatch = narrowPhaseInput.getConvexPolyhedronVsConvexPolyhedronBatch(); // Process the potential contacts computeOverlapSnapshotContactPairs(sphereVsSphereBatch, contactPairs, setOverlapContactPairId); computeOverlapSnapshotContactPairs(sphereVsCapsuleBatch, contactPairs, setOverlapContactPairId); computeOverlapSnapshotContactPairs(capsuleVsCapsuleBatch, contactPairs, setOverlapContactPairId); computeOverlapSnapshotContactPairs(sphereVsConvexPolyhedronBatch, contactPairs, setOverlapContactPairId); computeOverlapSnapshotContactPairs(capsuleVsConvexPolyhedronBatch, contactPairs, setOverlapContactPairId); computeOverlapSnapshotContactPairs(convexPolyhedronVsConvexPolyhedronBatch, contactPairs, setOverlapContactPairId); } // Notify that the overlapping pairs where a given collider is involved need to be tested for overlap void CollisionDetectionSystem::notifyOverlappingPairsToTestOverlap(Collider* collider) { // Get the overlapping pairs involved with this collider Array<uint64>& overlappingPairs = mCollidersComponents.getOverlappingPairs(collider->getEntity()); const uint32 nbPairs = overlappingPairs.size(); for (uint32 i=0; i < nbPairs; i++) { // Notify that the overlapping pair needs to be testbed for overlap mOverlappingPairs.setNeedToTestOverlap(overlappingPairs[i], true); } } // Convert the potential overlapping bodies for the testOverlap() methods void CollisionDetectionSystem::computeOverlapSnapshotContactPairs(NarrowPhaseInfoBatch& narrowPhaseInfoBatch, Array<ContactPair>& contactPairs, Set<uint64>& setOverlapContactPairId) const { RP3D_PROFILE("CollisionDetectionSystem::computeSnapshotContactPairs()", mProfiler); // For each narrow phase info object for(uint i=0; i < narrowPhaseInfoBatch.getNbObjects(); i++) { // If there is a collision if (narrowPhaseInfoBatch.narrowPhaseInfos[i].isColliding) { // If the contact pair does not already exist if (!setOverlapContactPairId.contains(narrowPhaseInfoBatch.narrowPhaseInfos[i].overlappingPairId)) { const Entity collider1Entity = narrowPhaseInfoBatch.narrowPhaseInfos[i].colliderEntity1; const Entity collider2Entity = narrowPhaseInfoBatch.narrowPhaseInfos[i].colliderEntity2; const uint32 collider1Index = mCollidersComponents.getEntityIndex(collider1Entity); const uint32 collider2Index = mCollidersComponents.getEntityIndex(collider2Entity); const Entity body1Entity = mCollidersComponents.mBodiesEntities[collider1Index]; const Entity body2Entity = mCollidersComponents.mBodiesEntities[collider2Index]; const bool isTrigger = mCollidersComponents.mIsTrigger[collider1Index] || mCollidersComponents.mIsTrigger[collider2Index]; // Create a new contact pair ContactPair contactPair(narrowPhaseInfoBatch.narrowPhaseInfos[i].overlappingPairId, body1Entity, body2Entity, collider1Entity, collider2Entity, contactPairs.size(), isTrigger, false, mMemoryManager.getHeapAllocator()); contactPairs.add(contactPair); setOverlapContactPairId.add(narrowPhaseInfoBatch.narrowPhaseInfos[i].overlappingPairId); } } narrowPhaseInfoBatch.resetContactPoints(i); } } // Compute the narrow-phase collision detection for the testCollision() methods. // This method returns true if contacts are found. bool CollisionDetectionSystem::computeNarrowPhaseCollisionSnapshot(NarrowPhaseInput& narrowPhaseInput, CollisionCallback& callback) { RP3D_PROFILE("CollisionDetectionSystem::computeNarrowPhaseCollisionSnapshot()", mProfiler); MemoryAllocator& allocator = mMemoryManager.getHeapAllocator(); // Test the narrow-phase collision detection on the batches to be tested bool collisionFound = testNarrowPhaseCollision(narrowPhaseInput, false, allocator); // If collision has been found, create contacts if (collisionFound) { Array<ContactPointInfo> potentialContactPoints(allocator); Array<ContactManifoldInfo> potentialContactManifolds(allocator); Array<ContactPair> contactPairs(allocator); Array<ContactPair> lostContactPairs(allocator); // Not used during collision snapshots Array<ContactManifold> contactManifolds(allocator); Array<ContactPoint> contactPoints(allocator); // Process all the potential contacts after narrow-phase collision processAllPotentialContacts(narrowPhaseInput, true, potentialContactPoints, potentialContactManifolds, &contactPairs); // Reduce the number of contact points in the manifolds reducePotentialContactManifolds(&contactPairs, potentialContactManifolds, potentialContactPoints); // Create the actual contact manifolds and contact points createSnapshotContacts(contactPairs, contactManifolds, contactPoints, potentialContactManifolds, potentialContactPoints); // Report the contacts to the user reportContacts(callback, &contactPairs, &contactManifolds, &contactPoints, lostContactPairs); } return collisionFound; } // Swap the previous and current contacts arrays void CollisionDetectionSystem::swapPreviousAndCurrentContacts() { if (mPreviousContactPairs == &mContactPairs1) { mPreviousContactPairs = &mContactPairs2; mPreviousContactManifolds = &mContactManifolds2; mPreviousContactPoints = &mContactPoints2; mCurrentContactPairs = &mContactPairs1; mCurrentContactManifolds = &mContactManifolds1; mCurrentContactPoints = &mContactPoints1; } else { mPreviousContactPairs = &mContactPairs1; mPreviousContactManifolds = &mContactManifolds1; mPreviousContactPoints = &mContactPoints1; mCurrentContactPairs = &mContactPairs2; mCurrentContactManifolds = &mContactManifolds2; mCurrentContactPoints = &mContactPoints2; } } // Create the actual contact manifolds and contacts points void CollisionDetectionSystem::createContacts() { RP3D_PROFILE("CollisionDetectionSystem::createContacts()", mProfiler); mCurrentContactManifolds->reserve(mCurrentContactPairs->size()); mCurrentContactPoints->reserve(mCurrentContactManifolds->size()); // We go through all the contact pairs and add the pairs with a least a CollisionBody at the end of the // mProcessContactPairsOrderIslands array because those pairs have not been added during the islands // creation (only the pairs with two RigidBodies are added during island creation) mWorld->mProcessContactPairsOrderIslands.addRange(mCollisionBodyContactPairsIndices); assert(mWorld->mProcessContactPairsOrderIslands.size() == (*mCurrentContactPairs).size()); // Process the contact pairs in the order defined by the islands such that the contact manifolds and // contact points of a given island are packed together in the array of manifolds and contact points const uint32 nbContactPairsToProcess = mWorld->mProcessContactPairsOrderIslands.size(); for (uint p=0; p < nbContactPairsToProcess; p++) { uint32 contactPairIndex = mWorld->mProcessContactPairsOrderIslands[p]; ContactPair& contactPair = (*mCurrentContactPairs)[contactPairIndex]; contactPair.contactManifoldsIndex = mCurrentContactManifolds->size(); contactPair.nbContactManifolds = contactPair.potentialContactManifoldsIndices.size(); contactPair.contactPointsIndex = mCurrentContactPoints->size(); // For each potential contact manifold of the pair for (uint32 m=0; m < contactPair.nbContactManifolds; m++) { ContactManifoldInfo& potentialManifold = mPotentialContactManifolds[contactPair.potentialContactManifoldsIndices[m]]; // Start index and number of contact points for this manifold const uint32 contactPointsIndex = mCurrentContactPoints->size(); const uint32 nbContactPoints = static_cast<uint32>(potentialManifold.potentialContactPointsIndices.size()); contactPair.nbToTalContactPoints += nbContactPoints; // Create and add the contact manifold mCurrentContactManifolds->emplace(contactPair.body1Entity, contactPair.body2Entity, contactPair.collider1Entity, contactPair.collider2Entity, contactPointsIndex, nbContactPoints); assert(potentialManifold.potentialContactPointsIndices.size() > 0); // For each contact point of the manifold for (uint c=0; c < nbContactPoints; c++) { ContactPointInfo& potentialContactPoint = mPotentialContactPoints[potentialManifold.potentialContactPointsIndices[c]]; // Create and add the contact point mCurrentContactPoints->emplace(potentialContactPoint, mWorld->mConfig.persistentContactDistanceThreshold); } } } // Initialize the current contacts with the contacts from the previous frame (for warmstarting) initContactsWithPreviousOnes(); // Compute the lost contacts (contact pairs that were colliding in previous frame but not in this one) computeLostContactPairs(); mPreviousContactPoints->clear(); mPreviousContactManifolds->clear(); mPreviousContactPairs->clear(); mNbPreviousPotentialContactManifolds = mPotentialContactManifolds.capacity(); mNbPreviousPotentialContactPoints = mPotentialContactPoints.capacity(); // Reset the potential contacts mPotentialContactPoints.clear(true); mPotentialContactManifolds.clear(true); // Compute the map from contact pairs ids to contact pair for the next frame computeMapPreviousContactPairs(); mCollisionBodyContactPairsIndices.clear(true); mNarrowPhaseInput.clear(); } // Compute the lost contact pairs (contact pairs in contact in the previous frame but not in the current one) void CollisionDetectionSystem::computeLostContactPairs() { // For each convex pair const uint32 nbConvexPairs = mOverlappingPairs.mConvexPairs.size(); for (uint32 i=0; i < nbConvexPairs; i++) { // If the two colliders of the pair were colliding in the previous frame but not in the current one if (mOverlappingPairs.mConvexPairs[i].collidingInPreviousFrame && !mOverlappingPairs.mConvexPairs[i].collidingInCurrentFrame) { // If both bodies still exist if (mCollidersComponents.hasComponent(mOverlappingPairs.mConvexPairs[i].collider1) && mCollidersComponents.hasComponent(mOverlappingPairs.mConvexPairs[i].collider2)) { // Create a lost contact pair addLostContactPair(mOverlappingPairs.mConvexPairs[i]); } } } // For each convex pair const uint32 nbConcavePairs = mOverlappingPairs.mConcavePairs.size(); for (uint32 i=0; i < nbConcavePairs; i++) { // If the two colliders of the pair were colliding in the previous frame but not in the current one if (mOverlappingPairs.mConcavePairs[i].collidingInPreviousFrame && !mOverlappingPairs.mConcavePairs[i].collidingInCurrentFrame) { // If both bodies still exist if (mCollidersComponents.hasComponent(mOverlappingPairs.mConcavePairs[i].collider1) && mCollidersComponents.hasComponent(mOverlappingPairs.mConcavePairs[i].collider2)) { // Create a lost contact pair addLostContactPair(mOverlappingPairs.mConcavePairs[i]); } } } } // Create the actual contact manifolds and contacts points for testCollision() methods void CollisionDetectionSystem::createSnapshotContacts(Array<ContactPair>& contactPairs, Array<ContactManifold>& contactManifolds, Array<ContactPoint>& contactPoints, Array<ContactManifoldInfo>& potentialContactManifolds, Array<ContactPointInfo>& potentialContactPoints) { RP3D_PROFILE("CollisionDetectionSystem::createSnapshotContacts()", mProfiler); contactManifolds.reserve(contactPairs.size()); contactPoints.reserve(contactManifolds.size()); // For each contact pair const uint32 nbContactPairs = contactPairs.size(); for (uint32 p=0; p < nbContactPairs; p++) { ContactPair& contactPair = contactPairs[p]; assert(contactPair.potentialContactManifoldsIndices.size() > 0); contactPair.contactManifoldsIndex = contactManifolds.size(); contactPair.nbContactManifolds = contactPair.potentialContactManifoldsIndices.size(); contactPair.contactPointsIndex = contactPoints.size(); // For each potential contact manifold of the pair for (uint32 m=0; m < contactPair.nbContactManifolds; m++) { ContactManifoldInfo& potentialManifold = potentialContactManifolds[contactPair.potentialContactManifoldsIndices[m]]; // Start index and number of contact points for this manifold const uint32 contactPointsIndex = contactPoints.size(); const uint32 nbContactPoints = static_cast<uint32>(potentialManifold.potentialContactPointsIndices.size()); contactPair.nbToTalContactPoints += nbContactPoints; // Create and add the contact manifold contactManifolds.emplace(contactPair.body1Entity, contactPair.body2Entity, contactPair.collider1Entity, contactPair.collider2Entity, contactPointsIndex, nbContactPoints); assert(nbContactPoints > 0); // For each contact point of the manifold for (uint32 c=0; c < nbContactPoints; c++) { ContactPointInfo& potentialContactPoint = potentialContactPoints[potentialManifold.potentialContactPointsIndices[c]]; // Create a new contact point ContactPoint contactPoint(potentialContactPoint, mWorld->mConfig.persistentContactDistanceThreshold); // Add the contact point contactPoints.add(contactPoint); } } } } // Initialize the current contacts with the contacts from the previous frame (for warmstarting) void CollisionDetectionSystem::initContactsWithPreviousOnes() { const decimal persistentContactDistThresholdSqr = mWorld->mConfig.persistentContactDistanceThreshold * mWorld->mConfig.persistentContactDistanceThreshold; // For each contact pair of the current frame const uint32 nbCurrentContactPairs = mCurrentContactPairs->size(); for (uint32 i=0; i < nbCurrentContactPairs; i++) { ContactPair& currentContactPair = (*mCurrentContactPairs)[i]; // Find the corresponding contact pair in the previous frame (if any) auto itPrevContactPair = mPreviousMapPairIdToContactPairIndex.find(currentContactPair.pairId); // If we have found a corresponding contact pair in the previous frame if (itPrevContactPair != mPreviousMapPairIdToContactPairIndex.end()) { const uint previousContactPairIndex = itPrevContactPair->second; ContactPair& previousContactPair = (*mPreviousContactPairs)[previousContactPairIndex]; // --------------------- Contact Manifolds --------------------- // const uint contactManifoldsIndex = currentContactPair.contactManifoldsIndex; const uint nbContactManifolds = currentContactPair.nbContactManifolds; // For each current contact manifold of the current contact pair for (uint m=contactManifoldsIndex; m < contactManifoldsIndex + nbContactManifolds; m++) { assert(m < mCurrentContactManifolds->size()); ContactManifold& currentContactManifold = (*mCurrentContactManifolds)[m]; assert(currentContactManifold.nbContactPoints > 0); ContactPoint& currentContactPoint = (*mCurrentContactPoints)[currentContactManifold.contactPointsIndex]; const Vector3& currentContactPointNormal = currentContactPoint.getNormal(); // Find a similar contact manifold among the contact manifolds from the previous frame (for warmstarting) const uint previousContactManifoldIndex = previousContactPair.contactManifoldsIndex; const uint previousNbContactManifolds = previousContactPair.nbContactManifolds; for (uint p=previousContactManifoldIndex; p < previousContactManifoldIndex + previousNbContactManifolds; p++) { ContactManifold& previousContactManifold = (*mPreviousContactManifolds)[p]; assert(previousContactManifold.nbContactPoints > 0); ContactPoint& previousContactPoint = (*mPreviousContactPoints)[previousContactManifold.contactPointsIndex]; // If the previous contact manifold has a similar contact normal with the current manifold if (previousContactPoint.getNormal().dot(currentContactPointNormal) >= mWorld->mConfig.cosAngleSimilarContactManifold) { // Transfer data from the previous contact manifold to the current one currentContactManifold.frictionVector1 = previousContactManifold.frictionVector1; currentContactManifold.frictionVector2 = previousContactManifold.frictionVector2; currentContactManifold.frictionImpulse1 = previousContactManifold.frictionImpulse1; currentContactManifold.frictionImpulse2 = previousContactManifold.frictionImpulse2; currentContactManifold.frictionTwistImpulse = previousContactManifold.frictionTwistImpulse; break; } } } // --------------------- Contact Points --------------------- // const uint contactPointsIndex = currentContactPair.contactPointsIndex; const uint nbTotalContactPoints = currentContactPair.nbToTalContactPoints; // For each current contact point of the current contact pair for (uint c=contactPointsIndex; c < contactPointsIndex + nbTotalContactPoints; c++) { assert(c < mCurrentContactPoints->size()); ContactPoint& currentContactPoint = (*mCurrentContactPoints)[c]; const Vector3& currentContactPointLocalShape1 = currentContactPoint.getLocalPointOnShape1(); // Find a similar contact point among the contact points from the previous frame (for warmstarting) const uint previousContactPointsIndex = previousContactPair.contactPointsIndex; const uint previousNbContactPoints = previousContactPair.nbToTalContactPoints; for (uint p=previousContactPointsIndex; p < previousContactPointsIndex + previousNbContactPoints; p++) { const ContactPoint& previousContactPoint = (*mPreviousContactPoints)[p]; // If the previous contact point is very close to th current one const decimal distSquare = (currentContactPointLocalShape1 - previousContactPoint.getLocalPointOnShape1()).lengthSquare(); if (distSquare <= persistentContactDistThresholdSqr) { // Transfer data from the previous contact point to the current one currentContactPoint.setPenetrationImpulse(previousContactPoint.getPenetrationImpulse()); currentContactPoint.setIsRestingContact(previousContactPoint.getIsRestingContact()); break; } } } } } } // Remove a body from the collision detection void CollisionDetectionSystem::removeCollider(Collider* collider) { const int colliderBroadPhaseId = collider->getBroadPhaseId(); assert(colliderBroadPhaseId != -1); assert(mMapBroadPhaseIdToColliderEntity.containsKey(colliderBroadPhaseId)); // Remove all the overlapping pairs involving this collider Array<uint64>& overlappingPairs = mCollidersComponents.getOverlappingPairs(collider->getEntity()); while(overlappingPairs.size() > 0) { // TODO : Remove all the contact manifold of the overlapping pair from the contact manifolds array of the two bodies involved // Remove the overlapping pair mOverlappingPairs.removePair(overlappingPairs[0]); } mMapBroadPhaseIdToColliderEntity.remove(colliderBroadPhaseId); // Remove the body from the broad-phase mBroadPhaseSystem.removeCollider(collider); } // Ray casting method void CollisionDetectionSystem::raycast(RaycastCallback* raycastCallback, const Ray& ray, unsigned short raycastWithCategoryMaskBits) const { RP3D_PROFILE("CollisionDetectionSystem::raycast()", mProfiler); RaycastTest rayCastTest(raycastCallback); // Ask the broad-phase algorithm to call the testRaycastAgainstShape() // callback method for each collider hit by the ray in the broad-phase mBroadPhaseSystem.raycast(ray, rayCastTest, raycastWithCategoryMaskBits); } // Convert the potential contact into actual contacts void CollisionDetectionSystem::processPotentialContacts(NarrowPhaseInfoBatch& narrowPhaseInfoBatch, bool updateLastFrameInfo, Array<ContactPointInfo>& potentialContactPoints, Array<ContactManifoldInfo>& potentialContactManifolds, Map<uint64, uint>& mapPairIdToContactPairIndex, Array<ContactPair>* contactPairs) { RP3D_PROFILE("CollisionDetectionSystem::processPotentialContacts()", mProfiler); const uint nbObjects = narrowPhaseInfoBatch.getNbObjects(); if (updateLastFrameInfo) { // For each narrow phase info object for(uint i=0; i < nbObjects; i++) { narrowPhaseInfoBatch.narrowPhaseInfos[i].lastFrameCollisionInfo->wasColliding = narrowPhaseInfoBatch.narrowPhaseInfos[i].isColliding; // The previous frame collision info is now valid narrowPhaseInfoBatch.narrowPhaseInfos[i].lastFrameCollisionInfo->isValid = true; } } // For each narrow phase info object for(uint i=0; i < nbObjects; i++) { // If the two colliders are colliding if (narrowPhaseInfoBatch.narrowPhaseInfos[i].isColliding) { const uint64 pairId = narrowPhaseInfoBatch.narrowPhaseInfos[i].overlappingPairId; OverlappingPairs::OverlappingPair* overlappingPair = mOverlappingPairs.getOverlappingPair(pairId); assert(overlappingPair != nullptr); overlappingPair->collidingInCurrentFrame = true; const Entity collider1Entity = narrowPhaseInfoBatch.narrowPhaseInfos[i].colliderEntity1; const Entity collider2Entity = narrowPhaseInfoBatch.narrowPhaseInfos[i].colliderEntity2; const uint32 collider1Index = mCollidersComponents.getEntityIndex(collider1Entity); const uint32 collider2Index = mCollidersComponents.getEntityIndex(collider2Entity); const Entity body1Entity = mCollidersComponents.mBodiesEntities[collider1Index]; const Entity body2Entity = mCollidersComponents.mBodiesEntities[collider2Index]; // If we have a convex vs convex collision (if we consider the base collision shapes of the colliders) if (mCollidersComponents.mCollisionShapes[collider1Index]->isConvex() && mCollidersComponents.mCollisionShapes[collider2Index]->isConvex()) { // Create a new ContactPair const bool isTrigger = mCollidersComponents.mIsTrigger[collider1Index] || mCollidersComponents.mIsTrigger[collider2Index]; assert(!mWorld->mCollisionBodyComponents.getIsEntityDisabled(body1Entity) || !mWorld->mCollisionBodyComponents.getIsEntityDisabled(body2Entity)); const uint32 newContactPairIndex = contactPairs->size(); contactPairs->emplace(pairId, body1Entity, body2Entity, collider1Entity, collider2Entity, newContactPairIndex, overlappingPair->collidingInPreviousFrame, isTrigger, mMemoryManager.getHeapAllocator()); ContactPair* pairContact = &((*contactPairs)[newContactPairIndex]); // Create a new potential contact manifold for the overlapping pair uint32 contactManifoldIndex = static_cast<uint>(potentialContactManifolds.size()); potentialContactManifolds.emplace(pairId, mMemoryManager.getHeapAllocator()); ContactManifoldInfo& contactManifoldInfo = potentialContactManifolds[contactManifoldIndex]; const uint32 contactPointIndexStart = static_cast<uint>(potentialContactPoints.size()); // Add the potential contacts for (uint j=0; j < narrowPhaseInfoBatch.narrowPhaseInfos[i].nbContactPoints; j++) { // Add the contact point to the manifold contactManifoldInfo.potentialContactPointsIndices.add(contactPointIndexStart + j); // Add the contact point to the array of potential contact points const ContactPointInfo& contactPoint = narrowPhaseInfoBatch.narrowPhaseInfos[i].contactPoints[j]; potentialContactPoints.add(contactPoint); } // Add the contact manifold to the overlapping pair contact assert(pairId == contactManifoldInfo.pairId); pairContact->potentialContactManifoldsIndices.add(contactManifoldIndex); } else { // If there is not already a contact pair for this overlapping pair auto it = mapPairIdToContactPairIndex.find(pairId); ContactPair* pairContact = nullptr; if (it == mapPairIdToContactPairIndex.end()) { // Create a new ContactPair const bool isTrigger = mCollidersComponents.mIsTrigger[collider1Index] || mCollidersComponents.mIsTrigger[collider2Index]; assert(!mWorld->mCollisionBodyComponents.getIsEntityDisabled(body1Entity) || !mWorld->mCollisionBodyComponents.getIsEntityDisabled(body2Entity)); const uint32 newContactPairIndex = contactPairs->size(); contactPairs->emplace(pairId, body1Entity, body2Entity, collider1Entity, collider2Entity, newContactPairIndex, overlappingPair->collidingInPreviousFrame, isTrigger, mMemoryManager.getHeapAllocator()); pairContact = &((*contactPairs)[newContactPairIndex]); mapPairIdToContactPairIndex.add(Pair<uint64, uint>(pairId, newContactPairIndex)); } else { // If a ContactPair already exists for this overlapping pair, we use this one assert(it->first == pairId); const uint pairContactIndex = it->second; pairContact = &((*contactPairs)[pairContactIndex]); } assert(pairContact != nullptr); // Add the potential contacts for (uint j=0; j < narrowPhaseInfoBatch.narrowPhaseInfos[i].nbContactPoints; j++) { const ContactPointInfo& contactPoint = narrowPhaseInfoBatch.narrowPhaseInfos[i].contactPoints[j]; // Add the contact point to the array of potential contact points const uint32 contactPointIndex = potentialContactPoints.size(); potentialContactPoints.add(contactPoint); bool similarManifoldFound = false; // For each contact manifold of the overlapping pair const uint32 nbPotentialManifolds = pairContact->potentialContactManifoldsIndices.size(); for (uint m=0; m < nbPotentialManifolds; m++) { uint contactManifoldIndex = pairContact->potentialContactManifoldsIndices[m]; // Get the first contact point of the current manifold assert(potentialContactManifolds[contactManifoldIndex].potentialContactPointsIndices.size() > 0); const uint manifoldContactPointIndex = potentialContactManifolds[contactManifoldIndex].potentialContactPointsIndices[0]; const ContactPointInfo& manifoldContactPoint = potentialContactPoints[manifoldContactPointIndex]; // If we have found a corresponding manifold for the new contact point // (a manifold with a similar contact normal direction) if (manifoldContactPoint.normal.dot(contactPoint.normal) >= mWorld->mConfig.cosAngleSimilarContactManifold) { // Add the contact point to the manifold potentialContactManifolds[contactManifoldIndex].potentialContactPointsIndices.add(contactPointIndex); similarManifoldFound = true; break; } } // If we have not found a manifold with a similar contact normal for the contact point if (!similarManifoldFound) { // Create a new potential contact manifold for the overlapping pair uint32 contactManifoldIndex = potentialContactManifolds.size(); potentialContactManifolds.emplace(pairId, mMemoryManager.getHeapAllocator()); ContactManifoldInfo& contactManifoldInfo = potentialContactManifolds[contactManifoldIndex]; // Add the contact point to the manifold contactManifoldInfo.potentialContactPointsIndices.add(contactPointIndex); assert(pairContact != nullptr); // Add the contact manifold to the overlapping pair contact assert(pairContact->pairId == contactManifoldInfo.pairId); pairContact->potentialContactManifoldsIndices.add(contactManifoldIndex); } assert(pairContact->potentialContactManifoldsIndices.size() > 0); } } narrowPhaseInfoBatch.resetContactPoints(i); } } } // Clear the obsolete manifolds and contact points and reduce the number of contacts points of the remaining manifolds void CollisionDetectionSystem::reducePotentialContactManifolds(Array<ContactPair>* contactPairs, Array<ContactManifoldInfo>& potentialContactManifolds, const Array<ContactPointInfo>& potentialContactPoints) const { RP3D_PROFILE("CollisionDetectionSystem::reducePotentialContactManifolds()", mProfiler); // Reduce the number of potential contact manifolds in a contact pair const uint32 nbContactPairs = contactPairs->size(); for (uint32 i=0; i < nbContactPairs; i++) { ContactPair& contactPair = (*contactPairs)[i]; // While there are too many manifolds in the contact pair while(contactPair.potentialContactManifoldsIndices.size() > NB_MAX_CONTACT_MANIFOLDS) { // Look for a manifold with the smallest contact penetration depth. decimal minDepth = DECIMAL_LARGEST; int minDepthManifoldIndex = -1; for (uint32 j=0; j < contactPair.potentialContactManifoldsIndices.size(); j++) { ContactManifoldInfo& manifold = potentialContactManifolds[contactPair.potentialContactManifoldsIndices[j]]; // Get the largest contact point penetration depth of the manifold const decimal depth = computePotentialManifoldLargestContactDepth(manifold, potentialContactPoints); if (depth < minDepth) { minDepth = depth; minDepthManifoldIndex = static_cast<int>(j); } } // Remove the non optimal manifold assert(minDepthManifoldIndex >= 0); contactPair.removePotentialManifoldAtIndex(minDepthManifoldIndex); } } // Reduce the number of potential contact points in the manifolds for (uint32 i=0; i < nbContactPairs; i++) { const ContactPair& pairContact = (*contactPairs)[i]; // For each potential contact manifold for (uint32 j=0; j < pairContact.potentialContactManifoldsIndices.size(); j++) { ContactManifoldInfo& manifold = potentialContactManifolds[pairContact.potentialContactManifoldsIndices[j]]; // If there are two many contact points in the manifold if (manifold.potentialContactPointsIndices.size() > MAX_CONTACT_POINTS_IN_MANIFOLD) { Transform shape1LocalToWorldTransoform = mCollidersComponents.getLocalToWorldTransform(pairContact.collider1Entity); // Reduce the number of contact points in the manifold reduceContactPoints(manifold, shape1LocalToWorldTransoform, potentialContactPoints); } assert(manifold.potentialContactPointsIndices.size() <= MAX_CONTACT_POINTS_IN_MANIFOLD); // Remove the duplicated contact points in the manifold (if any) removeDuplicatedContactPointsInManifold(manifold, potentialContactPoints); } } } // Return the largest depth of all the contact points of a potential manifold decimal CollisionDetectionSystem::computePotentialManifoldLargestContactDepth(const ContactManifoldInfo& manifold, const Array<ContactPointInfo>& potentialContactPoints) const { decimal largestDepth = 0.0f; const uint32 nbContactPoints = static_cast<uint32>(manifold.potentialContactPointsIndices.size()); assert(nbContactPoints > 0); for (uint32 i=0; i < nbContactPoints; i++) { decimal depth = potentialContactPoints[manifold.potentialContactPointsIndices[i]].penetrationDepth; if (depth > largestDepth) { largestDepth = depth; } } return largestDepth; } // Reduce the number of contact points of a potential contact manifold // This is based on the technique described by Dirk Gregorius in his // "Contacts Creation" GDC presentation. This method will reduce the number of // contact points to a maximum of 4 points (but it can be less). void CollisionDetectionSystem::reduceContactPoints(ContactManifoldInfo& manifold, const Transform& shape1ToWorldTransform, const Array<ContactPointInfo>& potentialContactPoints) const { assert(manifold.potentialContactPointsIndices.size() > MAX_CONTACT_POINTS_IN_MANIFOLD); // The following algorithm only works to reduce to a maximum of 4 contact points assert(MAX_CONTACT_POINTS_IN_MANIFOLD == 4); // Array of the candidate contact points indices in the manifold. Every time that we have found a // point we want to keep, we will remove it from this array Array<uint> candidatePointsIndices(manifold.potentialContactPointsIndices); assert(manifold.potentialContactPointsIndices.size() == candidatePointsIndices.size()); int8 nbReducedPoints = 0; uint pointsToKeepIndices[MAX_CONTACT_POINTS_IN_MANIFOLD]; for (int8 i=0; i<MAX_CONTACT_POINTS_IN_MANIFOLD; i++) { pointsToKeepIndices[i] = 0; } // Compute the initial contact point we need to keep. // The first point we keep is always the point in a given // constant direction (in order to always have same contact points // between frames for better stability) const Transform worldToShape1Transform = shape1ToWorldTransform.getInverse(); // Compute the contact normal of the manifold (we use the first contact point) // in the local-space of the first collision shape const Vector3 contactNormalShape1Space = worldToShape1Transform.getOrientation() * potentialContactPoints[candidatePointsIndices[0]].normal; // Compute a search direction const Vector3 searchDirection(1, 1, 1); decimal maxDotProduct = DECIMAL_SMALLEST; uint elementIndexToKeep = 0; for (uint i=0; i < candidatePointsIndices.size(); i++) { const ContactPointInfo& element = potentialContactPoints[candidatePointsIndices[i]]; decimal dotProduct = searchDirection.dot(element.localPoint1); if (dotProduct > maxDotProduct) { maxDotProduct = dotProduct; elementIndexToKeep = i; nbReducedPoints = 1; } } pointsToKeepIndices[0] = candidatePointsIndices[elementIndexToKeep]; removeItemAtInArray(candidatePointsIndices, elementIndexToKeep); //candidatePointsIndices.removeAt(elementIndexToKeep); assert(nbReducedPoints == 1); // Compute the second contact point we need to keep. // The second point we keep is the one farthest away from the first point. decimal maxDistance = decimal(0.0); elementIndexToKeep = 0; for (uint i=0; i < candidatePointsIndices.size(); i++) { const ContactPointInfo& element = potentialContactPoints[candidatePointsIndices[i]]; const ContactPointInfo& pointToKeep0 = potentialContactPoints[pointsToKeepIndices[0]]; assert(candidatePointsIndices[i] != pointsToKeepIndices[0]); const decimal distance = (pointToKeep0.localPoint1 - element.localPoint1).lengthSquare(); if (distance >= maxDistance) { maxDistance = distance; elementIndexToKeep = i; nbReducedPoints = 2; } } pointsToKeepIndices[1] = candidatePointsIndices[elementIndexToKeep]; removeItemAtInArray(candidatePointsIndices, elementIndexToKeep); assert(nbReducedPoints == 2); // Compute the third contact point we need to keep. // The third point is the one producing the triangle with the larger area // with first and second point. // We compute the most positive or most negative triangle area (depending on winding) uint thirdPointMaxAreaIndex = 0; uint thirdPointMinAreaIndex = 0; decimal minArea = decimal(0.0); decimal maxArea = decimal(0.0); bool isPreviousAreaPositive = true; for (uint i=0; i < candidatePointsIndices.size(); i++) { const ContactPointInfo& element = potentialContactPoints[candidatePointsIndices[i]]; const ContactPointInfo& pointToKeep0 = potentialContactPoints[pointsToKeepIndices[0]]; const ContactPointInfo& pointToKeep1 = potentialContactPoints[pointsToKeepIndices[1]]; assert(candidatePointsIndices[i] != pointsToKeepIndices[0]); assert(candidatePointsIndices[i] != pointsToKeepIndices[1]); const Vector3 newToFirst = pointToKeep0.localPoint1 - element.localPoint1; const Vector3 newToSecond = pointToKeep1.localPoint1 - element.localPoint1; // Compute the triangle area decimal area = newToFirst.cross(newToSecond).dot(contactNormalShape1Space); if (area >= maxArea) { maxArea = area; thirdPointMaxAreaIndex = i; } if (area <= minArea) { minArea = area; thirdPointMinAreaIndex = i; } } assert(minArea <= decimal(0.0)); assert(maxArea >= decimal(0.0)); if (maxArea > (-minArea)) { isPreviousAreaPositive = true; pointsToKeepIndices[2] = candidatePointsIndices[thirdPointMaxAreaIndex]; removeItemAtInArray(candidatePointsIndices, thirdPointMaxAreaIndex); } else { isPreviousAreaPositive = false; pointsToKeepIndices[2] = candidatePointsIndices[thirdPointMinAreaIndex]; removeItemAtInArray(candidatePointsIndices, thirdPointMinAreaIndex); } nbReducedPoints = 3; // Compute the 4th point by choosing the triangle that adds the most // triangle area to the previous triangle and has opposite sign area (opposite winding) decimal largestArea = decimal(0.0); // Largest area (positive or negative) elementIndexToKeep = 0; nbReducedPoints = 4; decimal area; // For each remaining candidate points for (uint i=0; i < candidatePointsIndices.size(); i++) { const ContactPointInfo& element = potentialContactPoints[candidatePointsIndices[i]]; assert(candidatePointsIndices[i] != pointsToKeepIndices[0]); assert(candidatePointsIndices[i] != pointsToKeepIndices[1]); assert(candidatePointsIndices[i] != pointsToKeepIndices[2]); // For each edge of the triangle made by the first three points for (uint j=0; j<3; j++) { uint edgeVertex1Index = j; uint edgeVertex2Index = j < 2 ? j + 1 : 0; const ContactPointInfo& pointToKeepEdgeV1 = potentialContactPoints[pointsToKeepIndices[edgeVertex1Index]]; const ContactPointInfo& pointToKeepEdgeV2 = potentialContactPoints[pointsToKeepIndices[edgeVertex2Index]]; const Vector3 newToFirst = pointToKeepEdgeV1.localPoint1 - element.localPoint1; const Vector3 newToSecond = pointToKeepEdgeV2.localPoint1 - element.localPoint1; // Compute the triangle area area = newToFirst.cross(newToSecond).dot(contactNormalShape1Space); // We are looking at the triangle with maximal area (positive or negative). // If the previous area is positive, we are looking at negative area now. // If the previous area is negative, we are looking at the positive area now. if (isPreviousAreaPositive && area <= largestArea) { largestArea = area; elementIndexToKeep = i; } else if (!isPreviousAreaPositive && area >= largestArea) { largestArea = area; elementIndexToKeep = i; } } } pointsToKeepIndices[3] = candidatePointsIndices[elementIndexToKeep]; removeItemAtInArray(candidatePointsIndices, elementIndexToKeep); // Only keep the four selected contact points in the manifold manifold.potentialContactPointsIndices.clear(); manifold.potentialContactPointsIndices.add(pointsToKeepIndices[0]); manifold.potentialContactPointsIndices.add(pointsToKeepIndices[1]); manifold.potentialContactPointsIndices.add(pointsToKeepIndices[2]); manifold.potentialContactPointsIndices.add(pointsToKeepIndices[3]); } // Remove the duplicated contact points in a given contact manifold void CollisionDetectionSystem::removeDuplicatedContactPointsInManifold(ContactManifoldInfo& manifold, const Array<ContactPointInfo>& potentialContactPoints) const { RP3D_PROFILE("CollisionDetectionSystem::removeDuplicatedContactPointsInManifold()", mProfiler); const decimal distThresholdSqr = SAME_CONTACT_POINT_DISTANCE_THRESHOLD * SAME_CONTACT_POINT_DISTANCE_THRESHOLD; // For each contact point of the manifold for (uint32 i=0; i < manifold.potentialContactPointsIndices.size(); i++) { for (uint32 j=i+1; j < manifold.potentialContactPointsIndices.size(); j++) { const ContactPointInfo& point1 = potentialContactPoints[manifold.potentialContactPointsIndices[i]]; const ContactPointInfo& point2 = potentialContactPoints[manifold.potentialContactPointsIndices[j]]; // Compute the distance between the two contact points const decimal distSqr = (point2.localPoint1 - point1.localPoint1).lengthSquare(); // We have a found a duplicated contact point if (distSqr < distThresholdSqr) { // Remove the duplicated contact point manifold.potentialContactPointsIndices.removeAtAndReplaceByLast(j); j--; } } } } // Remove an element in an array (and replace it by the last one in the array) void CollisionDetectionSystem::removeItemAtInArray(Array<uint>& array, uint32 index) const { assert(index < array.size()); assert(array.size() > 0); array.removeAtAndReplaceByLast(index); } // Report contacts and triggers void CollisionDetectionSystem::reportContactsAndTriggers() { // Report contacts and triggers to the user if (mWorld->mEventListener != nullptr) { reportContacts(*(mWorld->mEventListener), mCurrentContactPairs, mCurrentContactManifolds, mCurrentContactPoints, mLostContactPairs); reportTriggers(*(mWorld->mEventListener), mCurrentContactPairs, mLostContactPairs); } // Report contacts for debug rendering (if enabled) if (mWorld->mIsDebugRenderingEnabled) { reportDebugRenderingContacts(mCurrentContactPairs, mCurrentContactManifolds, mCurrentContactPoints, mLostContactPairs); } mOverlappingPairs.updateCollidingInPreviousFrame(); mLostContactPairs.clear(true); } // Report all contacts to the user void CollisionDetectionSystem::reportContacts(CollisionCallback& callback, Array<ContactPair>* contactPairs, Array<ContactManifold>* manifolds, Array<ContactPoint>* contactPoints, Array<ContactPair>& lostContactPairs) { RP3D_PROFILE("CollisionDetectionSystem::reportContacts()", mProfiler); // If there are contacts if (contactPairs->size() + lostContactPairs.size() > 0) { CollisionCallback::CallbackData callbackData(contactPairs, manifolds, contactPoints, lostContactPairs, *mWorld); // Call the callback method to report the contacts callback.onContact(callbackData); } } // Report all triggers to the user void CollisionDetectionSystem::reportTriggers(EventListener& eventListener, Array<ContactPair>* contactPairs, Array<ContactPair>& lostContactPairs) { RP3D_PROFILE("CollisionDetectionSystem::reportTriggers()", mProfiler); // If there are contacts if (contactPairs->size() + lostContactPairs.size() > 0) { OverlapCallback::CallbackData callbackData(*contactPairs, lostContactPairs, true, *mWorld); // Call the callback method to report the overlapping shapes eventListener.onTrigger(callbackData); } } // Report all contacts for debug rendering void CollisionDetectionSystem::reportDebugRenderingContacts(Array<ContactPair>* contactPairs, Array<ContactManifold>* manifolds, Array<ContactPoint>* contactPoints, Array<ContactPair>& lostContactPairs) { RP3D_PROFILE("CollisionDetectionSystem::reportDebugRenderingContacts()", mProfiler); // If there are contacts if (contactPairs->size() + lostContactPairs.size() > 0) { CollisionCallback::CallbackData callbackData(contactPairs, manifolds, contactPoints, lostContactPairs, *mWorld); // Call the callback method to report the contacts mWorld->mDebugRenderer.onContact(callbackData); } } // Return true if two bodies overlap (collide) bool CollisionDetectionSystem::testOverlap(CollisionBody* body1, CollisionBody* body2) { NarrowPhaseInput narrowPhaseInput(mMemoryManager.getPoolAllocator(), mOverlappingPairs); // Compute the broad-phase collision detection computeBroadPhase(); // Filter the overlapping pairs to get only the ones with the selected body involved Array<uint64> convexPairs(mMemoryManager.getPoolAllocator()); Array<uint64> concavePairs(mMemoryManager.getPoolAllocator()); filterOverlappingPairs(body1->getEntity(), body2->getEntity(), convexPairs, concavePairs); if (convexPairs.size() > 0 || concavePairs.size() > 0) { // Compute the middle-phase collision detection computeMiddlePhaseCollisionSnapshot(convexPairs, concavePairs, narrowPhaseInput, false); // Compute the narrow-phase collision detection return computeNarrowPhaseOverlapSnapshot(narrowPhaseInput, nullptr); } return false; } // Report all the bodies that overlap (collide) in the world void CollisionDetectionSystem::testOverlap(OverlapCallback& callback) { NarrowPhaseInput narrowPhaseInput(mMemoryManager.getPoolAllocator(), mOverlappingPairs); // Compute the broad-phase collision detection computeBroadPhase(); // Compute the middle-phase collision detection computeMiddlePhase(narrowPhaseInput, false); // Compute the narrow-phase collision detection and report overlapping shapes computeNarrowPhaseOverlapSnapshot(narrowPhaseInput, &callback); } // Report all the bodies that overlap (collide) with the body in parameter void CollisionDetectionSystem::testOverlap(CollisionBody* body, OverlapCallback& callback) { NarrowPhaseInput narrowPhaseInput(mMemoryManager.getPoolAllocator(), mOverlappingPairs); // Compute the broad-phase collision detection computeBroadPhase(); // Filter the overlapping pairs to get only the ones with the selected body involved Array<uint64> convexPairs(mMemoryManager.getPoolAllocator()); Array<uint64> concavePairs(mMemoryManager.getPoolAllocator()); filterOverlappingPairs(body->getEntity(), convexPairs, concavePairs); if (convexPairs.size() > 0 || concavePairs.size() > 0) { // Compute the middle-phase collision detection computeMiddlePhaseCollisionSnapshot(convexPairs, concavePairs, narrowPhaseInput, false); // Compute the narrow-phase collision detection computeNarrowPhaseOverlapSnapshot(narrowPhaseInput, &callback); } } // Test collision and report contacts between two bodies. void CollisionDetectionSystem::testCollision(CollisionBody* body1, CollisionBody* body2, CollisionCallback& callback) { NarrowPhaseInput narrowPhaseInput(mMemoryManager.getPoolAllocator(), mOverlappingPairs); // Compute the broad-phase collision detection computeBroadPhase(); // Filter the overlapping pairs to get only the ones with the selected body involved Array<uint64> convexPairs(mMemoryManager.getPoolAllocator()); Array<uint64> concavePairs(mMemoryManager.getPoolAllocator()); filterOverlappingPairs(body1->getEntity(), body2->getEntity(), convexPairs, concavePairs); if (convexPairs.size() > 0 || concavePairs.size() > 0) { // Compute the middle-phase collision detection computeMiddlePhaseCollisionSnapshot(convexPairs, concavePairs, narrowPhaseInput, true); // Compute the narrow-phase collision detection and report contacts computeNarrowPhaseCollisionSnapshot(narrowPhaseInput, callback); } } // Test collision and report all the contacts involving the body in parameter void CollisionDetectionSystem::testCollision(CollisionBody* body, CollisionCallback& callback) { NarrowPhaseInput narrowPhaseInput(mMemoryManager.getPoolAllocator(), mOverlappingPairs); // Compute the broad-phase collision detection computeBroadPhase(); // Filter the overlapping pairs to get only the ones with the selected body involved Array<uint64> convexPairs(mMemoryManager.getPoolAllocator()); Array<uint64> concavePairs(mMemoryManager.getPoolAllocator()); filterOverlappingPairs(body->getEntity(), convexPairs, concavePairs); if (convexPairs.size() > 0 || concavePairs.size() > 0) { // Compute the middle-phase collision detection computeMiddlePhaseCollisionSnapshot(convexPairs, concavePairs, narrowPhaseInput, true); // Compute the narrow-phase collision detection and report contacts computeNarrowPhaseCollisionSnapshot(narrowPhaseInput, callback); } } // Test collision and report contacts between each colliding bodies in the world void CollisionDetectionSystem::testCollision(CollisionCallback& callback) { NarrowPhaseInput narrowPhaseInput(mMemoryManager.getPoolAllocator(), mOverlappingPairs); // Compute the broad-phase collision detection computeBroadPhase(); // Compute the middle-phase collision detection computeMiddlePhase(narrowPhaseInput, true); // Compute the narrow-phase collision detection and report contacts computeNarrowPhaseCollisionSnapshot(narrowPhaseInput, callback); } // Filter the overlapping pairs to keep only the pairs where a given body is involved void CollisionDetectionSystem::filterOverlappingPairs(Entity bodyEntity, Array<uint64>& convexPairs, Array<uint64>& concavePairs) const { // For each convex pairs const uint32 nbConvexPairs = mOverlappingPairs.mConvexPairs.size(); for (uint32 i=0; i < nbConvexPairs; i++) { if (mCollidersComponents.getBody(mOverlappingPairs.mConvexPairs[i].collider1) == bodyEntity || mCollidersComponents.getBody(mOverlappingPairs.mConvexPairs[i].collider2) == bodyEntity) { convexPairs.add(mOverlappingPairs.mConvexPairs[i].pairID); } } // For each concave pairs const uint32 nbConcavePairs = mOverlappingPairs.mConcavePairs.size(); for (uint32 i=0; i < nbConcavePairs; i++) { if (mCollidersComponents.getBody(mOverlappingPairs.mConcavePairs[i].collider1) == bodyEntity || mCollidersComponents.getBody(mOverlappingPairs.mConcavePairs[i].collider2) == bodyEntity) { concavePairs.add(mOverlappingPairs.mConcavePairs[i].pairID); } } } // Filter the overlapping pairs to keep only the pairs where two given bodies are involved void CollisionDetectionSystem::filterOverlappingPairs(Entity body1Entity, Entity body2Entity, Array<uint64>& convexPairs, Array<uint64>& concavePairs) const { // For each convex pair const uint32 nbConvexPairs = mOverlappingPairs.mConvexPairs.size(); for (uint32 i=0; i < nbConvexPairs; i++) { const Entity collider1Body = mCollidersComponents.getBody(mOverlappingPairs.mConvexPairs[i].collider1); const Entity collider2Body = mCollidersComponents.getBody(mOverlappingPairs.mConvexPairs[i].collider2); if ((collider1Body == body1Entity && collider2Body == body2Entity) || (collider1Body == body2Entity && collider2Body == body1Entity)) { convexPairs.add(mOverlappingPairs.mConvexPairs[i].pairID); } } // For each concave pair const uint nbConcavePairs = mOverlappingPairs.mConcavePairs.size(); for (uint i=0; i < nbConcavePairs; i++) { const Entity collider1Body = mCollidersComponents.getBody(mOverlappingPairs.mConcavePairs[i].collider1); const Entity collider2Body = mCollidersComponents.getBody(mOverlappingPairs.mConcavePairs[i].collider2); if ((collider1Body == body1Entity && collider2Body == body2Entity) || (collider1Body == body2Entity && collider2Body == body1Entity)) { concavePairs.add(mOverlappingPairs.mConcavePairs[i].pairID); } } } // Return the world event listener EventListener* CollisionDetectionSystem::getWorldEventListener() { return mWorld->mEventListener; } // Return the world-space AABB of a given collider const AABB CollisionDetectionSystem::getWorldAABB(const Collider* collider) const { assert(collider->getBroadPhaseId() > -1); return mBroadPhaseSystem.getFatAABB(collider->getBroadPhaseId()); }
50.535522
234
0.70712
VaderY
4058914fa3ce8fe6ccb306ca35396bf2dcd5a009
253
cpp
C++
imposc-service/imposc-cpp/main.cpp
FelixDux/imposccpp
c8c612df87a53ddaca6260816c913ade44adbe6d
[ "MIT" ]
null
null
null
imposc-service/imposc-cpp/main.cpp
FelixDux/imposccpp
c8c612df87a53ddaca6260816c913ade44adbe6d
[ "MIT" ]
1
2021-03-22T17:27:17.000Z
2021-07-02T07:31:39.000Z
imposc-service/imposc-cpp/main.cpp
FelixDux/imposccpp
c8c612df87a53ddaca6260816c913ade44adbe6d
[ "MIT" ]
null
null
null
#include "imposcpy.hpp" #include <iostream> int main(int argc, char** argv) { // map_impacts(5.2, 0.8, -0.63, 100, 0.5, 2, 4000, "impact-map.png", "errors.txt"); map_doa(5.2, 0.8, -0.63, 100, 4, 10, 10, 1000, "doa.png", "errors.txt"); return 0; }
21.083333
84
0.600791
FelixDux
405a30d475896a9ba5d81cac6d72ff7e5769ce03
10,956
cpp
C++
test/systemtest/common/fms/fms_self_starting_test/fms_self_starting_test.cpp
openharmony-gitee-mirror/appexecfwk_standard
0edd750ed64940531881e0bb113a84155ac056d0
[ "Apache-2.0" ]
1
2021-11-23T08:13:14.000Z
2021-11-23T08:13:14.000Z
test/systemtest/common/fms/fms_self_starting_test/fms_self_starting_test.cpp
openharmony-gitee-mirror/appexecfwk_standard
0edd750ed64940531881e0bb113a84155ac056d0
[ "Apache-2.0" ]
null
null
null
test/systemtest/common/fms/fms_self_starting_test/fms_self_starting_test.cpp
openharmony-gitee-mirror/appexecfwk_standard
0edd750ed64940531881e0bb113a84155ac056d0
[ "Apache-2.0" ]
1
2021-09-13T11:17:54.000Z
2021-09-13T11:17:54.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <fcntl.h> #include <fstream> #include <future> #include <gtest/gtest.h> #include <iostream> #include <fstream> #include "ability_handler.h" #include "ability_info.h" #include "ability_local_record.h" #include "ability_start_setting.h" #include "app_log_wrapper.h" #include "common_event.h" #include "common_event_manager.h" #include "context_deal.h" #include "distributed_kv_data_manager.h" #include "form_db_info.h" #include "form_data_mgr.h" #include "form_item_info.h" #include "form_storage_mgr.h" #include "form_event.h" #include "form_st_common_info.h" #include "iservice_registry.h" #include "nlohmann/json.hpp" #include "self_starting_test_config_parser.h" #include "system_ability_definition.h" #include "system_test_form_util.h" using OHOS::AAFwk::Want; using namespace testing::ext; using namespace std::chrono_literals; using namespace OHOS::STtools; namespace OHOS { namespace AppExecFwk { static SelfStartingTestInfo selfStarting; static SelfStartingTestConfigParser selfStartingParser; const int ADD_FORM_A_NUMBER = 10; const int ADD_FORM_LENGTH = 20; class FmsSelfStartingTest : public testing::Test { public: static void SetUpTestCase(); static void TearDownTestCase(); static bool SubscribeEvent(); bool CompareA(); bool CompareB(); void SetUp(); void TearDown(); void StartAbilityKitTest(const std::string &abilityName, const std::string &bundleName); void TerminateAbility(const std::string &eventName, const std::string &abilityName); void ClearStorage(); bool CheckKvStore(); void TryTwice(const std::function<DistributedKv::Status()> &func); class FormEventSubscriber : public CommonEventSubscriber { public: explicit FormEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; virtual void OnReceiveEvent(const CommonEventData &data) override; ~FormEventSubscriber() = default; }; static sptr<AAFwk::IAbilityManager> abilityMs; static FormEvent event; static std::vector<std::string> eventList; static std::shared_ptr<FormEventSubscriber> subscriber_; }; std::vector<std::string> FmsSelfStartingTest::eventList = { FORM_EVENT_ABILITY_ONACTIVED, FORM_EVENT_RECV_SELF_STARTING_TEST_0100, FORM_EVENT_RECV_SELF_STARTING_TEST_0200, FORM_EVENT_RECV_SELF_STARTING_TEST_0300 }; FormEvent FmsSelfStartingTest::event = FormEvent(); sptr<AAFwk::IAbilityManager> FmsSelfStartingTest::abilityMs = nullptr; std::shared_ptr<FmsSelfStartingTest::FormEventSubscriber> FmsSelfStartingTest::subscriber_ = nullptr; void FmsSelfStartingTest::FormEventSubscriber::OnReceiveEvent(const CommonEventData &data) { GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); SystemTestFormUtil::Completed(event, data.GetWant().GetAction(), data.GetCode(), data.GetData()); } void FmsSelfStartingTest::SetUpTestCase() { if (!SubscribeEvent()) { GTEST_LOG_(INFO) << "SubscribeEvent error"; } SelfStartingTestConfigParser selfStartingTcp; selfStartingTcp.ParseForSelfStartingTest(FMS_TEST_CONFIG_FILE_PATH, selfStarting); std::cout << "self starting test status : " << "addFormStatus : " << selfStarting.addFormStatus << ", deleteFormStatus:" << selfStarting.deleteFormStatus << ", compareStatus:" << selfStarting.compareStatus << std::endl; if (selfStarting.addFormStatus) { selfStartingParser.ClearStorage(); for (int iCount = 0; iCount < ADD_FORM_A_NUMBER; iCount++) { Want want; want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); APP_LOGI("%{public}s, formCount: %{public}d", __func__, iCount + 1); want.SetParam(Constants::PARAM_FORM_ADD_COUNT, iCount + 1); // Set Want info end int errorCode = STtools::SystemTestFormUtil::DistributedDataAddForm(want); if (errorCode != 0) { GTEST_LOG_(INFO) << "add form failed, iCount:" << iCount << ", errorCode:" << errorCode; } sleep(1); } } if (selfStarting.addFormStatus) { for (int iCount = ADD_FORM_A_NUMBER; iCount < ADD_FORM_LENGTH; iCount++) { Want want; want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME2); want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME2); want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME2, FORM_PROVIDER_ABILITY_NAME2); APP_LOGI("%{public}s, formCount: %{public}d", __func__, iCount + 1); want.SetParam(Constants::PARAM_FORM_ADD_COUNT, iCount + 1); // Set Want info end int errorCode = STtools::SystemTestFormUtil::DistributedDataAddForm(want); if (errorCode != 0) { GTEST_LOG_(INFO) << "add form failed, iCount:" << iCount << ", errorCode:" << errorCode; } sleep(1); } } } bool FmsSelfStartingTest::CompareA() { bool compare = true; for (int iCount = 0; iCount < ADD_FORM_A_NUMBER; iCount++) { int64_t formId = iCount + 1; InnerFormInfo innerFormInfo; selfStartingParser.GetStorageFormInfoById(std::to_string(formId), innerFormInfo); if (innerFormInfo.GetFormId() != formId) { compare = false; break; } if (innerFormInfo.GetModuleName() != PARAM_PROVIDER_MODULE_NAME1) { compare = false; break; } if (innerFormInfo.GetBundleName() != FORM_PROVIDER_BUNDLE_NAME1) { compare = false; break; } if (innerFormInfo.GetAbilityName() != FORM_PROVIDER_ABILITY_NAME1) { compare = false; break; } if (innerFormInfo.GetFormName() != PARAM_FORM_NAME1) { compare = false; break; } } return compare; } bool FmsSelfStartingTest::CompareB() { bool compare = true; for (int iCount = ADD_FORM_A_NUMBER; iCount < ADD_FORM_LENGTH; iCount++) { int64_t formId = iCount + 1; InnerFormInfo innerFormInfo; selfStartingParser.GetStorageFormInfoById(std::to_string(formId), innerFormInfo); if (innerFormInfo.GetFormId() != formId) { compare = false; break; } if (innerFormInfo.GetModuleName() != PARAM_PROVIDER_MODULE_NAME2) { compare = false; break; } if (innerFormInfo.GetBundleName() != FORM_PROVIDER_BUNDLE_NAME2) { compare = false; break; } if (innerFormInfo.GetAbilityName() != FORM_PROVIDER_ABILITY_NAME2) { compare = false; break; } if (innerFormInfo.GetFormName() != PARAM_FORM_NAME2) { compare = false; break; } } return compare; } void FmsSelfStartingTest::TearDownTestCase() { GTEST_LOG_(INFO) << "UnSubscribeCommonEvent calld"; CommonEventManager::UnSubscribeCommonEvent(subscriber_); if (selfStarting.deleteFormStatus) { for (int iCount = 0; iCount < ADD_FORM_A_NUMBER; iCount++) { int64_t formId = iCount + 1; int errorCode = STtools::SystemTestFormUtil::DistributedDataDeleteForm(std::to_string(formId)); if (errorCode != 0) { GTEST_LOG_(INFO) << "delete form failed, iCount:" << iCount << ", errorCode:" << errorCode; } } } if (selfStarting.deleteFormStatus) { for (int iCount = ADD_FORM_A_NUMBER; iCount < ADD_FORM_LENGTH; iCount++) { int64_t formId = iCount + 1; int errorCode = STtools::SystemTestFormUtil::DistributedDataDeleteForm(std::to_string(formId)); if (errorCode != 0) { GTEST_LOG_(INFO) << "delete form failed, iCount:" << ", errorCode:" << errorCode; } } selfStartingParser.ClearStorage(); } } void FmsSelfStartingTest::SetUp() { } void FmsSelfStartingTest::TearDown() { GTEST_LOG_(INFO) << "CleanMsg calld"; SystemTestFormUtil::CleanMsg(event); } bool FmsSelfStartingTest::SubscribeEvent() { GTEST_LOG_(INFO) << "SubscribeEvent calld"; MatchingSkills matchingSkills; for (const auto &e : eventList) { matchingSkills.AddEvent(e); } CommonEventSubscribeInfo subscribeInfo(matchingSkills); subscribeInfo.SetPriority(1); subscriber_ = std::make_shared<FormEventSubscriber>(subscribeInfo); return CommonEventManager::SubscribeCommonEvent(subscriber_); } /** * @tc.number: FMS_Start_0300_03 * @tc.name: Form number 512 * @tc.desc: */ HWTEST_F(FmsSelfStartingTest, FMS_Start_0300_03, Function | MediumTest | Level1) { std::cout << "START FMS_Start_0300_03" << std::endl; if (selfStarting.compareStatus) { std::ifstream opbefore("/data/formmgr/beforeKill.txt"); std::ifstream opafter("/data/formmgr/afterKill.txt"); std::string beforeKill; std::string afterKill; while (!opbefore.eof()) { beforeKill += opbefore.get(); } while (!opafter.eof()) { afterKill += opafter.get(); } opbefore.close(); opafter.close(); EXPECT_TRUE(beforeKill != afterKill); EXPECT_TRUE(CompareA()); EXPECT_TRUE(CompareB()); } std::cout << "END FMS_Start_0300_03" << std::endl; } } // namespace AppExecFwk } // namespace OHOS
36.888889
115
0.6705
openharmony-gitee-mirror
405aa04e4e6d0f13d87abb1ed296120f7ebe605f
124
cpp
C++
TP3-9508/common_src/socketclosedexception.cpp
Jonathan-R0/TallerDeProgramacion
80038d06736c729310ff4c2a54195fb2d1c79ab7
[ "MIT" ]
null
null
null
TP3-9508/common_src/socketclosedexception.cpp
Jonathan-R0/TallerDeProgramacion
80038d06736c729310ff4c2a54195fb2d1c79ab7
[ "MIT" ]
null
null
null
TP3-9508/common_src/socketclosedexception.cpp
Jonathan-R0/TallerDeProgramacion
80038d06736c729310ff4c2a54195fb2d1c79ab7
[ "MIT" ]
null
null
null
#include "socketclosedexception.h" const char* SocketClosedException::what() const throw() { return errormsg.c_str(); }
17.714286
57
0.741935
Jonathan-R0
405b9985f6cbf6d74c8060e88ca9eb45119c85d8
11,937
cpp
C++
book_sample/Chpater 5 - Screen Space Effects/Lens Flare/LensflareManager.cpp
jjuiddong/HLSL-Development-Cookbook
8a322f4e7924fe0c7e757bd2453ce0adeb282aeb
[ "MIT" ]
10
2020-04-13T10:15:27.000Z
2022-03-10T08:57:46.000Z
book_sample/Chpater 5 - Screen Space Effects/Lens Flare/LensflareManager.cpp
jjuiddong/HLSL-Development-Cookbook
8a322f4e7924fe0c7e757bd2453ce0adeb282aeb
[ "MIT" ]
null
null
null
book_sample/Chpater 5 - Screen Space Effects/Lens Flare/LensflareManager.cpp
jjuiddong/HLSL-Development-Cookbook
8a322f4e7924fe0c7e757bd2453ce0adeb282aeb
[ "MIT" ]
1
2019-03-16T06:40:26.000Z
2019-03-16T06:40:26.000Z
#include "DXUT.h" #include "DXUTCamera.h" #include "SDKmisc.h" #include "LensflareManager.h" extern float g_fAspectRatio; extern ID3D11Device* g_pDevice; extern CFirstPersonCamera g_Camera; HRESULT CompileShader(PWCHAR strPath, D3D10_SHADER_MACRO* pMacros, char* strEntryPoint, char* strProfile, DWORD dwShaderFlags, ID3DBlob** ppVertexShaderBuffer); struct CB_LENSFLARE_VS { D3DXVECTOR4 Position; D3DXVECTOR4 ScaleRotate; D3DXVECTOR4 Color; }; CLensflareManager::CLensflareManager() : m_pPredicate(NULL), m_pOcclusionQuery(NULL), m_pNoDepthState(NULL), m_pAddativeBlendState(NULL), m_pNoColorBlendState(NULL), m_pLensflareCB(NULL), m_pLensflareVS(NULL), m_pLensflarePS(NULL), m_pCoronaTexView(NULL), m_pFlareTexView(NULL), m_fSunVisibility(0.0f), m_bQuerySunVisibility(true), m_fCoronaRotation(0.0f) { } CLensflareManager::~CLensflareManager() { } HRESULT CLensflareManager::Init() { HRESULT hr; D3D11_QUERY_DESC queryDesc; queryDesc.Query = D3D11_QUERY_OCCLUSION_PREDICATE; queryDesc.MiscFlags = 0; V_RETURN( g_pDevice->CreatePredicate(&queryDesc, &m_pPredicate) ); DXUT_SetDebugName( m_pPredicate, "Lens Flare - Predicate"); queryDesc.Query = D3D11_QUERY_OCCLUSION; V_RETURN( g_pDevice->CreateQuery(&queryDesc, &m_pOcclusionQuery) ); DXUT_SetDebugName( m_pOcclusionQuery, "Lens Flare - Occlusion Query"); m_fSunVisibility = 0.0f; m_bQuerySunVisibility = true; // Create constant buffers D3D11_BUFFER_DESC cbDesc; ZeroMemory( &cbDesc, sizeof(cbDesc) ); cbDesc.Usage = D3D11_USAGE_DYNAMIC; cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; cbDesc.ByteWidth = CLensflareManager::m_TotalFlares * sizeof( CB_LENSFLARE_VS ); V_RETURN( g_pDevice->CreateBuffer( &cbDesc, NULL, &m_pLensflareCB ) ); DXUT_SetDebugName( m_pLensflareCB, "Lensflare CB" ); // Compile the shaders DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS; #if defined( DEBUG ) || defined( _DEBUG ) // Set the D3DCOMPILE_DEBUG flag to embed debug information in the shaders. // Setting this flag improves the shader debugging experience, but still allows // the shaders to be optimized and to run exactly the way they will run in // the release configuration of this program. dwShaderFlags |= D3DCOMPILE_DEBUG; #endif WCHAR str[MAX_PATH]; V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"Lensflare.hlsl" ) ); ID3DBlob* pShaderBuffer = NULL; V_RETURN( CompileShader(str, NULL, "LensflareVS", "vs_5_0", dwShaderFlags, &pShaderBuffer) ); V_RETURN( g_pDevice->CreateVertexShader( pShaderBuffer->GetBufferPointer(), pShaderBuffer->GetBufferSize(), NULL, &m_pLensflareVS ) ); DXUT_SetDebugName( m_pLensflareVS, "LensflareVS" ); SAFE_RELEASE( pShaderBuffer ); V_RETURN( CompileShader(str, NULL, "LensflarePS", "ps_5_0", dwShaderFlags, &pShaderBuffer) ); V_RETURN( g_pDevice->CreatePixelShader( pShaderBuffer->GetBufferPointer(), pShaderBuffer->GetBufferSize(), NULL, &m_pLensflarePS ) ); DXUT_SetDebugName( m_pLensflarePS, "LensfalrePS" ); SAFE_RELEASE( pShaderBuffer ); // Load the corona texture V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"..\\Media\\Corona.dds" ) ); V_RETURN( D3DX11CreateShaderResourceViewFromFile( g_pDevice, str, NULL, NULL, &m_pCoronaTexView, NULL ) ); // Load the flares texture V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"..\\Media\\Flare.dds" ) ); V_RETURN( D3DX11CreateShaderResourceViewFromFile( g_pDevice, str, NULL, NULL, &m_pFlareTexView, NULL ) ); D3D11_DEPTH_STENCIL_DESC descDepth; descDepth.DepthEnable = FALSE; descDepth.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO; descDepth.DepthFunc = D3D11_COMPARISON_LESS; descDepth.StencilEnable = FALSE; descDepth.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK; descDepth.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK; const D3D11_DEPTH_STENCILOP_DESC defaultStencilOp = { D3D11_STENCIL_OP_KEEP, D3D11_STENCIL_OP_KEEP, D3D11_STENCIL_OP_KEEP, D3D11_COMPARISON_ALWAYS }; descDepth.FrontFace = defaultStencilOp; descDepth.BackFace = defaultStencilOp; V_RETURN( g_pDevice->CreateDepthStencilState(&descDepth, &m_pNoDepthState) ); DXUT_SetDebugName( m_pNoDepthState, "Lens Flare - No Depth DS" ); D3D11_BLEND_DESC descBlend; descBlend.AlphaToCoverageEnable = FALSE; descBlend.IndependentBlendEnable = FALSE; D3D11_RENDER_TARGET_BLEND_DESC TRBlenddDesc = { TRUE, D3D11_BLEND_ONE, D3D11_BLEND_ONE, D3D11_BLEND_OP_ADD, D3D11_BLEND_ONE, D3D11_BLEND_ONE, D3D11_BLEND_OP_ADD, D3D11_COLOR_WRITE_ENABLE_ALL, }; for (UINT i = 0; i < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i) descBlend.RenderTarget[ i ] = TRBlenddDesc; V_RETURN( g_pDevice->CreateBlendState(&descBlend, &m_pAddativeBlendState) ); DXUT_SetDebugName( m_pAddativeBlendState, "Lenst Flare - Addative Blending BS" ); TRBlenddDesc.BlendEnable = FALSE; TRBlenddDesc.RenderTargetWriteMask = 0; for (UINT i = 0; i < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i) descBlend.RenderTarget[ i ] = TRBlenddDesc; V_RETURN( g_pDevice->CreateBlendState(&descBlend, &m_pNoColorBlendState) ); DXUT_SetDebugName( m_pNoColorBlendState, "Lens Flare - No Color BS" ); m_arrFlares[0].fOffset = 0.0f; m_arrFlares[0].fScale = 0.028f; m_arrFlares[0].Color = D3DXVECTOR4(0.2f, 0.18f, 0.15f, 0.25f); m_arrFlares[1].fOffset = 0.0f; m_arrFlares[1].fScale = 0.028f; m_arrFlares[1].Color = D3DXVECTOR4(0.2f, 0.18f, 0.15f, 0.25f); m_arrFlares[2].fOffset = 0.0f; m_arrFlares[2].fScale = 0.028f; m_arrFlares[2].Color = D3DXVECTOR4(0.2f, 0.18f, 0.15f, 0.25f); m_arrFlares[3].fOffset = 0.0f; m_arrFlares[3].fScale = 0.028f; m_arrFlares[3].Color = D3DXVECTOR4(0.2f, 0.18f, 0.15f, 0.25f); m_arrFlares[4].fOffset = 0.5f; m_arrFlares[4].fScale = 0.075f; m_arrFlares[4].Color = D3DXVECTOR4(0.2f, 0.3f, 0.55f, 1.0f); m_arrFlares[5].fOffset = 1.0f; m_arrFlares[5].fScale = 0.054f; m_arrFlares[5].Color = D3DXVECTOR4(0.024f, 0.2f, 0.52f, 1.0f); m_arrFlares[6].fOffset = 1.35f; m_arrFlares[6].fScale = 0.095f; m_arrFlares[6].Color = D3DXVECTOR4(0.032f, 0.1f, 0.5f, 1.0f); m_arrFlares[7].fOffset = 0.9f; m_arrFlares[7].fScale = 0.065f; m_arrFlares[7].Color = D3DXVECTOR4(0.13f, 0.14f, 0.58f, 1.0f); m_arrFlares[8].fOffset = 1.55f; m_arrFlares[8].fScale = 0.038f; m_arrFlares[8].Color = D3DXVECTOR4(0.16f, 0.21, 0.44, 1.0f); m_arrFlares[9].fOffset = 0.25f; m_arrFlares[9].fScale = 0.1f; m_arrFlares[9].Color = D3DXVECTOR4(0.23f, 0.21, 0.44, 0.85f); return hr; } void CLensflareManager::Deinit() { SAFE_RELEASE( m_pPredicate ); SAFE_RELEASE( m_pOcclusionQuery ); SAFE_RELEASE( m_pNoDepthState ); SAFE_RELEASE( m_pAddativeBlendState ); SAFE_RELEASE( m_pNoColorBlendState ); SAFE_RELEASE( m_pLensflareCB ); SAFE_RELEASE( m_pLensflareVS ); SAFE_RELEASE( m_pLensflarePS ); SAFE_RELEASE( m_pCoronaTexView ); SAFE_RELEASE( m_pFlareTexView ); } void CLensflareManager::Update(const D3DXVECTOR3& sunWorldPos, float fElapsedTime) { D3DXMATRIX mView = *g_Camera.GetViewMatrix(); D3DXMATRIX mProj = *g_Camera.GetProjMatrix(); D3DXMATRIX mViewProjection = mView * mProj; for(int i=0; i < m_TotalLights; i++) { m_SunWorldPos = sunWorldPos; D3DXVECTOR3 ProjPos; D3DXVec3TransformCoord (&ProjPos, &m_SunWorldPos, &mViewProjection); m_SunPos2D.x = ProjPos.x; m_SunPos2D.y = ProjPos.y; } const float fCoronaRotationSpeed = 0.01f * D3DX_PI; m_fCoronaRotation += fElapsedTime * fCoronaRotationSpeed; } void CLensflareManager::Render(ID3D11DeviceContext* pd3dImmediateContext) { HRESULT hr; pd3dImmediateContext->SetPredication(m_pPredicate, FALSE); m_bQuerySunVisibility = false; UINT64 sunVisibility; if(pd3dImmediateContext->GetData(m_pOcclusionQuery, (void*)&sunVisibility, sizeof(sunVisibility), 0) == S_OK) { m_fSunVisibility = (float)sunVisibility / 700.0f; m_bQuerySunVisibility = true; } ID3D11DepthStencilState* pPrevDepthState; pd3dImmediateContext->OMGetDepthStencilState(&pPrevDepthState, NULL); pd3dImmediateContext->OMSetDepthStencilState(m_pNoDepthState, 0); ID3D11BlendState* pPrevBlendState; FLOAT prevBlendFactor[ 4 ]; UINT prevSampleMask; pd3dImmediateContext->OMGetBlendState(&pPrevBlendState, prevBlendFactor, &prevSampleMask); pd3dImmediateContext->OMSetBlendState(m_pAddativeBlendState, prevBlendFactor, prevSampleMask); pd3dImmediateContext->IASetInputLayout( NULL ); pd3dImmediateContext->IASetVertexBuffers(0, 0, NULL, NULL, NULL); pd3dImmediateContext->VSSetShader( m_pLensflareVS, NULL, 0 ); pd3dImmediateContext->PSSetShader( m_pLensflarePS, NULL, 0 ); // Fill the corona values D3D11_MAPPED_SUBRESOURCE MappedResource; V( pd3dImmediateContext->Map( m_pLensflareCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ) ); CB_LENSFLARE_VS* pCB = ( CB_LENSFLARE_VS* )MappedResource.pData; for(int j=0; j < m_TotalCoronaFlares; j++) { pCB[j].Position = D3DXVECTOR4(m_SunPos2D.x, m_SunPos2D.y, 0.0f, 0.0f); float fSin = sinf(m_fCoronaRotation + static_cast<float>(j) * D3DX_PI / 4.0f + D3DX_PI / 5.0f); float fCos = cosf(m_fCoronaRotation + static_cast<float>(j) * D3DX_PI / 4.0f + D3DX_PI / 5.0f); const float coronaWidthScale = 14.0f; float fScaleX = m_arrFlares[j].fScale * coronaWidthScale; float fScaleY = m_arrFlares[j].fScale; pCB[j].ScaleRotate = D3DXVECTOR4(fScaleX * fCos, fScaleY * -fSin, fScaleX * fSin * g_fAspectRatio, fScaleY * fCos * g_fAspectRatio); pCB[j].Color = m_arrFlares[j].Color * m_fSunVisibility; } pd3dImmediateContext->Unmap( m_pLensflareCB, 0 ); // Render the corona pd3dImmediateContext->PSSetShaderResources( 0, 1, &m_pCoronaTexView ); pd3dImmediateContext->VSSetConstantBuffers( 0, 1, &m_pLensflareCB ); pd3dImmediateContext->Draw(6 * m_TotalCoronaFlares, 0); // Fill the flare values D3DXVECTOR2 dirFlares = D3DXVECTOR2(0.0f, 0.0f) - m_SunPos2D; float fLength = D3DXVec2LengthSq(&dirFlares); dirFlares = dirFlares * (1.0f / fLength); V( pd3dImmediateContext->Map( m_pLensflareCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ) ); pCB = ( CB_LENSFLARE_VS* )MappedResource.pData; for(int j=3; j < m_TotalFlares; j++) { float fOffset = m_arrFlares[j].fOffset * fLength; D3DXVECTOR2 flarePos2D = fOffset * dirFlares + m_SunPos2D; pCB[j-3].Position = D3DXVECTOR4(flarePos2D.x, flarePos2D.y, 0.0f, 0.0f); float fScale = m_arrFlares[j].fScale; pCB[j-3].ScaleRotate = D3DXVECTOR4(fScale, 0.0f, 0.0f, fScale * g_fAspectRatio); pCB[j-3].Color = m_arrFlares[j].Color * m_fSunVisibility; } pd3dImmediateContext->Unmap( m_pLensflareCB, 0 ); // Render the flares pd3dImmediateContext->PSSetShaderResources( 0, 1, &m_pFlareTexView ); pd3dImmediateContext->VSSetConstantBuffers( 0, 1, &m_pLensflareCB ); pd3dImmediateContext->Draw(6 * (m_TotalFlares - m_TotalCoronaFlares), 0); // Restore the blend state pd3dImmediateContext->OMSetDepthStencilState(pPrevDepthState, 0); SAFE_RELEASE( pPrevDepthState ); pd3dImmediateContext->OMSetBlendState(pPrevBlendState, prevBlendFactor, prevSampleMask); SAFE_RELEASE( pPrevBlendState ); pd3dImmediateContext->SetPredication(NULL, FALSE); } void CLensflareManager::BeginSunVisibility(ID3D11DeviceContext* pd3dImmediateContext) { pd3dImmediateContext->OMGetBlendState(&m_pPrevBlendState, m_prevBlendFactor, &m_prevSampleMask); pd3dImmediateContext->OMSetBlendState(m_pNoColorBlendState, m_prevBlendFactor, m_prevSampleMask); pd3dImmediateContext->Begin(m_pPredicate); if(m_bQuerySunVisibility) { pd3dImmediateContext->Begin(m_pOcclusionQuery); } } void CLensflareManager::EndSunVisibility(ID3D11DeviceContext* pd3dImmediateContext) { pd3dImmediateContext->End(m_pPredicate); if(m_bQuerySunVisibility) { pd3dImmediateContext->End(m_pOcclusionQuery); } // Restore the previous blend state pd3dImmediateContext->OMSetBlendState(m_pPrevBlendState, m_prevBlendFactor, m_prevSampleMask); SAFE_RELEASE(m_pPrevBlendState); }
39.266447
165
0.764346
jjuiddong
40645b9aa78cb739fe57666415c51357c04c2105
8,282
cpp
C++
src/aadcUser/BirdsEyeTransform/BirdsEyeTransform.cpp
kimsoohwan/Cariosity2018
49f935623c41d627b45c47a219358f9d7d207fdf
[ "BSD-4-Clause" ]
null
null
null
src/aadcUser/BirdsEyeTransform/BirdsEyeTransform.cpp
kimsoohwan/Cariosity2018
49f935623c41d627b45c47a219358f9d7d207fdf
[ "BSD-4-Clause" ]
null
null
null
src/aadcUser/BirdsEyeTransform/BirdsEyeTransform.cpp
kimsoohwan/Cariosity2018
49f935623c41d627b45c47a219358f9d7d207fdf
[ "BSD-4-Clause" ]
1
2019-10-03T12:23:26.000Z
2019-10-03T12:23:26.000Z
#include "stdafx.h" #include "BirdsEyeTransform.h" #include "ADTF3_OpenCV_helper.h" #include <opencv/cv.h> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/cudaarithm.hpp> #include <opencv2/core/cuda.hpp> #include <opencv2/opencv.hpp> #include <opencv2/cudaimgproc.hpp> /// This defines a data triggered filter and exposes it via a plugin class factory. /// The Triggerfunction cSimpleDataStatistics will be embedded to the Filter /// and called repeatedly (last parameter of this macro)! ADTF_TRIGGER_FUNCTION_FILTER_PLUGIN(CID_CARIOSITY_DATA_TRIGGERED_FILTER, "Birds Eye Transform", fcBirdsEyeTransform, adtf::filter::pin_trigger({ "in" })); fcBirdsEyeTransform::fcBirdsEyeTransform() { //Register Properties RegisterPropertyVariable("ROIOffsetX [%]", m_ROIOffsetX); RegisterPropertyVariable("ROIOffsetY [%]", m_ROIOffsetY); RegisterPropertyVariable("ROIWidth [%]", m_ROIWidth); RegisterPropertyVariable("ROIHeight [%]", m_ROIHeight); RegisterPropertyVariable("Output Height [Pixel]", m_OutputHeight); RegisterPropertyVariable("side inset at top [%]", m_topSideInset); RegisterPropertyVariable("side inset at bottom [%]", m_bottomSideInset); RegisterPropertyVariable("Show ROI, no transform", m_showROIDebug); //create and set inital input format type m_InPinVideoFormat.m_strFormatName = ADTF_IMAGE_FORMAT(RGB_24); adtf::ucom::object_ptr<IStreamType> pTypeInput = adtf::ucom::make_object_ptr<cStreamType>(stream_meta_type_image()); set_stream_type_image_format(*pTypeInput, m_InPinVideoFormat); //Register input pin Register(m_oReaderVideo, "in", pTypeInput); //Register output pins adtf::ucom::object_ptr<IStreamType> pTypeOutput = adtf::ucom::make_object_ptr<cStreamType>(stream_meta_type_image()); set_stream_type_image_format(*pTypeOutput, m_OutPinVideoFormat); Register(m_oWriterVideo, "out", pTypeOutput); //register callback for type changes m_oReaderVideo.SetAcceptTypeCallback([this](const adtf::ucom::ant::iobject_ptr<const adtf::streaming::ant::IStreamType>& pType) -> tResult { return ChangeType(m_oReaderVideo, *pType.Get()); }); } tResult fcBirdsEyeTransform::Configure() { //get clock object RETURN_IF_FAILED(_runtime->GetObject(m_pClock)); RETURN_NOERROR; } tResult fcBirdsEyeTransform::ChangeType(adtf::streaming::cDynamicSampleReader& inputPin, const adtf::streaming::ant::IStreamType& oType) { if (oType == adtf::streaming::stream_meta_type_image()) { adtf::ucom::object_ptr<const adtf::streaming::IStreamType> pTypeInput; // get pType from input reader inputPin >> pTypeInput; adtf::streaming::get_stream_type_image_format(m_InPinVideoFormat, *pTypeInput); //set also output format adtf::streaming::get_stream_type_image_format(m_OutPinVideoFormat, *pTypeInput); // and set pType also to samplewriter m_oWriterVideo << pTypeInput; } else { RETURN_ERROR(ERR_INVALID_TYPE); } RETURN_NOERROR; } tResult fcBirdsEyeTransform::Process(tTimeStamp tmTimeOfTrigger) { object_ptr<const ISample> pReadSample; if (IS_OK(m_oReaderVideo.GetNextSample(pReadSample))) { object_ptr_shared_locked<const ISampleBuffer> pReadBuffer; Mat outputImage; cv::cuda::GpuMat dst, src; //lock read buffer if (IS_OK(pReadSample->Lock(pReadBuffer))) { RETURN_IF_FAILED(checkRoi()); Size inputSize = cv::Size(m_InPinVideoFormat.m_ui32Width, m_InPinVideoFormat.m_ui32Height); //create a opencv matrix from the media sample buffer Mat inputImage(inputSize, CV_8UC3, (uchar*)pReadBuffer->GetPtr()); inputImage = inputImage.clone(); Rect roi( inputSize.width * m_ROIOffsetX, inputSize.height * m_ROIOffsetY, inputSize.width * m_ROIWidth, inputSize.height * m_ROIHeight ); tInt64 aspectRatio = roi.width / roi.height; Size outputSize = cv::Size(m_OutputHeight * aspectRatio , m_OutputHeight); Point2f src_vertices[4]; src_vertices[0] = Point2f(roi.x, roi.y); src_vertices[1] = Point2f(roi.x + roi.width, roi.y); src_vertices[2] = Point2f(roi.x + roi.width, roi.y + roi.height); src_vertices[3] = Point2f(roi.x, roi.y + roi.height); Point2f dst_vertices[4]; dst_vertices[0] = Point2f(roi.x + roi.width * m_topSideInset, roi.y); // Point2f(inputSize.width * m_topSideInset, 0); dst_vertices[1] = Point2f(roi.x + roi.width * (1.0f - m_topSideInset), roi.y); // Point2f(inputSize.width * (1.0f - m_topSideInset), 0); dst_vertices[2] = Point2f(roi.x + (1.0f - m_bottomSideInset) * roi.width, roi.y + roi.height); // Point2f(inputSize.width * (1.0f - m_bottomSideInset), inputSize.height); dst_vertices[3] = Point2f(roi.x + m_bottomSideInset * roi.width, roi.y + roi.height); // Point2f(inputSize.width * m_bottomSideInset, inputSize.height); Mat M = getPerspectiveTransform(src_vertices, dst_vertices); if(m_showROIDebug) { outputImage = inputImage.clone(); line(outputImage, src_vertices[0], src_vertices[1], Scalar(0,255,255), 2); line(outputImage, src_vertices[1], src_vertices[2], Scalar(0,255,255), 2); line(outputImage, src_vertices[2], src_vertices[3], Scalar(0,255,255), 2); line(outputImage, src_vertices[3], src_vertices[0], Scalar(0,255,255), 2); line(outputImage, dst_vertices[0], dst_vertices[1], Scalar(255,255,255), 2); line(outputImage, dst_vertices[1], dst_vertices[2], Scalar(255,255,255), 2); line(outputImage, dst_vertices[2], dst_vertices[3], Scalar(255,255,255), 2); line(outputImage, dst_vertices[3], dst_vertices[0], Scalar(255,255,255), 2); resize(outputImage, outputImage, outputSize); } else { src.upload(inputImage); cv::cuda::warpPerspective(src, dst, M, inputSize, INTER_LINEAR, BORDER_CONSTANT); // cv::cuda::resize(dst, dst, outputSize); dst.download(outputImage); outputImage = outputImage(roi).clone(); } pReadBuffer->Unlock(); } //copy to outputimage //Write processed Image to Output Pin if (!outputImage.empty()) { //update output format if matrix size does not fit to if (outputImage.total() * outputImage.elemSize() != m_OutPinVideoFormat.m_szMaxByteSize) { setTypeFromMat(m_oWriterVideo, outputImage); } // write to pin writeMatToPin(m_oWriterVideo, outputImage, m_pClock->GetStreamTime()); } } RETURN_NOERROR; } tResult fcBirdsEyeTransform::checkRoi(void) { // if width or heigt are not set ignore the roi if (static_cast<tFloat32>(m_ROIWidth) == 0 || static_cast<tFloat32>(m_ROIHeight) == 0) { LOG_ERROR("ROI width or height is not set!"); RETURN_ERROR_DESC(ERR_INVALID_ARG, "ROI width or height is not set!"); } //check if we are within the boundaries of the image if ((static_cast<tFloat32>(m_ROIOffsetX) + static_cast<tFloat32>(m_ROIWidth)) > m_InPinVideoFormat.m_ui32Width) { LOG_ERROR("ROI is outside of image"); RETURN_ERROR_DESC(ERR_INVALID_ARG, "ROI is outside of image"); } if ((static_cast<tFloat32>(m_ROIOffsetY) + static_cast<tFloat32>(m_ROIHeight)) > m_InPinVideoFormat.m_ui32Height) { LOG_ERROR("ROI is outside of image"); RETURN_ERROR_DESC(ERR_INVALID_ARG, "ROI is outside of image"); } //create the rectangle m_LaneRoi = cv::Rect2f(static_cast<tFloat32>(m_ROIOffsetX), static_cast<tFloat32>(m_ROIOffsetY), static_cast<tFloat32>(m_ROIWidth), static_cast<tFloat32>(m_ROIHeight)); RETURN_NOERROR; }
42.040609
182
0.655277
kimsoohwan
406486fd3719f11df98280a5ba769ea3eef2ae14
1,720
hpp
C++
include/limitless/fx/modules/custom_material.hpp
Tehsapper/graphics-engine
5b7cd93c750ccce7b254c6bb4a13948b2b4ec975
[ "MIT" ]
9
2020-07-23T13:00:12.000Z
2021-01-07T10:44:24.000Z
include/limitless/fx/modules/custom_material.hpp
Tehsapper/graphics-engine
5b7cd93c750ccce7b254c6bb4a13948b2b4ec975
[ "MIT" ]
7
2020-09-11T18:23:45.000Z
2020-11-01T19:05:47.000Z
include/limitless/fx/modules/custom_material.hpp
Tehsapper/graphics-engine
5b7cd93c750ccce7b254c6bb4a13948b2b4ec975
[ "MIT" ]
3
2020-08-24T01:59:48.000Z
2021-02-18T16:41:27.000Z
#pragma once #include <limitless/fx/modules/module.hpp> namespace Limitless::fx { template<typename Particle> class CustomMaterial : public Module<Particle> { private: std::array<std::unique_ptr<Distribution<float>>, 4> properties; public: CustomMaterial(std::unique_ptr<Distribution<float>> prop1, std::unique_ptr<Distribution<float>> prop2, std::unique_ptr<Distribution<float>> prop3, std::unique_ptr<Distribution<float>> prop4 ) noexcept : Module<Particle>(ModuleType::CustomMaterial) , properties {std::move(prop1), std::move(prop2), std::move(prop3), std::move(prop4)} {} ~CustomMaterial() override = default; CustomMaterial(const CustomMaterial& module) : Module<Particle>(module.type){ for (size_t i = 0; i < module.properties.size(); ++i) { if (module.properties[i]) { properties[i] = std::unique_ptr<Distribution<float>>(module.properties[i]->clone()); } } } auto& getProperties() noexcept { return properties; } const auto& getProperties() const noexcept { return properties; } void initialize([[maybe_unused]] AbstractEmitter& emitter, Particle& particle, [[maybe_unused]] size_t index) noexcept override { for (size_t i = 0; i < properties.size(); ++i) { if (properties[i]) { particle.properties[i] = properties[i]->get(); } } } [[nodiscard]] CustomMaterial* clone() const override { return new CustomMaterial(*this); } }; }
39.090909
137
0.575581
Tehsapper
40664a29a8104c19ccfcaf385df93666aa2e4865
5,139
cpp
C++
native/common/file_descriptor.cpp
kaloianm/rural-pipe
7bdae362f360da3114282512ef2c0d01e621a4c1
[ "Unlicense" ]
null
null
null
native/common/file_descriptor.cpp
kaloianm/rural-pipe
7bdae362f360da3114282512ef2c0d01e621a4c1
[ "Unlicense" ]
1
2021-02-18T18:35:46.000Z
2021-02-18T18:35:46.000Z
native/common/file_descriptor.cpp
kaloianm/rural-pipe
7bdae362f360da3114282512ef2c0d01e621a4c1
[ "Unlicense" ]
null
null
null
/** * Copyright 2020 Kaloian Manassiev * * 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 "common/base.h" #include "common/file_descriptor.h" #include <boost/log/trivial.hpp> #include <poll.h> #include <sstream> #include <sys/ioctl.h> #include <unistd.h> #include "common/exception.h" namespace ruralpi { FileDescriptor::FileDescriptor(const std::string &desc, int fd) : _desc(desc), _fd(fd) { SYSCALL_MSG(_fd, boost::format("Could not open file descriptor (%d): %s") % _fd % _desc); } FileDescriptor::FileDescriptor(const FileDescriptor &) = default; FileDescriptor::FileDescriptor(FileDescriptor &&other) { *this = std::move(other); } FileDescriptor &FileDescriptor::operator=(FileDescriptor &&other) { _desc = std::move(other._desc); _fd = other._fd; other._fd = -1; return *this; } void FileDescriptor::makeNonBlocking() { int flags = SYSCALL(::fcntl(_fd, F_GETFL)); SYSCALL(::fcntl(_fd, F_SETFL, flags | O_NONBLOCK)); } int FileDescriptor::availableToRead() { int nAvailable; SYSCALL(::ioctl(_fd, FIONREAD, &nAvailable)); return nAvailable; } int FileDescriptor::readNonBlocking(void *buf, size_t nbytes) { int nRead = ::read(_fd, buf, nbytes); if (nRead < 0 && (errno == EWOULDBLOCK || errno == EAGAIN)) return nRead; SYSCALL_MSG(nRead, boost::format("Failed to read from file descriptor (%d): %s") % _fd % _desc); return nRead; } int FileDescriptor::read(void *buf, size_t nbytes) { while (true) { int nRead = readNonBlocking(buf, nbytes); if (nRead > 0) { return nRead; } else if (nRead == 0) { throw SystemException( boost::format("Failed to read from closed file descriptor (%d): %s") % _fd % _desc); } else if (nRead < 0 && (errno == EWOULDBLOCK || errno == EAGAIN)) { poll(Milliseconds(-1), POLLIN); } } } int FileDescriptor::writeNonBlocking(void const *buf, size_t nbytes) { int nWritten = ::write(_fd, buf, nbytes); if (nWritten < 0 && (errno == EWOULDBLOCK || errno == EAGAIN)) return nWritten; SYSCALL_MSG(nWritten, boost::format("Failed to write to file descriptor (%d): %s") % _fd % _desc); return nWritten; } int FileDescriptor::write(void const *buf, size_t nbytes) { while (true) { int nWritten = writeNonBlocking(buf, nbytes); if (nWritten > 0) { return nWritten; } else if (nWritten == 0) { throw SystemException( boost::format("Failed to write to closed file descriptor (%d): %s") % _fd % _desc); } else if (nWritten < 0 && (errno == EWOULDBLOCK || errno == EAGAIN)) { poll(Milliseconds(-1), POLLOUT); } } } int FileDescriptor::poll(Milliseconds timeout, short events) { pollfd fd; fd.fd = _fd; fd.events = events; return SYSCALL(::poll(&fd, 1, timeout.count())); } std::string FileDescriptor::toString() const { std::stringstream ss; ss << _desc << " (fd " << _fd << ')'; return ss.str(); } ScopedFileDescriptor::ScopedFileDescriptor(const std::string &desc, int fd) : FileDescriptor(desc, fd) { BOOST_LOG_TRIVIAL(debug) << boost::format("File descriptor created (%d): %s") % _fd % _desc; } ScopedFileDescriptor::ScopedFileDescriptor(ScopedFileDescriptor &&other) = default; ScopedFileDescriptor &ScopedFileDescriptor::operator=(ScopedFileDescriptor &&) = default; ScopedFileDescriptor::~ScopedFileDescriptor() { close(); } void ScopedFileDescriptor::close() { if (_fd > 0) { BOOST_LOG_TRIVIAL(debug) << boost::format("File descriptor closed (%d): %s") % _fd % _desc; if (::close(_fd) < 0) { BOOST_LOG_TRIVIAL(debug) << (boost::format("File descriptor close failed (%d): %s") % _fd % _desc) << ": " << SystemException::getLastError(); } _fd = -1; return; } else if (_fd == -1) { return; } RASSERT_MSG(false, boost::format("Illegal file descriptor (%d): %s") % _fd % _desc.c_str()); } } // namespace ruralpi
33.809211
100
0.650905
kaloianm
4066a29a25316d7395e4cd3fb2a5065ea0b53be4
1,554
cpp
C++
src/analysis/ismt/cvc_context.cpp
gdslang/summy
bd450278f18859eb94d1f30b7b878bbb1b94c42c
[ "Apache-2.0" ]
null
null
null
src/analysis/ismt/cvc_context.cpp
gdslang/summy
bd450278f18859eb94d1f30b7b878bbb1b94c42c
[ "Apache-2.0" ]
null
null
null
src/analysis/ismt/cvc_context.cpp
gdslang/summy
bd450278f18859eb94d1f30b7b878bbb1b94c42c
[ "Apache-2.0" ]
null
null
null
/* * cvc_context.cpp * * Created on: Nov 7, 2014 * Author: Julian Kranz */ #include <summy/analysis/ismt/cvc_context.h> #include <cvc4/cvc4.h> #include <string> #include <sstream> using namespace std; using namespace CVC4; analysis::cvc_context::cvc_context(bool unsat_cores) : smtEngine(&manager) { smtEngine.setOption("produce-models", SExpr("true")); smtEngine.setOption("incremental", SExpr("true")); if(unsat_cores) { smtEngine.setOption("produce-unsat-cores", SExpr("true")); // smtEngine.setOption("tear-down-incremental", SExpr("true")); } mem_type = manager.mkArrayType(manager.mkBitVectorType(61), manager.mkBitVectorType(64)); } CVC4::Expr analysis::cvc_context::var(std::string name) { auto i_it = var_map.find(name); if(i_it != var_map.end()) return i_it->second; else { Expr i_exp = manager.mkVar(name, manager.mkBitVectorType(64)); var_map[name] = i_exp; return i_exp; } } CVC4::Expr analysis::cvc_context::memory(memory_map_t &m, string base, size_t rev) { auto rev_it = m.find(rev); if(rev_it != m.end()) return rev_it->second; else { stringstream name; name << base << rev; Expr mem = manager.mkVar(name.str(), mem_type); m[rev] = mem; return mem; } } //CVC4::Expr analysis::cvc_context::var_def(std::string name) { // return var(name + "_def"); //} CVC4::Expr analysis::cvc_context::memory(size_t rev) { return memory(mem_map, "m_", rev); } CVC4::Expr analysis::cvc_context::memory_def(size_t rev) { return memory(mem_def_map, "m_def_", rev); }
25.9
91
0.680824
gdslang
4066afef5b51d9dfebfa257a88ce8d96a17ed2e7
4,334
hpp
C++
csrc/op/masked_multi_head_attention.hpp
dumpmemory/EET
4b98e2ec8fa91d73fd9d713a65e30b1f4bf35af2
[ "Apache-2.0" ]
null
null
null
csrc/op/masked_multi_head_attention.hpp
dumpmemory/EET
4b98e2ec8fa91d73fd9d713a65e30b1f4bf35af2
[ "Apache-2.0" ]
null
null
null
csrc/op/masked_multi_head_attention.hpp
dumpmemory/EET
4b98e2ec8fa91d73fd9d713a65e30b1f4bf35af2
[ "Apache-2.0" ]
null
null
null
#ifndef _OP_MASKED_MULTI_HEAD_ATTENTION_HPP_ #define _OP_MASKED_MULTI_HEAD_ATTENTION_HPP_ #include "op/common.hpp" #include "op/mmanager.hpp" #include "op/meta_desc.hpp" // #include "op/allocator.hpp" namespace eet{ namespace op{ class MaskedMultiHeadAttention : public OpBase{ public: MaskedMultiHeadAttention(MetaDesc desc, const torch::Tensor& QKV_weights, const torch::Tensor& Q_bias, const torch::Tensor& K_bias, const torch::Tensor& V_bias, const torch::Tensor& Output_weights, const torch::Tensor& Output_bias, const torch::Tensor& layernorm_weights, const torch::Tensor& layernorm_bias); torch::Tensor forward(torch::Tensor& input, const torch::Tensor& pre_padding_len, const torch::Tensor& reorder_state, bool pre_layernorm, bool add_redusial, bool first_pass); // full decode torch::Tensor forward_full(torch::Tensor& input, const torch::Tensor& pre_padding_length, bool pre_layernorm, bool add_redusial); // incremental decode torch::Tensor forward_inc(torch::Tensor& input, const torch::Tensor& pre_padding_len, const torch::Tensor& reorder_state, bool pre_layernorm, bool add_redusial); ~MaskedMultiHeadAttention(){ // check_cuda_error(cudaFree(&fused_qkv_ptr_)); }; private: // TODO layernorm void layer_norm(const torch::Tensor& input_tensor, Buffer& layernorm_query); void qkv_weights_mul(void* input, Buffer& qkv_buffer); void qkv_add_bias(const Buffer& qkv_buffer, Buffer& q_buf, Buffer& k_buf, Buffer& v_buf); void q_k_mul(const Buffer& q_buf, const Buffer& k_buf, Buffer& qk_buf); void qk_softmax(Buffer& qk_buf,const int64_t *padding_len); void attn_v_mul(const Buffer& qk_buf, const Buffer& v_buf, Buffer& transpose_dst); void transpose(const Buffer& transpose_dst, Buffer& dst); void project(const Buffer& dst, Buffer& res, torch::Tensor& input, bool pre_layernorm, bool add_redusial); void masked_attention(const Buffer& qkv_buffer, Buffer& context_buf, const int64_t *padding_len, const int64_t *reorder_index); void kv_transpose(torch::Tensor& d_K_buf, torch::Tensor& d_V_buf,Buffer& K_buf,Buffer& V_buf); MetaDesc desc_; // torch::Tensor output_; torch::Tensor k_cache_, v_cache_; cublasGemmAlgo_t qkv_weights_algo_, q_k_algo_, attn_v_algo_; int cur_batch_size_; int first_batch_size_; int cur_seq_len_; int size_per_head_; int step_; void* alpha_; void* beta_; void* atten_scaler_; void* fused_qkv_ptr_; void** qkv_input_; void** qkv_kernel_; void** qkv_buf_; private: void* qkv_weights_; void* q_bias_; void* k_bias_; void* v_bias_; void* output_weights_; void* output_bias_; void* layernorm_weights_; void* layernorm_bias_; }; } } #endif
37.362069
106
0.472543
dumpmemory
406b97028ccb28cab9c9edfb9485e4646e797cca
4,215
cc
C++
chrome/browser/lookalikes/lookalike_url_navigation_throttle_unittest.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
chrome/browser/lookalikes/lookalike_url_navigation_throttle_unittest.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/browser/lookalikes/lookalike_url_navigation_throttle_unittest.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/lookalikes/lookalike_url_navigation_throttle.h" #include "base/test/bind.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "components/lookalikes/core/features.h" #include "components/reputation/core/safety_tip_test_utils.h" #include "components/url_formatter/spoof_checks/idn_spoof_checker.h" #include "components/url_formatter/url_formatter.h" #include "content/public/test/mock_navigation_handle.h" #include "testing/gtest/include/gtest/gtest.h" namespace lookalikes { class LookalikeThrottleTest : public ChromeRenderViewHostTestHarness {}; // Tests that spoofy hostnames are properly handled in the throttle. TEST_F(LookalikeThrottleTest, SpoofsBlocked) { base::HistogramTester test; reputation::InitializeSafetyTipConfig(); const struct TestCase { const char* hostname; bool expected_blocked; url_formatter::IDNSpoofChecker::Result expected_spoof_check_result; } kTestCases[] = { // ASCII private domain. {"private.hostname", false, url_formatter::IDNSpoofChecker::Result::kNone}, // lɔlocked.com, fails ICU spoof checks. {"xn--llocked-9bd.com", true, url_formatter::IDNSpoofChecker::Result::kICUSpoofChecks}, // þook.com, contains a TLD specific character (þ). {"xn--ook-ooa.com", true, url_formatter::IDNSpoofChecker::Result::kTLDSpecificCharacters}, // example·com.com, unsafe middle dot. {"xn--examplecom-rra.com", true, url_formatter::IDNSpoofChecker::Result::kUnsafeMiddleDot}, // scope.com, with scope in Cyrillic. Whole script confusable. {"xn--e1argc3h.com", true, url_formatter::IDNSpoofChecker::Result::kWholeScriptConfusable}, // Non-ASCII Latin with Non-Latin character {"xn--caf-dma9024xvpg.kr", true, url_formatter::IDNSpoofChecker::Result:: kNonAsciiLatinCharMixedWithNonLatin}, // testーsite.com, has dangerous pattern (ー is CJK character). {"xn--testsite-1g5g.com", true, url_formatter::IDNSpoofChecker::Result::kDangerousPattern}, // TODO(crbug.com/1100485): Add an example for digit lookalikes. // 🍕.com, fails ICU spoof checks, but is allowed because consists of only // emoji and ASCII. {"xn--vi8h.com", false, url_formatter::IDNSpoofChecker::Result::kICUSpoofChecks}, // sparkasse-gießen.de, has a deviation character (ß). This is in punycode // because GURL canonicalizes ß to ss. {"xn--sparkasse-gieen-2ib.de", false, url_formatter::IDNSpoofChecker::Result::kDeviationCharacters}, }; base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature( lookalikes::features::kLookalikeInterstitialForPunycode); for (const TestCase& test_case : kTestCases) { url_formatter::IDNConversionResult idn_result = url_formatter::UnsafeIDNToUnicodeWithDetails(test_case.hostname); ASSERT_EQ(test_case.expected_spoof_check_result, idn_result.spoof_check_result) << test_case.hostname; GURL url(std::string("http://") + test_case.hostname); content::MockNavigationHandle handle(url, main_rfh()); handle.set_redirect_chain({url}); handle.set_page_transition(ui::PAGE_TRANSITION_TYPED); auto throttle = LookalikeUrlNavigationThrottle::MaybeCreateNavigationThrottle(&handle); ASSERT_TRUE(throttle); throttle->SetUseTestProfileForTesting(); EXPECT_EQ(content::NavigationThrottle::PROCEED, throttle->WillStartRequest().action()); if (test_case.expected_blocked) { EXPECT_EQ(content::NavigationThrottle::CANCEL, throttle->WillProcessResponse().action()) << "Failed: " << test_case.hostname; } else { EXPECT_EQ(content::NavigationThrottle::PROCEED, throttle->WillProcessResponse().action()) << "Failed: " << test_case.hostname; } } } } // namespace lookalikes
39.764151
80
0.7172
Ron423c
406def49682fe2b251bb469e529554cb8e02c00c
5,872
cpp
C++
device/built_ins/x64/gen8/aux_translation_Gen8core.cpp
shuangwan01/compute-runtime
efdd870b92c22beb9211f4a4ceaa2f062b84b7d3
[ "MIT" ]
null
null
null
device/built_ins/x64/gen8/aux_translation_Gen8core.cpp
shuangwan01/compute-runtime
efdd870b92c22beb9211f4a4ceaa2f062b84b7d3
[ "MIT" ]
1
2019-09-17T08:06:24.000Z
2019-09-17T08:06:24.000Z
device/built_ins/x64/gen8/aux_translation_Gen8core.cpp
shuangwan01/compute-runtime
efdd870b92c22beb9211f4a4ceaa2f062b84b7d3
[ "MIT" ]
2
2019-09-12T05:03:02.000Z
2020-03-12T02:17:34.000Z
#include <cstddef> #include <cstdint> size_t AuxTranslationBinarySize_Gen8core = 1692; uint32_t AuxTranslationBinary_Gen8core[423] = { 0x494e5443, 0x00000420, 0x0000000b, 0x00000008, 0x00000001, 0x00000000, 0x00000000, 0x2f674870, 0xad5c17e9, 0x304ea729, 0x0000000c, 0x000003a0, 0x000001c0, 0x00000000, 0x00000020, 0x000000cc, 0x00000140, 0x6c6c7566, 0x79706f43, 0x00000000, 0x00008006, 0x30000004, 0x16001000, 0x04c004c0, 0x202d8041, 0x00090800, 0x20004d01, 0x00007f07, 0x00800040, 0x20600a28, 0x12000100, 0x00b10020, 0x00802040, 0x20a00a28, 0x12000100, 0x00b10040, 0x20019640, 0x07030307, 0x00802040, 0x20a00a28, 0x0a8d00a0, 0x000000e0, 0x00800009, 0x21400a28, 0x1e8d0060, 0x00040004, 0x00802009, 0x21800a28, 0x1e8d00a0, 0x00040004, 0x0c800031, 0x21c03a68, 0x068d0140, 0x04805000, 0x20005601, 0x000a1e07, 0x0c802031, 0x22c03a68, 0x068d0180, 0x04805000, 0x00802001, 0x25000208, 0x008d0180, 0x00000000, 0x2002d601, 0x000e2007, 0x2002d601, 0x00102207, 0x2002d601, 0x00122407, 0x2002d601, 0x00142607, 0x00802001, 0x25400a28, 0x008d02c0, 0x00000000, 0x00802001, 0x25800a28, 0x008d0300, 0x00000000, 0x00802001, 0x25c00a28, 0x008d0340, 0x00000000, 0x00802001, 0x26000a28, 0x008d0380, 0x00000000, 0x0c800031, 0x20003a60, 0x068d03c0, 0x14025001, 0x0c802031, 0x20003a60, 0x068d0500, 0x14025001, 0x07600031, 0x20003a04, 0x068d0fe0, 0x82000010, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x000000c3, 0x00000000, 0x00000000, 0x00000003, 0x83ffc000, 0x03000000, 0x1fff007f, 0x0fe00000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x83ffc000, 0x03000000, 0x1fff007f, 0x0fe00000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x87ffc000, 0x03000000, 0x1fff007f, 0x0fe00000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000040, 0x00000080, 0x00000013, 0x0000000c, 0x00000000, 0x00000015, 0x00000018, 0x00000000, 0x00000000, 0x00000000, 0x000000c0, 0x00000008, 0x00000014, 0x000000c0, 0x00000003, 0x00000000, 0x00000011, 0x00000028, 0x00000010, 0x00000000, 0x00000000, 0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000011, 0x00000028, 0x00000010, 0x00000000, 0x00000004, 0x00000004, 0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000011, 0x00000028, 0x00000010, 0x00000000, 0x00000008, 0x00000004, 0x00000008, 0x00000000, 0x00000000, 0x00000000, 0x00000011, 0x00000028, 0x00000002, 0x00000000, 0x0000000c, 0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000011, 0x00000028, 0x00000002, 0x00000000, 0x00000010, 0x00000004, 0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000011, 0x00000028, 0x00000002, 0x00000000, 0x00000014, 0x00000004, 0x00000008, 0x00000000, 0x00000000, 0x00000000, 0x00000011, 0x00000028, 0x0000002b, 0x00000000, 0x00000020, 0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000011, 0x00000028, 0x0000002b, 0x00000001, 0x00000028, 0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000011, 0x00000028, 0x0000001c, 0x00000000, 0x00000040, 0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000011, 0x00000028, 0x0000001c, 0x00000000, 0x00000044, 0x00000004, 0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000011, 0x00000028, 0x0000001c, 0x00000000, 0x00000048, 0x00000004, 0x00000008, 0x00000000, 0x00000000, 0x00000000, 0x0000001e, 0x00000024, 0x00000000, 0x00000000, 0x00000020, 0x00000008, 0xffffffff, 0xffffffff, 0x00000000, 0x0000001e, 0x00000024, 0x00000001, 0x00000040, 0x00000028, 0x00000008, 0xffffffff, 0xffffffff, 0x00000000, 0x00000026, 0x00000018, 0x00000080, 0x00000030, 0x00000008, 0x00000000, 0x00000019, 0x0000000c, 0x00000060, 0x00000016, 0x00000040, 0x00000000, 0x00000001, 0x00000001, 0x00000001, 0x00000000, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000017, 0x00000064, 0x00000000, 0x00000000, 0x00000000, 0x00000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0x00000000, 0x00000080, 0x00000000, 0x00000000, 0x00000000, 0x0000001b, 0x00000010, 0x00000004, 0x00000000, 0x0000001a, 0x00000048, 0x00000000, 0x0000000c, 0x00000008, 0x00000004, 0x00000008, 0x00000008, 0x6c675f5f, 0x6c61626f, 0x00000000, 0x454e4f4e, 0x00000000, 0x00637273, 0x746e6975, 0x00383b2a, 0x736e6f63, 0x00000074, 0x0000001a, 0x00000048, 0x00000001, 0x0000000c, 0x00000008, 0x00000004, 0x00000008, 0x00000008, 0x6c675f5f, 0x6c61626f, 0x00000000, 0x454e4f4e, 0x00000000, 0x00747364, 0x746e6975, 0x00383b2a, 0x454e4f4e, 0x00000000}; #include "runtime/built_ins/registry/built_ins_registry.h" namespace NEO { static RegisterEmbeddedResource registerAuxTranslationBin( createBuiltinResourceName( EBuiltInOps::AuxTranslation, BuiltinCode::getExtension(BuiltinCode::ECodeType::Binary), "Gen8core", 0) .c_str(), (const char *)AuxTranslationBinary_Gen8core, AuxTranslationBinarySize_Gen8core); }
82.704225
100
0.790531
shuangwan01
406e6a83249ee895b4022c368f06af962166f4b4
2,059
cc
C++
Algorithms/Difference/Difference.cc
jwillemsen/sidecar
941d9f3b84d05ca405df1444d4d9fd0bde03887f
[ "MIT" ]
null
null
null
Algorithms/Difference/Difference.cc
jwillemsen/sidecar
941d9f3b84d05ca405df1444d4d9fd0bde03887f
[ "MIT" ]
null
null
null
Algorithms/Difference/Difference.cc
jwillemsen/sidecar
941d9f3b84d05ca405df1444d4d9fd0bde03887f
[ "MIT" ]
null
null
null
#include "boost/bind.hpp" #include "Utils/VsipVector.h" #include "Difference.h" #include "Difference_defaults.h" using namespace SideCar::Algorithms; using namespace SideCar::Messages; Difference::Difference(Controller& controller, Logger::Log& log) : Algorithm(controller, log), bufferSize_(Parameter::PositiveIntValue::Make("bufferSize", "Buffer Size", kDefaultBufferSize)), in0_(bufferSize_->getValue()), in1_(bufferSize_->getValue()) { bufferSize_->connectChangedSignalTo(boost::bind(&Difference::bufferSizeChanged, this, _1)); } bool Difference::startup() { registerProcessor<Difference, Video>(0, &Difference::processIn0); registerProcessor<Difference, Video>(1, &Difference::processIn1); return registerParameter(bufferSize_); } bool Difference::reset() { in0_.clear(); in1_.clear(); return true; } bool Difference::processIn0(Video::Ref in) { in0_.add(in); Video::Ref in1 = in1_.find(in->getSequenceCounter()); if (!in1) return true; return process(in, in1); } bool Difference::processIn1(Video::Ref in) { in1_.add(in); Video::Ref in0 = in0_.find(in->getSequenceCounter()); if (!in0) return true; return process(in0, in); } bool Difference::process(Video::Ref in0, Video::Ref in1) { Video::Ref out(Video::Make(getName(), in0)); out->resize(in0->size(), 0); // Calculate in0 - in1 // VsipVector<Video> vIn0(*in0); vIn0.admit(true); VsipVector<Video> vIn1(*in1); vIn1.admit(true); VsipVector<Video> vOut(*out); vOut.admit(false); vOut.v = vIn0.v; vIn0.release(false); vOut.v -= vIn1.v; vIn1.release(false); vOut.release(true); return send(out); } void Difference::bufferSizeChanged(const Parameter::PositiveIntValue& value) { in0_.setCapacity(value.getValue()); in0_.clear(); in1_.setCapacity(value.getValue()); in1_.clear(); } // DLL support // extern "C" ACE_Svc_Export Algorithm* DifferenceMake(Controller& controller, Logger::Log& log) { return new Difference(controller, log); }
22.380435
100
0.683341
jwillemsen
40715819e82a2de3e3fc52d3b2159bfe67b89525
6,015
cpp
C++
MemPool.cpp
mkschleg/MemoryPool
1c899bc2d4562b27102e2d2b38a75e5030008737
[ "MIT" ]
null
null
null
MemPool.cpp
mkschleg/MemoryPool
1c899bc2d4562b27102e2d2b38a75e5030008737
[ "MIT" ]
null
null
null
MemPool.cpp
mkschleg/MemoryPool
1c899bc2d4562b27102e2d2b38a75e5030008737
[ "MIT" ]
null
null
null
#include <iostream> #include "MemPool.h" Pool::Pool(int size){ //create the pool, or char array... pool = new unsigned char[size]; //create temp which is a temp pointer to the beginning of pool int* temp=(int*)pool; //The value of *temp becomes the size of our array *temp=size; //Out puts the size and where the char array is! std::cout<<*temp<<" "<<temp<<std::endl; //Create a new ptr in our pool which points nowhere but is casted as a int* long* ptr_b=(long*)temp+1; *ptr_b=(long)NULL; //Create a new ptr in our pool which points nowhere but is casted as a int* long* ptr_f=ptr_b+1; *ptr_f=(long)NULL; //Set our firstNode as the beginning of our empty array firstNode=temp; } void* Pool::allocate (unsigned int bytes){ //find where we can start allocating! int* temp=firstNode; if(firstNode==NULL){ std::cout<<"You are out of memory!"<<std::endl; return NULL; } //This is the next node where we can store data long* next=(long*)temp+2; //We need this loop to be able to loop through to find an appropriate space //to allocate the variable. while(true){ //This first if statement finds if the size of empty space is smaller than //the wanted size. If true we need to check if the next slot is available. //If so then we loop around and do the check again! If not there is no //space available for the variable and we just return the NULL pointer. if(*temp<bytes){ if(*next==(long)NULL){ std::cout<<"No space available for this item!"<<std::endl; return NULL; } else{ temp=(int*) *next; next=(long*)temp+2; } } //This is when the variable fits perfectly into the slot! If our current //slot is the only node we need to show that our memory is full and set //the firstNode to Null returning our memory. If it is not but is the //firstNode we change the memory area pointed to in next as the new //firstNode. else if(*temp==bytes){ std::cout<<"Warning your memory is getting full!!"<<std::endl; if(temp==firstNode){ if(*next==(long)NULL){ std::cout<<"You're memory is now full!"<<std::endl; //*temp alread is equivalent to the bytes //there are no more nodes! //and we need to send the pointer to the memory slot! firstNode=NULL; return temp+1; } else{ firstNode==(int*)*next; return temp+1; } } //Otherwise our node is in the middle and we need to close it and set //the appropriate pointers to the right places. else{ long* ptr_b=(long*)temp+1; long* ptr_f=(long*)temp+2; int* tempb=(int*)*ptr_b; long* ptrb_f=(long*)tempb+2; *ptrb_f=*ptr_f; int* tempf=(int*)*ptr_f; long* ptrf_b=(long*)tempf+1; *ptrf_b=*ptr_b; } } //This is when our space does not exactly equal the space wanted and we //split the area. else{ //std::cout<<"Help\n"; void* ptr=temp+1; long* pb=(long*) temp+1; long* pf=pb+1; int* temp2=temp+1+(bytes/sizeof(int)); *temp2=*temp-bytes-sizeof(int); *temp=bytes; long* ptr_b=(long*)temp2+1; *ptr_b=*pb; long* ptr_f=ptr_b+1; *ptr_f=*pf; firstNode=temp2; std::cout<<*temp<<' '<<ptr<<std::endl <<*temp2<<' '<<temp2<<' '<<ptr_b<<' '<<ptr_f<<std::endl <<firstNode<<std::endl; return ptr; } } } //Deallocate function void Pool::deallocate (void* ptr){ int* a=(int*) ptr; a-=1; int* b=firstNode; long* next=(long*) b+2; //if the firstNode is full we know our vector is full and have to make a //a node that will become our firstNode if(firstNode==NULL){ //size remains the same long* aptr_b=(long*)a+1; long* aptr_f=aptr_b+1; *aptr_b=(long)NULL; *aptr_f=(long)NULL; firstNode=a; } //If the slot comes before our firstNode else if(a<firstNode){ std::cout<<"1"; // std::cout<<a+(*a/sizeof(int))+1<<std::endl; //Is the slot connected to the first node? if(a+*a/sizeof(int)+1==b){ //Node pointers for a std::cout<<"a"<<std::endl; int* aptr_b=a+1; int* aptr_f=aptr_b+1; //Node pointers for b int* c=b+1; int* d=c+1; *a=*a+*b+sizeof(int); *aptr_b=*c; *aptr_f=*d; firstNode=a; } //When it is not connected to the firstNode else{ std::cout<<"b"<<std::endl; long* aptr_b=(long*) a+1; long* aptr_f=aptr_b+1; //The size stays the same! *a=*a *aptr_b=(long)NULL; *aptr_f=(long) b; firstNode=a; } } //When the deallocation spot comes after our firstNode else{ //std::cout<<"else"<<std::endl; //Finding where our slot is in the memory while((long)a>*next){ std::cout<<"loop"<<std::endl; if(a>(int*) *next){ b=(int*) *next; next=(long*) b+2; } } long* bptr_b=(long*) b+1; long* bptr_f=bptr_b+1; int* x=(int*) *bptr_f; long* xptr_b=(long*) x+1; long* xptr_f=xptr_b+1; //These are our test cases std::cout<<"2"; //connected on both sides to free space if(a==b+*b/sizeof(int)+1 and x==a+*a/sizeof(int)+1){ std::cout<<"a"<<std::endl; *b=*b+*a+*x+2*sizeof(int); *bptr_f=*xptr_f; } //connected on the front side else if(a==b+*b/sizeof(int)+1){ std::cout<<"b"<<std::endl; *b=*b+*a+sizeof(int); } //connected on the back side else if(x==a+*a/sizeof(int)+1){ std::cout<<"c"<<std::endl; long* aptr_b=(long*)a+1; long* aptr_f=aptr_b+1; *a=*a+*x+sizeof(int); *aptr_b=*xptr_b; *aptr_f=*xptr_f; } //not connected to any free space else{ std::cout<<"d"<<std::endl; long* aptr_b=(long*)a+1; long* aptr_f=aptr_b+1; //size stays the same! *a=*a *aptr_b=*xptr_b; *aptr_f=*bptr_f; *xptr_b=(long)a; *bptr_f=(long)a; } } } void Pool::print_size(){ int* temp=firstNode; std::cout<<*temp<<" "<<temp<<std::endl; }
24.352227
78
0.590357
mkschleg
4072ce1c8fbf3fd3267fe10c2a504eb15dcdadac
460
cpp
C++
src/ximage_overlay.cpp
jtpio/xleaflet
67df1c06ef7b8bb753180bfea545e5ad38ac88b3
[ "BSD-3-Clause" ]
null
null
null
src/ximage_overlay.cpp
jtpio/xleaflet
67df1c06ef7b8bb753180bfea545e5ad38ac88b3
[ "BSD-3-Clause" ]
null
null
null
src/ximage_overlay.cpp
jtpio/xleaflet
67df1c06ef7b8bb753180bfea545e5ad38ac88b3
[ "BSD-3-Clause" ]
null
null
null
#include "xleaflet/ximage_overlay.hpp" template class XLEAFLET_API xw::xmaterialize<xlf::ximage_overlay>; template xw::xmaterialize<xlf::ximage_overlay>::xmaterialize(); template class XLEAFLET_API xw::xtransport<xw::xmaterialize<xlf::ximage_overlay>>; template class XLEAFLET_API xw::xgenerator<xlf::ximage_overlay>; template xw::xgenerator<xlf::ximage_overlay>::xgenerator(); template class XLEAFLET_API xw::xtransport<xw::xgenerator<xlf::ximage_overlay>>;
51.111111
82
0.813043
jtpio
4073a13dcbdaf83823637a3f17f6030ff05454cc
59
cpp
C++
source/core/ObjLoader.cpp
zhanghao00925/CG-Path_Tracing-Algorithm
12bd6d7334051aa2bb0544dd26bfe4ad13ec5560
[ "MIT" ]
3
2020-04-05T13:09:17.000Z
2021-03-16T10:56:17.000Z
source/core/ObjLoader.cpp
zhanghao00925/CG-Path_Tracing-Algorithm
12bd6d7334051aa2bb0544dd26bfe4ad13ec5560
[ "MIT" ]
null
null
null
source/core/ObjLoader.cpp
zhanghao00925/CG-Path_Tracing-Algorithm
12bd6d7334051aa2bb0544dd26bfe4ad13ec5560
[ "MIT" ]
1
2020-02-19T02:59:44.000Z
2020-02-19T02:59:44.000Z
// // Created by hao on 3/6/19. // #include "ObjLoader.h"
9.833333
28
0.59322
zhanghao00925
4076ac8e691781c7c6718078f85819a903c9db24
263,248
cpp
C++
tests/xtd.drawing.unit_tests/src/color.cpp
ExternalRepositories/xtd
5889d69900ad22a00fcb640d7850a1d599cf593a
[ "MIT" ]
null
null
null
tests/xtd.drawing.unit_tests/src/color.cpp
ExternalRepositories/xtd
5889d69900ad22a00fcb640d7850a1d599cf593a
[ "MIT" ]
null
null
null
tests/xtd.drawing.unit_tests/src/color.cpp
ExternalRepositories/xtd
5889d69900ad22a00fcb640d7850a1d599cf593a
[ "MIT" ]
null
null
null
#include <xtd/drawing/color.h> #include <xtd/argument_exception.h> #include <xtd/xtd.tunit> using namespace xtd; using namespace xtd::drawing; using namespace xtd::tunit; namespace unit_tests { class test_class_(test_color) { public: void test_method_(create_empty_color) { color c; assert::are_equal(color(), c); assert::are_equal(color::empty, c); assert::are_equal(0, c.a()); assert::are_equal(0, c.r()); assert::are_equal(0, c.g()); assert::are_equal(0, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("0", c.name()); assert::are_equal("color [empty]", c.to_string()); assert::is_true(c.is_empty()); assert::is_false(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_false(c.is_named_color()); assert::are_equal(0U, c.to_argb()); assert::are_equal((known_color)0, c.to_known_color()); } void test_method_(create_from_argb_0) { color c = color::from_argb(0); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0, c.a()); assert::are_equal(0, c.r()); assert::are_equal(0, c.g()); assert::are_equal(0, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("0", c.name()); assert::are_equal("color [a=0, r=0, g=0, b=0]", c.to_string()); assert::is_false(c.is_empty()); assert::is_false(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_false(c.is_named_color()); assert::are_equal(0U, c.to_argb()); assert::are_equal((known_color)0, c.to_known_color()); } void test_method_(create_from_argb_0x12_0x34_0x56_0x78) { color c = color::from_argb(0x12, 0x34, 0x56, 0x78); assert::are_equal(color::from_argb(0x12345678), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0x12, c.a()); assert::are_equal(0x34, c.r()); assert::are_equal(0x56, c.g()); assert::are_equal(0x78, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("12345678", c.name()); assert::are_equal("color [a=18, r=52, g=86, b=120]", c.to_string()); assert::is_false(c.is_empty()); assert::is_false(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_false(c.is_named_color()); assert::are_equal(0x12345678U, c.to_argb()); assert::are_equal((known_color)0, c.to_known_color()); } void test_method_(create_from_argb_0x12_0x34_0x56) { color c = color::from_argb(0x12, 0x34, 0x56); assert::are_equal(color::from_argb(0xFF123456), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x12, c.r()); assert::are_equal(0x34, c.g()); assert::are_equal(0x56, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("FF123456", c.name()); assert::are_equal("color [a=255, r=18, g=52, b=86]", c.to_string()); assert::is_false(c.is_empty()); assert::is_false(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_false(c.is_named_color()); assert::are_equal(0xFF123456U, c.to_argb()); assert::are_equal((known_color)0, c.to_known_color()); } void test_method_(create_from_argb_0x20_color_blue) { color c = color::from_argb(0x20, color::blue); assert::are_equal(color::from_argb(0x20, color::blue), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0x20, c.a()); assert::are_equal(0x0, c.r()); assert::are_equal(0x0, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("200000FF", c.name()); assert::are_equal("color [a=32, r=0, g=0, b=255]", c.to_string()); assert::is_false(c.is_empty()); assert::is_false(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_false(c.is_named_color()); assert::are_equal(0x200000FFU, c.to_argb()); assert::are_equal((known_color)0, c.to_known_color()); } void test_method_(create_from_argb_0x12345678) { color c = color::from_argb(0x12345678); assert::are_equal(color::from_argb(0x12345678), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0x12, c.a()); assert::are_equal(0x34, c.r()); assert::are_equal(0x56, c.g()); assert::are_equal(0x78, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("12345678", c.name()); assert::are_equal("color [a=18, r=52, g=86, b=120]", c.to_string()); assert::is_false(c.is_empty()); assert::is_false(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_false(c.is_named_color()); assert::are_equal(0x12345678U, c.to_argb()); assert::are_equal((known_color)0, c.to_known_color()); } void test_method_(create_from_hsb_240_1_1) { color c = color::from_hsb(240, 1.0f, 1.0f); assert::are_equal(color::from_hsb(240, 1.0f, 1.0f), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("FF0000FF", c.name()); assert::are_equal(240, c.get_hue()); assert::are_equal(1.0f, c.get_saturation()); assert::are_equal(1.0f, c.get_brightness()); assert::are_equal("color [a=255, r=0, g=0, b=255]", c.to_string()); assert::is_false(c.is_empty()); assert::is_false(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_false(c.is_named_color()); assert::are_equal(0xFF0000FFU, c.to_argb()); assert::are_equal((known_color)0, c.to_known_color()); } void test_method_(create_from_hsl_138_050_076) { color c = color::from_hsl(138, 0.50f, 0.76f); assert::are_equal(color::from_hsl(138, 0.50f, 0.76f), c, line_info_); assert::are_not_equal(color(), c, line_info_); assert::are_not_equal(color::empty, c, line_info_); assert::are_equal(0xFF, c.a(), line_info_); assert::are_equal(0xA3, c.r(), line_info_); assert::are_equal(0xE0, c.g(), line_info_); assert::are_equal(0xB5, c.b(), line_info_); assert::are_equal(0, c.handle(), line_info_); assert::are_equal("FFA3E0B5", c.name(), line_info_); assert::are_equal(138.0f, c.get_hue(), 0.5f, line_info_); assert::are_equal(0.50f, c.get_saturation(), 0.005f, line_info_); assert::are_equal(0.76f, c.get_lightness(), 0.005f, line_info_); assert::are_equal("color [a=255, r=163, g=224, b=181]", c.to_string(), line_info_); assert::is_false(c.is_empty(), line_info_); assert::is_false(c.is_known_color(), line_info_); assert::is_false(c.is_system_color(), line_info_); assert::is_false(c.is_named_color(), line_info_); assert::are_equal(0xFFA3E0B5, c.to_argb(), line_info_); assert::are_equal((known_color)0, c.to_known_color(), line_info_); } void test_method_(create_from_know_color_invalid) { assert::throws<argument_exception>([] {color::from_known_color((known_color)7654);}); } void test_method_(create_from_know_color_transparent) { color c = color::from_known_color(known_color::transparent); assert::are_equal(color::from_known_color(known_color::transparent), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0x00, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("transparent", c.name()); assert::are_equal("color [transparent]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0x00FFFFFFU, c.to_argb()); assert::are_equal(known_color::transparent, c.to_known_color()); } void test_method_(create_from_know_color_alice_blue) { color c = color::from_known_color(known_color::alice_blue); assert::are_equal(color::from_known_color(known_color::alice_blue), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xF0, c.r()); assert::are_equal(0xF8, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("alice_blue", c.name()); assert::are_equal("color [alice_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFF0F8FFU, c.to_argb()); assert::are_equal(known_color::alice_blue, c.to_known_color()); } void test_method_(create_from_know_color_antique_white) { color c = color::from_known_color(known_color::antique_white); assert::are_equal(color::from_known_color(known_color::antique_white), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFA, c.r()); assert::are_equal(0xEB, c.g()); assert::are_equal(0xD7, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("antique_white", c.name()); assert::are_equal("color [antique_white]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFAEBD7U, c.to_argb()); assert::are_equal(known_color::antique_white, c.to_known_color()); } void test_method_(create_from_know_color_aqua) { color c = color::from_known_color(known_color::aqua); assert::are_equal(color::from_known_color(known_color::aqua), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("aqua", c.name()); assert::are_equal("color [aqua]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF00FFFFU, c.to_argb()); assert::are_equal(known_color::aqua, c.to_known_color()); } void test_method_(create_from_know_color_aquamarine) { color c = color::from_known_color(known_color::aquamarine); assert::are_equal(color::from_known_color(known_color::aquamarine), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x7F, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0xD4, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("aquamarine", c.name()); assert::are_equal("color [aquamarine]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF7FFFD4U, c.to_argb()); assert::are_equal(known_color::aquamarine, c.to_known_color()); } void test_method_(create_from_know_color_azure) { color c = color::from_known_color(known_color::azure); assert::are_equal(color::from_known_color(known_color::azure), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xF0, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("azure", c.name()); assert::are_equal("color [azure]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFF0FFFFU, c.to_argb()); assert::are_equal(known_color::azure, c.to_known_color()); } void test_method_(create_from_know_color_beige) { color c = color::from_known_color(known_color::beige); assert::are_equal(color::from_known_color(known_color::beige), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xF5, c.r()); assert::are_equal(0xF5, c.g()); assert::are_equal(0xDC, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("beige", c.name()); assert::are_equal("color [beige]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFF5F5DCU, c.to_argb()); assert::are_equal(known_color::beige, c.to_known_color()); } void test_method_(create_from_know_color_bisque) { color c = color::from_known_color(known_color::bisque); assert::are_equal(color::from_known_color(known_color::bisque), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xE4, c.g()); assert::are_equal(0xC4, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("bisque", c.name()); assert::are_equal("color [bisque]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFE4C4U, c.to_argb()); assert::are_equal(known_color::bisque, c.to_known_color()); } void test_method_(create_from_know_color_black) { color c = color::from_known_color(known_color::black); assert::are_equal(color::from_known_color(known_color::black), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("black", c.name()); assert::are_equal("color [black]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF000000U, c.to_argb()); assert::are_equal(known_color::black, c.to_known_color()); } void test_method_(create_from_know_color_blanched_almond) { color c = color::from_known_color(known_color::blanched_almond); assert::are_equal(color::from_known_color(known_color::blanched_almond), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xEB, c.g()); assert::are_equal(0xCD, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("blanched_almond", c.name()); assert::are_equal("color [blanched_almond]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFEBCDU, c.to_argb()); assert::are_equal(known_color::blanched_almond, c.to_known_color()); } void test_method_(create_from_know_color_blue) { color c = color::from_known_color(known_color::blue); assert::are_equal(color::from_known_color(known_color::blue), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("blue", c.name()); assert::are_equal("color [blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF0000FFU, c.to_argb()); assert::are_equal(known_color::blue, c.to_known_color()); } void test_method_(create_from_know_color_blue_violet) { color c = color::from_known_color(known_color::blue_violet); assert::are_equal(color::from_known_color(known_color::blue_violet), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x8A, c.r()); assert::are_equal(0x2B, c.g()); assert::are_equal(0xE2, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("blue_violet", c.name()); assert::are_equal("color [blue_violet]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF8A2BE2U, c.to_argb()); assert::are_equal(known_color::blue_violet, c.to_known_color()); } void test_method_(create_from_know_color_brown) { color c = color::from_known_color(known_color::brown); assert::are_equal(color::from_known_color(known_color::brown), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xA5, c.r()); assert::are_equal(0x2A, c.g()); assert::are_equal(0x2A, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("brown", c.name()); assert::are_equal("color [brown]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFA52A2AU, c.to_argb()); assert::are_equal(known_color::brown, c.to_known_color()); } void test_method_(create_from_know_color_burly_wood) { color c = color::from_known_color(known_color::burly_wood); assert::are_equal(color::from_known_color(known_color::burly_wood), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xDE, c.r()); assert::are_equal(0xB8, c.g()); assert::are_equal(0x87, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("burly_wood", c.name()); assert::are_equal("color [burly_wood]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFDEB887U, c.to_argb()); assert::are_equal(known_color::burly_wood, c.to_known_color()); } void test_method_(create_from_know_color_cadet_blue) { color c = color::from_known_color(known_color::cadet_blue); assert::are_equal(color::from_known_color(known_color::cadet_blue), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x5F, c.r()); assert::are_equal(0x9E, c.g()); assert::are_equal(0xA0, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("cadet_blue", c.name()); assert::are_equal("color [cadet_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF5F9EA0U, c.to_argb()); assert::are_equal(known_color::cadet_blue, c.to_known_color()); } void test_method_(create_from_know_color_chartreuse) { color c = color::from_known_color(known_color::chartreuse); assert::are_equal(color::from_known_color(known_color::chartreuse), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x7F, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("chartreuse", c.name()); assert::are_equal("color [chartreuse]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF7FFF00U, c.to_argb()); assert::are_equal(known_color::chartreuse, c.to_known_color()); } void test_method_(create_from_know_color_chocolate) { color c = color::from_known_color(known_color::chocolate); assert::are_equal(color::from_known_color(known_color::chocolate), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xD2, c.r()); assert::are_equal(0x69, c.g()); assert::are_equal(0x1E, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("chocolate", c.name()); assert::are_equal("color [chocolate]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFD2691EU, c.to_argb()); assert::are_equal(known_color::chocolate, c.to_known_color()); } void test_method_(create_from_know_color_coral) { color c = color::from_known_color(known_color::coral); assert::are_equal(color::from_known_color(known_color::coral), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0x7F, c.g()); assert::are_equal(0x50, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("coral", c.name()); assert::are_equal("color [coral]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFF7F50U, c.to_argb()); assert::are_equal(known_color::coral, c.to_known_color()); } void test_method_(create_from_know_color_cornflower_blue) { color c = color::from_known_color(known_color::cornflower_blue); assert::are_equal(color::from_known_color(known_color::cornflower_blue), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x64, c.r()); assert::are_equal(0x95, c.g()); assert::are_equal(0xED, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("cornflower_blue", c.name()); assert::are_equal("color [cornflower_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF6495EDU, c.to_argb()); assert::are_equal(known_color::cornflower_blue, c.to_known_color()); } void test_method_(create_from_know_color_cornsilk) { color c = color::from_known_color(known_color::cornsilk); assert::are_equal(color::from_known_color(known_color::cornsilk), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xF8, c.g()); assert::are_equal(0xDC, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("cornsilk", c.name()); assert::are_equal("color [cornsilk]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFF8DCU, c.to_argb()); assert::are_equal(known_color::cornsilk, c.to_known_color()); } void test_method_(create_from_know_color_crimson) { color c = color::from_known_color(known_color::crimson); assert::are_equal(color::from_known_color(known_color::crimson), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xDC, c.r()); assert::are_equal(0x14, c.g()); assert::are_equal(0x3C, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("crimson", c.name()); assert::are_equal("color [crimson]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFDC143CU, c.to_argb()); assert::are_equal(known_color::crimson, c.to_known_color()); } void test_method_(create_from_know_color_cyan) { color c = color::from_known_color(known_color::cyan); assert::are_equal(color::from_known_color(known_color::cyan), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("cyan", c.name()); assert::are_equal("color [cyan]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF00FFFFU, c.to_argb()); assert::are_equal(known_color::cyan, c.to_known_color()); } void test_method_(create_from_know_color_dark_blue) { color c = color::from_known_color(known_color::dark_blue); assert::are_equal(color::from_known_color(known_color::dark_blue), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0x8B, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_blue", c.name()); assert::are_equal("color [dark_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF00008BU, c.to_argb()); assert::are_equal(known_color::dark_blue, c.to_known_color()); } void test_method_(create_from_know_color_dark_cyan) { color c = color::from_known_color(known_color::dark_cyan); assert::are_equal(color::from_known_color(known_color::dark_cyan), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0x8B, c.g()); assert::are_equal(0x8B, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_cyan", c.name()); assert::are_equal("color [dark_cyan]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF008B8BU, c.to_argb()); assert::are_equal(known_color::dark_cyan, c.to_known_color()); } void test_method_(create_from_know_color_dark_goldenrod) { color c = color::from_known_color(known_color::dark_goldenrod); assert::are_equal(color::from_known_color(known_color::dark_goldenrod), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xB8, c.r()); assert::are_equal(0x86, c.g()); assert::are_equal(0x0B, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_goldenrod", c.name()); assert::are_equal("color [dark_goldenrod]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFB8860BU, c.to_argb()); assert::are_equal(known_color::dark_goldenrod, c.to_known_color()); } void test_method_(create_from_know_color_dark_gray) { color c = color::from_known_color(known_color::dark_gray); assert::are_equal(color::from_known_color(known_color::dark_gray), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xA9, c.r()); assert::are_equal(0xA9, c.g()); assert::are_equal(0xA9, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_gray", c.name()); assert::are_equal("color [dark_gray]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFA9A9A9U, c.to_argb()); assert::are_equal(known_color::dark_gray, c.to_known_color()); } void test_method_(create_from_know_color_dark_green) { color c = color::from_known_color(known_color::dark_green); assert::are_equal(color::from_known_color(known_color::dark_green), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0x64, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_green", c.name()); assert::are_equal("color [dark_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF006400U, c.to_argb()); assert::are_equal(known_color::dark_green, c.to_known_color()); } void test_method_(create_from_know_color_dark_khaki) { color c = color::from_known_color(known_color::dark_khaki); assert::are_equal(color::from_known_color(known_color::dark_khaki), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xBD, c.r()); assert::are_equal(0xB7, c.g()); assert::are_equal(0x6B, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_khaki", c.name()); assert::are_equal("color [dark_khaki]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFBDB76BU, c.to_argb()); assert::are_equal(known_color::dark_khaki, c.to_known_color()); } void test_method_(create_from_know_color_dark_magenta) { color c = color::from_known_color(known_color::dark_magenta); assert::are_equal(color::from_known_color(known_color::dark_magenta), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x8B, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0x8B, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_magenta", c.name()); assert::are_equal("color [dark_magenta]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF8B008BU, c.to_argb()); assert::are_equal(known_color::dark_magenta, c.to_known_color()); } void test_method_(create_from_know_color_dark_olive_green) { color c = color::from_known_color(known_color::dark_olive_green); assert::are_equal(color::from_known_color(known_color::dark_olive_green), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x55, c.r()); assert::are_equal(0x6B, c.g()); assert::are_equal(0x2F, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_olive_green", c.name()); assert::are_equal("color [dark_olive_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF556B2FU, c.to_argb()); assert::are_equal(known_color::dark_olive_green, c.to_known_color()); } void test_method_(create_from_know_color_dark_orange) { color c = color::from_known_color(known_color::dark_orange); assert::are_equal(color::from_known_color(known_color::dark_orange), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0x8C, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_orange", c.name()); assert::are_equal("color [dark_orange]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFF8C00U, c.to_argb()); assert::are_equal(known_color::dark_orange, c.to_known_color()); } void test_method_(create_from_know_color_dark_orchid) { color c = color::from_known_color(known_color::dark_orchid); assert::are_equal(color::from_known_color(known_color::dark_orchid), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x99, c.r()); assert::are_equal(0x32, c.g()); assert::are_equal(0xCC, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_orchid", c.name()); assert::are_equal("color [dark_orchid]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF9932CCU, c.to_argb()); assert::are_equal(known_color::dark_orchid, c.to_known_color()); } void test_method_(create_from_know_color_dark_red) { color c = color::from_known_color(known_color::dark_red); assert::are_equal(color::from_known_color(known_color::dark_red), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x8B, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_red", c.name()); assert::are_equal("color [dark_red]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF8B0000U, c.to_argb()); assert::are_equal(known_color::dark_red, c.to_known_color()); } void test_method_(create_from_know_color_dark_salmon) { color c = color::from_known_color(known_color::dark_salmon); assert::are_equal(color::from_known_color(known_color::dark_salmon), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xE9, c.r()); assert::are_equal(0x96, c.g()); assert::are_equal(0x7A, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_salmon", c.name()); assert::are_equal("color [dark_salmon]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFE9967AU, c.to_argb()); assert::are_equal(known_color::dark_salmon, c.to_known_color()); } void test_method_(create_from_know_color_dark_sea_green) { color c = color::from_known_color(known_color::dark_sea_green); assert::are_equal(color::from_known_color(known_color::dark_sea_green), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x8F, c.r()); assert::are_equal(0xBC, c.g()); assert::are_equal(0x8B, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_sea_green", c.name()); assert::are_equal("color [dark_sea_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF8FBC8BU, c.to_argb()); assert::are_equal(known_color::dark_sea_green, c.to_known_color()); } void test_method_(create_from_know_color_dark_slate_blue) { color c = color::from_known_color(known_color::dark_slate_blue); assert::are_equal(color::from_known_color(known_color::dark_slate_blue), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x48, c.r()); assert::are_equal(0x3D, c.g()); assert::are_equal(0x8B, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_slate_blue", c.name()); assert::are_equal("color [dark_slate_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF483D8BU, c.to_argb()); assert::are_equal(known_color::dark_slate_blue, c.to_known_color()); } void test_method_(create_from_know_color_dark_slate_gray) { color c = color::from_known_color(known_color::dark_slate_gray); assert::are_equal(color::from_known_color(known_color::dark_slate_gray), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x2F, c.r()); assert::are_equal(0x4F, c.g()); assert::are_equal(0x4F, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_slate_gray", c.name()); assert::are_equal("color [dark_slate_gray]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF2F4F4FU, c.to_argb()); assert::are_equal(known_color::dark_slate_gray, c.to_known_color()); } void test_method_(create_from_know_color_dark_turquoise) { color c = color::from_known_color(known_color::dark_turquoise); assert::are_equal(color::from_known_color(known_color::dark_turquoise), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0xCE, c.g()); assert::are_equal(0xD1, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_turquoise", c.name()); assert::are_equal("color [dark_turquoise]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF00CED1U, c.to_argb()); assert::are_equal(known_color::dark_turquoise, c.to_known_color()); } void test_method_(create_from_know_color_dark_violet) { color c = color::from_known_color(known_color::dark_violet); assert::are_equal(color::from_known_color(known_color::dark_violet), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x94, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0xD3, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_violet", c.name()); assert::are_equal("color [dark_violet]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF9400D3U, c.to_argb()); assert::are_equal(known_color::dark_violet, c.to_known_color()); } void test_method_(create_from_know_color_deep_pink) { color c = color::from_known_color(known_color::deep_pink); assert::are_equal(color::from_known_color(known_color::deep_pink), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0x14, c.g()); assert::are_equal(0x93, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("deep_pink", c.name()); assert::are_equal("color [deep_pink]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFF1493U, c.to_argb()); assert::are_equal(known_color::deep_pink, c.to_known_color()); } void test_method_(create_from_know_color_deep_sky_blue) { color c = color::from_known_color(known_color::deep_sky_blue); assert::are_equal(color::from_known_color(known_color::deep_sky_blue), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0xBF, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("deep_sky_blue", c.name()); assert::are_equal("color [deep_sky_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF00BFFFU, c.to_argb()); assert::are_equal(known_color::deep_sky_blue, c.to_known_color()); } void test_method_(create_from_know_color_dim_gray) { color c = color::from_known_color(known_color::dim_gray); assert::are_equal(color::from_known_color(known_color::dim_gray), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x69, c.r()); assert::are_equal(0x69, c.g()); assert::are_equal(0x69, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dim_gray", c.name()); assert::are_equal("color [dim_gray]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF696969U, c.to_argb()); assert::are_equal(known_color::dim_gray, c.to_known_color()); } void test_method_(create_from_know_color_dodger_blue) { color c = color::from_known_color(known_color::dodger_blue); assert::are_equal(color::from_known_color(known_color::dodger_blue), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x1E, c.r()); assert::are_equal(0x90, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dodger_blue", c.name()); assert::are_equal("color [dodger_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF1E90FFU, c.to_argb()); assert::are_equal(known_color::dodger_blue, c.to_known_color()); } void test_method_(create_from_know_color_firebrick) { color c = color::from_known_color(known_color::firebrick); assert::are_equal(color::from_known_color(known_color::firebrick), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xB2, c.r()); assert::are_equal(0x22, c.g()); assert::are_equal(0x22, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("firebrick", c.name()); assert::are_equal("color [firebrick]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFB22222U, c.to_argb()); assert::are_equal(known_color::firebrick, c.to_known_color()); } void test_method_(create_from_know_color_floral_white) { color c = color::from_known_color(known_color::floral_white); assert::are_equal(color::from_known_color(known_color::floral_white), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xFA, c.g()); assert::are_equal(0xF0, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("floral_white", c.name()); assert::are_equal("color [floral_white]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFFAF0U, c.to_argb()); assert::are_equal(known_color::floral_white, c.to_known_color()); } void test_method_(create_from_know_color_forest_green) { color c = color::from_known_color(known_color::forest_green); assert::are_equal(color::from_known_color(known_color::forest_green), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x22, c.r()); assert::are_equal(0x8B, c.g()); assert::are_equal(0x22, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("forest_green", c.name()); assert::are_equal("color [forest_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF228B22U, c.to_argb()); assert::are_equal(known_color::forest_green, c.to_known_color()); } void test_method_(create_from_know_color_fuchsia) { color c = color::from_known_color(known_color::fuchsia); assert::are_equal(color::from_known_color(known_color::fuchsia), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("fuchsia", c.name()); assert::are_equal("color [fuchsia]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFF00FFU, c.to_argb()); assert::are_equal(known_color::fuchsia, c.to_known_color()); } void test_method_(create_from_know_color_gainsboro) { color c = color::from_known_color(known_color::gainsboro); assert::are_equal(color::from_known_color(known_color::gainsboro), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xDC, c.r()); assert::are_equal(0xDC, c.g()); assert::are_equal(0xDC, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("gainsboro", c.name()); assert::are_equal("color [gainsboro]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFDCDCDCU, c.to_argb()); assert::are_equal(known_color::gainsboro, c.to_known_color()); } void test_method_(create_from_know_color_ghost_white) { color c = color::from_known_color(known_color::ghost_white); assert::are_equal(color::from_known_color(known_color::ghost_white), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xF8, c.r()); assert::are_equal(0xF8, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("ghost_white", c.name()); assert::are_equal("color [ghost_white]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFF8F8FFU, c.to_argb()); assert::are_equal(known_color::ghost_white, c.to_known_color()); } void test_method_(create_from_know_color_gold) { color c = color::from_known_color(known_color::gold); assert::are_equal(color::from_known_color(known_color::gold), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xD7, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("gold", c.name()); assert::are_equal("color [gold]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFD700U, c.to_argb()); assert::are_equal(known_color::gold, c.to_known_color()); } void test_method_(create_from_know_color_goldenrod) { color c = color::from_known_color(known_color::goldenrod); assert::are_equal(color::from_known_color(known_color::goldenrod), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xDA, c.r()); assert::are_equal(0xA5, c.g()); assert::are_equal(0x20, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("goldenrod", c.name()); assert::are_equal("color [goldenrod]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFDAA520U, c.to_argb()); assert::are_equal(known_color::goldenrod, c.to_known_color()); } void test_method_(create_from_know_color_gray) { color c = color::from_known_color(known_color::gray); assert::are_equal(color::from_known_color(known_color::gray), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x80, c.r()); assert::are_equal(0x80, c.g()); assert::are_equal(0x80, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("gray", c.name()); assert::are_equal("color [gray]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF808080U, c.to_argb()); assert::are_equal(known_color::gray, c.to_known_color()); } void test_method_(create_from_know_color_green) { color c = color::from_known_color(known_color::green); assert::are_equal(color::from_known_color(known_color::green), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0x80, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("green", c.name()); assert::are_equal("color [green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF008000U, c.to_argb()); assert::are_equal(known_color::green, c.to_known_color()); } void test_method_(create_from_know_color_green_yellow) { color c = color::from_known_color(known_color::green_yellow); assert::are_equal(color::from_known_color(known_color::green_yellow), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xAD, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0x2F, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("green_yellow", c.name()); assert::are_equal("color [green_yellow]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFADFF2FU, c.to_argb()); assert::are_equal(known_color::green_yellow, c.to_known_color()); } void test_method_(create_from_know_color_honeydew) { color c = color::from_known_color(known_color::honeydew); assert::are_equal(color::from_known_color(known_color::honeydew), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xF0, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0xF0, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("honeydew", c.name()); assert::are_equal("color [honeydew]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFF0FFF0U, c.to_argb()); assert::are_equal(known_color::honeydew, c.to_known_color()); } void test_method_(create_from_know_color_hot_pink) { color c = color::from_known_color(known_color::hot_pink); assert::are_equal(color::from_known_color(known_color::hot_pink), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0x69, c.g()); assert::are_equal(0xB4, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("hot_pink", c.name()); assert::are_equal("color [hot_pink]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFF69B4U, c.to_argb()); assert::are_equal(known_color::hot_pink, c.to_known_color()); } void test_method_(create_from_know_color_indian_red) { color c = color::from_known_color(known_color::indian_red); assert::are_equal(color::from_known_color(known_color::indian_red), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xCD, c.r()); assert::are_equal(0x5C, c.g()); assert::are_equal(0x5C, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("indian_red", c.name()); assert::are_equal("color [indian_red]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFCD5C5CU, c.to_argb()); assert::are_equal(known_color::indian_red, c.to_known_color()); } void test_method_(create_from_know_color_indigo) { color c = color::from_known_color(known_color::indigo); assert::are_equal(color::from_known_color(known_color::indigo), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x4B, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0x82, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("indigo", c.name()); assert::are_equal("color [indigo]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF4B0082U, c.to_argb()); assert::are_equal(known_color::indigo, c.to_known_color()); } void test_method_(create_from_know_color_ivory) { color c = color::from_known_color(known_color::ivory); assert::are_equal(color::from_known_color(known_color::ivory), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0xF0, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("ivory", c.name()); assert::are_equal("color [ivory]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFFFF0U, c.to_argb()); assert::are_equal(known_color::ivory, c.to_known_color()); } void test_method_(create_from_know_color_khaki) { color c = color::from_known_color(known_color::khaki); assert::are_equal(color::from_known_color(known_color::khaki), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xF0, c.r()); assert::are_equal(0xE6, c.g()); assert::are_equal(0x8C, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("khaki", c.name()); assert::are_equal("color [khaki]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFF0E68CU, c.to_argb()); assert::are_equal(known_color::khaki, c.to_known_color()); } void test_method_(create_from_know_color_lavender) { color c = color::from_known_color(known_color::lavender); assert::are_equal(color::from_known_color(known_color::lavender), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xE6, c.r()); assert::are_equal(0xE6, c.g()); assert::are_equal(0xFA, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("lavender", c.name()); assert::are_equal("color [lavender]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFE6E6FAU, c.to_argb()); assert::are_equal(known_color::lavender, c.to_known_color()); } void test_method_(create_from_know_color_lavender_blush) { color c = color::from_known_color(known_color::lavender_blush); assert::are_equal(color::from_known_color(known_color::lavender_blush), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xF0, c.g()); assert::are_equal(0xF5, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("lavender_blush", c.name()); assert::are_equal("color [lavender_blush]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFF0F5U, c.to_argb()); assert::are_equal(known_color::lavender_blush, c.to_known_color()); } void test_method_(create_from_know_color_lawn_green) { color c = color::from_known_color(known_color::lawn_green); assert::are_equal(color::from_known_color(known_color::lawn_green), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x7C, c.r()); assert::are_equal(0xFC, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("lawn_green", c.name()); assert::are_equal("color [lawn_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF7CFC00U, c.to_argb()); assert::are_equal(known_color::lawn_green, c.to_known_color()); } void test_method_(create_from_know_color_lemon_chiffon) { color c = color::from_known_color(known_color::lemon_chiffon); assert::are_equal(color::from_known_color(known_color::lemon_chiffon), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xFA, c.g()); assert::are_equal(0xCD, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("lemon_chiffon", c.name()); assert::are_equal("color [lemon_chiffon]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFFACDU, c.to_argb()); assert::are_equal(known_color::lemon_chiffon, c.to_known_color()); } void test_method_(create_from_know_color_light_blue) { color c = color::from_known_color(known_color::light_blue); assert::are_equal(color::from_known_color(known_color::light_blue), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xAD, c.r()); assert::are_equal(0xD8, c.g()); assert::are_equal(0xE6, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_blue", c.name()); assert::are_equal("color [light_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFADD8E6U, c.to_argb()); assert::are_equal(known_color::light_blue, c.to_known_color()); } void test_method_(create_from_know_color_light_coral) { color c = color::from_known_color(known_color::light_coral); assert::are_equal(color::from_known_color(known_color::light_coral), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xF0, c.r()); assert::are_equal(0x80, c.g()); assert::are_equal(0x80, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_coral", c.name()); assert::are_equal("color [light_coral]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFF08080U, c.to_argb()); assert::are_equal(known_color::light_coral, c.to_known_color()); } void test_method_(create_from_know_color_light_cyan) { color c = color::from_known_color(known_color::light_cyan); assert::are_equal(color::from_known_color(known_color::light_cyan), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xE0, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_cyan", c.name()); assert::are_equal("color [light_cyan]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFE0FFFFU, c.to_argb()); assert::are_equal(known_color::light_cyan, c.to_known_color()); } void test_method_(create_from_know_color_light_goldenrod_yellow) { color c = color::from_known_color(known_color::light_goldenrod_yellow); assert::are_equal(color::from_known_color(known_color::light_goldenrod_yellow), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFA, c.r()); assert::are_equal(0xFA, c.g()); assert::are_equal(0xD2, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_goldenrod_yellow", c.name()); assert::are_equal("color [light_goldenrod_yellow]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFAFAD2U, c.to_argb()); assert::are_equal(known_color::light_goldenrod_yellow, c.to_known_color()); } void test_method_(create_from_know_color_light_gray) { color c = color::from_known_color(known_color::light_gray); assert::are_equal(color::from_known_color(known_color::light_gray), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xD3, c.r()); assert::are_equal(0xD3, c.g()); assert::are_equal(0xD3, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_gray", c.name()); assert::are_equal("color [light_gray]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFD3D3D3U, c.to_argb()); assert::are_equal(known_color::light_gray, c.to_known_color()); } void test_method_(create_from_know_color_light_green) { color c = color::from_known_color(known_color::light_green); assert::are_equal(color::from_known_color(known_color::light_green), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x90, c.r()); assert::are_equal(0xEE, c.g()); assert::are_equal(0x90, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_green", c.name()); assert::are_equal("color [light_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF90EE90U, c.to_argb()); assert::are_equal(known_color::light_green, c.to_known_color()); } void test_method_(create_from_know_color_light_pink) { color c = color::from_known_color(known_color::light_pink); assert::are_equal(color::from_known_color(known_color::light_pink), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xB6, c.g()); assert::are_equal(0xC1, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_pink", c.name()); assert::are_equal("color [light_pink]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFB6C1U, c.to_argb()); assert::are_equal(known_color::light_pink, c.to_known_color()); } void test_method_(create_from_know_color_light_salmon) { color c = color::from_known_color(known_color::light_salmon); assert::are_equal(color::from_known_color(known_color::light_salmon), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xA0, c.g()); assert::are_equal(0x7A, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_salmon", c.name()); assert::are_equal("color [light_salmon]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFA07AU, c.to_argb()); assert::are_equal(known_color::light_salmon, c.to_known_color()); } void test_method_(create_from_know_color_light_sea_green) { color c = color::from_known_color(known_color::light_sea_green); assert::are_equal(color::from_known_color(known_color::light_sea_green), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x20, c.r()); assert::are_equal(0xB2, c.g()); assert::are_equal(0xAA, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_sea_green", c.name()); assert::are_equal("color [light_sea_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF20B2AAU, c.to_argb()); assert::are_equal(known_color::light_sea_green, c.to_known_color()); } void test_method_(create_from_know_color_light_sky_blue) { color c = color::from_known_color(known_color::light_sky_blue); assert::are_equal(color::from_known_color(known_color::light_sky_blue), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x87, c.r()); assert::are_equal(0xCE, c.g()); assert::are_equal(0xFA, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_sky_blue", c.name()); assert::are_equal("color [light_sky_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF87CEFAU, c.to_argb()); assert::are_equal(known_color::light_sky_blue, c.to_known_color()); } void test_method_(create_from_know_color_light_slate_gray) { color c = color::from_known_color(known_color::light_slate_gray); assert::are_equal(color::from_known_color(known_color::light_slate_gray), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x77, c.r()); assert::are_equal(0x88, c.g()); assert::are_equal(0x99, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_slate_gray", c.name()); assert::are_equal("color [light_slate_gray]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF778899U, c.to_argb()); assert::are_equal(known_color::light_slate_gray, c.to_known_color()); } void test_method_(create_from_know_color_light_steel_blue) { color c = color::from_known_color(known_color::light_steel_blue); assert::are_equal(color::from_known_color(known_color::light_steel_blue), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xB0, c.r()); assert::are_equal(0xC4, c.g()); assert::are_equal(0xDE, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_steel_blue", c.name()); assert::are_equal("color [light_steel_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFB0C4DEU, c.to_argb()); assert::are_equal(known_color::light_steel_blue, c.to_known_color()); } void test_method_(create_from_know_color_light_yellow) { color c = color::from_known_color(known_color::light_yellow); assert::are_equal(color::from_known_color(known_color::light_yellow), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0xE0, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_yellow", c.name()); assert::are_equal("color [light_yellow]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFFFE0U, c.to_argb()); assert::are_equal(known_color::light_yellow, c.to_known_color()); } void test_method_(create_from_know_color_lime) { color c = color::from_known_color(known_color::lime); assert::are_equal(color::from_known_color(known_color::lime), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("lime", c.name()); assert::are_equal("color [lime]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF00FF00U, c.to_argb()); assert::are_equal(known_color::lime, c.to_known_color()); } void test_method_(create_from_know_color_lime_green) { color c = color::from_known_color(known_color::lime_green); assert::are_equal(color::from_known_color(known_color::lime_green), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x32, c.r()); assert::are_equal(0xCD, c.g()); assert::are_equal(0x32, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("lime_green", c.name()); assert::are_equal("color [lime_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF32CD32U, c.to_argb()); assert::are_equal(known_color::lime_green, c.to_known_color()); } void test_method_(create_from_know_color_linen) { color c = color::from_known_color(known_color::linen); assert::are_equal(color::from_known_color(known_color::linen), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFA, c.r()); assert::are_equal(0xF0, c.g()); assert::are_equal(0xE6, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("linen", c.name()); assert::are_equal("color [linen]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFAF0E6U, c.to_argb()); assert::are_equal(known_color::linen, c.to_known_color()); } void test_method_(create_from_know_color_magenta) { color c = color::from_known_color(known_color::magenta); assert::are_equal(color::from_known_color(known_color::magenta), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("magenta", c.name()); assert::are_equal("color [magenta]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFF00FFU, c.to_argb()); assert::are_equal(known_color::magenta, c.to_known_color()); } void test_method_(create_from_know_color_maroon) { color c = color::from_known_color(known_color::maroon); assert::are_equal(color::from_known_color(known_color::maroon), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x80, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("maroon", c.name()); assert::are_equal("color [maroon]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF800000U, c.to_argb()); assert::are_equal(known_color::maroon, c.to_known_color()); } void test_method_(create_from_know_color_medium_aquamarine) { color c = color::from_known_color(known_color::medium_aquamarine); assert::are_equal(color::from_known_color(known_color::medium_aquamarine), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x66, c.r()); assert::are_equal(0xCD, c.g()); assert::are_equal(0xAA, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("medium_aquamarine", c.name()); assert::are_equal("color [medium_aquamarine]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF66CDAAU, c.to_argb()); assert::are_equal(known_color::medium_aquamarine, c.to_known_color()); } void test_method_(create_from_know_color_medium_blue) { color c = color::from_known_color(known_color::medium_blue); assert::are_equal(color::from_known_color(known_color::medium_blue), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0xCD, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("medium_blue", c.name()); assert::are_equal("color [medium_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF0000CDU, c.to_argb()); assert::are_equal(known_color::medium_blue, c.to_known_color()); } void test_method_(create_from_know_color_medium_orchid) { color c = color::from_known_color(known_color::medium_orchid); assert::are_equal(color::from_known_color(known_color::medium_orchid), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xBA, c.r()); assert::are_equal(0x55, c.g()); assert::are_equal(0xD3, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("medium_orchid", c.name()); assert::are_equal("color [medium_orchid]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFBA55D3U, c.to_argb()); assert::are_equal(known_color::medium_orchid, c.to_known_color()); } void test_method_(create_from_know_color_medium_purple) { color c = color::from_known_color(known_color::medium_purple); assert::are_equal(color::from_known_color(known_color::medium_purple), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x93, c.r()); assert::are_equal(0x70, c.g()); assert::are_equal(0xDB, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("medium_purple", c.name()); assert::are_equal("color [medium_purple]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF9370DBU, c.to_argb()); assert::are_equal(known_color::medium_purple, c.to_known_color()); } void test_method_(create_from_know_color_medium_sea_green) { color c = color::from_known_color(known_color::medium_sea_green); assert::are_equal(color::from_known_color(known_color::medium_sea_green), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x3C, c.r()); assert::are_equal(0xB3, c.g()); assert::are_equal(0x71, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("medium_sea_green", c.name()); assert::are_equal("color [medium_sea_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF3CB371U, c.to_argb()); assert::are_equal(known_color::medium_sea_green, c.to_known_color()); } void test_method_(create_from_know_color_medium_slate_blue) { color c = color::from_known_color(known_color::medium_slate_blue); assert::are_equal(color::from_known_color(known_color::medium_slate_blue), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x7B, c.r()); assert::are_equal(0x68, c.g()); assert::are_equal(0xEE, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("medium_slate_blue", c.name()); assert::are_equal("color [medium_slate_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF7B68EEU, c.to_argb()); assert::are_equal(known_color::medium_slate_blue, c.to_known_color()); } void test_method_(create_from_know_color_medium_spring_green) { color c = color::from_known_color(known_color::medium_spring_green); assert::are_equal(color::from_known_color(known_color::medium_spring_green), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0xFA, c.g()); assert::are_equal(0x9A, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("medium_spring_green", c.name()); assert::are_equal("color [medium_spring_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF00FA9AU, c.to_argb()); assert::are_equal(known_color::medium_spring_green, c.to_known_color()); } void test_method_(create_from_know_color_medium_turquoise) { color c = color::from_known_color(known_color::medium_turquoise); assert::are_equal(color::from_known_color(known_color::medium_turquoise), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x48, c.r()); assert::are_equal(0xD1, c.g()); assert::are_equal(0xCC, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("medium_turquoise", c.name()); assert::are_equal("color [medium_turquoise]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF48D1CCU, c.to_argb()); assert::are_equal(known_color::medium_turquoise, c.to_known_color()); } void test_method_(create_from_know_color_medium_violet_red) { color c = color::from_known_color(known_color::medium_violet_red); assert::are_equal(color::from_known_color(known_color::medium_violet_red), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xC7, c.r()); assert::are_equal(0x15, c.g()); assert::are_equal(0x85, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("medium_violet_red", c.name()); assert::are_equal("color [medium_violet_red]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFC71585U, c.to_argb()); assert::are_equal(known_color::medium_violet_red, c.to_known_color()); } void test_method_(create_from_know_color_midnight_blue) { color c = color::from_known_color(known_color::midnight_blue); assert::are_equal(color::from_known_color(known_color::midnight_blue), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x19, c.r()); assert::are_equal(0x19, c.g()); assert::are_equal(0x70, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("midnight_blue", c.name()); assert::are_equal("color [midnight_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF191970U, c.to_argb()); assert::are_equal(known_color::midnight_blue, c.to_known_color()); } void test_method_(create_from_know_color_mint_cream) { color c = color::from_known_color(known_color::mint_cream); assert::are_equal(color::from_known_color(known_color::mint_cream), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xF5, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0xFA, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("mint_cream", c.name()); assert::are_equal("color [mint_cream]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFF5FFFAU, c.to_argb()); assert::are_equal(known_color::mint_cream, c.to_known_color()); } void test_method_(create_from_know_color_misty_rose) { color c = color::from_known_color(known_color::misty_rose); assert::are_equal(color::from_known_color(known_color::misty_rose), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xE4, c.g()); assert::are_equal(0xE1, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("misty_rose", c.name()); assert::are_equal("color [misty_rose]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFE4E1U, c.to_argb()); assert::are_equal(known_color::misty_rose, c.to_known_color()); } void test_method_(create_from_know_color_moccasin) { color c = color::from_known_color(known_color::moccasin); assert::are_equal(color::from_known_color(known_color::moccasin), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xE4, c.g()); assert::are_equal(0xB5, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("moccasin", c.name()); assert::are_equal("color [moccasin]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFE4B5U, c.to_argb()); assert::are_equal(known_color::moccasin, c.to_known_color()); } void test_method_(create_from_know_color_navajo_white) { color c = color::from_known_color(known_color::navajo_white); assert::are_equal(color::from_known_color(known_color::navajo_white), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xDE, c.g()); assert::are_equal(0xAD, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("navajo_white", c.name()); assert::are_equal("color [navajo_white]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFDEADU, c.to_argb()); assert::are_equal(known_color::navajo_white, c.to_known_color()); } void test_method_(create_from_know_color_navy) { color c = color::from_known_color(known_color::navy); assert::are_equal(color::from_known_color(known_color::navy), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0x80, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("navy", c.name()); assert::are_equal("color [navy]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF000080U, c.to_argb()); assert::are_equal(known_color::navy, c.to_known_color()); } void test_method_(create_from_know_color_old_lace) { color c = color::from_known_color(known_color::old_lace); assert::are_equal(color::from_known_color(known_color::old_lace), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFD, c.r()); assert::are_equal(0xF5, c.g()); assert::are_equal(0xE6, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("old_lace", c.name()); assert::are_equal("color [old_lace]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFDF5E6U, c.to_argb()); assert::are_equal(known_color::old_lace, c.to_known_color()); } void test_method_(create_from_know_color_olive) { color c = color::from_known_color(known_color::olive); assert::are_equal(color::from_known_color(known_color::olive), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x80, c.r()); assert::are_equal(0x80, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("olive", c.name()); assert::are_equal("color [olive]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF808000U, c.to_argb()); assert::are_equal(known_color::olive, c.to_known_color()); } void test_method_(create_from_know_color_olive_drab) { color c = color::from_known_color(known_color::olive_drab); assert::are_equal(color::from_known_color(known_color::olive_drab), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x6B, c.r()); assert::are_equal(0x8E, c.g()); assert::are_equal(0x23, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("olive_drab", c.name()); assert::are_equal("color [olive_drab]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF6B8E23U, c.to_argb()); assert::are_equal(known_color::olive_drab, c.to_known_color()); } void test_method_(create_from_know_color_orange) { color c = color::from_known_color(known_color::orange); assert::are_equal(color::from_known_color(known_color::orange), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xA5, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("orange", c.name()); assert::are_equal("color [orange]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFA500U, c.to_argb()); assert::are_equal(known_color::orange, c.to_known_color()); } void test_method_(create_from_know_color_orange_red) { color c = color::from_known_color(known_color::orange_red); assert::are_equal(color::from_known_color(known_color::orange_red), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0x45, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("orange_red", c.name()); assert::are_equal("color [orange_red]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFF4500U, c.to_argb()); assert::are_equal(known_color::orange_red, c.to_known_color()); } void test_method_(create_from_know_color_orchid) { color c = color::from_known_color(known_color::orchid); assert::are_equal(color::from_known_color(known_color::orchid), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xDA, c.r()); assert::are_equal(0x70, c.g()); assert::are_equal(0xD6, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("orchid", c.name()); assert::are_equal("color [orchid]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFDA70D6U, c.to_argb()); assert::are_equal(known_color::orchid, c.to_known_color()); } void test_method_(create_from_know_color_pale_goldenrod) { color c = color::from_known_color(known_color::pale_goldenrod); assert::are_equal(color::from_known_color(known_color::pale_goldenrod), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xEE, c.r()); assert::are_equal(0xE8, c.g()); assert::are_equal(0xAA, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("pale_goldenrod", c.name()); assert::are_equal("color [pale_goldenrod]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFEEE8AAU, c.to_argb()); assert::are_equal(known_color::pale_goldenrod, c.to_known_color()); } void test_method_(create_from_know_color_pale_green) { color c = color::from_known_color(known_color::pale_green); assert::are_equal(color::from_known_color(known_color::pale_green), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x98, c.r()); assert::are_equal(0xFB, c.g()); assert::are_equal(0x98, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("pale_green", c.name()); assert::are_equal("color [pale_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF98FB98U, c.to_argb()); assert::are_equal(known_color::pale_green, c.to_known_color()); } void test_method_(create_from_know_color_pale_turquoise) { color c = color::from_known_color(known_color::pale_turquoise); assert::are_equal(color::from_known_color(known_color::pale_turquoise), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xAF, c.r()); assert::are_equal(0xEE, c.g()); assert::are_equal(0xEE, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("pale_turquoise", c.name()); assert::are_equal("color [pale_turquoise]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFAFEEEEU, c.to_argb()); assert::are_equal(known_color::pale_turquoise, c.to_known_color()); } void test_method_(create_from_know_color_pale_violet_red) { color c = color::from_known_color(known_color::pale_violet_red); assert::are_equal(color::from_known_color(known_color::pale_violet_red), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xDB, c.r()); assert::are_equal(0x70, c.g()); assert::are_equal(0x93, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("pale_violet_red", c.name()); assert::are_equal("color [pale_violet_red]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFDB7093U, c.to_argb()); assert::are_equal(known_color::pale_violet_red, c.to_known_color()); } void test_method_(create_from_know_color_papaya_whip) { color c = color::from_known_color(known_color::papaya_whip); assert::are_equal(color::from_known_color(known_color::papaya_whip), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xEF, c.g()); assert::are_equal(0xD5, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("papaya_whip", c.name()); assert::are_equal("color [papaya_whip]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFEFD5U, c.to_argb()); assert::are_equal(known_color::papaya_whip, c.to_known_color()); } void test_method_(create_from_know_color_peach_puff) { color c = color::from_known_color(known_color::peach_puff); assert::are_equal(color::from_known_color(known_color::peach_puff), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xDA, c.g()); assert::are_equal(0xB9, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("peach_puff", c.name()); assert::are_equal("color [peach_puff]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFDAB9U, c.to_argb()); assert::are_equal(known_color::peach_puff, c.to_known_color()); } void test_method_(create_from_know_color_peru) { color c = color::from_known_color(known_color::peru); assert::are_equal(color::from_known_color(known_color::peru), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xCD, c.r()); assert::are_equal(0x85, c.g()); assert::are_equal(0x3F, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("peru", c.name()); assert::are_equal("color [peru]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFCD853FU, c.to_argb()); assert::are_equal(known_color::peru, c.to_known_color()); } void test_method_(create_from_know_color_pink) { color c = color::from_known_color(known_color::pink); assert::are_equal(color::from_known_color(known_color::pink), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xC0, c.g()); assert::are_equal(0xCB, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("pink", c.name()); assert::are_equal("color [pink]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFC0CBU, c.to_argb()); assert::are_equal(known_color::pink, c.to_known_color()); } void test_method_(create_from_know_color_plum) { color c = color::from_known_color(known_color::plum); assert::are_equal(color::from_known_color(known_color::plum), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xDD, c.r()); assert::are_equal(0xA0, c.g()); assert::are_equal(0xDD, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("plum", c.name()); assert::are_equal("color [plum]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFDDA0DDU, c.to_argb()); assert::are_equal(known_color::plum, c.to_known_color()); } void test_method_(create_from_know_color_powder_blue) { color c = color::from_known_color(known_color::powder_blue); assert::are_equal(color::from_known_color(known_color::powder_blue), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xB0, c.r()); assert::are_equal(0xE0, c.g()); assert::are_equal(0xE6, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("powder_blue", c.name()); assert::are_equal("color [powder_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFB0E0E6U, c.to_argb()); assert::are_equal(known_color::powder_blue, c.to_known_color()); } void test_method_(create_from_know_color_purple) { color c = color::from_known_color(known_color::purple); assert::are_equal(color::from_known_color(known_color::purple), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x80, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0x80, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("purple", c.name()); assert::are_equal("color [purple]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF800080U, c.to_argb()); assert::are_equal(known_color::purple, c.to_known_color()); } void test_method_(create_from_know_color_rebecca_purple) { color c = color::from_known_color(known_color::rebecca_purple); assert::are_equal(color::from_known_color(known_color::rebecca_purple), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x66, c.r()); assert::are_equal(0x33, c.g()); assert::are_equal(0x99, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("rebecca_purple", c.name()); assert::are_equal("color [rebecca_purple]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF663399U, c.to_argb()); assert::are_equal(known_color::rebecca_purple, c.to_known_color()); } void test_method_(create_from_know_color_red) { color c = color::from_known_color(known_color::red); assert::are_equal(color::from_known_color(known_color::red), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("red", c.name()); assert::are_equal("color [red]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFF0000U, c.to_argb()); assert::are_equal(known_color::red, c.to_known_color()); } void test_method_(create_from_know_color_rosy_brown) { color c = color::from_known_color(known_color::rosy_brown); assert::are_equal(color::from_known_color(known_color::rosy_brown), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xBC, c.r()); assert::are_equal(0x8F, c.g()); assert::are_equal(0x8F, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("rosy_brown", c.name()); assert::are_equal("color [rosy_brown]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFBC8F8FU, c.to_argb()); assert::are_equal(known_color::rosy_brown, c.to_known_color()); } void test_method_(create_from_know_color_royal_blue) { color c = color::from_known_color(known_color::royal_blue); assert::are_equal(color::from_known_color(known_color::royal_blue), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x41, c.r()); assert::are_equal(0x69, c.g()); assert::are_equal(0xE1, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("royal_blue", c.name()); assert::are_equal("color [royal_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF4169E1U, c.to_argb()); assert::are_equal(known_color::royal_blue, c.to_known_color()); } void test_method_(create_from_know_color_saddle_brown) { color c = color::from_known_color(known_color::saddle_brown); assert::are_equal(color::from_known_color(known_color::saddle_brown), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x8B, c.r()); assert::are_equal(0x45, c.g()); assert::are_equal(0x13, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("saddle_brown", c.name()); assert::are_equal("color [saddle_brown]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF8B4513U, c.to_argb()); assert::are_equal(known_color::saddle_brown, c.to_known_color()); } void test_method_(create_from_know_color_salmon) { color c = color::from_known_color(known_color::salmon); assert::are_equal(color::from_known_color(known_color::salmon), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFA, c.r()); assert::are_equal(0x80, c.g()); assert::are_equal(0x72, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("salmon", c.name()); assert::are_equal("color [salmon]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFA8072U, c.to_argb()); assert::are_equal(known_color::salmon, c.to_known_color()); } void test_method_(create_from_know_color_sandy_brown) { color c = color::from_known_color(known_color::sandy_brown); assert::are_equal(color::from_known_color(known_color::sandy_brown), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xF4, c.r()); assert::are_equal(0xA4, c.g()); assert::are_equal(0x60, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("sandy_brown", c.name()); assert::are_equal("color [sandy_brown]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFF4A460U, c.to_argb()); assert::are_equal(known_color::sandy_brown, c.to_known_color()); } void test_method_(create_from_know_color_sea_green) { color c = color::from_known_color(known_color::sea_green); assert::are_equal(color::from_known_color(known_color::sea_green), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x2E, c.r()); assert::are_equal(0x8B, c.g()); assert::are_equal(0x57, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("sea_green", c.name()); assert::are_equal("color [sea_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF2E8B57U, c.to_argb()); assert::are_equal(known_color::sea_green, c.to_known_color()); } void test_method_(create_from_know_color_sea_shell) { color c = color::from_known_color(known_color::sea_shell); assert::are_equal(color::from_known_color(known_color::sea_shell), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xF5, c.g()); assert::are_equal(0xEE, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("sea_shell", c.name()); assert::are_equal("color [sea_shell]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFF5EEU, c.to_argb()); assert::are_equal(known_color::sea_shell, c.to_known_color()); } void test_method_(create_from_know_color_sienna) { color c = color::from_known_color(known_color::sienna); assert::are_equal(color::from_known_color(known_color::sienna), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xA0, c.r()); assert::are_equal(0x52, c.g()); assert::are_equal(0x2D, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("sienna", c.name()); assert::are_equal("color [sienna]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFA0522DU, c.to_argb()); assert::are_equal(known_color::sienna, c.to_known_color()); } void test_method_(create_from_know_color_silver) { color c = color::from_known_color(known_color::silver); assert::are_equal(color::from_known_color(known_color::silver), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xC0, c.r()); assert::are_equal(0xC0, c.g()); assert::are_equal(0xC0, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("silver", c.name()); assert::are_equal("color [silver]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFC0C0C0U, c.to_argb()); assert::are_equal(known_color::silver, c.to_known_color()); } void test_method_(create_from_know_color_sky_blue) { color c = color::from_known_color(known_color::sky_blue); assert::are_equal(color::from_known_color(known_color::sky_blue), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x87, c.r()); assert::are_equal(0xCE, c.g()); assert::are_equal(0xEB, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("sky_blue", c.name()); assert::are_equal("color [sky_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF87CEEBU, c.to_argb()); assert::are_equal(known_color::sky_blue, c.to_known_color()); } void test_method_(create_from_know_color_slate_blue) { color c = color::from_known_color(known_color::slate_blue); assert::are_equal(color::from_known_color(known_color::slate_blue), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x6A, c.r()); assert::are_equal(0x5A, c.g()); assert::are_equal(0xCD, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("slate_blue", c.name()); assert::are_equal("color [slate_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF6A5ACDU, c.to_argb()); assert::are_equal(known_color::slate_blue, c.to_known_color()); } void test_method_(create_from_know_color_slate_gray) { color c = color::from_known_color(known_color::slate_gray); assert::are_equal(color::from_known_color(known_color::slate_gray), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x70, c.r()); assert::are_equal(0x80, c.g()); assert::are_equal(0x90, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("slate_gray", c.name()); assert::are_equal("color [slate_gray]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF708090U, c.to_argb()); assert::are_equal(known_color::slate_gray, c.to_known_color()); } void test_method_(create_from_know_color_snow) { color c = color::from_known_color(known_color::snow); assert::are_equal(color::from_known_color(known_color::snow), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xFA, c.g()); assert::are_equal(0xFA, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("snow", c.name()); assert::are_equal("color [snow]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFFAFAU, c.to_argb()); assert::are_equal(known_color::snow, c.to_known_color()); } void test_method_(create_from_know_color_spring_green) { color c = color::from_known_color(known_color::spring_green); assert::are_equal(color::from_known_color(known_color::spring_green), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0x7F, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("spring_green", c.name()); assert::are_equal("color [spring_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF00FF7FU, c.to_argb()); assert::are_equal(known_color::spring_green, c.to_known_color()); } void test_method_(create_from_know_color_steel_blue) { color c = color::from_known_color(known_color::steel_blue); assert::are_equal(color::from_known_color(known_color::steel_blue), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x46, c.r()); assert::are_equal(0x82, c.g()); assert::are_equal(0xB4, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("steel_blue", c.name()); assert::are_equal("color [steel_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF4682B4U, c.to_argb()); assert::are_equal(known_color::steel_blue, c.to_known_color()); } void test_method_(create_from_know_color_tan) { color c = color::from_known_color(known_color::tan); assert::are_equal(color::from_known_color(known_color::tan), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xD2, c.r()); assert::are_equal(0xB4, c.g()); assert::are_equal(0x8C, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("tan", c.name()); assert::are_equal("color [tan]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFD2B48CU, c.to_argb()); assert::are_equal(known_color::tan, c.to_known_color()); } void test_method_(create_from_know_color_teal) { color c = color::from_known_color(known_color::teal); assert::are_equal(color::from_known_color(known_color::teal), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0x80, c.g()); assert::are_equal(0x80, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("teal", c.name()); assert::are_equal("color [teal]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF008080U, c.to_argb()); assert::are_equal(known_color::teal, c.to_known_color()); } void test_method_(create_from_know_color_thistle) { color c = color::from_known_color(known_color::thistle); assert::are_equal(color::from_known_color(known_color::thistle), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xD8, c.r()); assert::are_equal(0xBF, c.g()); assert::are_equal(0xD8, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("thistle", c.name()); assert::are_equal("color [thistle]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFD8BFD8U, c.to_argb()); assert::are_equal(known_color::thistle, c.to_known_color()); } void test_method_(create_from_know_color_tomato) { color c = color::from_known_color(known_color::tomato); assert::are_equal(color::from_known_color(known_color::tomato), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0x63, c.g()); assert::are_equal(0x47, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("tomato", c.name()); assert::are_equal("color [tomato]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFF6347U, c.to_argb()); assert::are_equal(known_color::tomato, c.to_known_color()); } void test_method_(create_from_know_color_turquoise) { color c = color::from_known_color(known_color::turquoise); assert::are_equal(color::from_known_color(known_color::turquoise), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x40, c.r()); assert::are_equal(0xE0, c.g()); assert::are_equal(0xD0, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("turquoise", c.name()); assert::are_equal("color [turquoise]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF40E0D0U, c.to_argb()); assert::are_equal(known_color::turquoise, c.to_known_color()); } void test_method_(create_from_know_color_violet) { color c = color::from_known_color(known_color::violet); assert::are_equal(color::from_known_color(known_color::violet), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xEE, c.r()); assert::are_equal(0x82, c.g()); assert::are_equal(0xEE, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("violet", c.name()); assert::are_equal("color [violet]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFEE82EEU, c.to_argb()); assert::are_equal(known_color::violet, c.to_known_color()); } void test_method_(create_from_know_color_wheat) { color c = color::from_known_color(known_color::wheat); assert::are_equal(color::from_known_color(known_color::wheat), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xF5, c.r()); assert::are_equal(0xDE, c.g()); assert::are_equal(0xB3, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("wheat", c.name()); assert::are_equal("color [wheat]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFF5DEB3U, c.to_argb()); assert::are_equal(known_color::wheat, c.to_known_color()); } void test_method_(create_from_know_color_white) { color c = color::from_known_color(known_color::white); assert::are_equal(color::from_known_color(known_color::white), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("white", c.name()); assert::are_equal("color [white]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFFFFFU, c.to_argb()); assert::are_equal(known_color::white, c.to_known_color()); } void test_method_(create_from_know_color_white_smoke) { color c = color::from_known_color(known_color::white_smoke); assert::are_equal(color::from_known_color(known_color::white_smoke), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xF5, c.r()); assert::are_equal(0xF5, c.g()); assert::are_equal(0xF5, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("white_smoke", c.name()); assert::are_equal("color [white_smoke]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFF5F5F5U, c.to_argb()); assert::are_equal(known_color::white_smoke, c.to_known_color()); } void test_method_(create_from_know_color_yellow) { color c = color::from_known_color(known_color::yellow); assert::are_equal(color::from_known_color(known_color::yellow), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("yellow", c.name()); assert::are_equal("color [yellow]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFFF00U, c.to_argb()); assert::are_equal(known_color::yellow, c.to_known_color()); } void test_method_(create_from_name_transparent) { color c = color::from_name("transparent"); assert::are_equal(color::from_name("transparent"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0x00, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("transparent", c.name()); assert::are_equal("color [transparent]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0x00FFFFFFU, c.to_argb()); assert::are_equal(known_color::transparent, c.to_known_color()); } void test_method_(create_from_name_alice_blue) { color c = color::from_name("alice_blue"); assert::are_equal(color::from_name("alice_blue"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xF0, c.r()); assert::are_equal(0xF8, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("alice_blue", c.name()); assert::are_equal("color [alice_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFF0F8FFU, c.to_argb()); assert::are_equal(known_color::alice_blue, c.to_known_color()); } void test_method_(create_from_name_antique_white) { color c = color::from_name("antique_white"); assert::are_equal(color::from_name("antique_white"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFA, c.r()); assert::are_equal(0xEB, c.g()); assert::are_equal(0xD7, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("antique_white", c.name()); assert::are_equal("color [antique_white]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFAEBD7U, c.to_argb()); assert::are_equal(known_color::antique_white, c.to_known_color()); } void test_method_(create_from_name_aqua) { color c = color::from_name("aqua"); assert::are_equal(color::from_name("aqua"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("aqua", c.name()); assert::are_equal("color [aqua]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF00FFFFU, c.to_argb()); assert::are_equal(known_color::aqua, c.to_known_color()); } void test_method_(create_from_name_aquamarine) { color c = color::from_name("aquamarine"); assert::are_equal(color::from_name("aquamarine"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x7F, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0xD4, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("aquamarine", c.name()); assert::are_equal("color [aquamarine]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF7FFFD4U, c.to_argb()); assert::are_equal(known_color::aquamarine, c.to_known_color()); } void test_method_(create_from_name_azure) { color c = color::from_name("azure"); assert::are_equal(color::from_name("azure"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xF0, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("azure", c.name()); assert::are_equal("color [azure]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFF0FFFFU, c.to_argb()); assert::are_equal(known_color::azure, c.to_known_color()); } void test_method_(create_from_name_beige) { color c = color::from_name("beige"); assert::are_equal(color::from_name("beige"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xF5, c.r()); assert::are_equal(0xF5, c.g()); assert::are_equal(0xDC, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("beige", c.name()); assert::are_equal("color [beige]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFF5F5DCU, c.to_argb()); assert::are_equal(known_color::beige, c.to_known_color()); } void test_method_(create_from_name_bisque) { color c = color::from_name("bisque"); assert::are_equal(color::from_name("bisque"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xE4, c.g()); assert::are_equal(0xC4, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("bisque", c.name()); assert::are_equal("color [bisque]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFE4C4U, c.to_argb()); assert::are_equal(known_color::bisque, c.to_known_color()); } void test_method_(create_from_name_black) { color c = color::from_name("black"); assert::are_equal(color::from_name("black"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("black", c.name()); assert::are_equal("color [black]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF000000U, c.to_argb()); assert::are_equal(known_color::black, c.to_known_color()); } void test_method_(create_from_name_blanched_almond) { color c = color::from_name("blanched_almond"); assert::are_equal(color::from_name("blanched_almond"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xEB, c.g()); assert::are_equal(0xCD, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("blanched_almond", c.name()); assert::are_equal("color [blanched_almond]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFEBCDU, c.to_argb()); assert::are_equal(known_color::blanched_almond, c.to_known_color()); } void test_method_(create_from_name_blue) { color c = color::from_name("blue"); assert::are_equal(color::from_name("blue"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("blue", c.name()); assert::are_equal("color [blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF0000FFU, c.to_argb()); assert::are_equal(known_color::blue, c.to_known_color()); } void test_method_(create_from_name_blue_violet) { color c = color::from_name("blue_violet"); assert::are_equal(color::from_name("blue_violet"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x8A, c.r()); assert::are_equal(0x2B, c.g()); assert::are_equal(0xE2, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("blue_violet", c.name()); assert::are_equal("color [blue_violet]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF8A2BE2U, c.to_argb()); assert::are_equal(known_color::blue_violet, c.to_known_color()); } void test_method_(create_from_name_brown) { color c = color::from_name("brown"); assert::are_equal(color::from_name("brown"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xA5, c.r()); assert::are_equal(0x2A, c.g()); assert::are_equal(0x2A, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("brown", c.name()); assert::are_equal("color [brown]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFA52A2AU, c.to_argb()); assert::are_equal(known_color::brown, c.to_known_color()); } void test_method_(create_from_name_burly_wood) { color c = color::from_name("burly_wood"); assert::are_equal(color::from_name("burly_wood"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xDE, c.r()); assert::are_equal(0xB8, c.g()); assert::are_equal(0x87, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("burly_wood", c.name()); assert::are_equal("color [burly_wood]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFDEB887U, c.to_argb()); assert::are_equal(known_color::burly_wood, c.to_known_color()); } void test_method_(create_from_name_cadet_blue) { color c = color::from_name("cadet_blue"); assert::are_equal(color::from_name("cadet_blue"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x5F, c.r()); assert::are_equal(0x9E, c.g()); assert::are_equal(0xA0, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("cadet_blue", c.name()); assert::are_equal("color [cadet_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF5F9EA0U, c.to_argb()); assert::are_equal(known_color::cadet_blue, c.to_known_color()); } void test_method_(create_from_name_chartreuse) { color c = color::from_name("chartreuse"); assert::are_equal(color::from_name("chartreuse"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x7F, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("chartreuse", c.name()); assert::are_equal("color [chartreuse]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF7FFF00U, c.to_argb()); assert::are_equal(known_color::chartreuse, c.to_known_color()); } void test_method_(create_from_name_chocolate) { color c = color::from_name("chocolate"); assert::are_equal(color::from_name("chocolate"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xD2, c.r()); assert::are_equal(0x69, c.g()); assert::are_equal(0x1E, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("chocolate", c.name()); assert::are_equal("color [chocolate]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFD2691EU, c.to_argb()); assert::are_equal(known_color::chocolate, c.to_known_color()); } void test_method_(create_from_name_coral) { color c = color::from_name("coral"); assert::are_equal(color::from_name("coral"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0x7F, c.g()); assert::are_equal(0x50, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("coral", c.name()); assert::are_equal("color [coral]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFF7F50U, c.to_argb()); assert::are_equal(known_color::coral, c.to_known_color()); } void test_method_(create_from_name_cornflower_blue) { color c = color::from_name("cornflower_blue"); assert::are_equal(color::from_name("cornflower_blue"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x64, c.r()); assert::are_equal(0x95, c.g()); assert::are_equal(0xED, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("cornflower_blue", c.name()); assert::are_equal("color [cornflower_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF6495EDU, c.to_argb()); assert::are_equal(known_color::cornflower_blue, c.to_known_color()); } void test_method_(create_from_name_cornsilk) { color c = color::from_name("cornsilk"); assert::are_equal(color::from_name("cornsilk"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xF8, c.g()); assert::are_equal(0xDC, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("cornsilk", c.name()); assert::are_equal("color [cornsilk]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFF8DCU, c.to_argb()); assert::are_equal(known_color::cornsilk, c.to_known_color()); } void test_method_(create_from_name_crimson) { color c = color::from_name("crimson"); assert::are_equal(color::from_name("crimson"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xDC, c.r()); assert::are_equal(0x14, c.g()); assert::are_equal(0x3C, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("crimson", c.name()); assert::are_equal("color [crimson]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFDC143CU, c.to_argb()); assert::are_equal(known_color::crimson, c.to_known_color()); } void test_method_(create_from_name_cyan) { color c = color::from_name("cyan"); assert::are_equal(color::from_name("cyan"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("cyan", c.name()); assert::are_equal("color [cyan]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF00FFFFU, c.to_argb()); assert::are_equal(known_color::cyan, c.to_known_color()); } void test_method_(create_from_name_dark_blue) { color c = color::from_name("dark_blue"); assert::are_equal(color::from_name("dark_blue"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0x8B, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_blue", c.name()); assert::are_equal("color [dark_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF00008BU, c.to_argb()); assert::are_equal(known_color::dark_blue, c.to_known_color()); } void test_method_(create_from_name_dark_cyan) { color c = color::from_name("dark_cyan"); assert::are_equal(color::from_name("dark_cyan"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0x8B, c.g()); assert::are_equal(0x8B, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_cyan", c.name()); assert::are_equal("color [dark_cyan]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF008B8BU, c.to_argb()); assert::are_equal(known_color::dark_cyan, c.to_known_color()); } void test_method_(create_from_name_dark_goldenrod) { color c = color::from_name("dark_goldenrod"); assert::are_equal(color::from_name("dark_goldenrod"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xB8, c.r()); assert::are_equal(0x86, c.g()); assert::are_equal(0x0B, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_goldenrod", c.name()); assert::are_equal("color [dark_goldenrod]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFB8860BU, c.to_argb()); assert::are_equal(known_color::dark_goldenrod, c.to_known_color()); } void test_method_(create_from_name_dark_gray) { color c = color::from_name("dark_gray"); assert::are_equal(color::from_name("dark_gray"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xA9, c.r()); assert::are_equal(0xA9, c.g()); assert::are_equal(0xA9, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_gray", c.name()); assert::are_equal("color [dark_gray]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFA9A9A9U, c.to_argb()); assert::are_equal(known_color::dark_gray, c.to_known_color()); } void test_method_(create_from_name_dark_green) { color c = color::from_name("dark_green"); assert::are_equal(color::from_name("dark_green"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0x64, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_green", c.name()); assert::are_equal("color [dark_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF006400U, c.to_argb()); assert::are_equal(known_color::dark_green, c.to_known_color()); } void test_method_(create_from_name_dark_khaki) { color c = color::from_name("dark_khaki"); assert::are_equal(color::from_name("dark_khaki"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xBD, c.r()); assert::are_equal(0xB7, c.g()); assert::are_equal(0x6B, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_khaki", c.name()); assert::are_equal("color [dark_khaki]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFBDB76BU, c.to_argb()); assert::are_equal(known_color::dark_khaki, c.to_known_color()); } void test_method_(create_from_name_dark_magenta) { color c = color::from_name("dark_magenta"); assert::are_equal(color::from_name("dark_magenta"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x8B, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0x8B, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_magenta", c.name()); assert::are_equal("color [dark_magenta]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF8B008BU, c.to_argb()); assert::are_equal(known_color::dark_magenta, c.to_known_color()); } void test_method_(create_from_name_dark_olive_green) { color c = color::from_name("dark_olive_green"); assert::are_equal(color::from_name("dark_olive_green"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x55, c.r()); assert::are_equal(0x6B, c.g()); assert::are_equal(0x2F, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_olive_green", c.name()); assert::are_equal("color [dark_olive_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF556B2FU, c.to_argb()); assert::are_equal(known_color::dark_olive_green, c.to_known_color()); } void test_method_(create_from_name_dark_orange) { color c = color::from_name("dark_orange"); assert::are_equal(color::from_name("dark_orange"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0x8C, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_orange", c.name()); assert::are_equal("color [dark_orange]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFF8C00U, c.to_argb()); assert::are_equal(known_color::dark_orange, c.to_known_color()); } void test_method_(create_from_name_dark_orchid) { color c = color::from_name("dark_orchid"); assert::are_equal(color::from_name("dark_orchid"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x99, c.r()); assert::are_equal(0x32, c.g()); assert::are_equal(0xCC, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_orchid", c.name()); assert::are_equal("color [dark_orchid]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF9932CCU, c.to_argb()); assert::are_equal(known_color::dark_orchid, c.to_known_color()); } void test_method_(create_from_name_dark_red) { color c = color::from_name("dark_red"); assert::are_equal(color::from_name("dark_red"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x8B, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_red", c.name()); assert::are_equal("color [dark_red]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF8B0000U, c.to_argb()); assert::are_equal(known_color::dark_red, c.to_known_color()); } void test_method_(create_from_name_dark_salmon) { color c = color::from_name("dark_salmon"); assert::are_equal(color::from_name("dark_salmon"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xE9, c.r()); assert::are_equal(0x96, c.g()); assert::are_equal(0x7A, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_salmon", c.name()); assert::are_equal("color [dark_salmon]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFE9967AU, c.to_argb()); assert::are_equal(known_color::dark_salmon, c.to_known_color()); } void test_method_(create_from_name_dark_sea_green) { color c = color::from_name("dark_sea_green"); assert::are_equal(color::from_name("dark_sea_green"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x8F, c.r()); assert::are_equal(0xBC, c.g()); assert::are_equal(0x8B, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_sea_green", c.name()); assert::are_equal("color [dark_sea_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF8FBC8BU, c.to_argb()); assert::are_equal(known_color::dark_sea_green, c.to_known_color()); } void test_method_(create_from_name_dark_slate_blue) { color c = color::from_name("dark_slate_blue"); assert::are_equal(color::from_name("dark_slate_blue"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x48, c.r()); assert::are_equal(0x3D, c.g()); assert::are_equal(0x8B, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_slate_blue", c.name()); assert::are_equal("color [dark_slate_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF483D8BU, c.to_argb()); assert::are_equal(known_color::dark_slate_blue, c.to_known_color()); } void test_method_(create_from_name_dark_slate_gray) { color c = color::from_name("dark_slate_gray"); assert::are_equal(color::from_name("dark_slate_gray"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x2F, c.r()); assert::are_equal(0x4F, c.g()); assert::are_equal(0x4F, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_slate_gray", c.name()); assert::are_equal("color [dark_slate_gray]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF2F4F4FU, c.to_argb()); assert::are_equal(known_color::dark_slate_gray, c.to_known_color()); } void test_method_(create_from_name_dark_turquoise) { color c = color::from_name("dark_turquoise"); assert::are_equal(color::from_name("dark_turquoise"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0xCE, c.g()); assert::are_equal(0xD1, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_turquoise", c.name()); assert::are_equal("color [dark_turquoise]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF00CED1U, c.to_argb()); assert::are_equal(known_color::dark_turquoise, c.to_known_color()); } void test_method_(create_from_name_dark_violet) { color c = color::from_name("dark_violet"); assert::are_equal(color::from_name("dark_violet"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x94, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0xD3, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dark_violet", c.name()); assert::are_equal("color [dark_violet]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF9400D3U, c.to_argb()); assert::are_equal(known_color::dark_violet, c.to_known_color()); } void test_method_(create_from_name_deep_pink) { color c = color::from_name("deep_pink"); assert::are_equal(color::from_name("deep_pink"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0x14, c.g()); assert::are_equal(0x93, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("deep_pink", c.name()); assert::are_equal("color [deep_pink]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFF1493U, c.to_argb()); assert::are_equal(known_color::deep_pink, c.to_known_color()); } void test_method_(create_from_name_deep_sky_blue) { color c = color::from_name("deep_sky_blue"); assert::are_equal(color::from_name("deep_sky_blue"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0xBF, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("deep_sky_blue", c.name()); assert::are_equal("color [deep_sky_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF00BFFFU, c.to_argb()); assert::are_equal(known_color::deep_sky_blue, c.to_known_color()); } void test_method_(create_from_name_dim_gray) { color c = color::from_name("dim_gray"); assert::are_equal(color::from_name("dim_gray"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x69, c.r()); assert::are_equal(0x69, c.g()); assert::are_equal(0x69, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dim_gray", c.name()); assert::are_equal("color [dim_gray]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF696969U, c.to_argb()); assert::are_equal(known_color::dim_gray, c.to_known_color()); } void test_method_(create_from_name_dodger_blue) { color c = color::from_name("dodger_blue"); assert::are_equal(color::from_name("dodger_blue"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x1E, c.r()); assert::are_equal(0x90, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("dodger_blue", c.name()); assert::are_equal("color [dodger_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF1E90FFU, c.to_argb()); assert::are_equal(known_color::dodger_blue, c.to_known_color()); } void test_method_(create_from_name_firebrick) { color c = color::from_name("firebrick"); assert::are_equal(color::from_name("firebrick"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xB2, c.r()); assert::are_equal(0x22, c.g()); assert::are_equal(0x22, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("firebrick", c.name()); assert::are_equal("color [firebrick]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFB22222U, c.to_argb()); assert::are_equal(known_color::firebrick, c.to_known_color()); } void test_method_(create_from_name_floral_white) { color c = color::from_name("floral_white"); assert::are_equal(color::from_name("floral_white"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xFA, c.g()); assert::are_equal(0xF0, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("floral_white", c.name()); assert::are_equal("color [floral_white]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFFAF0U, c.to_argb()); assert::are_equal(known_color::floral_white, c.to_known_color()); } void test_method_(create_from_name_forest_green) { color c = color::from_name("forest_green"); assert::are_equal(color::from_name("forest_green"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x22, c.r()); assert::are_equal(0x8B, c.g()); assert::are_equal(0x22, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("forest_green", c.name()); assert::are_equal("color [forest_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF228B22U, c.to_argb()); assert::are_equal(known_color::forest_green, c.to_known_color()); } void test_method_(create_from_name_fuchsia) { color c = color::from_name("fuchsia"); assert::are_equal(color::from_name("fuchsia"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("fuchsia", c.name()); assert::are_equal("color [fuchsia]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFF00FFU, c.to_argb()); assert::are_equal(known_color::fuchsia, c.to_known_color()); } void test_method_(create_from_name_gainsboro) { color c = color::from_name("gainsboro"); assert::are_equal(color::from_name("gainsboro"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xDC, c.r()); assert::are_equal(0xDC, c.g()); assert::are_equal(0xDC, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("gainsboro", c.name()); assert::are_equal("color [gainsboro]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFDCDCDCU, c.to_argb()); assert::are_equal(known_color::gainsboro, c.to_known_color()); } void test_method_(create_from_name_ghost_white) { color c = color::from_name("ghost_white"); assert::are_equal(color::from_name("ghost_white"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xF8, c.r()); assert::are_equal(0xF8, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("ghost_white", c.name()); assert::are_equal("color [ghost_white]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFF8F8FFU, c.to_argb()); assert::are_equal(known_color::ghost_white, c.to_known_color()); } void test_method_(create_from_name_gold) { color c = color::from_name("gold"); assert::are_equal(color::from_name("gold"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xD7, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("gold", c.name()); assert::are_equal("color [gold]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFD700U, c.to_argb()); assert::are_equal(known_color::gold, c.to_known_color()); } void test_method_(create_from_name_goldenrod) { color c = color::from_name("goldenrod"); assert::are_equal(color::from_name("goldenrod"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xDA, c.r()); assert::are_equal(0xA5, c.g()); assert::are_equal(0x20, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("goldenrod", c.name()); assert::are_equal("color [goldenrod]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFDAA520U, c.to_argb()); assert::are_equal(known_color::goldenrod, c.to_known_color()); } void test_method_(create_from_name_gray) { color c = color::from_name("gray"); assert::are_equal(color::from_name("gray"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x80, c.r()); assert::are_equal(0x80, c.g()); assert::are_equal(0x80, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("gray", c.name()); assert::are_equal("color [gray]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF808080U, c.to_argb()); assert::are_equal(known_color::gray, c.to_known_color()); } void test_method_(create_from_name_green) { color c = color::from_name("green"); assert::are_equal(color::from_name("green"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0x80, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("green", c.name()); assert::are_equal("color [green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF008000U, c.to_argb()); assert::are_equal(known_color::green, c.to_known_color()); } void test_method_(create_from_name_green_yellow) { color c = color::from_name("green_yellow"); assert::are_equal(color::from_name("green_yellow"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xAD, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0x2F, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("green_yellow", c.name()); assert::are_equal("color [green_yellow]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFADFF2FU, c.to_argb()); assert::are_equal(known_color::green_yellow, c.to_known_color()); } void test_method_(create_from_name_honeydew) { color c = color::from_name("honeydew"); assert::are_equal(color::from_name("honeydew"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xF0, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0xF0, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("honeydew", c.name()); assert::are_equal("color [honeydew]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFF0FFF0U, c.to_argb()); assert::are_equal(known_color::honeydew, c.to_known_color()); } void test_method_(create_from_name_hot_pink) { color c = color::from_name("hot_pink"); assert::are_equal(color::from_name("hot_pink"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0x69, c.g()); assert::are_equal(0xB4, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("hot_pink", c.name()); assert::are_equal("color [hot_pink]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFF69B4U, c.to_argb()); assert::are_equal(known_color::hot_pink, c.to_known_color()); } void test_method_(create_from_name_indian_red) { color c = color::from_name("indian_red"); assert::are_equal(color::from_name("indian_red"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xCD, c.r()); assert::are_equal(0x5C, c.g()); assert::are_equal(0x5C, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("indian_red", c.name()); assert::are_equal("color [indian_red]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFCD5C5CU, c.to_argb()); assert::are_equal(known_color::indian_red, c.to_known_color()); } void test_method_(create_from_name_indigo) { color c = color::from_name("indigo"); assert::are_equal(color::from_name("indigo"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x4B, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0x82, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("indigo", c.name()); assert::are_equal("color [indigo]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF4B0082U, c.to_argb()); assert::are_equal(known_color::indigo, c.to_known_color()); } void test_method_(create_from_name_ivory) { color c = color::from_name("ivory"); assert::are_equal(color::from_name("ivory"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0xF0, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("ivory", c.name()); assert::are_equal("color [ivory]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFFFF0U, c.to_argb()); assert::are_equal(known_color::ivory, c.to_known_color()); } void test_method_(create_from_name_khaki) { color c = color::from_name("khaki"); assert::are_equal(color::from_name("khaki"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xF0, c.r()); assert::are_equal(0xE6, c.g()); assert::are_equal(0x8C, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("khaki", c.name()); assert::are_equal("color [khaki]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFF0E68CU, c.to_argb()); assert::are_equal(known_color::khaki, c.to_known_color()); } void test_method_(create_from_name_lavender) { color c = color::from_name("lavender"); assert::are_equal(color::from_name("lavender"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xE6, c.r()); assert::are_equal(0xE6, c.g()); assert::are_equal(0xFA, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("lavender", c.name()); assert::are_equal("color [lavender]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFE6E6FAU, c.to_argb()); assert::are_equal(known_color::lavender, c.to_known_color()); } void test_method_(create_from_name_lavender_blush) { color c = color::from_name("lavender_blush"); assert::are_equal(color::from_name("lavender_blush"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xF0, c.g()); assert::are_equal(0xF5, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("lavender_blush", c.name()); assert::are_equal("color [lavender_blush]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFF0F5U, c.to_argb()); assert::are_equal(known_color::lavender_blush, c.to_known_color()); } void test_method_(create_from_name_lawn_green) { color c = color::from_name("lawn_green"); assert::are_equal(color::from_name("lawn_green"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x7C, c.r()); assert::are_equal(0xFC, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("lawn_green", c.name()); assert::are_equal("color [lawn_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF7CFC00U, c.to_argb()); assert::are_equal(known_color::lawn_green, c.to_known_color()); } void test_method_(create_from_name_lemon_chiffon) { color c = color::from_name("lemon_chiffon"); assert::are_equal(color::from_name("lemon_chiffon"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xFA, c.g()); assert::are_equal(0xCD, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("lemon_chiffon", c.name()); assert::are_equal("color [lemon_chiffon]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFFACDU, c.to_argb()); assert::are_equal(known_color::lemon_chiffon, c.to_known_color()); } void test_method_(create_from_name_light_blue) { color c = color::from_name("light_blue"); assert::are_equal(color::from_name("light_blue"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xAD, c.r()); assert::are_equal(0xD8, c.g()); assert::are_equal(0xE6, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_blue", c.name()); assert::are_equal("color [light_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFADD8E6U, c.to_argb()); assert::are_equal(known_color::light_blue, c.to_known_color()); } void test_method_(create_from_name_light_coral) { color c = color::from_name("light_coral"); assert::are_equal(color::from_name("light_coral"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xF0, c.r()); assert::are_equal(0x80, c.g()); assert::are_equal(0x80, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_coral", c.name()); assert::are_equal("color [light_coral]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFF08080U, c.to_argb()); assert::are_equal(known_color::light_coral, c.to_known_color()); } void test_method_(create_from_name_light_cyan) { color c = color::from_name("light_cyan"); assert::are_equal(color::from_name("light_cyan"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xE0, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_cyan", c.name()); assert::are_equal("color [light_cyan]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFE0FFFFU, c.to_argb()); assert::are_equal(known_color::light_cyan, c.to_known_color()); } void test_method_(create_from_name_light_goldenrod_yellow) { color c = color::from_name("light_goldenrod_yellow"); assert::are_equal(color::from_name("light_goldenrod_yellow"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFA, c.r()); assert::are_equal(0xFA, c.g()); assert::are_equal(0xD2, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_goldenrod_yellow", c.name()); assert::are_equal("color [light_goldenrod_yellow]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFAFAD2U, c.to_argb()); assert::are_equal(known_color::light_goldenrod_yellow, c.to_known_color()); } void test_method_(create_from_name_light_gray) { color c = color::from_name("light_gray"); assert::are_equal(color::from_name("light_gray"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xD3, c.r()); assert::are_equal(0xD3, c.g()); assert::are_equal(0xD3, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_gray", c.name()); assert::are_equal("color [light_gray]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFD3D3D3U, c.to_argb()); assert::are_equal(known_color::light_gray, c.to_known_color()); } void test_method_(create_from_name_light_green) { color c = color::from_name("light_green"); assert::are_equal(color::from_name("light_green"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x90, c.r()); assert::are_equal(0xEE, c.g()); assert::are_equal(0x90, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_green", c.name()); assert::are_equal("color [light_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF90EE90U, c.to_argb()); assert::are_equal(known_color::light_green, c.to_known_color()); } void test_method_(create_from_name_light_pink) { color c = color::from_name("light_pink"); assert::are_equal(color::from_name("light_pink"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xB6, c.g()); assert::are_equal(0xC1, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_pink", c.name()); assert::are_equal("color [light_pink]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFB6C1U, c.to_argb()); assert::are_equal(known_color::light_pink, c.to_known_color()); } void test_method_(create_from_name_light_salmon) { color c = color::from_name("light_salmon"); assert::are_equal(color::from_name("light_salmon"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xA0, c.g()); assert::are_equal(0x7A, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_salmon", c.name()); assert::are_equal("color [light_salmon]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFA07AU, c.to_argb()); assert::are_equal(known_color::light_salmon, c.to_known_color()); } void test_method_(create_from_name_light_sea_green) { color c = color::from_name("light_sea_green"); assert::are_equal(color::from_name("light_sea_green"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x20, c.r()); assert::are_equal(0xB2, c.g()); assert::are_equal(0xAA, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_sea_green", c.name()); assert::are_equal("color [light_sea_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF20B2AAU, c.to_argb()); assert::are_equal(known_color::light_sea_green, c.to_known_color()); } void test_method_(create_from_name_light_sky_blue) { color c = color::from_name("light_sky_blue"); assert::are_equal(color::from_name("light_sky_blue"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x87, c.r()); assert::are_equal(0xCE, c.g()); assert::are_equal(0xFA, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_sky_blue", c.name()); assert::are_equal("color [light_sky_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF87CEFAU, c.to_argb()); assert::are_equal(known_color::light_sky_blue, c.to_known_color()); } void test_method_(create_from_name_light_slate_gray) { color c = color::from_name("light_slate_gray"); assert::are_equal(color::from_name("light_slate_gray"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x77, c.r()); assert::are_equal(0x88, c.g()); assert::are_equal(0x99, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_slate_gray", c.name()); assert::are_equal("color [light_slate_gray]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF778899U, c.to_argb()); assert::are_equal(known_color::light_slate_gray, c.to_known_color()); } void test_method_(create_from_name_light_steel_blue) { color c = color::from_name("light_steel_blue"); assert::are_equal(color::from_name("light_steel_blue"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xB0, c.r()); assert::are_equal(0xC4, c.g()); assert::are_equal(0xDE, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_steel_blue", c.name()); assert::are_equal("color [light_steel_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFB0C4DEU, c.to_argb()); assert::are_equal(known_color::light_steel_blue, c.to_known_color()); } void test_method_(create_from_name_light_yellow) { color c = color::from_name("light_yellow"); assert::are_equal(color::from_name("light_yellow"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0xE0, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("light_yellow", c.name()); assert::are_equal("color [light_yellow]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFFFE0U, c.to_argb()); assert::are_equal(known_color::light_yellow, c.to_known_color()); } void test_method_(create_from_name_lime) { color c = color::from_name("lime"); assert::are_equal(color::from_name("lime"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("lime", c.name()); assert::are_equal("color [lime]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF00FF00U, c.to_argb()); assert::are_equal(known_color::lime, c.to_known_color()); } void test_method_(create_from_name_lime_green) { color c = color::from_name("lime_green"); assert::are_equal(color::from_name("lime_green"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x32, c.r()); assert::are_equal(0xCD, c.g()); assert::are_equal(0x32, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("lime_green", c.name()); assert::are_equal("color [lime_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF32CD32U, c.to_argb()); assert::are_equal(known_color::lime_green, c.to_known_color()); } void test_method_(create_from_name_linen) { color c = color::from_name("linen"); assert::are_equal(color::from_name("linen"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFA, c.r()); assert::are_equal(0xF0, c.g()); assert::are_equal(0xE6, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("linen", c.name()); assert::are_equal("color [linen]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFAF0E6U, c.to_argb()); assert::are_equal(known_color::linen, c.to_known_color()); } void test_method_(create_from_name_magenta) { color c = color::from_name("magenta"); assert::are_equal(color::from_name("magenta"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("magenta", c.name()); assert::are_equal("color [magenta]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFF00FFU, c.to_argb()); assert::are_equal(known_color::magenta, c.to_known_color()); } void test_method_(create_from_name_maroon) { color c = color::from_name("maroon"); assert::are_equal(color::from_name("maroon"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x80, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("maroon", c.name()); assert::are_equal("color [maroon]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF800000U, c.to_argb()); assert::are_equal(known_color::maroon, c.to_known_color()); } void test_method_(create_from_name_medium_aquamarine) { color c = color::from_name("medium_aquamarine"); assert::are_equal(color::from_name("medium_aquamarine"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x66, c.r()); assert::are_equal(0xCD, c.g()); assert::are_equal(0xAA, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("medium_aquamarine", c.name()); assert::are_equal("color [medium_aquamarine]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF66CDAAU, c.to_argb()); assert::are_equal(known_color::medium_aquamarine, c.to_known_color()); } void test_method_(create_from_name_medium_blue) { color c = color::from_name("medium_blue"); assert::are_equal(color::from_name("medium_blue"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0xCD, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("medium_blue", c.name()); assert::are_equal("color [medium_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF0000CDU, c.to_argb()); assert::are_equal(known_color::medium_blue, c.to_known_color()); } void test_method_(create_from_name_medium_orchid) { color c = color::from_name("medium_orchid"); assert::are_equal(color::from_name("medium_orchid"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xBA, c.r()); assert::are_equal(0x55, c.g()); assert::are_equal(0xD3, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("medium_orchid", c.name()); assert::are_equal("color [medium_orchid]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFBA55D3U, c.to_argb()); assert::are_equal(known_color::medium_orchid, c.to_known_color()); } void test_method_(create_from_name_medium_purple) { color c = color::from_name("medium_purple"); assert::are_equal(color::from_name("medium_purple"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x93, c.r()); assert::are_equal(0x70, c.g()); assert::are_equal(0xDB, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("medium_purple", c.name()); assert::are_equal("color [medium_purple]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF9370DBU, c.to_argb()); assert::are_equal(known_color::medium_purple, c.to_known_color()); } void test_method_(create_from_name_medium_sea_green) { color c = color::from_name("medium_sea_green"); assert::are_equal(color::from_name("medium_sea_green"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x3C, c.r()); assert::are_equal(0xB3, c.g()); assert::are_equal(0x71, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("medium_sea_green", c.name()); assert::are_equal("color [medium_sea_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF3CB371U, c.to_argb()); assert::are_equal(known_color::medium_sea_green, c.to_known_color()); } void test_method_(create_from_name_medium_slate_blue) { color c = color::from_name("medium_slate_blue"); assert::are_equal(color::from_name("medium_slate_blue"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x7B, c.r()); assert::are_equal(0x68, c.g()); assert::are_equal(0xEE, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("medium_slate_blue", c.name()); assert::are_equal("color [medium_slate_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF7B68EEU, c.to_argb()); assert::are_equal(known_color::medium_slate_blue, c.to_known_color()); } void test_method_(create_from_name_medium_spring_green) { color c = color::from_name("medium_spring_green"); assert::are_equal(color::from_name("medium_spring_green"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0xFA, c.g()); assert::are_equal(0x9A, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("medium_spring_green", c.name()); assert::are_equal("color [medium_spring_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF00FA9AU, c.to_argb()); assert::are_equal(known_color::medium_spring_green, c.to_known_color()); } void test_method_(create_from_name_medium_turquoise) { color c = color::from_name("medium_turquoise"); assert::are_equal(color::from_name("medium_turquoise"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x48, c.r()); assert::are_equal(0xD1, c.g()); assert::are_equal(0xCC, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("medium_turquoise", c.name()); assert::are_equal("color [medium_turquoise]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF48D1CCU, c.to_argb()); assert::are_equal(known_color::medium_turquoise, c.to_known_color()); } void test_method_(create_from_name_medium_violet_red) { color c = color::from_name("medium_violet_red"); assert::are_equal(color::from_name("medium_violet_red"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xC7, c.r()); assert::are_equal(0x15, c.g()); assert::are_equal(0x85, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("medium_violet_red", c.name()); assert::are_equal("color [medium_violet_red]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFC71585U, c.to_argb()); assert::are_equal(known_color::medium_violet_red, c.to_known_color()); } void test_method_(create_from_name_midnight_blue) { color c = color::from_name("midnight_blue"); assert::are_equal(color::from_name("midnight_blue"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x19, c.r()); assert::are_equal(0x19, c.g()); assert::are_equal(0x70, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("midnight_blue", c.name()); assert::are_equal("color [midnight_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF191970U, c.to_argb()); assert::are_equal(known_color::midnight_blue, c.to_known_color()); } void test_method_(create_from_name_mint_cream) { color c = color::from_name("mint_cream"); assert::are_equal(color::from_name("mint_cream"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xF5, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0xFA, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("mint_cream", c.name()); assert::are_equal("color [mint_cream]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFF5FFFAU, c.to_argb()); assert::are_equal(known_color::mint_cream, c.to_known_color()); } void test_method_(create_from_name_misty_rose) { color c = color::from_name("misty_rose"); assert::are_equal(color::from_name("misty_rose"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xE4, c.g()); assert::are_equal(0xE1, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("misty_rose", c.name()); assert::are_equal("color [misty_rose]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFE4E1U, c.to_argb()); assert::are_equal(known_color::misty_rose, c.to_known_color()); } void test_method_(create_from_name_moccasin) { color c = color::from_name("moccasin"); assert::are_equal(color::from_name("moccasin"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xE4, c.g()); assert::are_equal(0xB5, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("moccasin", c.name()); assert::are_equal("color [moccasin]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFE4B5U, c.to_argb()); assert::are_equal(known_color::moccasin, c.to_known_color()); } void test_method_(create_from_name_navajo_white) { color c = color::from_name("navajo_white"); assert::are_equal(color::from_name("navajo_white"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xDE, c.g()); assert::are_equal(0xAD, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("navajo_white", c.name()); assert::are_equal("color [navajo_white]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFDEADU, c.to_argb()); assert::are_equal(known_color::navajo_white, c.to_known_color()); } void test_method_(create_from_name_navy) { color c = color::from_name("navy"); assert::are_equal(color::from_name("navy"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0x80, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("navy", c.name()); assert::are_equal("color [navy]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF000080U, c.to_argb()); assert::are_equal(known_color::navy, c.to_known_color()); } void test_method_(create_from_name_old_lace) { color c = color::from_name("old_lace"); assert::are_equal(color::from_name("old_lace"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFD, c.r()); assert::are_equal(0xF5, c.g()); assert::are_equal(0xE6, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("old_lace", c.name()); assert::are_equal("color [old_lace]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFDF5E6U, c.to_argb()); assert::are_equal(known_color::old_lace, c.to_known_color()); } void test_method_(create_from_name_olive) { color c = color::from_name("olive"); assert::are_equal(color::from_name("olive"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x80, c.r()); assert::are_equal(0x80, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("olive", c.name()); assert::are_equal("color [olive]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF808000U, c.to_argb()); assert::are_equal(known_color::olive, c.to_known_color()); } void test_method_(create_from_name_olive_drab) { color c = color::from_name("olive_drab"); assert::are_equal(color::from_name("olive_drab"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x6B, c.r()); assert::are_equal(0x8E, c.g()); assert::are_equal(0x23, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("olive_drab", c.name()); assert::are_equal("color [olive_drab]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF6B8E23U, c.to_argb()); assert::are_equal(known_color::olive_drab, c.to_known_color()); } void test_method_(create_from_name_orange) { color c = color::from_name("orange"); assert::are_equal(color::from_name("orange"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xA5, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("orange", c.name()); assert::are_equal("color [orange]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFA500U, c.to_argb()); assert::are_equal(known_color::orange, c.to_known_color()); } void test_method_(create_from_name_orange_red) { color c = color::from_name("orange_red"); assert::are_equal(color::from_name("orange_red"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0x45, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("orange_red", c.name()); assert::are_equal("color [orange_red]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFF4500U, c.to_argb()); assert::are_equal(known_color::orange_red, c.to_known_color()); } void test_method_(create_from_name_orchid) { color c = color::from_name("orchid"); assert::are_equal(color::from_name("orchid"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xDA, c.r()); assert::are_equal(0x70, c.g()); assert::are_equal(0xD6, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("orchid", c.name()); assert::are_equal("color [orchid]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFDA70D6U, c.to_argb()); assert::are_equal(known_color::orchid, c.to_known_color()); } void test_method_(create_from_name_pale_goldenrod) { color c = color::from_name("pale_goldenrod"); assert::are_equal(color::from_name("pale_goldenrod"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xEE, c.r()); assert::are_equal(0xE8, c.g()); assert::are_equal(0xAA, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("pale_goldenrod", c.name()); assert::are_equal("color [pale_goldenrod]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFEEE8AAU, c.to_argb()); assert::are_equal(known_color::pale_goldenrod, c.to_known_color()); } void test_method_(create_from_name_pale_green) { color c = color::from_name("pale_green"); assert::are_equal(color::from_name("pale_green"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x98, c.r()); assert::are_equal(0xFB, c.g()); assert::are_equal(0x98, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("pale_green", c.name()); assert::are_equal("color [pale_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF98FB98U, c.to_argb()); assert::are_equal(known_color::pale_green, c.to_known_color()); } void test_method_(create_from_name_pale_turquoise) { color c = color::from_name("pale_turquoise"); assert::are_equal(color::from_name("pale_turquoise"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xAF, c.r()); assert::are_equal(0xEE, c.g()); assert::are_equal(0xEE, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("pale_turquoise", c.name()); assert::are_equal("color [pale_turquoise]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFAFEEEEU, c.to_argb()); assert::are_equal(known_color::pale_turquoise, c.to_known_color()); } void test_method_(create_from_name_pale_violet_red) { color c = color::from_name("pale_violet_red"); assert::are_equal(color::from_name("pale_violet_red"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xDB, c.r()); assert::are_equal(0x70, c.g()); assert::are_equal(0x93, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("pale_violet_red", c.name()); assert::are_equal("color [pale_violet_red]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFDB7093U, c.to_argb()); assert::are_equal(known_color::pale_violet_red, c.to_known_color()); } void test_method_(create_from_name_papaya_whip) { color c = color::from_name("papaya_whip"); assert::are_equal(color::from_name("papaya_whip"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xEF, c.g()); assert::are_equal(0xD5, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("papaya_whip", c.name()); assert::are_equal("color [papaya_whip]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFEFD5U, c.to_argb()); assert::are_equal(known_color::papaya_whip, c.to_known_color()); } void test_method_(create_from_name_peach_puff) { color c = color::from_name("peach_puff"); assert::are_equal(color::from_name("peach_puff"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xDA, c.g()); assert::are_equal(0xB9, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("peach_puff", c.name()); assert::are_equal("color [peach_puff]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFDAB9U, c.to_argb()); assert::are_equal(known_color::peach_puff, c.to_known_color()); } void test_method_(create_from_name_peru) { color c = color::from_name("peru"); assert::are_equal(color::from_name("peru"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xCD, c.r()); assert::are_equal(0x85, c.g()); assert::are_equal(0x3F, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("peru", c.name()); assert::are_equal("color [peru]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFCD853FU, c.to_argb()); assert::are_equal(known_color::peru, c.to_known_color()); } void test_method_(create_from_name_pink) { color c = color::from_name("pink"); assert::are_equal(color::from_name("pink"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xC0, c.g()); assert::are_equal(0xCB, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("pink", c.name()); assert::are_equal("color [pink]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFC0CBU, c.to_argb()); assert::are_equal(known_color::pink, c.to_known_color()); } void test_method_(create_from_name_plum) { color c = color::from_name("plum"); assert::are_equal(color::from_name("plum"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xDD, c.r()); assert::are_equal(0xA0, c.g()); assert::are_equal(0xDD, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("plum", c.name()); assert::are_equal("color [plum]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFDDA0DDU, c.to_argb()); assert::are_equal(known_color::plum, c.to_known_color()); } void test_method_(create_from_name_powder_blue) { color c = color::from_name("powder_blue"); assert::are_equal(color::from_name("powder_blue"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xB0, c.r()); assert::are_equal(0xE0, c.g()); assert::are_equal(0xE6, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("powder_blue", c.name()); assert::are_equal("color [powder_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFB0E0E6U, c.to_argb()); assert::are_equal(known_color::powder_blue, c.to_known_color()); } void test_method_(create_from_name_purple) { color c = color::from_name("purple"); assert::are_equal(color::from_name("purple"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x80, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0x80, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("purple", c.name()); assert::are_equal("color [purple]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF800080U, c.to_argb()); assert::are_equal(known_color::purple, c.to_known_color()); } void test_method_(create_from_name_rebecca_purple) { color c = color::from_name("rebecca_purple"); assert::are_equal(color::from_name("rebecca_purple"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x66, c.r()); assert::are_equal(0x33, c.g()); assert::are_equal(0x99, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("rebecca_purple", c.name()); assert::are_equal("color [rebecca_purple]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF663399U, c.to_argb()); assert::are_equal(known_color::rebecca_purple, c.to_known_color()); } void test_method_(create_from_name_red) { color c = color::from_name("red"); assert::are_equal(color::from_name("red"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0x00, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("red", c.name()); assert::are_equal("color [red]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFF0000U, c.to_argb()); assert::are_equal(known_color::red, c.to_known_color()); } void test_method_(create_from_name_rosy_brown) { color c = color::from_name("rosy_brown"); assert::are_equal(color::from_name("rosy_brown"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xBC, c.r()); assert::are_equal(0x8F, c.g()); assert::are_equal(0x8F, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("rosy_brown", c.name()); assert::are_equal("color [rosy_brown]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFBC8F8FU, c.to_argb()); assert::are_equal(known_color::rosy_brown, c.to_known_color()); } void test_method_(create_from_name_royal_blue) { color c = color::from_name("royal_blue"); assert::are_equal(color::from_name("royal_blue"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x41, c.r()); assert::are_equal(0x69, c.g()); assert::are_equal(0xE1, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("royal_blue", c.name()); assert::are_equal("color [royal_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF4169E1U, c.to_argb()); assert::are_equal(known_color::royal_blue, c.to_known_color()); } void test_method_(create_from_name_saddle_brown) { color c = color::from_name("saddle_brown"); assert::are_equal(color::from_name("saddle_brown"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x8B, c.r()); assert::are_equal(0x45, c.g()); assert::are_equal(0x13, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("saddle_brown", c.name()); assert::are_equal("color [saddle_brown]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF8B4513U, c.to_argb()); assert::are_equal(known_color::saddle_brown, c.to_known_color()); } void test_method_(create_from_name_salmon) { color c = color::from_name("salmon"); assert::are_equal(color::from_name("salmon"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFA, c.r()); assert::are_equal(0x80, c.g()); assert::are_equal(0x72, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("salmon", c.name()); assert::are_equal("color [salmon]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFA8072U, c.to_argb()); assert::are_equal(known_color::salmon, c.to_known_color()); } void test_method_(create_from_name_sandy_brown) { color c = color::from_name("sandy_brown"); assert::are_equal(color::from_name("sandy_brown"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xF4, c.r()); assert::are_equal(0xA4, c.g()); assert::are_equal(0x60, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("sandy_brown", c.name()); assert::are_equal("color [sandy_brown]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFF4A460U, c.to_argb()); assert::are_equal(known_color::sandy_brown, c.to_known_color()); } void test_method_(create_from_name_sea_green) { color c = color::from_name("sea_green"); assert::are_equal(color::from_name("sea_green"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x2E, c.r()); assert::are_equal(0x8B, c.g()); assert::are_equal(0x57, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("sea_green", c.name()); assert::are_equal("color [sea_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF2E8B57U, c.to_argb()); assert::are_equal(known_color::sea_green, c.to_known_color()); } void test_method_(create_from_name_sea_shell) { color c = color::from_name("sea_shell"); assert::are_equal(color::from_name("sea_shell"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xF5, c.g()); assert::are_equal(0xEE, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("sea_shell", c.name()); assert::are_equal("color [sea_shell]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFF5EEU, c.to_argb()); assert::are_equal(known_color::sea_shell, c.to_known_color()); } void test_method_(create_from_name_sienna) { color c = color::from_name("sienna"); assert::are_equal(color::from_name("sienna"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xA0, c.r()); assert::are_equal(0x52, c.g()); assert::are_equal(0x2D, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("sienna", c.name()); assert::are_equal("color [sienna]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFA0522DU, c.to_argb()); assert::are_equal(known_color::sienna, c.to_known_color()); } void test_method_(create_from_name_silver) { color c = color::from_name("silver"); assert::are_equal(color::from_name("silver"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xC0, c.r()); assert::are_equal(0xC0, c.g()); assert::are_equal(0xC0, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("silver", c.name()); assert::are_equal("color [silver]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFC0C0C0U, c.to_argb()); assert::are_equal(known_color::silver, c.to_known_color()); } void test_method_(create_from_name_sky_blue) { color c = color::from_name("sky_blue"); assert::are_equal(color::from_name("sky_blue"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x87, c.r()); assert::are_equal(0xCE, c.g()); assert::are_equal(0xEB, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("sky_blue", c.name()); assert::are_equal("color [sky_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF87CEEBU, c.to_argb()); assert::are_equal(known_color::sky_blue, c.to_known_color()); } void test_method_(create_from_name_slate_blue) { color c = color::from_name("slate_blue"); assert::are_equal(color::from_name("slate_blue"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x6A, c.r()); assert::are_equal(0x5A, c.g()); assert::are_equal(0xCD, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("slate_blue", c.name()); assert::are_equal("color [slate_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF6A5ACDU, c.to_argb()); assert::are_equal(known_color::slate_blue, c.to_known_color()); } void test_method_(create_from_name_slate_gray) { color c = color::from_name("slate_gray"); assert::are_equal(color::from_name("slate_gray"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x70, c.r()); assert::are_equal(0x80, c.g()); assert::are_equal(0x90, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("slate_gray", c.name()); assert::are_equal("color [slate_gray]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF708090U, c.to_argb()); assert::are_equal(known_color::slate_gray, c.to_known_color()); } void test_method_(create_from_name_snow) { color c = color::from_name("snow"); assert::are_equal(color::from_name("snow"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xFA, c.g()); assert::are_equal(0xFA, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("snow", c.name()); assert::are_equal("color [snow]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFFAFAU, c.to_argb()); assert::are_equal(known_color::snow, c.to_known_color()); } void test_method_(create_from_name_spring_green) { color c = color::from_name("spring_green"); assert::are_equal(color::from_name("spring_green"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0x7F, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("spring_green", c.name()); assert::are_equal("color [spring_green]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF00FF7FU, c.to_argb()); assert::are_equal(known_color::spring_green, c.to_known_color()); } void test_method_(create_from_name_steel_blue) { color c = color::from_name("steel_blue"); assert::are_equal(color::from_name("steel_blue"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x46, c.r()); assert::are_equal(0x82, c.g()); assert::are_equal(0xB4, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("steel_blue", c.name()); assert::are_equal("color [steel_blue]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF4682B4U, c.to_argb()); assert::are_equal(known_color::steel_blue, c.to_known_color()); } void test_method_(create_from_name_tan) { color c = color::from_name("tan"); assert::are_equal(color::from_name("tan"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xD2, c.r()); assert::are_equal(0xB4, c.g()); assert::are_equal(0x8C, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("tan", c.name()); assert::are_equal("color [tan]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFD2B48CU, c.to_argb()); assert::are_equal(known_color::tan, c.to_known_color()); } void test_method_(create_from_name_teal) { color c = color::from_name("teal"); assert::are_equal(color::from_name("teal"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x00, c.r()); assert::are_equal(0x80, c.g()); assert::are_equal(0x80, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("teal", c.name()); assert::are_equal("color [teal]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF008080U, c.to_argb()); assert::are_equal(known_color::teal, c.to_known_color()); } void test_method_(create_from_name_thistle) { color c = color::from_name("thistle"); assert::are_equal(color::from_name("thistle"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xD8, c.r()); assert::are_equal(0xBF, c.g()); assert::are_equal(0xD8, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("thistle", c.name()); assert::are_equal("color [thistle]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFD8BFD8U, c.to_argb()); assert::are_equal(known_color::thistle, c.to_known_color()); } void test_method_(create_from_name_tomato) { color c = color::from_name("tomato"); assert::are_equal(color::from_name("tomato"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0x63, c.g()); assert::are_equal(0x47, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("tomato", c.name()); assert::are_equal("color [tomato]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFF6347U, c.to_argb()); assert::are_equal(known_color::tomato, c.to_known_color()); } void test_method_(create_from_name_turquoise) { color c = color::from_name("turquoise"); assert::are_equal(color::from_name("turquoise"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0x40, c.r()); assert::are_equal(0xE0, c.g()); assert::are_equal(0xD0, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("turquoise", c.name()); assert::are_equal("color [turquoise]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFF40E0D0U, c.to_argb()); assert::are_equal(known_color::turquoise, c.to_known_color()); } void test_method_(create_from_name_violet) { color c = color::from_name("violet"); assert::are_equal(color::from_name("violet"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xEE, c.r()); assert::are_equal(0x82, c.g()); assert::are_equal(0xEE, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("violet", c.name()); assert::are_equal("color [violet]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFEE82EEU, c.to_argb()); assert::are_equal(known_color::violet, c.to_known_color()); } void test_method_(create_from_name_wheat) { color c = color::from_name("wheat"); assert::are_equal(color::from_name("wheat"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xF5, c.r()); assert::are_equal(0xDE, c.g()); assert::are_equal(0xB3, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("wheat", c.name()); assert::are_equal("color [wheat]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFF5DEB3U, c.to_argb()); assert::are_equal(known_color::wheat, c.to_known_color()); } void test_method_(create_from_name_white) { color c = color::from_name("white"); assert::are_equal(color::from_name("white"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0xFF, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("white", c.name()); assert::are_equal("color [white]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFFFFFU, c.to_argb()); assert::are_equal(known_color::white, c.to_known_color()); } void test_method_(create_from_name_white_smoke) { color c = color::from_name("white_smoke"); assert::are_equal(color::from_name("white_smoke"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xF5, c.r()); assert::are_equal(0xF5, c.g()); assert::are_equal(0xF5, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("white_smoke", c.name()); assert::are_equal("color [white_smoke]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFF5F5F5U, c.to_argb()); assert::are_equal(known_color::white_smoke, c.to_known_color()); } void test_method_(create_from_name_yellow) { color c = color::from_name("yellow"); assert::are_equal(color::from_name("yellow"), c); assert::are_not_equal(color(), c); assert::are_not_equal(color::empty, c); assert::are_equal(0xFF, c.a()); assert::are_equal(0xFF, c.r()); assert::are_equal(0xFF, c.g()); assert::are_equal(0x00, c.b()); assert::are_equal(0, c.handle()); assert::are_equal("yellow", c.name()); assert::are_equal("color [yellow]", c.to_string()); assert::is_false(c.is_empty()); assert::is_true(c.is_known_color()); assert::is_false(c.is_system_color()); assert::is_true(c.is_named_color()); assert::are_equal(0xFFFFFF00U, c.to_argb()); assert::are_equal(known_color::yellow, c.to_known_color()); } }; }
36.195243
91
0.615701
ExternalRepositories
4076f1eeea7219a4ee3230d0d0acf26ff0ec34b5
2,762
cpp
C++
src/cpp/JNI/org_jsfml_graphics_Image.cpp
comqdhb/JSFML
c1397d0ed1ac1c334e33a346b17b59ead2dfb862
[ "Zlib" ]
41
2015-01-10T16:39:36.000Z
2022-02-03T12:06:12.000Z
src/cpp/JNI/org_jsfml_graphics_Image.cpp
comqdhb/JSFML
c1397d0ed1ac1c334e33a346b17b59ead2dfb862
[ "Zlib" ]
22
2015-01-26T01:36:16.000Z
2019-01-05T07:31:49.000Z
src/cpp/JNI/org_jsfml_graphics_Image.cpp
comqdhb/JSFML
c1397d0ed1ac1c334e33a346b17b59ead2dfb862
[ "Zlib" ]
38
2015-03-12T00:55:51.000Z
2021-11-08T22:38:43.000Z
#include <JSFML/JNI/org_jsfml_graphics_Image.h> #include <JSFML/Intercom/Intercom.hpp> #include <JSFML/Intercom/NativeObject.hpp> #include <SFML/Graphics/Image.hpp> /* * Class: org_jsfml_graphics_Image * Method: nativeCreate * Signature: ()J */ JNIEXPORT jlong JNICALL Java_org_jsfml_graphics_Image_nativeCreate (JNIEnv *env, jobject obj) { return (jlong)new sf::Image(); } /* * Class: org_jsfml_graphics_Image * Method: nativeDelete * Signature: ()V */ JNIEXPORT void JNICALL Java_org_jsfml_graphics_Image_nativeDelete (JNIEnv *env, jobject obj) { delete THIS(sf::Image); } /* * Class: org_jsfml_graphics_Image * Method: nativeLoadFromMemory * Signature: ([B)Z */ JNIEXPORT jboolean JNICALL Java_org_jsfml_graphics_Image_nativeLoadFromMemory (JNIEnv *env, jobject obj, jbyteArray arr) { std::size_t n = (std::size_t)env->GetArrayLength(arr); jbyte* mem = env->GetByteArrayElements(arr, 0); jboolean result = THIS(sf::Image)->loadFromMemory(mem, n); env->ReleaseByteArrayElements(arr, mem, JNI_ABORT); return result; } /* * Class: org_jsfml_graphics_Image * Method: nativeSaveToFile * Signature: (Ljava/lang/String;)Z */ JNIEXPORT jboolean JNICALL Java_org_jsfml_graphics_Image_nativeSaveToFile (JNIEnv *env, jobject obj, jstring fileName) { const char *utf8 = env->GetStringUTFChars(fileName, NULL); jboolean result = THIS(sf::Image)->saveToFile(std::string(utf8)); env->ReleaseStringUTFChars(fileName, utf8); return result; } /* * Class: org_jsfml_graphics_Image * Method: nativeGetSize * Signature: ()J */ JNIEXPORT jlong JNICALL Java_org_jsfml_graphics_Image_nativeGetSize (JNIEnv *env, jobject obj) { return JSFML::Intercom::encodeVector2u(THIS(sf::Image)->getSize()); } /* * Class: org_jsfml_graphics_Image * Method: nativeSync * Signature: (IILjava/nio/Buffer;)V */ JNIEXPORT void JNICALL Java_org_jsfml_graphics_Image_nativeSync (JNIEnv *env, jobject obj, jint width, jint height, jobject buffer) { sf::Uint8 *dst = (sf::Uint8*)env->GetDirectBufferAddress(buffer); const sf::Uint8 *src = THIS(sf::Image)->getPixelsPtr(); int x = width * height * 4; while(x) { *dst++ = *src++; x--; } } /* * Class: org_jsfml_graphics_Image * Method: nativeCommit * Signature: (IILjava/nio/Buffer;)V */ JNIEXPORT void JNICALL Java_org_jsfml_graphics_Image_nativeCommit (JNIEnv *env, jobject obj, jint width, jint height, jobject buffer) { if(width == 0 || height == 0) { THIS(sf::Image)->create(0, 0); } else { const sf::Uint8 *pixels = (const sf::Uint8*)env->GetDirectBufferAddress(buffer); THIS(sf::Image)->create(width, height, pixels); } }
27.89899
122
0.695148
comqdhb
407917d32becd9a35deb6c6f126c78b4c698fda3
553
cpp
C++
Session_04/00_FlowerClassVector/src/ofApp.cpp
SAIC-ATS/ARTTECH3135
179805d373601ac92dcdbb51ddc4925fc65f7c22
[ "MIT" ]
26
2015-09-23T12:31:16.000Z
2020-12-14T03:19:19.000Z
Session_04/00_FlowerClassVector/src/ofApp.cpp
SAIC-ATS/ARTTECH3135
179805d373601ac92dcdbb51ddc4925fc65f7c22
[ "MIT" ]
2
2017-07-05T18:14:52.000Z
2017-10-31T00:04:13.000Z
Session_04/00_FlowerClassVector/src/ofApp.cpp
SAIC-ATS/ARTTECH3135
179805d373601ac92dcdbb51ddc4925fc65f7c22
[ "MIT" ]
37
2015-09-19T22:10:32.000Z
2019-12-07T19:35:55.000Z
#include "ofApp.h" void ofApp::setup() { ofBackground(80); ofSetCircleResolution(64); // flowers = { Flower(), Flower(), Flower() }; } void ofApp::update() { for (std::size_t i = 0; i < flowers.size(); i++) { flowers[i].update(); } } void ofApp::draw() { for (std::size_t i = 0; i < flowers.size(); i++) { flowers[i].draw(); } } void ofApp::mousePressed(int x, int y, int button) { Flower aFlower; aFlower.x = x; aFlower.y = y; flowers.push_back(aFlower); }
13.487805
52
0.522604
SAIC-ATS
407c33a7706e2a2f32b2c4deff70000c1f365e79
1,848
cpp
C++
activemq-cpp/src/main/activemq/transport/inactivity/WriteChecker.cpp
novomatic-tech/activemq-cpp
d6f76ede90d21b7ee2f0b5d4648e440e66d63003
[ "Apache-2.0" ]
87
2015-03-02T17:58:20.000Z
2022-02-11T02:52:52.000Z
activemq-cpp/src/main/activemq/transport/inactivity/WriteChecker.cpp
korena/activemq-cpp
e4c56ee4fec75c3284b9167a7215e2d80a9a4dc4
[ "Apache-2.0" ]
3
2017-05-10T13:16:08.000Z
2019-01-23T20:21:53.000Z
activemq-cpp/src/main/activemq/transport/inactivity/WriteChecker.cpp
korena/activemq-cpp
e4c56ee4fec75c3284b9167a7215e2d80a9a4dc4
[ "Apache-2.0" ]
71
2015-04-28T06:04:04.000Z
2022-03-15T13:34:06.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 "WriteChecker.h" #include <activemq/transport/inactivity/InactivityMonitor.h> #include <decaf/lang/System.h> #include <decaf/lang/exceptions/NullPointerException.h> using namespace activemq; using namespace activemq::transport; using namespace activemq::transport::inactivity; using namespace decaf; using namespace decaf::util; using namespace decaf::lang; using namespace decaf::lang::exceptions; //////////////////////////////////////////////////////////////////////////////// WriteChecker::WriteChecker(InactivityMonitor* parent) : TimerTask(), parent(parent), lastRunTime(0) { if (this->parent == NULL) { throw NullPointerException(__FILE__, __LINE__, "WriteChecker created with NULL parent."); } } //////////////////////////////////////////////////////////////////////////////// WriteChecker::~WriteChecker() {} //////////////////////////////////////////////////////////////////////////////// void WriteChecker::run() { this->lastRunTime = System::currentTimeMillis(); this->parent->writeCheck(); }
37.714286
101
0.655844
novomatic-tech
407c72000ab7cfb5d427ccb9cf9a401af39c7f0d
4,002
cpp
C++
src/connection.cpp
tmplt/libircppclient
99121502564b9085b7ce81367ac73e933213706c
[ "MIT" ]
1
2020-11-12T22:57:20.000Z
2020-11-12T22:57:20.000Z
src/connection.cpp
tmplt/libircppclient
99121502564b9085b7ce81367ac73e933213706c
[ "MIT" ]
null
null
null
src/connection.cpp
tmplt/libircppclient
99121502564b9085b7ce81367ac73e933213706c
[ "MIT" ]
null
null
null
#include "connection.hpp" #include <boost/bind.hpp> #include <thread> #include <string> #include <iostream> namespace irc { connection::connection(const bool use_ssl) : socket_(io_service_), use_ssl_(use_ssl), ctx_(ssl::context::sslv23), ssl_socket_(io_service_, ctx_) { if (use_ssl_) { ctx_.set_default_verify_paths(ec_); if (ec_) throw ec_; } } boost::system::error_code connection::verify_cert() { boost::system::error_code ec; ssl_socket_.set_verify_mode(ssl::verify_peer | ssl::verify_fail_if_no_peer_cert); ssl_socket_.set_verify_callback(ssl::rfc2818_verification(addr_), ec); return ec; } boost::system::error_code connection::shake_hands() { boost::system::error_code ec; ssl_socket_.handshake(ssl_socket::client, ec); return ec; } void connection::connect() { using boost::asio::ip::tcp; tcp::resolver r(io_service_); tcp::resolver::query query(addr_, port_); /* default error. */ ec_ = boost::asio::error::host_not_found; if (use_ssl_) { boost::asio::connect(ssl_socket_.lowest_layer(), r.resolve(query), ec_); if (!ec_) { ec_ = verify_cert(); if (!ec_) ec_ = shake_hands(); } } else { boost::asio::connect(socket_.lowest_layer(), r.resolve(query), ec_); } if (ec_) throw ec_; } template<class S> void connection::read_some(S &s) { s.async_read_some(boost::asio::buffer(read_buffer_), boost::bind(&connection::read_handler, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred())); } void connection::read_handler(const boost::system::error_code &ec, std::size_t length) { using std::experimental::string_view; if (ec) { /* Unable to read from server. */ throw ec; } else { const string_view content(read_buffer_.data(), length); std::stringstream iss(content.data()); std::string command; iss >> command; if (command == "PING") pong(); else ext_read_handler_(content); if (use_ssl_) read_some(ssl_socket_); else read_some(socket_); } } void connection::run() { std::thread ping_thread(ping_handler_); if (use_ssl_) read_some(ssl_socket_); else read_some(socket_); boost::system::error_code ec; io_service_.run(ec); /* * Remain at this point until we * do not need the connection any more. */ ping_thread.join(); if (ec) throw ec; } void connection::ping() { using namespace std::literals; while (do_ping) { /* * Interval decided by mimicing WeeChat. * The standard does not seem to explicitly * state a ping inverval. Is it the server's * decision? */ std::this_thread::sleep_for(1min + 30s); write("PING " + addr_); } } void connection::pong() { write("PONG :" + addr_); } void connection::write(std::string content) { /* * The IRC protocol specifies that all messages sent to the server * must be terminated with CR-LF (Carriage Return - Line Feed) */ content.append("\r\n"); #ifdef DEBUG std::cout << "[debug] writing: " << content; #endif if (use_ssl_) boost::asio::write(ssl_socket_, boost::asio::buffer(content), ec_); else boost::asio::write(socket_.next_layer(), boost::asio::buffer(content), ec_); if (ec_) throw ec_; } void connection::stop() { /* * For a proper shutdown, we first need to terminate * the ping thread, which might have to be done while * it's in nanosleep. After that, we are free to stop * the io_service. */ if (use_ssl_) ssl_socket_.lowest_layer().close(); else socket_.lowest_layer().close(); io_service_.stop(); } /* ns irc */ }
21.516129
86
0.601949
tmplt
407c7ad3c3a83f0c135ad2ebe28d5cba02b3015f
2,667
cpp
C++
app/android/jni/tango-gl/camera.cpp
Riotpiaole/rtabmap
2b8b36db2ed7a08361dcffc9e2da3070b92a3883
[ "BSD-3-Clause" ]
null
null
null
app/android/jni/tango-gl/camera.cpp
Riotpiaole/rtabmap
2b8b36db2ed7a08361dcffc9e2da3070b92a3883
[ "BSD-3-Clause" ]
null
null
null
app/android/jni/tango-gl/camera.cpp
Riotpiaole/rtabmap
2b8b36db2ed7a08361dcffc9e2da3070b92a3883
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "tango-gl/camera.h" #include "tango-gl/util.h" namespace tango_gl { Camera::Camera() { field_of_view_ = 45.0f * DEGREE_2_RADIANS; aspect_ratio_ = 4.0f / 3.0f; width_ = 800.0f; height_ = 600.0f; near_clip_plane_ = 0.2f; far_clip_plane_ = 1000.0f; ortho_ = false; orthoScale_ = 2.0f; orthoCropFactor_ = -1.0f; } glm::mat4 Camera::GetViewMatrix() { return glm::inverse(GetTransformationMatrix()); } glm::mat4 Camera::GetProjectionMatrix() { if(ortho_) { return glm::ortho(-orthoScale_*aspect_ratio_, orthoScale_*aspect_ratio_, -orthoScale_, orthoScale_, orthoScale_ + orthoCropFactor_, far_clip_plane_); } return glm::perspective(field_of_view_, aspect_ratio_, near_clip_plane_, far_clip_plane_); } void Camera::SetWindowSize(float width, float height) { width_ = width; height_ = height; aspect_ratio_ = width/height; } void Camera::SetFieldOfView(float fov) { field_of_view_ = fov * DEGREE_2_RADIANS; } void Camera::SetNearFarClipPlanes(const float near, const float far) { near_clip_plane_ = near; far_clip_plane_ = far; } Camera::~Camera() { } glm::mat4 Camera::ProjectionMatrixForCameraIntrinsics(float width, float height, float fx, float fy, float cx, float cy, float near, float far) { const float xscale = near / fx; const float yscale = near / fy; const float xoffset = (cx - (width / 2.0)) * xscale; // Color camera's coordinates has y pointing downwards so we negate this term. const float yoffset = -(cy - (height / 2.0)) * yscale; return glm::frustum(xscale * -width / 2.0f - xoffset, xscale * width / 2.0f - xoffset, yscale * -height / 2.0f - yoffset, yscale * height / 2.0f - yoffset, near, far); } } // namespace tango_gl
31.75
152
0.625422
Riotpiaole
407cb6a554f15952175ad3d696ea28e709f832f0
1,510
cpp
C++
Codechef/STRPALIN.cpp
JanaSabuj/cpmaster
d943780c7ca4badbefbce2d300848343c4032650
[ "MIT" ]
1
2020-11-29T08:36:38.000Z
2020-11-29T08:36:38.000Z
Codechef/STRPALIN.cpp
Sahu49/CompetitiveProgramming
adf11a546f81878ad2975926219af84deb3414e8
[ "MIT" ]
null
null
null
Codechef/STRPALIN.cpp
Sahu49/CompetitiveProgramming
adf11a546f81878ad2975926219af84deb3414e8
[ "MIT" ]
null
null
null
/*--------------------------"SABUJ-JANA"------"JADAVPUR UNIVERSITY"--------*/ /*-------------------------------@greenindia-----------------------------------*/ /*---------------------- Magic. Do not touch.-----------------------------*/ /*------------------------------God is Great/\---------------------------------*/ #include <bits/stdc++.h> using namespace std; #define crap ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) //cout<<fixed<<showpoint<<setprecision(12)<<ans<<endl; #define dbg(x) cerr << #x << " = " << x << endl #define endl "\n" #define int long long int #define double long double #define pb push_back #define mp make_pair #define PI acos(-1) const int INF = 1e9 + 5; //billion #define MAX 100007 string alpha = "abcdefghijklmnopqrstuvwxyz"; //power (a^b)%m // int power(int a, int b, int m) {int ans = 1; while (b) {if (b & 1)ans = (ans * a) % m; b /= 2; a = (a * a) % m;} return ans;} signed main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); freopen("error.txt", "w", stderr); crap; int t; cin >> t; while (t--) { string a, b; cin >> a >> b; int f1[26] = {0}; int f2[26] = {0}; for (int i = 0; i < a.length(); i++) { f1[a[i] - 'a'] = 1; } for (int i = 0; i < b.length(); i++) { f2[b[i] - 'a'] = 1; } bool found=false; for(int i=0; i<26; i++){ if(f1[i]==f2[i] and f1[i]>0 and f2[i]>0){ found=true; break; } } if(found) cout<<"Yes"<<endl; else cout<<"No"<<endl; } return 0; }
22.537313
128
0.476821
JanaSabuj
407cf629fcf94f07c138846cc23266e7741e9941
7,987
cpp
C++
src/eval.cpp
andrew-pa/bicycle
03a7bd1a5d08eb43cafcb6cfe4d38b3a6841895c
[ "MIT" ]
2
2020-06-12T20:13:17.000Z
2020-12-22T05:01:25.000Z
src/eval.cpp
andrew-pa/bicycle
03a7bd1a5d08eb43cafcb6cfe4d38b3a6841895c
[ "MIT" ]
null
null
null
src/eval.cpp
andrew-pa/bicycle
03a7bd1a5d08eb43cafcb6cfe4d38b3a6841895c
[ "MIT" ]
null
null
null
#include "eval.h" void eval::analyzer::visit(ast::seq_stmt* s) { s->first->visit(this); if (s->second != nullptr) s->second->visit(this); } void eval::analyzer::visit(ast::block_stmt* s) { if (s->body == nullptr) return; instrs.push_back(std::make_shared<enter_scope_instr>()); s->body->visit(this); instrs.push_back(std::make_shared<exit_scope_instr>()); } void eval::analyzer::visit(ast::let_stmt* s) { s->value->visit(this); instrs.push_back(std::make_shared<bind_instr>(ids->at(s->identifer))); } void eval::analyzer::visit(ast::expr_stmt* s) { s->expr->visit(this); instrs.push_back(std::make_shared<discard_instr>()); } void eval::analyzer::visit(ast::if_stmt* s) { // compute condition // if true // stuff // go to end // if false // other stuff // end s->condition->visit(this); auto true_b_mark = new_marker(); auto false_b_mark = new_marker(); instrs.push_back(std::make_shared<if_instr>(true_b_mark, false_b_mark)); instrs.push_back(std::make_shared<marker_instr>(true_b_mark)); s->if_true->visit(this); if (s->if_false != nullptr) { auto end_mark = new_marker(); instrs.push_back(std::make_shared<jump_to_marker_instr>(end_mark)); instrs.push_back(std::make_shared<marker_instr>(false_b_mark)); s->if_false->visit(this); instrs.push_back(std::make_shared<marker_instr>(end_mark)); } else { instrs.push_back(std::make_shared<marker_instr>(false_b_mark)); } } void eval::analyzer::visit(ast::continue_stmt* s) { auto start = 0; if (s->name.has_value()) { for (int i = loop_marker_stack.size() - 1; i >= 0; --i) { auto loop = loop_marker_stack[i]; if (std::get<0>(loop).has_value() && std::get<0>(loop).value() == s->name.value()) { start = std::get<1>(loop); break; } } } else { auto loop = loop_marker_stack[loop_marker_stack.size() - 1]; start = std::get<1>(loop); } instrs.push_back(std::make_shared<jump_instr>(start)); } void eval::analyzer::visit(ast::break_stmt* s) { auto end_mark = 0; if (s->name.has_value()) { for (int i = loop_marker_stack.size() - 1; i >= 0; --i) { auto loop = loop_marker_stack[i]; if (std::get<0>(loop).has_value() && std::get<0>(loop).value() == s->name.value()) { end_mark = std::get<2>(loop); break; } } } else { auto loop = loop_marker_stack[loop_marker_stack.size() - 1]; end_mark = std::get<2>(loop); } instrs.push_back(std::make_shared<jump_to_marker_instr>(end_mark)); } void eval::analyzer::visit(ast::loop_stmt* s) { auto start = instrs.size(); auto endm = new_marker(); loop_marker_stack.push_back(std::tuple(s->name, start, endm)); s->body->visit(this); instrs.push_back(std::make_shared<jump_instr>(start)); instrs.push_back(std::make_shared<marker_instr>(endm)); loop_marker_stack.pop_back(); } void eval::analyzer::visit(ast::return_stmt* s) { if (s->expr != nullptr) s->expr->visit(this); instrs.push_back(std::make_shared<ret_instr>()); } void eval::analyzer::visit(ast::named_value* x) { instrs.push_back(std::make_shared<get_binding_instr>(ids->at(x->identifier))); } void eval::analyzer::visit(ast::qualified_value* x) { std::vector<std::string> path; for (auto i : x->path) path.push_back(ids->at(i)); instrs.push_back(std::make_shared<get_qualified_binding_instr>(path)); } void eval::analyzer::visit(ast::integer_value* x) { auto v = std::make_shared<int_value>(x->value); instrs.push_back(std::make_shared<literal_instr>(v)); } void eval::analyzer::visit(ast::str_value* x) { auto v = std::make_shared<str_value>(x->value); instrs.push_back(std::make_shared<literal_instr>(v)); } void eval::analyzer::visit(ast::bool_value* x) { auto v = std::make_shared<bool_value>(x->value); instrs.push_back(std::make_shared<literal_instr>(v)); } void eval::analyzer::visit(ast::list_value* x) { auto v = std::make_shared<list_value>(); instrs.push_back(std::make_shared<literal_instr>(v)); for (auto v : x->values) { v->visit(this); instrs.push_back(std::make_shared<append_list_instr>()); } } void eval::analyzer::visit(ast::map_value* x) { auto v = std::make_shared<map_value>(); instrs.push_back(std::make_shared<literal_instr>(v)); for (auto v : x->values) { auto n = std::make_shared<str_value>(ids->at(v.first)); instrs.push_back(std::make_shared<literal_instr>(n)); v.second->visit(this); instrs.push_back(std::make_shared<set_key_instr>()); } } void eval::analyzer::visit(ast::binary_op* x) { if (x->op == op_type::assign) { auto path = std::dynamic_pointer_cast<ast::binary_op>(x->left); if (path != nullptr && path->op == op_type::dot) { path->left->visit(this); auto name = ids->at(std::dynamic_pointer_cast<ast::named_value>(path->right)->identifier); instrs.push_back(std::make_shared<literal_instr>(std::make_shared<str_value>(name))); x->right->visit(this); instrs.push_back(std::make_shared<set_key_instr>()); return; } auto index = std::dynamic_pointer_cast<ast::index_into>(x->left); if (index != nullptr) { index->collection->visit(this); index->index->visit(this); x->right->visit(this); instrs.push_back(std::make_shared<set_index_instr>()); return; } auto name = std::dynamic_pointer_cast<ast::named_value>(x->left)->identifier; x->right->visit(this); instrs.push_back(std::make_shared<set_binding_instr>(ids->at(name))); return; } else if (x->op == op_type::dot) { x->left->visit(this); auto name = ids->at(std::dynamic_pointer_cast<ast::named_value>(x->right)->identifier); instrs.push_back(std::make_shared<literal_instr>(std::make_shared<str_value>(name))); instrs.push_back(std::make_shared<get_key_instr>()); return; } x->left->visit(this); x->right->visit(this); instrs.push_back(std::make_shared<bin_op_instr>(x->op)); } void eval::analyzer::visit(ast::logical_negation* x) { x->value->visit(this); instrs.push_back(std::make_shared<log_not_instr>()); } void eval::analyzer::visit(ast::index_into* x) { x->collection->visit(this); x->index->visit(this); instrs.push_back(std::make_shared<get_index_instr>()); } void eval::analyzer::visit(ast::fn_call* x) { if (x->args.size() > 0) { for (int i = x->args.size() - 1; i >= 0; --i) { x->args[i]->visit(this); } } x->fn->visit(this); instrs.push_back(std::make_shared<call_instr>(x->args.size())); } void eval::analyzer::visit(ast::fn_value* x) { std::vector<std::string> arg_names; for (auto an : x->args) arg_names.push_back(ids->at(an)); eval::analyzer anl(ids, this->root_path); instrs.push_back(std::make_shared<make_closure_instr>(arg_names, anl.analyze(x->body), x->name)); } void eval::analyzer::visit(ast::module_stmt* s) { if(!s->inner_import) instrs.push_back(std::make_shared<enter_scope_instr>()); if (s->body != nullptr) { s->body->visit(this); } else { auto modcode = eval::load_and_assemble(root_path / (ids->at(s->name)+".bcy")); instrs.insert(instrs.end(), std::make_move_iterator(modcode.begin()), std::make_move_iterator(modcode.end())); } if(!s->inner_import) instrs.push_back(std::make_shared<exit_scope_as_new_module_instr>(ids->at(s->name))); } #include <fstream> #include "parse.h" std::vector<std::shared_ptr<eval::instr>> eval::load_and_assemble(const std::filesystem::path& path) { std::ifstream input_stream(path); tokenizer tok(&input_stream); parser par(&tok); std::vector<std::shared_ptr<eval::instr>> code; while (!tok.peek().is_eof()) { try { auto stmt = par.next_stmt(); eval::analyzer anl(&tok.identifiers, path.parent_path()); auto part = anl.analyze(stmt); code.insert(code.end(), std::make_move_iterator(part.begin()), std::make_move_iterator(part.end())); } catch (const parse_error& pe) { std::cout << "parse error: " << pe.what() << " [file= " << path << "line= " << tok.line_number << " token type=" << pe.irritant.type << " data=" << pe.irritant.data << "]"; } catch (const std::runtime_error& e) { std::cout << "error: " << e.what() << " in file " << path << std::endl; } } return code; }
31.444882
107
0.679354
andrew-pa
4080d686ee627e59e199a18a5078cacd1118b1ba
2,727
cc
C++
src/shared/id.cc
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
20
2017-07-03T19:09:09.000Z
2021-09-10T02:53:56.000Z
src/shared/id.cc
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
null
null
null
src/shared/id.cc
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
9
2017-09-17T02:05:06.000Z
2020-01-31T00:12:01.000Z
/* * Copyright 2013 Stanford University. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * - Neither the name of the copyright holders nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * Object representation of an identifires. * * Author: Omid Mashayekhi <omidm@stanford.edu> */ #include "src/shared/id.h" using namespace nimbus; // NOLINT template<typename T> ID<T>::ID() { elem_ = 0; } template<typename T> ID<T>::ID(const T& elem) { elem_ = elem; } template<typename T> ID<T>::ID(const ID<T>& other) : elem_(other.elem_) { } template<typename T> ID<T>::~ID() {} template<typename T> bool ID<T>::Parse(const std::string& input) { std::stringstream ss(input); T num; ss >> num; if (ss.fail()) { std::cout << "ERROR: wrong element as ID." << std::endl; return false; } elem_ = num; return true; } template<typename T> std::string ID<T>::ToNetworkData() { std::ostringstream ss; ss << elem_; std::string rval; return ss.str(); } template<typename T> void ID<T>::set_elem(T elem) { elem_ = elem; } template<typename T> T ID<T>::elem() const { return elem_; } template<typename T> ID<T>& ID<T>::operator= (const ID<T>& right) { elem_ = right.elem_; return *this; } template class ID<uint64_t>; template class ID<uint32_t>; template class ID<int32_t>;
25.485981
72
0.711038
schinmayee
408115ebbf873df278bc62fdb8834b2e4094ca84
5,029
cpp
C++
simulator/simulator.cpp
M-ximus/mipt-mips
ea0b131e3b70273a58311c6921998b6be4549b9c
[ "MIT" ]
null
null
null
simulator/simulator.cpp
M-ximus/mipt-mips
ea0b131e3b70273a58311c6921998b6be4549b9c
[ "MIT" ]
null
null
null
simulator/simulator.cpp
M-ximus/mipt-mips
ea0b131e3b70273a58311c6921998b6be4549b9c
[ "MIT" ]
null
null
null
/* * simulator.cpp - interface for simulator * Copyright 2018 MIPT-MIPS */ // Configurations #include <infra/config/config.h> #include <infra/exception.h> // Simulators #include <func_sim/func_sim.h> #include <modules/core/perf_sim.h> // ISAs #include <mips/mips.h> #include <risc_v/risc_v.h> #include "simulator.h" #include <algorithm> namespace config { static AliasedValue<std::string> isa = { "I", "isa", "mars", "modeled ISA"}; static AliasedSwitch disassembly_on = { "d", "disassembly", "print disassembly"}; static AliasedSwitch functional_only = { "f", "functional-only", "run functional simulation only"}; } // namespace config void CPUModel::duplicate_all_registers_to( CPUModel* model) const { auto max = model->max_cpu_register(); for ( size_t i = 0; i < max; ++i) model->write_cpu_register( i, read_cpu_register( i)); } class SimulatorFactory { struct Builder { virtual std::unique_ptr<Simulator> get_funcsim( bool log) = 0; virtual std::unique_ptr<CycleAccurateSimulator> get_perfsim() = 0; Builder() = default; virtual ~Builder() = default; Builder( const Builder&) = delete; Builder( Builder&&) = delete; Builder& operator=( const Builder&) = delete; Builder& operator=( Builder&&) = delete; }; template<typename T> struct TBuilder : public Builder { const std::string isa; const Endian e; TBuilder( std::string_view isa, Endian e) : isa( isa), e( e) { } std::unique_ptr<Simulator> get_funcsim( bool log) final { return std::make_unique<FuncSim<T>>( e, log, isa); } std::unique_ptr<CycleAccurateSimulator> get_perfsim() final { return std::make_unique<PerfSim<T>>( e, isa); } }; std::map<std::string, std::unique_ptr<Builder>> map; template<typename T> void emplace( std::string_view name, Endian e) { map.emplace( name, std::make_unique<TBuilder<T>>( name, e)); } template<typename T> void emplace_all_endians( std::string name) { emplace<T>( name, Endian::little); emplace<T>( name + "le", Endian::little); if constexpr ( std::is_base_of_v<IsMIPS, T>) emplace<T>( name + "be", Endian::big); } std::string get_supported_isa_message() const { std::ostringstream oss; oss << "Supported ISAs:" << std::endl; for ( const auto& isa : get_supported_isa()) oss << "\t" << isa << std::endl; return oss.str(); } auto get_factory( const std::string& name) const try { return map.at( name).get(); } catch ( const std::out_of_range&) { throw InvalidISA( name + "\n" + get_supported_isa_message()); } SimulatorFactory() { emplace_all_endians<MIPSI>( "mipsI"); emplace_all_endians<MIPSII>( "mipsII"); emplace_all_endians<MIPSIII>( "mipsIII"); emplace_all_endians<MIPSIV>( "mipsIV"); emplace_all_endians<MIPS32>( "mips32"); emplace_all_endians<MIPS64>( "mips64"); emplace_all_endians<MARS>( "mars"); emplace_all_endians<MARS64>( "mars64"); emplace_all_endians<RISCV32>( "riscv32"); emplace_all_endians<RISCV64>( "riscv64"); emplace_all_endians<RISCV128>( "riscv128"); } public: static SimulatorFactory& get_instance() { static SimulatorFactory sf; return sf; } std::vector<std::string> get_supported_isa() const { std::vector<std::string> result( map.size()); std::transform( map.begin(), map.end(), result.begin(), [](const auto& e) { return e.first; }); return result; } auto get_funcsim( const std::string& name, bool log) const { return get_factory( name)->get_funcsim( log); } auto get_perfsim( const std::string& name) const { return get_factory( name)->get_perfsim(); } }; std::vector<std::string> Simulator::get_supported_isa() { return SimulatorFactory::get_instance().get_supported_isa(); } std::shared_ptr<Simulator> Simulator::create_simulator( const std::string& isa, bool functional_only, bool log) { if ( functional_only) return SimulatorFactory::get_instance().get_funcsim( isa, log); return CycleAccurateSimulator::create_simulator( isa); } std::shared_ptr<Simulator> Simulator::create_simulator( const std::string& isa, bool functional_only) { return create_simulator( isa, functional_only, false); } std::shared_ptr<Simulator> Simulator::create_configured_simulator() { return create_simulator( config::isa, config::functional_only, config::disassembly_on); } std::shared_ptr<Simulator> Simulator::create_configured_isa_simulator( const std::string& isa) { return create_simulator( isa, config::functional_only, config::disassembly_on); } std::shared_ptr<CycleAccurateSimulator> CycleAccurateSimulator::create_simulator( const std::string& isa) { return SimulatorFactory::get_instance().get_perfsim( isa); }
29.409357
118
0.653211
M-ximus
4087cdd57b29a693ca79a42f78ff8bc0df351c52
124
cpp
C++
src/combinemode.cpp
MelvinG24/dust3d
c4936fd900a9a48220ebb811dfeaea0effbae3ee
[ "MIT" ]
2,392
2016-12-17T14:14:12.000Z
2022-03-30T19:40:40.000Z
src/combinemode.cpp
MelvinG24/dust3d
c4936fd900a9a48220ebb811dfeaea0effbae3ee
[ "MIT" ]
106
2018-04-19T17:47:31.000Z
2022-03-01T19:44:11.000Z
src/combinemode.cpp
MelvinG24/dust3d
c4936fd900a9a48220ebb811dfeaea0effbae3ee
[ "MIT" ]
184
2017-11-15T09:55:37.000Z
2022-02-21T16:30:46.000Z
#include <QObject> #include "combinemode.h" IMPL_CombineModeToString IMPL_CombineModeFromString IMPL_CombineModeToDispName
17.714286
26
0.879032
MelvinG24
408abb005896f1833358fcc4734abc16ee18bd9c
1,475
hpp
C++
lib/Util/CoutBuf.hpp
EnjoMitch/EnjoLib
321167146657cba1497a9d3b4ffd71430f9b24b3
[ "BSD-3-Clause" ]
3
2021-06-14T15:36:46.000Z
2022-02-28T15:16:08.000Z
lib/Util/CoutBuf.hpp
EnjoMitch/EnjoLib
321167146657cba1497a9d3b4ffd71430f9b24b3
[ "BSD-3-Clause" ]
1
2021-07-17T07:52:15.000Z
2021-07-17T07:52:15.000Z
lib/Util/CoutBuf.hpp
EnjoMitch/EnjoLib
321167146657cba1497a9d3b4ffd71430f9b24b3
[ "BSD-3-Clause" ]
3
2021-07-12T14:52:38.000Z
2021-11-28T17:10:33.000Z
#ifndef COUTBUF_H #define COUTBUF_H #include <Ios/Osstream.hpp> #include <Ios/Cout.hpp> #include <3rdParty/stdfwd.hh> namespace EnjoLib { class LogBuf { public: LogBuf(bool verbose = true); virtual ~LogBuf(); void Flush(); Ostream & GetLog(); private: //SafePtrFast<std::ostream> m_cnull; //std::wostream m_wcnull; Osstream m_ostr; bool m_verbose; }; class Log { public: Log(); virtual ~Log(); Ostream & GetLog(); private: Cout m_cout; }; } extern std::ostream cnull; //extern std::wostream wcnull; std::ostream & GetLog(bool verbose); /// Create a buffered log object "logLocal" with optional disabled logging. /** The log will be displayed on the destruction of the object, but may be flushed before. Usage: ELOG // or ELOG(verbose) LOG << "Text" << EnjoLib::Nl; LOG_FLUSH // optional flushing */ #define ELOG(verbose) EnjoLib::LogBuf logLocal(verbose); /// Create a buffered log object logLocal with enabled logging #define ELO ELOG(true) #define LOG logLocal.GetLog() #define LOG_FLUSH logLocal.Flush() /// Create a non buffered log object "logLocal". /** No need to flush it, but it needs to be wraped in braces, if it's expected to be reused. Usage: LOGL << "Text" << EnjoLib::Nl; or: {LOGL << "Text1" << EnjoLib::Nl;} {LOGL << "Text2" << EnjoLib::Nl;} */ #define LOGL EnjoLib::Log logLocal; logLocal.GetLog() #endif // COUTBUF_H
19.407895
88
0.650847
EnjoMitch
408d6ce8d45ee870b0c0f2870e5cc65eeca53ec7
50,562
cpp
C++
source/d3d11/d3d11_runtime.cpp
Kaldaien/reshade
5dfd2eebce6a00d4c3270f3b9ba628f15c5460fa
[ "BSD-3-Clause" ]
4
2017-03-23T01:52:32.000Z
2018-10-25T00:37:06.000Z
source/d3d11/d3d11_runtime.cpp
Kaldaien/reshade
5dfd2eebce6a00d4c3270f3b9ba628f15c5460fa
[ "BSD-3-Clause" ]
null
null
null
source/d3d11/d3d11_runtime.cpp
Kaldaien/reshade
5dfd2eebce6a00d4c3270f3b9ba628f15c5460fa
[ "BSD-3-Clause" ]
2
2017-02-28T18:10:53.000Z
2020-08-04T02:55:35.000Z
/** * Copyright (C) 2014 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license */ #include "log.hpp" #include "d3d11_runtime.hpp" #include "d3d11_effect_compiler.hpp" #include "lexer.hpp" #include "input.hpp" #include "resource_loading.hpp" #include "..\deps\imgui\imgui.h" #include <algorithm> #include <map> #include <mutex> #include <atlbase.h> typedef bool (__stdcall *SK_ReShade_PresentCallback_pfn)(void *user); typedef void (__stdcall *SK_ReShade_OnCopyResourceD3D11_pfn)(void* user, ID3D11Resource *&dest, ID3D11Resource *&source); typedef void (__stdcall *SK_ReShade_OnClearDepthStencilViewD3D11_pfn)(void* user, ID3D11DepthStencilView *&depthstencil); typedef void (__stdcall *SK_ReShade_OnGetDepthStencilViewD3D11_pfn)(void* user, ID3D11DepthStencilView *&depthstencil); typedef void (__stdcall *SK_ReShade_OnSetDepthStencilViewD3D11_pfn)(void* user, ID3D11DepthStencilView *&depthstencil); typedef void (__stdcall *SK_ReShade_OnDrawD3D11_pfn)(void* user, ID3D11DeviceContext *context, unsigned int vertices); __declspec (dllimport) void SK_ReShade_InstallPresentCallback (SK_ReShade_PresentCallback_pfn fn, void* user); __declspec (dllimport) void SK_ReShade_InstallDrawCallback (SK_ReShade_OnDrawD3D11_pfn fn, void* user); __declspec (dllimport) void SK_ReShade_InstallSetDepthStencilViewCallback (SK_ReShade_OnSetDepthStencilViewD3D11_pfn fn, void* user); __declspec (dllimport) void SK_ReShade_InstallGetDepthStencilViewCallback (SK_ReShade_OnGetDepthStencilViewD3D11_pfn fn, void* user); __declspec (dllimport) void SK_ReShade_InstallClearDepthStencilViewCallback (SK_ReShade_OnClearDepthStencilViewD3D11_pfn fn, void* user); __declspec (dllimport) void SK_ReShade_InstallCopyResourceCallback (SK_ReShade_OnCopyResourceD3D11_pfn fn, void* user); struct explict_draw_s { void* ptr; ID3D11RenderTargetView* pRTV; bool pass = false; int calls = 0; } explicit_draw; bool __stdcall SK_ReShade_PresentCallbackD3D11 (void *user) { const auto runtime = (reshade::d3d11::d3d11_runtime *)((explict_draw_s *)user)->ptr; if (! explicit_draw.pass) { //explicit_draw.calls = ((explict_draw_s *)user)->calls; explicit_draw.pass = true; runtime->on_present (); explicit_draw.pass = false; } return true; } void __stdcall SK_ReShade_OnCopyResourceCallbackD3D11 (void* user, ID3D11Resource *&dest, ID3D11Resource *&source) { ((reshade::d3d11::d3d11_runtime *)user)->on_copy_resource (dest, source); } void __stdcall SK_ReShade_OnClearDepthStencilViewD3D11 (void* user, ID3D11DepthStencilView *&depthstencil) { ((reshade::d3d11::d3d11_runtime *)user)->on_clear_depthstencil_view (depthstencil); } void __stdcall SK_ReShade_OnGetDepthStencilViewD3D11 (void* user, ID3D11DepthStencilView *&depthstencil) { ((reshade::d3d11::d3d11_runtime *)user)->on_get_depthstencil_view (depthstencil); } void __stdcall SK_ReShade_OnSetDepthStencilViewD3D11 (void* user, ID3D11DepthStencilView *&depthstencil) { ((reshade::d3d11::d3d11_runtime *)user)->on_set_depthstencil_view (depthstencil); } void __stdcall SK_ReShade_OnDrawD3D11 (void* user, ID3D11DeviceContext *context, unsigned int vertices) { ((reshade::d3d11::d3d11_runtime *)user)->on_draw_call (context, vertices); } _Return_type_success_ (nullptr) IUnknown* SK_COM_ValidateRelease (IUnknown** ppObj) { if ((! ppObj) || (! ReadPointerAcquire ((volatile LPVOID *)ppObj))) return nullptr; ULONG refs = (*ppObj)->Release (); assert (refs == 0); if (refs == 0) { InterlockedExchangePointer ((void **)ppObj, nullptr); } return *ppObj; } IMGUI_API void ImGui_ImplDX11_RenderDrawLists (ImDrawData* draw_data); #if 0 struct SK_DisjointTimerQueryD3D11 { volatile ID3D11Query* async = nullptr; volatile LONG active = false; D3D11_QUERY_DATA_TIMESTAMP_DISJOINT last_results = { }; }; struct SK_TimerQueryD3D11 { volatile ID3D11Query* async = nullptr; volatile LONG active = FALSE; UINT64 last_results = { }; }; struct SK_DisjointTimerQueryD3D11 { ID3D11Query* async = nullptr; bool active = false; D3D11_QUERY_DATA_TIMESTAMP_DISJOINT last_results = { }; }; struct SK_TimerQueryD3D11 { ID3D11Query* async = nullptr; bool active = false; UINT64 last_results = { }; }; static SK_DisjointTimerQueryD3D11 disjoint_query; struct duration_s { // Timestamp at beginning SK_TimerQueryD3D11 start; // Timestamp at end SK_TimerQueryD3D11 end; }; std::vector <duration_s> timers; // Cumulative runtime of all timers after the disjoint query // is finished and reading these results would not stall // the pipeline UINT64 runtime_ticks = 0ULL; double runtime_ms = 0.0; double last_runtime_ms = 0.0; #endif namespace reshade::d3d11 { extern DXGI_FORMAT make_format_srgb (DXGI_FORMAT format); extern DXGI_FORMAT make_format_normal (DXGI_FORMAT format); extern DXGI_FORMAT make_format_typeless (DXGI_FORMAT format); d3d11_runtime::d3d11_runtime (ID3D11Device *device, IDXGISwapChain *swapchain) : runtime (device->GetFeatureLevel ()), _device (device), _swapchain (swapchain), _stateblock (device) { assert (device != nullptr); assert (swapchain != nullptr); _device->GetImmediateContext (&_immediate_context); HRESULT hr = E_FAIL; DXGI_ADAPTER_DESC adapter_desc = { }; com_ptr <IDXGIDevice> dxgidevice = nullptr; com_ptr <IDXGIAdapter> dxgiadapter = nullptr; hr = _device->QueryInterface (&dxgidevice); assert (SUCCEEDED (hr)); hr = dxgidevice->GetAdapter (&dxgiadapter); assert (SUCCEEDED (hr)); hr = dxgiadapter->GetDesc (&adapter_desc); assert (SUCCEEDED (hr)); _vendor_id = adapter_desc.VendorId; _device_id = adapter_desc.DeviceId; } bool d3d11_runtime::init_backbuffer_texture (void) { // Get back buffer texture HRESULT hr = _swapchain->GetBuffer (0, IID_PPV_ARGS (&_backbuffer)); assert (SUCCEEDED (hr)); D3D11_TEXTURE2D_DESC texdesc = { }; texdesc.Width = _width; texdesc.Height = _height; texdesc.ArraySize = texdesc.MipLevels = 1; texdesc.Format = make_format_typeless (_backbuffer_format); texdesc.SampleDesc = { 1, 0 }; texdesc.Usage = D3D11_USAGE_DEFAULT; texdesc.BindFlags = D3D11_BIND_RENDER_TARGET; OSVERSIONINFOEX verinfo_windows7 = { sizeof (OSVERSIONINFOEX), 6, 1 }; const bool is_windows7 = VerifyVersionInfo ( &verinfo_windows7, VER_MAJORVERSION | VER_MINORVERSION, VerSetConditionMask ( VerSetConditionMask (0, VER_MAJORVERSION, VER_EQUAL), VER_MINORVERSION, VER_EQUAL ) ) != FALSE; //if ( _is_multisampling_enabled || // make_format_normal (_backbuffer_format) != _backbuffer_format || // (! is_windows7) ) //{ hr = _device->CreateTexture2D (&texdesc, nullptr, &_backbuffer_resolved); if (FAILED (hr)) { LOG (ERROR) << "Failed to create back buffer resolve texture (" "Width = " << texdesc.Width << ", " "Height = " << texdesc.Height << ", " "Format = " << texdesc.Format << ", " "SampleCount = " << texdesc.SampleDesc.Count << ", " "SampleQuality = " << texdesc.SampleDesc.Quality << ")! HRESULT is '" << std::hex << hr << std::dec << "'."; return false; } hr = _device->CreateRenderTargetView (_backbuffer.get (), nullptr, &_backbuffer_rtv [2]); assert (SUCCEEDED (hr)); //} if (! ( _is_multisampling_enabled || make_format_normal (_backbuffer_format) != _backbuffer_format || (! is_windows7) ) ) { _backbuffer_resolved = _backbuffer; } // Create back buffer shader texture texdesc.BindFlags = D3D11_BIND_SHADER_RESOURCE; hr = _device->CreateTexture2D (&texdesc, nullptr, &_backbuffer_texture); if (SUCCEEDED (hr)) { D3D11_SHADER_RESOURCE_VIEW_DESC srvdesc = { }; srvdesc.Format = make_format_normal (texdesc.Format); srvdesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srvdesc.Texture2D.MipLevels = texdesc.MipLevels; if (SUCCEEDED(hr)) { hr = _device->CreateShaderResourceView (_backbuffer_texture.get (), &srvdesc, &_backbuffer_texture_srv [0]); } else { LOG(ERROR) << "Failed to create back buffer texture resource view (" "Format = " << srvdesc.Format << ")! HRESULT is '" << std::hex << hr << std::dec << "'."; } srvdesc.Format = make_format_srgb (texdesc.Format); if (SUCCEEDED(hr)) { hr = _device->CreateShaderResourceView (_backbuffer_texture.get (), &srvdesc, &_backbuffer_texture_srv [1]); } else { LOG(ERROR) << "Failed to create back buffer SRGB texture resource view (" "Format = " << srvdesc.Format << ")! HRESULT is '" << std::hex << hr << std::dec << "'."; } } else { LOG (ERROR) << "Failed to create back buffer texture (" "Width = " << texdesc.Width << ", " "Height = " << texdesc.Height << ", " "Format = " << texdesc.Format << ", " "SampleCount = " << texdesc.SampleDesc.Count << ", " "SampleQuality = " << texdesc.SampleDesc.Quality << ")! HRESULT is '" << std::hex << hr << std::dec << "'."; } if (FAILED (hr)) { return false; } D3D11_RENDER_TARGET_VIEW_DESC rtdesc = { }; rtdesc.Format = make_format_normal (texdesc.Format); rtdesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; hr = _device->CreateRenderTargetView (_backbuffer_resolved.get (), &rtdesc, &_backbuffer_rtv [0]); if (FAILED (hr)) { LOG (ERROR) << "Failed to create back buffer render target (" "Format = " << rtdesc.Format << ")! HRESULT is '" << std::hex << hr << std::dec << "'."; return false; } rtdesc.Format = make_format_srgb (texdesc.Format); hr = _device->CreateRenderTargetView (_backbuffer_resolved.get (), &rtdesc, &_backbuffer_rtv [1]); if (FAILED (hr)) { LOG (ERROR) << "Failed to create back buffer SRGB render target (" "Format = " << rtdesc.Format << ")! HRESULT is '" << std::hex << hr << std::dec << "'."; return false; } { const resources::data_resource vs = resources::load_data_resource (IDR_RCDATA1); hr = _device->CreateVertexShader (vs.data, vs.data_size, nullptr, &_copy_vertex_shader); if (FAILED (hr)) { return false; } const resources::data_resource ps = resources::load_data_resource (IDR_RCDATA2); hr = _device->CreatePixelShader (ps.data, ps.data_size, nullptr, &_copy_pixel_shader); if (FAILED (hr)) { return false; } } { const D3D11_SAMPLER_DESC desc = { D3D11_FILTER_MIN_MAG_MIP_POINT, D3D11_TEXTURE_ADDRESS_CLAMP, D3D11_TEXTURE_ADDRESS_CLAMP, D3D11_TEXTURE_ADDRESS_CLAMP }; hr = _device->CreateSamplerState (&desc, &_copy_sampler); if (FAILED (hr)) { return false; } } return true; } bool d3d11_runtime::init_default_depth_stencil (void) { const D3D11_TEXTURE2D_DESC texdesc = { _width, _height, 1, 1, DXGI_FORMAT_D24_UNORM_S8_UINT, { 1, 0 }, D3D11_USAGE_DEFAULT, D3D11_BIND_DEPTH_STENCIL }; com_ptr <ID3D11Texture2D> depth_stencil_texture = nullptr; HRESULT hr = _device->CreateTexture2D (&texdesc, nullptr, &depth_stencil_texture); if (FAILED (hr)) { LOG (ERROR) << "Failed to create depth stencil texture (" "Width = " << texdesc.Width << ", " "Height = " << texdesc.Height << ", " "Format = " << texdesc.Format << ", " "SampleCount = " << texdesc.SampleDesc.Count << ", " "SampleQuality = " << texdesc.SampleDesc.Quality << ")! HRESULT is '" << std::hex << hr << std::dec << "'."; return false; } hr = _device->CreateDepthStencilView (depth_stencil_texture.get (), nullptr, &_default_depthstencil); return SUCCEEDED (hr); } bool d3d11_runtime::init_fx_resources (void) { D3D11_RASTERIZER_DESC desc = { }; desc.FillMode = D3D11_FILL_SOLID; desc.CullMode = D3D11_CULL_NONE; desc.DepthClipEnable = TRUE; desc.SlopeScaledDepthBias = 0.0f; desc.DepthBiasClamp = 0.0f; return SUCCEEDED (_device->CreateRasterizerState (&desc, &_effect_rasterizer_state)); } bool d3d11_runtime::on_init (const DXGI_SWAP_CHAIN_DESC &desc) { _width = desc.BufferDesc.Width; _height = desc.BufferDesc.Height; _backbuffer_format = desc.BufferDesc.Format; _is_multisampling_enabled = desc.SampleDesc.Count > 1; if ( (! init_backbuffer_texture ()) || (! init_default_depth_stencil ()) || (! init_fx_resources ()) ) { return false; } // Clear reference count to make UnrealEngine happy _backbuffer->Release (); return runtime::on_init (); } void d3d11_runtime::on_reset (void) { if (! is_initialized ()) { return; } runtime::on_reset (); // Reset reference count to make UnrealEngine happy _backbuffer->AddRef (); // Destroy resources _backbuffer.reset (); _backbuffer_resolved.reset (); _backbuffer_texture.reset (); _backbuffer_texture_srv [0].reset (); _backbuffer_texture_srv [1].reset (); _backbuffer_rtv [0].reset (); _backbuffer_rtv [1].reset (); _backbuffer_rtv [2].reset (); _depthstencil.reset (); _depthstencil_replacement.reset (); for ( auto it : _depth_source_table ) it.first->Release (); _depth_source_table.clear (); _depthstencil_texture.reset (); _depthstencil_texture_srv.reset (); _default_depthstencil.reset (); _copy_vertex_shader.reset (); _copy_pixel_shader.reset (); _copy_sampler.reset (); _effect_rasterizer_state.reset (); } void d3d11_runtime::on_reset_effect (void) { runtime::on_reset_effect (); for (auto it : _effect_sampler_states) { it->Release (); } _effect_sampler_descs.clear (); _effect_sampler_states.clear (); _constant_buffers.clear (); _effect_shader_resources.resize (3); _effect_shader_resources [0] = _backbuffer_texture_srv [0].get (); _effect_shader_resources [1] = _backbuffer_texture_srv [1].get (); _effect_shader_resources [2] = _depthstencil_texture_srv.get (); } void d3d11_runtime::on_present (void) { static int last_calls = 0; static bool first = true; if (is_initialized ()) { SK_ReShade_InstallPresentCallback (SK_ReShade_PresentCallbackD3D11, this); //SK_ReShade_InstallCopyResourceCallback (SK_ReShade_OnCopyResourceCallbackD3D11, this); //SK_ReShade_InstallSetDepthStencilViewCallback (SK_ReShade_OnSetDepthStencilViewD3D11, this); //SK_ReShade_InstallGetDepthStencilViewCallback (SK_ReShade_OnGetDepthStencilViewD3D11, this); //SK_ReShade_InstallClearDepthStencilViewCallback (SK_ReShade_OnClearDepthStencilViewD3D11, this); SK_ReShade_InstallDrawCallback (SK_ReShade_OnDrawD3D11, this); first = false; } if ((! is_initialized ()) || _drawcalls.load () == 0) { return; } #if 0 if (is_effect_loaded ()) { if (ReadPointerAcquire ((void **)&_techniques [0].timer.disjoint_query.async) == nullptr) { D3D11_QUERY_DESC query_desc { D3D11_QUERY_TIMESTAMP_DISJOINT, 0x00 }; ID3D11Query* pQuery = nullptr; if (SUCCEEDED (_device->CreateQuery (&query_desc, &pQuery))) { InterlockedExchangePointer ((void **)&_techniques [0].timer.disjoint_query.async, pQuery); _immediate_context->Begin (pQuery); InterlockedExchange ((volatile unsigned long *)&_techniques [0].timer.disjoint_query.active, TRUE); } } } #endif if (explicit_draw.pass) { CComPtr <ID3D11Resource> pRTVRes = nullptr; CComPtr <ID3D11RenderTargetView> pRTV = nullptr; D3D11_TEXTURE2D_DESC tex_desc = { }; // Apply post processing if (is_effect_loaded ()) { CComPtr <ID3D11DepthStencilView> pDSV = nullptr; CComPtr <ID3D11RenderTargetView> pRTVs [D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT]; _immediate_context->OMGetRenderTargets (D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, &pRTVs [0], &pDSV); D3D11_TEXTURE2D_DESC bb_desc = { }; _backbuffer_texture.get ()->GetDesc (&bb_desc); //pRTV = pRTVs [0]; // CComPtr <ID3D11Resource > pRTVRes = nullptr; // pRTV->GetResource (&pRTVRes); // CComQIPtr <ID3D11Texture2D> pRTVTex (pRTVRes); // // pRTVTex->GetDesc (&tex_desc); for ( auto it : pRTVs ) { if (it == nullptr) continue; D3D11_RENDER_TARGET_VIEW_DESC rt_desc = { }; it->GetDesc (&rt_desc); if (/*make_format_typeless (rt_desc.Format) == make_format_typeless (bb_desc.Format) && */rt_desc.Texture2D.MipSlice == 0) { CComPtr <ID3D11Resource > pRTVRes = nullptr; it->GetResource (&pRTVRes); CComQIPtr <ID3D11Texture2D> pRTVTex (pRTVRes); pRTVTex->GetDesc (&tex_desc); if ( tex_desc.SampleDesc.Count == 1 && tex_desc.ArraySize == 1 && tex_desc.MipLevels <= 1 && (tex_desc.BindFlags & ( D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE ) ) ) { pRTV = it; break; } } } if (pRTV != nullptr) { // Capture device state _stateblock.capture (_immediate_context.get ()); // Disable unused pipeline stages _immediate_context->HSSetShader (nullptr, nullptr, 0); _immediate_context->DSSetShader (nullptr, nullptr, 0); _immediate_context->GSSetShader (nullptr, nullptr, 0); const uintptr_t null = 0; pRTV->GetResource (&pRTVRes); D3D11_SHADER_RESOURCE_VIEW_DESC srv_desc = { }; srv_desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srv_desc.Format = tex_desc.Format; srv_desc.Texture2D.MipLevels = 1; CComPtr <ID3D11ShaderResourceView> pSRV = nullptr; bool view = SUCCEEDED (_device->CreateShaderResourceView (pRTVRes, &srv_desc, &pSRV)); const auto rtv = _backbuffer_rtv [0].get (); _immediate_context->OMSetRenderTargets (1, &rtv, nullptr); D3D11_DEPTH_STENCIL_DESC stencil_desc = { }; stencil_desc.DepthEnable = FALSE; stencil_desc.DepthFunc = D3D11_COMPARISON_ALWAYS; stencil_desc.StencilEnable = FALSE; CComPtr <ID3D11DepthStencilState> pDepthState = nullptr; _device->CreateDepthStencilState (&stencil_desc, &pDepthState); _immediate_context->OMSetDepthStencilState (pDepthState, 0); _immediate_context->RSSetState (_effect_rasterizer_state.get ()); _immediate_context->IASetPrimitiveTopology (D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); _immediate_context->IASetInputLayout (nullptr); _immediate_context->IASetVertexBuffers (0, 1, reinterpret_cast<ID3D11Buffer *const *>(&null), reinterpret_cast<const UINT *>(&null), reinterpret_cast<const UINT *>(&null)); _immediate_context->RSSetState (_effect_rasterizer_state.get ()); _immediate_context->VSSetShader (_copy_vertex_shader.get (), nullptr, 0); _immediate_context->PSSetShader (_copy_pixel_shader.get (), nullptr, 0); //// Setup samplers _immediate_context->VSSetSamplers (0, static_cast <UINT> (_effect_sampler_states.size ()), _effect_sampler_states.data ()); _immediate_context->PSSetSamplers (0, static_cast <UINT> (_effect_sampler_states.size ()), _effect_sampler_states.data ()); const auto sst = _copy_sampler.get (); if (view) { _immediate_context->PSSetSamplers (0, 1, &sst); _immediate_context->PSSetShaderResources (0, 1, &pSRV); _immediate_context->Draw (3, 0); } else _immediate_context->ResolveSubresource (_backbuffer_resolved.get (), 0, pRTVRes, 0, _backbuffer_format); _immediate_context->RSSetState (_effect_rasterizer_state.get ()); int techs = on_present_effect (); if (techs > 0) { _immediate_context->CopyResource (_backbuffer_texture.get (), _backbuffer_resolved.get ()); _immediate_context->OMSetRenderTargets (1, &pRTV, nullptr); _immediate_context->IASetPrimitiveTopology (D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); _immediate_context->IASetInputLayout (nullptr); _immediate_context->IASetVertexBuffers (0, 1, reinterpret_cast<ID3D11Buffer *const *>(&null), reinterpret_cast<const UINT *>(&null), reinterpret_cast<const UINT *>(&null)); _immediate_context->RSSetState (_effect_rasterizer_state.get ()); _immediate_context->VSSetShader (_copy_vertex_shader.get (), nullptr, 0); _immediate_context->PSSetShader (_copy_pixel_shader.get (), nullptr, 0); const auto srv = _backbuffer_texture_srv [make_format_srgb(_backbuffer_format) == _backbuffer_format].get(); _immediate_context->PSSetSamplers (0, 1, &sst); _immediate_context->PSSetShaderResources (0, 1, &srv); _immediate_context->Draw (3, 0); } // Apply previous device state _stateblock.apply_and_release (); explicit_draw.calls++; } } } else { detect_depth_source (); // Apply presenting runtime::on_present (); if (last_calls == explicit_draw.calls) { // Apply post processing if (is_effect_loaded ()) { // Capture device state _stateblock.capture (_immediate_context.get ()); // Disable unused pipeline stages _immediate_context->HSSetShader (nullptr, nullptr, 0); _immediate_context->DSSetShader (nullptr, nullptr, 0); _immediate_context->GSSetShader (nullptr, nullptr, 0); // Setup real back buffer const auto rtv = _backbuffer_rtv [0].get (); _immediate_context->OMSetRenderTargets (1, &rtv, nullptr); // Resolve back buffer if (_backbuffer_resolved != _backbuffer) { _immediate_context->ResolveSubresource(_backbuffer_resolved.get(), 0, _backbuffer.get(), 0, _backbuffer_format); } // Setup vertex input const uintptr_t null = 0; _immediate_context->IASetPrimitiveTopology (D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); _immediate_context->IASetInputLayout (nullptr); _immediate_context->IASetVertexBuffers (0, 1, reinterpret_cast<ID3D11Buffer *const *>(&null), reinterpret_cast<const UINT *>(&null), reinterpret_cast<const UINT *>(&null)); _immediate_context->RSSetState (_effect_rasterizer_state.get ()); D3D11_DEPTH_STENCIL_DESC stencil_desc = { }; stencil_desc.DepthEnable = FALSE; stencil_desc.DepthFunc = D3D11_COMPARISON_ALWAYS; stencil_desc.StencilEnable = FALSE; CComPtr <ID3D11DepthStencilState> pDepthState = nullptr; _device->CreateDepthStencilState (&stencil_desc, &pDepthState); // Setup samplers _immediate_context->VSSetSamplers (0, static_cast <UINT> (_effect_sampler_states.size ()), _effect_sampler_states.data ()); _immediate_context->PSSetSamplers (0, static_cast <UINT> (_effect_sampler_states.size ()), _effect_sampler_states.data ()); int techs = on_present_effect (); // Copy to back buffer if (techs > 0 && _backbuffer_resolved != _backbuffer) { _immediate_context->CopyResource(_backbuffer_texture.get(), _backbuffer_resolved.get()); const auto rtv = _backbuffer_rtv[2].get(); _immediate_context->OMSetRenderTargets(1, &rtv, nullptr); const uintptr_t null = 0; _immediate_context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); _immediate_context->IASetInputLayout(nullptr); _immediate_context->IASetVertexBuffers(0, 1, reinterpret_cast<ID3D11Buffer *const *>(&null), reinterpret_cast<const UINT *>(&null), reinterpret_cast<const UINT *>(&null)); _immediate_context->RSSetState(_effect_rasterizer_state.get()); _immediate_context->VSSetShader(_copy_vertex_shader.get(), nullptr, 0); _immediate_context->PSSetShader(_copy_pixel_shader.get(), nullptr, 0); const auto sst = _copy_sampler.get(); _immediate_context->PSSetSamplers(0, 1, &sst); const auto srv = _backbuffer_texture_srv[make_format_srgb(_backbuffer_format) == _backbuffer_format].get(); _immediate_context->PSSetShaderResources(0, 1, &srv); _immediate_context->Draw(3, 0); } // Apply previous device state _stateblock.apply_and_release (); } } #if 0 if (is_effect_loaded ()) { if ((! _techniques [0].timer.disjoint_done) && ReadPointerAcquire ((volatile PVOID *)_techniques [0].timer.disjoint_query.async)) { if (ReadAcquire ((volatile const LONG *)&_techniques [0].timer.disjoint_query.active)) { _immediate_context->End ((ID3D11Asynchronous *)ReadPointerAcquire ((volatile PVOID*)&_techniques [0].timer.disjoint_query.async)); InterlockedExchange ((volatile unsigned long *)&_techniques [0].timer.disjoint_query.active, FALSE); } else { HRESULT const hr = _immediate_context->GetData ( (ID3D11Asynchronous *)ReadPointerAcquire ((volatile PVOID*)&_techniques [0].timer.disjoint_query.async), &_techniques [0].timer.disjoint_query.last_results, sizeof D3D11_QUERY_DATA_TIMESTAMP_DISJOINT, 0x0 ); if (hr == S_OK) { ((ID3D11Asynchronous *)ReadPointerAcquire ((volatile PVOID*)&_techniques [0].timer.disjoint_query.async))->Release (); InterlockedExchangePointer ((void **)&_techniques [0].timer.disjoint_query.async, nullptr); // Check for failure, if so, toss out the results. if (! _techniques [0].timer.disjoint_query.last_results.Disjoint) _techniques [0].timer.disjoint_done = true; else { for (auto& technique : _techniques) { technique.timer.timer.start.active = 0; technique.timer.timer.end.active = 0; if (technique.timer.timer.start.async != nullptr) { SK_COM_ValidateRelease ((IUnknown **)&technique.timer.timer.start.async); technique.timer.timer.start.async = nullptr; } if (technique.timer.timer.end.async != nullptr) { SK_COM_ValidateRelease ((IUnknown **)&technique.timer.timer.end.async); technique.timer.timer.end.async = nullptr; } } _techniques [0].timer.disjoint_done = true; } } } } if (_techniques [0].timer.disjoint_done) { for (auto& technique : _techniques) { auto GetTimerDataStart = [](ID3D11DeviceContext* dev_ctx, duration* pDuration, bool& success) -> UINT64 { if (! FAILED (dev_ctx->GetData ( (ID3D11Query *)ReadPointerAcquire ((volatile PVOID *)&pDuration->start.async), &pDuration->start.last_results, sizeof UINT64, 0x00 ))) { SK_COM_ValidateRelease ((IUnknown **)&pDuration->start.async); success = true; return pDuration->start.last_results; } success = false; return 0; }; auto GetTimerDataEnd = [](ID3D11DeviceContext* dev_ctx, duration* pDuration, bool& success) -> UINT64 { if (pDuration->end.async == nullptr) { success = true; return pDuration->start.last_results; } if (! FAILED (dev_ctx->GetData ( (ID3D11Query *)ReadPointerAcquire ((volatile PVOID *)&pDuration->end.async), &pDuration->end.last_results, sizeof UINT64, 0x00 ))) { SK_COM_ValidateRelease ((IUnknown **)&pDuration->end.async); success = true; return pDuration->end.last_results; } success = false; return 0; }; auto CalcRuntimeMS = [&](gpu_interval_timer* timer) { if (ReadAcquire64 ((volatile LONG64 *)&timer->runtime_ticks) != 0LL) { timer->runtime_ms = 1000.0 * (((double)(ULONG64)ReadAcquire64 ((volatile LONG64 *)&timer->runtime_ticks)) / (double)_techniques [0].timer.disjoint_query.last_results.Frequency); // Filter out queries that spanned multiple frames // if (timer->runtime_ms > 0.0 && timer->last_runtime_ms > 0.0) { if (timer->runtime_ms > timer->last_runtime_ms * 100.0 || timer->runtime_ms > 12.0) timer->runtime_ms = timer->last_runtime_ms; } timer->last_runtime_ms = timer->runtime_ms; } }; auto AccumulateRuntimeTicks = [&](ID3D11DeviceContext* dev_ctx, gpu_interval_timer* timer) -> void { std::vector <duration> rejects; InterlockedExchange64 ((volatile LONG64 *)&timer->runtime_ticks, 0LL); bool success0 = false, success1 = false; UINT64 time0 = 0ULL, time1 = 0ULL; time0 = GetTimerDataEnd (dev_ctx, &timer->timer, success0); time1 = GetTimerDataStart (dev_ctx, &timer->timer, success1); if (success0 && success1) InterlockedAdd64 ((volatile LONG64 *)&timer->runtime_ticks, time0 - time1); else rejects.push_back (timer->timer); // If effect was cancelled ... //{ // InterlockedExchange64 ((volatile LONG64 *)&tracker->runtime_ticks, 0LL); // timer->runtime_ms = 0.0; // timer->last_runtime_ms = 0.0; //} // Anything that fails goes back on the list and we will try again next frame //if (! rejects.empty ()) // timer->timer = rejects [0]; }; AccumulateRuntimeTicks (_immediate_context.get (), &technique.timer); CalcRuntimeMS (&technique.timer); technique.average_gpu_duration.append (technique.timer.last_runtime_ms); } _techniques [0].timer.disjoint_done = false; } } #endif last_calls = explicit_draw.calls; } } void d3d11_runtime::on_draw_call (ID3D11DeviceContext *context, unsigned int vertices) { _vertices += vertices; _drawcalls += 1; com_ptr <ID3D11DepthStencilView> current_depthstencil = nullptr; context->OMGetRenderTargets ( 0, nullptr, &current_depthstencil ); if ( current_depthstencil == nullptr || current_depthstencil == _default_depthstencil ) { return; } if (current_depthstencil == _depthstencil_replacement) { current_depthstencil = _depthstencil; } const auto it = _depth_source_table.find (current_depthstencil.get ()); if (it != _depth_source_table.cend () && (! it->second.invalidated)) { it->second.drawcall_count = _drawcalls.load (); it->second.vertices_count += vertices; } } void d3d11_runtime::on_set_depthstencil_view (ID3D11DepthStencilView *&depthstencil) { if ( (! _depth_source_table.count (depthstencil)) || _depth_source_table [depthstencil].invalidated ) { D3D11_TEXTURE2D_DESC texture_desc = { }; com_ptr <ID3D11Resource> resource = nullptr; com_ptr <ID3D11Texture2D> texture = nullptr; depthstencil->GetResource (&resource); if (FAILED (resource->QueryInterface (&texture))) { return; } texture->GetDesc (&texture_desc); // Early depth stencil rejection if ( texture_desc.Width != _width || texture_desc.Height != _height || texture_desc.SampleDesc.Count > 1 ) { return; } depthstencil->AddRef (); // Begin tracking new depth stencil const depth_source_info info = { texture_desc.Width, texture_desc.Height, 0, 0, false }; _depth_source_table [depthstencil] = info; } if (_depthstencil_replacement != nullptr && depthstencil == _depthstencil) { depthstencil = _depthstencil_replacement.get (); } } void d3d11_runtime::on_get_depthstencil_view (ID3D11DepthStencilView *&depthstencil) { if ( _depthstencil_replacement != nullptr && depthstencil == _depthstencil_replacement ) { depthstencil->Release (); depthstencil = _depthstencil.get (); depthstencil->AddRef (); } } void d3d11_runtime::on_clear_depthstencil_view (ID3D11DepthStencilView *&depthstencil) { if ( _depthstencil_replacement != nullptr && depthstencil == _depthstencil ) { depthstencil = _depthstencil_replacement.get (); } } void d3d11_runtime::on_copy_resource (ID3D11Resource *&dest, ID3D11Resource *&source) { if (_depthstencil_replacement != nullptr) { com_ptr <ID3D11Resource> resource = nullptr; _depthstencil->GetResource (&resource); if (dest == resource) { dest = _depthstencil_texture.get (); } if (source == resource) { source = _depthstencil_texture.get (); } } } void d3d11_runtime::capture_frame(uint8_t *buffer) const { if (_backbuffer_format != DXGI_FORMAT_R8G8B8A8_UNORM && _backbuffer_format != DXGI_FORMAT_R8G8B8A8_UNORM_SRGB && _backbuffer_format != DXGI_FORMAT_B8G8R8A8_UNORM && _backbuffer_format != DXGI_FORMAT_B8G8R8A8_UNORM_SRGB) { LOG (WARNING) << "Screenshots are not supported for back buffer format " << _backbuffer_format << "."; return; } D3D11_TEXTURE2D_DESC texture_desc = { }; texture_desc.Width = _width; texture_desc.Height = _height; texture_desc.ArraySize = 1; texture_desc.MipLevels = 1; texture_desc.Format = _backbuffer_format; texture_desc.SampleDesc.Count = 1; texture_desc.Usage = D3D11_USAGE_STAGING; texture_desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; com_ptr<ID3D11Texture2D> texture_staging; HRESULT hr = _device->CreateTexture2D (&texture_desc, nullptr, &texture_staging); if (FAILED (hr)) { LOG (ERROR) << "Failed to create staging resource for screenshot capture! HRESULT is '" << std::hex << hr << std::dec << "'."; return; } _immediate_context->CopyResource ( texture_staging.get (), _backbuffer_resolved.get () ); D3D11_MAPPED_SUBRESOURCE mapped = { }; hr = _immediate_context->Map (texture_staging.get (), 0, D3D11_MAP_READ, 0, &mapped); if (FAILED (hr)) { LOG(ERROR) << "Failed to map staging resource with screenshot capture! HRESULT is '" << std::hex << hr << std::dec << "'."; return; } auto mapped_data = static_cast <BYTE *> (mapped.pData); const UINT pitch = texture_desc.Width * 4; for (UINT y = 0; y < texture_desc.Height; y++) { CopyMemory (buffer, mapped_data, std::min (pitch, static_cast <UINT> (mapped.RowPitch))); for (UINT x = 0; x < pitch; x += 4) { buffer [x + 3] = 0xFF; if ( texture_desc.Format == DXGI_FORMAT_B8G8R8A8_UNORM || texture_desc.Format == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB ) { std::swap (buffer [x + 0], buffer [x + 2]); } } buffer += pitch; mapped_data += mapped.RowPitch; } _immediate_context->Unmap (texture_staging.get (), 0); } bool d3d11_runtime::load_effect (const reshadefx::syntax_tree &ast, std::string &errors) { return d3d11_effect_compiler (this, ast, errors, false).run (); } bool d3d11_runtime::update_texture (texture &texture, const uint8_t *data) { if (texture.impl_reference != texture_reference::none) { return false; } const auto texture_impl = texture.impl->as <d3d11_tex_data> (); assert (data != nullptr); assert (texture_impl != nullptr); switch (texture.format) { case texture_format::r8: { std::vector <uint8_t> data2 (texture.width * texture.height); for (size_t i = 0, k = 0; i < texture.width * texture.height * 4; i += 4, k++) data2 [k] = data [i]; _immediate_context->UpdateSubresource ( texture_impl->texture.get (), 0, nullptr, data2.data (), texture.width, texture.width * texture.height ); } break; case texture_format::rg8: { std::vector <uint8_t> data2 (texture.width * texture.height * 2); for (size_t i = 0, k = 0; i < texture.width * texture.height * 4; i += 4, k += 2) data2 [k ] = data [i ], data2 [k + 1] = data [i + 1]; _immediate_context->UpdateSubresource ( texture_impl->texture.get (), 0, nullptr, data2.data (), texture.width * 2, texture.width * texture.height * 2 ); } break; default: { _immediate_context->UpdateSubresource ( texture_impl->texture.get (), 0, nullptr, data, texture.width * 4, texture.width * texture.height * 4 ); } break; } if (texture.levels > 1) { _immediate_context->GenerateMips (texture_impl->srv [0].get ()); } return true; } void d3d11_runtime::render_technique (const technique &technique) { #if 0 if (_techniques [0].timer.disjoint_query.active) { // Start a new query D3D11_QUERY_DESC query_desc { D3D11_QUERY_TIMESTAMP, 0x00 }; duration duration_; ID3D11Query* pQuery = nullptr; if (SUCCEEDED (_device->CreateQuery (&query_desc, &pQuery))) { InterlockedExchangePointer ((void **)&technique.timer.timer.start.async, pQuery); _immediate_context->End (pQuery); } } #endif bool is_default_depthstencil_cleared = false; // Setup shader constants if (technique.uniform_storage_index >= 0) { const auto constant_buffer = _constant_buffers [technique.uniform_storage_index].get (); D3D11_MAPPED_SUBRESOURCE mapped = { }; const HRESULT hr = _immediate_context->Map (constant_buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped); if (SUCCEEDED (hr)) { CopyMemory (mapped.pData, get_uniform_value_storage().data() + technique.uniform_storage_offset, mapped.RowPitch); _immediate_context->Unmap (constant_buffer, 0); } else { LOG(ERROR) << "Failed to map constant buffer! HRESULT is '" << std::hex << hr << std::dec << "'!"; } _immediate_context->VSSetConstantBuffers (0, 1, &constant_buffer); _immediate_context->PSSetConstantBuffers (0, 1, &constant_buffer); } for (const auto &pass_object : technique.passes) { const d3d11_pass_data &pass = *pass_object->as <d3d11_pass_data> (); // Setup states _immediate_context->VSSetShader (pass.vertex_shader.get (), nullptr, 0); _immediate_context->PSSetShader (pass.pixel_shader.get (), nullptr, 0); //if (pass.shader_resources.empty ()) // continue; static const float blendfactor [4] = { 1.0f, 1.0f, 1.0f, 1.0f }; _immediate_context->OMSetBlendState (pass.blend_state.get (), blendfactor, D3D11_DEFAULT_SAMPLE_MASK); _immediate_context->OMSetDepthStencilState (pass.depth_stencil_state.get (), pass.stencil_reference); // Save back buffer of previous pass _immediate_context->CopyResource ( _backbuffer_texture.get (), _backbuffer_resolved.get () ); // Setup shader resources _immediate_context->VSSetShaderResources (0, static_cast <UINT> (pass.shader_resources.size ()), pass.shader_resources.data ()); _immediate_context->PSSetShaderResources (0, static_cast <UINT> (pass.shader_resources.size ()), pass.shader_resources.data ()); // Setup render targets if ( static_cast <UINT> (pass.viewport.Width) == _width && static_cast <UINT> (pass.viewport.Height) == _height ) { _immediate_context->OMSetRenderTargets (D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, pass.render_targets, _default_depthstencil.get()); if (!is_default_depthstencil_cleared) { is_default_depthstencil_cleared = true; _immediate_context->ClearDepthStencilView (_default_depthstencil.get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); } } else { _immediate_context->OMSetRenderTargets (D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, pass.render_targets, nullptr); } _immediate_context->RSSetViewports (1, &pass.viewport); if (pass.clear_render_targets) { for (const auto target : pass.render_targets) { if (target != nullptr) { constexpr float color [4] = { 0.0f, 0.0f, 0.0f, 0.0f }; _immediate_context->ClearRenderTargetView(target, color); } } } // Draw triangle _immediate_context->Draw (3, 0); _vertices += 3; _drawcalls += 1; // Reset render targets _immediate_context->OMSetRenderTargets ( 0, nullptr, nullptr ); // Reset shader resources ID3D11ShaderResourceView* null [D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT] = { nullptr }; _immediate_context->VSSetShaderResources (0, static_cast <UINT> (pass.shader_resources.size ()), null); _immediate_context->PSSetShaderResources (0, static_cast <UINT> (pass.shader_resources.size ()), null); // Update shader resources for (const auto resource : pass.render_target_resources) { if (resource == nullptr) { continue; } D3D11_SHADER_RESOURCE_VIEW_DESC resource_desc = { }; resource->GetDesc (&resource_desc); if (resource_desc.Texture2D.MipLevels > 1) { _immediate_context->GenerateMips (resource); } } } #if 0 if (_techniques [0].timer.disjoint_query.active) { D3D11_QUERY_DESC query_desc { D3D11_QUERY_TIMESTAMP, 0x00 }; ID3D11Query* pQuery = nullptr; if (SUCCEEDED (_device->CreateQuery (&query_desc, &pQuery))) { InterlockedExchangePointer ((void **)&technique.timer.timer.end.async, pQuery); _immediate_context->End (pQuery); } } #endif } void d3d11_runtime::render_imgui_draw_data (ImDrawData *draw_data) { ImGui_ImplDX11_RenderDrawLists (draw_data); } void d3d11_runtime::detect_depth_source (void) { if ( _is_multisampling_enabled || _depth_source_table.empty () ) { return; } depth_source_info best_info = { 0 }; ID3D11DepthStencilView *best_match = nullptr; for (auto it = _depth_source_table.begin (); it != _depth_source_table.end ();) { const auto depthstencil = it->first; auto &depthstencil_info = it->second; if ((! depthstencil_info.invalidated) && (depthstencil->AddRef (), depthstencil->Release ()) == 1) { depthstencil_info.invalidated = TRUE; depthstencil->Release (); ++it; continue; } else { ++it; } if (depthstencil_info.drawcall_count == 0) { continue; } if ((depthstencil_info.vertices_count * (1.2f - float(depthstencil_info.drawcall_count) / _drawcalls.load ())) >= (best_info.vertices_count * (1.2f - float(best_info.drawcall_count) / _drawcalls.load ()))) { best_match = depthstencil; best_info = depthstencil_info; } depthstencil_info.drawcall_count = depthstencil_info.vertices_count = 0; } static int overload_iters = 0; if (_depth_source_table.load_factor () > 0.75f && (! (overload_iters++ % 15))) { concurrency::concurrent_unordered_map <ID3D11DepthStencilView *, depth_source_info> live_map; // Trim the table for (auto& it : _depth_source_table) { if (! it.second.invalidated) { live_map.insert (std::make_pair (it.first, it.second)); } } _depth_source_table.swap (live_map); } if (best_match != nullptr && _depthstencil != best_match) { create_depthstencil_replacement (best_match); } } bool d3d11_runtime::create_depthstencil_replacement (ID3D11DepthStencilView *depthstencil) { _depthstencil.reset (); _depthstencil_replacement.reset (); _depthstencil_texture.reset (); _depthstencil_texture_srv.reset (); if (depthstencil != nullptr) { _depthstencil = depthstencil; depthstencil->GetResource (reinterpret_cast <ID3D11Resource **> (&_depthstencil_texture)); D3D11_TEXTURE2D_DESC texdesc = { }; _depthstencil_texture->GetDesc (&texdesc); HRESULT hr = S_OK; if ((texdesc.BindFlags & D3D11_BIND_SHADER_RESOURCE) == 0) { _depthstencil_texture.reset (); switch (texdesc.Format) { case DXGI_FORMAT_R16_TYPELESS: case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_D16_UNORM: texdesc.Format = DXGI_FORMAT_R16_TYPELESS; break; case DXGI_FORMAT_R8_UNORM: case DXGI_FORMAT_R32_TYPELESS: case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_D32_FLOAT: texdesc.Format = DXGI_FORMAT_R32_TYPELESS; break; default: case DXGI_FORMAT_R24G8_TYPELESS: case DXGI_FORMAT_D24_UNORM_S8_UINT: texdesc.Format = DXGI_FORMAT_R24G8_TYPELESS; break; case DXGI_FORMAT_R32G8X24_TYPELESS: case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: texdesc.Format = DXGI_FORMAT_R32G8X24_TYPELESS; break; } texdesc.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE; hr = _device->CreateTexture2D (&texdesc, nullptr, &_depthstencil_texture); if (SUCCEEDED (hr)) { D3D11_DEPTH_STENCIL_VIEW_DESC dsvdesc = { }; dsvdesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; switch (texdesc.Format) { case DXGI_FORMAT_R16_TYPELESS: dsvdesc.Format = DXGI_FORMAT_D16_UNORM; break; case DXGI_FORMAT_R32_TYPELESS: dsvdesc.Format = DXGI_FORMAT_D32_FLOAT; break; case DXGI_FORMAT_R24G8_TYPELESS: dsvdesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; break; case DXGI_FORMAT_R32G8X24_TYPELESS: dsvdesc.Format = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; break; } hr = _device->CreateDepthStencilView (_depthstencil_texture.get (), &dsvdesc, &_depthstencil_replacement); } } if (FAILED (hr)) { LOG(ERROR) << "Failed to create depth stencil replacement texture! HRESULT is '" << std::hex << hr << std::dec << "'."; return false; } D3D11_SHADER_RESOURCE_VIEW_DESC srvdesc = { }; srvdesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srvdesc.Texture2D.MipLevels = 1; switch (texdesc.Format) { case DXGI_FORMAT_R16_TYPELESS: srvdesc.Format = DXGI_FORMAT_R16_FLOAT; break; case DXGI_FORMAT_R32_TYPELESS: srvdesc.Format = DXGI_FORMAT_R32_FLOAT; break; case DXGI_FORMAT_R24G8_TYPELESS: srvdesc.Format = DXGI_FORMAT_R24_UNORM_X8_TYPELESS; break; case DXGI_FORMAT_R32G8X24_TYPELESS: srvdesc.Format = DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; break; } hr = _device->CreateShaderResourceView (_depthstencil_texture.get (), &srvdesc, &_depthstencil_texture_srv); if (FAILED (hr)) { LOG (ERROR) << "Failed to create depth stencil replacement resource view! HRESULT is '" << std::hex << hr << std::dec << "'."; return false; } if (_depthstencil != _depthstencil_replacement) { // Update auto depth stencil com_ptr <ID3D11DepthStencilView> current_depthstencil = nullptr; ID3D11RenderTargetView *targets [D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT] = { nullptr }; _immediate_context->OMGetRenderTargets (D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, targets, &current_depthstencil); if (current_depthstencil != nullptr && current_depthstencil == _depthstencil) { _immediate_context->OMSetRenderTargets (D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, targets, _depthstencil_replacement.get ()); } for (auto& target : targets) { if (target != nullptr) { target->Release (); } } } } // Update effect textures _effect_shader_resources [2] = _depthstencil_texture_srv.get (); for (const auto &technique : _techniques) for (const auto &pass : technique.passes) pass->as <d3d11_pass_data> ()->shader_resources [2] = _depthstencil_texture_srv.get (); return true; } }
31.019632
208
0.632095
Kaldaien
408ff649f0f996b9dfed62f373d980e7e12b4866
1,672
cpp
C++
src/Client/States/AbstractState.cpp
AntoineJT/BurgWar
8e435bd58dda0610d7dfc3ba6d313bd443c9b4b8
[ "MIT" ]
45
2018-09-29T14:16:04.000Z
2022-03-10T18:53:58.000Z
src/Client/States/AbstractState.cpp
AntoineJT/BurgWar
8e435bd58dda0610d7dfc3ba6d313bd443c9b4b8
[ "MIT" ]
46
2019-12-22T17:29:41.000Z
2022-03-20T14:15:06.000Z
src/Client/States/AbstractState.cpp
AntoineJT/BurgWar
8e435bd58dda0610d7dfc3ba6d313bd443c9b4b8
[ "MIT" ]
19
2018-09-29T11:53:25.000Z
2022-01-14T17:00:07.000Z
// Copyright (C) 2020 Jérôme Leclercq // This file is part of the "Burgwar" project // For conditions of distribution and use, see copyright notice in LICENSE #include <Client/States/AbstractState.hpp> namespace bw { AbstractState::AbstractState(std::shared_ptr<StateData> stateData) : m_stateData(std::move(stateData)), m_isVisible(false) { m_onTargetChangeSizeSlot.Connect(m_stateData->window->OnRenderTargetSizeChange, [this](const Nz::RenderTarget*) { if (m_isVisible) LayoutWidgets(); }); } AbstractState::~AbstractState() { for (const auto& cleanupFunc : m_cleanupFunctions) cleanupFunc(); for (WidgetEntry& entry : m_widgets) entry.widget->Destroy(); } void AbstractState::Enter(Ndk::StateMachine& /*fsm*/) { m_isVisible = true; for (WidgetEntry& entry : m_widgets) { if (entry.wasVisible) entry.widget->Show(); } for (auto it = m_entities.begin(); it != m_entities.end();) { const Ndk::EntityHandle& entity = *it; if (entity) { entity->Enable(); ++it; } else it = m_entities.erase(it); } LayoutWidgets(); } void AbstractState::Leave(Ndk::StateMachine& /*fsm*/) { m_isVisible = false; for (WidgetEntry& entry : m_widgets) { entry.wasVisible = entry.widget->IsVisible(); entry.widget->Hide(); } for (auto it = m_entities.begin(); it != m_entities.end();) { const Ndk::EntityHandle& entity = *it; if (entity) { entity->Disable(); ++it; } else it = m_entities.erase(it); } } bool AbstractState::Update(Ndk::StateMachine& /*fsm*/, float /*elapsedTime*/) { return true; } void AbstractState::LayoutWidgets() { } }
19.44186
113
0.655502
AntoineJT
40916bc0026863bc9ac779a5c3456633dc8a3fbf
715
hpp
C++
src/pixelwriter.hpp
intbeam/dos-rpg-game
7b2ee87d00319da609b61f054ebf4eed34714768
[ "MIT" ]
2
2021-01-23T19:22:53.000Z
2021-09-15T10:39:41.000Z
src/pixelwriter.hpp
intbeam/dos-rpg-game
7b2ee87d00319da609b61f054ebf4eed34714768
[ "MIT" ]
null
null
null
src/pixelwriter.hpp
intbeam/dos-rpg-game
7b2ee87d00319da609b61f054ebf4eed34714768
[ "MIT" ]
null
null
null
#ifndef PIXELWRITER_HPP #define PIXELWRITER_HPP #include "displayadapter.hpp" #define PACKET_SINGLE_COLOR 0 #define PACKET_SOURCE_COPY 1 #define PACKET_SKIP 2 #define PACKET_NEXT_LINE 3 typedef struct pixel_packet { int count; int value; void *data; int type; } pixel_packet; class PixelWriter { protected: surface_rect dimensions; int line_length; public: PixelWriter(surface_rect dimensions); void set_line_length(int width); virtual void write_pixeldata(int x_origin, int y_origin, const pixel_packet *operations, int packet_count) = 0; virtual void copy_line(int x_origin, int y_origin, void *source, int numpixels) = 0; }; #endif
20.428571
119
0.718881
intbeam
40922616eb2419a55194d539c52fe3ebe134ba23
3,974
cpp
C++
common/src/ttime.cpp
jangmys/PBBPerm
c13ad1045d0c7a36fd8d8ace728410fee38d70a4
[ "MIT" ]
null
null
null
common/src/ttime.cpp
jangmys/PBBPerm
c13ad1045d0c7a36fd8d8ace728410fee38d70a4
[ "MIT" ]
null
null
null
common/src/ttime.cpp
jangmys/PBBPerm
c13ad1045d0c7a36fd8d8ace728410fee38d70a4
[ "MIT" ]
null
null
null
#include <time.h> #include <iostream> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include "../include/ttime.h" #include "../include/arguments.h" #include "../include/log.h" // ___________________________________________ ttime::ttime() { period_set(CHECKPOINT_TTIME, arguments::checkpointv); // std::cout<<"lasts 1 "<<arguments::checkpointv<<" "<<lasts[CHECKPOINT_TTIME]<<" "<<periods[CHECKPOINT_TTIME]<<std::endl; period_set(WORKER_BALANCING, arguments::balancingv); // std::cout<<"lasts 2 "<<lasts[WORKER_BALANCING]<<" "<<periods[WORKER_BALANCING]<<std::endl; processRequest = new mytimer(); masterWalltime = new mytimer(); wall = new mytimer(); update = new mytimer(); split = new mytimer(); test = new mytimer(); workerExploretime = new mytimer(); pthread_mutex_init(&mutex_lasttime, NULL); // printElapsed(wserver,"WSERVER"); } ttime::~ttime() { delete processRequest; delete masterWalltime; delete wall; delete update; delete split; } void ttime::reset() { wall->isOn=false; wall->elapsed.tv_sec=0; wall->elapsed.tv_nsec=0; processRequest->isOn=false; processRequest->elapsed.tv_sec=0; processRequest->elapsed.tv_nsec=0; // wall.tv_nsec=0; masterWalltime->isOn=false; masterWalltime->elapsed.tv_sec=0; masterWalltime->elapsed.tv_nsec=0; // masterWalltime.tv_nsec=0; // processRequest.tv_sec=0; // processRequest.tv_nsec=0; } time_t ttime::time_get() { time_t tmp; time(&tmp); return tmp; } void ttime::wait(int index) { srand48(getpid()); double t = (unsigned int) (periods[index] * 1.0) * drand48(); std::cout << (unsigned int) t << std::endl << std::flush; std::cout << "debut" << std::endl << std::flush; sleep((unsigned int) t); std::cout << "fin" << std::endl << std::flush; } // ___________________________________________ void ttime::period_set(int index, time_t t) { srand48(getpid()); lasts[index] = (time_t) (time_get() - (t * 1.0) * drand48()); periods[index] = t; } bool ttime::period_passed(int index) { time_t tmp = time_get(); // std::cout<<"time? "<<tmp<<"\t"<<lasts[index]<<"\t"<<periods[index]<<std::endl<<std::flush; if ((tmp - lasts[index]) < periods[index]) return false; // multi-core worker threads execute this function... pthread_mutex_lock(&mutex_lasttime); lasts[index] = tmp; // std::cout<<"PASSED "<<lasts[index]<<"\n"<<std::flush; pthread_mutex_unlock(&mutex_lasttime); return true; } // ====================================== void ttime::on(mytimer * t) { t->isOn = true; clock_gettime(CLOCK_MONOTONIC, &t->start); } void ttime::off(mytimer * t) { clock_gettime(CLOCK_MONOTONIC, &t->stop); struct timespec diff = subtractTime(t->stop, t->start); if (t->isOn) t->elapsed = addTime(t->elapsed, diff); t->isOn = false; } void ttime::printElapsed(mytimer * t, const char * name) { printf("%s\t:\t %lld.%.9ld\n", name, (long long) t->elapsed.tv_sec, t->elapsed.tv_nsec); } void ttime::logElapsed(mytimer * t, const char * name) { FILE_LOG(logINFO) << name << "\t:" << (long long) t->elapsed.tv_sec << "." << t->elapsed.tv_nsec; } float ttime::divide(mytimer * t1, mytimer * t2) { return (t1->elapsed.tv_sec + t1->elapsed.tv_nsec / 1e9) / (t2->elapsed.tv_sec + t2->elapsed.tv_nsec / 1e9); } float ttime::masterLoadPerc() { return 100.0 * divide(masterWalltime, wall); } timespec ttime::subtractTime(struct timespec t2, struct timespec t1) { t2.tv_sec -= t1.tv_sec; t2.tv_nsec -= t1.tv_nsec; while (t2.tv_nsec < 0) { t2.tv_sec--; t2.tv_nsec += NSECS; } return t2; } timespec ttime::addTime(struct timespec t1, struct timespec t2) { t1.tv_sec += t2.tv_sec; t1.tv_nsec += t2.tv_nsec; while (t1.tv_nsec > NSECS) { t1.tv_sec++; t1.tv_nsec -= NSECS; } return t1; }
22.451977
126
0.627831
jangmys
4099ed056428ea6cbf70361a8417861140a5bfa9
1,001
cpp
C++
test/sandbox/hash_map/foldable/foldr.cpp
rbock/hana
2b76377f91a5ebe037dea444e4eaabba6498d3a8
[ "BSL-1.0" ]
2
2015-05-07T14:29:13.000Z
2015-07-04T10:59:46.000Z
test/sandbox/hash_map/foldable/foldr.cpp
rbock/hana
2b76377f91a5ebe037dea444e4eaabba6498d3a8
[ "BSL-1.0" ]
null
null
null
test/sandbox/hash_map/foldable/foldr.cpp
rbock/hana
2b76377f91a5ebe037dea444e4eaabba6498d3a8
[ "BSL-1.0" ]
null
null
null
/* @copyright Louis Dionne 2014 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #include <boost/hana/detail/sandbox/hash_map.hpp> #include <boost/hana/detail/assert.hpp> #include <boost/hana/detail/constexpr.hpp> #include <boost/hana/functional.hpp> #include <boost/hana/integral.hpp> #include <boost/hana/list/instance.hpp> #include <boost/hana/pair.hpp> using namespace boost::hana; BOOST_HANA_CONSTEXPR_LAMBDA auto check_fold = [](auto ...pairs) { auto values = fmap(second, list(pairs...)); auto result = foldr(hash_map(pairs...), list(), cons); BOOST_HANA_CONSTANT_ASSERT(elem(permutations(values), result)); }; template <int k, int v> BOOST_HANA_CONSTEXPR_LAMBDA auto p = pair(int_<k>, int_<v>); int main() { check_fold(); check_fold(p<1, 1>); check_fold(p<1, 1>, p<2, 2>); check_fold(p<1, 1>, p<2, 2>, p<3, 3>); check_fold(p<1, 1>, p<2, 2>, p<3, 3>, p<4, 4>); }
29.441176
78
0.689311
rbock
409eaab8bf630029623932270308d14028651142
3,123
cc
C++
chrome/browser/install_verification/win/module_ids.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
chrome/browser/install_verification/win/module_ids.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
chrome/browser/install_verification/win/module_ids.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/install_verification/win/module_ids.h" #include <utility> #include "base/logging.h" #include "base/macros.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "base/strings/string_tokenizer.h" #include "base/strings/string_util.h" #include "chrome/grit/browser_resources.h" #include "ui/base/resource/resource_bundle.h" namespace { struct { size_t id; const char* module_name_digest; } kExpectedInstallModules[] = { {1u, "c8cc47613e155f2129f480c6ced84549"}, // chrome.dll {2u, "49b78a23b0d8d5d8fb60d4e472b22764"}, // chrome_child.dll }; // Parses a line consisting of a positive decimal number and a 32-digit // hexadecimal number, separated by a space. Inserts the output, if valid, into // |module_ids|. Unexpected leading or trailing characters will cause // the line to be ignored, as will invalid decimal/hexadecimal characters. void ParseAdditionalModuleID( const base::StringPiece& line, ModuleIDs* module_ids) { DCHECK(module_ids); base::CStringTokenizer line_tokenizer(line.begin(), line.end(), " "); if (!line_tokenizer.GetNext()) return; // Empty string. base::StringPiece id_piece(line_tokenizer.token_piece()); if (!line_tokenizer.GetNext()) return; // No delimiter (' '). base::StringPiece digest_piece(line_tokenizer.token_piece()); if (line_tokenizer.GetNext()) return; // Unexpected trailing characters. unsigned id = 0; if (!StringToUint(id_piece, &id)) return; // First token was not decimal. if (digest_piece.length() != 32) return; // Second token is not the right length. for (base::StringPiece::const_iterator it = digest_piece.begin(); it != digest_piece.end(); ++it) { if (!base::IsHexDigit(*it)) return; // Second token has invalid characters. } // This is a valid line. module_ids->insert(std::make_pair(digest_piece.as_string(), id)); } } // namespace void ParseAdditionalModuleIDs( const base::StringPiece& raw_data, ModuleIDs* module_ids) { DCHECK(module_ids); base::CStringTokenizer file_tokenizer(raw_data.begin(), raw_data.end(), "\r\n"); while (file_tokenizer.GetNext()) { ParseAdditionalModuleID(base::StringPiece(file_tokenizer.token_piece()), module_ids); } } void LoadModuleIDs(ModuleIDs* module_ids) { for (size_t i = 0; i < arraysize(kExpectedInstallModules); ++i) { module_ids->insert( std::make_pair( kExpectedInstallModules[i].module_name_digest, kExpectedInstallModules[i].id)); } base::StringPiece additional_module_ids; #if defined(GOOGLE_CHROME_BUILD) additional_module_ids = ui::ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_ADDITIONAL_MODULE_IDS); #endif ParseAdditionalModuleIDs(additional_module_ids, module_ids); }
32.53125
79
0.699007
zipated
40a02c2a03baa3e13058f1ebb84c0f7ea95783f8
7,612
cpp
C++
test.cpp
Tweety-FER/bioinf-bwt
9e39456d72f0bc4964106621d5eb9e7ebe51c280
[ "MIT" ]
1
2015-12-15T22:51:32.000Z
2015-12-15T22:51:32.000Z
test.cpp
Tweety-FER/bioinf-bwt
9e39456d72f0bc4964106621d5eb9e7ebe51c280
[ "MIT" ]
null
null
null
test.cpp
Tweety-FER/bioinf-bwt
9e39456d72f0bc4964106621d5eb9e7ebe51c280
[ "MIT" ]
null
null
null
#include "DynamicSuffixArray.h" #define CATCH_CONFIG_RUNNER #include "catch.hpp" #include <string.h> #include <time.h> #include <sys/time.h> using namespace std; //Common variables for some tests dynsa::DynamicSuffixArray *a; ustring dist_string; float *fs; int main( int argc, char* const argv[]){ dist_string = (ustring) "CCGAACACCCGTACCGAGGTGAGCACCCTCTGCATCAGCCAGTTCCGCTACAGCGCACAAATCCGTCCTTCNNNNNNNNNNNNNNNNNNNTTCCGTAGTGACCAAAGACTACACCTTTAAACGCCCCGGCTGGGCCGGACGTTTTGAACAGGAAGGCCAGCACCAGGACTACCAGCGCACGCAGTATGAAGTGTATGACTACCCCGGACGTTTCAAGAGCGCCCACGGGCAGAACTTTGCCCGCTGGCAGATGGACGGCTGGCGAAACAACGCAGAAACCGCGCGGGGAATGAGCCGCTCGCCGGAGATATGGCCGGGACGGCGAATTGTGCTGACGGGGCATCCGCAGGCGAACCTGAACCGGGAATGGCAGGTGGTGGCAAGTGAACTGCACGGCGAACAGCCACAGGCGGTGCCAGGACGGCAGGGAGCGGGGACGGCGCTGGAGAACCATTTTGCGGTGATCCCGGCAGACAGAACATGGCGACCACAGCCGTTGCTGAAACCGCTGGTCGACGGCCCGCAGAGCGC"; fs = DynRankS::createCharDistribution(dist_string, 512, 1); a = new dynsa::DynamicSuffixArray(fs); int result = Catch::Session().run(argc, argv); return result; } TEST_CASE("Short setText", "[short]"){ ustring s = (ustring) "GTGAGTGAG"; ustring bwt = (ustring) "GGGATTA$GG"; a->setText(s, 10); int sz = strlen((char*)s); CHECK((memcmp(a->getText(), s, sz) == 0)); sz = strlen((char*)bwt); REQUIRE((memcmp(a->getBWT(), bwt, sz) == 0)); } TEST_CASE("Short insert", "[short]"){ ustring s = (ustring) "GAAGT"; a->insertFactor(s, 3, 5); s = (ustring) "GTGAAGTGAGTGAG"; ustring bwt = (ustring) "GGGGAATTT$AAGGG"; int sz = strlen((char*)s); CHECK((memcmp(a->getText(), s, sz) == 0)); sz = strlen((char*)bwt); REQUIRE((memcmp(a->getBWT(), bwt, sz) == 0)); } TEST_CASE("Short delete", "[short]"){ ustring s = (ustring) "GTGAGTGAG"; ustring bwt = (ustring) "GGGATTA$GG"; a -> deleteAt(3,5); int sz = strlen((char*)s); CHECK((memcmp(a->getText(), s, sz) == 0)); sz = strlen((char*)bwt); REQUIRE((memcmp(a->getBWT(), bwt, sz) == 0)); } TEST_CASE("Short replace", "[short]"){ a -> replace((ustring) "TT", 3, 2); ustring s = (ustring) "GTTTGTGAG"; ustring bwt = (ustring) "GGATT$GTTG"; int sz = strlen((char*)s); CHECK((memcmp(a->getText(), s, sz) == 0)); sz = strlen((char*)bwt); REQUIRE((memcmp(a->getBWT(), bwt, sz) == 0)); } TEST_CASE("Single insert", "[short]"){ a -> insertToText((uchar)'C', 4); ustring s = (ustring) "GTTCTGTGAG"; ustring bwt = (ustring) "GGTATT$TGCG"; int sz = strlen((char*)s); CHECK((memcmp(a->getText(), s, sz) == 0)); sz = strlen((char*)bwt); REQUIRE((memcmp(a->getBWT(), bwt, sz) == 0)); } TEST_CASE("1031 long bwt verification - test1", "[verification]"){ FILE* input = fopen("testdata/test1/GCA_000731455_1031.in", "r"); ustring s = new uchar[1033]; fscanf(input," %s", s); fclose(input); FILE* expected = fopen("testdata/test1/GCA_000731455_1031.out", "r"); ustring bwt = new uchar[1033]; fscanf(expected," %s", bwt); fclose(expected); int sz = strlen((char*)bwt); a = new dynsa::DynamicSuffixArray(fs); a -> setText(s, 1032); REQUIRE((memcmp(a -> getBWT(), bwt, sz) == 0)); } TEST_CASE("5385 long bwt verification - test2", "[verification]"){ FILE* input = fopen("testdata/test2/GCA_000731455_5385.in", "r"); ustring s = new uchar[5388]; fscanf(input," %s", s); fclose(input); FILE* expected = fopen("testdata/test2/GCA_000731455_5385.out", "r"); ustring bwt = new uchar[5388]; fscanf(expected," %s", bwt); fclose(expected); int sz = strlen((char*)bwt); a = new dynsa::DynamicSuffixArray(fs); a -> setText(s, 5386); REQUIRE((memcmp(a -> getBWT(), bwt, sz) == 0)); } TEST_CASE("35970 long bwt verification - test3", "[verification]"){ FILE* input = fopen("testdata/test3/GCA_000731455_35970.in", "r"); ustring s = new uchar[35972]; fscanf(input," %s", s); fclose(input); FILE* expected = fopen("testdata/test3/GCA_000731455_35970.out", "r"); ustring bwt = new uchar[35972]; fscanf(expected," %s", bwt); fclose(expected); int sz = strlen((char*)bwt); a = new dynsa::DynamicSuffixArray(fs); a -> setText(s, 35971); REQUIRE((memcmp(a -> getBWT(), bwt, sz) == 0)); } TEST_CASE("176616 large time monitor - test4", "[time]"){ FILE* input = fopen("testdata/test4/GCA_000731455_176616.in", "r"); ustring s = new uchar[176620]; fscanf(input," %s", s); fclose(input); a = new dynsa::DynamicSuffixArray(fs); int sz = strlen((char*)s); a -> setText(s, 176617); REQUIRE(memcmp(a -> getText(), s, sz) == 0); } TEST_CASE("Check size after modifications", "[size]"){ FILE* input = fopen("testdata/test5/GCA_000731455_189561.in", "r"); ustring s = new uchar[189565]; fscanf(input," %s", s); fclose(input); a = new dynsa::DynamicSuffixArray(fs); int sz = strlen((char*)s); CHECK( a -> size() == 0); CHECK( a -> isEmpty() == true); a -> setText(s, 148); CHECK( a -> size() == 148); a -> insertFactor(s+1200, 37, 231); CHECK( a -> size() == 379); a -> deleteAt(47, 85); CHECK( a -> size() == 294); a -> deleteAt(1,280); CHECK( a -> size() == 14); a -> deleteAt(1,12); CHECK( a -> isEmpty() == false); REQUIRE( a -> size() == 2); } /* * BWT for the example used in documentation */ TEST_CASE("Short setText1"," [short]") { ustring s=(ustring) "CTCTGC"; ustring bwt=(ustring) "CG$TTCC"; a = new dynsa::DynamicSuffixArray(fs); a->setText(s,7); int sz=strlen((char*)s); CHECK((memcmp(a->getText(),s,sz)==0)); sz=strlen((char*)s); REQUIRE((memcmp(a->getBWT(),bwt,sz)==0)); } TEST_CASE("Short insert1","[short]") { ustring s=(ustring) "G"; a->insertFactor(s,3,1); ustring bwt = (ustring) "CGG$TTCC"; s=(ustring) "CTGCTGC"; int sz=strlen((char*)s); CHECK((memcmp(a->getText(),s,sz)==0)); sz=strlen((char*)bwt); REQUIRE((memcmp(a->getBWT(),bwt,sz)==0)); } TEST_CASE("524 into 3631 long bwt insert", "[insert]"){ FILE* input = fopen("testdata/test6/GCA_000731455_3631.in", "r"); ustring s1 = new uchar[3631]; fscanf(input," %s", s1); fclose(input); FILE* insert = fopen("testdata/test6/GCA_000731455_524.in", "r"); ustring s2 = new uchar[524]; fscanf(insert," %s", s2); fclose(insert); int sz1 = strlen((char*)s1); int sz2 = strlen((char*)s2); FILE* bwt = fopen("testdata/test6/GCA_000731455_3631ins.out", "r"); ustring s3 = new uchar[sz2+sz1]; fscanf(insert," %s", s3); fclose(insert); a = new dynsa::DynamicSuffixArray(fs); a -> setText(s1, 3632); a->insertFactor(s2,500,524); REQUIRE((memcmp(a -> getBWT(), s3, sz1+sz2+1) == 0)); } TEST_CASE("35970 delete - test7", "[delete]"){ FILE* input = fopen("testdata/test7/GCA_000731455_35970.in", "r"); ustring s = new uchar[35972]; fscanf(input," %s", s); fclose(input); FILE* deleted = fopen("testdata/test7/GCA_000731455_35970del.in", "r"); ustring del = new uchar[35972]; fscanf(deleted," %s", del); fclose(deleted); int sz = strlen((char*)del); a = new dynsa::DynamicSuffixArray(fs); a -> setText(s, 35971); a ->deleteAt(4000,4000); CHECK((memcmp(a -> getText(), del, 31970) == 0)); FILE* expected = fopen("testdata/test7/GCA_000731455_35970del", "r"); ustring bwt = new uchar[31971]; fscanf(expected," %s", bwt); fclose(expected); REQUIRE((memcmp(a -> getBWT(), bwt, 31971) == 0)); }
29.618677
562
0.617315
Tweety-FER
40a1896fa3d4af5338d7fcdb488b6d6154e951bb
286
cc
C++
test/abc185/d.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
test/abc185/d.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
test/abc185/d.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
#include "abc185/d.cc" #include "gtest/gtest.h" TEST(abc185d, 1) { EXPECT_EQ(3, solve(5, 2, {1, 3})); } TEST(abc185d, 2) { EXPECT_EQ(6, solve(13, 3, {13, 3, 9})); } TEST(abc185d, 3) { EXPECT_EQ(0, solve(5, 5, {5, 2, 1, 4, 3})); } TEST(abc185d, 4) { EXPECT_EQ(1, solve(1, 0, {})); }
26
64
0.566434
nryotaro
40a40d6b1d333dcb37f7659c3058c4fb08b7c1f1
10,277
cpp
C++
test/TestOramReadPathEvictionRW.cpp
young-du/PathORAM
23d18b23153adf2e4a689e26d4bd05dc7db2497e
[ "MIT" ]
9
2020-08-01T22:00:47.000Z
2021-11-08T09:44:18.000Z
test/TestOramReadPathEvictionRW.cpp
young-du/PathORAM
23d18b23153adf2e4a689e26d4bd05dc7db2497e
[ "MIT" ]
null
null
null
test/TestOramReadPathEvictionRW.cpp
young-du/PathORAM
23d18b23153adf2e4a689e26d4bd05dc7db2497e
[ "MIT" ]
5
2020-06-24T19:23:57.000Z
2022-01-24T14:52:48.000Z
#include "catch.h" #include "Bucket.h" #include "ServerStorage.h" #include "OramInterface.h" #include "RandForOramInterface.h" #include "RandomForOram.h" #include "UntrustedStorageInterface.h" #include "OramReadPathEviction.h" #include "OramReadPathEviction.h" int* sampleDataReadPathEviction(int i) { int* newArray = new int[Block::BLOCK_SIZE]; for (int j = 0; j < Block::BLOCK_SIZE; ++j) { newArray[j] = i; } return newArray; } TEST_CASE("Test ORAM with read path eviction read very small numBlocks") { int bucketSize = 2; int numBlocks = 1; Bucket::setMaxSize(bucketSize); UntrustedStorageInterface* storage = new ServerStorage(); RandForOramInterface* random = new RandomForOram(); OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks); int bound = numBlocks; for(int i = 0; i < bound; i++){ int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks)); } for(int i = 0; i < bound; i++){ int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL); for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) { int temp = accessed[j]; REQUIRE(temp == i%numBlocks); } } Bucket::resetState(); ServerStorage::is_initialized = false; ServerStorage::is_capacity_set = false; RandomForOram::is_initialized = false; RandomForOram::bound = -1; } TEST_CASE("Test ORAM with read path eviction read small numBlocks") { int bucketSize = 2; int numBlocks = 32; Bucket::setMaxSize(bucketSize); UntrustedStorageInterface* storage = new ServerStorage(); RandForOramInterface* random = new RandomForOram(); OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks); int bound = numBlocks; for(int i = 0; i < bound; i++){ int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks)); } for(int i = 0; i < bound; i++){ int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL); for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) { int temp = accessed[j]; REQUIRE(temp == i%numBlocks); } } Bucket::resetState(); ServerStorage::is_initialized = false; ServerStorage::is_capacity_set = false; RandomForOram::is_initialized = false; RandomForOram::bound = -1; } TEST_CASE("Test ORAM with read path eviction read larger numBlocks") { int bucketSize = 2; int numBlocks = 1024; Bucket::setMaxSize(bucketSize); UntrustedStorageInterface* storage = new ServerStorage(); RandForOramInterface* random = new RandomForOram(); OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks); int bound = numBlocks; for(int i = 0; i < bound; i++){ int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks)); } for(int i = 0; i < bound; i++){ int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL); for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) { int temp = accessed[j]; REQUIRE(temp == i%numBlocks); } } Bucket::resetState(); ServerStorage::is_initialized = false; ServerStorage::is_capacity_set = false; RandomForOram::is_initialized = false; RandomForOram::bound = -1; } TEST_CASE("Test ORAM with read path eviction read numBlocks not power of 2") { int bucketSize = 2; int numBlocks = 30; Bucket::setMaxSize(bucketSize); UntrustedStorageInterface* storage = new ServerStorage(); RandForOramInterface* random = new RandomForOram(); OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks); int bound = numBlocks; for(int i = 0; i < bound; i++){ int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks)); } for(int i = 0; i < bound; i++){ int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL); for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) { int temp = accessed[j]; REQUIRE(temp == i%numBlocks); } } Bucket::resetState(); ServerStorage::is_initialized = false; ServerStorage::is_capacity_set = false; RandomForOram::is_initialized = false; RandomForOram::bound = -1; } TEST_CASE("Test ORAM with read path eviction read very small numBlocks, bucketSize = 4") { int bucketSize = 4; int numBlocks = 1; Bucket::setMaxSize(bucketSize); UntrustedStorageInterface* storage = new ServerStorage(); RandForOramInterface* random = new RandomForOram(); OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks); int bound = numBlocks; for(int i = 0; i < bound; i++){ int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks)); } for(int i = 0; i < bound; i++){ int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL); for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) { int temp = accessed[j]; REQUIRE(temp == i%numBlocks); } } Bucket::resetState(); ServerStorage::is_initialized = false; ServerStorage::is_capacity_set = false; RandomForOram::is_initialized = false; RandomForOram::bound = -1; } TEST_CASE("Test ORAM with read path eviction read small numBlocks, bucketSize = 4") { int bucketSize = 4; int numBlocks = 32; Bucket::setMaxSize(bucketSize); UntrustedStorageInterface* storage = new ServerStorage(); RandForOramInterface* random = new RandomForOram(); OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks); int bound = numBlocks; for(int i = 0; i < bound; i++){ int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks)); } for(int i = 0; i < bound; i++){ int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL); for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) { int temp = accessed[j]; REQUIRE(temp == i%numBlocks); } } Bucket::resetState(); ServerStorage::is_initialized = false; ServerStorage::is_capacity_set = false; RandomForOram::is_initialized = false; RandomForOram::bound = -1; } TEST_CASE("Test ORAM with read path eviction read larger numBlocks, bucketSize = 4") { int bucketSize = 4; int numBlocks = 1024; Bucket::setMaxSize(bucketSize); UntrustedStorageInterface* storage = new ServerStorage(); RandForOramInterface* random = new RandomForOram(); OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks); int bound = numBlocks; for(int i = 0; i < bound; i++){ int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks)); } for(int i = 0; i < bound; i++){ int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL); for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) { int temp = accessed[j]; REQUIRE(temp == i%numBlocks); } } Bucket::resetState(); ServerStorage::is_initialized = false; ServerStorage::is_capacity_set = false; RandomForOram::is_initialized = false; RandomForOram::bound = -1; } TEST_CASE("Test ORAM with read path eviction read numBlocks not power of 2, bucketSize = 4") { int bucketSize = 4; int numBlocks = 30; Bucket::setMaxSize(bucketSize); UntrustedStorageInterface* storage = new ServerStorage(); RandForOramInterface* random = new RandomForOram(); OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks); int bound = numBlocks; for(int i = 0; i < bound; i++){ int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks)); } for(int i = 0; i < bound; i++){ int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL); for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) { int temp = accessed[j]; REQUIRE(temp == i%numBlocks); } } Bucket::resetState(); ServerStorage::is_initialized = false; ServerStorage::is_capacity_set = false; RandomForOram::is_initialized = false; RandomForOram::bound = -1; } // Uncomment the below test case to run for when the number of blocks is very large (=2^20). /* TEST_CASE("Test ORAM read path eviction read very large numBlocks", "[setup_det2]") { int bucketSize = 2; int numBlocks = 1048576; Bucket::setMaxSize(bucketSize); UntrustedStorageInterface* storage = new ServerStorage(); RandForOramInterface* random = new RandomForOram(); OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks); int bound = numBlocks; for(int i = 0; i < bound; i++){ int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks)); } for(int i = 0; i < bound; i++){ int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL); for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) { int temp = accessed[j]; REQUIRE(temp == i%numBlocks); } } Bucket::resetState(); ServerStorage::is_initialized = false; ServerStorage::is_capacity_set = false; RandomForOram::is_initialized = false; RandomForOram::bound = -1; } */
29.113314
126
0.637054
young-du
40a6f0044b675d29396de67bc5154e30b823347c
967
cpp
C++
week1/Arrays/Rotate Array without using extraSpace.cpp
rishabhrathore055/gfg-11-weeks-workshop-on-DSA
052039bfbe3ae261740fc73d50f32528ddd49e6a
[ "MIT" ]
9
2021-08-01T16:17:04.000Z
2022-01-22T19:51:18.000Z
week1/Arrays/Rotate Array without using extraSpace.cpp
rishabhrathore055/gfg-11-weeks-workshop-on-DSA
052039bfbe3ae261740fc73d50f32528ddd49e6a
[ "MIT" ]
null
null
null
week1/Arrays/Rotate Array without using extraSpace.cpp
rishabhrathore055/gfg-11-weeks-workshop-on-DSA
052039bfbe3ae261740fc73d50f32528ddd49e6a
[ "MIT" ]
1
2021-08-30T12:26:11.000Z
2021-08-30T12:26:11.000Z
#include<bits/stdc++.h> using namespace std; class Solution { public: void reverseArr(int arr[],int start,int end) { while(start<end) { swap(arr[start],arr[end]); start++; end--; } } void rotateArr(int arr[],int d, int n) { d=d%n; if(d==0) return; reverseArr(arr,0,n-1); reverseArr(arr,0,d-1); reverseArr(arr,d,n-1); } }; int main() { int t; //taking testcases cin >> t; while(t--){ int n, d; //input n and d cin >> n >> d; int arr[n]; //inserting elements in the array for(int i = 0; i < n; i++){ cin >> arr[i]; } Solution ob; //calling rotateArr() function ob.rotateArr(arr, d,n); //printing the elements of the array for(int i =0;i<n;i++){ cout << arr[i] << " "; } cout << endl; } return 0; } // } Driver Code Ends
16.964912
48
0.463289
rishabhrathore055
40ab556d22b4cd023760f114b916061bc55a866a
1,204
cpp
C++
src/main/cpp/commands/SetBallHolder.cpp
Team7433/2021InfiniteRecharge
c14d3a06347cdafa22443298fdc12b9406bf6312
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/commands/SetBallHolder.cpp
Team7433/2021InfiniteRecharge
c14d3a06347cdafa22443298fdc12b9406bf6312
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/commands/SetBallHolder.cpp
Team7433/2021InfiniteRecharge
c14d3a06347cdafa22443298fdc12b9406bf6312
[ "BSD-3-Clause" ]
null
null
null
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include "commands/SetBallHolder.h" SetBallHolder::SetBallHolder(BallHolder * ballholder, double indexer, double magazine) { AddRequirements({ballholder}); m_indexerTarget = indexer; m_magazineTarget = magazine; m_ballholder = ballholder; } // Called when the command is initially scheduled. void SetBallHolder::Initialize() { m_ballholder->SetIndexer(m_indexerTarget); m_ballholder->SetMagazine(m_magazineTarget); } // Called repeatedly when this Command is scheduled to run void SetBallHolder::Execute() {} // Called once the command ends or is interrupted. void SetBallHolder::End(bool interrupted) {} // Returns true when the command should end. bool SetBallHolder::IsFinished() { return true; }
38.83871
88
0.596346
Team7433
40ab75dc84e001432a0e4b10fcfbe5fac78fc068
22,392
cpp
C++
emulator/src/mame/drivers/piratesh.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
1
2022-01-15T21:38:38.000Z
2022-01-15T21:38:38.000Z
emulator/src/mame/drivers/piratesh.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
emulator/src/mame/drivers/piratesh.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
// license:BSD-3-Clause /************************************************************************** Pirate Ship PWB(A)354460B MC68HC00FN16 054539 - 8-Channel ADPCM sound generator. Clock input 18.432MHz. Clock outputs 18.432/4 & 18.432/8 053250 - LVC road generator 053246A - Sprite generator 055673 - Sprite generator 055555 - Mixer/Priority encoder 056832 - Tilemap generator 054156 - Tilemap generator 053252 - CRTC 053250 config: SELC (69) GND SEL1 (83) GND SEL0 (82) GND MODE (68) GND TODO: Music stops if a coin is inserted. MAME or BTNAB? **************************************************************************/ #include "emu.h" #include "speaker.h" #include "video/k053250_ps.h" #include "machine/nvram.h" #include "machine/timer.h" #include "cpu/m68000/m68000.h" #include "sound/k054539.h" #include "includes/konamigx.h" // TODO: WHY? #include "video/konami_helper.h" #include "machine/ticket.h" #include "machine/gen_latch.h" #include "machine/k053252.h" #include "video/k055555.h" #include "video/k054000.h" #include "video/k053246_k053247_k055673.h" class piratesh_state : public driver_device { public: piratesh_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag), m_maincpu(*this,"maincpu"), m_k053250(*this, "k053250"), m_k053252(*this, "k053252"), m_k056832(*this, "k056832"), m_k055673(*this, "k055673"), m_k055555(*this, "k055555"), // m_k053246(*this, "k053246"), m_k054539(*this, "k054539"), m_spriteram(*this,"spriteram") { } required_device<cpu_device> m_maincpu; required_device<k053250ps_device> m_k053250; required_device<k053252_device> m_k053252; required_device<k056832_device> m_k056832; required_device<k055673_device> m_k055673; required_device<k055555_device> m_k055555; required_device<k054539_device> m_k054539; // required_device<k053247_device> m_k053246; optional_shared_ptr<uint16_t> m_spriteram; int m_layer_colorbase[6]; int m_sprite_colorbase; int m_lvc_colorbase; uint8_t m_int_enable; uint8_t m_int_status; uint8_t m_sound_ctrl; uint8_t m_sound_nmi_clk; uint16_t m_control; void update_interrupts(); DECLARE_READ16_MEMBER(K056832_rom_r); DECLARE_WRITE16_MEMBER(control1_w); DECLARE_WRITE16_MEMBER(control2_w); DECLARE_WRITE16_MEMBER(control3_w); DECLARE_WRITE16_MEMBER(irq_ack_w); DECLARE_READ16_MEMBER(k053247_scattered_word_r); DECLARE_WRITE16_MEMBER(k053247_scattered_word_w); DECLARE_READ16_MEMBER(k053247_martchmp_word_r); DECLARE_WRITE16_MEMBER(k053247_martchmp_word_w); DECLARE_CUSTOM_INPUT_MEMBER(helm_r); DECLARE_CUSTOM_INPUT_MEMBER(battery_r); DECLARE_MACHINE_START(piratesh); DECLARE_MACHINE_RESET(piratesh); DECLARE_VIDEO_START(piratesh); uint32_t screen_update_piratesh(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect); DECLARE_WRITE_LINE_MEMBER(k054539_nmi_gen); TIMER_DEVICE_CALLBACK_MEMBER(piratesh_interrupt); K056832_CB_MEMBER(piratesh_tile_callback); K055673_CB_MEMBER(piratesh_sprite_callback); void piratesh(machine_config &config); void piratesh_map(address_map &map); }; void piratesh_state::update_interrupts() { m_maincpu->set_input_line(M68K_IRQ_2, m_int_status & 2 ? ASSERT_LINE : CLEAR_LINE); // INT 1 m_maincpu->set_input_line(M68K_IRQ_4, m_int_status & 1 ? ASSERT_LINE : CLEAR_LINE); m_maincpu->set_input_line(M68K_IRQ_5, m_int_status & 4 ? ASSERT_LINE : CLEAR_LINE); } /* Priority issues: 1. On title screen, stars should be behind the helm 2. The Konami logo is a square transition 3. */ K056832_CB_MEMBER(piratesh_state::piratesh_tile_callback) { // Layer // Code // Color // Flags // if (*color != 0) // printf("%x %x %x\n", layer, *code, *color >> 2); *color = (m_layer_colorbase[layer] << 4) + ((*color >> 2));// & 0x0f); } K055673_CB_MEMBER(piratesh_state::piratesh_sprite_callback) { int c = *color; *color = (c & 0x001f); //int pri = (c >> 5) & 7; // .... .... ...x xxxx - Color // .... .... xxx. .... - Priority? // .... ..x. .... .... - ? // ..x. .... .... .... - ? #if 0 int layerpri[4]; static const int pris[4] = { K55_PRIINP_0, K55_PRIINP_3, K55_PRIINP_6, K55_PRIINP_7 }; for (uint32_t i = 0; i < 4; i++) { layerpri[i] = m_k055555->K055555_read_register(pris[i]); } // TODO: THIS IS ALL WRONG if (pri <= layerpri[0]) *priority_mask = 0; else if (pri <= layerpri[1]) *priority_mask = 0xf0; else if (pri <= layerpri[2]) *priority_mask = 0xf0|0xcc; else *priority_mask = 0xf0|0xcc|0xaa; #endif *priority_mask = 0; // 0 - Sprites over everything // f0 - // f0 cc - // f0 cc aa - // 1111 0000 // 1100 1100 // 1010 1010 } VIDEO_START_MEMBER(piratesh_state, piratesh) { // TODO: These come from the 055555 m_layer_colorbase[0] = 0; m_layer_colorbase[1] = 2; m_layer_colorbase[2] = 4; m_layer_colorbase[3] = 6; m_sprite_colorbase = 1; m_lvc_colorbase = 3; #if 0 konamigx_mixer_init(*m_screen, 0); m_k056832->set_layer_offs(0, -2+2-1, 0-1); m_k056832->set_layer_offs(1, 0+2, 0); m_k056832->set_layer_offs(2, 2+2, 0); m_k056832->set_layer_offs(3, 3+2, 0); #endif } uint32_t piratesh_state::screen_update_piratesh(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect) { bitmap.fill(0, cliprect); #if 1 int layers[4], layerpri[4]; static const int pris[4] = { K55_PRIINP_0, K55_PRIINP_3, K55_PRIINP_6, K55_PRIINP_7 }; static const int enables[4] = { K55_INP_VRAM_A, K55_INP_VRAM_B, K55_INP_VRAM_C, K55_INP_VRAM_D }; for (uint32_t i = 0; i < 4; i++) { layers[i] = i; layerpri[i] = m_k055555->K055555_read_register(pris[i]); } konami_sortlayers4(layers, layerpri); screen.priority().fill(0, cliprect); const uint32_t input_enables = m_k055555->K055555_read_register(K55_INPUT_ENABLES); // TODO: FIX COLORBASES if (input_enables & K55_INP_SUB3) m_k053250->draw(bitmap, cliprect, 0x20, 0, screen.priority(), 2); for (uint32_t i = 0; i < 4; i++) { if (input_enables & enables[layers[i]]) { m_k056832->tilemap_draw(screen, bitmap, cliprect, layers[i], 0, 1 << i); } } if (input_enables & K55_INP_SUB2) m_k055673->k053247_sprites_draw(bitmap, cliprect); #if 0 #define K55_INP_VRAM_A 0x01 #define K55_INP_VRAM_B 0x02 #define K55_INP_VRAM_C 0x04 #define K55_INP_VRAM_D 0x08 #define K55_INP_OBJ 0x10 #define K55_INP_SUB1 0x20 #define K55_INP_SUB2 0x40 #define K55_INP_SUB3 0x80 #endif //055555: 4 to reg 7 (A PRI 0) //055555: 0 to reg 8 (A PRI 1) //055555: 0 to reg 9 (A COLPRI) //055555: 6 to reg a (B PRI 0) //055555: 0 to reg b (B PRI 1) //055555: 0 to reg c (B COLPRI) //055555: 16 to reg d (C PRI) //055555: 18 to reg e (D PRI) //055555: 0 to reg 11 (SUB2 PRI) //055555: 0 to reg 12 (SUB3 PRI) //055555: 0 to reg 17 (A PAL) //055555: 2 to reg 18 (B PAL) //055555: 4 to reg 19 (C PAL) //055555: 6 to reg 1a (D PAL) //055555: 3 to reg 1d (SUB2 PAL) //055555: 1 to reg 1e (SUB3 PAL) #else // LAYER, FLAGS, PRIORITY m_k056832->tilemap_draw(screen, bitmap, cliprect, 3, K056832_DRAW_FLAG_MIRROR, 1); m_k056832->tilemap_draw(screen, bitmap, cliprect, 2, K056832_DRAW_FLAG_MIRROR, 2); // TODO: Fix priority m_k053250->draw(bitmap, cliprect, 0x20, 0, screen.priority(), 8); m_k055673->k053247_sprites_draw(bitmap, cliprect); m_k056832->tilemap_draw(screen, bitmap, cliprect, 1, K056832_DRAW_FLAG_MIRROR, 4); m_k056832->tilemap_draw(screen, bitmap, cliprect, 0, K056832_DRAW_FLAG_MIRROR, 0); #endif return 0; } /**********************************************************************************/ /* IRQ controllers */ TIMER_DEVICE_CALLBACK_MEMBER(piratesh_state::piratesh_interrupt) { int scanline = param; // IRQ2 - CCUINT1 (VBL START) // IRQ4 - Sound // IRQ5 - CCUINT2 (VBL END) if (scanline == 240) { m_k053250->vblank_w(1); if (m_int_enable & 2) { m_int_status |= 2; update_interrupts(); } } if (scanline == 0) { m_k053250->vblank_w(0); if (m_int_enable & 4) { m_int_status |= 4; update_interrupts(); } } } READ16_MEMBER(piratesh_state::K056832_rom_r) { uint16_t offs; offs = (m_control & 2 ? 0x1000 : 0) + offset; return m_k056832->piratesh_rom_r(space, offs, mem_mask); } WRITE16_MEMBER(piratesh_state::control1_w) { // .... ..xx .... .... - Unknown // .... .x.. .... .... - Unknown - Active during attract, clear during game // .... x... .... .... - Lamp? (active when waiting to start game) if (data & ~0x0f00) printf("CTRL3: %x %x %x\n", offset, data, mem_mask); } WRITE16_MEMBER(piratesh_state::control2_w) { // .... .... ...x .... - Unknown (always 1?) // .... .... ..x. .... - Unknown // .... .... .x.. .... - Counter out // .... .... x... .... - Counter in // .... ...x .... .... - 053246A OBJCRBK (Pin 9) // .... ..x. .... .... - LV related // .... x... .... .... - INT4/SND control (0=clear 1=enable) // ...x .... .... .... - INT2/CCUINT1 control (0=clear 1=enable) // ..x. .... .... .... - INT5/CCUINT2 control (0=clear 1=enable) // .x.. .... .... .... - Unknown // x... .... .... .... - Unknown m_int_enable = (data >> 11) & 7; m_int_status &= m_int_enable; update_interrupts(); if (data & ~0xfbf0) printf("CTRL2: %x %x %x\n", offset, data, mem_mask); } WRITE16_MEMBER(piratesh_state::control3_w) { // .... .... .... ...x - Watchdog? (051550?) // .... .... .... ..x. - 056832 ROM bank control // .... .... ...x .... - Ticket dispenser enable (active high) // .... .... ..x. .... - Hopper enable (active high) // .... ...x .... .... - Unknown (always 1?) if ((data & ~0x0133) || (~data & 0x100)) printf("CTRL1 W: %x %x %x\n", offset, data, mem_mask); // printf("CTRL 1: %x\n", data & 0x0010); machine().device<ticket_dispenser_device>("ticket")->motor_w(data & 0x0010 ? 1 : 0); machine().device<ticket_dispenser_device>("hopper")->motor_w(data & 0x0020 ? 1 : 0); m_control = data; } void piratesh_state::piratesh_map(address_map &map) { map(0x000000, 0x07ffff).rom(); map(0x080000, 0x083fff).ram().share("nvram"); map(0x084000, 0x087fff).ram(); map(0x100000, 0x10001f).rw(m_k053252, FUNC(k053252_device::read), FUNC(k053252_device::write)).umask16(0x00ff); // CRTC map(0x180000, 0x18003f).w(m_k056832, FUNC(k056832_device::word_w)); // TILEMAP map(0x280000, 0x280007).w(m_k055673, FUNC(k055673_device::k053246_word_w)); // SPRITES map(0x290000, 0x29000f).r(m_k055673, FUNC(k055673_device::k055673_ps_rom_word_r)); // SPRITES map(0x290010, 0x29001f).w(m_k055673, FUNC(k055673_device::k055673_reg_word_w)); // SPRITES map(0x2a0000, 0x2a0fff).rw(m_k055673, FUNC(k055673_device::k053247_word_r), FUNC(k055673_device::k053247_word_w)); // SPRITES map(0x2a1000, 0x2a3fff).nopw(); map(0x2b0000, 0x2b000f).rw(m_k053250, FUNC(k053250ps_device::reg_r), FUNC(k053250ps_device::reg_w)); // LVC map(0x300000, 0x3000ff).w(m_k055555, FUNC(k055555_device::K055555_word_w)); map(0x380000, 0x381fff).ram().w("palette", FUNC(palette_device::write16)).share("palette"); map(0x400000, 0x400001).portr("IN0"); map(0x400002, 0x400003).portr("IN1"); map(0x400004, 0x400005).portr("DSW1"); map(0x400006, 0x400007).portr("DSW2"); map(0x400008, 0x400009).portr("SPECIAL"); map(0x40000c, 0x40000d).w(this, FUNC(piratesh_state::control1_w)); map(0x400010, 0x400011).w(this, FUNC(piratesh_state::control2_w)); map(0x400014, 0x400015).w(this, FUNC(piratesh_state::control3_w)); map(0x500000, 0x50ffff).r(this, FUNC(piratesh_state::K056832_rom_r)); // VRAM ROM map(0x580000, 0x581fff).r(m_k053250, FUNC(k053250ps_device::rom_r)); // LVC ROM access map(0x600000, 0x6004ff).rw("k054539", FUNC(k054539_device::read), FUNC(k054539_device::write)).umask16(0xff00); // SOUND map(0x680000, 0x681fff).rw(m_k056832, FUNC(k056832_device::ram_word_r), FUNC(k056832_device::ram_word_w)); // TILEMAP map(0x700000, 0x703fff).rw(m_k053250, FUNC(k053250ps_device::ram_r), FUNC(k053250ps_device::ram_w)); // LVC } WRITE_LINE_MEMBER(piratesh_state::k054539_nmi_gen) { static int m_sound_intck = 0; // TODO: KILL ME // Trigger an interrupt on the rising edge if (!m_sound_intck && state) { if (m_int_enable & 1) { m_int_status |= 1; update_interrupts(); } } m_sound_intck = state; } CUSTOM_INPUT_MEMBER(piratesh_state::helm_r) { // Appears to be a quadrature encoder uint8_t xa, xb; uint16_t dx = ioport("HELM")->read(); xa = ((dx + 1) & 7) <= 3; xb = (dx & 7) <= 3; return (xb << 1) | xa; } CUSTOM_INPUT_MEMBER(piratesh_state::battery_r) { // .x MB3790 /ALARM1 // x. MB3790 /ALARM2 return 0x3; } /**********************************************************************************/ static INPUT_PORTS_START( piratesh ) PORT_START("IN0") PORT_BIT( 0x0001, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0002, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0004, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0008, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0010, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0020, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0040, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0080, IP_ACTIVE_LOW, IPT_BUTTON3 ) // 7f60 btst $7,$40000 PORT_BIT( 0x0100, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0200, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0400, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) // HELM? PORT_BIT( 0x0800, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) // HELM? PORT_BIT( 0x1000, IP_ACTIVE_LOW, IPT_SERVICE2 ) PORT_NAME("Reset") PORT_BIT( 0x2000, IP_ACTIVE_LOW, IPT_START ) PORT_BIT( 0x4000, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x8000, IP_ACTIVE_LOW, IPT_SERVICE ) PORT_NAME(DEF_STR( Test )) PORT_CODE(KEYCODE_F2) PORT_START("SPECIAL") PORT_BIT( 0x0100, IP_ACTIVE_HIGH, IPT_SPECIAL ) PORT_READ_LINE_DEVICE_MEMBER("k053250", k053250ps_device, dmairq_r) PORT_BIT( 0x0200, IP_ACTIVE_HIGH, IPT_UNKNOWN ) // FIXME: NCPU from 053246 (DMA) PORT_BIT( 0x0c00, IP_ACTIVE_HIGH, IPT_SPECIAL )PORT_CUSTOM_MEMBER(DEVICE_SELF, piratesh_state, battery_r, nullptr) PORT_START("HELM") PORT_BIT( 0xff, 0x00, IPT_DIAL ) PORT_SENSITIVITY(25) PORT_KEYDELTA(1) PORT_START("IN1") PORT_BIT( 0x0001, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0002, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0004, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0008, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0010, IP_ACTIVE_LOW, IPT_SERVICE1 ) PORT_NAME("Service") PORT_BIT( 0x0020, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0040, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0080, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0100, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0200, IP_ACTIVE_LOW, IPT_SPECIAL ) PORT_READ_LINE_DEVICE_MEMBER("ticket", ticket_dispenser_device, line_r) PORT_BIT( 0x0400, IP_ACTIVE_LOW, IPT_SPECIAL ) PORT_READ_LINE_DEVICE_MEMBER("hopper", ticket_dispenser_device, line_r) PORT_BIT( 0x1800, IP_ACTIVE_HIGH, IPT_SPECIAL )PORT_CUSTOM_MEMBER(DEVICE_SELF, piratesh_state, helm_r, nullptr) PORT_BIT( 0x2000, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x4000, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x8000, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START("DSW1") // TODO: DIP switches are used for settings when battery failure has occurred PORT_DIPNAME( 0x0100, 0x0100, "DSW1:0" ) PORT_DIPLOCATION("DSW1:1") PORT_DIPSETTING( 0x0100, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x0200, 0x0200, "DSW1:1" ) PORT_DIPLOCATION("DSW1:2") PORT_DIPSETTING( 0x0200, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x0400, 0x0400, "DSW1:2" ) PORT_DIPLOCATION("DSW1:3") PORT_DIPSETTING( 0x0400, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x0800, 0x0800, "DSW1:3" ) PORT_DIPLOCATION("DSW1:4") PORT_DIPSETTING( 0x0800, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x3000, 0x1000, DEF_STR( Difficulty ) ) PORT_DIPLOCATION("DSW1:5,6") PORT_DIPSETTING( 0x0000, "A" ) PORT_DIPSETTING( 0x1000, "B" ) PORT_DIPSETTING( 0x2000, "C" ) PORT_DIPSETTING( 0x3000, "D" ) PORT_DIPNAME( 0x4000, 0x4000, DEF_STR( Demo_Sounds ) ) PORT_DIPLOCATION("DSW1:7") PORT_DIPSETTING( 0x0000, DEF_STR( Off ) ) PORT_DIPSETTING( 0x4000, DEF_STR( On ) ) PORT_DIPNAME( 0x8000, 0x8000, DEF_STR( Free_Play ) ) PORT_DIPLOCATION("DSW1:8") PORT_DIPSETTING( 0x8000, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_START("DSW2") // TODO: Finish me PORT_DIPNAME( 0x0100, 0x0100, "DSW2:0" ) PORT_DIPLOCATION("DSW2:1") PORT_DIPSETTING( 0x0100, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x0200, 0x0200, "DSW2:1" ) PORT_DIPLOCATION("DSW2:2") PORT_DIPSETTING( 0x0200, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x0400, 0x0400, "DSW2:2" ) PORT_DIPLOCATION("DSW2:3") PORT_DIPSETTING( 0x0400, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x0800, 0x0800, "DSW2:3" ) PORT_DIPLOCATION("DSW2:4") PORT_DIPSETTING( 0x0800, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x1000, 0x1000, "DSW2:4" ) PORT_DIPLOCATION("DSW2:5") PORT_DIPSETTING( 0x1000, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x2000, 0x2000, "DSW2:5" ) PORT_DIPLOCATION("DSW2:6") PORT_DIPSETTING( 0x2000, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x4000, 0x4000, "DSW2:6" ) PORT_DIPLOCATION("DSW2:7") PORT_DIPSETTING( 0x4000, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x8000, 0x8000, "Redemption Type" ) PORT_DIPLOCATION("DSW2:8") PORT_DIPSETTING( 0x8000, "Ticket" ) PORT_DIPSETTING( 0x0000, "Capsule" ) INPUT_PORTS_END /**********************************************************************************/ MACHINE_START_MEMBER(piratesh_state, piratesh) { #if 0 m_sound_ctrl = 2; m_mw_irq_control = 0; /* konamigx_mixer uses this, so better initialize it */ m_gx_wrport1_0 = 0; save_item(NAME(m_mw_irq_control)); save_item(NAME(m_sound_ctrl)); save_item(NAME(m_sound_nmi_clk)); #endif } MACHINE_RESET_MEMBER(piratesh_state,piratesh) { m_int_status = 0; int i; // soften chorus(chip 0 channel 0-3), boost voice(chip 0 channel 4-7) for (i=0; i<=7; i++) { // m_k054539->set_gain(i, 0.5); } // // soften percussions(chip 1 channel 0-7) // for (i=0; i<=7; i++) m_k054539_2->set_gain(i, 0.5); } MACHINE_CONFIG_START(piratesh_state::piratesh) /* basic machine hardware */ MCFG_CPU_ADD("maincpu", M68000, XTAL(32'000'000)/2) MCFG_CPU_PROGRAM_MAP(piratesh_map) MCFG_TIMER_DRIVER_ADD_SCANLINE("scantimer", piratesh_state, piratesh_interrupt, "screen", 0, 1) MCFG_NVRAM_ADD_0FILL("nvram") MCFG_DEVICE_ADD("k053252", K053252, XTAL(32'000'000)/4) MCFG_K053252_OFFSETS(40, 16) // TODO MCFG_MACHINE_START_OVERRIDE(piratesh_state, piratesh) MCFG_MACHINE_RESET_OVERRIDE(piratesh_state, piratesh) MCFG_TICKET_DISPENSER_ADD("ticket", attotime::from_msec(200), TICKET_MOTOR_ACTIVE_HIGH, TICKET_STATUS_ACTIVE_HIGH) MCFG_TICKET_DISPENSER_ADD("hopper", attotime::from_msec(200), TICKET_MOTOR_ACTIVE_HIGH, TICKET_STATUS_ACTIVE_HIGH) /* video hardware */ MCFG_SCREEN_ADD("screen", RASTER) MCFG_SCREEN_VIDEO_ATTRIBUTES(VIDEO_UPDATE_AFTER_VBLANK) // MCFG_SCREEN_REFRESH_RATE(60) MCFG_SCREEN_RAW_PARAMS(6000000, 288+16+32+48, 0, 287, 224+16+8+16, 0, 223) // TODO MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(600)) MCFG_SCREEN_SIZE(64*8, 32*8) MCFG_SCREEN_VISIBLE_AREA(24, 24+288-1, 16, 16+224-1) MCFG_SCREEN_UPDATE_DRIVER(piratesh_state, screen_update_piratesh) MCFG_PALETTE_ADD("palette", 2048) MCFG_PALETTE_FORMAT(BGRX) MCFG_PALETTE_ENABLE_SHADOWS() MCFG_PALETTE_ENABLE_HILIGHTS() MCFG_DEVICE_ADD("k056832", K056832, 0) MCFG_K056832_CB(piratesh_state, piratesh_tile_callback) MCFG_K056832_CONFIG("gfx1", K056832_BPP_4PIRATESH, 1, 0, "none") MCFG_K056832_PALETTE("palette") MCFG_K055555_ADD("k055555") MCFG_K053250PS_ADD("k053250", "palette", "screen", -16, 0) MCFG_DEVICE_ADD("k055673", K055673, 0) MCFG_K055673_CB(piratesh_state, piratesh_sprite_callback) MCFG_K055673_CONFIG("gfx2", K055673_LAYOUT_PS, -60, 24) MCFG_K055673_PALETTE("palette") // ???? //MCFG_DEVICE_ADD("k053246", K053246, 0) //MCFG_K053246_CB(moo_state, sprite_callback) //MCFG_K053246_CONFIG("gfx2", NORMAL_PLANE_ORDER, -48+1, 23) //MCFG_K053246_PALETTE("palette") MCFG_DEVICE_ADD("k054338", K054338, 0) MCFG_K054338_ALPHAINV(1) MCFG_K054338_MIXER("k055555") MCFG_VIDEO_START_OVERRIDE(piratesh_state, piratesh) /* sound hardware */ MCFG_SPEAKER_STANDARD_STEREO("lspeaker", "rspeaker") MCFG_DEVICE_ADD("k054539", K054539, XTAL(18'432'000)) MCFG_K054539_TIMER_HANDLER(WRITELINE(piratesh_state, k054539_nmi_gen)) MCFG_SOUND_ROUTE(0, "lspeaker", 0.2) MCFG_SOUND_ROUTE(1, "rspeaker", 0.2) MACHINE_CONFIG_END ROM_START( piratesh ) ROM_REGION( 0x80000, "maincpu", 0 ) ROM_LOAD16_WORD_SWAP( "360ua-c04.4p", 0x000000, 0x80000, CRC(6d69dd90) SHA1(ccbdbfea406d9cbc3f242211290ba82ccbbe3795) ) /* tiles */ ROM_REGION( 0x80000, "gfx1", ROMREGION_ERASE00 ) // 27C4096 ROM_LOAD( "360ua-a01.17g", 0x000000, 0x80000, CRC(e39153f5) SHA1(5da9132a2c24a15b55c3f65c26e2ad0467411a88) ) /* sprites */ ROM_REGION( 0x80000*8, "gfx2", ROMREGION_ERASE00 ) // 27C4096 ROM_LOAD16_BYTE( "360ua-a02.21l", 0x000000, 0x80000, CRC(82207997) SHA1(fe143285a12fab5227e883113d798acad7bf4c97) ) ROM_LOAD16_BYTE( "360ua-a03.23l", 0x000001, 0x80000, CRC(a9e36d51) SHA1(1a8de8d8d2abfee5ac0f0822e203846f7f5f1767) ) /* road generator */ ROM_REGION( 0x080000, "k053250", ROMREGION_ERASE00 ) // 27C040 ROM_LOAD( "360ua-a05.26p", 0x000000, 0x80000, CRC(dab7f439) SHA1(2372612c0b04c77a85ccbadc100cb741b85f0481) ) /* sound data */ ROM_REGION( 0x100000, "k054539", 0 ) // 27C040 ROM_LOAD( "360ua-a06.15t", 0x000000, 0x80000, CRC(6816a493) SHA1(4fc4cfbc164d84bbf8d75ccd78c9f40f3273d852) ) ROM_LOAD( "360ua-a07.17t", 0x080000, 0x80000, CRC(af7127c5) SHA1(b525f3c6b831e3354eba46016d414bedcb3ae8dc) ) // ROM_REGION( 0x80, "eeprom", 0 ) // default eeprom to prevent game booting upside down with error // ROM_LOAD( "piratesh.nv", 0x0000, 0x080, CRC(28df2269) SHA1(3f071c97662745a199f96964e2e79f795bd5a391) ) ROM_END // year name parent machine input state init GAME( 1995, piratesh, 0, piratesh, piratesh, piratesh_state, 0, ROT90, "Konami", "Pirate Ship (ver UAA)", MACHINE_IMPERFECT_GRAPHICS )
32.736842
144
0.700429
rjw57
40ad55f29ea62bc0faf20b0fdd64a7ce4cc67377
3,654
cpp
C++
Implementation/Core/amc_parameterhandler.cpp
FabianSpangler/AutodeskMachineControlFramework
da257a4a609edbbdf3d7c5d834d61f8555c68e09
[ "BSD-3-Clause" ]
null
null
null
Implementation/Core/amc_parameterhandler.cpp
FabianSpangler/AutodeskMachineControlFramework
da257a4a609edbbdf3d7c5d834d61f8555c68e09
[ "BSD-3-Clause" ]
null
null
null
Implementation/Core/amc_parameterhandler.cpp
FabianSpangler/AutodeskMachineControlFramework
da257a4a609edbbdf3d7c5d834d61f8555c68e09
[ "BSD-3-Clause" ]
null
null
null
/*++ Copyright (C) 2020 Autodesk Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Autodesk Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AUTODESK INC. 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 "amc_parameterhandler.hpp" #include "libmc_interfaceexception.hpp" #define AMC_MAXPARAMETERGROUPCOUNT (1024 * 1024) namespace AMC { CParameterHandler::CParameterHandler() { m_DataStore = std::make_shared <CParameterGroup>(); } CParameterHandler::~CParameterHandler() { } bool CParameterHandler::hasGroup(const std::string& sName) { std::lock_guard <std::mutex> lockGuard(m_Mutex); auto iter = m_Groups.find(sName); return (iter != m_Groups.end()); } void CParameterHandler::addGroup(PParameterGroup pGroup) { std::lock_guard <std::mutex> lockGuard(m_Mutex); if (pGroup.get() == nullptr) throw ELibMCInterfaceException(LIBMC_ERROR_INVALIDPARAM); auto sName = pGroup->getName(); if (m_Groups.find(sName) != m_Groups.end()) throw ELibMCInterfaceException(LIBMC_ERROR_DUPLICATEPARAMETERGROUPNAME); if (m_GroupList.size() >= AMC_MAXPARAMETERGROUPCOUNT) throw ELibMCInterfaceException(LIBMC_ERROR_TOOMANYPARAMETERGROUPS); m_Groups.insert(std::make_pair(sName, pGroup)); m_GroupList.push_back(pGroup); } PParameterGroup CParameterHandler::addGroup(const std::string& sName, const std::string& sDescription) { PParameterGroup pGroup = std::make_shared<CParameterGroup>(sName, sDescription); addGroup(pGroup); return pGroup; } uint32_t CParameterHandler::getGroupCount() { std::lock_guard <std::mutex> lockGuard(m_Mutex); return (uint32_t)m_GroupList.size(); } CParameterGroup* CParameterHandler::getGroup(const uint32_t nIndex) { std::lock_guard <std::mutex> lockGuard(m_Mutex); if (nIndex >= m_GroupList.size()) throw ELibMCInterfaceException(LIBMC_ERROR_INVALIDINDEX); return m_GroupList[nIndex].get(); } CParameterGroup* CParameterHandler::findGroup(const std::string& sName, const bool bFailIfNotExisting) { std::lock_guard <std::mutex> lockGuard(m_Mutex); auto iter = m_Groups.find(sName); if (iter != m_Groups.end()) return iter->second.get(); if (bFailIfNotExisting) throw ELibMCInterfaceException(LIBMC_ERROR_PARAMETERGROUPNOTFOUND); return nullptr; } CParameterGroup* CParameterHandler::getDataStore() { return m_DataStore.get(); } }
28.771654
103
0.769294
FabianSpangler
40ad9f8285dc3f4a13de6f5d963eafac52603fdd
36,721
cpp
C++
OREData/test/commodityvolcurve.cpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
335
2016-10-07T16:31:10.000Z
2022-03-02T07:12:03.000Z
OREData/test/commodityvolcurve.cpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
59
2016-10-31T04:20:24.000Z
2022-01-03T16:39:57.000Z
OREData/test/commodityvolcurve.cpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
180
2016-10-08T14:23:50.000Z
2022-03-28T10:43:05.000Z
/* Copyright (C) 2018 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at <http://opensourcerisk.org> This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ // clang-format off #include <boost/test/unit_test.hpp> #include <boost/test/data/test_case.hpp> // clang-format on #include <oret/datapaths.hpp> #include <oret/toplevelfixture.hpp> #include <boost/make_shared.hpp> #include <cmath> #include <ored/configuration/curveconfigurations.hpp> #include <ored/marketdata/commodityvolcurve.hpp> #include <ored/marketdata/csvloader.hpp> #include <ored/marketdata/curvespec.hpp> #include <ored/marketdata/loader.hpp> #include <ored/marketdata/todaysmarket.hpp> #include <ored/utilities/csvfilereader.hpp> #include <ored/utilities/parsers.hpp> #include <ored/utilities/to_string.hpp> #include <ql/termstructures/volatility/equityfx/blackvariancesurface.hpp> #include <qle/termstructures/aposurface.hpp> #include <qle/termstructures/blackvariancesurfacesparse.hpp> #include <qle/termstructures/blackvolsurfacedelta.hpp> #include <qle/termstructures/blackvolsurfacewithatm.hpp> using namespace std; using namespace boost::unit_test_framework; using namespace QuantLib; using namespace QuantExt; using namespace ore::data; namespace bdata = boost::unit_test::data; namespace { // testTolerance for Real comparison Real testTolerance = 1e-10; class MockLoader : public Loader { public: MockLoader(); const vector<boost::shared_ptr<MarketDatum>>& loadQuotes(const Date&) const { return data_; } const boost::shared_ptr<MarketDatum>& get(const string& name, const Date&) const { return dummyDatum_; } const vector<Fixing>& loadFixings() const { return dummyFixings_; } const vector<Fixing>& loadDividends() const { return dummyDividends_; } void add(QuantLib::Date date, const string& name, QuantLib::Real value) {} void addFixing(QuantLib::Date date, const string& name, QuantLib::Real value) {} void addDividend(Date date, const string& name, Real value) {} private: vector<boost::shared_ptr<MarketDatum>> data_; boost::shared_ptr<MarketDatum> dummyDatum_; vector<Fixing> dummyFixings_; vector<Fixing> dummyDividends_; }; MockLoader::MockLoader() { Date asof(5, Feb, 2016); data_ = { boost::make_shared<CommodityOptionQuote>(0.11, asof, "COMMODITY_OPTION/RATE_LNVOL/GOLD/USD/1Y/ATM/AtmFwd", MarketDatum::QuoteType::RATE_LNVOL, "GOLD", "USD", boost::make_shared<ExpiryPeriod>(1 * Years), boost::make_shared<AtmStrike>(DeltaVolQuote::AtmFwd)), boost::make_shared<CommodityOptionQuote>(0.10, asof, "COMMODITY_OPTION/RATE_LNVOL/GOLD/USD/2Y/ATM/AtmFwd", MarketDatum::QuoteType::RATE_LNVOL, "GOLD", "USD", boost::make_shared<ExpiryPeriod>(2 * Years), boost::make_shared<AtmStrike>(DeltaVolQuote::AtmFwd)), boost::make_shared<CommodityOptionQuote>(0.09, asof, "COMMODITY_OPTION/RATE_LNVOL/GOLD/USD/5Y/ATM/AtmFwd", MarketDatum::QuoteType::RATE_LNVOL, "GOLD", "USD", boost::make_shared<ExpiryPeriod>(5 * Years), boost::make_shared<AtmStrike>(DeltaVolQuote::AtmFwd)), boost::make_shared<CommodityOptionQuote>( 0.105, asof, "COMMODITY_OPTION/RATE_LNVOL/GOLD_USD_VOLS/USD/1Y/1150", MarketDatum::QuoteType::RATE_LNVOL, "GOLD", "USD", boost::make_shared<ExpiryPeriod>(1 * Years), boost::make_shared<AbsoluteStrike>(1150)), boost::make_shared<CommodityOptionQuote>( 0.115, asof, "COMMODITY_OPTION/RATE_LNVOL/GOLD_USD_VOLS/USD/1Y/1190", MarketDatum::QuoteType::RATE_LNVOL, "GOLD", "USD", boost::make_shared<ExpiryPeriod>(1 * Years), boost::make_shared<AbsoluteStrike>(1190)), boost::make_shared<CommodityOptionQuote>( 0.095, asof, "COMMODITY_OPTION/RATE_LNVOL/GOLD_USD_VOLS/USD/2Y/1150", MarketDatum::QuoteType::RATE_LNVOL, "GOLD", "USD", boost::make_shared<ExpiryPeriod>(2 * Years), boost::make_shared<AbsoluteStrike>(1150)), boost::make_shared<CommodityOptionQuote>( 0.105, asof, "COMMODITY_OPTION/RATE_LNVOL/GOLD_USD_VOLS/USD/2Y/1190", MarketDatum::QuoteType::RATE_LNVOL, "GOLD", "USD", boost::make_shared<ExpiryPeriod>(2 * Years), boost::make_shared<AbsoluteStrike>(1190)), boost::make_shared<CommodityOptionQuote>( 0.085, asof, "COMMODITY_OPTION/RATE_LNVOL/GOLD_USD_VOLS/USD/5Y/1150", MarketDatum::QuoteType::RATE_LNVOL, "GOLD", "USD", boost::make_shared<ExpiryPeriod>(5 * Years), boost::make_shared<AbsoluteStrike>(1150)), boost::make_shared<CommodityOptionQuote>( 0.095, asof, "COMMODITY_OPTION/RATE_LNVOL/GOLD_USD_VOLS/USD/5Y/1190", MarketDatum::QuoteType::RATE_LNVOL, "GOLD", "USD", boost::make_shared<ExpiryPeriod>(5 * Years), boost::make_shared<AbsoluteStrike>(1190))}; } boost::shared_ptr<TodaysMarket> createTodaysMarket(const Date& asof, const string& inputDir, const string& curveConfigFile, const string& marketFile = "market.txt", const string& fixingsFile = "fixings.txt") { auto conventions = boost::make_shared<Conventions>(); conventions->fromFile(TEST_INPUT_FILE(string(inputDir + "/conventions.xml"))); auto curveConfigs = boost::make_shared<CurveConfigurations>(); curveConfigs->fromFile(TEST_INPUT_FILE(string(inputDir + "/" + curveConfigFile))); auto todaysMarketParameters = boost::make_shared<TodaysMarketParameters>(); todaysMarketParameters->fromFile(TEST_INPUT_FILE(string(inputDir + "/todaysmarket.xml"))); auto loader = boost::make_shared<CSVLoader>(TEST_INPUT_FILE(string(inputDir + "/" + marketFile)), TEST_INPUT_FILE(string(inputDir + "/" + fixingsFile)), false); return boost::make_shared<TodaysMarket>(asof, todaysMarketParameters, loader, curveConfigs, conventions); } // clang-format off // NYMEX input volatility data that is provided in the input market data file struct NymexVolatilityData { vector<Date> expiries; map<Date, vector<Real>> strikes; map<Date, vector<Real>> volatilities; map<Date, Real> atmVolatilities; NymexVolatilityData() { expiries = { Date(17, Oct, 2019), Date(16, Dec, 2019), Date(17, Mar, 2020) }; strikes = { { Date(17, Oct, 2019), { 60, 61, 62 } }, { Date(16, Dec, 2019), { 59, 60, 61 } }, { Date(17, Mar, 2020), { 57, 58, 59 } } }; volatilities = { { Date(17, Oct, 2019), { 0.4516, 0.4558, 0.4598 } }, { Date(16, Dec, 2019), { 0.4050, 0.4043, 0.4041 } }, { Date(17, Mar, 2020), { 0.3599, 0.3573, 0.3545 } } }; atmVolatilities = { { Date(17, Oct, 2019), 0.4678 }, { Date(16, Dec, 2019), 0.4353 }, { Date(17, Mar, 2020), 0.3293 } }; } }; // clang-format on } // namespace BOOST_FIXTURE_TEST_SUITE(OREDataTestSuite, ore::test::TopLevelFixture) BOOST_AUTO_TEST_SUITE(CommodityVolCurveTests) BOOST_AUTO_TEST_CASE(testCommodityVolCurveTypeConstant) { BOOST_TEST_MESSAGE("Testing commodity vol curve building with a single configured volatility"); // As of date Date asof(5, Feb, 2016); // Constant volatility config auto cvc = boost::make_shared<ConstantVolatilityConfig>("COMMODITY_OPTION/RATE_LNVOL/GOLD/USD/2Y/ATM/AtmFwd"); // Volatility configuration with a single quote boost::shared_ptr<CommodityVolatilityConfig> curveConfig = boost::make_shared<CommodityVolatilityConfig>("GOLD_USD_VOLS", "", "USD", cvc, "A365", "NullCalendar"); // Curve configurations CurveConfigurations curveConfigs; curveConfigs.commodityVolatilityConfig("GOLD_USD_VOLS") = curveConfig; // Commodity curve spec CommodityVolatilityCurveSpec curveSpec("USD", "GOLD_USD_VOLS"); // Market data loader MockLoader loader; // Empty Conventions Conventions conventions; // Check commodity volatility construction works boost::shared_ptr<CommodityVolCurve> curve; BOOST_CHECK_NO_THROW(curve = boost::make_shared<CommodityVolCurve>(asof, curveSpec, loader, curveConfigs, conventions)); // Check volatilities are all equal to the configured volatility regardless of strike and expiry Real configuredVolatility = 0.10; boost::shared_ptr<BlackVolTermStructure> volatility = curve->volatility(); BOOST_CHECK_CLOSE(volatility->blackVol(0.25, 1000.0), configuredVolatility, testTolerance); BOOST_CHECK_CLOSE(volatility->blackVol(0.25, 1200.0), configuredVolatility, testTolerance); BOOST_CHECK_CLOSE(volatility->blackVol(asof + 3 * Months, 1000.0), configuredVolatility, testTolerance); BOOST_CHECK_CLOSE(volatility->blackVol(asof + 3 * Months, 1200.0), configuredVolatility, testTolerance); BOOST_CHECK_CLOSE(volatility->blackVol(50.0, 1000.0), configuredVolatility, testTolerance); BOOST_CHECK_CLOSE(volatility->blackVol(50.0, 1200.0), configuredVolatility, testTolerance); BOOST_CHECK_CLOSE(volatility->blackVol(asof + 50 * Years, 1000.0), configuredVolatility, testTolerance); BOOST_CHECK_CLOSE(volatility->blackVol(asof + 50 * Years, 1200.0), configuredVolatility, testTolerance); } BOOST_AUTO_TEST_CASE(testCommodityVolCurveTypeCurve) { BOOST_TEST_MESSAGE("Testing commodity vol curve building with time dependent volatilities"); // As of date Date asof(5, Feb, 2016); // Quotes for the volatility curve vector<string> quotes{"COMMODITY_OPTION/RATE_LNVOL/GOLD/USD/1Y/ATM/AtmFwd", "COMMODITY_OPTION/RATE_LNVOL/GOLD/USD/2Y/ATM/AtmFwd", "COMMODITY_OPTION/RATE_LNVOL/GOLD/USD/5Y/ATM/AtmFwd"}; // Volatility curve config with linear interpolation and flat extrapolation. auto vcc = boost::make_shared<VolatilityCurveConfig>(quotes, "Linear", "Flat"); // Commodity volatility configuration with time dependent volatilities boost::shared_ptr<CommodityVolatilityConfig> curveConfig = boost::make_shared<CommodityVolatilityConfig>("GOLD_USD_VOLS", "", "USD", vcc, "A365", "NullCalendar"); // Curve configurations CurveConfigurations curveConfigs; curveConfigs.commodityVolatilityConfig("GOLD_USD_VOLS") = curveConfig; // Commodity curve spec CommodityVolatilityCurveSpec curveSpec("USD", "GOLD_USD_VOLS"); // Market data loader MockLoader loader; // Empty Conventions Conventions conventions; // Check commodity volatility construction works boost::shared_ptr<CommodityVolCurve> curve; BOOST_CHECK_NO_THROW(curve = boost::make_shared<CommodityVolCurve>(asof, curveSpec, loader, curveConfigs, conventions)); // Check time depending volatilities are as expected boost::shared_ptr<BlackVolTermStructure> volatility = curve->volatility(); Real configuredVolatility; // Check configured pillar points: { (1Y, 0.11), (2Y, 0.10), (5Y, 0.09) } // Check also strike independence configuredVolatility = 0.11; BOOST_CHECK_CLOSE(volatility->blackVol(asof + 1 * Years, 1000.0), configuredVolatility, testTolerance); BOOST_CHECK_CLOSE(volatility->blackVol(asof + 1 * Years, 1200.0), configuredVolatility, testTolerance); configuredVolatility = 0.10; BOOST_CHECK_CLOSE(volatility->blackVol(asof + 2 * Years, 1000.0), configuredVolatility, testTolerance); BOOST_CHECK_CLOSE(volatility->blackVol(asof + 2 * Years, 1200.0), configuredVolatility, testTolerance); configuredVolatility = 0.09; BOOST_CHECK_CLOSE(volatility->blackVol(asof + 5 * Years, 1000.0), configuredVolatility, testTolerance); BOOST_CHECK_CLOSE(volatility->blackVol(asof + 5 * Years, 1200.0), configuredVolatility, testTolerance); // Check briefly the default linear interpolation and extrapolation Time t_s = volatility->dayCounter().yearFraction(asof, asof + 2 * Years); Real v_s = 0.10; Time t_e = volatility->dayCounter().yearFraction(asof, asof + 5 * Years); Real v_e = 0.09; // at 3 years Time t = volatility->dayCounter().yearFraction(asof, asof + 3 * Years); Real v = sqrt((v_s * v_s * t_s + (v_e * v_e * t_e - v_s * v_s * t_s) * (t - t_s) / (t_e - t_s)) / t); BOOST_CHECK_CLOSE(volatility->blackVol(asof + 3 * Years, 1000.0), v, testTolerance); BOOST_CHECK_CLOSE(volatility->blackVol(asof + 3 * Years, 1200.0), v, testTolerance); // at 6 years, extrapolation is with a flat vol BOOST_CHECK_CLOSE(volatility->blackVol(asof + 6 * Years, 1000.0), v_e, testTolerance); BOOST_CHECK_CLOSE(volatility->blackVol(asof + 6 * Years, 1200.0), v_e, testTolerance); } BOOST_AUTO_TEST_CASE(testCommodityVolCurveTypeSurface) { BOOST_TEST_MESSAGE("Testing commodity vol curve building with time and strike dependent volatilities"); // As of date Date asof(5, Feb, 2016); // Volatility configuration with expiry period vs. absolute strike matrix. Bilinear interpolation and flat // extrapolation. vector<string> strikes{"1150", "1190"}; vector<string> expiries{"1Y", "2Y", "5Y"}; auto vssc = boost::make_shared<VolatilityStrikeSurfaceConfig>(strikes, expiries, "Linear", "Linear", true, "Flat", "Flat"); // Commodity volatility configuration boost::shared_ptr<CommodityVolatilityConfig> curveConfig = boost::make_shared<CommodityVolatilityConfig>("GOLD_USD_VOLS", "", "USD", vssc, "A365", "NullCalendar"); // Curve configurations CurveConfigurations curveConfigs; curveConfigs.commodityVolatilityConfig("GOLD_USD_VOLS") = curveConfig; // Commodity curve spec CommodityVolatilityCurveSpec curveSpec("USD", "GOLD_USD_VOLS"); // Market data loader MockLoader loader; // Empty Conventions Conventions conventions; // Check commodity volatility construction works boost::shared_ptr<CommodityVolCurve> curve; BOOST_CHECK_NO_THROW(curve = boost::make_shared<CommodityVolCurve>(asof, curveSpec, loader, curveConfigs, conventions)); // Check time and strike depending volatilities are as expected boost::shared_ptr<BlackVolTermStructure> volatility = curve->volatility(); // Check configured pillar points BOOST_CHECK_CLOSE(volatility->blackVol(asof + 1 * Years, 1150.0), 0.105, testTolerance); BOOST_CHECK_CLOSE(volatility->blackVol(asof + 1 * Years, 1190.0), 0.115, testTolerance); BOOST_CHECK_CLOSE(volatility->blackVol(asof + 2 * Years, 1150.0), 0.095, testTolerance); BOOST_CHECK_CLOSE(volatility->blackVol(asof + 2 * Years, 1190.0), 0.105, testTolerance); BOOST_CHECK_CLOSE(volatility->blackVol(asof + 5 * Years, 1150.0), 0.085, testTolerance); BOOST_CHECK_CLOSE(volatility->blackVol(asof + 5 * Years, 1190.0), 0.095, testTolerance); } BOOST_AUTO_TEST_CASE(testCommodityVolSurfaceWildcardExpiriesWildcardStrikes) { // Testing commodity volatility curve building wildcard expiries and strikes in configuration and more than one // set of commodity volatility quotes in the market data. In particular, the market data in the wildcard_data // folder has commodity volatility data for two surfaces NYMEX:CL and ICE:B. Check here that the commodity // volatility curve building for NYMEX:CL uses only the 9 NYMEX:CL quotes - 3 tenors, each with 3 strikes. BOOST_TEST_MESSAGE("Testing commodity volatility curve building wildcard expiries and strikes in configuration"); auto todaysMarket = createTodaysMarket(Date(16, Sep, 2019), "wildcard_data", "curveconfig_surface_wc_expiries_wc_strikes.xml"); auto vts = todaysMarket->commodityVolatility("NYMEX:CL"); // Wildcards in configuration so we know that a BlackVarianceSurfaceSparse has been created and fed to a // BlackVolatilityWithATM surface in TodaysMarket auto tmSurface = boost::dynamic_pointer_cast<BlackVolatilityWithATM>(*vts); BOOST_REQUIRE_MESSAGE(tmSurface, "Expected the commodity vol structure in TodaysMarket" << " to be of type BlackVolatilityWithATM"); auto surface = boost::dynamic_pointer_cast<BlackVarianceSurfaceSparse>(tmSurface->surface()); BOOST_REQUIRE_MESSAGE(tmSurface, "Expected the commodity vol structure in TodaysMarket to contain" << " a surface of type BlackVarianceSurfaceSparse"); // The expected NYMEX CL volatility data NymexVolatilityData expData; // Check what is loaded against expected data as provided in market data file for NYMEX:CL. // Note: the BlackVarianceSurfaceSparse adds a dummy expiry slice at time zero BOOST_REQUIRE_EQUAL(surface->expiries().size() - 1, expData.expiries.size()); for (Size i = 0; i < expData.strikes.size(); i++) { BOOST_CHECK_EQUAL(surface->expiries()[i + 1], expData.expiries[i]); } BOOST_REQUIRE_EQUAL(surface->strikes().size() - 1, expData.strikes.size()); for (Size i = 0; i < expData.strikes.size(); i++) { // Check the strikes against the input Date e = expData.expiries[i]; BOOST_REQUIRE_EQUAL(surface->strikes()[i + 1].size(), expData.strikes[e].size()); for (Size j = 0; j < surface->strikes()[i + 1].size(); j++) { BOOST_CHECK_CLOSE(expData.strikes[e][j], surface->strikes()[i + 1][j], 1e-12); } // Check the volatilities against the input BOOST_REQUIRE_EQUAL(surface->values()[i + 1].size(), expData.volatilities[e].size()); for (Size j = 0; j < surface->values()[i + 1].size(); j++) { BOOST_CHECK_CLOSE(expData.volatilities[e][j], surface->blackVol(e, surface->strikes()[i + 1][j]), 1e-12); } } } BOOST_AUTO_TEST_CASE(testCommodityVolSurfaceWildcardExpiriesExplicitStrikes) { BOOST_TEST_MESSAGE( "Testing commodity volatility curve building wildcard expiries and explicit strikes in configuration"); auto todaysMarket = createTodaysMarket(Date(16, Sep, 2019), "wildcard_data", "curveconfig_surface_wc_expiries_explicit_strikes.xml"); auto vts = todaysMarket->commodityVolatility("NYMEX:CL"); // Wildcards in configuration so we know that a BlackVarianceSurfaceSparse has been created and fed to a // BlackVolatilityWithATM surface in TodaysMarket auto tmSurface = boost::dynamic_pointer_cast<BlackVolatilityWithATM>(*vts); BOOST_REQUIRE_MESSAGE(tmSurface, "Expected the commodity vol structure in TodaysMarket" << " to be of type BlackVolatilityWithATM"); auto surface = boost::dynamic_pointer_cast<BlackVarianceSurfaceSparse>(tmSurface->surface()); BOOST_REQUIRE_MESSAGE(tmSurface, "Expected the commodity vol structure in TodaysMarket to contain" << " a surface of type BlackVarianceSurfaceSparse"); // The expected NYMEX CL volatility data NymexVolatilityData expData; // Check what is loaded against expected data as provided in market data file for NYMEX:CL. The explicit strikes // that we have chosen lead have only two corresponding expiries i.e. 2019-10-17 and 2019-12-16 // Note: the BlackVarianceSurfaceSparse adds a dummy expiry slice at time zero vector<Date> expExpiries{Date(17, Oct, 2019), Date(16, Dec, 2019)}; BOOST_REQUIRE_EQUAL(surface->expiries().size() - 1, expExpiries.size()); for (Size i = 0; i < expExpiries.size(); i++) { BOOST_CHECK_EQUAL(surface->expiries()[i + 1], expExpiries[i]); } // The explicit strikes in the config are 60 and 61 vector<Real> expStrikes{60, 61}; BOOST_REQUIRE_EQUAL(surface->strikes().size() - 1, expExpiries.size()); for (Size i = 0; i < expExpiries.size(); i++) { // Check the strikes against the expected explicit strikes BOOST_REQUIRE_EQUAL(surface->strikes()[i + 1].size(), expStrikes.size()); for (Size j = 0; j < surface->strikes()[i + 1].size(); j++) { BOOST_CHECK_CLOSE(expStrikes[j], surface->strikes()[i + 1][j], 1e-12); } // Check the volatilities against the input Date e = expExpiries[i]; BOOST_REQUIRE_EQUAL(surface->values()[i + 1].size(), expStrikes.size()); for (Size j = 0; j < surface->values()[i + 1].size(); j++) { // Find the index of the explicit strike in the input data Real expStrike = expStrikes[j]; auto it = find_if(expData.strikes[e].begin(), expData.strikes[e].end(), [expStrike](Real s) { return close(expStrike, s); }); BOOST_REQUIRE_MESSAGE(it != expData.strikes[e].end(), "Strike not found in input strikes"); auto idx = distance(expData.strikes[e].begin(), it); BOOST_CHECK_CLOSE(expData.volatilities[e][idx], surface->blackVol(e, surface->strikes()[i + 1][j]), 1e-12); } } } BOOST_AUTO_TEST_CASE(testCommodityVolSurfaceExplicitExpiriesWildcardStrikes) { BOOST_TEST_MESSAGE( "Testing commodity volatility curve building explicit expiries and wildcard strikes in configuration"); auto todaysMarket = createTodaysMarket(Date(16, Sep, 2019), "wildcard_data", "curveconfig_surface_explicit_expiries_wc_strikes.xml"); auto vts = todaysMarket->commodityVolatility("NYMEX:CL"); // Wildcards in configuration so we know that a BlackVarianceSurfaceSparse has been created and fed to a // BlackVolatilityWithATM surface in TodaysMarket auto tmSurface = boost::dynamic_pointer_cast<BlackVolatilityWithATM>(*vts); BOOST_REQUIRE_MESSAGE(tmSurface, "Expected the commodity vol structure in TodaysMarket" << " to be of type BlackVolatilityWithATM"); auto surface = boost::dynamic_pointer_cast<BlackVarianceSurfaceSparse>(tmSurface->surface()); BOOST_REQUIRE_MESSAGE(tmSurface, "Expected the commodity vol structure in TodaysMarket to contain" << " a surface of type BlackVarianceSurfaceSparse"); // The expected NYMEX CL volatility data NymexVolatilityData expData; // Check what is loaded against expected data as provided in market data file for NYMEX:CL. // We have chosen the explicit expiries 2019-10-17 and 2019-12-16 // Note: the BlackVarianceSurfaceSparse adds a dummy expiry slice at time zero vector<Date> expExpiries{Date(17, Oct, 2019), Date(16, Dec, 2019)}; BOOST_REQUIRE_EQUAL(surface->expiries().size() - 1, expExpiries.size()); for (Size i = 0; i < expExpiries.size(); i++) { BOOST_CHECK_EQUAL(surface->expiries()[i + 1], expExpiries[i]); } BOOST_REQUIRE_EQUAL(surface->strikes().size() - 1, expExpiries.size()); for (Size i = 0; i < expExpiries.size(); i++) { // Check the strikes against the input Date e = expExpiries[i]; BOOST_REQUIRE_EQUAL(surface->strikes()[i + 1].size(), expData.strikes[e].size()); for (Size j = 0; j < surface->strikes()[i + 1].size(); j++) { BOOST_CHECK_CLOSE(expData.strikes[e][j], surface->strikes()[i + 1][j], 1e-12); } // Check the volatilities against the input BOOST_REQUIRE_EQUAL(surface->values()[i + 1].size(), expData.volatilities[e].size()); for (Size j = 0; j < surface->values()[i + 1].size(); j++) { BOOST_CHECK_CLOSE(expData.volatilities[e][j], surface->blackVol(e, surface->strikes()[i + 1][j]), 1e-12); } } } BOOST_AUTO_TEST_CASE(testCommodityVolSurfaceExplicitExpiriesExplicitStrikes) { BOOST_TEST_MESSAGE( "Testing commodity volatility curve building explicit expiries and explicit strikes in configuration"); auto todaysMarket = createTodaysMarket(Date(16, Sep, 2019), "wildcard_data", "curveconfig_surface_explicit_expiries_explicit_strikes.xml"); auto vts = todaysMarket->commodityVolatility("NYMEX:CL"); // The expected NYMEX CL volatility data NymexVolatilityData expData; // We have provided two explicit expiries, 2019-10-17 and 2019-12-16, and two explicit strikes, 60 and 61. // We check the volatility term structure at these 4 points against the input data vector<Date> expExpiries{Date(17, Oct, 2019), Date(16, Dec, 2019)}; vector<Real> expStrikes{60, 61}; for (const Date& e : expExpiries) { for (Real s : expStrikes) { // Find the index of the explicit strike in the input data auto it = find_if(expData.strikes[e].begin(), expData.strikes[e].end(), [s](Real strike) { return close(strike, s); }); BOOST_REQUIRE_MESSAGE(it != expData.strikes[e].end(), "Strike not found in input strikes"); auto idx = distance(expData.strikes[e].begin(), it); Real inputVol = expData.volatilities[e][idx]; BOOST_CHECK_CLOSE(inputVol, vts->blackVol(e, s), 1e-12); } } } // As of dates for delta surface building below. // 15 Jan is when c1 contract rolls from NYMEX WTI Feb option contract to NYMEX WTI Mar option contract vector<Date> asofDates{Date(13, Jan, 2020), Date(15, Jan, 2020)}; // Different curve configurations for the surface building below. vector<string> curveConfigs{"curveconfig_explicit_expiries.xml", "curveconfig_wildcard_expiries.xml"}; BOOST_DATA_TEST_CASE(testCommodityVolDeltaSurface, bdata::make(asofDates) * bdata::make(curveConfigs), asof, curveConfig) { BOOST_TEST_MESSAGE("Testing commodity volatility delta surface building"); auto todaysMarket = createTodaysMarket(asof, "delta_surface", curveConfig, "market.txt"); // Get the built commodity volatility surface auto vts = todaysMarket->commodityVolatility("NYMEX:CL"); // Cast to expected type and check that it succeeds // For some reason, todaysmarket wraps the surface built in CommodityVolCurve in a BlackVolatilityWithATM. auto bvwa = dynamic_pointer_cast<BlackVolatilityWithATM>(*vts); BOOST_REQUIRE(bvwa); auto bvsd = boost::dynamic_pointer_cast<BlackVolatilitySurfaceDelta>(bvwa->surface()); BOOST_REQUIRE(bvsd); // Tolerance for float comparison Real tol = 1e-12; // Read in the expected on-grid results for the given date. string filename = "delta_surface/expected_grid_" + to_string(io::iso_date(asof)) + ".csv"; CSVFileReader reader(TEST_INPUT_FILE(filename), true, ","); BOOST_REQUIRE_EQUAL(reader.numberOfColumns(), 3); while (reader.next()) { // Get the expected expiry date, strike and volatility grid point Date expiryDate = parseDate(reader.get(0)); Real strike = parseReal(reader.get(1)); Real volatility = parseReal(reader.get(2)); // Check that the expected grid expiry date is one of the surface dates auto itExpiry = find(bvsd->dates().begin(), bvsd->dates().end(), expiryDate); BOOST_REQUIRE(itExpiry != bvsd->dates().end()); // Get the smile section, cast to expected type and check cast succeeds. auto fxss = bvsd->blackVolSmile(expiryDate); auto iss = boost::dynamic_pointer_cast<InterpolatedSmileSection>(fxss); BOOST_REQUIRE(iss); // Check that the expected grid strike is one of the smile section strikes. auto itStrike = find_if(iss->strikes().begin(), iss->strikes().end(), [&](Real s) { return std::abs(s - strike) < tol; }); BOOST_REQUIRE(itStrike != iss->strikes().end()); // Check that the expected volatility is equal to that at the grid strike auto pos = distance(iss->strikes().begin(), itStrike); BOOST_CHECK_SMALL(volatility - iss->volatilities()[pos], tol); } // Check flat time extrapolation auto fxss = bvsd->blackVolSmile(bvsd->dates().back()); auto iss = boost::dynamic_pointer_cast<InterpolatedSmileSection>(fxss); BOOST_REQUIRE(iss); vector<Real> lastVolatilities = iss->volatilities(); fxss = bvsd->blackVolSmile(bvsd->dates().back() + 1 * Years); iss = boost::dynamic_pointer_cast<InterpolatedSmileSection>(fxss); BOOST_REQUIRE(iss); vector<Real> extrapVolatilities = iss->volatilities(); BOOST_REQUIRE_EQUAL(lastVolatilities.size(), extrapVolatilities.size()); for (Size i = 0; i < lastVolatilities.size(); i++) { BOOST_CHECK_SMALL(lastVolatilities[i] - extrapVolatilities[i], tol); } // Check flat strike extrapolation. Date testDate = asof + 1 * Years; fxss = bvsd->blackVolSmile(testDate); iss = boost::dynamic_pointer_cast<InterpolatedSmileSection>(fxss); BOOST_REQUIRE(iss); Volatility volAtMinStrike = iss->volatilities().front(); Real minStrike = iss->strikes().front(); Real extrapStrike = minStrike / 2.0; BOOST_CHECK_SMALL(volAtMinStrike - bvsd->blackVol(testDate, extrapStrike), tol); Volatility volAtMaxStrike = iss->volatilities().back(); Real maxStrike = iss->strikes().back(); extrapStrike = maxStrike * 2.0; BOOST_CHECK_SMALL(volAtMaxStrike - bvsd->blackVol(testDate, extrapStrike), tol); } BOOST_DATA_TEST_CASE(testCommodityVolMoneynessSurface, bdata::make(asofDates) * bdata::make(curveConfigs), asof, curveConfig) { BOOST_TEST_MESSAGE("Testing commodity volatility forward moneyness surface building"); Settings::instance().evaluationDate() = asof; auto todaysMarket = createTodaysMarket(asof, "moneyness_surface", curveConfig, "market.txt"); // Get the built commodity volatility surface auto vts = todaysMarket->commodityVolatility("NYMEX:CL"); // Tolerance for float comparison Real tol = 1e-12; // Read in the expected on-grid results for the given date. string filename = "moneyness_surface/expected_grid_" + to_string(io::iso_date(asof)) + ".csv"; CSVFileReader reader(TEST_INPUT_FILE(filename), true, ","); BOOST_REQUIRE_EQUAL(reader.numberOfColumns(), 3); while (reader.next()) { // Get the expected expiry date, strike and volatility grid point Date expiryDate = parseDate(reader.get(0)); Real strike = parseReal(reader.get(1)); Real volatility = parseReal(reader.get(2)); // Check the surface on the grid point. BOOST_CHECK_SMALL(volatility - vts->blackVol(expiryDate, strike), tol); } // Price term structure auto pts = todaysMarket->commodityPriceCurve("NYMEX:CL"); // Pick two future expiries beyond max vol surface time and get their prices // This should correspond to moneyness 1.0 and we should see flat vol extrapolation. // This only passes because we have set sticky strike to false in CommodityVolCurve. Date extrapDate_1(20, Mar, 2024); Date extrapDate_2(22, Apr, 2024); Real strike_1 = pts->price(extrapDate_1); Real strike_2 = pts->price(extrapDate_2); Volatility vol_1 = vts->blackVol(extrapDate_1, strike_1); Volatility vol_2 = vts->blackVol(extrapDate_2, strike_2); BOOST_TEST_MESSAGE("The two time extrapolated volatilities are: " << fixed << setprecision(12) << vol_1 << "," << vol_2 << "."); BOOST_CHECK_SMALL(vol_1 - vol_2, tol); // Test flat strike extrapolation at lower and upper strikes i.e. at 50% and 150% forward moneyness. Date optionExpiry(14, Jan, 2021); Date futureExpiry(20, Jan, 2021); Real futurePrice = pts->price(futureExpiry); Real lowerStrike = 0.5 * futurePrice; Volatility volLowerStrike = vts->blackVol(optionExpiry, lowerStrike); Volatility volLowerExtrapStrike = vts->blackVol(optionExpiry, lowerStrike / 2.0); BOOST_TEST_MESSAGE("The two lower strike extrapolated volatilities are: " << fixed << setprecision(12) << volLowerStrike << "," << volLowerExtrapStrike << "."); BOOST_CHECK_SMALL(volLowerStrike - volLowerExtrapStrike, tol); Real upperStrike = 1.5 * futurePrice; Volatility volUpperStrike = vts->blackVol(optionExpiry, upperStrike); Volatility volUpperExtrapStrike = vts->blackVol(optionExpiry, upperStrike * 2.0); BOOST_TEST_MESSAGE("The two upper strike extrapolated volatilities are: " << fixed << setprecision(12) << volUpperStrike << "," << volUpperExtrapStrike << "."); BOOST_CHECK_SMALL(volUpperStrike - volUpperExtrapStrike, tol); } BOOST_DATA_TEST_CASE(testCommodityApoSurface, bdata::make(asofDates), asof) { BOOST_TEST_MESSAGE("Testing commodity volatility forward moneyness surface building"); Settings::instance().evaluationDate() = asof; string fixingsFile = "fixings_" + to_string(io::iso_date(asof)) + ".txt"; auto todaysMarket = createTodaysMarket(asof, "apo_surface", "curveconfig.xml", "market.txt", fixingsFile); // Get the built commodity volatility surface auto vts = todaysMarket->commodityVolatility("NYMEX:FF"); // Tolerance for float comparison Real tol = 1e-12; // Read in the expected on-grid results for the given date. string filename = "apo_surface/expected_grid_" + to_string(io::iso_date(asof)) + ".csv"; CSVFileReader reader(TEST_INPUT_FILE(filename), true, ","); BOOST_REQUIRE_EQUAL(reader.numberOfColumns(), 3); BOOST_TEST_MESSAGE("exp_vol,calc_vol,difference"); while (reader.next()) { // Get the expected expiry date, strike and volatility grid point Date expiryDate = parseDate(reader.get(0)); Real strike = parseReal(reader.get(1)); Real volatility = parseReal(reader.get(2)); // Check the surface on the grid point. auto calcVolatility = vts->blackVol(expiryDate, strike); auto difference = volatility - calcVolatility; BOOST_TEST_MESSAGE(std::fixed << std::setprecision(12) << strike << "," << volatility << "," << calcVolatility << "," << difference); BOOST_CHECK_SMALL(difference, tol); } } // Main point of this test is to test that the option expiries are interpreted correctly. BOOST_AUTO_TEST_CASE(testCommodityVolSurfaceMyrCrudePalmOil) { BOOST_TEST_MESSAGE("Testing commodity volatility delta surface building for MYR Crude Palm Oil"); Date asof(14, Oct, 2020); auto todaysMarket = createTodaysMarket(asof, "myr_crude_palm_oil", "curveconfig.xml", "market.txt"); // Get the built commodity volatility surface auto vts = todaysMarket->commodityVolatility("XKLS:FCPO"); // Check that it built ok i.e. can query a volatility. BOOST_CHECK_NO_THROW(vts->blackVol(1.0, 2800)); // Cast to expected type and check that it succeeds // For some reason, todaysmarket wraps the surface built in CommodityVolCurve in a BlackVolatilityWithATM. auto bvwa = dynamic_pointer_cast<BlackVolatilityWithATM>(*vts); BOOST_REQUIRE(bvwa); auto bvsd = boost::dynamic_pointer_cast<BlackVolatilitySurfaceDelta>(bvwa->surface()); BOOST_REQUIRE(bvsd); // Now check that the surface dates are as expected. // Calculated surface dates. const vector<Date>& surfaceDates = bvsd->dates(); // Read in the expected dates. vector<Date> expectedDates; string filename = "myr_crude_palm_oil/expected_expiries.csv"; CSVFileReader reader(TEST_INPUT_FILE(filename), true, ","); BOOST_REQUIRE_EQUAL(reader.numberOfColumns(), 1); while (reader.next()) { expectedDates.push_back(parseDate(reader.get(0))); } // Check equal. BOOST_CHECK_EQUAL_COLLECTIONS(surfaceDates.begin(), surfaceDates.end(), expectedDates.begin(), expectedDates.end()); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()
48.637086
120
0.685439
mrslezak
40ae7e2ea8c1874ba95f3a3ee5ef419fa784e7a2
2,023
cpp
C++
ares/ws/cartridge/io.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
153
2020-07-25T17:55:29.000Z
2021-10-01T23:45:01.000Z
ares/ws/cartridge/io.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
245
2021-10-08T09:14:46.000Z
2022-03-31T08:53:13.000Z
ares/ws/cartridge/io.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
44
2020-07-25T08:51:55.000Z
2021-09-25T16:09:01.000Z
auto Cartridge::readIO(n16 address) -> n8 { n8 data; switch(address) { case 0x00c0: //BANK_ROM2 data = io.romBank2; break; case 0x00c1: //BANK_SRAM data = io.sramBank; break; case 0x00c2: //BANK_ROM0 data = io.romBank0; break; case 0x00c3: //BANK_ROM1 data = io.romBank1; break; case 0x00c4: //EEP_DATALO data = eeprom.read(EEPROM::DataLo); break; case 0x00c5: //EEP_DATAHI data = eeprom.read(EEPROM::DataHi); break; case 0x00c6: //EEP_ADDRLO data = eeprom.read(EEPROM::AddressLo); break; case 0x00c7: //EEP_ADDRHI data = eeprom.read(EEPROM::AddressHi); break; case 0x00c8: //EEP_STATUS data = eeprom.read(EEPROM::Status); break; case 0x00ca: //RTC_STATUS data = rtc.status(); break; case 0x00cb: //RTC_DATA data = rtc.read(); break; case 0x00cc: //GPO_EN data = io.gpoEnable; break; case 0x00cd: //GPO_DATA data = io.gpoData; break; } return data; } auto Cartridge::writeIO(n16 address, n8 data) -> void { switch(address) { case 0x00c0: //BANK_ROM2 io.romBank2 = data; break; case 0x00c1: //BANK_SRAM io.sramBank = data; break; case 0x00c2: //BANK_ROM0 io.romBank0 = data; break; case 0x00c3: //BANK_ROM1 io.romBank1 = data; break; case 0x00c4: //EEP_DATALO eeprom.write(EEPROM::DataLo, data); break; case 0x00c5: //EEP_DATAHI eeprom.write(EEPROM::DataHi, data); break; case 0x00c6: //EEP_ADDRLO eeprom.write(EEPROM::AddressLo, data); break; case 0x00c7: //EEP_ADDRHI eeprom.write(EEPROM::AddressHi, data); break; case 0x00c8: //EEP_CMD eeprom.write(EEPROM::Command, data); break; case 0x00ca: //RTC_CMD rtc.execute(data); break; case 0x00cb: //RTC_DATA rtc.write(data); break; case 0x00cc: //GPO_EN io.gpoEnable = data; break; case 0x00cd: //GPO_DATA io.gpoData = data; break; } return; }
16.581967
55
0.610479
CasualPokePlayer
40b1260ec98ef4fc9580894e01d570ab57783b71
19,222
cpp
C++
src/vm/assemblynativeresource.cpp
danmosemsft/coreclr
04a3d11e4eecec2a4b7dcc81ab1575a57e30e3e2
[ "MIT" ]
6
2017-09-22T06:55:45.000Z
2021-07-02T07:07:08.000Z
src/vm/assemblynativeresource.cpp
danmosemsft/coreclr
04a3d11e4eecec2a4b7dcc81ab1575a57e30e3e2
[ "MIT" ]
2
2018-07-13T00:48:13.000Z
2019-02-27T16:19:30.000Z
src/vm/assemblynativeresource.cpp
danmosemsft/coreclr
04a3d11e4eecec2a4b7dcc81ab1575a57e30e3e2
[ "MIT" ]
2
2020-01-16T10:14:30.000Z
2020-02-09T08:48:51.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //////////////////////////////////////////////////////////////////////////////// // ResFile.CPP #include "common.h" #include "assemblynativeresource.h" #include <limits.h> #ifndef CP_WINUNICODE #define CP_WINUNICODE 1200 #endif #ifndef MAKEINTRESOURCE #define MAKEINTRESOURCE MAKEINTRESOURCEW #endif Win32Res::Win32Res() { CONTRACTL { NOTHROW; GC_NOTRIGGER; FORBID_FAULT; } CONTRACTL_END m_szFile = NULL; m_Icon = NULL; int i; for (i = 0; i < NUM_VALUES; i++) m_Values[i] = NULL; for (i = 0; i < NUM_VALUES; i++) m_Values[i] = NULL; m_fDll = false; m_pData = NULL; m_pCur = NULL; m_pEnd = NULL; } Win32Res::~Win32Res() { CONTRACTL { NOTHROW; GC_NOTRIGGER; FORBID_FAULT; } CONTRACTL_END m_szFile = NULL; m_Icon = NULL; int i; for (i = 0; i < NUM_VALUES; i++) m_Values[i] = NULL; for (i = 0; i < NUM_VALUES; i++) m_Values[i] = NULL; m_fDll = false; if (m_pData) delete [] m_pData; m_pData = NULL; m_pCur = NULL; m_pEnd = NULL; } //***************************************************************************** // Initializes the structures with version information. //***************************************************************************** VOID Win32Res::SetInfo( LPCWSTR szFile, LPCWSTR szTitle, LPCWSTR szIconName, LPCWSTR szDescription, LPCWSTR szCopyright, LPCWSTR szTrademark, LPCWSTR szCompany, LPCWSTR szProduct, LPCWSTR szProductVersion, LPCWSTR szFileVersion, LCID lcid, BOOL fDLL) { STANDARD_VM_CONTRACT; _ASSERTE(szFile != NULL); m_szFile = szFile; if (szIconName && szIconName[0] != 0) m_Icon = szIconName; // a non-mepty string #define NonNull(sz) (sz == NULL || *sz == W('\0') ? W(" ") : sz) m_Values[v_Description] = NonNull(szDescription); m_Values[v_Title] = NonNull(szTitle); m_Values[v_Copyright] = NonNull(szCopyright); m_Values[v_Trademark] = NonNull(szTrademark); m_Values[v_Product] = NonNull(szProduct); m_Values[v_ProductVersion] = NonNull(szProductVersion); m_Values[v_Company] = NonNull(szCompany); m_Values[v_FileVersion] = NonNull(szFileVersion); #undef NonNull m_fDll = fDLL; m_lcid = lcid; } VOID Win32Res::MakeResFile(const void **pData, DWORD *pcbData) { STANDARD_VM_CONTRACT; static const RESOURCEHEADER magic = { 0x00000000, 0x00000020, 0xFFFF, 0x0000, 0xFFFF, 0x0000, 0x00000000, 0x0000, 0x0000, 0x00000000, 0x00000000 }; _ASSERTE(pData != NULL && pcbData != NULL); *pData = NULL; *pcbData = 0; m_pData = new BYTE[(sizeof(RESOURCEHEADER) * 3 + sizeof(EXEVERRESOURCE))]; m_pCur = m_pData; m_pEnd = m_pData + sizeof(RESOURCEHEADER) * 3 + sizeof(EXEVERRESOURCE); // inject the magic empty entry Write( &magic, sizeof(magic) ); WriteVerResource(); if (m_Icon) { WriteIconResource(); } *pData = m_pData; *pcbData = (DWORD)(m_pCur - m_pData); return; } /* * WriteIconResource * Writes the Icon resource into the RES file. * * RETURNS: TRUE on succes, FALSE on failure (errors reported to user) */ VOID Win32Res::WriteIconResource() { STANDARD_VM_CONTRACT; HandleHolder hIconFile = INVALID_HANDLE_VALUE; WORD wTemp, wCount, resID = 2; // Skip 1 for the version ID DWORD dwRead = 0, dwWritten = 0; RESOURCEHEADER grpHeader = { 0x00000000, 0x00000020, 0xFFFF, (WORD)(size_t)RT_GROUP_ICON, 0xFFFF, 0x7F00, // 0x7F00 == IDI_APPLICATION 0x00000000, 0x1030, 0x0000, 0x00000000, 0x00000000 }; // Read the icon hIconFile = WszCreateFile( m_Icon, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL); if (hIconFile == INVALID_HANDLE_VALUE) { COMPlusThrowWin32(); } // Read the magic reserved WORD if (ReadFile( hIconFile, &wTemp, sizeof(WORD), &dwRead, NULL) == FALSE) { COMPlusThrowWin32(); } else if (wTemp != 0 || dwRead != sizeof(WORD)) { COMPlusThrowHR(HRESULT_FROM_WIN32(ERROR_INVALID_DATA)); } // Verify the Type WORD if (ReadFile( hIconFile, &wCount, sizeof(WORD), &dwRead, NULL) == FALSE) { COMPlusThrowWin32(); } else if (wCount != 1 || dwRead != sizeof(WORD)) { COMPlusThrowHR(HRESULT_FROM_WIN32(ERROR_INVALID_DATA)); } // Read the Count WORD if (ReadFile( hIconFile, &wCount, sizeof(WORD), &dwRead, NULL) == FALSE) { COMPlusThrowWin32(); } else if (wCount == 0 || dwRead != sizeof(WORD)) { COMPlusThrowHR(HRESULT_FROM_WIN32(ERROR_INVALID_DATA)); } NewArrayHolder<ICONRESDIR> grp = new ICONRESDIR[wCount]; grpHeader.DataSize = 3 * sizeof(WORD) + wCount * sizeof(ICONRESDIR); // For each Icon for (WORD i = 0; i < wCount; i++) { ICONDIRENTRY ico; DWORD icoPos, newPos; RESOURCEHEADER icoHeader = { 0x00000000, 0x00000020, 0xFFFF, (WORD)(size_t)RT_ICON, 0xFFFF, 0x0000, 0x00000000, 0x1010, 0x0000, 0x00000000, 0x00000000 }; icoHeader.Name = resID++; // Read the Icon header if (ReadFile( hIconFile, &ico, sizeof(ICONDIRENTRY), &dwRead, NULL) == FALSE) { COMPlusThrowWin32(); } else if (dwRead != sizeof(ICONDIRENTRY)) { COMPlusThrowHR(HRESULT_FROM_WIN32(ERROR_INVALID_DATA)); } _ASSERTE(sizeof(ICONRESDIR) + sizeof(WORD) == sizeof(ICONDIRENTRY)); memcpy(grp + i, &ico, sizeof(ICONRESDIR)); grp[i].IconId = icoHeader.Name; icoHeader.DataSize = ico.dwBytesInRes; NewArrayHolder<BYTE> icoBuffer = new BYTE[icoHeader.DataSize]; // Write the header to the RES file Write( &icoHeader, sizeof(RESOURCEHEADER) ); // Position to read the Icon data icoPos = SetFilePointer( hIconFile, 0, NULL, FILE_CURRENT); if (icoPos == INVALID_SET_FILE_POINTER) { COMPlusThrowWin32(); } newPos = SetFilePointer( hIconFile, ico.dwImageOffset, NULL, FILE_BEGIN); if (newPos == INVALID_SET_FILE_POINTER) { COMPlusThrowWin32(); } // Actually read the data if (ReadFile( hIconFile, icoBuffer, icoHeader.DataSize, &dwRead, NULL) == FALSE) { COMPlusThrowWin32(); } else if (dwRead != icoHeader.DataSize) { COMPlusThrowHR(HRESULT_FROM_WIN32(ERROR_INVALID_DATA)); } // Because Icon files don't seem to record the actual Planes and BitCount in // the ICONDIRENTRY, get the info from the BITMAPINFOHEADER at the beginning // of the data here: grp[i].Planes = ((BITMAPINFOHEADER*)(BYTE*)icoBuffer)->biPlanes; grp[i].BitCount = ((BITMAPINFOHEADER*)(BYTE*)icoBuffer)->biBitCount; // Now write the data to the RES file Write( (BYTE*)icoBuffer, icoHeader.DataSize ); // Reposition to read the next Icon header newPos = SetFilePointer( hIconFile, icoPos, NULL, FILE_BEGIN); if (newPos != icoPos) { COMPlusThrowWin32(); } } // inject the icon group Write( &grpHeader, sizeof(RESOURCEHEADER) ); // Write the header to the RES file wTemp = 0; // the reserved WORD Write( &wTemp, sizeof(WORD) ); wTemp = RES_ICON; // the GROUP type Write( &wTemp, sizeof(WORD) ); Write( &wCount, sizeof(WORD) ); // now write the entries Write( grp, sizeof(ICONRESDIR) * wCount ); return; } /* * WriteVerResource * Writes the version resource into the RES file. * * RETURNS: TRUE on succes, FALSE on failure (errors reported to user) */ VOID Win32Res::WriteVerResource() { STANDARD_VM_CONTRACT; WCHAR szLangCp[9]; // language/codepage string. EXEVERRESOURCE VerResource; WORD cbStringBlocks; int i; bool bUseFileVer = false; WCHAR rcFile[_MAX_PATH] = {0}; // Name of file without path WCHAR rcFileExtension[_MAX_PATH] = {0}; // file extension WCHAR rcFileName[_MAX_PATH]; // Name of file with extension but without path DWORD cbTmp; SplitPath(m_szFile, 0, 0, 0, 0, rcFile, _MAX_PATH, rcFileExtension, _MAX_PATH); wcscpy_s(rcFileName, COUNTOF(rcFileName), rcFile); wcscat_s(rcFileName, COUNTOF(rcFileName), rcFileExtension); static const EXEVERRESOURCE VerResourceTemplate = { sizeof(EXEVERRESOURCE), sizeof(VS_FIXEDFILEINFO), 0, W("VS_VERSION_INFO"), { VS_FFI_SIGNATURE, // Signature VS_FFI_STRUCVERSION, // structure version 0, 0, // file version number 0, 0, // product version number VS_FFI_FILEFLAGSMASK, // file flags mask 0, // file flags VOS__WINDOWS32, VFT_APP, // file type 0, // subtype 0, 0 // file date/time }, sizeof(WORD) * 2 + 2 * HDRSIZE + KEYBYTES("VarFileInfo") + KEYBYTES("Translation"), 0, 1, W("VarFileInfo"), sizeof(WORD) * 2 + HDRSIZE + KEYBYTES("Translation"), sizeof(WORD) * 2, 0, W("Translation"), 0, 0, 2 * HDRSIZE + KEYBYTES("StringFileInfo") + KEYBYTES("12345678"), 0, 1, W("StringFileInfo"), HDRSIZE + KEYBYTES("12345678"), 0, 1, W("12345678") }; static const WCHAR szComments[] = W("Comments"); static const WCHAR szCompanyName[] = W("CompanyName"); static const WCHAR szFileDescription[] = W("FileDescription"); static const WCHAR szCopyright[] = W("LegalCopyright"); static const WCHAR szTrademark[] = W("LegalTrademarks"); static const WCHAR szProdName[] = W("ProductName"); static const WCHAR szFileVerResName[] = W("FileVersion"); static const WCHAR szProdVerResName[] = W("ProductVersion"); static const WCHAR szInternalNameResName[] = W("InternalName"); static const WCHAR szOriginalNameResName[] = W("OriginalFilename"); // If there's no product version, use the file version if (m_Values[v_ProductVersion][0] == 0) { m_Values[v_ProductVersion] = m_Values[v_FileVersion]; bUseFileVer = true; } // Keep the two following arrays in the same order #define MAX_KEY 10 static const LPCWSTR szKeys [MAX_KEY] = { szComments, szCompanyName, szFileDescription, szFileVerResName, szInternalNameResName, szCopyright, szTrademark, szOriginalNameResName, szProdName, szProdVerResName, }; LPCWSTR szValues [MAX_KEY] = { // values for keys m_Values[v_Description], //compiler->assemblyDescription == NULL ? W("") : compiler->assemblyDescription, m_Values[v_Company], // Company Name m_Values[v_Title], // FileDescription //compiler->assemblyTitle == NULL ? W("") : compiler->assemblyTitle, m_Values[v_FileVersion], // FileVersion rcFileName, // InternalName m_Values[v_Copyright], // Copyright m_Values[v_Trademark], // Trademark rcFileName, // OriginalName m_Values[v_Product], // Product Name //compiler->assemblyTitle == NULL ? W("") : compiler->assemblyTitle, m_Values[v_ProductVersion] // Product Version }; memcpy(&VerResource, &VerResourceTemplate, sizeof(VerResource)); if (m_fDll) VerResource.vsFixed.dwFileType = VFT_DLL; else VerResource.vsFixed.dwFileType = VFT_APP; // Extract the numeric version from the string. m_Version[0] = m_Version[1] = m_Version[2] = m_Version[3] = 0; int nNumStrings = swscanf_s(m_Values[v_FileVersion], W("%hu.%hu.%hu.%hu"), m_Version, m_Version + 1, m_Version + 2, m_Version + 3); // Fill in the FIXEDFILEINFO VerResource.vsFixed.dwFileVersionMS = ((DWORD)m_Version[0] << 16) + m_Version[1]; VerResource.vsFixed.dwFileVersionLS = ((DWORD)m_Version[2] << 16) + m_Version[3]; if (bUseFileVer) { VerResource.vsFixed.dwProductVersionLS = VerResource.vsFixed.dwFileVersionLS; VerResource.vsFixed.dwProductVersionMS = VerResource.vsFixed.dwFileVersionMS; } else { WORD v[4]; v[0] = v[1] = v[2] = v[3] = 0; // Try to get the version numbers, but don't waste time or give any errors // just default to zeros nNumStrings = swscanf_s(m_Values[v_ProductVersion], W("%hu.%hu.%hu.%hu"), v, v + 1, v + 2, v + 3); VerResource.vsFixed.dwProductVersionMS = ((DWORD)v[0] << 16) + v[1]; VerResource.vsFixed.dwProductVersionLS = ((DWORD)v[2] << 16) + v[3]; } // There is no documentation on what units to use for the date! So we use zero. // The Windows resource compiler does too. VerResource.vsFixed.dwFileDateMS = VerResource.vsFixed.dwFileDateLS = 0; // Fill in codepage/language -- we'll assume the IDE language/codepage // is the right one. if (m_lcid != -1) VerResource.langid = static_cast<WORD>(m_lcid); else VerResource.langid = MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL); VerResource.codepage = CP_WINUNICODE; // Unicode codepage. swprintf_s(szLangCp, NumItems(szLangCp), W("%04x%04x"), VerResource.langid, VerResource.codepage); wcscpy_s(VerResource.szLangCpKey, COUNTOF(VerResource.szLangCpKey), szLangCp); // Determine the size of all the string blocks. cbStringBlocks = 0; for (i = 0; i < MAX_KEY; i++) { if (szValues[i] == NULL || wcslen(szValues[i]) == 0) continue; cbTmp = SizeofVerString( szKeys[i], szValues[i]); if ((cbStringBlocks + cbTmp) > USHRT_MAX / 2) COMPlusThrow(kArgumentException, W("Argument_VerStringTooLong")); cbStringBlocks += (WORD) cbTmp; } if ((cbStringBlocks + VerResource.cbLangCpBlock) > USHRT_MAX / 2) COMPlusThrow(kArgumentException, W("Argument_VerStringTooLong")); VerResource.cbLangCpBlock += cbStringBlocks; if ((cbStringBlocks + VerResource.cbStringBlock) > USHRT_MAX / 2) COMPlusThrow(kArgumentException, W("Argument_VerStringTooLong")); VerResource.cbStringBlock += cbStringBlocks; if ((cbStringBlocks + VerResource.cbRootBlock) > USHRT_MAX / 2) COMPlusThrow(kArgumentException, W("Argument_VerStringTooLong")); VerResource.cbRootBlock += cbStringBlocks; // Call this VS_VERSION_INFO RESOURCEHEADER verHeader = { 0x00000000, 0x0000003C, 0xFFFF, (WORD)(size_t)RT_VERSION, 0xFFFF, 0x0001, 0x00000000, 0x0030, 0x0000, 0x00000000, 0x00000000 }; verHeader.DataSize = VerResource.cbRootBlock; // Write the header Write( &verHeader, sizeof(RESOURCEHEADER) ); // Write the version resource Write( &VerResource, sizeof(VerResource) ); // Write each string block. for (i = 0; i < MAX_KEY; i++) { if (szValues[i] == NULL || wcslen(szValues[i]) == 0) continue; WriteVerString( szKeys[i], szValues[i] ); } #undef MAX_KEY return; } /* * SizeofVerString * Determines the size of a version string to the given stream. * RETURNS: size of block in bytes. */ WORD Win32Res::SizeofVerString(LPCWSTR lpszKey, LPCWSTR lpszValue) { STANDARD_VM_CONTRACT; size_t cbKey, cbValue; cbKey = (wcslen(lpszKey) + 1) * 2; // Make room for the NULL cbValue = (wcslen(lpszValue) + 1) * 2; if (cbValue == 2) cbValue = 4; // Empty strings need a space and NULL terminator (for Win9x) if (cbKey + cbValue >= 0xFFF0) COMPlusThrow(kArgumentException, W("Argument_VerStringTooLong")); #ifdef _PREFAST_ #pragma warning(push) #pragma warning(disable:6305) // "Potential mismatch between sizeof and countof quantities" #endif return (WORD)(PadKeyLen(cbKey) + // key, 0 padded to DWORD boundary PadValLen(cbValue) + // value, 0 padded to dword boundary HDRSIZE); // block header. #ifdef _PREFAST_ #pragma warning(pop) #endif } /*---------------------------------------------------------------------------- * WriteVerString * Writes a version string to the given file. */ VOID Win32Res::WriteVerString( LPCWSTR lpszKey, LPCWSTR lpszValue) { STANDARD_VM_CONTRACT; size_t cbKey, cbValue, cbBlock; bool bNeedsSpace = false; cbKey = (wcslen(lpszKey) + 1) * 2; // includes terminating NUL cbValue = wcslen(lpszValue); if (cbValue > 0) cbValue++; // make room for NULL else { bNeedsSpace = true; cbValue = 2; // Make room for space and NULL (for Win9x) } cbBlock = SizeofVerString(lpszKey, lpszValue); NewArrayHolder<BYTE> pbBlock = new BYTE[(DWORD)cbBlock + HDRSIZE]; ZeroMemory(pbBlock, (DWORD)cbBlock + HDRSIZE); _ASSERTE(cbValue < USHRT_MAX && cbKey < USHRT_MAX && cbBlock < USHRT_MAX); // Copy header, key and value to block. *(WORD *)((BYTE *)pbBlock) = (WORD)cbBlock; *(WORD *)(pbBlock + sizeof(WORD)) = (WORD)cbValue; *(WORD *)(pbBlock + 2 * sizeof(WORD)) = 1; // 1 = text value // size = (cbBlock + HDRSIZE - HDRSIZE) / sizeof(WCHAR) wcscpy_s((WCHAR*)(pbBlock + HDRSIZE), (cbBlock / sizeof(WCHAR)), lpszKey); #ifdef _PREFAST_ #pragma warning(push) #pragma warning(disable:6305) // "Potential mismatch between sizeof and countof quantities" #endif if (bNeedsSpace) *((WCHAR*)(pbBlock + (HDRSIZE + PadKeyLen(cbKey)))) = W(' '); else { wcscpy_s((WCHAR*)(pbBlock + (HDRSIZE + PadKeyLen(cbKey))), //size = ((cbBlock + HDRSIZE) - (HDRSIZE + PadKeyLen(cbKey))) / sizeof(WCHAR) (cbBlock - PadKeyLen(cbKey))/sizeof(WCHAR), lpszValue); } #ifdef _PREFAST_ #pragma warning(pop) #endif // Write block Write( pbBlock, cbBlock); return; } VOID Win32Res::Write(LPCVOID pData, size_t len) { STANDARD_VM_CONTRACT; if (m_pCur + len > m_pEnd) { // Grow size_t newSize = (m_pEnd - m_pData); // double the size unless we need more than that if (len > newSize) newSize += len; else newSize *= 2; LPBYTE pNew = new BYTE[newSize]; memcpy(pNew, m_pData, m_pCur - m_pData); delete [] m_pData; // Relocate the pointers m_pCur = pNew + (m_pCur - m_pData); m_pData = pNew; m_pEnd = pNew + newSize; } // Copy it in memcpy(m_pCur, pData, len); m_pCur += len; return; }
32.802048
138
0.606128
danmosemsft
40b247e8597a26a7b79c918d3032501ba456f018
844
cc
C++
3rdParty/V8/v5.7.492.77/src/promise-utils.cc
sita1999/arangodb
6a4f462fa209010cd064f99e63d85ce1d432c500
[ "Apache-2.0" ]
1
2018-12-08T01:58:16.000Z
2018-12-08T01:58:16.000Z
3rdParty/V8/v5.7.492.77/src/promise-utils.cc
lipper/arangodb
66ea1fd4946668192e3f0d1060f0844f324ad7b8
[ "Apache-2.0" ]
null
null
null
3rdParty/V8/v5.7.492.77/src/promise-utils.cc
lipper/arangodb
66ea1fd4946668192e3f0d1060f0844f324ad7b8
[ "Apache-2.0" ]
1
2018-12-05T04:56:16.000Z
2018-12-05T04:56:16.000Z
// Copyright 2016 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/promise-utils.h" #include "src/factory.h" #include "src/isolate.h" #include "src/objects-inl.h" namespace v8 { namespace internal { JSPromise* PromiseUtils::GetPromise(Handle<Context> context) { return JSPromise::cast(context->get(kPromiseSlot)); } Object* PromiseUtils::GetDebugEvent(Handle<Context> context) { return context->get(kDebugEventSlot); } bool PromiseUtils::HasAlreadyVisited(Handle<Context> context) { return Smi::cast(context->get(kAlreadyVisitedSlot))->value() != 0; } void PromiseUtils::SetAlreadyVisited(Handle<Context> context) { context->set(kAlreadyVisitedSlot, Smi::FromInt(1)); } } // namespace internal } // namespace v8
26.375
73
0.746445
sita1999
40b5d8fc2532554b65212e12da18a8c740bd2163
6,728
cpp
C++
render_delegate/render_param.cpp
krishnancr/arnold-usd
e32b6042cb16a87bdef90c602e2fdc0c921a9d5c
[ "Apache-2.0" ]
1
2019-12-02T13:51:27.000Z
2019-12-02T13:51:27.000Z
render_delegate/render_param.cpp
krishnancr/arnold-usd
e32b6042cb16a87bdef90c602e2fdc0c921a9d5c
[ "Apache-2.0" ]
1
2020-01-07T20:57:45.000Z
2020-01-17T10:41:39.000Z
render_delegate/render_param.cpp
krishnancr/arnold-usd
e32b6042cb16a87bdef90c602e2fdc0c921a9d5c
[ "Apache-2.0" ]
3
2019-12-03T07:45:47.000Z
2022-01-25T08:43:05.000Z
// Copyright 2019 Luma Pictures // // 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. // // Modifications Copyright 2019 Autodesk, 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 "render_param.h" #include "render_delegate.h" #include <ai.h> PXR_NAMESPACE_OPEN_SCOPE #ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS HdArnoldRenderParam::HdArnoldRenderParam(HdArnoldRenderDelegate* delegate) : _delegate(delegate) #else HdArnoldRenderParam::HdArnoldRenderParam() #endif { _needsRestart.store(false, std::memory_order::memory_order_release); _aborted.store(false, std::memory_order::memory_order_release); } HdArnoldRenderParam::Status HdArnoldRenderParam::Render() { const auto aborted = _aborted.load(std::memory_order_acquire); // Checking early if the render was aborted earlier. if (aborted) { return Status::Aborted; } #ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS const auto status = AiRenderGetStatus(_delegate->GetRenderSession()); #else const auto status = AiRenderGetStatus(); #endif if (status == AI_RENDER_STATUS_FINISHED) { // If render restart is true, it means the Render Delegate received an update after rendering has finished // and AiRenderInterrupt does not change the status anymore. // For the atomic operations we are using a release-acquire model. const auto needsRestart = _needsRestart.exchange(false, std::memory_order_acq_rel); if (needsRestart) { _paused.store(false, std::memory_order_release); #ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS AiRenderRestart(_delegate->GetRenderSession()); #else AiRenderRestart(); #endif return Status::Converging; } return Status::Converged; } // Resetting the value. _needsRestart.store(false, std::memory_order_release); if (status == AI_RENDER_STATUS_PAUSED) { const auto needsRestart = _needsRestart.exchange(false, std::memory_order_acq_rel); if (needsRestart) { _paused.store(false, std::memory_order_release); #ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS AiRenderRestart(_delegate->GetRenderSession()); #else AiRenderRestart(); #endif } else if (!_paused.load(std::memory_order_acquire)) { #ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS AiRenderResume(_delegate->GetRenderSession()); #else AiRenderResume(); #endif } return Status::Converging; } if (status == AI_RENDER_STATUS_RESTARTING) { _paused.store(false, std::memory_order_release); return Status::Converging; } if (status == AI_RENDER_STATUS_FAILED) { _aborted.store(true, std::memory_order_release); _paused.store(false, std::memory_order_release); #ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS const auto errorCode = AiRenderEnd(_delegate->GetRenderSession()); #else const auto errorCode = AiRenderEnd(); #endif if (errorCode == AI_ABORT) { TF_WARN("[arnold-usd] Render was aborted."); } else if (errorCode == AI_ERROR_NO_CAMERA) { TF_WARN("[arnold-usd] Camera not defined."); } else if (errorCode == AI_ERROR_BAD_CAMERA) { TF_WARN("[arnold-usd] Bad camera data."); } else if (errorCode == AI_ERROR_VALIDATION) { TF_WARN("[arnold-usd] Usage not validated."); } else if (errorCode == AI_ERROR_RENDER_REGION) { TF_WARN("[arnold-usd] Invalid render region."); } else if (errorCode == AI_INTERRUPT) { TF_WARN("[arnold-usd] Render interrupted by user."); } else if (errorCode == AI_ERROR_NO_OUTPUTS) { TF_WARN("[arnold-usd] No rendering outputs."); } else if (errorCode == AI_ERROR_UNAVAILABLE_DEVICE) { TF_WARN("[arnold-usd] Cannot create GPU context."); } else if (errorCode == AI_ERROR) { TF_WARN("[arnold-usd] Generic error."); } return Status::Aborted; } _paused.store(false, std::memory_order_release); if (status != AI_RENDER_STATUS_RENDERING) { #ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS AiRenderBegin(_delegate->GetRenderSession()); #else AiRenderBegin(); #endif } return Status::Converging; } void HdArnoldRenderParam::Interrupt(bool needsRestart, bool clearStatus) { #ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS const auto status = AiRenderGetStatus(_delegate->GetRenderSession()); #else const auto status = AiRenderGetStatus(); #endif if (status != AI_RENDER_STATUS_NOT_STARTED) { #ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS AiRenderInterrupt(_delegate->GetRenderSession(), AI_BLOCKING); #else AiRenderInterrupt(AI_BLOCKING); #endif } if (needsRestart) { _needsRestart.store(true, std::memory_order_release); } if (clearStatus) { _aborted.store(false, std::memory_order_release); } } void HdArnoldRenderParam::Pause() { Interrupt(false, false); _paused.store(true, std::memory_order_release); } void HdArnoldRenderParam::Resume() { _paused.store(false, std::memory_order_release); } void HdArnoldRenderParam::Restart() { _paused.store(false, std::memory_order_release); _needsRestart.store(true, std::memory_order_release); } bool HdArnoldRenderParam::UpdateShutter(const GfVec2f& shutter) { if (!GfIsClose(_shutter[0], shutter[0], AI_EPSILON) || !GfIsClose(_shutter[1], shutter[1], AI_EPSILON)) { _shutter = shutter; return true; } return false; } bool HdArnoldRenderParam::UpdateFPS(const float FPS) { if (!GfIsClose(_fps, FPS, AI_EPSILON)) { _fps = FPS; return true; } return false; } PXR_NAMESPACE_CLOSE_SCOPE
34.502564
114
0.695898
krishnancr
40b85203fb671cbf485eee6d339700b7e69245bd
30,398
cpp
C++
libfairygui/Classes/Transition.cpp
zeas2/FairyGUI-cocos2dx
c6ddaafc1b1bf51b0ef6929d6937c0cf111cd06a
[ "MIT" ]
null
null
null
libfairygui/Classes/Transition.cpp
zeas2/FairyGUI-cocos2dx
c6ddaafc1b1bf51b0ef6929d6937c0cf111cd06a
[ "MIT" ]
null
null
null
libfairygui/Classes/Transition.cpp
zeas2/FairyGUI-cocos2dx
c6ddaafc1b1bf51b0ef6929d6937c0cf111cd06a
[ "MIT" ]
null
null
null
#include "Transition.h" #include "GComponent.h" #include "utils/ToolSet.h" NS_FGUI_BEGIN USING_NS_CC; using namespace std; const int FRAME_RATE = 24; const int OPTION_IGNORE_DISPLAY_CONTROLLER = 1; const int OPTION_AUTO_STOP_DISABLED = 2; const int OPTION_AUTO_STOP_AT_END = 4; class TransitionValue { public: float f1;//x, scalex, pivotx,alpha,shakeAmplitude,rotation float f2;//y, scaley, pivoty, shakePeriod float f3; float f4; int i;//frame Color4B c;//color bool b;//playing string s;//sound,transName bool b1; bool b2; TransitionValue(); TransitionValue(TransitionValue& source); TransitionValue& operator= (const TransitionValue& other); }; TransitionValue::TransitionValue() : f1(0), f2(0), f3(0), f4(0), i(0), b(false), b1(false), b2(false) { } TransitionValue::TransitionValue(TransitionValue& other) { *this = other; } TransitionValue& TransitionValue::operator= (const TransitionValue& other) { f1 = other.f1; f2 = other.f2; f3 = other.f3; f4 = other.f4; i = other.i; c = other.c; b = other.b; s = other.s; b1 = other.b1; b2 = other.b2; return *this; } class TransitionItem { public: float time; string targetId; TransitionActionType type; float duration; TransitionValue value; TransitionValue startValue; TransitionValue endValue; tweenfunc::TweenType easeType; int repeat; bool yoyo; bool tween; string label; string label2; //hooks Transition::TransitionHook hook; Transition::TransitionHook hook2; //running properties bool completed; GObject* target; bool filterCreated; uint32_t displayLockToken; TransitionItem(); }; TransitionItem::TransitionItem() : time(0), type(TransitionActionType::XY), duration(0), easeType(tweenfunc::TweenType::Quad_EaseOut), repeat(0), yoyo(false), tween(false), hook(nullptr), hook2(nullptr), completed(false), target(nullptr), filterCreated(false), displayLockToken(0) { } Transition::Transition(GComponent* owner, int index) : autoPlayRepeat(1), autoPlayDelay(0), _owner(owner), _totalTimes(0), _totalTasks(0), _playing(false), _ownerBaseX(0), _ownerBaseY(0), _onComplete(nullptr), _options(0), _reversed(false), _maxTime(0), _autoPlay(false), _actionTag(ActionTag::TRANSITION_ACTION + index) { } Transition::~Transition() { for (auto &item : _items) delete item; } void Transition::setAutoPlay(bool value) { if (_autoPlay != value) { _autoPlay = value; if (_autoPlay) { if (_owner->onStage()) play(autoPlayRepeat, autoPlayDelay, nullptr); } else { if (!_owner->onStage()) stop(false, true); } } } void Transition::play(PlayCompleteCallback callback) { play(1, 0, callback); } void Transition::play(int times, float delay, PlayCompleteCallback callback) { play(times, delay, callback, false); } void Transition::playReverse(PlayCompleteCallback callback) { playReverse(1, 0, callback); } void Transition::playReverse(int times, float delay, PlayCompleteCallback callback) { play(times, delay, callback, true); } void Transition::changeRepeat(int value) { _totalTimes = value; } void Transition::play(int times, float delay, PlayCompleteCallback onComplete, bool reverse) { stop(true, true); _totalTimes = times; _reversed = reverse; internalPlay(delay); _playing = _totalTasks > 0; if (_playing) { _onComplete = onComplete; if ((_options & OPTION_IGNORE_DISPLAY_CONTROLLER) != 0) { for (auto &item : _items) { if (item->target != nullptr && item->target != _owner) item->displayLockToken = item->target->addDisplayLock(); } } } else if (onComplete != nullptr) onComplete(); } void Transition::stop() { stop(true, false); } void Transition::stop(bool setToComplete, bool processCallback) { if (_playing) { _playing = false; _totalTasks = 0; _totalTimes = 0; PlayCompleteCallback func = _onComplete; _onComplete = nullptr; _owner->displayObject()->stopAllActionsByTag(_actionTag); int cnt = (int)_items.size(); if (_reversed) { for (int i = cnt - 1; i >= 0; i--) { TransitionItem* item = _items[i]; if (item->target == nullptr) continue; stopItem(item, setToComplete); } } else { for (int i = 0; i < cnt; i++) { TransitionItem *item = _items[i]; if (item->target == nullptr) continue; stopItem(item, setToComplete); } } if (processCallback && func != nullptr) func(); } } void Transition::stopItem(TransitionItem * item, bool setToComplete) { if (item->displayLockToken != 0) { item->target->releaseDisplayLock(item->displayLockToken); item->displayLockToken = 0; } //if (item->type == TransitionActionType::ColorFilter && item->filterCreated) // item->target->setFilter(nullptr); if (item->completed) return; if (item->type == TransitionActionType::Transition) { Transition* trans = item->target->as<GComponent>()->getTransition(item->value.s); if (trans != nullptr) trans->stop(setToComplete, false); } else if (item->type == TransitionActionType::Shake) { Director::getInstance()->getScheduler()->unschedule("-", item); item->target->_gearLocked = true; item->target->setPosition(item->target->getX() - item->startValue.f1, item->target->getY() - item->startValue.f2); item->target->_gearLocked = false; } else { if (setToComplete) { if (item->tween) { if (!item->yoyo || item->repeat % 2 == 0) applyValue(item, _reversed ? item->startValue : item->endValue); else applyValue(item, _reversed ? item->endValue : item->startValue); } else if (item->type != TransitionActionType::Sound) applyValue(item, item->value); } } } void Transition::setValue(const std::string & label, const ValueVector& values) { for (auto &item : _items) { if (item->label == label) { if (item->tween) setValue(item, item->startValue, values); else setValue(item, item->value, values); } else if (item->label2 == label) { setValue(item, item->endValue, values); } } } void Transition::setValue(TransitionItem* item, TransitionValue& value, const ValueVector& values) { switch (item->type) { case TransitionActionType::XY: case TransitionActionType::Size: case TransitionActionType::Pivot: case TransitionActionType::Scale: case TransitionActionType::Skew: value.b1 = true; value.b2 = true; value.f1 = values[0].asFloat(); value.f2 = values[1].asFloat(); break; case TransitionActionType::Alpha: value.f1 = values[0].asFloat(); break; case TransitionActionType::Rotation: value.f1 = values[0].asFloat(); break; case TransitionActionType::Color: { uint32_t v = values[0].asUnsignedInt(); value.c = Color4B((v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF, (v >> 24) & 0xFF); break; } case TransitionActionType::Animation: value.i = values[0].asInt(); if (values.size() > 1) value.b = values[1].asBool(); break; case TransitionActionType::Visible: value.b = values[0].asBool(); break; case TransitionActionType::Sound: value.s = values[0].asString(); if (values.size() > 1) value.f1 = values[1].asFloat(); break; case TransitionActionType::Transition: value.s = values[0].asString(); if (values.size() > 1) value.i = values[1].asInt(); break; case TransitionActionType::Shake: value.f1 = values[0].asFloat(); if (values.size() > 1) value.f2 = values[1].asFloat(); break; case TransitionActionType::ColorFilter: value.f1 = values[1].asFloat(); value.f2 = values[2].asFloat(); value.f3 = values[3].asFloat(); value.f4 = values[4].asFloat(); break; default: break; } } void Transition::setHook(const std::string & label, TransitionHook callback) { for (auto &item : _items) { if (item->label == label) { item->hook = callback; break; } else if (item->label2 == label) { item->hook2 = callback; break; } } } void Transition::clearHooks() { for (auto &item : _items) { item->hook = nullptr; item->hook2 = nullptr; } } void Transition::setTarget(const std::string & label, GObject * newTarget) { for (auto &item : _items) { if (item->label == label) item->targetId = newTarget->id; } } void Transition::setDuration(const std::string & label, float value) { for (auto &item : _items) { if (item->tween && item->label == label) item->duration = value; } } void Transition::updateFromRelations(const std::string & targetId, float dx, float dy) { int cnt = (int)_items.size(); if (cnt == 0) return; for (int i = 0; i < cnt; i++) { TransitionItem* item = _items[i]; if (item->type == TransitionActionType::XY && item->targetId == targetId) { if (item->tween) { item->startValue.f1 += dx; item->startValue.f2 += dy; item->endValue.f1 += dx; item->endValue.f2 += dy; } else { item->value.f1 += dx; item->value.f2 += dy; } } } } void Transition::OnOwnerRemovedFromStage() { if ((_options & OPTION_AUTO_STOP_DISABLED) == 0) stop((_options & OPTION_AUTO_STOP_AT_END) != 0 ? true : false, false); } void Transition::internalPlay(float delay) { _ownerBaseX = _owner->getX(); _ownerBaseY = _owner->getY(); _totalTasks = 0; for (auto &item : _items) { if (!item->targetId.empty()) item->target = _owner->getChildById(item->targetId); else item->target = _owner; if (item->target == nullptr) continue; if (item->tween) { float startTime = delay; if (_reversed) startTime += (_maxTime - item->time - item->duration); else startTime += item->time; if (startTime > 0 && (item->type == TransitionActionType::XY || item->type == TransitionActionType::Size)) { _totalTasks++; item->completed = false; ActionInterval* action = Sequence::createWithTwoActions(DelayTime::create(startTime), CallFunc::create([item, this] { _totalTasks--; startTween(item, 0); })); action->setTag(ActionTag::TRANSITION_ACTION); _owner->displayObject()->runAction(action); } else startTween(item, startTime); } else { float startTime = delay; if (_reversed) startTime += (_maxTime - item->time); else startTime += item->time; if (startTime == 0) { applyValue(item, item->value); if (item->hook) item->hook(); } else { item->completed = false; _totalTasks++; ActionInterval* action = Sequence::createWithTwoActions(DelayTime::create(startTime), CallFunc::create([item, this] { item->completed = true; _totalTasks--; applyValue(item, item->value); if (item->hook) item->hook(); checkAllComplete(); })); action->setTag(ActionTag::TRANSITION_ACTION); _owner->displayObject()->runAction(action); } } } } void Transition::startTween(TransitionItem * item, float delay) { if (_reversed) startTween(item, delay, item->endValue, item->startValue); else startTween(item, delay, item->startValue, item->endValue); } void Transition::startTween(TransitionItem * item, float delay, TransitionValue& startValue, TransitionValue& endValue) { ActionInterval* mainAction = nullptr; switch (item->type) { case TransitionActionType::XY: case TransitionActionType::Size: { if (item->type == TransitionActionType::XY) { if (item->target == _owner) { if (!startValue.b1) startValue.f1 = 0; if (!startValue.b2) startValue.f2 = 0; } else { if (!startValue.b1) startValue.f1 = item->target->getX(); if (!startValue.b2) startValue.f2 = item->target->getY(); } } else { if (!startValue.b1) startValue.f1 = item->target->getWidth(); if (!startValue.b2) startValue.f2 = item->target->getHeight(); } item->value.f1 = startValue.f1; item->value.f2 = startValue.f2; if (!endValue.b1) endValue.f1 = item->value.f1; if (!endValue.b2) endValue.f2 = item->value.f2; item->value.b1 = startValue.b1 || endValue.b1; item->value.b2 = startValue.b2 || endValue.b2; mainAction = ActionVec2::create(item->duration, Vec2(startValue.f1, startValue.f2), Vec2(endValue.f1, endValue.f2), [this, item](const Vec2& value) { item->value.f1 = value.x; item->value.f2 = value.y; applyValue(item, item->value); }); break; } case TransitionActionType::Scale: case TransitionActionType::Skew: { item->value.f1 = startValue.f1; item->value.f2 = startValue.f2; mainAction = ActionVec2::create(item->duration, Vec2(startValue.f1, startValue.f2), Vec2(endValue.f1, endValue.f2), [this, item](const Vec2& value) { item->value.f1 = value.x; item->value.f2 = value.y; applyValue(item, item->value); }); break; } case TransitionActionType::Alpha: case TransitionActionType::Rotation: { item->value.f1 = startValue.f1; mainAction = ActionFloat::create(item->duration, startValue.f1, endValue.f1, [this, item](float value) { item->value.f1 = value; applyValue(item, item->value); }); break; } case TransitionActionType::Color: { item->value.c = startValue.c; mainAction = ActionVec4::create(item->duration, Vec4(item->value.c.r, item->value.c.g, item->value.c.b, item->value.c.a), Vec4(endValue.c.r, endValue.c.g, endValue.c.b, endValue.c.a), [this, item](const Vec4& value) { item->value.c.r = value.x; item->value.c.g = value.y; item->value.c.b = value.z; item->value.c.a = value.w; applyValue(item, item->value); }); break; } case TransitionActionType::ColorFilter: { item->value.f1 = startValue.f1; item->value.f2 = startValue.f2; item->value.f3 = startValue.f3; item->value.f4 = startValue.f4; mainAction = ActionVec4::create(item->duration, Vec4(startValue.f1, startValue.f2, startValue.f3, startValue.f4), Vec4(endValue.f1, endValue.f2, endValue.f3, endValue.f4), [this, item](const Vec4& value) { item->value.f1 = value.x; item->value.f2 = value.y; item->value.f3 = value.z; item->value.f4 = value.w; applyValue(item, item->value); }); break; } default: break; } mainAction = createEaseAction(item->easeType, mainAction); if (item->repeat != 0) mainAction = RepeatYoyo::create(mainAction, item->repeat == -1 ? INT_MAX : (item->repeat + 1), item->yoyo); FiniteTimeAction* completeAction = CallFunc::create([this, item]() { tweenComplete(item); }); if (delay > 0) { FiniteTimeAction* delayAction = DelayTime::create(delay); if (item->hook) mainAction = Sequence::create({ delayAction, CallFunc::create(item->hook), mainAction, completeAction }); else mainAction = Sequence::create({ delayAction, mainAction, completeAction }); } else { applyValue(item, item->value); if (item->hook) item->hook(); mainAction = Sequence::createWithTwoActions(mainAction, completeAction); } mainAction->setTag(ActionTag::TRANSITION_ACTION); _owner->displayObject()->runAction(mainAction); _totalTasks++; item->completed = false; } void Transition::tweenComplete(TransitionItem * item) { item->completed = true; _totalTasks--; if (item->hook2) item->hook2(); checkAllComplete(); } void Transition::checkAllComplete() { if (_playing && _totalTasks == 0) { if (_totalTimes < 0) { internalPlay(0); } else { _totalTimes--; if (_totalTimes > 0) internalPlay(0); else { _playing = false; for (auto &item : _items) { if (item->target != nullptr) { if (item->displayLockToken != 0) { item->target->releaseDisplayLock(item->displayLockToken); item->displayLockToken = 0; } /*if (item->filterCreated) { item->filterCreated = false; item->target->setFilter(nullptr); }*/ } } if (_onComplete) { PlayCompleteCallback func = _onComplete; _onComplete = nullptr; func(); } } } } } void Transition::applyValue(TransitionItem * item, TransitionValue & value) { item->target->_gearLocked = true; switch (item->type) { case TransitionActionType::XY: if (item->target == _owner) { float f1, f2; if (!value.b1) f1 = item->target->getX(); else f1 = value.f1 + _ownerBaseX; if (!value.b2) f2 = item->target->getY(); else f2 = value.f2 + _ownerBaseY; item->target->setPosition(f1, f2); } else { if (!value.b1) value.f1 = item->target->getX(); if (!value.b2) value.f2 = item->target->getY(); item->target->setPosition(value.f1, value.f2); } break; case TransitionActionType::Size: if (!value.b1) value.f1 = item->target->getWidth(); if (!value.b2) value.f2 = item->target->getHeight(); item->target->setSize(value.f1, value.f2); break; case TransitionActionType::Pivot: item->target->setPivot(value.f1, value.f2); break; case TransitionActionType::Alpha: item->target->setAlpha(value.f1); break; case TransitionActionType::Rotation: item->target->setRotation(value.f1); break; case TransitionActionType::Scale: item->target->setScale(value.f1, value.f2); break; case TransitionActionType::Skew: item->target->setSkewX(value.f1); item->target->setSkewY(value.f2); break; case TransitionActionType::Color: { IColorGear* cg = dynamic_cast<IColorGear*>(item->target); if (cg) cg->cg_setColor(value.c); break; } case TransitionActionType::Animation: { IAnimationGear* ag = dynamic_cast<IAnimationGear*>(item->target); if (ag) { if (!value.b1) value.i = ag->getCurrentFrame(); ag->setCurrentFrame(value.i); ag->setPlaying(value.b); } break; } case TransitionActionType::Visible: item->target->setVisible(value.b); break; case TransitionActionType::Transition: { Transition* trans = item->target->as<GComponent>()->getTransition(value.s); if (trans != nullptr) { if (value.i == 0) trans->stop(false, true); else if (trans->isPlaying()) trans->_totalTimes = value.i; else { item->completed = false; _totalTasks++; if (_reversed) trans->playReverse(value.i, 0, [this, item]() { playTransComplete(item); }); else trans->play(value.i, 0, [this, item]() { playTransComplete(item); }); } } break; } case TransitionActionType::Sound: { UIRoot->playSound(value.s, value.f1); break; } case TransitionActionType::Shake: item->startValue.f1 = 0; //offsetX item->startValue.f2 = 0; //offsetY item->startValue.f3 = item->value.f2;//shakePeriod Director::getInstance()->getScheduler()->schedule(CC_CALLBACK_1(Transition::shakeItem, this, item), item, 0, false, "-"); _totalTasks++; item->completed = false; break; case TransitionActionType::ColorFilter: break; default: break; } item->target->_gearLocked = false; } void Transition::playTransComplete(TransitionItem* item) { _totalTasks--; item->completed = true; checkAllComplete(); } void Transition::shakeItem(float dt, TransitionItem * item) { float r = ceil(item->value.f1 * item->startValue.f3 / item->value.f2); float x1 = (1 - rand_0_1() * 2)*r; float y1 = (1 - rand_0_1() * 2)*r; x1 = x1 > 0 ? ceil(x1) : floor(x1); y1 = y1 > 0 ? ceil(y1) : floor(y1); item->target->_gearLocked = true; item->target->setPosition(item->target->getX() - item->startValue.f1 + x1, item->target->getY() - item->startValue.f2 + y1); item->target->_gearLocked = false; item->startValue.f1 = x1; item->startValue.f2 = y1; item->startValue.f3 -= dt; if (item->startValue.f3 <= 0) { item->target->_gearLocked = true; item->target->setPosition(item->target->getX() - item->startValue.f1, item->target->getY() - item->startValue.f2); item->target->_gearLocked = false; item->completed = true; _totalTasks--; Director::getInstance()->getScheduler()->unschedule("-", item); checkAllComplete(); } } void Transition::decodeValue(TransitionActionType type, const char* pValue, TransitionValue & value) { string str; if (pValue) str = pValue; switch (type) { case TransitionActionType::XY: case TransitionActionType::Size: case TransitionActionType::Pivot: case TransitionActionType::Skew: { string s1, s2; ToolSet::splitString(str, ',', s1, s2); if (s1 == "-") { value.b1 = false; } else { value.f1 = atof(s1.c_str()); value.b1 = true; } if (s2 == "-") { value.b2 = false; } else { value.f2 = atof(s2.c_str()); value.b2 = true; } break; } case TransitionActionType::Alpha: value.f1 = atof(str.c_str()); break; case TransitionActionType::Rotation: value.f1 = atof(str.c_str()); break; case TransitionActionType::Scale: { Vec2 v2; ToolSet::splitString(str, ',', v2); value.f1 = v2.x; value.f2 = v2.y; break; } case TransitionActionType::Color: value.c = ToolSet::convertFromHtmlColor(str.c_str()); break; case TransitionActionType::Animation: { string s1, s2; ToolSet::splitString(str, ',', s1, s2); if (s1 == "-") { value.b1 = false; } else { value.i = atoi(s1.c_str()); value.b1 = true; } value.b = s2 == "p"; break; } case TransitionActionType::Visible: value.b = str == "true"; break; case TransitionActionType::Sound: { string s; ToolSet::splitString(str, ',', value.s, s); if (!s.empty()) { int intv = atoi(s.c_str()); if (intv == 100 || intv == 0) value.f1 = 1; else value.f1 = (float)intv / 100; } else value.f1 = 1; break; } case TransitionActionType::Transition: { string s; ToolSet::splitString(str, ',', value.s, s); if (!s.empty()) value.i = atoi(s.c_str()); else value.i = 1; break; } case TransitionActionType::Shake: { Vec2 v2; ToolSet::splitString(str, ',', v2); value.f1 = v2.x; value.f2 = v2.y; break; } case TransitionActionType::ColorFilter: { Vec4 v4; ToolSet::splitString(str, ',', v4); value.f1 = v4.x; value.f2 = v4.y; value.f3 = v4.z; value.f4 = v4.w; break; } default: break; } } void Transition::setup(TXMLElement * xml) { const char* p; name = xml->Attribute("name"); p = xml->Attribute("options"); if (p) _options = atoi(p); _autoPlay = xml->BoolAttribute("autoPlay"); if (_autoPlay) { p = xml->Attribute("autoPlayRepeat"); if (p) autoPlayRepeat = atoi(p); autoPlayDelay = xml->FloatAttribute("autoPlayDelay"); } TXMLElement* cxml = xml->FirstChildElement("item"); while (cxml) { TransitionItem* item = new TransitionItem(); _items.push_back(item); item->time = (float)cxml->IntAttribute("time") / (float)FRAME_RATE; p = cxml->Attribute("target"); if (p) item->targetId = p; p = cxml->Attribute("type"); if (p) item->type = ToolSet::parseTransitionActionType(p); item->tween = cxml->BoolAttribute("tween"); p = cxml->Attribute("label"); if (p) item->label = p; if (item->tween) { item->duration = (float)cxml->IntAttribute("duration") / FRAME_RATE; if (item->time + item->duration > _maxTime) _maxTime = item->time + item->duration; p = cxml->Attribute("ease"); if (p) item->easeType = ToolSet::parseEaseType(p); item->repeat = cxml->IntAttribute("repeat"); item->yoyo = cxml->BoolAttribute("yoyo"); p = cxml->Attribute("label2"); if (p) item->label2 = p; p = cxml->Attribute("endValue"); if (p) { decodeValue(item->type, cxml->Attribute("startValue"), item->startValue); decodeValue(item->type, p, item->endValue); } else { item->tween = false; decodeValue(item->type, cxml->Attribute("startValue"), item->value); } } else { if (item->time > _maxTime) _maxTime = item->time; decodeValue(item->type, cxml->Attribute("value"), item->value); } cxml = cxml->NextSiblingElement("item"); } } NS_FGUI_END
27.141071
132
0.506086
zeas2
40bba22d34acaf7d3cc2f0ec0642006778387ec2
941
cpp
C++
solutions/edit_distance.cpp
spythrone/gfg-solutions
7bb5198a1a8c7a06d7f81eea78dfa9451252c6b2
[ "MIT" ]
null
null
null
solutions/edit_distance.cpp
spythrone/gfg-solutions
7bb5198a1a8c7a06d7f81eea78dfa9451252c6b2
[ "MIT" ]
null
null
null
solutions/edit_distance.cpp
spythrone/gfg-solutions
7bb5198a1a8c7a06d7f81eea78dfa9451252c6b2
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; class Solution { public: int getsol(string s, string t, int n, int m, vector<vector<int>> &v){ if(n==0) return m; if(m==0) return n; if(v[n][m] > -1) return v[n][m]; if(s[n-1] == t[m-1]) return getsol(s, t, n-1, m-1, v); v[n][m] = 1 + min(getsol(s, t, n, m-1, v), min(getsol(s, t, n-1, m, v), getsol(s, t, n-1, m-1, v))); return v[n][m]; } int editDistance(string s, string t) { int n = s.size(); int m = t.size(); vector<vector<int>> v(n+1, vector<int>(m+1, -1)); int sol = getsol(s, t, n, m, v); return sol; } }; int main() { int T; cin >> T; while (T--) { string s, t; cin >> s >> t; Solution ob; int ans = ob.editDistance(s, t); cout << ans << "\n"; } return 0; }
22.404762
108
0.428268
spythrone
40bc70b2d2bf2ee43f9d3da2ea799c7b4c33856c
11,248
cpp
C++
packages/monte_carlo/collision/electron/src/MonteCarlo_ScreenedRutherfordElasticElectronScatteringDistribution.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
10
2019-11-14T19:58:30.000Z
2021-04-04T17:44:09.000Z
packages/monte_carlo/collision/electron/src/MonteCarlo_ScreenedRutherfordElasticElectronScatteringDistribution.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
43
2020-03-03T19:59:20.000Z
2021-09-08T03:36:08.000Z
packages/monte_carlo/collision/electron/src/MonteCarlo_ScreenedRutherfordElasticElectronScatteringDistribution.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
6
2020-02-12T17:37:07.000Z
2020-09-08T18:59:51.000Z
//---------------------------------------------------------------------------// //! //! \file MonteCarlo_ScreenedRutherfordElasticElectronScatteringDistribution.cpp //! \author Luke Kersting //! \brief The electron screened Rutherford elastic scattering distribution definition //! //---------------------------------------------------------------------------// // FRENSIE Includes #include "MonteCarlo_ScreenedRutherfordElasticElectronScatteringDistribution.hpp" #include "MonteCarlo_KinematicHelpers.hpp" #include "Utility_RandomNumberGenerator.hpp" #include "Utility_SearchAlgorithms.hpp" #include "Utility_3DCartesianVectorHelpers.hpp" #include "Utility_PhysicalConstants.hpp" namespace MonteCarlo{ // Constructor ScreenedRutherfordElasticElectronScatteringDistribution::ScreenedRutherfordElasticElectronScatteringDistribution( const int atomic_number, const bool seltzer_modification_on ) { d_elastic_traits.reset( new ElasticTraits( atomic_number, seltzer_modification_on ) ); } // Evaluate the distribution at the given energy and scattering angle cosine /*! \details The returned value is not normalized to the elastic cutoff * distribution. The correct normalized value can be calculated by multiplying * the the returned value by the pdf of the cutoff distribution at mu peak. * When the scattering angle cosine is very close to one, precision will be lost. */ double ScreenedRutherfordElasticElectronScatteringDistribution::evaluate( const double incoming_energy, const double scattering_angle_cosine ) const { // Make sure the energy and angle are valid testPrecondition( incoming_energy > 0.0 ); testPrecondition( scattering_angle_cosine >= ElasticTraits::mu_peak ); testPrecondition( scattering_angle_cosine <= 1.0 ); return this->evaluatePDF( incoming_energy, scattering_angle_cosine ); } // Evaluate the distribution at the given energy and scattering angle cosine /*! \details The returned value is not normalized to the elastic cutoff * distribution. The correct normalized value can be calculated by multiplying * the the returned value by the pdf of the cutoff distribution at mu peak. * When the scattering angle cosine is very close to one, precision will be lost. */ double ScreenedRutherfordElasticElectronScatteringDistribution::evaluate( const double incoming_energy, const double scattering_angle_cosine, const double eta ) const { // Make sure the energy, eta and angle are valid testPrecondition( incoming_energy > 0.0 ); testPrecondition( scattering_angle_cosine >= ElasticTraits::mu_peak ); testPrecondition( scattering_angle_cosine <= 1.0 ); testPrecondition( eta > 0.0 ); return this->evaluatePDF( incoming_energy, scattering_angle_cosine, eta ); } // Evaluate the PDF at the given energy and scattering angle cosine /*! \details The returned value is not normalized to the elastic cutoff * distribution. The correct normalized value can be calculated by multiplying * the the returned value by the pdf of the cutoff distribution at mu peak. * When the scattering angle cosine is very close to one, precision will be lost. */ double ScreenedRutherfordElasticElectronScatteringDistribution::evaluatePDF( const double incoming_energy, const double scattering_angle_cosine ) const { // Make sure the energy, eta and angle are valid testPrecondition( incoming_energy > 0.0 ); testPrecondition( scattering_angle_cosine >= ElasticTraits::mu_peak ); testPrecondition( scattering_angle_cosine <= 1.0 ); double eta = d_elastic_traits->evaluateMoliereScreeningConstant( incoming_energy ); return this->evaluatePDF( incoming_energy, scattering_angle_cosine, eta ); } // Evaluate the PDF at the given energy and scattering angle cosine /*! \details The returned value is not normalized to the elastic cutoff * distribution. The correct normalized value can be calculated by multiplying * the the returned value by the pdf of the cutoff distribution at mu peak. * When the scattering angle cosine is very close to one, precision will be lost. */ double ScreenedRutherfordElasticElectronScatteringDistribution::evaluatePDF( const double incoming_energy, const double scattering_angle_cosine, const double eta ) const { // Make sure the energy, eta and angle are valid testPrecondition( incoming_energy > 0.0 ); testPrecondition( scattering_angle_cosine >= ElasticTraits::mu_peak ); testPrecondition( scattering_angle_cosine <= 1.0 ); testPrecondition( eta > 0.0 ); double delta_mu = 1.0L - scattering_angle_cosine; return ( ElasticTraits::delta_mu_peak + eta )*( ElasticTraits::delta_mu_peak + eta )/( ( delta_mu + eta )*( delta_mu + eta ) ); } // Evaluate the CDF double ScreenedRutherfordElasticElectronScatteringDistribution::evaluateCDF( const double incoming_energy, const double scattering_angle_cosine ) const { // Make sure the energy and angle are valid testPrecondition( incoming_energy > 0.0 ); testPrecondition( scattering_angle_cosine >= ElasticTraits::mu_peak ); testPrecondition( scattering_angle_cosine <= 1.0 ); double eta = d_elastic_traits->evaluateMoliereScreeningConstant( incoming_energy ); return this->evaluateCDF( incoming_energy, scattering_angle_cosine, eta ); } // Evaluate the CDF double ScreenedRutherfordElasticElectronScatteringDistribution::evaluateCDF( const double incoming_energy, const double scattering_angle_cosine, const double eta ) const { // Make sure the energy, eta and angle cosine are valid testPrecondition( incoming_energy > 0.0 ); testPrecondition( scattering_angle_cosine >= ElasticTraits::mu_peak ); testPrecondition( scattering_angle_cosine <= 1.0 ); testPrecondition( eta > 0.0 ); double delta_mu = 1.0L - scattering_angle_cosine; return ( ElasticTraits::delta_mu_peak + eta )/( delta_mu + eta )* ( delta_mu/ElasticTraits::delta_mu_peak ); } // Sample an outgoing energy and direction from the distribution void ScreenedRutherfordElasticElectronScatteringDistribution::sample( const double incoming_energy, double& outgoing_energy, double& scattering_angle_cosine ) const { // The outgoing energy is always equal to the incoming energy outgoing_energy = incoming_energy; Counter trial_dummy; // Sample an outgoing direction this->sampleAndRecordTrialsImpl( incoming_energy, scattering_angle_cosine, trial_dummy ); } // Sample an outgoing energy and direction and record the number of trials void ScreenedRutherfordElasticElectronScatteringDistribution::sampleAndRecordTrials( const double incoming_energy, double& outgoing_energy, double& scattering_angle_cosine, Counter& trials ) const { // The outgoing energy is always equal to the incoming energy outgoing_energy = incoming_energy; // Sample an outgoing direction this->sampleAndRecordTrialsImpl( incoming_energy, scattering_angle_cosine, trials ); } // Randomly scatter the electron void ScreenedRutherfordElasticElectronScatteringDistribution::scatterElectron( ElectronState& electron, ParticleBank& bank, Data::SubshellType& shell_of_interaction ) const { double scattering_angle_cosine; Counter trial_dummy; // Sample an outgoing direction this->sampleAndRecordTrialsImpl( electron.getEnergy(), scattering_angle_cosine, trial_dummy ); shell_of_interaction =Data::UNKNOWN_SUBSHELL; // Set the new direction electron.rotateDirection( scattering_angle_cosine, this->sampleAzimuthalAngle() ); } // Randomly scatter the positron void ScreenedRutherfordElasticElectronScatteringDistribution::scatterPositron( PositronState& positron, ParticleBank& bank, Data::SubshellType& shell_of_interaction ) const { double scattering_angle_cosine; Counter trial_dummy; // Sample an outgoing direction this->sampleAndRecordTrialsImpl( positron.getEnergy(), scattering_angle_cosine, trial_dummy ); shell_of_interaction =Data::UNKNOWN_SUBSHELL; // Set the new direction positron.rotateDirection( scattering_angle_cosine, this->sampleAzimuthalAngle() ); } // Randomly scatter the adjoint electron void ScreenedRutherfordElasticElectronScatteringDistribution::scatterAdjointElectron( AdjointElectronState& adjoint_electron, ParticleBank& bank, Data::SubshellType& shell_of_interaction ) const { double scattering_angle_cosine; Counter trial_dummy; // Sample an outgoing direction this->sampleAndRecordTrialsImpl( adjoint_electron.getEnergy(), scattering_angle_cosine, trial_dummy ); shell_of_interaction = Data::UNKNOWN_SUBSHELL; // Set the new direction adjoint_electron.rotateDirection( scattering_angle_cosine, this->sampleAzimuthalAngle() ); } // Sample an outgoing direction from the distribution /* \details The CDF is inverted to create the sampling routine. * mu = ( eta mu_p + ( 1 + eta )( 1 - mu_p )CDF )/ * ( eta + ( 1 - mu_p )CDF ) */ void ScreenedRutherfordElasticElectronScatteringDistribution::sampleAndRecordTrialsImpl( const double incoming_energy, double& scattering_angle_cosine, Counter& trials ) const { // Make sure the incoming energy is valid testPrecondition( incoming_energy > 0.0 ); // Increment the number of trials ++trials; double random_number = Utility::RandomNumberGenerator::getRandomNumber<double>(); double eta = d_elastic_traits->evaluateMoliereScreeningConstant( incoming_energy ); scattering_angle_cosine = ( ElasticTraits::mu_peak * eta + ( 1.0L + eta ) * ElasticTraits::delta_mu_peak * random_number )/ ( eta + ElasticTraits::delta_mu_peak * random_number ); // Make sure the scattering angle cosine is valid testPostcondition( scattering_angle_cosine >= ElasticTraits::mu_peak - 1e-15 ); testPostcondition( scattering_angle_cosine <= 1.0+1e-15 ); // There will sometimes be roundoff error in which case the scattering angle // cosine should never be greater than 1 scattering_angle_cosine = std::min( scattering_angle_cosine, 1.0 ); } } // end MonteCarlo namespace //---------------------------------------------------------------------------// // end MonteCarlo_ScreenedRutherfordElasticElectronScatteringDistribution.cpp //---------------------------------------------------------------------------//
39.886525
113
0.69159
bam241
8ad62ce7a35a43ef06ac6339a10e8d5558d65373
631
cpp
C++
code/Remove_Nth_Node_From_End_of_List.cpp
Shiv-sharma-111/Leetcode_Solution
52c941f32f0670271360821a8675225d83fa04a6
[ "MIT" ]
null
null
null
code/Remove_Nth_Node_From_End_of_List.cpp
Shiv-sharma-111/Leetcode_Solution
52c941f32f0670271360821a8675225d83fa04a6
[ "MIT" ]
null
null
null
code/Remove_Nth_Node_From_End_of_List.cpp
Shiv-sharma-111/Leetcode_Solution
52c941f32f0670271360821a8675225d83fa04a6
[ "MIT" ]
null
null
null
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* pre = new ListNode(0); pre->next = head; ListNode* cur = pre; int L = 0; while (cur){ L += 1; cur = cur->next; } cur = pre; int i = 0; while (i < L-n-1){ cur = cur->next; i += 1; } cur->next = cur->next->next; return pre->next; } };
21.033333
55
0.44374
Shiv-sharma-111
8ad646965f25dd10137c3f86db2856f25c57f91c
431
cpp
C++
Source_code_result_01_06/Source_code_result_01_06.cpp
boa9448/Cpp_study
0f445bf68978eba96a34f366ad51fe65cb4e39f8
[ "MIT" ]
1
2022-01-25T10:43:25.000Z
2022-01-25T10:43:25.000Z
Source_code_result_01_06/Source_code_result_01_06.cpp
boa9448/Cpp_study
0f445bf68978eba96a34f366ad51fe65cb4e39f8
[ "MIT" ]
null
null
null
Source_code_result_01_06/Source_code_result_01_06.cpp
boa9448/Cpp_study
0f445bf68978eba96a34f366ad51fe65cb4e39f8
[ "MIT" ]
1
2021-07-18T18:05:45.000Z
2021-07-18T18:05:45.000Z
#include<iostream> int BoxVolume(int lenght, int width, int heght) { return lenght * width * heght; } int BoxVolume(int lenght, int width) { return lenght * width; } int BoxVolume(int lenght) { return lenght; } int main(void) { std::cout << "[3, 3, 3] : " << BoxVolume(3, 3, 3) << std::endl; std::cout << "[5, 5, D] : " << BoxVolume(5, 5) << std::endl; std::cout << "[7, D, D] : " << BoxVolume(7) << std::endl; return 0; }
23.944444
64
0.591647
boa9448
8ad91ca22293db54fcc19764318ec7ebfcd7eea2
27,001
cpp
C++
src/parser/ifc3_parser.cpp
bostonceltics20/phoebe
b7e6294ee32d7f94299cd027ba2e72c3552ab246
[ "MIT" ]
null
null
null
src/parser/ifc3_parser.cpp
bostonceltics20/phoebe
b7e6294ee32d7f94299cd027ba2e72c3552ab246
[ "MIT" ]
null
null
null
src/parser/ifc3_parser.cpp
bostonceltics20/phoebe
b7e6294ee32d7f94299cd027ba2e72c3552ab246
[ "MIT" ]
null
null
null
#include "ifc3_parser.h" #include "constants.h" #include "eigen.h" #include "mpiHelper.h" #include <fstream>// it may be used #include <iostream> #include <set> #ifdef HDF5_AVAIL #include <highfive/H5Easy.hpp> #endif // decide which ifc3 parser to use Interaction3Ph IFC3Parser::parse(Context &context, Crystal &crystal) { // check if this is a phonopy file is set in input if (context.getPhFC3FileName().find("hdf5") != std::string::npos) { if(context.getPhonopyDispFileName().empty()) { Error("You need both fc3.hdf5 and phonopy_disp.yaml " "files to run phono3py." ); } else { if (mpi->mpiHead()) { std::cout << "Using anharmonic force constants from phono3py." << std::endl; } } return parseFromPhono3py(context, crystal); } else { if (mpi->mpiHead()) { std::cout << "Using anharmonic force constants from ShengBTE." << std::endl; } return parseFromShengBTE(context, crystal); } } /* this function is used by phono3py parser, and * constructs a list of vectors which are in the first WS * superCell of the phonon superCell */ Eigen::MatrixXd IFC3Parser::wsInit(Crystal &crystal, Eigen::Vector3i qCoarseGrid) { const int nx = 2; int index = 0; const int nrwsx = 200; Eigen::MatrixXd directUnitCell = crystal.getDirectUnitCell(); Eigen::MatrixXd unitCell(3, 3); unitCell.col(0) = directUnitCell.col(0) * qCoarseGrid(0); unitCell.col(1) = directUnitCell.col(1) * qCoarseGrid(1); unitCell.col(2) = directUnitCell.col(2) * qCoarseGrid(2); Eigen::MatrixXd tmpResult(3, nrwsx); for (int ir = -nx; ir <= nx; ir++) { for (int jr = -nx; jr <= nx; jr++) { for (int kr = -nx; kr <= nx; kr++) { for (int i : {0, 1, 2}) { tmpResult(i, index) = unitCell(i, 0) * ir + unitCell(i, 1) * jr + unitCell(i, 2) * kr; } if (tmpResult.col(index).squaredNorm() > 1.0e-6) { index += 1; } if (index > nrwsx) { Error("WSInit > nrwsx"); } } } } int nrws = index; Eigen::MatrixXd rws(3, nrws); for (int i = 0; i < nrws; i++) { rws.col(i) = tmpResult.col(i); } return rws; } /* given the list of all vectors in the WS superCell (rws), * determine the weight of a particular vector, r */ double wsWeight(const Eigen::VectorXd &r, const Eigen::MatrixXd &rws) { int nreq = 1; for (int ir = 0; ir < rws.cols(); ir++) { double rrt = r.dot(rws.col(ir)); double ck = rrt - rws.col(ir).squaredNorm() / 2.; if (ck > 1.0e-6) { return 0.; } if (abs(ck) < 1.0e-6) { nreq += 1; } } double x = 1. / (double) nreq; return x; } /* find the index of a particular vector in cellPositions */ int findIndexRow(Eigen::MatrixXd &cellPositions, Eigen::Vector3d &position) { int ir2 = -1; for (int i = 0; i < cellPositions.cols(); i++) { if ((position - cellPositions.col(i)).norm() < 1.e-12) { ir2 = i; return ir2; } } if (ir2 == -1) { Error("index not found"); } return ir2; } std::tuple<Eigen::MatrixXd, Eigen::Tensor<double, 3>, Eigen::MatrixXd, Eigen::Tensor<double, 3>> reorderDynamicalMatrix( Crystal &crystal, const Eigen::Vector3i &qCoarseGrid, const Eigen::MatrixXd &rws, Eigen::Tensor<double, 5> &mat3R, Eigen::MatrixXd &cellPositions, const std::vector< std::vector<std::vector<std::vector<std::vector<std::vector<double>>>>>> &ifc3Tensor, const std::vector<int> &cellMap) { int numAtoms = crystal.getNumAtoms(); Eigen::MatrixXd atomicPositions = crystal.getAtomicPositions(); int nr1Big = qCoarseGrid(0) * 2; int nr2Big = qCoarseGrid(1) * 2; int nr3Big = qCoarseGrid(2) * 2; Eigen::MatrixXd directUnitCell = crystal.getDirectUnitCell(); // Count the number of bravais vectors we need to loop over int numBravaisVectors = 0; // Record how many BV with non-zero weight // belong to each atom, so that we can index iR3 // properly later in the code Eigen::VectorXi startBVForAtom(numAtoms); int numBVThisAtom = 0; std::set<std::vector<double>> setBravaisVectors; for (int na = 0; na < numAtoms; na++) { startBVForAtom(na) = numBVThisAtom; for (int nb = 0; nb < numAtoms; nb++) { // loop over all possible indices for the first vector for (int nr1 = -nr1Big; nr1 < nr1Big; nr1++) { for (int nr2 = -nr2Big; nr2 < nr2Big; nr2++) { for (int nr3 = -nr3Big; nr3 < nr3Big; nr3++) { // calculate the R2 vector for atom nb Eigen::Vector3d r2; std::vector<double> R2(3); for (int i : {0, 1, 2}) { R2[i] = nr1 * directUnitCell(i, 0) + nr2 * directUnitCell(i, 1) + nr3 * directUnitCell(i, 2); r2(i) = R2[i] - atomicPositions(na, i) + atomicPositions(nb, i); } double weightR2 = wsWeight(r2, rws); // count this vector if it contributes if (weightR2 > 0) { numBravaisVectors += 1; numBVThisAtom += 1; setBravaisVectors.insert(R2); } } } } } } int numR = setBravaisVectors.size(); std::vector<Eigen::Vector3d> listBravaisVectors; for (auto x : setBravaisVectors) { Eigen::Vector3d R2; for (int i : {0, 1, 2}) { R2(i) = x[i]; } listBravaisVectors.push_back(R2); } Eigen::MatrixXd bravaisVectors(3, numR); Eigen::Tensor<double, 3> weights(numR, numAtoms, numAtoms); bravaisVectors.setZero(); weights.setConstant(0.); for (int na = 0; na < numAtoms; na++) { for (int nb = 0; nb < numAtoms; nb++) { // loop over all possible indices for the first vector for (int nr1 = -nr1Big; nr1 < nr1Big; nr1++) { for (int nr2 = -nr2Big; nr2 < nr2Big; nr2++) { for (int nr3 = -nr3Big; nr3 < nr3Big; nr3++) { // calculate the R2 vector for atom nb Eigen::Vector3d r2, R2; for (int i : {0, 1, 2}) { R2(i) = nr1 * directUnitCell(i, 0) + nr2 * directUnitCell(i, 1) + nr3 * directUnitCell(i, 2); r2(i) = R2(i) - atomicPositions(na, i) + atomicPositions(nb, i); } double weightR2 = wsWeight(r2, rws); // count this vector if it contributes if (weightR2 > 0) { int ir; { auto it = std::find(listBravaisVectors.begin(), listBravaisVectors.end(), R2); if (it == listBravaisVectors.end()) Error("phono3py parser index not found"); ir = it - listBravaisVectors.begin(); } for (int i : {0, 1, 2}) { bravaisVectors(i, ir) = R2(i); } weights(ir, na, nb) = weightR2; } } } } } } //--------- // next, we reorder the dynamical matrix along the bravais lattice vectors // similarly to what was done in the harmonic class. mat3R.resize(3 * numAtoms, 3 * numAtoms, 3 * numAtoms, numR, numR); mat3R.setZero(); double conversion = pow(distanceBohrToAng, 3) / energyRyToEv; // Note: it may be possible to make these loops faster. // It is likely possible to avoid using findIndexRow, // and there could be a faster order of loops. // loop over all possible indices for the first vector for (int nr3 = -nr3Big; nr3 < nr3Big; nr3++) { for (int nr2 = -nr2Big; nr2 < nr2Big; nr2++) { for (int nr1 = -nr1Big; nr1 < nr1Big; nr1++) { Eigen::Vector3d r2; for (int i : {0, 1, 2}) { r2(i) = nr1 * directUnitCell(i, 0) + nr2 * directUnitCell(i, 1) + nr3 * directUnitCell(i, 2); } int iR2; { auto it = std::find(listBravaisVectors.begin(), listBravaisVectors.end(), r2); if (it == listBravaisVectors.end()) continue; iR2 = it - listBravaisVectors.begin(); } // calculate the positive quadrant equivalents int m1 = mod((nr1 + 1), qCoarseGrid(0)); if (m1 <= 0) { m1 += qCoarseGrid(0); } int m2 = mod((nr2 + 1), qCoarseGrid(1)); if (m2 <= 0) { m2 += qCoarseGrid(1); } int m3 = mod((nr3 + 1), qCoarseGrid(2)); if (m3 <= 0) { m3 += qCoarseGrid(2); } m1 += -1; m2 += -1; m3 += -1; // build the unit cell equivalent vectors to look up Eigen::Vector3d rp2; for (int i : {0, 1, 2}) { rp2(i) = m1 * directUnitCell(i, 0) + m2 * directUnitCell(i, 1) + m3 * directUnitCell(i, 2); } // look up the index of the original atom auto ir2 = findIndexRow(cellPositions, rp2); // loop over all possible indices for the R3 vector for (int mr3 = -nr3Big; mr3 < nr3Big; mr3++) { for (int mr2 = -nr2Big; mr2 < nr2Big; mr2++) { for (int mr1 = -nr1Big; mr1 < nr1Big; mr1++) { // calculate the R3 vector for atom nc Eigen::Vector3d r3; for (int i : {0, 1, 2}) { r3(i) = mr1 * directUnitCell(i, 0) + mr2 * directUnitCell(i, 1) + mr3 * directUnitCell(i, 2); } int iR3; { auto it = std::find(listBravaisVectors.begin(), listBravaisVectors.end(), r3); if (it == listBravaisVectors.end()) continue; iR3 = it - listBravaisVectors.begin(); } // calculate the positive quadrant equivalents int p1 = mod((mr1 + 1), qCoarseGrid(0)); if (p1 <= 0) { p1 += qCoarseGrid(0); } int p2 = mod((mr2 + 1), qCoarseGrid(1)); if (p2 <= 0) { p2 += qCoarseGrid(1); } int p3 = mod((mr3 + 1), qCoarseGrid(2)); if (p3 <= 0) { p3 += qCoarseGrid(2); } p1 += -1; p2 += -1; p3 += -1; // build the unit cell equivalent vectors to look up Eigen::Vector3d rp3; for (int i : {0, 1, 2}) { rp3(i) = p1 * directUnitCell(i, 0) + p2 * directUnitCell(i, 1) + p3 * directUnitCell(i, 2); } // look up the index of the original atom auto ir3 = findIndexRow(cellPositions, rp3); // loop over the atoms involved in the first vector for (int na = 0; na < numAtoms; na++) { for (int nb = 0; nb < numAtoms; nb++) { // calculate the R2 vector for atom nb Eigen::Vector3d ra2; for (int i : {0, 1, 2}) { ra2(i) = r2(i) - atomicPositions(na, i) + atomicPositions(nb, i); } // skip vectors which do not contribute double weightR2 = wsWeight(ra2, rws); if (weightR2 == 0) continue; // loop over atoms involved in R3 vector for (int nc = 0; nc < numAtoms; nc++) { // calculate the R3 vector for atom nc Eigen::Vector3d ra3; for (int i : {0, 1, 2}) { ra3(i) = r3(i) - atomicPositions(na, i) + atomicPositions(nc, i); } // continue only if this vector matters double weightR3 = wsWeight(ra3, rws); if (weightR3 == 0) continue; // index back to superCell positions int sat2 = cellMap[nb] + ir2; int sat3 = cellMap[nc] + ir3; // loop over the cartesian directions for (int i : {0, 1, 2}) { for (int j : {0, 1, 2}) { for (int k : {0, 1, 2}) { // compress the cartesian indices and unit cell atom // indices for the first three indices of FC3 auto ind1 = compress2Indices(na, i, numAtoms, 3); auto ind2 = compress2Indices(nb, j, numAtoms, 3); auto ind3 = compress2Indices(nc, k, numAtoms, 3); if ( mat3R(ind1, ind2, ind3, iR3, iR2) != 0 ) { // this doesn't happen, so I am picking each element only once std::cout << "already visited\n"; std::cout << ind1 << " " << ind2 << " " << ind3 << " " << iR3 << " " << iR2 << "\n"; } mat3R(ind1, ind2, ind3, iR3, iR2) += ifc3Tensor[cellMap[na]][sat2][sat3][i][j][k] * conversion; // ifc3Tensor[cellMap[na]][sat2][sat3][i][j][k] * conversion; }// close cartesian loops } } }// r3 loops } } }// close nc loop } // close R2 loops } } }// close nb loop } // close na loop return std::make_tuple(bravaisVectors, weights, bravaisVectors, weights); } Interaction3Ph IFC3Parser::parseFromPhono3py(Context &context, Crystal &crystal) { #ifndef HDF5_AVAIL Error( "Phono3py HDF5 output cannot be read if Phoebe is not built with HDF5."); // return void; #else // Notes about p3py's fc3.hdf5 file: // 3rd order fcs are listed as (num_atom, num_atom, num_atom, 3, 3, 3) // stored in eV/Angstrom3 // Look here for additional details // https://phonopy.github.io/phono3py/output-files.html#fc3-hdf5 // the information we need outside the ifcs3 is in a file called // disp_fc3.yaml, which contains the atomic positions of the // superCell and the displacements of the atoms // The mapping between the superCell and unit cell atoms is // set up so that the first nAtoms*dimSup of the superCell are unit cell // atom #1, and the second nAtoms*dimSup are atom #2, and so on. // First, get num atoms from the crystal int numAtoms = crystal.getNumAtoms(); // Open disp_fc3 file, read superCell positions, nSupAtoms // ========================================================== auto fileName = context.getPhonopyDispFileName(); std::ifstream infile(fileName); std::string line; if (fileName.empty()) { Error("Phono3py required file phonopyDispFileName " "(phono3py_disp.yaml) not specified in input file."); } if (not infile.is_open()) { Error("Phono3py required file phonopyDispFileName " "phono3py_disp.yaml) file not found at " + fileName); } if (mpi->mpiHead()) std::cout << "Reading in " + fileName + "." << std::endl; // read in the dimension information. Eigen::Vector3i qCoarseGrid; while (infile) { std::getline(infile, line); if (line.find("dim:") != std::string::npos) { std::vector<std::string> tok = tokenize(line); //std::istringstream iss(temp); //iss >> qCoarseGrid(0) >> qCoarseGrid(1) >> qCoarseGrid(2); qCoarseGrid(0) = std::stoi(tok[1]); qCoarseGrid(1) = std::stoi(tok[2]); qCoarseGrid(2) = std::stoi(tok[3]); break; } } // First, we open the phonopyDispFileName to check the distance units. // Phono3py uses Bohr for QE calculations and Angstrom for VASP // so, here we decide which is the correct unit, // by parsing the phono3py_disp.yaml file double distanceConversion = 1. / distanceBohrToAng; while (infile) { std::getline(infile, line); if (line.find("length") != std::string::npos) { if (line.find("au") != std::string::npos) { distanceConversion = 1.; // distances already in Bohr } break; } } // read the rest of the file to look for superCell positions std::vector<std::vector<double>> supPositionsVec; Eigen::MatrixXd lattice(3, 3); int ilatt = 3; bool readSupercell = false; while (infile) { getline(infile, line); // we dont want to read the positions after phonon_supercell_matrix, // so we break here if(line.find("phonon_supercell_matrix") != std::string::npos) { break; } // read all the lines after we see the flag for the supercell // no matter what, the ifc3 info will always come after "supercell:" // and supercell comes before phonon_supercell in the output file if (line.find("supercell:") != std::string::npos) { readSupercell = true; } // if this is a cell position, save it if (line.find("coordinates: ") != std::string::npos && readSupercell) { std::vector<double> position = {0.,0.,0.}; std::vector<std::string> tok = tokenize(line); position[0] = std::stod(tok[2]); position[1] = std::stod(tok[3]); position[2] = std::stod(tok[4]); supPositionsVec.push_back(position); } if (ilatt < 3 && readSupercell) { // count down lattice lines // convert from angstrom to bohr std::vector<std::string> tok = tokenize(line); lattice(ilatt, 0) = std::stod(tok[2]); lattice(ilatt, 1) = std::stod(tok[3]); lattice(ilatt, 2) = std::stod(tok[4]); ilatt++; } if (line.find("lattice:") != std::string::npos && readSupercell) { ilatt = 0; } } infile.close(); infile.clear(); // number of atoms in the supercell for later use int numSupAtoms = supPositionsVec.size(); int nr = numSupAtoms / numAtoms; // check that this matches the ifc2 atoms int numAtomsCheck = numSupAtoms/ (qCoarseGrid[0]*qCoarseGrid[1]*qCoarseGrid[2]); if (numAtomsCheck != numAtoms) { Error("IFC3s seem to come from a cell with a different number\n" "of atoms than the IFC2s. Check your inputs." "FC2 atoms: " + std::to_string(numAtoms) + " FC3 atoms: " + std::to_string(numAtomsCheck)); } // convert std::vectors to Eigen formats required by the // next part of phoebe Eigen::MatrixXd supPositions(numSupAtoms, 3); for ( int n = 0; n < numSupAtoms; n++) { for (int i : {0, 1, 2}) { supPositions(n,i) = supPositionsVec[n][i]; } } // convert distances to Bohr lattice *= distanceConversion; // convert positions to cartesian, in bohr for (int i = 0; i < numSupAtoms; i++) { Eigen::Vector3d temp(supPositions(i, 0), supPositions(i, 1), supPositions(i, 2)); Eigen::Vector3d temp2 = lattice.transpose() * temp; supPositions(i, 0) = temp2(0); supPositions(i, 1) = temp2(1); supPositions(i, 2) = temp2(2); } // Open the hdf5 file containing the IFC3s // =================================================== fileName = context.getPhFC3FileName(); if (fileName.empty()) { Error("Phono3py phFC3FileName (fc3.hdf5) file not " "specified in input file."); } if (mpi->mpiHead()) std::cout << "Reading in " + fileName + "." << std::endl; // user info about memory // note, this is for a temporary array -- // later we reduce to (numAtoms*3)^3 * numRVecs { double rx; double x = pow(numSupAtoms * 3, 3) / pow(1024., 3) * sizeof(rx); if (mpi->mpiHead()) { std::cout << "Allocating " << x << " (GB) (per MPI process) for the 3-ph coupling matrix." << std::endl; } } // set up buffer to read entire matrix // have to use this monstrosity because the // phono3py data is shaped as a 6 dimensional array, // and eigen tensor is not supported by highFive std::vector< std::vector<std::vector<std::vector<std::vector<std::vector<double>>>>>> ifc3Tensor; std::vector<int> cellMap; try { HighFive::File file(fileName, HighFive::File::ReadOnly); // Set up hdf5 datasets HighFive::DataSet difc3 = file.getDataSet("/fc3"); HighFive::DataSet dcellMap = file.getDataSet("/p2s_map"); // read in the ifc3 data difc3.read(ifc3Tensor); dcellMap.read(cellMap); } catch (std::exception &error) { if(mpi->mpiHead()) std::cout << error.what() << std::endl; Error("Issue reading fc3.hdf5 file. Make sure it exists at " + fileName + "\n and is not open by some other persisting processes."); } // Determine the list of possible R2, R3 vectors // the distances from the origin unit cell to another // unit cell in the positive quadrant superCell Eigen::MatrixXd cellPositions(3, nr); cellPositions.setZero(); // get all possible ws cell vectors Eigen::MatrixXd rws = wsInit(crystal, qCoarseGrid); // find all possible vectors R2, R3, which are // position of atomPosSuperCell - atomPosUnitCell = R for (int is = 0; is < nr; is++) { cellPositions(0, is) = supPositions(is, 0) - supPositions(0, 0); cellPositions(1, is) = supPositions(is, 1) - supPositions(0, 1); cellPositions(2, is) = supPositions(is, 2) - supPositions(0, 2); } // reshape to FC3 format Eigen::Tensor<double, 5> FC3; auto tup = reorderDynamicalMatrix(crystal, qCoarseGrid, rws, FC3, cellPositions, ifc3Tensor, cellMap); auto bravaisVectors2 = std::get<0>(tup); auto weights2 = std::get<1>(tup); auto bravaisVectors3 = std::get<2>(tup); auto weights3 = std::get<3>(tup); if (mpi->mpiHead()) { std::cout << "Successfully parsed anharmonic " "phono3py files.\n" << std::endl; } // Create interaction3Ph object Interaction3Ph interaction3Ph(crystal, FC3, bravaisVectors2, bravaisVectors3, weights2, weights3); return interaction3Ph; #endif } Interaction3Ph IFC3Parser::parseFromShengBTE(Context &context, Crystal &crystal) { auto fileName = context.getPhFC3FileName(); // Open IFC3 file std::ifstream infile(fileName); std::string line; if (not infile.is_open()) { Error("FC3 file not found"); } if (mpi->mpiHead()) std::cout << "Reading in " + fileName + "." << std::endl; // Number of triplets std::getline(infile, line); int numTriplets = std::stoi(line); // user info about memory { double rx; double x = 27 * numTriplets / pow(1024., 3) * sizeof(rx); if (mpi->mpiHead()) { std::cout << "Allocating " << x << " (GB) (per MPI process) for the 3-ph coupling matrix.\n" << std::endl; } } // Allocate quantities to be read Eigen::Tensor<double, 4> ifc3Tensor(3, 3, 3, numTriplets); ifc3Tensor.setZero(); Eigen::Tensor<double, 3> cellPositions(numTriplets, 2, 3); cellPositions.setZero(); Eigen::Tensor<int, 2> displacedAtoms(numTriplets, 3); displacedAtoms.setZero(); for (int i = 0; i < numTriplets; i++) {// loop over all triplets // empty line std::getline(infile, line); // line with a counter std::getline(infile, line); // Read position of 2nd cell std::getline(infile, line); std::istringstream iss(line); std::string item; int j = 0; while (iss >> item) { cellPositions(i, 0, j) = std::stod(item) / distanceBohrToAng; j++; } // Read position of 3rd cell std::getline(infile, line); std::istringstream iss2(line); j = 0; while (iss2 >> item) { cellPositions(i, 1, j) = std::stod(item) / distanceBohrToAng; j++; } // Read triplet atom indices std::getline(infile, line); std::istringstream iss3(line); j = 0; int i0; while (iss3 >> i0) { displacedAtoms(i, j) = i0 - 1; j++; } // Read the 3x3x3 force constants tensor int i1, i2, i3; double d4; double conversion = pow(distanceBohrToAng, 3) / energyRyToEv; for (int a : {0, 1, 2}) { for (int b : {0, 1, 2}) { for (int c : {0, 1, 2}) { std::getline(infile, line); std::istringstream iss4(line); while (iss4 >> i1 >> i2 >> i3 >> d4) { ifc3Tensor(c, b, a, i) = d4 * conversion; } } } } } // Close IFC3 file infile.close(); // TODO Round cellPositions to the nearest lattice vectors // start processing ifc3s into FC3 matrix int numAtoms = crystal.getNumAtoms(); int numBands = numAtoms * 3; int nr2 = 0; int nr3 = 0; std::vector<Eigen::Vector3d> tmpCellPositions2, tmpCellPositions3; for (int it = 0; it < numTriplets; it++) { // load the position of the 2 atom in the current triplet Eigen::Vector3d position2, position3; for (int ic : {0, 1, 2}) { position2(ic) = cellPositions(it, 0, ic); position3(ic) = cellPositions(it, 1, ic); } // now check if this element is in the list. bool found2 = false; if (std::find(tmpCellPositions2.begin(), tmpCellPositions2.end(), position2) != tmpCellPositions2.end()) { found2 = true; } bool found3 = false; if (std::find(tmpCellPositions3.begin(), tmpCellPositions3.end(), position3) != tmpCellPositions3.end()) { found3 = true; } if (!found2) { tmpCellPositions2.push_back(position2); nr2++; } if (!found3) { tmpCellPositions3.push_back(position3); nr3++; } } Eigen::MatrixXd cellPositions2(3, nr2); Eigen::MatrixXd cellPositions3(3, nr3); cellPositions2.setZero(); cellPositions3.setZero(); for (int i = 0; i < nr2; i++) { cellPositions2.col(i) = tmpCellPositions2[i]; } for (int i = 0; i < nr3; i++) { cellPositions3.col(i) = tmpCellPositions3[i]; } Eigen::Tensor<double, 5> FC3(numBands, numBands, numBands, nr2, nr3); FC3.setZero(); for (int it = 0; it < numTriplets; it++) {// sum over all triplets int ia1 = displacedAtoms(it, 0); int ia2 = displacedAtoms(it, 1); int ia3 = displacedAtoms(it, 2); Eigen::Vector3d position2, position3; for (int ic : {0, 1, 2}) { position2(ic) = cellPositions(it, 0, ic); position3(ic) = cellPositions(it, 1, ic); } int ir2 = findIndexRow(cellPositions2, position2); int ir3 = findIndexRow(cellPositions3, position3); for (int ic1 : {0, 1, 2}) { for (int ic2 : {0, 1, 2}) { for (int ic3 : {0, 1, 2}) { auto ind1 = compress2Indices(ia1, ic1, numAtoms, 3); auto ind2 = compress2Indices(ia2, ic2, numAtoms, 3); auto ind3 = compress2Indices(ia3, ic3, numAtoms, 3); FC3(ind1, ind2, ind3, ir3, ir2) = ifc3Tensor(ic3, ic2, ic1, it); } } } } Eigen::Tensor<double, 3> weights(nr2, numAtoms, numAtoms); weights.setConstant(1.); Interaction3Ph interaction3Ph(crystal, FC3, cellPositions2, cellPositions3, weights, weights); if (mpi->mpiHead()) { std::cout << "Successfully parsed anharmonic " "ShengBTE files.\n" << std::endl; } return interaction3Ph; }
33.334568
109
0.560757
bostonceltics20
8ad93e641a30183442ab18bb01ef7af9edafcf80
2,806
hpp
C++
boost/actor/response_promise.hpp
syoummer/boost.actor
58f35499bac8871b8f5b0b024246a467b63c6fb0
[ "BSL-1.0" ]
2
2015-03-20T21:11:16.000Z
2020-01-20T08:05:41.000Z
boost/actor/response_promise.hpp
syoummer/boost.actor
58f35499bac8871b8f5b0b024246a467b63c6fb0
[ "BSL-1.0" ]
null
null
null
boost/actor/response_promise.hpp
syoummer/boost.actor
58f35499bac8871b8f5b0b024246a467b63c6fb0
[ "BSL-1.0" ]
null
null
null
/******************************************************************************\ * * * ____ _ _ _ * * | __ ) ___ ___ ___| |_ / \ ___| |_ ___ _ __ * * | _ \ / _ \ / _ \/ __| __| / _ \ / __| __/ _ \| '__| * * | |_) | (_) | (_) \__ \ |_ _ / ___ \ (__| || (_) | | * * |____/ \___/ \___/|___/\__(_)_/ \_\___|\__\___/|_| * * * * * * * * Copyright (C) 2011 - 2014 * * Dominik Charousset <dominik.charousset@haw-hamburg.de> * * * * Distributed under the Boost Software License, Version 1.0. See * * accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt * \******************************************************************************/ #ifndef BOOST_ACTOR_RESPONSE_PROMISE_HPP #define BOOST_ACTOR_RESPONSE_PROMISE_HPP #include "boost/actor/actor.hpp" #include "boost/actor/message.hpp" #include "boost/actor/actor_addr.hpp" #include "boost/actor/message_id.hpp" namespace boost { namespace actor { /** * @brief A response promise can be used to deliver a uniquely identifiable * response message from the server (i.e. receiver of the request) * to the client (i.e. the sender of the request). */ class response_promise { public: response_promise() = default; response_promise(response_promise&&) = default; response_promise(const response_promise&) = default; response_promise& operator=(response_promise&&) = default; response_promise& operator=(const response_promise&) = default; response_promise(const actor_addr& from, const actor_addr& to, const message_id& response_id); /** * @brief Queries whether this promise is still valid, i.e., no response * was yet delivered to the client. */ inline explicit operator bool() const { // handle is valid if it has a receiver return static_cast<bool>(m_to); } /** * @brief Sends @p response_message and invalidates this handle afterwards. */ void deliver(message response_message); private: actor_addr m_from; actor_addr m_to; message_id m_id; }; } // namespace actor } // namespace boost #endif // BOOST_ACTOR_RESPONSE_PROMISE_HPP
36.921053
80
0.465075
syoummer
8adaf485d11acb911b7c988d600c130fce03a36e
1,927
cpp
C++
Filesystem/Problem33/main.cpp
vegemil/ModernCppChallengeStudy
52c2bb22c76ae3f3a883ae479cd70ac27513e78d
[ "MIT" ]
null
null
null
Filesystem/Problem33/main.cpp
vegemil/ModernCppChallengeStudy
52c2bb22c76ae3f3a883ae479cd70ac27513e78d
[ "MIT" ]
null
null
null
Filesystem/Problem33/main.cpp
vegemil/ModernCppChallengeStudy
52c2bb22c76ae3f3a883ae479cd70ac27513e78d
[ "MIT" ]
null
null
null
// 33. Tabular printing of a list of processes // Suppose you have a snapshot of the list of all processes in a system. The // information for each process includes name, identifier, status (which can be // either running or suspended), account name (under which the process runs), // memory size in bytes, and platform (which can be either 32-bit or 64-bit). Your // task is to writer a function that takes such a list of processes and prints them // to the console alphabetically, in tabular format. All columns must be left- // aligned, except for the memory column which must be right-aligned. The value // of the memory size must be displayed in KB. The following is an example of the // output of this function: // chrome.exe 1044 Running marius.bancila 25180 32-bit // chrome.exe 10100 Running marius.bancila 227756 32-bit // cmd.exe 512 Running SYSTEM 48 64-bit // explorer.exe 7108 Running marius.bancila 29529 64-bit // skype.exe 22456 Syspended marius.bancila 656 64-bit // 33. 표로 정리된 프로세스들의 목록을 출력 // 당신이 어떤 시스템의 모든 프로세스들의 목록을 스냅샷으로 가지고 있다고 가정하자. 각 프로세 // 스의 정보는 이름, 식별자, 상태(running 또는 suspended 두 가지 상태일 수 있다), 계정 이름 // (프로세스가 동작중인 계정), 메모리 크기(byte), 그리고 플랫폼(32-bit 또는 64-bit 일 수 있 // 다)을 포함한다. 당신의 임무는 프로세스의 목록을 가져와서, 콘솔에 알파벳 표의 형식으로 목록 // 을 출력하는 함수를 작성하는 것이다. 모든 컬럼은 반드시 left-aligned 여야 하며, 메모리 컬럼 // 만 예외적으로 right-aligned 이다. 메모리 크기 값은 반드시 KB로 보여져야 한다. 아래에 보여 // 지는 것은, 이 하마수의 출력 예제이다: // chrome.exe 1044 Running marius.bancila 25180 32-bit // chrome.exe 10100 Running marius.bancila 227756 32-bit // cmd.exe 512 Running SYSTEM 48 64-bit // explorer.exe 7108 Running marius.bancila 29529 64-bit // skype.exe 22456 Syspended marius.bancila 656 64-bit #include "gsl/gsl" // create `main` function for catch #define CATCH_CONFIG_MAIN #include "catch2/catch.hpp" // Redirect CMake's #define to C++ constexpr string constexpr auto TestName = PROJECT_NAME_STRING; TEST_CASE("tokenize", "[Joining strings]") { }
48.175
83
0.741048
vegemil
8add19cc54e5ebc2f76a2f519d709fc650857952
1,090
cpp
C++
src/rendering/ui/ui_object.cpp
krait-games/hyperion-engine
5c52085658630fbf0992f794ecfcb25325b80b1c
[ "MIT" ]
21
2022-01-23T15:20:59.000Z
2022-03-31T22:10:14.000Z
src/rendering/ui/ui_object.cpp
krait-games/hyperion-engine
5c52085658630fbf0992f794ecfcb25325b80b1c
[ "MIT" ]
2
2022-01-30T22:24:58.000Z
2022-03-28T02:37:07.000Z
src/rendering/ui/ui_object.cpp
krait-games/hyperion-engine
5c52085658630fbf0992f794ecfcb25325b80b1c
[ "MIT" ]
2
2022-02-10T13:55:26.000Z
2022-03-31T22:10:16.000Z
#include "ui_object.h" #include "../shader_manager.h" #include "../shaders/ui/ui_object_shader.h" #include "../../util/mesh_factory.h" #include <algorithm> namespace hyperion { namespace ui { UIObject::UIObject(const std::string &name) : Node(name) { GetMaterial().depth_test = false; GetMaterial().depth_write = false; GetMaterial().alpha_blended = true; SetRenderable(MeshFactory::CreateQuad()); GetRenderable()->SetShader(ShaderManager::GetInstance()->GetShader<UIObjectShader>(ShaderProperties())); GetSpatial().SetBucket(Spatial::Bucket::RB_SCREEN); } void UIObject::UpdateTransform() { Node::UpdateTransform(); } bool UIObject::IsMouseOver(double x, double y) const { if (x < GetGlobalTranslation().x) { return false; } if (x > GetGlobalTranslation().x + GetGlobalScale().x) { return false; } if (y < GetGlobalTranslation().y) { return false; } if (y > GetGlobalTranslation().y + GetGlobalScale().y) { return false; } return true; } } // namespace ui } // namespace hyperion
22.244898
108
0.659633
krait-games
8adeb089c923a09e22cd22039c3730dd63aa7448
1,608
cpp
C++
B2G/gecko/content/svg/content/src/SVGMotionSMILAttr.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/content/svg/content/src/SVGMotionSMILAttr.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/content/svg/content/src/SVGMotionSMILAttr.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* representation of a dummy attribute targeted by <animateMotion> element */ #include "SVGMotionSMILAttr.h" #include "SVGMotionSMILType.h" #include "nsISMILAnimationElement.h" #include "nsSMILValue.h" #include "nsAttrValue.h" #include "nsGkAtoms.h" #include "nsDebug.h" #include "nsCRT.h" #include "nsSVGLength2.h" #include "nsSMILParserUtils.h" namespace mozilla { nsresult SVGMotionSMILAttr::ValueFromString(const nsAString& aStr, const nsISMILAnimationElement* aSrcElement, nsSMILValue& aValue, bool& aPreventCachingOfSandwich) const { NS_NOTREACHED("Shouldn't using nsISMILAttr::ValueFromString for parsing " "animateMotion's SMIL values."); return NS_ERROR_FAILURE; } nsSMILValue SVGMotionSMILAttr::GetBaseValue() const { return nsSMILValue(&SVGMotionSMILType::sSingleton); } void SVGMotionSMILAttr::ClearAnimValue() { mSVGElement->SetAnimateMotionTransform(nullptr); } nsresult SVGMotionSMILAttr::SetAnimValue(const nsSMILValue& aValue) { gfxMatrix matrix = SVGMotionSMILType::CreateMatrix(aValue); mSVGElement->SetAnimateMotionTransform(&matrix); return NS_OK; } const nsIContent* SVGMotionSMILAttr::GetTargetNode() const { return mSVGElement; } } // namespace mozilla
27.254237
79
0.710821
wilebeast
8ae4e2ebf43f447bb0a682a75c0a49e80ec0fec8
32,004
hpp
C++
include/GlobalNamespace/PlayerSpecificSettings.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/PlayerSpecificSettings.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/PlayerSpecificSettings.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: NoteJumpDurationTypeSettings #include "GlobalNamespace/NoteJumpDurationTypeSettings.hpp" // Including type: EnvironmentEffectsFilterPreset #include "GlobalNamespace/EnvironmentEffectsFilterPreset.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: Nullable`1<T> template<typename T> struct Nullable_1; } // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: BeatmapDifficulty struct BeatmapDifficulty; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Forward declaring type: PlayerSpecificSettings class PlayerSpecificSettings; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::GlobalNamespace::PlayerSpecificSettings); DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::PlayerSpecificSettings*, "", "PlayerSpecificSettings"); // Type namespace: namespace GlobalNamespace { // Size: 0x44 #pragma pack(push, 1) // Autogenerated type: PlayerSpecificSettings // [TokenAttribute] Offset: FFFFFFFF class PlayerSpecificSettings : public ::Il2CppObject { public: #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // private System.Boolean _leftHanded // Size: 0x1 // Offset: 0x10 bool leftHanded; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: leftHanded and: playerHeight char __padding0[0x3] = {}; // private System.Single _playerHeight // Size: 0x4 // Offset: 0x14 float playerHeight; // Field size check static_assert(sizeof(float) == 0x4); // private System.Boolean _automaticPlayerHeight // Size: 0x1 // Offset: 0x18 bool automaticPlayerHeight; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: automaticPlayerHeight and: sfxVolume char __padding2[0x3] = {}; // private System.Single _sfxVolume // Size: 0x4 // Offset: 0x1C float sfxVolume; // Field size check static_assert(sizeof(float) == 0x4); // private System.Boolean _reduceDebris // Size: 0x1 // Offset: 0x20 bool reduceDebris; // Field size check static_assert(sizeof(bool) == 0x1); // private System.Boolean _noTextsAndHuds // Size: 0x1 // Offset: 0x21 bool noTextsAndHuds; // Field size check static_assert(sizeof(bool) == 0x1); // private System.Boolean _noFailEffects // Size: 0x1 // Offset: 0x22 bool noFailEffects; // Field size check static_assert(sizeof(bool) == 0x1); // private System.Boolean _advancedHud // Size: 0x1 // Offset: 0x23 bool advancedHud; // Field size check static_assert(sizeof(bool) == 0x1); // private System.Boolean _autoRestart // Size: 0x1 // Offset: 0x24 bool autoRestart; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: autoRestart and: saberTrailIntensity char __padding8[0x3] = {}; // private System.Single _saberTrailIntensity // Size: 0x4 // Offset: 0x28 float saberTrailIntensity; // Field size check static_assert(sizeof(float) == 0x4); // private NoteJumpDurationTypeSettings _noteJumpDurationTypeSettings // Size: 0x4 // Offset: 0x2C ::GlobalNamespace::NoteJumpDurationTypeSettings noteJumpDurationTypeSettings; // Field size check static_assert(sizeof(::GlobalNamespace::NoteJumpDurationTypeSettings) == 0x4); // private System.Single _noteJumpFixedDuration // Size: 0x4 // Offset: 0x30 float noteJumpFixedDuration; // Field size check static_assert(sizeof(float) == 0x4); // private System.Single _noteJumpStartBeatOffset // Size: 0x4 // Offset: 0x34 float noteJumpStartBeatOffset; // Field size check static_assert(sizeof(float) == 0x4); // private System.Boolean _hideNoteSpawnEffect // Size: 0x1 // Offset: 0x38 bool hideNoteSpawnEffect; // Field size check static_assert(sizeof(bool) == 0x1); // private System.Boolean _adaptiveSfx // Size: 0x1 // Offset: 0x39 bool adaptiveSfx; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: adaptiveSfx and: environmentEffectsFilterDefaultPreset char __padding14[0x2] = {}; // private EnvironmentEffectsFilterPreset _environmentEffectsFilterDefaultPreset // Size: 0x4 // Offset: 0x3C ::GlobalNamespace::EnvironmentEffectsFilterPreset environmentEffectsFilterDefaultPreset; // Field size check static_assert(sizeof(::GlobalNamespace::EnvironmentEffectsFilterPreset) == 0x4); // private EnvironmentEffectsFilterPreset _environmentEffectsFilterExpertPlusPreset // Size: 0x4 // Offset: 0x40 ::GlobalNamespace::EnvironmentEffectsFilterPreset environmentEffectsFilterExpertPlusPreset; // Field size check static_assert(sizeof(::GlobalNamespace::EnvironmentEffectsFilterPreset) == 0x4); public: // Get instance field reference: private System.Boolean _leftHanded bool& dyn__leftHanded(); // Get instance field reference: private System.Single _playerHeight float& dyn__playerHeight(); // Get instance field reference: private System.Boolean _automaticPlayerHeight bool& dyn__automaticPlayerHeight(); // Get instance field reference: private System.Single _sfxVolume float& dyn__sfxVolume(); // Get instance field reference: private System.Boolean _reduceDebris bool& dyn__reduceDebris(); // Get instance field reference: private System.Boolean _noTextsAndHuds bool& dyn__noTextsAndHuds(); // Get instance field reference: private System.Boolean _noFailEffects bool& dyn__noFailEffects(); // Get instance field reference: private System.Boolean _advancedHud bool& dyn__advancedHud(); // Get instance field reference: private System.Boolean _autoRestart bool& dyn__autoRestart(); // Get instance field reference: private System.Single _saberTrailIntensity float& dyn__saberTrailIntensity(); // Get instance field reference: private NoteJumpDurationTypeSettings _noteJumpDurationTypeSettings ::GlobalNamespace::NoteJumpDurationTypeSettings& dyn__noteJumpDurationTypeSettings(); // Get instance field reference: private System.Single _noteJumpFixedDuration float& dyn__noteJumpFixedDuration(); // Get instance field reference: private System.Single _noteJumpStartBeatOffset float& dyn__noteJumpStartBeatOffset(); // Get instance field reference: private System.Boolean _hideNoteSpawnEffect bool& dyn__hideNoteSpawnEffect(); // Get instance field reference: private System.Boolean _adaptiveSfx bool& dyn__adaptiveSfx(); // Get instance field reference: private EnvironmentEffectsFilterPreset _environmentEffectsFilterDefaultPreset ::GlobalNamespace::EnvironmentEffectsFilterPreset& dyn__environmentEffectsFilterDefaultPreset(); // Get instance field reference: private EnvironmentEffectsFilterPreset _environmentEffectsFilterExpertPlusPreset ::GlobalNamespace::EnvironmentEffectsFilterPreset& dyn__environmentEffectsFilterExpertPlusPreset(); // public System.Boolean get_leftHanded() // Offset: 0x1372B30 bool get_leftHanded(); // public System.Single get_playerHeight() // Offset: 0x1372B38 float get_playerHeight(); // public System.Boolean get_automaticPlayerHeight() // Offset: 0x1372B40 bool get_automaticPlayerHeight(); // public System.Single get_sfxVolume() // Offset: 0x1372B48 float get_sfxVolume(); // public System.Boolean get_reduceDebris() // Offset: 0x1372B50 bool get_reduceDebris(); // public System.Boolean get_noTextsAndHuds() // Offset: 0x1372B58 bool get_noTextsAndHuds(); // public System.Boolean get_noFailEffects() // Offset: 0x1372B60 bool get_noFailEffects(); // public System.Boolean get_advancedHud() // Offset: 0x1372B68 bool get_advancedHud(); // public System.Boolean get_autoRestart() // Offset: 0x1372B70 bool get_autoRestart(); // public System.Single get_saberTrailIntensity() // Offset: 0x1372B78 float get_saberTrailIntensity(); // public NoteJumpDurationTypeSettings get_noteJumpDurationTypeSettings() // Offset: 0x1372B80 ::GlobalNamespace::NoteJumpDurationTypeSettings get_noteJumpDurationTypeSettings(); // public System.Single get_noteJumpFixedDuration() // Offset: 0x1372B88 float get_noteJumpFixedDuration(); // public System.Single get_noteJumpStartBeatOffset() // Offset: 0x1372B90 float get_noteJumpStartBeatOffset(); // public System.Boolean get_hideNoteSpawnEffect() // Offset: 0x1372B98 bool get_hideNoteSpawnEffect(); // public System.Boolean get_adaptiveSfx() // Offset: 0x1372BA0 bool get_adaptiveSfx(); // public EnvironmentEffectsFilterPreset get_environmentEffectsFilterDefaultPreset() // Offset: 0x1372BA8 ::GlobalNamespace::EnvironmentEffectsFilterPreset get_environmentEffectsFilterDefaultPreset(); // public EnvironmentEffectsFilterPreset get_environmentEffectsFilterExpertPlusPreset() // Offset: 0x1372BB0 ::GlobalNamespace::EnvironmentEffectsFilterPreset get_environmentEffectsFilterExpertPlusPreset(); // public System.Void .ctor(System.Boolean leftHanded, System.Single playerHeight, System.Boolean automaticPlayerHeight, System.Single sfxVolume, System.Boolean reduceDebris, System.Boolean noTextsAndHuds, System.Boolean noFailEffects, System.Boolean advancedHud, System.Boolean autoRestart, System.Single saberTrailIntensity, NoteJumpDurationTypeSettings noteJumpDurationTypeSettings, System.Single noteJumpFixedDuration, System.Single noteJumpStartBeatOffset, System.Boolean hideNoteSpawnEffect, System.Boolean adaptiveSfx, EnvironmentEffectsFilterPreset environmentEffectsFilterDefaultPreset, EnvironmentEffectsFilterPreset environmentEffectsFilterExpertPlusPreset) // Offset: 0x1372C2C template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static PlayerSpecificSettings* New_ctor(bool leftHanded, float playerHeight, bool automaticPlayerHeight, float sfxVolume, bool reduceDebris, bool noTextsAndHuds, bool noFailEffects, bool advancedHud, bool autoRestart, float saberTrailIntensity, ::GlobalNamespace::NoteJumpDurationTypeSettings noteJumpDurationTypeSettings, float noteJumpFixedDuration, float noteJumpStartBeatOffset, bool hideNoteSpawnEffect, bool adaptiveSfx, ::GlobalNamespace::EnvironmentEffectsFilterPreset environmentEffectsFilterDefaultPreset, ::GlobalNamespace::EnvironmentEffectsFilterPreset environmentEffectsFilterExpertPlusPreset) { static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::PlayerSpecificSettings::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<PlayerSpecificSettings*, creationType>(leftHanded, playerHeight, automaticPlayerHeight, sfxVolume, reduceDebris, noTextsAndHuds, noFailEffects, advancedHud, autoRestart, saberTrailIntensity, noteJumpDurationTypeSettings, noteJumpFixedDuration, noteJumpStartBeatOffset, hideNoteSpawnEffect, adaptiveSfx, environmentEffectsFilterDefaultPreset, environmentEffectsFilterExpertPlusPreset))); } // public PlayerSpecificSettings CopyWith(System.Nullable`1<System.Boolean> leftHanded, System.Nullable`1<System.Single> playerHeight, System.Nullable`1<System.Boolean> automaticPlayerHeight, System.Nullable`1<System.Single> sfxVolume, System.Nullable`1<System.Boolean> reduceDebris, System.Nullable`1<System.Boolean> noTextsAndHuds, System.Nullable`1<System.Boolean> noFailEffects, System.Nullable`1<System.Boolean> advancedHud, System.Nullable`1<System.Boolean> autoRestart, System.Nullable`1<System.Single> saberTrailIntensity, System.Nullable`1<NoteJumpDurationTypeSettings> noteJumpDurationTypeSettings, System.Nullable`1<System.Single> noteJumpFixedDuration, System.Nullable`1<System.Single> noteJumpStartBeatOffset, System.Nullable`1<System.Boolean> hideNoteSpawnEffect, System.Nullable`1<System.Boolean> adaptiveSfx, System.Nullable`1<EnvironmentEffectsFilterPreset> environmentEffectsFilterDefaultPreset, System.Nullable`1<EnvironmentEffectsFilterPreset> environmentEffectsFilterExpertPlusPreset) // Offset: 0x1371A10 ::GlobalNamespace::PlayerSpecificSettings* CopyWith(::System::Nullable_1<bool> leftHanded, ::System::Nullable_1<float> playerHeight, ::System::Nullable_1<bool> automaticPlayerHeight, ::System::Nullable_1<float> sfxVolume, ::System::Nullable_1<bool> reduceDebris, ::System::Nullable_1<bool> noTextsAndHuds, ::System::Nullable_1<bool> noFailEffects, ::System::Nullable_1<bool> advancedHud, ::System::Nullable_1<bool> autoRestart, ::System::Nullable_1<float> saberTrailIntensity, ::System::Nullable_1<::GlobalNamespace::NoteJumpDurationTypeSettings> noteJumpDurationTypeSettings, ::System::Nullable_1<float> noteJumpFixedDuration, ::System::Nullable_1<float> noteJumpStartBeatOffset, ::System::Nullable_1<bool> hideNoteSpawnEffect, ::System::Nullable_1<bool> adaptiveSfx, ::System::Nullable_1<::GlobalNamespace::EnvironmentEffectsFilterPreset> environmentEffectsFilterDefaultPreset, ::System::Nullable_1<::GlobalNamespace::EnvironmentEffectsFilterPreset> environmentEffectsFilterExpertPlusPreset); // public EnvironmentEffectsFilterPreset GetEnvironmentEffectsFilterPreset(BeatmapDifficulty difficulty) // Offset: 0x1372D4C ::GlobalNamespace::EnvironmentEffectsFilterPreset GetEnvironmentEffectsFilterPreset(::GlobalNamespace::BeatmapDifficulty difficulty); // public System.Void .ctor() // Offset: 0x1372BB8 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static PlayerSpecificSettings* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::PlayerSpecificSettings::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<PlayerSpecificSettings*, creationType>())); } }; // PlayerSpecificSettings #pragma pack(pop) static check_size<sizeof(PlayerSpecificSettings), 64 + sizeof(::GlobalNamespace::EnvironmentEffectsFilterPreset)> __GlobalNamespace_PlayerSpecificSettingsSizeCheck; static_assert(sizeof(PlayerSpecificSettings) == 0x44); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_leftHanded // Il2CppName: get_leftHanded template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_leftHanded)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_leftHanded", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_playerHeight // Il2CppName: get_playerHeight template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_playerHeight)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_playerHeight", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_automaticPlayerHeight // Il2CppName: get_automaticPlayerHeight template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_automaticPlayerHeight)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_automaticPlayerHeight", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_sfxVolume // Il2CppName: get_sfxVolume template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_sfxVolume)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_sfxVolume", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_reduceDebris // Il2CppName: get_reduceDebris template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_reduceDebris)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_reduceDebris", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_noTextsAndHuds // Il2CppName: get_noTextsAndHuds template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_noTextsAndHuds)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_noTextsAndHuds", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_noFailEffects // Il2CppName: get_noFailEffects template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_noFailEffects)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_noFailEffects", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_advancedHud // Il2CppName: get_advancedHud template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_advancedHud)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_advancedHud", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_autoRestart // Il2CppName: get_autoRestart template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_autoRestart)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_autoRestart", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_saberTrailIntensity // Il2CppName: get_saberTrailIntensity template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_saberTrailIntensity)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_saberTrailIntensity", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_noteJumpDurationTypeSettings // Il2CppName: get_noteJumpDurationTypeSettings template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::NoteJumpDurationTypeSettings (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_noteJumpDurationTypeSettings)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_noteJumpDurationTypeSettings", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_noteJumpFixedDuration // Il2CppName: get_noteJumpFixedDuration template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_noteJumpFixedDuration)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_noteJumpFixedDuration", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_noteJumpStartBeatOffset // Il2CppName: get_noteJumpStartBeatOffset template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_noteJumpStartBeatOffset)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_noteJumpStartBeatOffset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_hideNoteSpawnEffect // Il2CppName: get_hideNoteSpawnEffect template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_hideNoteSpawnEffect)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_hideNoteSpawnEffect", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_adaptiveSfx // Il2CppName: get_adaptiveSfx template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_adaptiveSfx)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_adaptiveSfx", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_environmentEffectsFilterDefaultPreset // Il2CppName: get_environmentEffectsFilterDefaultPreset template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::EnvironmentEffectsFilterPreset (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_environmentEffectsFilterDefaultPreset)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_environmentEffectsFilterDefaultPreset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_environmentEffectsFilterExpertPlusPreset // Il2CppName: get_environmentEffectsFilterExpertPlusPreset template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::EnvironmentEffectsFilterPreset (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_environmentEffectsFilterExpertPlusPreset)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_environmentEffectsFilterExpertPlusPreset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::CopyWith // Il2CppName: CopyWith template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::PlayerSpecificSettings* (GlobalNamespace::PlayerSpecificSettings::*)(::System::Nullable_1<bool>, ::System::Nullable_1<float>, ::System::Nullable_1<bool>, ::System::Nullable_1<float>, ::System::Nullable_1<bool>, ::System::Nullable_1<bool>, ::System::Nullable_1<bool>, ::System::Nullable_1<bool>, ::System::Nullable_1<bool>, ::System::Nullable_1<float>, ::System::Nullable_1<::GlobalNamespace::NoteJumpDurationTypeSettings>, ::System::Nullable_1<float>, ::System::Nullable_1<float>, ::System::Nullable_1<bool>, ::System::Nullable_1<bool>, ::System::Nullable_1<::GlobalNamespace::EnvironmentEffectsFilterPreset>, ::System::Nullable_1<::GlobalNamespace::EnvironmentEffectsFilterPreset>)>(&GlobalNamespace::PlayerSpecificSettings::CopyWith)> { static const MethodInfo* get() { static auto* leftHanded = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg; static auto* playerHeight = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Single")})->byval_arg; static auto* automaticPlayerHeight = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg; static auto* sfxVolume = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Single")})->byval_arg; static auto* reduceDebris = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg; static auto* noTextsAndHuds = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg; static auto* noFailEffects = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg; static auto* advancedHud = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg; static auto* autoRestart = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg; static auto* saberTrailIntensity = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Single")})->byval_arg; static auto* noteJumpDurationTypeSettings = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "NoteJumpDurationTypeSettings")})->byval_arg; static auto* noteJumpFixedDuration = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Single")})->byval_arg; static auto* noteJumpStartBeatOffset = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Single")})->byval_arg; static auto* hideNoteSpawnEffect = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg; static auto* adaptiveSfx = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg; static auto* environmentEffectsFilterDefaultPreset = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "EnvironmentEffectsFilterPreset")})->byval_arg; static auto* environmentEffectsFilterExpertPlusPreset = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "EnvironmentEffectsFilterPreset")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "CopyWith", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{leftHanded, playerHeight, automaticPlayerHeight, sfxVolume, reduceDebris, noTextsAndHuds, noFailEffects, advancedHud, autoRestart, saberTrailIntensity, noteJumpDurationTypeSettings, noteJumpFixedDuration, noteJumpStartBeatOffset, hideNoteSpawnEffect, adaptiveSfx, environmentEffectsFilterDefaultPreset, environmentEffectsFilterExpertPlusPreset}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::GetEnvironmentEffectsFilterPreset // Il2CppName: GetEnvironmentEffectsFilterPreset template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::EnvironmentEffectsFilterPreset (GlobalNamespace::PlayerSpecificSettings::*)(::GlobalNamespace::BeatmapDifficulty)>(&GlobalNamespace::PlayerSpecificSettings::GetEnvironmentEffectsFilterPreset)> { static const MethodInfo* get() { static auto* difficulty = &::il2cpp_utils::GetClassFromName("", "BeatmapDifficulty")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "GetEnvironmentEffectsFilterPreset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{difficulty}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
70.030635
1,010
0.76731
RedBrumbler
8ae5d409101796e92d796219f8f8aed03f9df2df
741
cpp
C++
FortuneHunter/FortuneHunter/ConfirmQuitCommandProcessor.cpp
playdeezgames/FortuneHunter
44bbf19e728aa8c3330a08876809dd471b92311b
[ "MIT" ]
null
null
null
FortuneHunter/FortuneHunter/ConfirmQuitCommandProcessor.cpp
playdeezgames/FortuneHunter
44bbf19e728aa8c3330a08876809dd471b92311b
[ "MIT" ]
null
null
null
FortuneHunter/FortuneHunter/ConfirmQuitCommandProcessor.cpp
playdeezgames/FortuneHunter
44bbf19e728aa8c3330a08876809dd471b92311b
[ "MIT" ]
null
null
null
#include "ConfirmQuitCommandProcessor.h" void ConfirmQuitCommandProcessor::OnCommand(const Command& command) { switch (command) { case Command::UP: case Command::DOWN: confirmState = (confirmState==ConfirmState::YES) ? (ConfirmState::NO) : (ConfirmState::YES); return; case Command::BACK: SetUIState(UIState::MAIN_MENU); return; case Command::GREEN: switch (confirmState) { case ConfirmState::YES: SetUIState(UIState::QUIT); return; case ConfirmState::NO: SetUIState(UIState::MAIN_MENU); return; default: return; } } } ConfirmQuitCommandProcessor::ConfirmQuitCommandProcessor ( UIState& uiState, ConfirmState& confirmState ) : BaseCommandProcessor(uiState) , confirmState(confirmState) { }
20.027027
94
0.731444
playdeezgames
8ae6248f6889794f112db1896ac4c959f75d3c90
712
cpp
C++
casbin/persist/file_adapter/batch_file_adapter.cpp
xcaptain/casbin-cpp
d90e72d921f4a3369692913cfbcab2047343a49b
[ "Apache-2.0" ]
null
null
null
casbin/persist/file_adapter/batch_file_adapter.cpp
xcaptain/casbin-cpp
d90e72d921f4a3369692913cfbcab2047343a49b
[ "Apache-2.0" ]
null
null
null
casbin/persist/file_adapter/batch_file_adapter.cpp
xcaptain/casbin-cpp
d90e72d921f4a3369692913cfbcab2047343a49b
[ "Apache-2.0" ]
null
null
null
#pragma once #include "pch.h" #include "./batch_file_adapter.h" #include "../../exception/unsupported_operation_exception.h" // NewAdapter is the constructor for Adapter. BatchFileAdapter* BatchFileAdapter :: NewAdapter(string file_path) { BatchFileAdapter* adapter = new BatchFileAdapter; adapter->file_path = file_path; adapter->filtered = false; return adapter; } void BatchFileAdapter :: AddPolicies(string sec, string p_type, vector<vector<string>> rules) { throw UnsupportedOperationException("not implemented hello"); } void BatchFileAdapter :: RemovePolicies(string sec, string p_type, vector<vector<string>> rules) { throw UnsupportedOperationException("not implemented"); }
32.363636
98
0.761236
xcaptain
8ae653a690ed033b5e708e7021f98998082f0ca1
1,160
cc
C++
base/allocator/win_allocator.cc
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
212
2015-01-31T11:55:58.000Z
2022-02-22T06:35:11.000Z
base/allocator/win_allocator.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
5
2015-03-27T14:29:23.000Z
2019-09-25T13:23:12.000Z
base/allocator/win_allocator.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
221
2015-01-07T06:21:24.000Z
2022-02-11T02:51:12.000Z
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This is a simple allocator based on the windows heap. extern "C" { HANDLE win_heap; bool win_heap_init(bool use_lfh) { win_heap = HeapCreate(0, 0, 0); if (win_heap == NULL) return false; if (use_lfh) { ULONG enable_lfh = 2; HeapSetInformation(win_heap, HeapCompatibilityInformation, &enable_lfh, sizeof(enable_lfh)); // NOTE: Setting LFH may fail. Vista already has it enabled. // And under the debugger, it won't use LFH. So we // ignore any errors. } return true; } void* win_heap_malloc(size_t size) { return HeapAlloc(win_heap, 0, size); } void win_heap_free(void* size) { HeapFree(win_heap, 0, size); } void* win_heap_realloc(void* ptr, size_t size) { if (!ptr) return win_heap_malloc(size); if (!size) { win_heap_free(ptr); return NULL; } return HeapReAlloc(win_heap, 0, ptr, size); } size_t win_heap_msize(void* ptr) { return HeapSize(win_heap, 0, ptr); } } // extern "C"
22.745098
73
0.662931
Scopetta197
8ae8f26615e9d030e89494029408e687f67685d0
2,290
cpp
C++
auditory/package/voicelock/native/audiorecog/frontend/preprocess/preprocess.cpp
yao-matrix/mProto
e5fecce2693056ac53f7d34d00801829ea1094c3
[ "Apache-2.0" ]
3
2016-11-06T04:55:11.000Z
2019-05-18T06:56:10.000Z
auditory/package/voicelock/native/audiorecog/frontend/preprocess/preprocess.cpp
yao-matrix/mProto
e5fecce2693056ac53f7d34d00801829ea1094c3
[ "Apache-2.0" ]
null
null
null
auditory/package/voicelock/native/audiorecog/frontend/preprocess/preprocess.cpp
yao-matrix/mProto
e5fecce2693056ac53f7d34d00801829ea1094c3
[ "Apache-2.0" ]
4
2016-11-27T01:08:41.000Z
2021-03-11T05:32:04.000Z
#include <math.h> #include <stdlib.h> #include <stdio.h> #include <memory.h> #include <string.h> #include "math/mmath.h" #include "AudioDef.h" #include "AudioUtil.h" #include "AudioRecog.h" #include "AudioConfig.h" /* signal normalization */ void sig_normalize( AUD_Int16s *pInBuf, AUD_Int16s *pOutBuf, AUD_Int32s len ) { AUD_Int32s i, v; AUD_Double mean = 0; for ( i = 0; i < len; i++ ) { mean += pInBuf[i]; } mean /= len; for ( i = 0; i < len; i++ ) { v = (AUD_Int32s)round( pInBuf[i] - mean ); v = SATURATE_16s( v ); pOutBuf[i] = (AUD_Int16s)v; } #if 1 AUD_Double x = 0; AUD_Double tmp; for ( i = 0; i < len; i++ ) { x += (AUD_Double)pOutBuf[i] * pOutBuf[i]; } x /= len; // x = sqrt( x ); if ( x < 1024 ) { for ( i = 0; i < len; i++ ) { // tmp = pOutBuf[i] / x * 8192; tmp = pOutBuf[i] * 256; tmp = SATURATE_16s( tmp ); pOutBuf[i] = (AUD_Int16s)tmp; } } #endif #if 0 AUD_Int16s maxMag = 0, mag = 0; for ( i = 0; i < len; i++ ) { mag = abs( pOutBuf[i] ); if ( maxMag < mag ) { maxMag = mag; } } for ( i = 0; i < len; i++ ) { pOutBuf[i] = (AUD_Int16s)( (AUD_Double)pOutBuf[i] / maxMag * 0.25 * 32768. ); } #endif return; } /* signal pre-emphasis */ void sig_preemphasis( AUD_Int16s *pInBuf, AUD_Int16s *pOutBuf, AUD_Int32s len ) { AUD_Int16s x0, x1; AUD_Double out; AUD_Int32s i; x1 = pInBuf[0]; for ( i = 1; i < len; i++ ) { x0 = pInBuf[i]; out = x0 - PREEMPHASIS_FACTOR * x1; out = SATURATE_16s( out ); pOutBuf[i] = (AUD_Int16s)out; x1 = x0; } pOutBuf[0] = (AUD_Int16s)( ( 1 - PREEMPHASIS_FACTOR ) * pInBuf[0] ); return; } /* signal de-emphasis */ void sig_deemphasis( AUD_Int16s *pInBuf, AUD_Int16s *pOutBuf, AUD_Int32s len ) { AUD_Int16s y1; AUD_Double out; AUD_Int32s i; y1 = 0; for ( i = 0; i < len; i++ ) { out = pInBuf[i] + PREEMPHASIS_FACTOR * y1; out = SATURATE_16s( out ); pOutBuf[i] = (AUD_Int16s)out; y1 = pOutBuf[i]; } return; }
17.615385
85
0.500437
yao-matrix
8aef81e187d39ab8b4eb1c25fb16944072ff28a5
3,382
cc
C++
src/lib/hooks/tests/full_callout_library.cc
sebschrader/debian-pkg-isc-kea
1bdb18f90c48dd9674374fb8454d0efb846656bc
[ "Apache-2.0" ]
null
null
null
src/lib/hooks/tests/full_callout_library.cc
sebschrader/debian-pkg-isc-kea
1bdb18f90c48dd9674374fb8454d0efb846656bc
[ "Apache-2.0" ]
null
null
null
src/lib/hooks/tests/full_callout_library.cc
sebschrader/debian-pkg-isc-kea
1bdb18f90c48dd9674374fb8454d0efb846656bc
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2013-2015 Internet Systems Consortium, Inc. ("ISC") // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. /// @file /// @brief Full callout library /// /// This is source of a test library for various test (LibraryManager and /// HooksManager). The characteristics of the library produced from this /// file are: /// /// The characteristics of this library are: /// /// - All three framework functions are supplied (version(), load() and /// unload()), with unload() creating a marker file. The test code checks /// for the presence of this file, so verifying that unload() has been run. /// /// - One standard and two non-standard callouts are supplied, with the latter /// being registered by the load() function. /// /// All callouts do trivial calculations, the result of all being called in /// sequence being /// /// @f[ ((7 * data_1) - data_2) * data_3 @f] /// /// ...where data_1, data_2 and data_3 are the values passed in arguments of /// the same name to the three callouts (data_1 passed to hookpt_one, data_2 /// to hookpt_two etc.) and the result is returned in the argument "result". #include <config.h> #include <hooks/hooks.h> #include <hooks/tests/marker_file.h> #include <fstream> using namespace isc::hooks; extern "C" { // Callouts int context_create(CalloutHandle& handle) { handle.setContext("result", static_cast<int>(7)); handle.setArgument("result", static_cast<int>(7)); return (0); } // First callout adds the passed "data_1" argument to the initialized context // value of 7. (Note that the value set by context_create is accessed through // context and not the argument, so checking that context is correctly passed // between callouts in the same library.) int hookpt_one(CalloutHandle& handle) { int data; handle.getArgument("data_1", data); int result; handle.getArgument("result", result); result *= data; handle.setArgument("result", result); return (0); } // Second callout subtracts the passed value of data_2 from the current // running total. static int hook_nonstandard_two(CalloutHandle& handle) { int data; handle.getArgument("data_2", data); int result; handle.getArgument("result", result); result -= data; handle.setArgument("result", result); return (0); } // Final callout multiplies the current running total by data_3. static int hook_nonstandard_three(CalloutHandle& handle) { int data; handle.getArgument("data_3", data); int result; handle.getArgument("result", result); result *= data; handle.setArgument("result", result); return (0); } // Framework functions int version() { return (KEA_HOOKS_VERSION); } int load(LibraryHandle& handle) { // Initialize if the main image was statically linked #ifdef USE_STATIC_LINK hooksStaticLinkInit(); #endif // Register the non-standard functions handle.registerCallout("hookpt_two", hook_nonstandard_two); handle.registerCallout("hookpt_three", hook_nonstandard_three); return (0); } int unload() { // Create the marker file. std::fstream marker; marker.open(MARKER_FILE, std::fstream::out); marker.close(); return (0); } };
24.867647
78
0.693968
sebschrader
8af10568434c6c5ef925481bedf9d47380ad0372
3,167
cpp
C++
tests/stage2/motion/motion.cpp
PtCu/RenderToy
a53be2b6d8c91f7b132cee47b377e327a9605fbb
[ "MIT" ]
2
2021-03-17T07:32:18.000Z
2021-04-01T14:58:51.000Z
tests/stage2/motion/motion.cpp
PtCu/RenderToy
a53be2b6d8c91f7b132cee47b377e327a9605fbb
[ "MIT" ]
null
null
null
tests/stage2/motion/motion.cpp
PtCu/RenderToy
a53be2b6d8c91f7b132cee47b377e327a9605fbb
[ "MIT" ]
null
null
null
#include <render_toy.h> #include <ROOT_PATH.h> using namespace platinum; using namespace glm; using namespace std; const static string root_path(ROOT_PATH); const static string assets_path = root_path + "/assets/"; void random_scene(Scene &world) { int n = 500; shared_ptr<Object> sph; sph = make_shared<Sphere>(vec3(0, -1000, 0), 1000, make_shared<Lambertian>(vec3(0.5, 0.5, 0.5))); world.AddObject(sph); int i = 1; for (int a = -11; a < 11; a++) { for (int b = -11; b < 11; b++) { float choose_mat = Random::RandomInUnitFloat(); vec3 center(a + 0.9 * Random::RandomInUnitFloat(), 0.2, b + 0.9 * Random::RandomInUnitFloat()); if (length(center - vec3(4, 0.2, 0)) > 0.9) { if (choose_mat < 0.8) { // diffuse sph = make_shared<MovingSphere>(center, center + vec3(0, 0.5 * Random::RandomInUnitFloat(), 0), 0.0, 1.0, 0.2, make_shared<Lambertian>(vec3(Random::RandomInUnitFloat() * Random::RandomInUnitFloat(), Random::RandomInUnitFloat() * Random::RandomInUnitFloat(), Random::RandomInUnitFloat() * Random::RandomInUnitFloat()))); } else if (choose_mat < 0.95) { // metal sph = make_shared<Sphere>(center, 0.2f, make_shared<Metal>(vec3(0.5 * (1 + Random::RandomInUnitFloat()), 0.5 * (1 + Random::RandomInUnitFloat()), 0.5 * (1 + Random::RandomInUnitFloat())), 0.5 * Random::RandomInUnitFloat())); } else { // glass sph = make_shared<Sphere>(center, 0.2f, make_shared<Dielectric>(1.5)); } world.AddObject(sph); } } } world.AddObject(make_shared<Sphere>(vec3(0, 1, 0), 1.0, make_shared<Dielectric>(1.5))); world.AddObject(make_shared<Sphere>(vec3(-4, 1, 0), 1.0, make_shared<Lambertian>(vec3(0.4, 0.2, 0.1)))); world.AddObject(make_shared<Sphere>(vec3(4, 1, 0), 1.0, make_shared<Metal>(vec3(0.7, 0.6, 0.5), 0.0))); } int main() { int nx = 1200; int ny = 800; int ns = 100; Scene world(true,false); random_scene(world); vec3 lookfrom(13, 2, 3); vec3 lookat(0, 0, 0); float dist_to_focus = 10.0f; float aperture = 0.1f; Camera cam(lookfrom, lookat, vec3(0, -1, 0), 45, static_cast<float>(nx) / static_cast<float>(ny), aperture, dist_to_focus); Renderer render(nx, ny, 3, "motion.png", ns); render.Render(world, cam); world.Reset(); return 0; }
39.098765
142
0.462899
PtCu
8af2d89b5a52efc264df5851264851c7046575bc
463
cpp
C++
gameboy/src/harucar/LuaCommandViewer.cpp
JJhuk/study_emu
24f8a55496486d534edd1cb713b056d862641a22
[ "MIT" ]
9
2020-05-22T09:42:42.000Z
2022-01-06T00:51:15.000Z
gameboy/src/harucar/LuaCommandViewer.cpp
JJhuk/study_emu
24f8a55496486d534edd1cb713b056d862641a22
[ "MIT" ]
1
2021-04-18T06:56:03.000Z
2021-04-18T06:56:03.000Z
gameboy/src/harucar/LuaCommandViewer.cpp
JJhuk/study_emu
24f8a55496486d534edd1cb713b056d862641a22
[ "MIT" ]
3
2020-05-17T15:31:14.000Z
2022-01-06T12:18:03.000Z
// // Created by nhy20 on 2020-11-01. // #include "LuaCommandViewer.h" #include "imgui.h" void LuaCommandViewer::Render(std::shared_ptr<Base::Interface::Provider> provider_ptr, std::shared_ptr<UI::Structure::UIEventProtocol> protocol_ptr) { ImGui::Begin("Lua Command Viewer"); if (ImGui::Button("Reload")) { protocol_ptr->AddEvent("Lua:Reload"); } if (ImGui::Button("Execute")) { protocol_ptr->AddEvent("Lua:Execute"); } ImGui::End(); }
18.52
86
0.682505
JJhuk
8af594afdcbf53ad17242d6af37d99888f3303bb
2,599
hpp
C++
source/Utilities/BasicCameraControllers.hpp
dantros/MonaEngine
e3d0048c2fe2dd282b84686f0e31e5741714222b
[ "MIT" ]
null
null
null
source/Utilities/BasicCameraControllers.hpp
dantros/MonaEngine
e3d0048c2fe2dd282b84686f0e31e5741714222b
[ "MIT" ]
null
null
null
source/Utilities/BasicCameraControllers.hpp
dantros/MonaEngine
e3d0048c2fe2dd282b84686f0e31e5741714222b
[ "MIT" ]
1
2021-09-07T03:06:01.000Z
2021-09-07T03:06:01.000Z
#pragma once #ifndef BASICCAMERACONTROLLER_HPP #define BASICCAMERACONTROLLER_HPP #include "../World/World.hpp" #include "../Platform/KeyCodes.hpp" namespace Mona { class BasicPerspectiveCamera : public GameObject { public: BasicPerspectiveCamera() = default; virtual void UserStartUp(World& world) noexcept override { m_transform = world.AddComponent<TransformComponent>(*this); m_camera = world.AddComponent<CameraComponent>(*this); m_transform->Translate(glm::vec3(0.0f, -5.0f, 0.0f)); auto& input = world.GetInput(); glm::vec2 res = world.GetWindow().GetWindowDimensions(); screenPos = glm::vec2(1 / res.x, 1 / res.y) * glm::vec2(input.GetMousePosition()); } void SetActive(bool active) { m_active = active; } virtual void UserUpdate(World& world, float timeStep) noexcept override { auto& input = world.GetInput(); if(m_active) { if (input.IsKeyPressed(MONA_KEY_A)) { glm::vec3 right = m_transform->GetRightVector(); m_transform->Translate(-m_cameraSpeed * timeStep * right); } else if (input.IsKeyPressed(MONA_KEY_D)) { glm::vec3 right = m_transform->GetRightVector(); m_transform->Translate(m_cameraSpeed * timeStep * right); } if (input.IsKeyPressed(MONA_KEY_W)) { glm::vec3 front = m_transform->GetFrontVector(); m_transform->Translate(m_cameraSpeed * timeStep * front); } else if (input.IsKeyPressed(MONA_KEY_S)) { glm::vec3 front = m_transform->GetFrontVector(); m_transform->Translate(-m_cameraSpeed * timeStep * front); } if (input.IsKeyPressed(MONA_KEY_E)) { m_transform->Rotate(glm::vec3(0.0f,1.0f,0.0f), m_rollSpeed * timeStep); } else if (input.IsKeyPressed(MONA_KEY_Q)) { m_transform->Rotate(glm::vec3(0.0f, 1.0f, 0.0f), -m_rollSpeed * timeStep); } } glm::vec2 res = world.GetWindow().GetWindowDimensions(); glm::vec2 newScreenPos = glm::vec2(1/res.x, 1/res.y) * glm::vec2(input.GetMousePosition()); glm::vec2 delta = newScreenPos - screenPos; if (glm::length2(delta) != 0.0f && m_active) { float amountX = delta.x * m_rotationSpeed; float amountY = delta.y * m_rotationSpeed; m_transform->Rotate(glm::vec3(0.0f,0.0f,-1.0f), amountX); m_transform->Rotate(glm::vec3(-1.0, 0.0f, 0.0f), amountY); } screenPos = newScreenPos; } private: bool m_active = true; float m_cameraSpeed = 2.0f; float m_rollSpeed = 1.5f; float m_rotationSpeed = 1.5f; TransformHandle m_transform; CameraHandle m_camera; glm::vec2 screenPos; }; } #endif
30.576471
94
0.671027
dantros
8af9fdf0734d9c3275feef5e98183229dcb64966
2,372
hpp
C++
dal/platform/platform.hpp
lnsongxf/Derivatives-Algorithms-Lib
4ba95f55a26b7f5f872a39db306de9206bfc2a3e
[ "MIT" ]
2
2022-02-23T02:10:02.000Z
2022-02-23T02:10:04.000Z
dal/platform/platform.hpp
lnsongxf/Derivatives-Algorithms-Lib
4ba95f55a26b7f5f872a39db306de9206bfc2a3e
[ "MIT" ]
null
null
null
dal/platform/platform.hpp
lnsongxf/Derivatives-Algorithms-Lib
4ba95f55a26b7f5f872a39db306de9206bfc2a3e
[ "MIT" ]
null
null
null
// // Created by Cheng Li on 17-12-19. // #pragma once #include <cassert> #include <dal/utilities/noncopyable.hpp> #include <memory> #include <utility> #ifdef MIN #undef MIN #endif #ifdef MAX #undef MAX #endif using std::make_pair; using std::pair; template <class T_> using scoped_ptr = const std::unique_ptr<T_>; namespace Dal { using Time_ = double; template <class = double> class Vector_; template <class = double> class Matrix_; template <class = double> class SquareMatrix_; class Dictionary_; constexpr const double EPSILON = 2e-14; constexpr const double INF = 1e29; constexpr const double PI = 3.1415926535897932; constexpr const double M_SQRT_2 = 1.4142135623730951; template <class T_> inline bool IsZero(const T_& x) { return x < Dal::EPSILON && -x < Dal::EPSILON; } template <class T_> inline bool IsPositive(const T_& x) { return x >= Dal::EPSILON; } template <class T_> inline bool IsNegative(const T_& x) { return x <= -Dal::EPSILON; } template <class T_> inline T_ Square(const T_& x) { return x * x; } template <class T_> inline T_ Cube(const T_& x) { return x * x * x; } template <class T_> inline T_ Max(const T_& a, const T_& b) { return a > b ? a : b; } template <class T_> inline T_ Min(const T_& a, const T_& b) { return a < b ? a : b; } struct Empty_ {}; template <class T_> class Handle_ : public std::shared_ptr<const T_> { typedef typename std::shared_ptr<const T_> base_t; public: Handle_() : base_t() {} explicit Handle_(const T_* src) : base_t(src) {} explicit Handle_(const base_t& src) : base_t(src) {} bool IsEmpty() const { return !base_t::get(); } }; template <class T_, class U_> Handle_<T_> handle_cast(const std::shared_ptr<U_>& src) { return Handle_<T_>(std::dynamic_pointer_cast<const T_>(src)); }; } // namespace Dal #define RETURN_STATIC(...) \ static __VA_ARGS__ RETVAL; \ return RETVAL #define DYN_PTR(n, t, s) t* n = dynamic_cast<t*>(s) #define LENGTH(a) (sizeof(a) / sizeof(a[0])) #define VALUE_TYPE_OF(expr) std::remove_const_t<std::remove_reference_t<decltype(expr)>>
28.238095
120
0.604553
lnsongxf
8afb77a9feaee8d9945ff6cd962d4f467e66f58e
5,812
cpp
C++
test_conformance/basic/test_writeimage_int16.cpp
jainvikas8/OpenCL-CTS
b7e7a3eb65d80d6847bd522f66f876fd5f6fe938
[ "Apache-2.0" ]
130
2017-05-16T14:15:25.000Z
2022-03-26T22:31:05.000Z
test_conformance/basic/test_writeimage_int16.cpp
jainvikas8/OpenCL-CTS
b7e7a3eb65d80d6847bd522f66f876fd5f6fe938
[ "Apache-2.0" ]
919
2017-05-19T08:01:20.000Z
2022-03-29T23:08:35.000Z
test_conformance/basic/test_writeimage_int16.cpp
jainvikas8/OpenCL-CTS
b7e7a3eb65d80d6847bd522f66f876fd5f6fe938
[ "Apache-2.0" ]
125
2017-05-17T01:14:15.000Z
2022-03-25T22:34:42.000Z
// // Copyright (c) 2017 The Khronos Group 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 "harness/compat.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include "procs.h" static const char *rgba16_write_kernel_code = "__kernel void test_rgba16_write(__global unsigned short *src, write_only image2d_t dstimg)\n" "{\n" " int tid_x = get_global_id(0);\n" " int tid_y = get_global_id(1);\n" " int indx = tid_y * get_image_width(dstimg) + tid_x;\n" " float4 color;\n" "\n" " indx *= 4;\n" " color = (float4)((float)src[indx+0], (float)src[indx+1], (float)src[indx+2], (float)src[indx+3]);\n" " color /= 65535.0f;\n" " write_imagef(dstimg, (int2)(tid_x, tid_y), color);\n" "\n" "}\n"; static unsigned short * generate_16bit_image(int w, int h, MTdata d) { cl_ushort *ptr = (cl_ushort*)malloc(w * h * 4 * sizeof(cl_ushort)); int i; for (i=0; i<w*h*4; i++) ptr[i] = (cl_ushort)genrand_int32(d); return ptr; } // normalized 16bit ints ... get dived by 64k then muled by 64k... // give the poor things some tolerance #define MAX_ERR 1 static int verify_16bit_image(const char *string, cl_ushort *image, cl_ushort *outptr, int w, int h) { int i; for (i=0; i<w*h*4; i++) { if (abs(outptr[i] - image[i]) > MAX_ERR) { log_error("%s failed\n", string); return -1; } } log_info("%s passed\n", string); return 0; } int test_writeimage_int16(cl_device_id device, cl_context context, cl_command_queue queue, int num_elements) { cl_mem streams[3]; cl_program program; cl_kernel kernel[2]; cl_image_format img_format; cl_ushort *input_ptr, *output_ptr; size_t threads[2]; int img_width = 512; int img_height = 512; int i, err, any_err = 0; size_t origin[3] = {0, 0, 0}; size_t region[3] = {img_width, img_height, 1}; size_t length = img_width * img_height * 4 * sizeof(cl_ushort); PASSIVE_REQUIRE_IMAGE_SUPPORT( device ) MTdata d = init_genrand( gRandomSeed ); input_ptr = generate_16bit_image(img_width, img_height, d); free_mtdata(d); d = NULL; output_ptr = (cl_ushort*)malloc(length); img_format.image_channel_order = CL_RGBA; img_format.image_channel_data_type = CL_UNORM_INT16; streams[0] = create_image_2d(context, CL_MEM_READ_WRITE, &img_format, img_width, img_height, 0, NULL, NULL); if (!streams[0]) { log_error("create_image_2d failed\n"); return -1; } img_format.image_channel_order = CL_RGBA; img_format.image_channel_data_type = CL_UNORM_INT16; streams[1] = create_image_2d(context, CL_MEM_WRITE_ONLY, &img_format, img_width, img_height, 0, NULL, NULL); if (!streams[1]) { log_error("create_image_2d failed\n"); return -1; } streams[2] = clCreateBuffer(context, CL_MEM_READ_WRITE, length, NULL, NULL); if (!streams[2]) { log_error("clCreateArray failed\n"); return -1; } err = clEnqueueWriteBuffer(queue, streams[2], CL_TRUE, 0, length, input_ptr, 0, NULL, NULL); if (err != CL_SUCCESS) { log_error("clEnqueueWriteBuffer failed\n"); return -1; } err = create_single_kernel_helper(context, &program, &kernel[0], 1, &rgba16_write_kernel_code, "test_rgba16_write" ); if (err) return -1; kernel[1] = clCreateKernel(program, "test_rgba16_write", NULL); if (!kernel[1]) { log_error("clCreateKernel failed\n"); return -1; } err = clSetKernelArg(kernel[0], 0, sizeof streams[2], &streams[2]); err |= clSetKernelArg(kernel[0], 1, sizeof streams[0], &streams[0]); if (err != CL_SUCCESS) { log_error("clSetKernelArgs failed\n"); return -1; } err = clSetKernelArg(kernel[1], 0, sizeof streams[2], &streams[2]); err |= clSetKernelArg(kernel[1], 1, sizeof streams[1], &streams[1]); if (err != CL_SUCCESS) { log_error("clSetKernelArgs failed\n"); return -1; } threads[0] = (unsigned int)img_width; threads[1] = (unsigned int)img_height; for (i=0; i<2; i++) { err = clEnqueueNDRangeKernel(queue, kernel[i], 2, NULL, threads, NULL, 0, NULL, NULL); if (err != CL_SUCCESS) { log_error("clExecuteKernel failed\n"); return -1; } err = clEnqueueReadImage(queue, streams[i], CL_TRUE, origin, region, 0, 0, output_ptr, 0, NULL, NULL); if (err != CL_SUCCESS) { log_error("clReadImage failed\n"); return -1; } err = verify_16bit_image((i == 0) ? "WRITE_IMAGE_RGBA_UNORM_INT16 test with memflags = CL_MEM_READ_WRITE" : "WRITE_IMAGE_RGBA_UNORM_INT16 test with memflags = CL_MEM_WRITE_ONLY", input_ptr, output_ptr, img_width, img_height); any_err |= err; } // cleanup clReleaseMemObject(streams[0]); clReleaseMemObject(streams[1]); clReleaseMemObject(streams[2]); clReleaseKernel(kernel[0]); clReleaseKernel(kernel[1]); clReleaseProgram(program); free(input_ptr); free(output_ptr); return any_err; }
29.653061
119
0.63128
jainvikas8
c10084d69335f87a04e35a413d4e8101307b5f0d
1,497
hpp
C++
include/LIEF/Abstract/json.hpp
lkollar/LIEF
04037644af42c75fbace582bd2eb64c061a197e5
[ "Apache-2.0" ]
4
2020-09-19T21:23:47.000Z
2020-10-02T19:17:04.000Z
include/LIEF/Abstract/json.hpp
prarthanats/LIEF
b26abae9a9b0dc0e82dd803b7b54a2a9dfe1034a
[ "Apache-2.0" ]
1
2018-12-22T16:08:03.000Z
2018-12-22T16:08:21.000Z
include/LIEF/Abstract/json.hpp
prarthanats/LIEF
b26abae9a9b0dc0e82dd803b7b54a2a9dfe1034a
[ "Apache-2.0" ]
1
2018-12-30T10:00:48.000Z
2018-12-30T10:00:48.000Z
/* Copyright 2017 R. Thomas * Copyright 2017 Quarkslab * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef LIEF_ABSTRACT_JSON_H_ #define LIEF_ABSTRACT_JSON_H_ #include "LIEF/config.h" #ifdef LIEF_JSON_SUPPORT #include "LIEF/visibility.h" #include "LIEF/visitors/json.hpp" #include "LIEF/Abstract.hpp" namespace LIEF { LIEF_API json to_json_from_abstract(const Object& v); LIEF_API std::string to_json_str_from_abstract(const Object& v); class LIEF_API AbstractJsonVisitor : public LIEF::JsonVisitor { public: using LIEF::JsonVisitor::JsonVisitor; public: virtual void visit(const Binary& binary) override; virtual void visit(const Header& header) override; virtual void visit(const Section& section) override; virtual void visit(const Symbol& symbol) override; virtual void visit(const Relocation& relocation) override; virtual void visit(const Function& f) override; }; } #endif // LIEF_JSON_SUPPORT #endif
29.352941
75
0.741483
lkollar
c100912d80436574c73b1a06d149290ec13bb5e5
1,333
cpp
C++
ros/ROS_Helpers.cpp
jwatson-CO-edu/cpp_helpers
be83019b749d6cdb8ed09e6fcedc9ca8983f3e19
[ "MIT" ]
null
null
null
ros/ROS_Helpers.cpp
jwatson-CO-edu/cpp_helpers
be83019b749d6cdb8ed09e6fcedc9ca8983f3e19
[ "MIT" ]
null
null
null
ros/ROS_Helpers.cpp
jwatson-CO-edu/cpp_helpers
be83019b749d6cdb8ed09e6fcedc9ca8983f3e19
[ "MIT" ]
null
null
null
/*********** ROS_Helpers.cpp James Watson , 2018 June Common ROS Functions & Tasks Template Version: 2017-09-23 ***********/ #include "ROS_Helpers.h" // === Classes and Structs ================================================================================================================= // ___ End Classes _________________________________________________________________________________________________________________________ // === Functions =========================================================================================================================== void ros_log( string msg , LogLevel level ){ switch( level ) { case WARN : { ROS_WARN_STREAM( msg ); break; } case ERROR : { ROS_ERROR_STREAM( msg ); break; } default: { ROS_INFO_STREAM( msg ); break; } } } // ___ End Func ____________________________________________________________________________________________________________________________ /* === Spare Parts ========================================================================================================================= ___ End Parts ___________________________________________________________________________________________________________________________ */
22.59322
140
0.505626
jwatson-CO-edu
c10392664e47ce224775b7ff50610219c4869736
23,489
cpp
C++
src/Simulation.cpp
ericwolter/position-based-fluids
30e92ead037b397573a0b7fb9fbac3770093793a
[ "MIT" ]
2
2018-01-03T01:26:54.000Z
2022-01-01T08:43:04.000Z
src/Simulation.cpp
ericwolter/position-based-fluids
30e92ead037b397573a0b7fb9fbac3770093793a
[ "MIT" ]
null
null
null
src/Simulation.cpp
ericwolter/position-based-fluids
30e92ead037b397573a0b7fb9fbac3770093793a
[ "MIT" ]
null
null
null
#include "Precomp_OpenGL.h" #include "Simulation.hpp" #include "Resources.hpp" #include "ParamUtils.hpp" #include "ocl/OCLUtils.hpp" #include "SOIL.h" #define _USE_MATH_DEFINES #include <math.h> #include <cmath> #include <sstream> #include <algorithm> using namespace std; cl::Memory Simulation::CreateCachedBuffer(cl::ImageFormat& format, int elements) { if (format.image_channel_order != CL_RGBA) throw "Image type is not supported"; // Choose what type should be created if (Params.EnableCachedBuffers) return cl::Image2D(mCLContext, CL_MEM_READ_WRITE, format, 2048, DivCeil(elements, 2048)); else return cl::Buffer(mCLContext, CL_MEM_READ_WRITE, elements * sizeof(float) * 4); } void OCL_InitMemory(cl::CommandQueue& queue, cl::Memory& mem, void* pData = NULL, int nDataSize = 0) { // Get buffer size int memSize = mem.getInfo<CL_MEM_SIZE>(); // Create memory char* pBuf = new char[memSize]; memset(pBuf, 0, memSize); // Fill with data if ((pData != NULL) && (nDataSize > 0)) for (int i = 0; i < memSize; i++) pBuf[i] = ((char*)pData)[i % nDataSize]; // Choose the way to transfer the data switch (mem.getInfo<CL_MEM_TYPE>()) { case CL_MEM_OBJECT_BUFFER: queue.enqueueWriteBuffer(*((cl::Buffer*)&mem), CL_TRUE, 0, memSize, pBuf); break; } // Release memory delete[] pBuf; } Simulation::Simulation(const cl::Context &clContext, const cl::Device &clDevice) : mCLContext(clContext), mCLDevice(clDevice), bDumpParticlesData(false) { // Create Queue mQueue = cl::CommandQueue(mCLContext, mCLDevice, CL_QUEUE_PROFILING_ENABLE); } Simulation::~Simulation() { glFinish(); mQueue.finish(); } void Simulation::CreateParticles() { // Create buffers cl_float4* positions = new cl_float4[Params.particleCount]; // Compute particle count per axis int ParticlesPerAxis = (int)ceil(pow(Params.particleCount, 1 / 3.0)); // Build particles blcok float d = Params.h * Params.setupSpacing; float offsetX = (1.0f - ParticlesPerAxis * d) / 2.0f; float offsetY = 0.3f; float offsetZ = (1.0f - ParticlesPerAxis * d) / 2.0f; for (cl_uint i = 0; i < Params.particleCount; i++) { cl_uint x = ((cl_uint)(i / pow(ParticlesPerAxis, 1)) % ParticlesPerAxis); cl_uint y = ((cl_uint)(i / pow(ParticlesPerAxis, 0)) % ParticlesPerAxis); cl_uint z = ((cl_uint)(i / pow(ParticlesPerAxis, 2)) % ParticlesPerAxis); positions[i].s[0] = offsetX + (x /*+ (y % 2) * .5*/) * d; positions[i].s[1] = offsetY + (y) * d; positions[i].s[2] = offsetZ + (z /*+ (y % 2) * .5*/) * d; positions[i].s[3] = 0; } // Copy data from Host to GPU OCL_InitMemory(mQueue, mPositionsPingBuffer, positions , sizeof(positions[0]) * Params.particleCount); OCL_InitMemory(mQueue, mVelocitiesBuffer); delete[] positions; } const std::string *Simulation::KernelFileList() { static const std::string kernels[] = { "hesp.hpp", "parameters.hpp", "logging.cl", "utilities.cl", "predict_positions.cl", "update_cells.cl", "build_friends_list.cl", "reset_grid.cl", "compute_scaling.cl", "compute_delta.cl", "update_predicted.cl", "pack_data.cl", "update_velocities.cl", "apply_viscosity.cl", "apply_vorticity.cl", "radixsort.cl", "" }; return kernels; } bool Simulation::InitKernels() { // Setup OpenCL Ranges const cl_uint globalSize = (cl_uint)ceil(Params.particleCount / 32.0f) * 32; mGlobalRange = cl::NDRange(globalSize); mLocalRange = cl::NullRange; // Notify OCL logging that we're about to start new kernel processing oclLog.StartKernelProcessing(mCLContext, mCLDevice, 4096); // setup kernel sources OCLUtils clSetup; vector<string> kernelSources; // Load kernel sources const std::string *pKernels = KernelFileList(); for (int iSrc = 0; pKernels[iSrc] != ""; iSrc++) { // Read source from disk string source = getKernelSource(pKernels[iSrc]); // Patch kernel for logging if (pKernels[iSrc] != "logging.cl") source = oclLog.PatchKernel(source); // Load into compile list kernelSources.push_back(source); } // Setup kernel compiler flags std::ostringstream clflags; clflags << "-cl-mad-enable -cl-no-signed-zeros -cl-fast-relaxed-math "; // Vendor related flags string devVendor = mCLDevice.getInfo<CL_DEVICE_VENDOR>(); if (devVendor.find("NVIDIA") != std::string::npos) clflags << "-cl-nv-verbose "; clflags << std::showpoint; clflags << "-DLOG_SIZE=" << (int)1024 << " "; clflags << "-DEND_OF_CELL_LIST=" << (int)(-1) << " "; clflags << "-DMAX_PARTICLES_COUNT=" << (int)(Params.particleCount) << " "; clflags << "-DMAX_FRIENDS_CIRCLES=" << (int)(Params.friendsCircles) << " "; clflags << "-DMAX_FRIENDS_IN_CIRCLE=" << (int)(Params.particlesPerCircle) << " "; clflags << "-DFRIENDS_BLOCK_SIZE=" << (int)(Params.particleCount * Params.friendsCircles) << " "; clflags << "-DGRID_BUF_SIZE=" << (int)(Params.gridBufSize) << " "; clflags << "-DPOLY6_FACTOR=" << 315.0f / (64.0f * M_PI * pow(Params.h, 9)) << "f "; clflags << "-DGRAD_SPIKY_FACTOR=" << 45.0f / (M_PI * pow(Params.h, 6)) << "f "; if (Params.EnableCachedBuffers) clflags << "-DENABLE_CACHED_BUFFERS "; // Compile kernels cl::Program program = clSetup.createProgram(kernelSources, mCLContext, mCLDevice, clflags.str()); if (program() == 0) return false; // save BuildLog string buildLog = program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(mCLDevice); ofstream f("build.log", ios::out | ios::trunc); f << buildLog; f.close(); // Build kernels table mKernels = clSetup.createKernelsMap(program); // Write kernel info cout << "CL_KERNEL_WORK_GROUP_SIZE=" << mKernels["computeDelta"].getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(mCLDevice) << endl; cout << "CL_KERNEL_LOCAL_MEM_SIZE =" << mKernels["computeDelta"].getWorkGroupInfo<CL_KERNEL_LOCAL_MEM_SIZE>(mCLDevice) << endl; return true; } void Simulation::InitBuffers() { // Create buffers mPositionsPingBuffer = cl::BufferGL(mCLContext, CL_MEM_READ_WRITE, mSharedPingBufferID); // buffer could be changed to be CL_MEM_WRITE_ONLY but for debugging also reading it might be helpful mPositionsPongBuffer = cl::BufferGL(mCLContext, CL_MEM_READ_WRITE, mSharedPongBufferID); // buffer could be changed to be CL_MEM_WRITE_ONLY but for debugging also reading it might be helpful mParticlePosImg = cl::Image2DGL(mCLContext, CL_MEM_READ_WRITE, GL_TEXTURE_2D, 0, mSharedParticlesPos); mPredictedPingBuffer = CreateCachedBuffer(cl::ImageFormat(CL_RGBA, CL_FLOAT), Params.particleCount); mPredictedPongBuffer = CreateCachedBuffer(cl::ImageFormat(CL_RGBA, CL_FLOAT), Params.particleCount); mVelocitiesBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, Params.particleCount * sizeof(cl_float4)); mDeltaBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, Params.particleCount * sizeof(cl_float4)); mOmegaBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, Params.particleCount * sizeof(cl_float4)); mDensityBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, Params.particleCount * sizeof(cl_float)); mLambdaBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, Params.particleCount * sizeof(cl_float)); mParameters = cl::Buffer(mCLContext, CL_MEM_READ_ONLY, sizeof(Params)); // Radix buffers mKeysCount = IntCeil(Params.particleCount, _ITEMS * _GROUPS); mInKeysBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, sizeof(cl_uint) * mKeysCount); mInPermutationBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, sizeof(cl_uint) * mKeysCount); mOutKeysBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, sizeof(cl_uint) * mKeysCount); mOutPermutationBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, sizeof(cl_uint) * mKeysCount); mHistogramBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, sizeof(cl_uint) * _RADIX * _GROUPS * _ITEMS); mGlobSumBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, sizeof(cl_uint) * _HISTOSPLIT); mHistoTempBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, sizeof(cl_uint) * _HISTOSPLIT); // Update OpenGL lock list mGLLockList.push_back(mPositionsPingBuffer); mGLLockList.push_back(mPositionsPongBuffer); mGLLockList.push_back(mParticlePosImg); // Update mPositionsPingBuffer and mVelocitiesBuffer LockGLObjects(); CreateParticles(); UnlockGLObjects(); // Copy Params (Host) => mParams (GPU) mQueue.enqueueWriteBuffer(mParameters, CL_TRUE, 0, sizeof(Params), &Params); } void Simulation::InitCells() { // Write buffer for cells mCellsBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, Params.gridBufSize * 2 * sizeof(cl_uint)); OCL_InitMemory(mQueue, mCellsBuffer, (void*)&END_OF_CELL_LIST, sizeof(END_OF_CELL_LIST)); // Init Friends list buffer mFriendsListBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, Params.particleCount * Params.friendsCircles * (1 + Params.particlesPerCircle) * sizeof(cl_uint)); OCL_InitMemory(mQueue, mFriendsListBuffer); } void Simulation::LoadForceMasks() { // Load file int width = 0, height = 0, channels = 0; byte* data = SOIL_load_image(getPathForTexture(string("Scene_fp_mask.png")).c_str(), &width, &height, &channels, 4); // Clear alpha for (int i = 0; i < width * height * 4; i+=4) { data[i+1] = 0; data[i+2] = 0; data[i+3] = 0; } // Create OpenCL image mSurfacesMask = cl::Image2D(mCLContext, CL_MEM_READ_WRITE, cl::ImageFormat(CL_R, CL_UNSIGNED_INT32), width, height); // Write data cl::size_t<3> org, region; region[0] = width; region[1] = height; region[2] = 1; mQueue.enqueueWriteImage(mSurfacesMask, true, org, region, 0, 0, data); //mQueue.enqueueReadImage(mSurfacesMask, true, org, region, 0, 0, data); // Release image data SOIL_free_image_data(data); } int dumpSession = 0; int dumpCounter = 0; int cycleCounter = 0; void SaveFile(cl::CommandQueue queue, cl::Buffer buffer, const char *szFilename) { // Exit if dump session is disabled if (dumpSession == 0) return; // Get buffer size int bufSize = buffer.getInfo<CL_MEM_SIZE>(); // Read data from GPU char *buf = new char[bufSize]; queue.enqueueReadBuffer(buffer, CL_TRUE, 0, bufSize, buf); queue.finish(); // Compose file name dumpCounter++; char szTarget[256]; sprintf(szTarget, "%s/dump%d/%d_%d_%s.bin", getRootPath().c_str(), dumpSession, dumpCounter, cycleCounter, szFilename); // Save to disk ofstream f(szTarget, ios::out | ios::trunc | ios::binary); f.seekp(0); f.write((const char *)buf, bufSize); f.close(); delete[] buf; } void Simulation::updateVelocities() { int param = 0; cl::Kernel kernel = mKernels["updateVelocities"]; kernel.setArg(param++, mParameters); kernel.setArg(param++, mPositionsPingBuffer); kernel.setArg(param++, mPredictedPingBuffer); kernel.setArg(param++, mParticlePosImg); kernel.setArg(param++, mVelocitiesBuffer); kernel.setArg(param++, Params.particleCount); mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("updateVelocities")); } void Simulation::applyViscosity() { int param = 0; cl::Kernel kernel = mKernels["applyViscosity"]; kernel.setArg(param++, mParameters); kernel.setArg(param++, mPredictedPingBuffer); kernel.setArg(param++, mVelocitiesBuffer); kernel.setArg(param++, mOmegaBuffer); kernel.setArg(param++, mFriendsListBuffer); kernel.setArg(param++, Params.particleCount); mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("applyViscosity")); } void Simulation::applyVorticity() { int param = 0; cl::Kernel kernel = mKernels["applyVorticity"]; kernel.setArg(param++, mParameters); kernel.setArg(param++, mPredictedPingBuffer); kernel.setArg(param++, mVelocitiesBuffer); kernel.setArg(param++, mOmegaBuffer); kernel.setArg(param++, mFriendsListBuffer); kernel.setArg(param++, Params.particleCount); mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("applyVorticity")); } void Simulation::predictPositions() { int param = 0; cl::Kernel kernel = mKernels["predictPositions"]; kernel.setArg(param++, mParameters); kernel.setArg(param++, (cl_uint)bPauseSim); kernel.setArg(param++, mPositionsPingBuffer); kernel.setArg(param++, mPredictedPingBuffer); kernel.setArg(param++, mVelocitiesBuffer); kernel.setArg(param++, Params.particleCount); mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("predictPositions")); } void Simulation::buildFriendsList() { int param = 0; cl::Kernel kernel = mKernels["buildFriendsList"]; kernel.setArg(param++, mParameters); kernel.setArg(param++, mPredictedPingBuffer); kernel.setArg(param++, mCellsBuffer); kernel.setArg(param++, mFriendsListBuffer); kernel.setArg(param++, Params.particleCount); mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("buildFriendsList")); param = 0; kernel = mKernels["resetGrid"]; kernel.setArg(param++, mParameters); kernel.setArg(param++, mInKeysBuffer); kernel.setArg(param++, mCellsBuffer); kernel.setArg(param++, Params.particleCount); mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("resetPartList")); } void Simulation::updatePredicted(int iterationIndex) { int param = 0; cl::Kernel kernel = mKernels["updatePredicted"]; kernel.setArg(param++, mPredictedPingBuffer); kernel.setArg(param++, mPredictedPongBuffer); kernel.setArg(param++, mDeltaBuffer); kernel.setArg(param++, Params.particleCount); mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("updatePredicted", iterationIndex)); SWAP(cl::Memory, mPredictedPingBuffer, mPredictedPongBuffer); } void Simulation::packData(cl::Memory& sourceImg, cl::Memory& pongImg, cl::Buffer packSource, int iterationIndex) { int param = 0; cl::Kernel kernel = mKernels["packData"]; kernel.setArg(param++, pongImg); kernel.setArg(param++, sourceImg); kernel.setArg(param++, packSource); kernel.setArg(param++, Params.particleCount); mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("packData", iterationIndex)); // Swap between source and pong SWAP(cl::Memory, sourceImg, pongImg); } void Simulation::computeDelta(int iterationIndex) { int param = 0; cl::Kernel kernel = mKernels["computeDelta"]; kernel.setArg(param++, mParameters); kernel.setArg(param++, oclLog.GetDebugBuffer()); kernel.setArg(param++, mDeltaBuffer); kernel.setArg(param++, mPositionsPingBuffer); kernel.setArg(param++, mPredictedPingBuffer); // xyz=Predicted z=Scaling kernel.setArg(param++, mFriendsListBuffer); kernel.setArg(param++, fWavePos); kernel.setArg(param++, mSurfacesMask); kernel.setArg(param++, Params.particleCount); #ifdef LOCALMEM mQueue.enqueueNDRangeKernel(kernel, 0, cl::NDRange(DivCeil(Params.particleCount, 256)*256), cl::NDRange(256), NULL, PerfData.GetTrackerEvent("computeDelta", iterationIndex)); #else mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("computeDelta", iterationIndex)); #endif } void Simulation::computeScaling(int iterationIndex) { int param = 0; cl::Kernel kernel = mKernels["computeScaling"]; kernel.setArg(param++, mParameters); kernel.setArg(param++, mPredictedPingBuffer); kernel.setArg(param++, mDensityBuffer); kernel.setArg(param++, mLambdaBuffer); kernel.setArg(param++, mFriendsListBuffer); kernel.setArg(param++, Params.particleCount); mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("computeScaling", iterationIndex)); // mQueue.enqueueNDRangeKernel(kernel, 0, cl::NDRange(((Params.particleCount + 399) / 400) * 400), cl::NDRange(400), NULL, PerfData.GetTrackerEvent("computeScaling", iterationIndex)); } void Simulation::updateCells() { int param = 0; cl::Kernel kernel = mKernels["updateCells"]; kernel.setArg(param++, mParameters); kernel.setArg(param++, mInKeysBuffer); kernel.setArg(param++, mCellsBuffer); kernel.setArg(param++, Params.particleCount); mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("updateCells")); } void Simulation::radixsort() { int param = 0; cl::Kernel kernel = mKernels["computeKeys"]; kernel.setArg(param++, mParameters); kernel.setArg(param++, mPredictedPingBuffer); kernel.setArg(param++, mInKeysBuffer); kernel.setArg(param++, mInPermutationBuffer); kernel.setArg(param++, Params.particleCount); mQueue.enqueueNDRangeKernel(kernel, 0, cl::NDRange(mKeysCount), mLocalRange, NULL, PerfData.GetTrackerEvent("computeKeys")); for (size_t pass = 0; pass < _PASS; pass++) { // Histogram(pass); const size_t h_nblocitems = _ITEMS; const size_t h_nbitems = _GROUPS * _ITEMS; param = 0; kernel = mKernels["histogram"]; kernel.setArg(param++, mInKeysBuffer); kernel.setArg(param++, mHistogramBuffer); kernel.setArg(param++, pass); kernel.setArg(param++, sizeof(cl_uint) * _RADIX * _ITEMS, NULL); kernel.setArg(param++, mKeysCount); mQueue.enqueueNDRangeKernel(kernel, 0, cl::NDRange(h_nbitems), cl::NDRange(h_nblocitems), NULL, PerfData.GetTrackerEvent("histogram", pass)); // ScanHistogram(); param = 0; kernel = mKernels["scanhistograms"]; const size_t sh1_nbitems = _RADIX * _GROUPS * _ITEMS / 2; const size_t sh1_nblocitems = sh1_nbitems / _HISTOSPLIT ; const int maxmemcache = max(_HISTOSPLIT, _ITEMS * _GROUPS * _RADIX / _HISTOSPLIT); kernel.setArg(param++, mHistogramBuffer); kernel.setArg(param++, sizeof(cl_uint)* maxmemcache, NULL); kernel.setArg(param++, mGlobSumBuffer); mQueue.enqueueNDRangeKernel(kernel, 0, cl::NDRange(sh1_nbitems), cl::NDRange(sh1_nblocitems), NULL, PerfData.GetTrackerEvent("scanhistograms1", pass)); mQueue.finish(); param = 0; kernel = mKernels["scanhistograms"]; const size_t sh2_nbitems = _HISTOSPLIT / 2; const size_t sh2_nblocitems = sh2_nbitems; kernel.setArg(0, mGlobSumBuffer); kernel.setArg(2, mHistoTempBuffer); mQueue.enqueueNDRangeKernel(kernel, 0, cl::NDRange(sh2_nbitems), cl::NDRange(sh2_nblocitems), NULL, PerfData.GetTrackerEvent("scanhistograms2", pass)); param = 0; kernel = mKernels["pastehistograms"]; const size_t ph_nbitems = _RADIX * _GROUPS * _ITEMS / 2; const size_t ph_nblocitems = ph_nbitems / _HISTOSPLIT; kernel.setArg(param++, mHistogramBuffer); kernel.setArg(param++, mGlobSumBuffer); mQueue.enqueueNDRangeKernel(kernel, 0, cl::NDRange(ph_nbitems), cl::NDRange(ph_nblocitems), NULL, PerfData.GetTrackerEvent("pastehistograms", pass)); // Reorder(pass); param = 0; kernel = mKernels["reorder"]; const size_t r_nblocitems = _ITEMS; const size_t r_nbitems = _GROUPS * _ITEMS; kernel.setArg(param++, mInKeysBuffer); kernel.setArg(param++, mOutKeysBuffer); kernel.setArg(param++, mHistogramBuffer); kernel.setArg(param++, pass); kernel.setArg(param++, mInPermutationBuffer); kernel.setArg(param++, mOutPermutationBuffer); kernel.setArg(param++, sizeof(cl_uint)* _RADIX * _ITEMS, NULL); kernel.setArg(param++, mKeysCount); mQueue.enqueueNDRangeKernel(kernel, 0, cl::NDRange(r_nbitems), cl::NDRange(r_nblocitems), NULL, PerfData.GetTrackerEvent("reorder", pass)); SWAP(cl::Buffer, mInKeysBuffer, mOutKeysBuffer); SWAP(cl::Buffer, mInPermutationBuffer, mOutPermutationBuffer); } // Execute particle reposition param = 0; kernel = mKernels["sortParticles"]; kernel.setArg(param++, mInPermutationBuffer); kernel.setArg(param++, mPositionsPingBuffer); kernel.setArg(param++, mPositionsPongBuffer); kernel.setArg(param++, mPredictedPingBuffer); kernel.setArg(param++, mPredictedPongBuffer); kernel.setArg(param++, Params.particleCount); mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("sortParticles")); // Double buffering of positions and velocity buffers SWAP(cl::BufferGL, mPositionsPingBuffer, mPositionsPongBuffer); SWAP(cl::Memory, mPredictedPingBuffer, mPredictedPongBuffer); SWAP(GLuint, mSharedPingBufferID, mSharedPongBufferID); } void Simulation::LockGLObjects() { // Make sure OpenGL finish doing things (This is required according to OpenCL spec, see enqueueAcquireGLObjects) glFinish(); // Request lock mQueue.enqueueAcquireGLObjects(&mGLLockList); } void Simulation::UnlockGLObjects() { // Release lock mQueue.enqueueReleaseGLObjects(&mGLLockList); mQueue.finish(); } void Simulation::Step() { // Lock OpenGL objects LockGLObjects(); // Inc sample counter cycleCounter++; // Predicit positions this->predictPositions(); // sort particles buffer if (!bPauseSim) this->radixsort(); // Update cells this->updateCells(); // Build friends list this->buildFriendsList(); for (unsigned int i = 0; i < Params.simIterations; ++i) { // Compute scaling value this->computeScaling(i); // Place lambda in "mPredictedPingBuffer[x].w" this->packData(mPredictedPingBuffer, mPredictedPongBuffer, mLambdaBuffer, i); // Compute position delta this->computeDelta(i); // Update predicted position this->updatePredicted(i); } // Place density in "mPredictedPingBuffer[x].w" this->packData(mPredictedPingBuffer, mPredictedPongBuffer, mDensityBuffer, -1); // Recompute velocities this->updateVelocities(); // Update vorticity and Viscosity this->applyViscosity(); this->applyVorticity(); // [DEBUG] Read back friends information (if needed) //if (bReadFriendsList || bDumpParticlesData) // TODO: Get frients list to host // [DEBUG] Do we need to dump particle data if (bDumpParticlesData) { // Turn off flag bDumpParticlesData = false; // TODO: Dump particles to disk } // Release OpenGL shared object, allowing openGL do to it's thing... UnlockGLObjects(); // Collect performance data PerfData.UpdateTimings(); // Allow OpenCL logger to process oclLog.CycleExecute(mQueue); }
37.763666
196
0.680787
ericwolter
c105302eb2ae2bf3b741dcf95bda20b6215e954a
3,446
cpp
C++
examples/KNeighbors.cpp
aniketsharma00411/alpha
4a1010150388022a6c799e9204621c281b1f92cb
[ "MIT" ]
1
2021-04-04T12:12:54.000Z
2021-04-04T12:12:54.000Z
examples/KNeighbors.cpp
mlcpp/alpha
4a1010150388022a6c799e9204621c281b1f92cb
[ "MIT" ]
3
2020-09-17T05:14:58.000Z
2020-09-20T11:12:29.000Z
examples/KNeighbors.cpp
mlcpp/alpha
4a1010150388022a6c799e9204621c281b1f92cb
[ "MIT" ]
1
2020-09-16T10:30:11.000Z
2020-09-16T10:30:11.000Z
// import header files #include <KNeighborsClassifier.hpp> #include <matplotlibcpp.hpp> #include <model_selection.hpp> namespace plt = matplotlibcpp; // Example program // Read csv files to get a Matrix object. // Slice the Matrix object to a suitable size. // Plot known data points // Run KNeighborsClustering and predict the cluster label for a Matrix // Print score and plot necessary graphs int main() { // Specify backend renderer for matplotlib plt::backend("GTK3Agg"); // create dataset with two feature Matrix mat = read_csv("./datasets/blobs/blobs.csv"); Matrix X = mat.slice(1, mat.row_length(), 0, 2); Matrix Y = mat.slice(1, mat.row_length(), 2, 3); X.to_double(); Y.to_double(); // Split the data and targets into training/testing sets auto [X_train, X_test, Y_train, Y_test] = model_selection.train_test_split(X, Y, 0); // plot training dataset plt::figure_size(800, 600); plt::title("KNeighbors Known Dataset"); plt::plot(matrix.slice_select(X_train, Y_train, 0.0, 0).get_col(0), matrix.slice_select(X_train, Y_train, 0.0, 1).get_col(0), "ro"); plt::plot(matrix.slice_select(X_train, Y_train, 1.0, 0).get_col(0), matrix.slice_select(X_train, Y_train, 1.0, 1).get_col(0), "g^"); plt::plot(matrix.slice_select(X_train, Y_train, 2.0, 0).get_col(0), matrix.slice_select(X_train, Y_train, 2.0, 1).get_col(0), "bD"); plt::save("./build/plots/KNeighbors Known Dataset.png"); plt::show(); // plot test data plt::figure_size(800, 600); plt::title("KNeighbors Unknown Dataset"); plt::plot(X_test.get_col(0), X_test.get_col(1), "mo"); plt::save("./build/plots/KNeighbors Unknown Dataset.png"); plt::show(); // create KMeans object with k and epochs as parameters KNeighborsClassifier knn(1); knn.fit(X_train, Y_train); std::cout << "K Neighbors Clustering Algorithm: " << std::endl; Matrix Y_pred = knn.predict(X_test); // plot predicted dataset plt::figure_size(800, 600); plt::title("KNeighbors Predicted Dataset along with Known Dataset"); plt::named_plot("Known red", matrix.slice_select(X_train, Y_train, 0.0, 0).get_col(0), matrix.slice_select(X_train, Y_train, 0.0, 1).get_col(0), "ro"); plt::named_plot("Known green", matrix.slice_select(X_train, Y_train, 1.0, 0).get_col(0), matrix.slice_select(X_train, Y_train, 1.0, 1).get_col(0), "g^"); plt::named_plot("Known blue", matrix.slice_select(X_train, Y_train, 2.0, 0).get_col(0), matrix.slice_select(X_train, Y_train, 2.0, 1).get_col(0), "bD"); plt::named_plot("Predicted red", matrix.slice_select(X_test, Y_pred, 0.0, 0).get_col(0), matrix.slice_select(X_test, Y_pred, 0.0, 1).get_col(0), "rP"); plt::named_plot("Predicted green", matrix.slice_select(X_test, Y_pred, 1.0, 0).get_col(0), matrix.slice_select(X_test, Y_pred, 1.0, 1).get_col(0), "gP"); plt::named_plot("Predicted blue", matrix.slice_select(X_test, Y_pred, 2.0, 0).get_col(0), matrix.slice_select(X_test, Y_pred, 2.0, 1).get_col(0), "bP"); plt::legend(); plt::save("./build/plots/KNeighbors Predicted Dataset.png"); plt::show(); // Comparison of predicted and actual cluster label std::cout << "KNN Model Score: " << knn.score(Y_pred, Y_test) << std::endl; return 0; }
43.075
94
0.652351
aniketsharma00411
c106c1d7cbab7d15f10e6b3920c90895042bd2b8
1,559
cpp
C++
fastSLAMproject/src/gmapping/openslam_gmapping/grid/graphmap.cpp
HouCongCN/Gmapping-Code
946db1678a99043fc179a5a82499c4bd98cd19d6
[ "MIT" ]
null
null
null
fastSLAMproject/src/gmapping/openslam_gmapping/grid/graphmap.cpp
HouCongCN/Gmapping-Code
946db1678a99043fc179a5a82499c4bd98cd19d6
[ "MIT" ]
null
null
null
fastSLAMproject/src/gmapping/openslam_gmapping/grid/graphmap.cpp
HouCongCN/Gmapping-Code
946db1678a99043fc179a5a82499c4bd98cd19d6
[ "MIT" ]
null
null
null
#ifndef GRAPHMAP_H #define GRAPHMAP_H #include <list> #include "../include/gmapping/utils/point.h" #include "../include/gmapping/grid/map.h" #include <utils/graph.h> /* * 这个地方感觉像是用用来做图优化的。 * 不过不知道为什么最终没有用来做这个。 */ namespace GMapping { class RasterMap; struct GraphMapPatch { typedef typename std::list<IntPoint> PointList; /**Renders the map relatively to the center of the patch*/ //void render(RenderMap rmap); /**returns the lower left corner of the patch, relative to the center*/ //Point minBoundary() const; /**returns the upper right corner of the patch, relative to the center*/ //Point maxBoundary() const; // OrientedPoint center; PointList m_points; }; struct Covariance3 { double sxx, sxy, sxt, syy, syt ,stt; }; struct GraphMapEdge { Covariance3 covariance; GraphMapPatch* first, *second; inline operator double() const { return sqrt((first->center-second->center)*(first->center-second->center)); } }; struct GraphPatchGraph: public Graph<GraphMapPatch, Covariance3> { void addEdge(Vertex* v1, Vertex* v2, const Covariance3& covariance); }; void GraphPatchGraph::addEdge(GraphPatchGraph::Vertex* v1, GraphPatchGraph::VertexVertex* v2, const Covariance3& cov) { GraphMapEdge gme; gme.covariance=cov; gme.first=v1; gme.second=v2; return Graph<GraphMapPatch, Covariance3>::addEdge(v1,v2,gme); } struct GraphPatchDirectoryCell: public std::set<GraphMapPatch::Vertex*> { GraphPatchDirectoryCell(double); }; typedef Map<GraphPatchDirectoryCell>, Array2D::set<GraphPatchDirectoryCell> > }; #endif
21.067568
94
0.738935
HouCongCN
c10777ba36df234d1b2d19455d1c64fdf57e0080
375
cpp
C++
Olympiad Solutions/URI/1544.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
Olympiad Solutions/URI/1544.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
Olympiad Solutions/URI/1544.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
// Ivan Carvalho // Solution to https://www.urionlinejudge.com.br/judge/problems/view/1544 #include <cstdio> int main(){ long long a,b; while(scanf("%lld %lld",&a,&b) != EOF){ long long resp = 1; for(long long i = a - b + 1;i <= a;i++){ resp *= i; while(resp % 10LL == 0LL) resp /= 10LL; resp %= 100000000000LL; } printf("%lld\n",resp%10); } return 0; }
22.058824
73
0.592
Ashwanigupta9125
c1092fef99d77914804941d406c360279b0ff2a9
484
cpp
C++
acmp.ru/0317/317.cpp
mstrechen/cp
ffac439840a71f70580a0ef197e47479e167a0eb
[ "MIT" ]
null
null
null
acmp.ru/0317/317.cpp
mstrechen/cp
ffac439840a71f70580a0ef197e47479e167a0eb
[ "MIT" ]
null
null
null
acmp.ru/0317/317.cpp
mstrechen/cp
ffac439840a71f70580a0ef197e47479e167a0eb
[ "MIT" ]
null
null
null
#include <iostream> //#include <ctime> using namespace std; int main(){ ios::sync_with_stdio(false); long long answer = 0; int x,y,z,w; cin >> x >> y >> z >> w; //double be = clock(); for(int i = w/x; i>=0;i--) { for(int j = (w-x*i)/y; j>=0; j--) { for(int k = (w-x*i-y*j)/z; k>=0; k--) { if(w==x*i+y*j+z*k) { answer++; } } } } //double en = clock(); cout << answer; //cout << (en-be)/CLOCKS_PER_SEC; return 0; }
17.285714
41
0.464876
mstrechen
c10a693697c48bb72d21c2338637ca7d0e4c8943
3,699
hxx
C++
include/criterion/internal/assert/op.hxx
Keenuts/Criterion
982e569233fac4c1e3b984611fe52bdb991d82ec
[ "MIT" ]
6
2019-01-18T13:36:55.000Z
2021-03-15T05:59:34.000Z
include/criterion/internal/assert/op.hxx
Keenuts/Criterion
982e569233fac4c1e3b984611fe52bdb991d82ec
[ "MIT" ]
null
null
null
include/criterion/internal/assert/op.hxx
Keenuts/Criterion
982e569233fac4c1e3b984611fe52bdb991d82ec
[ "MIT" ]
1
2019-06-09T11:44:00.000Z
2019-06-09T11:44:00.000Z
/* * The MIT License (MIT) * * Copyright © 2016 Franklin "Snaipe" Mathieu <http://snai.pe/> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef CRITERION_INTERNAL_ASSERT_OP_HXX_ #define CRITERION_INTERNAL_ASSERT_OP_HXX_ #include <cwchar> /* *INDENT-OFF* */ namespace criterion { namespace internal { namespace operators { /* *INDENT-ON* */ #define CRI_DEFINE_MEMBER_DETECTOR(Member) \ template <class T> \ class HasMember_ ## Member { \ private: \ using yes = char[2]; \ using no = char[1]; \ struct fallback { int Member; }; \ struct derived : T, fallback {}; \ template <class U> static no &test(decltype (U::Member) *); \ template <typename U> static yes &test(U *); \ public: \ static constexpr bool result = sizeof (test<derived>(nullptr)) == sizeof (yes); \ }; \ template <class T> \ struct has_member_ ## Member : public std::integral_constant<bool, HasMember_ ## Member<T>::result> {} CRI_DEFINE_MEMBER_DETECTOR(empty); template <typename T> bool zero(const T *t) { return !t; } template <typename T> bool zero(const typename std::enable_if<!std::is_pointer<T>::value, T>::type &t) { return !t; } template <typename T, typename = typename has_member_empty<T>::type> bool zero(const T &t) { return t.empty(); } template <> inline bool zero<>(const char *t) { return !*t; } template <> inline bool zero<>(const wchar_t *t) { return !*t; } /* relops without const */ template <typename T, typename U> inline bool operator!= (T& t, U& u) { return !(t == u); } template <typename T, typename U> inline bool operator<= (T& t, U& u) { return t < u || t == u; } template <typename T, typename U> inline bool operator> (T& t, U& u) { return !(t <= u); } template <typename T, typename U> inline bool operator>= (T& t, U& u) { return !(t < u); } /* *INDENT-OFF* */ }}} /* *INDENT-ON* */ #endif /* !CRITERION_INTERNAL_ASSERT_OP_HXX_ */
45.666667
106
0.550419
Keenuts
c10b03340959e31b498915378adf29241476e537
592
cc
C++
dynet/saxe-init.cc
ruyimarone/dynet
67bace3fb1d79327ada53b248e497c894819760d
[ "Apache-2.0" ]
3,307
2016-10-08T15:51:28.000Z
2022-03-30T04:40:44.000Z
dynet/saxe-init.cc
ruyimarone/dynet
67bace3fb1d79327ada53b248e497c894819760d
[ "Apache-2.0" ]
1,348
2016-10-08T14:36:55.000Z
2022-03-26T15:19:27.000Z
dynet/saxe-init.cc
ruyimarone/dynet
67bace3fb1d79327ada53b248e497c894819760d
[ "Apache-2.0" ]
741
2016-10-09T04:44:30.000Z
2022-03-29T22:29:02.000Z
#include "dynet/saxe-init.h" #include "dynet/tensor.h" #include "dynet/tensor-eigen.h" #include "dynet/globals.h" #include <random> #include <cstring> #include <Eigen/SVD> using namespace std; namespace dynet { void orthonormal_random(unsigned dd, float g, Tensor& x) { Tensor t; t.d = Dim({dd, dd}); t.v = new float[dd * dd]; normal_distribution<float> distribution(0, 0.01); auto b = [&] () {return distribution(*rndeng);}; generate(t.v, t.v + dd*dd, b); Eigen::JacobiSVD<Eigen::MatrixXf> svd(mat(t), Eigen::ComputeFullU); mat(x) = svd.matrixU(); delete[] t.v; } }
20.413793
69
0.660473
ruyimarone
c10b078745addf396b476a277c021ea7ac972ce3
610
cpp
C++
Workshops/salaries_workshop_main.cpp
hoelzl/CleanCodeCppCatch
88861faf48967e840b1d66f7faf94c0e9bef26a4
[ "MIT" ]
null
null
null
Workshops/salaries_workshop_main.cpp
hoelzl/CleanCodeCppCatch
88861faf48967e840b1d66f7faf94c0e9bef26a4
[ "MIT" ]
null
null
null
Workshops/salaries_workshop_main.cpp
hoelzl/CleanCodeCppCatch
88861faf48967e840b1d66f7faf94c0e9bef26a4
[ "MIT" ]
null
null
null
#include "salaries_workshop.h" #include <iostream> #include <vector> void pay_some_salaries() { std::vector<double> all_salaries{}; double tax_1{handle_money_stuff(3, 240.0, "Joe", all_salaries)}; double tax_2{handle_money_stuff(5, 240.0, "Jack", all_salaries)}; double tax_3{handle_money_stuff(6, 260.0, "Jill", all_salaries)}; double tax_4{handle_money_stuff(6, 800.0, "Jane", all_salaries)}; std::cout << "Taxes:" << tax_1 << ", " << tax_2 << ", " << tax_3 << ", " << tax_4 << "\n"; } int main() { std::cout << "Salaries original\n\n"; pay_some_salaries(); }
29.047619
76
0.62623
hoelzl
c10b9fab74b9b346a7c874f34c791de5bccca6af
1,978
cpp
C++
src/ImageTile.cpp
kamilsan/haruno-renderer
0c3d9cff1efc3a5735b3304e2037bf251a64450e
[ "MIT" ]
1
2022-03-30T19:54:27.000Z
2022-03-30T19:54:27.000Z
src/ImageTile.cpp
kamilsan/haruno-renderer
0c3d9cff1efc3a5735b3304e2037bf251a64450e
[ "MIT" ]
null
null
null
src/ImageTile.cpp
kamilsan/haruno-renderer
0c3d9cff1efc3a5735b3304e2037bf251a64450e
[ "MIT" ]
null
null
null
#include "ImageTile.hpp" #include <cstring> #include <fstream> ImageTile::ImageTile(unsigned int minX, unsigned int maxX, unsigned int minY, unsigned int maxY) : minX_(minX), maxX_(maxX), minY_(minY), maxY_(maxY) { if (maxX < minX || maxY < minY) { throw std::runtime_error("Improper ImageTile bounds!"); } width_ = maxX_ - minX_; height_ = maxY_ - minY_; len_ = 3 * width_ * height_; pixels_ = std::make_unique<float[]>(len_); memset(pixels_.get(), 0, len_ * sizeof(float)); } ImageTile::ImageTile(const ImageTile& other) { minX_ = other.minX_; maxX_ = other.maxX_; minY_ = other.minY_; maxY_ = other.maxY_; width_ = other.width_; height_ = other.height_; len_ = other.len_; pixels_ = std::make_unique<float[]>(len_); memcpy(pixels_.get(), other.pixels_.get(), len_ * sizeof(float)); } ImageTile::ImageTile(ImageTile&& other) { minX_ = other.minX_; maxX_ = other.maxX_; minY_ = other.minY_; maxY_ = other.maxY_; width_ = other.width_; height_ = other.height_; len_ = other.len_; pixels_ = std::move(other.pixels_); } ImageTile& ImageTile::operator=(const ImageTile& other) { if (&other != this) { minX_ = other.minX_; maxX_ = other.maxX_; minY_ = other.minY_; maxY_ = other.maxY_; width_ = other.width_; height_ = other.height_; len_ = other.len_; pixels_ = std::make_unique<float[]>(len_); memcpy(pixels_.get(), other.pixels_.get(), len_ * sizeof(float)); } return *this; } ImageTile& ImageTile::operator=(ImageTile&& other) { if (&other != this) { minX_ = other.minX_; maxX_ = other.maxX_; minY_ = other.minY_; maxY_ = other.maxY_; width_ = other.width_; height_ = other.height_; len_ = other.len_; pixels_ = std::move(other.pixels_); } return *this; } void ImageTile::clear(const Color& color) { for (unsigned int i = 0; i < len_;) { pixels_[i++] = color.r; pixels_[i++] = color.g; pixels_[i++] = color.b; } }
24.121951
96
0.641052
kamilsan
c10bca075ed75ff941fa1357f0394bd6b9174e6c
7,562
cpp
C++
system/apps/115_hunter/source/main.cpp
tomwei7/LA104
fdf04061f37693d37e2812ed6074348e65d7e5f9
[ "MIT" ]
336
2018-11-23T23:54:15.000Z
2022-03-21T03:47:05.000Z
system/apps/115_hunter/source/main.cpp
tomwei7/LA104
fdf04061f37693d37e2812ed6074348e65d7e5f9
[ "MIT" ]
56
2019-02-01T05:01:07.000Z
2022-03-26T16:00:24.000Z
system/apps/115_hunter/source/main.cpp
tomwei7/LA104
fdf04061f37693d37e2812ed6074348e65d7e5f9
[ "MIT" ]
52
2019-02-06T17:05:04.000Z
2022-03-04T12:30:53.000Z
#include <library.h> #include "../../os_host/source/framework/Console.h" #include "../../os_host/source/framework/SimpleApp.h" #include "hunter.h" #include "framework/shapes.h" #include "framework/layout.h" using namespace BIOS; class CHunterInterface { public: void StartZone(int zone, int minutes) { CONSOLE::Print("Starting zone %d for %d minutes.\n", zone, minutes); HunterStart(zone, minutes); } void StopZone(int zone) { CONSOLE::Print("Stopping zone %d.\n", zone); HunterStop(zone); } void RunProgram(int program) { CONSOLE::Print("Running program %c.\n", 'A' - 1 + program); HunterProgram(program); } }; class CAppPage : public CWnd, public CHunterInterface { public: int mX{0}; int mY{0}; int mnPage{0}; int mnRunZone{1}; int mnRunFor{10}; int mnRunProgram{3}; bool mDemo{false}; int mDemoZone{0}; void DrawMenu() { const char* mPages[] = {"Control"}; CRect rcControls(0, 14+14*10, BIOS::LCD::Width, 14+14*10+14+4); LCD::Bar(rcControls, CONSOLE::colorBack); rcControls.top += 4; int x = 8; for (int i=0; i<COUNT(mPages); i++) { if (mnPage != i) { x += BIOS::LCD::Draw(x, rcControls.top, RGB565(4040b0), RGBTRANS, CShapes_tab_left); x += BIOS::LCD::Print(x, rcControls.top, RGB565(b0b0b0), RGB565(4040b0), mPages[i]); x += BIOS::LCD::Draw(x, rcControls.top, RGB565(4040b0), RGBTRANS, CShapes_tab_right); } else if (mY != -1) { x += BIOS::LCD::Draw(x, rcControls.top, RGB565(404040), RGBTRANS, CShapes_tab_left); x += BIOS::LCD::Print(x, rcControls.top, RGB565(ffffff), RGB565(404040), mPages[i]); x += BIOS::LCD::Draw(x, rcControls.top, RGB565(404040), RGBTRANS, CShapes_tab_right); } else { x += BIOS::LCD::Draw(x, rcControls.top, RGB565(ffffff), RGBTRANS, CShapes_tab_left); x += BIOS::LCD::Print(x, rcControls.top, RGB565(000000), RGB565(ffffff), mPages[i]); x += BIOS::LCD::Draw(x, rcControls.top, RGB565(ffffff), RGBTRANS, CShapes_tab_right); } x += 8; } } void Draw(Layout::Render& r) { using namespace Layout; GUI::Background(r.GetRectangle(), RGB565(404040), RGB565(404040)); r << Padding(4, 4, 4, 2); Color def(RGB565(b0b0b0)); Color hig(RGB565(ffffff)); #define S(x, y) Select(mX == x && mY == y) r << S(0, 0) << RadioButton(true, "Run") << "zone" << S(1, 0) << RadioButton(false, "\x11") << toString(mnRunZone) << S(2, 0) << RadioButton(false, "\x10") << "for" << S(3, 0) << RadioButton(false, "\x11") << toString(mnRunFor) << S(4, 0) << RadioButton(false, "\x10") << "minutes" << NewLine(); r << S(0, 1) << RadioButton(true, "Stop") << "zone " << toString(mnRunZone) << NewLine(); r << S(0, 2) << RadioButton(true, "Run") << "program" << S(1, 2) << RadioButton(false, "\x11") << toChar(mnRunProgram) << S(2, 2) << RadioButton(false, "\x10") << Spacer(64) << S(3, 2) << Radio(mDemo, "Demo"); #undef S } void DrawPage() { CRect rcControls(0, 14+14*10+14+4, BIOS::LCD::Width, BIOS::LCD::Height-14); Layout::Render r(rcControls); Draw(r); } virtual void OnKey(int key) override { if (key == BIOS::KEY::Enter) { switch (mY*16 + mX) { // 1st row case 0x00: StartZone(mnRunZone, mnRunFor); break; case 0x01: if (mnRunZone > 1) mnRunZone--; break; case 0x02: if (mnRunZone < 48) mnRunZone++; break; case 0x03: if (mnRunFor > 5) mnRunFor-=5; break; case 0x04: if (mnRunFor <= 240-5) mnRunFor+=5; break; // 2nd row case 0x10: StopZone(mnRunZone); break; // 3rd row case 0x20: RunProgram(mnRunProgram); break; case 0x21: if (mnRunProgram > 1) mnRunProgram--; break; case 0x22: if (mnRunProgram < 4) mnRunProgram++; break; case 0x23: mDemo = !mDemo; if (!mDemo) StopDemo(); break; } } switch (mY) { case 0: mX = max(0, min(mX, 4)); break; case 1: mX = max(0, min(mX, 0)); break; case 2: mX = max(0, min(mX, 3)); break; case 3: mY = 2; break; } } virtual void OnTimer() override { if (mDemo) DoDemo(); } void DoDemo() { if (++mDemoZone > 4) mDemoZone = 1; StartZone(mDemoZone, 30); } void StopDemo() { StopZone(mDemoZone); } private: char* toString(int n) { static char temp[16]; sprintf(temp, "%d", n); return temp; } char* toChar(int n) { static char temp[2]; sprintf(temp, "%c", 'A'-1+n); return temp; } }; class CApp : public CAppPage { public: //CApp() : CAppPage() {} void Create() { CWnd::Create("application", CWnd::WsVisible, CRect(0, 0, BIOS::LCD::Width, BIOS::LCD::Height), nullptr); CONSOLE::colorBack = RGB565(4040b0); CONSOLE::colorFront = RGB565(aaaaaa); APP::Init("Hunter X-Core controller"); CONSOLE::window = CRect(8, 14, BIOS::LCD::Width-8, 14+14*10); CONSOLE::cursor = CONSOLE::window.TopLeft(); DrawLayout(); APP::Status("AC1: n/c, AC2: +3V, REM: P1"); HunterInit(); SetTimer(5000); } void Destroy() { HunterDeinit(); } void DrawLayout() { DrawMenu(); DrawPage(); } virtual void OnKey(int key) override { if (key == BIOS::KEY::Up && mY > 0) mY--; if (key == BIOS::KEY::Down) mY++; if (key == BIOS::KEY::Left) mX--; if (key == BIOS::KEY::Right) mX++; CAppPage::OnKey(key); DrawPage(); } }; CApp app; #ifdef _ARM __attribute__((__section__(".entry"))) #endif int _main(void) { app.Create(); BIOS::KEY::EKey key; while ((key = KEY::GetKey()) != BIOS::KEY::EKey::Escape) { if (key != BIOS::KEY::EKey::None) app.OnKey(key); app.WindowMessage(CWnd::WmTick); } app.Destroy(); return 0; } void _HandleAssertion(const char* file, int line, const char* cond) { CONSOLE::Color(RGB565(ffff00)); CONSOLE::Print("Assertion failed in "); CONSOLE::Print(file); CONSOLE::Print(" [%d]: %s\n", line, cond); #ifdef __APPLE__ //kill(getpid(), SIGSTOP); #endif while (1); }
27.007143
167
0.470246
tomwei7
c10c1fa2212ad463fe21e8b316ab313120778ff3
30,223
cpp
C++
amd_tressfx_sample/src/Lights/SuLightManager.cpp
kostenickj/TressFX
9a9a1008fbcc9cc71a6b08331a75bed81c2119ac
[ "MIT" ]
1
2020-07-20T19:07:05.000Z
2020-07-20T19:07:05.000Z
amd_tressfx_sample/src/Lights/SuLightManager.cpp
kostenickj/TressFX
9a9a1008fbcc9cc71a6b08331a75bed81c2119ac
[ "MIT" ]
null
null
null
amd_tressfx_sample/src/Lights/SuLightManager.cpp
kostenickj/TressFX
9a9a1008fbcc9cc71a6b08331a75bed81c2119ac
[ "MIT" ]
null
null
null
// // Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "PCH.h" #include "SuAlgorithm.h" #include "SuAnimationSet.h" #include "SuAreaLight.h" #include "SuDirectionalLight.h" #include "SuHashMap.h" #include "SuLight.h" #include "SuLightController.h" #include "SuLightManager.h" #include "SuPointLight.h" #include "SuSpotLight.h" #include "SuVolumeLight.h" /// Light manager singleton instance SuLightManager* SuLightManager::ms_pInstance = NULL; //================================================================================================================================= // // Constructor(s) / Destructor(s) Block // //================================================================================================================================= //================================================================================================================================= /// Default constructor //================================================================================================================================= SuLightManager::SuLightManager() {} //================================================================================================================================= /// Destructor //================================================================================================================================= SuLightManager::~SuLightManager() { for (LightNameMap::iterator itr = m_lights.begin(); itr != m_lights.end(); ++itr) { SU_SAFE_DELETE(itr->second); } } //================================================================================================================================= // // Public methods block // //================================================================================================================================= //================================================================================================================================= /// \return A pointer to the light manager //================================================================================================================================= SuLightManager* SuLightManager::GetPtr() { if (ms_pInstance) { return ms_pInstance; } ms_pInstance = new SuLightManager(); return ms_pInstance; } //================================================================================================================================= /// \return A reference to the light manager //================================================================================================================================= SuLightManager& SuLightManager::GetRef() { return *GetPtr(); } //================================================================================================================================= /// Destroys the light manager and all managed lights //================================================================================================================================= void SuLightManager::ShutDown() { SU_SAFE_DELETE(ms_pInstance); } //================================================================================================================================= /// \param rLightName The name to assign to the point light /// /// \return A point light. Returns NULL if another light with the given name already exists. The /// light manager retains ownership /// of the returned camera. //================================================================================================================================= SuPointLight* SuLightManager::CreatePointLight(const SuString& rLightName) { if (SuLight* pExisting = GetLightByName(rLightName)) { if (pExisting->GetType() != SuLight::POINT_LIGHT) { SuLogError("Light \"%s\" already exists and is not a point light.", static_cast<const char8*>(rLightName)); return NULL; } else { SuLogWarning("Point light \"%s\" already exists. Returning existing point light.", static_cast<const char8*>(rLightName)); return (SuPointLight*)pExisting; } } SuPointLight* pLight = new SuPointLight(rLightName); m_lights.insert(rLightName, pLight); m_lightArray.push_back(pLight); // pLight->SetIndex(m_lightArray.size()-1); return pLight; } //================================================================================================================================= /// \param rLightName The name to assign to the directional light /// /// \return A directional light. Returns NULL if another light with the given name already exists. /// The light manager retains /// ownership of the returned camera. //================================================================================================================================= SuDirectionalLight* SuLightManager::CreateDirectionalLight(const SuString& rLightName) { if (SuLight* pExisting = GetLightByName(rLightName)) { if (pExisting->GetType() != SuLight::DIRECTIONAL_LIGHT) { SuLogError("Light \"%s\" already exists and is not a directional light.", static_cast<const char8*>(rLightName)); return NULL; } else { SuLogWarning( "Directional light \"%s\" already exists. Returning existing directional light.", static_cast<const char8*>(rLightName)); return (SuDirectionalLight*)pExisting; } } SuDirectionalLight* pLight = new SuDirectionalLight(rLightName); m_lights.insert(rLightName, pLight); m_lightArray.push_back(pLight); // pLight->SetIndex(m_lightArray.size()-1); return pLight; } //================================================================================================================================= /// \param rLightName The name to assign to the spot light /// /// \return A spot light. Returns NULL if another light with the given name already exists. The /// light manager retains ownership /// of the returned camera. //================================================================================================================================= SuSpotLight* SuLightManager::CreateSpotLight(const SuString& rLightName) { if (SuLight* pExisting = GetLightByName(rLightName)) { if (pExisting->GetType() != SuLight::SPOT_LIGHT) { SuLogError("Light \"%s\" already exists and is not a spotlight.", static_cast<const char8*>(rLightName)); return NULL; } else { SuLogWarning("Spotlight \"%s\" already exists. Returning existing spotlight.", static_cast<const char8*>(rLightName)); return (SuSpotLight*)pExisting; } } SuSpotLight* pLight = new SuSpotLight(rLightName); m_lights.insert(rLightName, pLight); m_lightArray.push_back(pLight); // pLight->SetIndex(m_lightArray.size()-1); return pLight; } //================================================================================================================================= /// \param rLightName The name to assign to the volume light /// /// \return A volume light. Returns NULL or the original camera if another light with the given /// name already exists. //================================================================================================================================= SuVolumeLight* SuLightManager::CreateVolumeLight(const SuString& rLightName) { if (SuLight* pExisting = GetLightByName(rLightName)) { if (pExisting->GetType() != SuLight::VOLUME_LIGHT) { SuLogError("Light \"%s\" already exists and is not a volume light.", static_cast<const char8*>(rLightName)); return NULL; } else { SuLogWarning("Volume light \"%s\" already exists. Returning existing volume light.", static_cast<const char8*>(rLightName)); return (SuVolumeLight*)pExisting; } } SuVolumeLight* pLight = new SuVolumeLight(rLightName); m_lights.insert(rLightName, pLight); m_lightArray.push_back(pLight); // pLight->SetIndex(m_lightArray.size()-1); return pLight; } //================================================================================================================================= /// \param rLightName The name to assign to the area light /// /// \return A area light. Returns NULL if another light with the given name already exists. The /// light manager retains ownership /// of the returned camera. //================================================================================================================================= SuAreaLight* SuLightManager::CreateAreaLight(const SuString& rLightName) { if (SuLight* pExisting = GetLightByName(rLightName)) { if (pExisting->GetType() != SuLight::AREA_LIGHT) { SuLogError("Light \"%s\" already exists and is not an area light.", static_cast<const char8*>(rLightName)); return NULL; } else { SuLogWarning("Area light \"%s\" already exists. Returning existing area light.", static_cast<const char8*>(rLightName)); return (SuAreaLight*)pExisting; } } SuAreaLight* pLight = new SuAreaLight(rLightName); m_lights.insert(rLightName, pLight); m_lightArray.push_back(pLight); // pLight->SetIndex(m_lightArray.size()-1); return pLight; } //================================================================================================================================= /// \param rLightName The name of the desired light /// /// \return A pointer to the light with the given name. NULL if no such light exists. //================================================================================================================================= SuLight* SuLightManager::GetLightByName(const SuString& rLightName) const { LightNameMap::iterator itr = m_lights.find(rLightName); if (itr != m_lights.end()) { return itr->second; } return NULL; } //================================================================================================================================= /// Loads a light set file /// /// \param rFileName The light set file name /// /// \return true on success, false otherwise //================================================================================================================================= bool SuLightManager::LoadLightSet(const SuString& rFileName) { return LoadLightSet(rFileName, 0, NULL); } //================================================================================================================================= /// Loads a light set file /// /// \param rFileName The light set file name /// \param nNumProperties Number of properties in properties array /// \param pProperties Array of properties to assign to the lights in the set /// /// \return true on success, false otherwise //================================================================================================================================= bool SuLightManager::LoadLightSet(const SuString& rFileName, uint32 nNumProperties, const SuString* pProperties) { SuAnimationSet* pAnimSet = SuAnimationSet::CreateFromFile(rFileName); if (pAnimSet == NULL) { return false; } // extract light types and names from the animation set SuArray<SuString> lightNames; SuArray<uint8> lightTypes; ExtractLightsFromLightSet(lightNames, lightTypes, pAnimSet); // create a LightSetInfo structure for this light set m_lightSets.push_back(SuLightSetInfo()); SuLightSetInfo& rSetInfo = m_lightSets.back(); rSetInfo.animationFile = rFileName; rSetInfo.properties.reserve(nNumProperties); for (uint32 iProperty = 0; iProperty < nNumProperties; ++iProperty) { rSetInfo.properties.push_back(pProperties[iProperty]); } // create lights for (uint32 i = 0; i < lightNames.size(); i++) { SuLight* pLight = CreateLightFromLightSet(lightNames[i], lightTypes[i], pAnimSet); if (pLight) { rSetInfo.lights.insert(lightNames[i], pLight); } for (uint32 n = 0; n < nNumProperties; n++) { pLight->AddProperty(pProperties[n]); } } SU_SAFE_DELETE(pAnimSet); return true; } //================================================================================================================================= /// Reloads all light sets that were loaded through a call to LoadLightSet() /// /// This method cannot support changing light types. If a light-set reload would cause light types /// to change, /// then re-loading of that particular light is skipped. /// /// \return True if successful, false if any lightsets were skipped due to light type changes //================================================================================================================================= bool SuLightManager::ReloadLightSets() { bool bErrors = false; // attempt to re-load each of the light sets that was loaded previously for (SuList<SuLightSetInfo>::iterator itr = m_lightSets.begin(); itr != m_lightSets.end(); itr++) { SuLogInfo("Reloading light set from file: %s ", itr->animationFile.GetBuffer()); // re-open animation set const SuAnimationSet* pSet = SuAnimationSet::CreateFromFile(itr->animationFile); if (!pSet) { SuLogError("Unable to create animation set from file: %s ", itr->animationFile.GetBuffer()); bErrors = true; continue; } // extract light information SuArray<SuString> lightNames; SuArray<uint8> lightTypes; ExtractLightsFromLightSet(lightNames, lightTypes, pSet); // modify existing lights, and create new lights if specified for (uint32 i = 0; i < lightNames.size(); i++) { SuLight* pLight = GetLightByName(lightNames[i]); if (pLight) { // existing light. Type specified in animation set must match actual type if (pLight->GetType() != lightTypes[i]) { SuLogError( "Light type in lightset '%s' for light named: '%s' does not match type of existing light. To change light types, you must restart the demo.", itr->animationFile.GetBuffer(), lightNames[i].GetBuffer()); continue; } // light types match for existing light, make a new controller SuLightControllerPtr pCtrl = CreateLightController(pLight, lightNames[i], *pSet); pLight->SetController(pCtrl); } else { // create new light for this light set SuLight* pLight = CreateLightFromLightSet(lightNames[i], lightTypes[i], pSet); if (pLight) { size_t nProperties = itr->properties.size(); for (size_t iProperty = 0; iProperty < nProperties; ++iProperty) { pLight->AddProperty(itr->properties[iProperty]); } itr->lights.insert(lightNames[i], pLight); } else { bErrors = true; } } } SU_SAFE_DELETE(pSet); } if (bErrors) { SuLogError("Reloaded lightsets with errors!!!"); } else { SuLogInfo("Reloaded lightsets."); } return bErrors; } //================================================================================================================================= // // Private methods block // //================================================================================================================================= //================================================================================================================================= /// \param rLightName Name of light to create /// \param nLightType Type of light to create /// \param pAnimSet Animation set containing light parameter curves /// \return A pointer to the created light, or NULL //================================================================================================================================= SuLight* SuLightManager::CreateLightFromLightSet(const SuString& rLightName, uint8 nLightType, const SuAnimationSet* pAnimSet) { SuLight* pLight = NULL; switch (nLightType) { case SuLight::POINT_LIGHT: { pLight = CreatePointLight(rLightName); if (!pLight) { SuLogWarning("Unable to create point light!"); } } break; case SuLight::DIRECTIONAL_LIGHT: { pLight = CreateDirectionalLight(rLightName); if (!pLight) { SuLogWarning("Unable to create directional light!"); } } break; case SuLight::SPOT_LIGHT: { pLight = CreateSpotLight(rLightName); if (!pLight) { SuLogWarning("Unable to create spot light!"); } } break; case SuLight::VOLUME_LIGHT: { pLight = CreateVolumeLight(rLightName); if (!pLight) { SuLogWarning("Unable to create volume light!"); } } break; case SuLight::AREA_LIGHT: { pLight = CreateAreaLight(rLightName); if (!pLight) { SuLogWarning(" Unable to create area light!"); } } break; default: { SuLogError("Unidentified light type!"); return NULL; } } if (!pLight) { return NULL; } SuLightControllerPtr pCtrl = CreateLightController(pLight, rLightName, *pAnimSet); pLight->SetController(pCtrl); return pLight; } //================================================================================================================================= /// Extracts an array of light names and types from an animation set /// This is done by parsing the curve names and looking for the prefixes 'point', 'directional' or /// 'spot' /// \param rLightNames An array that will be filled with light names /// \param rLightTypes An array that will be filled with light types /// \param pAnimSet The animation set to parse //================================================================================================================================= void SuLightManager::ExtractLightsFromLightSet(SuArray<SuString>& rLightNames, SuArray<uint8>& rLightTypes, const SuAnimationSet* pAnimSet) { SuStringList animNames = pAnimSet->GetAllCurveNames(); typedef SuHashMap<SuString, bool, SuStringHasher, SuHashComparer<SuString> > LightNameSet; LightNameSet pointLightNames; LightNameSet dirLightNames; LightNameSet spotLightNames; LightNameSet volumeLightNames; LightNameSet areaLightNames; // get all unique lights in the set for (SuStringList::iterator it = animNames.begin(); it != animNames.end(); ++it) { SuStringList tokens = it->Split("."); if (tokens.size() != 3) { SuLogWarning("Unrecognized animation in light set: " + *it); continue; } if (tokens.front() == "point") { tokens.pop_front(); pointLightNames.insert(tokens.front(), true); } else if (tokens.front() == "directional") { tokens.pop_front(); dirLightNames.insert(tokens.front(), true); } else if (tokens.front() == "spot") { tokens.pop_front(); spotLightNames.insert(tokens.front(), true); } else if (tokens.front() == "volume") { tokens.pop_front(); volumeLightNames.insert(tokens.front(), true); } else if (tokens.front() == "area") { tokens.pop_front(); areaLightNames.insert(tokens.front(), true); } else { SuLogWarning("Unrecognized light type in light set: " + tokens.front()); continue; } } // count lights uint32 nLights = pointLightNames.size() + dirLightNames.size() + spotLightNames.size() + volumeLightNames.size() + areaLightNames.size(); // initialize array of light types rLightTypes.reserve(nLights); rLightTypes.insert(rLightTypes.end(), pointLightNames.size(), SuLight::POINT_LIGHT); rLightTypes.insert(rLightTypes.end(), dirLightNames.size(), SuLight::DIRECTIONAL_LIGHT); rLightTypes.insert(rLightTypes.end(), spotLightNames.size(), SuLight::SPOT_LIGHT); rLightTypes.insert(rLightTypes.end(), volumeLightNames.size(), SuLight::VOLUME_LIGHT); rLightTypes.insert(rLightTypes.end(), areaLightNames.size(), SuLight::AREA_LIGHT); // initialize array of light names rLightNames.reserve(nLights); for (LightNameSet::iterator it = pointLightNames.begin(); it != pointLightNames.end(); ++it) { rLightNames.push_back(it->first); } for (LightNameSet::iterator it = dirLightNames.begin(); it != dirLightNames.end(); ++it) { rLightNames.push_back(it->first); } for (LightNameSet::iterator it = spotLightNames.begin(); it != spotLightNames.end(); ++it) { rLightNames.push_back(it->first); } for (LightNameSet::iterator it = volumeLightNames.begin(); it != volumeLightNames.end(); ++it) { rLightNames.push_back(it->first); } for (LightNameSet::iterator it = areaLightNames.begin(); it != areaLightNames.end(); ++it) { rLightNames.push_back(it->first); } } //================================================================================================================================= /// \param pLight Light to create a controller for /// \param rLightName Light name /// \param rAnimSet Animation set that contains the animation curves for the light /// /// \return Smart pointer to a light controller with the relevant animation curves from the /// animation set //================================================================================================================================= SuLightControllerPtr SuLightManager::CreateLightController(SuLight* pLight, const SuString& rLightName, const SuAnimationSet& rAnimSet) { SU_ASSERT(pLight != NULL); SuString curveNamePrefix; switch (pLight->GetType()) { case SuLight::POINT_LIGHT: curveNamePrefix = "point."; break; case SuLight::DIRECTIONAL_LIGHT: curveNamePrefix = "directional."; break; case SuLight::SPOT_LIGHT: curveNamePrefix = "spot."; break; case SuLight::VOLUME_LIGHT: curveNamePrefix = "volume."; break; case SuLight::AREA_LIGHT: curveNamePrefix = "area."; break; default: SU_ASSERT(!"Unsupported light type"); break; } curveNamePrefix += rLightName; // Common attributes SuString curveName = curveNamePrefix + ".vColor"; SuAnimationCurvePtr pColorCurve = rAnimSet.GetCurve(curveName); curveName = curveNamePrefix + ".fIntensity"; SuAnimationCurvePtr pIntensityCurve = rAnimSet.GetCurve(curveName); curveName = curveNamePrefix + ".bEmitDiffuse"; SuAnimationCurvePtr pDiffuseCurve = rAnimSet.GetCurve(curveName); curveName = curveNamePrefix + ".bEmitSpecular"; SuAnimationCurvePtr pSpecularCurve = rAnimSet.GetCurve(curveName); curveName = curveNamePrefix + ".nDecayRate"; SuAnimationCurvePtr pFalloffCurve = rAnimSet.GetCurve(curveName); curveName = curveNamePrefix + ".visibility"; SuAnimationCurvePtr pVisibilityCurve = rAnimSet.GetCurve(curveName); SuAnimationCurvePtr pRadiusCurve; SuAnimationCurvePtr pPosCurve; SuAnimationCurvePtr pOrientationCurve; SuAnimationCurvePtr pScaleCurve; SuAnimationCurvePtr pConeAngleCurve; SuAnimationCurvePtr pPenumbraAngleCurve; SuAnimationCurvePtr pDropOffCurve; SuAnimationCurvePtr pLightShapeCurve; SuAnimationCurvePtr pSushiLightIndirectCurve; if (pLight->GetType() == SuLight::POINT_LIGHT) { // point light curveName = curveNamePrefix + ".fRadius"; pRadiusCurve = rAnimSet.GetCurve(curveName); } if (pLight->GetType() == SuLight::POINT_LIGHT || pLight->GetType() == SuLight::SPOT_LIGHT || pLight->GetType() == SuLight::VOLUME_LIGHT || pLight->GetType() == SuLight::AREA_LIGHT) { // point and spot light curveName = curveNamePrefix + ".vPosition"; pPosCurve = rAnimSet.GetCurve(curveName); } if (pLight->GetType() == SuLight::DIRECTIONAL_LIGHT || pLight->GetType() == SuLight::SPOT_LIGHT || pLight->GetType() == SuLight::VOLUME_LIGHT || pLight->GetType() == SuLight::AREA_LIGHT) { // directional, splot light and vollume light curveName = curveNamePrefix + ".qOrientation"; pOrientationCurve = rAnimSet.GetCurve(curveName); } if (pLight->GetType() == SuLight::SPOT_LIGHT) { // spotlight curveName = curveNamePrefix + ".fConeAngle"; pConeAngleCurve = rAnimSet.GetCurve(curveName); curveName = curveNamePrefix + ".fPenumbraAngle"; pPenumbraAngleCurve = rAnimSet.GetCurve(curveName); curveName = curveNamePrefix + ".fDropOff"; pDropOffCurve = rAnimSet.GetCurve(curveName); } if (pLight->GetType() == SuLight::VOLUME_LIGHT || pLight->GetType() == SuLight::AREA_LIGHT) { curveName = curveNamePrefix + ".vScale"; pScaleCurve = rAnimSet.GetCurve(curveName); } if (pLight->GetType() == SuLight::VOLUME_LIGHT) { curveName = curveNamePrefix + ".nLightShape"; pLightShapeCurve = rAnimSet.GetCurve(curveName); curveName = curveNamePrefix + ".bSushiLightIndirect"; pSushiLightIndirectCurve = rAnimSet.GetCurve(curveName); } // create controller SuLightControllerPtr pController = SuLightControllerPtr(new SuLightController(pColorCurve, pIntensityCurve, pDiffuseCurve, pSpecularCurve, pFalloffCurve, pRadiusCurve, pPosCurve, pOrientationCurve, pScaleCurve, pConeAngleCurve, pPenumbraAngleCurve, pDropOffCurve, pVisibilityCurve, pLightShapeCurve, pSushiLightIndirectCurve)); SU_ASSERT(pController != NULL); return pController; }
39.767105
167
0.483274
kostenickj
c11426d3563aa8365db081c4919eb131a87f8cc4
2,789
cpp
C++
drivers/unix/ip_unix.cpp
ayrat-forks/godot
02669e95a4975898d97aeaedc913b16f60688a01
[ "MIT" ]
3
2015-11-10T03:53:31.000Z
2019-11-10T20:39:47.000Z
drivers/unix/ip_unix.cpp
bshawk/godot
c12a8e922ff724d7fe9909c16f9a1b5aec7f010b
[ "MIT" ]
2
2021-08-18T15:38:29.000Z
2021-08-31T08:06:16.000Z
drivers/unix/ip_unix.cpp
bshawk/godot
c12a8e922ff724d7fe9909c16f9a1b5aec7f010b
[ "MIT" ]
null
null
null
/*************************************************************************/ /* ip_unix.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* 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 "ip_unix.h" #if defined(UNIX_ENABLED) || defined(WINDOWS_ENABLED) #ifdef WINDOWS_ENABLED #include <ws2tcpip.h> #include <winsock2.h> #include <windows.h> #else #include <netdb.h> #endif IP_Address IP_Unix::_resolve_hostname(const String& p_hostname) { struct hostent *he; if ((he=gethostbyname(p_hostname.utf8().get_data())) == NULL) { // get the host info ERR_PRINT("gethostbyname failed!"); return IP_Address(); } IP_Address ip; ip.host= *((unsigned long*)he->h_addr); return ip; } void IP_Unix::make_default() { _create=_create_unix; } IP* IP_Unix::_create_unix() { return memnew( IP_Unix ); } IP_Unix::IP_Unix() { } #endif
40.42029
86
0.498745
ayrat-forks
c116098ef8a95e80c77ca1d1705cdb6924b0c9e5
520
cpp
C++
CodeForces/Complete/1200-1299/1200A-Hotelier.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
CodeForces/Complete/1200-1299/1200A-Hotelier.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
CodeForces/Complete/1200-1299/1200A-Hotelier.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
#include <iostream> #include <vector> int main(){ const int cap = 10; long n; std::cin >> n; std::string s; std::cin >> s; std::vector<int> a(cap, 0); for(long p = 0; p < n; p++){ if(s[p] == 'L'){for(long u = 0; u < cap; u++){if(!a[u]){a[u] = 1; break;}}} else if(s[p] == 'R'){for(long u = cap - 1; u >= 0; u--){if(!a[u]){a[u] = 1; break;}}} else{a[s[p] - '0'] = 0;} } for(long p = 0; p < cap; p++){std::cout << a[p];} std::cout << std::endl; return 0; }
23.636364
93
0.434615
Ashwanigupta9125
c1177ae0d3a2d7f1c45ec7dcc59e50650644849e
4,626
cpp
C++
blas/L3/examples/gemm/gemm_common_example.cpp
heeran-xilinx/Vitis_Libraries
ab3f6969e397dc44705a7278fb0d480e905e72db
[ "Apache-2.0" ]
null
null
null
blas/L3/examples/gemm/gemm_common_example.cpp
heeran-xilinx/Vitis_Libraries
ab3f6969e397dc44705a7278fb0d480e905e72db
[ "Apache-2.0" ]
null
null
null
blas/L3/examples/gemm/gemm_common_example.cpp
heeran-xilinx/Vitis_Libraries
ab3f6969e397dc44705a7278fb0d480e905e72db
[ "Apache-2.0" ]
1
2021-06-08T06:18:10.000Z
2021-06-08T06:18:10.000Z
/* * Copyright 2019 Xilinx, 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 "xf_blas.hpp" #define IDX2R(i, j, ld) (((i) * (ld)) + (j)) #define m 5 // a - mxk matrix #define n 5 // b - kxn matrix #define k 5 // c - mxn matrix using namespace std; int main(int argc, char** argv) { if (argc < 3) { cerr << " usage: \n" << " gemm_common_test.exe gemx.xclbin config_info.dat 1\n" << " gemm_common_test.exe gemx.xclbin config_info.dat\n"; return EXIT_FAILURE; } unsigned int l_argIdx = 1; string l_xclbinFile(argv[l_argIdx++]); string l_configFile(argv[l_argIdx++]); string l_logFile; ofstream logFile("xrt_report.txt"); logFile.close(); l_logFile = "xrt_report.txt"; int l_numKernel = 1; if (argc == 4) { cout << "read custom number of kernels\n"; l_numKernel = stoi(argv[l_argIdx++]); } int i, j; // i-row index ,j- column index XFBLAS_dataType *a, *b, *c; a = (XFBLAS_dataType*)malloc(m * k * sizeof(XFBLAS_dataType)); // host memory for a b = (XFBLAS_dataType*)malloc(k * n * sizeof(XFBLAS_dataType)); c = (XFBLAS_dataType*)malloc(m * n * sizeof(XFBLAS_dataType)); int ind = 1; for (i = 0; i < m; i++) { for (j = 0; j < k; j++) { a[IDX2R(i, j, k)] = (XFBLAS_dataType)ind++; } } for (i = 0; i < k; i++) { for (j = 0; j < n; j++) { b[IDX2R(i, j, n)] = (XFBLAS_dataType)ind++; } } for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { c[IDX2R(i, j, n)] = 0; } } XFBLAS_dataType *d_a, *d_b, *d_c; xfblasEngine_t engineName = XFBLAS_ENGINE_GEMM; xfblasStatus_t status = XFBLAS_STATUS_SUCCESS; status = xfblasCreate(l_xclbinFile.c_str(), l_configFile, l_logFile.c_str(), engineName, l_numKernel); if (status != XFBLAS_STATUS_SUCCESS) { cout << "Create Handle failed with error code: " << status << "\n"; return EXIT_FAILURE; } status = xfblasMalloc(&d_a, m, k, sizeof(*a), l_numKernel - 1); if (status != XFBLAS_STATUS_SUCCESS) { cout << "Malloc memory for matrix A failed with error code: " << status << "\n"; return EXIT_FAILURE; } status = xfblasMalloc(&d_b, k, n, sizeof(*b), l_numKernel - 1); if (status != XFBLAS_STATUS_SUCCESS) { cout << "Malloc memory for matrix B failed with error code: " << status << "\n"; return EXIT_FAILURE; } status = xfblasMalloc(&d_c, m, n, sizeof(*c), l_numKernel - 1); if (status != XFBLAS_STATUS_SUCCESS) { cout << "Malloc memory for matrix C failed with error code: " << status << "\n"; return EXIT_FAILURE; } status = xfblasSetMatrix(m, k, sizeof(*a), a, k, d_a, l_numKernel - 1); status = xfblasSetMatrix(k, n, sizeof(*b), b, n, d_b, l_numKernel - 1); status = xfblasSetMatrix(m, n, sizeof(*c), c, n, d_c, l_numKernel - 1); if (status != XFBLAS_STATUS_SUCCESS) { cout << "Set Matrix failed with error code: " << status << "\n"; return EXIT_FAILURE; } status = xfblasGemm(XFBLAS_OP_N, XFBLAS_OP_N, m, n, k, 1, d_a, k, d_b, n, 1, d_c, n, l_numKernel - 1); if (status != XFBLAS_STATUS_SUCCESS) { cout << "Matrix Multiplication failed with error code: " << status << "\n"; return EXIT_FAILURE; } status = xfblasGetMatrix(m, n, sizeof(*c), d_c, c, n, l_numKernel - 1); if (status != XFBLAS_STATUS_SUCCESS) { cout << "Get Matirx failed with error code: " << status << "\n"; return EXIT_FAILURE; } for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { cout << (c[IDX2R(i, j, k)]) << " "; } cout << "\n"; } // 590 605 620 635 650 // 1490 1530 1570 1610 1650 // 2390 2455 2520 2585 2650 // 3290 3380 3470 3560 3650 // 4190 4305 4420 4535 4650 xfblasFree(d_a, l_numKernel - 1); xfblasFree(d_b, l_numKernel - 1); xfblasFree(d_c, l_numKernel - 1); xfblasDestroy(l_numKernel); free(a); free(b); free(c); }
30.84
106
0.585171
heeran-xilinx
c1183c22b37dd1958f3e3efd5dd808a8c5aa282b
2,697
cpp
C++
Source/FSD/Private/LineCutterProjectile.cpp
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
null
null
null
Source/FSD/Private/LineCutterProjectile.cpp
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
null
null
null
Source/FSD/Private/LineCutterProjectile.cpp
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
null
null
null
#include "LineCutterProjectile.h" #include "Net/UnrealNetwork.h" #include "Particles/ParticleSystemComponent.h" #include "DamageComponent.h" #include "Components/SceneComponent.h" void ALineCutterProjectile::UpdateBeamLocations() { } void ALineCutterProjectile::TerrainSweep(const FVector& Left, const FVector& Right) { } void ALineCutterProjectile::SpawnDecal(FHitResult& Result) { } void ALineCutterProjectile::Server_RemoveDebris_Implementation(int32 instance, int32 Component) { } bool ALineCutterProjectile::Server_RemoveDebris_Validate(int32 instance, int32 Component) { return true; } void ALineCutterProjectile::OnRep_LineRotation() { } void ALineCutterProjectile::Fire(const FVector& Origin, const FVector& Direction, float Distance) { } void ALineCutterProjectile::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME(ALineCutterProjectile, LineRotation); DOREPLIFETIME(ALineCutterProjectile, RotationMode); } ALineCutterProjectile::ALineCutterProjectile() { this->SwipeRadius = 5.00f; this->DoubleLineDistanceMultiplier = 2.00f; this->OverlapRadius = 5.00f; this->DestroyOnTerrainCollision = true; this->IsDead = false; this->bHasReversedDirection = false; this->FlyStraighTime = 0.20f; this->EletricDecalSize = EImpactDecalSize::Small; this->ImpactDecalSize = EImpactDecalSize::Small; this->LineRoot = CreateDefaultSubobject<USceneComponent>(TEXT("LineRoot")); this->LeftSphere = NULL; this->RightSphere = NULL; this->LeftSphere2 = NULL; this->RightSphere2 = NULL; this->LeftSphere3 = NULL; this->RightSphere3 = NULL; this->BeamParticle = NULL; this->BeamParticle2 = NULL; this->BeamParticle3 = NULL; this->LeftHitParticles = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("LeftImpact")); this->RightHitParticles = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("RightImpact")); this->RotationSpeed = 400.00f; this->RotationMode = ELineRotation::None; this->ShouldExplode = false; this->OnlyOne = false; this->IsDoubleLine = false; this->HasPlasmaTrail = false; this->LineMaxSize = 150.00f; this->LineExpansionDelay = 0.25f; this->TimeToLineExpansion = 0.35f; this->FireRate = 0.01f; this->DamageComponent = CreateDefaultSubobject<UDamageComponent>(TEXT("DamageComponent")); this->InitialDamageComponent = CreateDefaultSubobject<UDamageComponent>(TEXT("InitialDamageComponent")); this->InitialHitDamageMultiplier = 5; this->InhibitImpactDecalsTime = 0.00f; this->MinTimeBetweenImpactDecals = 0.15f; }
35.486842
108
0.754542
trumank
c11c3ec3e0ee66d9266874f466fe8a91a4c39dd6
10,080
hpp
C++
include/GlobalNamespace/RemoteProcedureCall.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/RemoteProcedureCall.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/RemoteProcedureCall.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: IRemoteProcedureCall #include "GlobalNamespace/IRemoteProcedureCall.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { } // Forward declaring namespace: LiteNetLib::Utils namespace LiteNetLib::Utils { // Forward declaring type: NetDataWriter class NetDataWriter; // Forward declaring type: NetDataReader class NetDataReader; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Size: 0x14 #pragma pack(push, 1) // Autogenerated type: RemoteProcedureCall // [TokenAttribute] Offset: FFFFFFFF class RemoteProcedureCall : public ::Il2CppObject/*, public GlobalNamespace::IRemoteProcedureCall*/ { public: // Nested type: GlobalNamespace::RemoteProcedureCall::TypeWrapper_1<T> template<typename T> struct TypeWrapper_1; // private System.Single <syncTime>k__BackingField // Size: 0x4 // Offset: 0x10 float syncTime; // Field size check static_assert(sizeof(float) == 0x4); // Creating value type constructor for type: RemoteProcedureCall RemoteProcedureCall(float syncTime_ = {}) noexcept : syncTime{syncTime_} {} // Creating interface conversion operator: operator GlobalNamespace::IRemoteProcedureCall operator GlobalNamespace::IRemoteProcedureCall() noexcept { return *reinterpret_cast<GlobalNamespace::IRemoteProcedureCall*>(this); } // Creating conversion operator: operator float constexpr operator float() const noexcept { return syncTime; } // Get instance field: private System.Single <syncTime>k__BackingField float _get_$syncTime$k__BackingField(); // Set instance field: private System.Single <syncTime>k__BackingField void _set_$syncTime$k__BackingField(float value); // public System.Single get_syncTime() // Offset: 0x23CEFB0 float get_syncTime(); // public System.Void set_syncTime(System.Single value) // Offset: 0x23CEFB8 void set_syncTime(float value); // protected System.Void SerializeData(LiteNetLib.Utils.NetDataWriter writer) // Offset: 0x23CEFC0 void SerializeData(LiteNetLib::Utils::NetDataWriter* writer); // protected System.Void DeserializeData(LiteNetLib.Utils.NetDataReader reader) // Offset: 0x23CEFC4 void DeserializeData(LiteNetLib::Utils::NetDataReader* reader); // private System.Void LiteNetLib.Utils.INetSerializable.Serialize(LiteNetLib.Utils.NetDataWriter writer) // Offset: 0x23CEFC8 void LiteNetLib_Utils_INetSerializable_Serialize(LiteNetLib::Utils::NetDataWriter* writer); // private System.Void LiteNetLib.Utils.INetSerializable.Deserialize(LiteNetLib.Utils.NetDataReader reader) // Offset: 0x23CF010 void LiteNetLib_Utils_INetSerializable_Deserialize(LiteNetLib::Utils::NetDataReader* reader); // public System.Void Release() // Offset: 0x23CF058 void Release(); // public IRemoteProcedureCall Init(System.Single syncTime) // Offset: 0x23CF178 GlobalNamespace::IRemoteProcedureCall* Init(float syncTime); // protected System.Void .ctor() // Offset: 0x23CF180 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static RemoteProcedureCall* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::RemoteProcedureCall::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<RemoteProcedureCall*, creationType>())); } }; // RemoteProcedureCall #pragma pack(pop) static check_size<sizeof(RemoteProcedureCall), 16 + sizeof(float)> __GlobalNamespace_RemoteProcedureCallSizeCheck; static_assert(sizeof(RemoteProcedureCall) == 0x14); } DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::RemoteProcedureCall*, "", "RemoteProcedureCall"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::get_syncTime // Il2CppName: get_syncTime template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::RemoteProcedureCall::*)()>(&GlobalNamespace::RemoteProcedureCall::get_syncTime)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RemoteProcedureCall*), "get_syncTime", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::set_syncTime // Il2CppName: set_syncTime template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::RemoteProcedureCall::*)(float)>(&GlobalNamespace::RemoteProcedureCall::set_syncTime)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RemoteProcedureCall*), "set_syncTime", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::SerializeData // Il2CppName: SerializeData template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::RemoteProcedureCall::*)(LiteNetLib::Utils::NetDataWriter*)>(&GlobalNamespace::RemoteProcedureCall::SerializeData)> { static const MethodInfo* get() { static auto* writer = &::il2cpp_utils::GetClassFromName("LiteNetLib.Utils", "NetDataWriter")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RemoteProcedureCall*), "SerializeData", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{writer}); } }; // Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::DeserializeData // Il2CppName: DeserializeData template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::RemoteProcedureCall::*)(LiteNetLib::Utils::NetDataReader*)>(&GlobalNamespace::RemoteProcedureCall::DeserializeData)> { static const MethodInfo* get() { static auto* reader = &::il2cpp_utils::GetClassFromName("LiteNetLib.Utils", "NetDataReader")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RemoteProcedureCall*), "DeserializeData", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{reader}); } }; // Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::LiteNetLib_Utils_INetSerializable_Serialize // Il2CppName: LiteNetLib.Utils.INetSerializable.Serialize template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::RemoteProcedureCall::*)(LiteNetLib::Utils::NetDataWriter*)>(&GlobalNamespace::RemoteProcedureCall::LiteNetLib_Utils_INetSerializable_Serialize)> { static const MethodInfo* get() { static auto* writer = &::il2cpp_utils::GetClassFromName("LiteNetLib.Utils", "NetDataWriter")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RemoteProcedureCall*), "LiteNetLib.Utils.INetSerializable.Serialize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{writer}); } }; // Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::LiteNetLib_Utils_INetSerializable_Deserialize // Il2CppName: LiteNetLib.Utils.INetSerializable.Deserialize template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::RemoteProcedureCall::*)(LiteNetLib::Utils::NetDataReader*)>(&GlobalNamespace::RemoteProcedureCall::LiteNetLib_Utils_INetSerializable_Deserialize)> { static const MethodInfo* get() { static auto* reader = &::il2cpp_utils::GetClassFromName("LiteNetLib.Utils", "NetDataReader")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RemoteProcedureCall*), "LiteNetLib.Utils.INetSerializable.Deserialize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{reader}); } }; // Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::Release // Il2CppName: Release template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::RemoteProcedureCall::*)()>(&GlobalNamespace::RemoteProcedureCall::Release)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RemoteProcedureCall*), "Release", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::Init // Il2CppName: Init template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::IRemoteProcedureCall* (GlobalNamespace::RemoteProcedureCall::*)(float)>(&GlobalNamespace::RemoteProcedureCall::Init)> { static const MethodInfo* get() { static auto* syncTime = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RemoteProcedureCall*), "Init", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{syncTime}); } }; // Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
58.604651
241
0.754365
marksteward
c11d9c294e7f6cd4f7f77911292c4233a1cda89a
4,966
hh
C++
RecoDataProducts/inc/TrackSummary.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
9
2020-03-28T00:21:41.000Z
2021-12-09T20:53:26.000Z
RecoDataProducts/inc/TrackSummary.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
684
2019-08-28T23:37:43.000Z
2022-03-31T22:47:45.000Z
RecoDataProducts/inc/TrackSummary.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
61
2019-08-16T23:28:08.000Z
2021-12-20T08:29:48.000Z
// TrackSummary is a persistable class to communicate track // reconstruction results to physics analyses. // // Andrei Gaponenko, 2014 #ifndef RecoDataProducts_TrackSummary_hh #define RecoDataProducts_TrackSummary_hh #include "CLHEP/Vector/ThreeVector.h" #include "CLHEP/Matrix/SymMatrix.h" #include <ostream> class TrkSimpTraj; // BaBar class namespace mu2e { class TrackSummary { public: //================================================================ class HelixParams { public: // See docdb-781 for parameter definitions double d0() const { return d0_; } double phi0() const { return phi0_; } double omega() const { return omega_; } double z0() const { return z0_; } double tanDip() const { return tanDip_; } // Picked from BTrk/BaBar/BTrk/TrkBase/include/HelixParams.hh enum ParIndex {d0Index=0, phi0Index, omegaIndex, z0Index, tanDipIndex, NHLXPRM}; const CLHEP::HepSymMatrix& covariance() const { return covariance_; } //Not yet implemented - commented out until it is. //double parErr(ParIndex i); // Some derived quantities double dOut() const; // max distance to Z axis, opposite to d0() double radius() const; // of the helix double wavelength() const; // of the helix explicit HelixParams(const TrkSimpTraj& ltraj); // Default constructor is required by ROOT persistency HelixParams() : d0_(), phi0_(), omega_(), z0_(), tanDip_(), covariance_(NHLXPRM) {} private: double d0_; double phi0_; double omega_; double z0_; double tanDip_; CLHEP::HepSymMatrix covariance_; }; //================================================================ class TrackStateAtPoint { public: const HelixParams& helix() const { return helix_; } const CLHEP::Hep3Vector& position() const { return position_; } const CLHEP::Hep3Vector& momentum() const { return momentum_; } const CLHEP::HepSymMatrix& momentumCovariance() const { return momentumCovariance_; } double arrivalTime() const { return arrivalTime_; } double flightLength() const { return flightLength_; } // Derived quantities double momentumError() const; double costh() const; // momentum vector cosine to the Z axis TrackStateAtPoint(const HelixParams& h, const CLHEP::Hep3Vector& pos, const CLHEP::Hep3Vector& mom, const CLHEP::HepSymMatrix& momCov, double arrivalTime, double flightLength) : helix_(h) , position_(pos), momentum_(mom) , momentumCovariance_(momCov) , arrivalTime_(arrivalTime), flightLength_(flightLength) {} // Default constructor is required by ROOT persistency TrackStateAtPoint() : arrivalTime_(), flightLength_() {} private: // Converting (pos,mom) to a helix depends on B field and we want // to decouple from that. Therefore we store redundant info here. HelixParams helix_; CLHEP::Hep3Vector position_; CLHEP::Hep3Vector momentum_; CLHEP::HepSymMatrix momentumCovariance_; double arrivalTime_; double flightLength_; }; //================================================================ int fitstatus() const { return fitstatus_; } int charge() const { return charge_; } int nactive() const { return nactive_; } int ndof() const { return ndof_; } double chi2() const { return chi2_; } double fitcon() const; double t0() const { return t0_; } double t0Err() const { return t0Err_; } // flight length associated with t0. double flt0() const { return flt0_; } const std::vector<TrackStateAtPoint>& states() const { return states_; } TrackSummary(int fitstatus, int charge, int nactive, int ndof, double chi2, double t0, double t0Err, double flt0) : fitstatus_(fitstatus), charge_(charge), nactive_(nactive) , ndof_(ndof), chi2_(chi2) , t0_(t0), t0Err_(t0Err), flt0_(flt0) {} void addState(const TrackStateAtPoint& st); // Default constructor is required by ROOT persistency TrackSummary() : fitstatus_(), charge_(), nactive_(), ndof_(), chi2_(), t0_(), t0Err_(), flt0_() {} private: std::vector<TrackStateAtPoint> states_; int fitstatus_; int charge_; int nactive_; int ndof_; double chi2_; double t0_; double t0Err_; double flt0_; }; //================================================================ typedef std::vector<TrackSummary> TrackSummaryCollection; std::ostream& operator<<(std::ostream& os, const TrackSummary::TrackStateAtPoint& st); std::ostream& operator<<(std::ostream& os, const TrackSummary& sum); std::ostream& operator<<(std::ostream& os, const TrackSummaryCollection& sc); } // namespace mu2e #endif /* RecoDataProducts_TrackSummary_hh */
32.457516
103
0.622634
bonventre
c11fbfd64ba4424d553bca0891eb247a02330666
35,836
cpp
C++
src/OpenSpaceToolkit/Core/Types/Integer.cpp
open-space-collective/library-core
0b031edb403e2d657d02761b07dd4b35680fcafc
[ "Apache-2.0" ]
8
2018-06-13T06:50:34.000Z
2019-07-15T03:36:50.000Z
src/OpenSpaceToolkit/Core/Types/Integer.cpp
open-space-collective/library-core
0b031edb403e2d657d02761b07dd4b35680fcafc
[ "Apache-2.0" ]
37
2018-06-12T07:42:38.000Z
2020-01-05T01:13:27.000Z
src/OpenSpaceToolkit/Core/Types/Integer.cpp
open-space-collective/library-core
0b031edb403e2d657d02761b07dd4b35680fcafc
[ "Apache-2.0" ]
2
2020-03-05T18:17:24.000Z
2020-04-07T18:18:24.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @project Open Space Toolkit ▸ Core /// @file OpenSpaceToolkit/Core/Types/Integer.cpp /// @author Lucas Brémond <lucas@loftorbital.com> /// @license Apache License 2.0 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <OpenSpaceToolkit/Core/Types/Integer.hpp> #include <OpenSpaceToolkit/Core/Error.hpp> #include <boost/lexical_cast.hpp> #include <limits> #include <iostream> //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace ostk { namespace core { namespace types { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Integer::Integer ( Integer::ValueType anInteger ) : type_(Integer::Type::Defined), value_(anInteger) { } Integer& Integer::operator = ( Integer::ValueType anInteger ) { type_ = Integer::Type::Defined ; value_ = anInteger ; return *this ; } bool Integer::operator == ( const Integer& anInteger ) const { return (type_ == Integer::Type::Defined) && (anInteger.type_ == Integer::Type::Defined) && (value_ == anInteger.value_) ; } bool Integer::operator != ( const Integer& anInteger ) const { return (type_ == Integer::Type::Defined) && (anInteger.type_ == Integer::Type::Defined) && (value_ != anInteger.value_) ; } bool Integer::operator < ( const Integer& anInteger ) const { return (type_ == Integer::Type::Defined) && (anInteger.type_ == Integer::Type::Defined) && (value_ < anInteger.value_) ; } bool Integer::operator <= ( const Integer& anInteger ) const { return (type_ == Integer::Type::Defined) && (anInteger.type_ == Integer::Type::Defined) && (value_ <= anInteger.value_) ; } bool Integer::operator > ( const Integer& anInteger ) const { return (type_ == Integer::Type::Defined) && (anInteger.type_ == Integer::Type::Defined) && (value_ > anInteger.value_) ; } bool Integer::operator >= ( const Integer& anInteger ) const { return (type_ == Integer::Type::Defined) && (anInteger.type_ == Integer::Type::Defined) && (value_ >= anInteger.value_) ; } bool Integer::operator == ( const Integer::ValueType& anInteger ) const { return (type_ == Integer::Type::Defined) && (value_ == anInteger) ; } bool Integer::operator != ( const Integer::ValueType& anInteger ) const { return (type_ == Integer::Type::Defined) && (value_ != anInteger) ; } bool Integer::operator < ( const Integer::ValueType& anInteger ) const { return (type_ == Integer::Type::Defined) && (value_ < anInteger) ; } bool Integer::operator <= ( const Integer::ValueType& anInteger ) const { return (type_ == Integer::Type::Defined) && (value_ <= anInteger) ; } bool Integer::operator > ( const Integer::ValueType& anInteger ) const { return (type_ == Integer::Type::Defined) && (value_ > anInteger) ; } bool Integer::operator >= ( const Integer::ValueType& anInteger ) const { return (type_ == Integer::Type::Defined) && (value_ >= anInteger) ; } Integer Integer::operator + ( const Integer& anInteger ) const { if ((type_ != Integer::Type::Undefined) && (anInteger.type_ != Integer::Type::Undefined)) { if ((type_ == Integer::Type::PositiveInfinity) && (anInteger.type_ == Integer::Type::PositiveInfinity)) { return Integer::PositiveInfinity() ; } else if ((type_ == Integer::Type::NegativeInfinity) && (anInteger.type_ == Integer::Type::NegativeInfinity)) { return Integer::NegativeInfinity() ; } else if ((type_ == Integer::Type::Defined) || (anInteger.type_ == Integer::Type::Defined)) { if (type_ != Integer::Type::Defined) { return *this ; } else if (anInteger.type_ != Integer::Type::Defined) { return anInteger ; } // [TBC] Use __builtin_add_overflow instead? if ((anInteger.value_ > 0) && (value_ > (std::numeric_limits<Integer::ValueType>::max() - anInteger.value_))) // Addition would overflow { return Integer::PositiveInfinity() ; } if ((anInteger.value_ < 0) && (value_ < (std::numeric_limits<Integer::ValueType>::min() - anInteger.value_))) // Addition would underflow { return Integer::NegativeInfinity() ; } return Integer(value_ + anInteger.value_) ; } } return Integer::Undefined() ; } Integer Integer::operator - ( const Integer& anInteger ) const { if ((type_ != Integer::Type::Undefined) && (anInteger.type_ != Integer::Type::Undefined)) { if ((type_ == Integer::Type::PositiveInfinity) && (anInteger.type_ == Integer::Type::NegativeInfinity)) { return Integer::PositiveInfinity() ; } else if ((type_ == Integer::Type::NegativeInfinity) && (anInteger.type_ == Integer::Type::PositiveInfinity)) { return Integer::NegativeInfinity() ; } else if ((type_ == Integer::Type::Defined) || (anInteger.type_ == Integer::Type::Defined)) { if (type_ != Integer::Type::Defined) { return *this ; } else if (anInteger.type_ != Integer::Type::Defined) { if (anInteger.type_ == Integer::Type::PositiveInfinity) { return Integer::NegativeInfinity() ; } return Integer::PositiveInfinity() ; } if ((anInteger.value_ < 0) && (value_ > (std::numeric_limits<Integer::ValueType>::max() + anInteger.value_))) // Subtraction would overflow { return Integer::PositiveInfinity() ; } if ((anInteger.value_ > 0) && (value_ < (std::numeric_limits<Integer::ValueType>::min() + anInteger.value_))) // Subtraction would underflow { return Integer::NegativeInfinity() ; } return Integer(value_ - anInteger.value_) ; } } return Integer::Undefined() ; } Integer Integer::operator * ( const Integer& anInteger ) const { if ((type_ != Integer::Type::Undefined) && (anInteger.type_ != Integer::Type::Undefined)) { if (type_ == Integer::Type::PositiveInfinity) { if (anInteger.isStrictlyPositive()) { return Integer::PositiveInfinity() ; } else if (anInteger.isStrictlyNegative()) { return Integer::NegativeInfinity() ; } return Integer::Undefined() ; } else if (type_ == Integer::Type::NegativeInfinity) { if (anInteger.isStrictlyPositive()) { return Integer::NegativeInfinity() ; } else if (anInteger.isStrictlyNegative()) { return Integer::PositiveInfinity() ; } return Integer::Undefined() ; } else if (anInteger.type_ == Integer::Type::PositiveInfinity) { if (this->isStrictlyPositive()) { return Integer::PositiveInfinity() ; } else if (this->isStrictlyNegative()) { return Integer::NegativeInfinity() ; } return Integer::Undefined() ; } else if (anInteger.type_ == Integer::Type::NegativeInfinity) { if (this->isStrictlyPositive()) { return Integer::NegativeInfinity() ; } else if (this->isStrictlyNegative()) { return Integer::PositiveInfinity() ; } return Integer::Undefined() ; } else { if (this->isZero() || anInteger.isZero()) { return Integer::Zero() ; } // Check for -1 for two's complement machines if ((value_ < 0) && (anInteger.value_ == std::numeric_limits<Integer::ValueType>::min())) // Multiplication can overflow { return Integer::PositiveInfinity() ; } if ((anInteger.value_ < 0) && (value_ == std::numeric_limits<Integer::ValueType>::min())) // Multiplication can overflow { return Integer::PositiveInfinity() ; } if ((this->getSign() == anInteger.getSign()) && (std::abs(value_) > (std::numeric_limits<Integer::ValueType>::max() / std::abs(anInteger.value_)))) // Multiplication would overflow { return Integer::PositiveInfinity() ; } if ((value_ == +1) && (anInteger.value_ == std::numeric_limits<Integer::ValueType>::min())) { return Integer(std::numeric_limits<Integer::ValueType>::min()) ; } if ((value_ == -1) && (anInteger.value_ == std::numeric_limits<Integer::ValueType>::min())) { return Integer::PositiveInfinity() ; } if ((anInteger.value_ != -1) && (this->getSign() != anInteger.getSign()) && ((-std::abs(value_)) < (std::numeric_limits<Integer::ValueType>::min() / std::abs(anInteger.value_)))) // Multiplication would underflow { return Integer::NegativeInfinity() ; } return Integer(value_ * anInteger.value_) ; } } return Integer::Undefined() ; } Integer Integer::operator / ( const Integer& anInteger ) const { if (anInteger.isZero()) { return Integer::Undefined() ; } if ((type_ != Integer::Type::Undefined) && (anInteger.type_ != Integer::Type::Undefined)) { if (type_ == Integer::Type::PositiveInfinity) { if (anInteger.isInfinity()) { return Integer::Undefined() ; } else if (anInteger.isStrictlyPositive()) { return Integer::PositiveInfinity() ; } else if (anInteger.isStrictlyNegative()) { return Integer::NegativeInfinity() ; } return Integer::Undefined() ; } else if (type_ == Integer::Type::NegativeInfinity) { if (anInteger.isInfinity()) { return Integer::Undefined() ; } else if (anInteger.isStrictlyPositive()) { return Integer::NegativeInfinity() ; } else if (anInteger.isStrictlyNegative()) { return Integer::PositiveInfinity() ; } return Integer::Undefined() ; } else { if (this->isZero() || anInteger.isInfinity()) { return Integer::Zero() ; } else { if ((value_ == std::numeric_limits<Integer::ValueType>::min()) && (anInteger.value_ == -1)) { return Integer::PositiveInfinity() ; } return Integer(value_ / anInteger.value_) ; } } } return Integer::Undefined() ; } Integer Integer::operator % ( const Integer& anInteger ) const { if (anInteger.isZero()) { return Integer::Undefined() ; } if ((type_ != Integer::Type::Undefined) && (anInteger.type_ != Integer::Type::Undefined)) { if (this->isZero()) { return Integer::Zero() ; } else if (!this->isInfinity() && anInteger.isInfinity()) { return *this ; } else if ((!this->isInfinity()) && this->isStrictlyPositive() && (!anInteger.isInfinity()) && (anInteger.value_ == std::numeric_limits<Integer::ValueType>::min())) { return *this ; } else if ((!anInteger.isInfinity()) && (std::abs(anInteger.value_) == 1)) { return Integer::Zero() ; } else if (this->isInfinity()) { return Integer::Undefined() ; } else { return Integer(value_ % anInteger.value_) ; } } return Integer::Undefined() ; } Integer Integer::operator + ( const Integer::ValueType& anInteger ) const { return (*this) + Integer(anInteger) ; } Integer Integer::operator - ( const Integer::ValueType& anInteger ) const { return (*this) - Integer(anInteger) ; } Integer Integer::operator * ( const Integer::ValueType& anInteger ) const { return (*this) * Integer(anInteger) ; } Integer Integer::operator / ( const Integer::ValueType& anInteger ) const { return (*this) / Integer(anInteger) ; } Integer Integer::operator % ( const Integer::ValueType& anInteger ) const { return (*this) % Integer(anInteger) ; } Integer& Integer::operator += ( const Integer& anInteger ) { (*this) = (*this) + anInteger ; return *this ; } Integer& Integer::operator -= ( const Integer& anInteger ) { (*this) = (*this) - anInteger ; return *this ; } Integer& Integer::operator *= ( const Integer& anInteger ) { (*this) = (*this) * anInteger ; return *this ; } Integer& Integer::operator /= ( const Integer& anInteger ) { (*this) = (*this) / anInteger ; return *this ; } Integer& Integer::operator %= ( const Integer& anInteger ) { (*this) = (*this) % anInteger ; return *this ; } Integer& Integer::operator += ( const Integer::ValueType& anInteger ) { (*this) = (*this) + Integer(anInteger) ; return *this ; } Integer& Integer::operator -= ( const Integer::ValueType& anInteger ) { (*this) = (*this) - Integer(anInteger) ; return *this ; } Integer& Integer::operator *= ( const Integer::ValueType& anInteger ) { (*this) = (*this) * Integer(anInteger) ; return *this ; } Integer& Integer::operator /= ( const Integer::ValueType& anInteger ) { (*this) = (*this) / Integer(anInteger) ; return *this ; } Integer& Integer::operator %= ( const Integer::ValueType& anInteger ) { (*this) = (*this) % Integer(anInteger) ; return *this ; } Integer operator + ( const Integer::ValueType& anInt, const Integer& anInteger ) { return Integer(anInt) + anInteger ; } Integer operator - ( const Integer::ValueType& anInt, const Integer& anInteger ) { return Integer(anInt) - anInteger ; } Integer operator * ( const Integer::ValueType& anInt, const Integer& anInteger ) { return Integer(anInt) * anInteger ; } Integer operator / ( const Integer::ValueType& anInt, const Integer& anInteger ) { return Integer(anInt) / anInteger ; } Integer operator % ( const Integer::ValueType& anInt, const Integer& anInteger ) { return Integer(anInt) % anInteger ; } Integer Integer::operator + ( ) const { return *this ; } Integer Integer::operator - ( ) const { switch (type_) { case Integer::Type::Defined: { if (value_ == std::numeric_limits<Integer::ValueType>::min()) { return Integer::PositiveInfinity() ; } return Integer(-value_) ; } case Integer::Type::Undefined: return Integer::Undefined() ; case Integer::Type::PositiveInfinity: return Integer::NegativeInfinity() ; case Integer::Type::NegativeInfinity: return Integer::PositiveInfinity() ; default: break ; } return Integer::Undefined() ; } Integer& Integer::operator ++ ( ) { switch (type_) { case Integer::Type::Defined: { if (value_ == std::numeric_limits<Integer::ValueType>::max()) { type_ = Integer::Type::PositiveInfinity ; } else { ++value_ ; } break ; } case Integer::Type::Undefined: case Integer::Type::PositiveInfinity: case Integer::Type::NegativeInfinity: default: break ; } return *this ; } Integer& Integer::operator -- ( ) { switch (type_) { case Integer::Type::Defined: { if (value_ == std::numeric_limits<Integer::ValueType>::min()) { type_ = Integer::Type::NegativeInfinity ; } else { --value_ ; } break ; } case Integer::Type::Undefined: case Integer::Type::PositiveInfinity: case Integer::Type::NegativeInfinity: default: break ; } return *this ; } Integer Integer::operator ++ ( int anInteger ) { (void) anInteger ; Integer integerCopy(*this) ; switch (type_) { case Integer::Type::Defined: { if (value_ == std::numeric_limits<Integer::ValueType>::max()) { type_ = Integer::Type::PositiveInfinity ; } else { value_++ ; } break ; } case Integer::Type::Undefined: case Integer::Type::PositiveInfinity: case Integer::Type::NegativeInfinity: default: break ; } return integerCopy ; } Integer Integer::operator -- ( int anInteger ) { (void) anInteger ; Integer integerCopy(*this) ; switch (type_) { case Integer::Type::Defined: { if (value_ == std::numeric_limits<Integer::ValueType>::min()) { type_ = Integer::Type::NegativeInfinity ; } else { value_-- ; } break ; } case Integer::Type::Undefined: case Integer::Type::PositiveInfinity: case Integer::Type::NegativeInfinity: default: break ; } return integerCopy ; } Integer::operator Integer::ValueType ( ) const { if (type_ != Integer::Type::Defined) { throw ostk::core::error::runtime::Undefined("Integer") ; } return value_ ; } std::ostream& operator << ( std::ostream& anOutputStream, const Integer& anInteger ) { (void) anInteger ; switch (anInteger.type_) { case Integer::Type::Undefined: anOutputStream << "Undefined" ; break ; case Integer::Type::Defined: anOutputStream << anInteger.value_ ; break ; case Integer::Type::PositiveInfinity: anOutputStream << "+Inf" ; break ; case Integer::Type::NegativeInfinity: anOutputStream << "-Inf" ; break ; } // ostk::core::utilities::Output::Header(anOutputStream, "Integer") ; // ostk::core::utilities::Output::Line(anOutputStream) << "Type:" << anInteger.type_ ; // ostk::core::utilities::Output::Line(anOutputStream) << "Value:" << anInteger.value_ ; // ostk::core::utilities::Output::Footer(anOutputStream) ; return anOutputStream ; } bool Integer::isDefined ( ) const { return type_ != Integer::Type::Undefined ; } bool Integer::isZero ( ) const { return (type_ == Integer::Type::Defined) && (value_ == 0) ; } bool Integer::isPositive ( ) const { return ((type_ == Integer::Type::Defined) && (value_ >= 0)) || this->isPositiveInfinity() ; } bool Integer::isNegative ( ) const { return ((type_ == Integer::Type::Defined) && (value_ <= 0)) || this->isNegativeInfinity() ; } bool Integer::isStrictlyPositive ( ) const { return ((type_ == Integer::Type::Defined) && (value_ > 0)) || this->isPositiveInfinity() ; } bool Integer::isStrictlyNegative ( ) const { return ((type_ == Integer::Type::Defined) && (value_ < 0)) || this->isNegativeInfinity() ; } bool Integer::isInfinity ( ) const { return this->isPositiveInfinity() || this->isNegativeInfinity() ; } bool Integer::isPositiveInfinity ( ) const { return type_ == Integer::Type::PositiveInfinity ; } bool Integer::isNegativeInfinity ( ) const { return type_ == Integer::Type::NegativeInfinity ; } bool Integer::isFinite ( ) const { return type_ == Integer::Type::Defined ; } bool Integer::isEven ( ) const { return this->isFinite() && (value_ % 2 == 0) ; } bool Integer::isOdd ( ) const { return this->isFinite() && (value_ % 2 != 0) ; } types::Sign Integer::getSign ( ) const { switch (type_) { case Integer::Type::Undefined: return types::Sign::Undefined ; case Integer::Type::Defined: { if (value_ > 0) { return types::Sign::Positive ; } else if (value_ < 0) { return types::Sign::Negative ; } return types::Sign::None ; } case Integer::Type::PositiveInfinity: return types::Sign::Positive ; case Integer::Type::NegativeInfinity: return types::Sign::Negative ; default: return types::Sign::Undefined ; } return types::Sign::Undefined ; } types::String Integer::toString ( ) const { switch (type_) { case Integer::Type::Undefined: return "Undefined" ; case Integer::Type::Defined: return boost::lexical_cast<std::string>(value_) ; case Integer::Type::PositiveInfinity: return "+Inf" ; case Integer::Type::NegativeInfinity: return "-Inf" ; } return types::String::Empty() ; } Integer Integer::Undefined ( ) { return Integer(Integer::Type::Undefined, 0) ; } Integer Integer::Zero ( ) { return Integer(Integer::Type::Defined, 0) ; } Integer Integer::PositiveInfinity ( ) { return Integer(Integer::Type::PositiveInfinity, std::numeric_limits<Integer::ValueType>::max()) ; } Integer Integer::NegativeInfinity ( ) { return Integer(Integer::Type::NegativeInfinity, std::numeric_limits<Integer::ValueType>::min()) ; } Integer Integer::Int8 ( types::Int8 anInteger ) { return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anInteger)) ; } Integer Integer::Int16 ( types::Int16 anInteger ) { return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anInteger)) ; } Integer Integer::Int32 ( types::Int32 anInteger ) { return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anInteger)) ; } Integer Integer::Int64 ( types::Int64 anInteger ) { if ((anInteger < static_cast<types::Int64>(std::numeric_limits<Integer::ValueType>::min())) || (anInteger > static_cast<types::Int64>(std::numeric_limits<Integer::ValueType>::max()))) { throw ostk::core::error::RuntimeError("Int64 value [" + boost::lexical_cast<std::string>(anInteger) + "] is out of Integer supported range [" + boost::lexical_cast<std::string>(std::numeric_limits<Integer::ValueType>::min()) + ", " + boost::lexical_cast<std::string>(std::numeric_limits<Integer::ValueType>::max()) + "].") ; } return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anInteger)) ; } Integer Integer::Uint8 ( types::Uint8 anInteger ) { return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anInteger)) ; } Integer Integer::Uint16 ( types::Uint16 anInteger ) { return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anInteger)) ; } Integer Integer::Uint32 ( types::Uint32 anInteger ) { if (anInteger > static_cast<types::Uint32>(std::numeric_limits<Integer::ValueType>::max())) { throw ostk::core::error::RuntimeError("Uint32 value [" + boost::lexical_cast<std::string>(anInteger) + "] is out of Integer supported range [" + boost::lexical_cast<std::string>(std::numeric_limits<Integer::ValueType>::min()) + ", " + boost::lexical_cast<std::string>(std::numeric_limits<Integer::ValueType>::max()) + "].") ; } return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anInteger)) ; } Integer Integer::Uint64 ( types::Uint64 anInteger ) { if (anInteger > static_cast<types::Uint64>(std::numeric_limits<Integer::ValueType>::max())) { throw ostk::core::error::RuntimeError("Uint64 value [" + boost::lexical_cast<std::string>(anInteger) + "] is out of Integer supported range [" + boost::lexical_cast<std::string>(std::numeric_limits<Integer::ValueType>::min()) + ", " + boost::lexical_cast<std::string>(std::numeric_limits<Integer::ValueType>::max()) + "].") ; } return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anInteger)) ; } Integer Integer::Index ( const types::Index& anIndex ) { if (!(anIndex < std::numeric_limits<Integer::ValueType>::max())) { throw ostk::core::error::RuntimeError("Index out of bounds.") ; } return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anIndex)) ; } Integer Integer::Size ( const types::Size& aSize ) { if (!(aSize < std::numeric_limits<Integer::ValueType>::max())) { throw ostk::core::error::RuntimeError("Size out of bounds.") ; } return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(aSize)) ; } bool Integer::CanParse ( char aCharacter ) { return std::isdigit(aCharacter) ; } bool Integer::CanParse ( const types::String& aString ) { if (aString.isEmpty()) { return false ; } if ((aString == "Undefined") || (aString == "Inf") || (aString == "+Inf") || (aString == "-Inf")) { return true ; } Integer::ValueType integer ; return boost::conversion::try_lexical_convert<Integer::ValueType>(aString, integer) ; } Integer Integer::Parse ( char aCharacter ) { try { return Integer(boost::lexical_cast<Integer::ValueType>(aCharacter)) ; } catch (const boost::bad_lexical_cast&) { throw ostk::core::error::RuntimeError("Cannot cast character [" + String::Char(aCharacter) + "] to Integer.") ; } return Integer::Undefined() ; } Integer Integer::Parse ( const types::String& aString ) { if (aString.isEmpty()) { throw ostk::core::error::runtime::Undefined("String") ; } if (aString == "Undefined") { return Integer::Undefined() ; } if ((aString == "Inf") || (aString == "+Inf")) { return Integer::PositiveInfinity() ; } if (aString == "-Inf") { return Integer::NegativeInfinity() ; } try { return Integer(boost::lexical_cast<Integer::ValueType>(aString)) ; } catch (const boost::bad_lexical_cast&) { throw ostk::core::error::RuntimeError("Cannot cast string [" + aString + "] to Integer.") ; } return Integer::Undefined() ; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Integer::Integer ( const Integer::Type& aType, const Integer::ValueType& anInteger ) : type_(aType), value_(anInteger) { } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
31.352581
333
0.426024
open-space-collective
c12012ee4cad24b03a03b597d150b1a9011f1fa5
4,156
hpp
C++
main/app_camera.hpp
andriyadi/esp32-custom-vision
ebc3f781fd85bf063d96ae89bb56bfa263fa6af5
[ "Apache-2.0" ]
44
2019-02-11T04:53:38.000Z
2021-10-04T12:00:38.000Z
main/app_camera.hpp
andriyadi/esp32-custom-vision
ebc3f781fd85bf063d96ae89bb56bfa263fa6af5
[ "Apache-2.0" ]
2
2019-06-20T18:03:10.000Z
2021-01-07T09:18:38.000Z
main/app_camera.hpp
andriyadi/esp32-custom-vision
ebc3f781fd85bf063d96ae89bb56bfa263fa6af5
[ "Apache-2.0" ]
12
2019-02-12T06:27:11.000Z
2021-02-16T22:46:45.000Z
/* * app_camera.hpp * * Created on: Feb 8, 2019 * Author: andri */ #ifndef MAIN_APP_CAMERA_HPP_ #define MAIN_APP_CAMERA_HPP_ #include "esp_err.h" #include "esp_camera.h" #include "sdkconfig.h" /** * PIXFORMAT_RGB565, // 2BPP/RGB565 * PIXFORMAT_YUV422, // 2BPP/YUV422 * PIXFORMAT_GRAYSCALE, // 1BPP/GRAYSCALE * PIXFORMAT_JPEG, // JPEG/COMPRESSED * PIXFORMAT_RGB888, // 3BPP/RGB888 */ #define CAMERA_PIXEL_FORMAT PIXFORMAT_JPEG /* * FRAMESIZE_QQVGA, // 160x120 * FRAMESIZE_QQVGA2, // 128x160 * FRAMESIZE_QCIF, // 176x144 * FRAMESIZE_HQVGA, // 240x176 * FRAMESIZE_QVGA, // 320x240 * FRAMESIZE_CIF, // 400x296 * FRAMESIZE_VGA, // 640x480 * FRAMESIZE_SVGA, // 800x600 * FRAMESIZE_XGA, // 1024x768 * FRAMESIZE_SXGA, // 1280x1024 * FRAMESIZE_UXGA, // 1600x1200 */ #define CAMERA_FRAME_SIZE FRAMESIZE_QVGA #if CONFIG_CAMERA_BOARD_WROVER //WROVER-KIT PIN Map #define PWDN_GPIO_NUM -1 #define RESET_GPIO_NUM -1 #define XCLK_GPIO_NUM 21 #define SIOD_GPIO_NUM 26 #define SIOC_GPIO_NUM 27 #define Y9_GPIO_NUM 35 #define Y8_GPIO_NUM 34 #define Y7_GPIO_NUM 39 #define Y6_GPIO_NUM 36 #define Y5_GPIO_NUM 19 #define Y4_GPIO_NUM 18 #define Y3_GPIO_NUM 5 #define Y2_GPIO_NUM 4 #define VSYNC_GPIO_NUM 25 #define HREF_GPIO_NUM 23 #define PCLK_GPIO_NUM 22 //Specific #define USER_BUTTON_1_PIN_NUM 34 #define XCLK_FREQ 20000000 #elif CONFIG_CAMERA_BOARD_EYE //ESP-EYE Pin Map #define PWDN_GPIO_NUM -1 #define RESET_GPIO_NUM -1 #define XCLK_GPIO_NUM 4 #define SIOD_GPIO_NUM 18 #define SIOC_GPIO_NUM 23 #define Y9_GPIO_NUM 36 #define Y8_GPIO_NUM 37 #define Y7_GPIO_NUM 38 #define Y6_GPIO_NUM 39 #define Y5_GPIO_NUM 35 #define Y4_GPIO_NUM 14 #define Y3_GPIO_NUM 13 #define Y2_GPIO_NUM 34 #define VSYNC_GPIO_NUM 5 #define HREF_GPIO_NUM 27 #define PCLK_GPIO_NUM 25 #define XCLK_FREQ 20000000 #else //CAMERA_BOARD_TTGO_TCAM //TTGO_T-CAM #define PWDN_GPIO_NUM 26 #define RESET_GPIO_NUM -1 #define XCLK_GPIO_NUM 32 #define SIOD_GPIO_NUM 13 #define SIOC_GPIO_NUM 12 #define Y9_GPIO_NUM 39 #define Y8_GPIO_NUM 36 #define Y7_GPIO_NUM 23 #define Y6_GPIO_NUM 18 #define Y5_GPIO_NUM 15 #define Y4_GPIO_NUM 4 #define Y3_GPIO_NUM 14 #define Y2_GPIO_NUM 5 #define VSYNC_GPIO_NUM 27 #define HREF_GPIO_NUM 25 #define PCLK_GPIO_NUM 19 //Specific #define AS312_PIN_NUM 33 #define USER_BUTTON_1_PIN_NUM 34 #define I2C_SDA_PIN_NUM 21 #define I2C_SCL_PIN_NUM 22 #define XCLK_FREQ 20000000 #endif esp_err_t camera_init() { gpio_config_t conf; conf.mode = GPIO_MODE_INPUT; conf.pull_up_en = GPIO_PULLUP_ENABLE; conf.pull_down_en = GPIO_PULLDOWN_DISABLE; conf.intr_type = GPIO_INTR_DISABLE; conf.pin_bit_mask = 1LL << 13; gpio_config(&conf); conf.pin_bit_mask = 1LL << 14; gpio_config(&conf); camera_config_t config; config.ledc_channel = LEDC_CHANNEL_0; config.ledc_timer = LEDC_TIMER_0; config.pin_d0 = Y2_GPIO_NUM; config.pin_d1 = Y3_GPIO_NUM; config.pin_d2 = Y4_GPIO_NUM; config.pin_d3 = Y5_GPIO_NUM; config.pin_d4 = Y6_GPIO_NUM; config.pin_d5 = Y7_GPIO_NUM; config.pin_d6 = Y8_GPIO_NUM; config.pin_d7 = Y9_GPIO_NUM; config.pin_xclk = XCLK_GPIO_NUM; config.pin_pclk = PCLK_GPIO_NUM; config.pin_vsync = VSYNC_GPIO_NUM; config.pin_href = HREF_GPIO_NUM; config.pin_sscb_sda = SIOD_GPIO_NUM; config.pin_sscb_scl = SIOC_GPIO_NUM; config.pin_pwdn = PWDN_GPIO_NUM; config.pin_reset = RESET_GPIO_NUM; config.xclk_freq_hz = XCLK_FREQ; config.pixel_format = CAMERA_PIXEL_FORMAT; //init with high specs to pre-allocate larger buffers config.frame_size = FRAMESIZE_UXGA; config.jpeg_quality = 10; config.fb_count = 2; esp_err_t res = esp_camera_init(&config); if (res == ESP_OK) { //drop down frame size for higher initial frame rate sensor_t * s = esp_camera_sensor_get(); s->set_framesize(s, CAMERA_FRAME_SIZE); #if CONFIG_CAMERA_BOARD_TTGO_TCAM s->set_vflip(s, 1); #endif } return res; } #endif /* MAIN_APP_CAMERA_HPP_ */
24.304094
54
0.723532
andriyadi
c123bb7da49d4cbe99b07c6fb257ee58d97cd5b2
308
cc
C++
src/test/hello.cc
smikes/inchi
7a980f01b2c3eef3b5cf4f2502d814724366d385
[ "MIT" ]
7
2015-01-21T04:48:06.000Z
2021-05-26T09:10:58.000Z
src/test/hello.cc
smikes/inchi
7a980f01b2c3eef3b5cf4f2502d814724366d385
[ "MIT" ]
1
2018-02-20T19:47:40.000Z
2018-02-20T19:47:40.000Z
src/test/hello.cc
smikes/inchi
7a980f01b2c3eef3b5cf4f2502d814724366d385
[ "MIT" ]
1
2015-06-25T15:09:14.000Z
2015-06-25T15:09:14.000Z
#include "CppUnitLite/TestHarness.h" #include <string> static inline SimpleString StringFrom(const std::string& value) { return SimpleString(value.c_str()); } TEST( Hello, world ) { std::string s1("Hello"), s2("Hello"), s3("world"); CHECK_EQUAL(s1, s2); CHECK_EQUAL(s2, s1); CHECK(s1 != s3); }
16.210526
63
0.672078
smikes
c12483522d334171d00dd497d723554af35243af
4,122
hpp
C++
include/System/Net/Http/Headers/HttpHeaders_HeaderBucket.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/Net/Http/Headers/HttpHeaders_HeaderBucket.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/Net/Http/Headers/HttpHeaders_HeaderBucket.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Net.Http.Headers.HttpHeaders #include "System/Net/Http/Headers/HttpHeaders.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: List`1<T> template<typename T> class List_1; } // Forward declaring namespace: System namespace System { // Forward declaring type: Func`2<T, TResult> template<typename T, typename TResult> class Func_2; } // Completed forward declares // Type namespace: System.Net.Http.Headers namespace System::Net::Http::Headers { // Size: 0x28 #pragma pack(push, 1) // Autogenerated type: System.Net.Http.Headers.HttpHeaders/HeaderBucket class HttpHeaders::HeaderBucket : public ::Il2CppObject { public: // public System.Object Parsed // Size: 0x8 // Offset: 0x10 ::Il2CppObject* Parsed; // Field size check static_assert(sizeof(::Il2CppObject*) == 0x8); // private System.Collections.Generic.List`1<System.String> values // Size: 0x8 // Offset: 0x18 System::Collections::Generic::List_1<::Il2CppString*>* values; // Field size check static_assert(sizeof(System::Collections::Generic::List_1<::Il2CppString*>*) == 0x8); // public readonly System.Func`2<System.Object,System.String> CustomToString // Size: 0x8 // Offset: 0x20 System::Func_2<::Il2CppObject*, ::Il2CppString*>* CustomToString; // Field size check static_assert(sizeof(System::Func_2<::Il2CppObject*, ::Il2CppString*>*) == 0x8); // Creating value type constructor for type: HeaderBucket HeaderBucket(::Il2CppObject* Parsed_ = {}, System::Collections::Generic::List_1<::Il2CppString*>* values_ = {}, System::Func_2<::Il2CppObject*, ::Il2CppString*>* CustomToString_ = {}) noexcept : Parsed{Parsed_}, values{values_}, CustomToString{CustomToString_} {} // public System.Void .ctor(System.Object parsed, System.Func`2<System.Object,System.String> converter) // Offset: 0x157A55C template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static HttpHeaders::HeaderBucket* New_ctor(::Il2CppObject* parsed, System::Func_2<::Il2CppObject*, ::Il2CppString*>* converter) { static auto ___internal__logger = ::Logger::get().WithContext("System::Net::Http::Headers::HttpHeaders::HeaderBucket::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<HttpHeaders::HeaderBucket*, creationType>(parsed, converter))); } // public System.Boolean get_HasStringValues() // Offset: 0x157B15C bool get_HasStringValues(); // public System.Collections.Generic.List`1<System.String> get_Values() // Offset: 0x157A598 System::Collections::Generic::List_1<::Il2CppString*>* get_Values(); // public System.Void set_Values(System.Collections.Generic.List`1<System.String> value) // Offset: 0x157B64C void set_Values(System::Collections::Generic::List_1<::Il2CppString*>* value); // public System.String ParsedToString() // Offset: 0x157B0D8 ::Il2CppString* ParsedToString(); }; // System.Net.Http.Headers.HttpHeaders/HeaderBucket #pragma pack(pop) static check_size<sizeof(HttpHeaders::HeaderBucket), 32 + sizeof(System::Func_2<::Il2CppObject*, ::Il2CppString*>*)> __System_Net_Http_Headers_HttpHeaders_HeaderBucketSizeCheck; static_assert(sizeof(HttpHeaders::HeaderBucket) == 0x28); } DEFINE_IL2CPP_ARG_TYPE(System::Net::Http::Headers::HttpHeaders::HeaderBucket*, "System.Net.Http.Headers", "HttpHeaders/HeaderBucket");
51.525
268
0.707181
darknight1050
c124f212c4768797eb097d7364540532d6fbb8bf
2,095
cpp
C++
030-third_party/src/PlatisSolutionsBenchmarker.cpp
platisd/refactoring-for-testablity-cpp
126ee079c73c169bae8a31a2f2ccdc873e819cca
[ "MIT" ]
33
2020-04-18T22:43:57.000Z
2022-02-01T23:48:34.000Z
030-third_party/src/PlatisSolutionsBenchmarker.cpp
platisd/refactoring-for-testablity-cpp
126ee079c73c169bae8a31a2f2ccdc873e819cca
[ "MIT" ]
null
null
null
030-third_party/src/PlatisSolutionsBenchmarker.cpp
platisd/refactoring-for-testablity-cpp
126ee079c73c169bae8a31a2f2ccdc873e819cca
[ "MIT" ]
7
2020-04-23T00:39:09.000Z
2021-11-10T15:05:33.000Z
#include "PlatisSolutionsBenchmarker.hpp" #include <chrono> #include <curl/curl.h> // You probably want to remove this after refactoring #include <string> namespace { const auto kUrl = "https://platis.solutions/assets/images/smartcar_featured.jpg"; const auto kFilePath = "/dev/null"; } // namespace namespace before { std::optional<std::chrono::milliseconds> PlatisSolutionsBenchmarker::getResponseTime() const { const auto start = std::chrono::system_clock::now(); auto downloadSuccessful = false; if (auto curl = curl_easy_init()) { auto fp = fopen(kFilePath, "wb"); curl_easy_setopt(curl, CURLOPT_URL, kUrl); curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); downloadSuccessful = curl_easy_perform(curl) == CURLE_OK; fclose(fp); curl_easy_cleanup(curl); } const auto end = std::chrono::system_clock::now(); if (downloadSuccessful) { const auto elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(end - start); return std::make_optional(elapsedTime); } return std::nullopt; } } // namespace before namespace after { PlatisSolutionsBenchmarker::PlatisSolutionsBenchmarker(Downloader& downloader) : mDownloader{downloader} { } std::optional<std::chrono::milliseconds> PlatisSolutionsBenchmarker::getResponseTime() const { const auto start = std::chrono::system_clock::now(); const auto downloadSuccessful = mDownloader.download(kUrl, kFilePath); const auto end = std::chrono::system_clock::now(); if (downloadSuccessful) { const auto elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(end - start); return std::make_optional(elapsedTime); } return std::nullopt; } } // namespace after
29.097222
78
0.6358
platisd
c1250230f3a33c676940b4fbbe97fdc9b0d3729c
1,400
cpp
C++
code/data-structures/avl_tree.test.cpp
guru-raj/CompetitiveProgramming
5b326ad153f52d46a84f3d670f035af59a3ec016
[ "MIT" ]
549
2015-02-13T00:46:04.000Z
2022-03-10T07:35:32.000Z
code/data-structures/avl_tree.test.cpp
guru-raj/CompetitiveProgramming
5b326ad153f52d46a84f3d670f035af59a3ec016
[ "MIT" ]
6
2016-12-02T10:51:31.000Z
2022-02-22T16:47:42.000Z
code/data-structures/avl_tree.test.cpp
guru-raj/CompetitiveProgramming
5b326ad153f52d46a84f3d670f035af59a3ec016
[ "MIT" ]
143
2015-06-14T17:59:20.000Z
2022-01-07T19:47:49.000Z
void test() { /* Field testing: UVa 978, UVa 1513, UVa 12049, Kattis turbo */ int cnt = 10000, range = 1000; avl_tree<int> t1; set<int> t2; assert_equal(0, t1.size()); for (int i = 0; i < cnt; i++) { int n = rand() % range; avl_tree<int>::node *p = t1.insert(n); assert_equal(n, p->item); t2.insert(n); assert_equal((int)size(t2), (int)size(t1)); int n1 = rand() % range; avl_tree<int>::node *b = t1.find(n1); if (b) assert_equal(n1, b->item); assert_equal(b == NULL, t2.find(n1) == t2.end()); int n2 = rand() % range; t1.erase(n2); t2.erase(n2); assert_equal((int)size(t2), (int)size(t1)); } t1.clear(); t2.clear(); assert_equal(0, t1.size()); for (int i = 0; i < cnt; i++) { int n = rand() % range; avl_tree<int>::node *p = t1.insert(n); assert_equal(n, p->item); t2.insert(n); assert_equal((int)size(t2), (int)size(t1)); int n1 = rand() % range; avl_tree<int>::node *b = t1.find(n1); if (b) assert_equal(n1, b->item); assert_equal(b == NULL, t2.find(n1) == t2.end()); int n2 = rand() % range; t1.erase(n2); t2.erase(n2); assert_equal((int)size(t2), (int)size(t1)); } for (int i = 0; i < range; i++) { t1.erase(i); t2.erase(i); assert_equal((int)size(t2), (int)size(t1)); } assert_equal(0, t1.size()); } // vim: cc=60 ts=2 sts=2 sw=2:
22.580645
65
0.544286
guru-raj
c125f43b11f6c55d13dd21d99ce11d0a61d0003b
187,622
cpp
C++
wxWidgets/UserInterface/MainFrame.cpp
st-gb/CPUinfoAndControl
5e93d4a195b4692d147bb05cfef534e38d7f8b64
[ "MIT" ]
null
null
null
wxWidgets/UserInterface/MainFrame.cpp
st-gb/CPUinfoAndControl
5e93d4a195b4692d147bb05cfef534e38d7f8b64
[ "MIT" ]
null
null
null
wxWidgets/UserInterface/MainFrame.cpp
st-gb/CPUinfoAndControl
5e93d4a195b4692d147bb05cfef534e38d7f8b64
[ "MIT" ]
1
2021-07-16T21:01:26.000Z
2021-07-16T21:01:26.000Z
/* Do not remove this header/ copyright information. * * Copyright © Trilobyte Software Engineering GmbH, Berlin, Germany 2010-2011. * You are allowed to modify and use the source code from * Trilobyte Software Engineering GmbH, Berlin, Germany for free if you are not * making profit with it or its adaption. Else you may contact Trilobyte SE. */ //"For compilers that support precompilation, includes "wx/wx.h"." #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif // for all others, include the necessary headers (this file is usually all you // need because it includes almost all "standard" wxWidgets headers) #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "MainFrame.hpp" //wxWidgets include files #include <wx/defs.h> //for wxBG_STYLE_CUSTOM #include <wx/dcbuffer.h> //for class wxBufferedPaintDC #include <wx/dynlib.h> //wxDynamicLibrary::GetDllExt() #include <wx/filename.h> //wxFileName::GetPathSeparator(...) #include "wx/frame.h" //for base class wxFrame //#include <wx/icon.h> //for class wxIcon #include <wx/menu.h> //for class wxMenu, class wxMenuBar #include <wx/menuitem.h> //class wxMenuItem #include <wx/numdlg.h> //for ::wxGetNumberFromUser(...) #include <wx/stattext.h> //for wxStaticText #include <wx/string.h> //for wxString::Format(...) #include <wx/timer.h> //for EVT_TIMER (,...?) //#include <wx/tooltip.h> //for wxToolTip::SetDelay(...) #include <wx/wx.h> //for wxMessageBox(...) (,etc.) //#include "wx/window.h" //#include <wx/menubar.h> //#include "../Controller/RunAsService.h" //for MyServiceStart etc. #include "FreqAndVoltageSettingDlg.hpp" //SUPPRESS_UNUSED_VARIABLE_WARNING(...) #include <compiler/GCC/suppress_unused_variable.h> #include <Controller/CalculationThreadProc.h> //for GetInterpolatedVoltageFromFreq( // WORD wFreqInMHzToGetVoltageFrom // , float & r_fVoltageInVolt // , const std::set<VoltageAndFreq> & r_stdsetvoltageandfreq // ); #include <Controller/CPU-related/GetInterpolatedVoltageFromFreq.hpp> //::wxGetApp().mp_cpucoreusagegetter #include <Controller/CPU-related/ICPUcoreUsageGetter.hpp> #include <Controller/CPU-related/I_CPUcontroller.hpp> ////GetFilenameWithoutExtension(const std::string &) //#include <Controller/FileSystem/GetFilenameWithoutExtension/\_ //GetFilenameWithoutExtension.hpp> ////for ::GetErrorMessageFromLastErrorCodeA(...) //#include <Controller/GetErrorMessageFromLastErrorCode.hpp> #include <Controller/IDynFreqScalingAccess.hpp> #include <Controller/I_CPUaccess.hpp> //class I_CPUaccess //WriteFileContent(...) #include <InputOutput/WriteFileContent/WriteFileContent.hpp> //for member m_stdmapwmenuid2i_cpucontrolleraction #include <Controller/I_CPUcontrollerAction.hpp>//class I_CPUcontrollerAction #include <Controller/IPC/I_IPC.hpp> //enum IPCcontrolCodes #include <Controller/character_string/stdtstr.hpp> //Getstdtstring(...) //DISable g++ "deprecated conversion from string constant to 'char*'" warning, //from //http://stackoverflow.com/questions/59670/how-to-get-rid-of-deprecated-conversion-from-string-constant-to-char-warning // : "I believe passing -Wno-write-strings to gcc will suppress this warning." #pragma GCC diagnostic ignored "-Wwrite-strings" #include <x86IandC.xpm> //ENable g++ "deprecated conversion from string constant to 'char*'" warning #pragma GCC diagnostic warning "-Wwrite-strings" #include <ModelData/ModelData.hpp> //class CPUcoreData #include <ModelData/PerCPUcoreAttributes.hpp> //class PerCPUcoreAttributes #include <ModelData/RegisterData.hpp> //#include <ModelData/HighLoadThreadAttributes.hpp> #include <ModelData/SpecificCPUcoreActionAttributes.hpp> #include <preprocessor_macros/logging_preprocessor_macros.h> //LOGN(...) //Pre-defined preprocessor macro under MSVC, MinGW for 32 and 64 bit Windows. #ifdef _WIN32 //Built-in macro for MSVC, MinGW (also for 64 bit Windows) //#include <Windows/CalculationThread.hpp> #include <OperatingSystem/Windows/DLLloadError.hpp> #include <OperatingSystem/Windows/ErrorCode/ErrorCodeFromGetLastErrorToString.h> #include <OperatingSystem/Windows/ErrorCode/LocalLanguageMessageFromErrorCode.h> #include <OperatingSystem/Windows/Service/ServiceBase.hpp> #endif #include <wxWidgets/App.hpp> //for wxGetApp() / DECLARE_APP #include <wxWidgets/Controller/wxDynLibCPUcontroller.hpp> #include <wxWidgets/Controller/wxDynLibCPUcoreUsageGetter.hpp> //#include <wxWidgets/wxStringHelper.h> //getwxString(const std::string &) / getwxString(const std::wstring &) #include <wxWidgets/Controller/character_string/wxStringHelper.hpp> //class NonBlocking::wxServiceSocketClient #include <wxWidgets/Controller/non-blocking_socket/client/\ wxServiceSocketClient.hpp> #include <wxWidgets/DynFreqScalingThread.hpp> #include <wxWidgets/icon/CreateTextIcon.hpp> //CreateTextIcon(...) #include <wxWidgets/ModelData/wxCPUcoreID.hpp> //#ifdef COMPILE_WITH_SYSTEM_TRAY_ICON #include <wxWidgets/UserInterface/TaskBarIcon.hpp>//class TaskBarIcon //#endif #include <wxWidgets/UserInterface/AboutDialog.hpp> //class AboutDialog #include <wxWidgets/UserInterface/DynFreqScalingDlg.hpp> #include <Xerces/XMLAccess.hpp> #include "wxExamineCPUregistersDialog.hpp" #ifdef COMPILE_WITH_MSR_EXAMINATION #include "CPUregisterReadAndWriteDialog.hpp" #endif //COMPILE_WITH_MSR_EXAMINATION //#include <limits.h> #ifndef MAXWORD #define MAXWORD 65535 #endif //#ifndef MAXWORD #include <map> //std::map #include <set> //std::set #include <valarray> //class std::valarray //#include <xercesc/framework/MemBufInputSource.hpp> #include <hardware/CPU/fastest_data_type.h> //typedef #ifdef USE_WINDOWS_API_DIRECTLY_FOR_SYSTEM_TRAY_ICON #include "SystemTrayAccess.hpp" #endif //#ifdef USE_WINDOWS_API_DIRECTLY_FOR_SYSTEM_TRAY_ICON #ifdef _MSC_VER #define __FLT_MIN__ FLT_MIN #endif class wxObject ; extern CPUcontrolBase * gp_cpucontrolbase ; //Static class variables must (also) be declared/ defined in the source file. float * MainFrame::s_arfTemperatureInDegreesCelsius = NULL ; wxIcon MainFrame::s_wxiconTemperature ; wxIcon MainFrame::s_wxiconCPUcoreUsages; wxIcon MainFrame::s_wxiconCPUcoresMultipliers; wxString MainFrame::s_wxstrHighestCPUcoreTemperative ; wxString MainFrame::s_wxstrTaskBarIconToolTip = wxT("x86IandC--highest CPU core temperature [°C]") ; DEFINE_LOCAL_EVENT_TYPE( wxEVT_COMMAND_REDRAW_EVERYTHING ) BEGIN_EVENT_TABLE(MainFrame, wxFrame) EVT_COMMAND(wxID_ANY, wxEVT_COMMAND_REDRAW_EVERYTHING, MainFrame::OnRedrawEverything) //"Cross-Platform GUI Programming with wxWidgets" // (Copyright © 2006 Pearson Education, Inc.) // ISBN 0-13-147381-6 "First printing, July 2005" //"CHAPTER 5 Drawing and Printing" -> //"UNDERSTANDING DEVICE CONTEXTS" -> "Drawing on Windows with wxPaintDC" : // "[...] another thing you can do to make // drawing smoother (particularly when resizing) is to paint the background in // your paint handler, and not in an erase background handler. All the painting // will then be done in your buffered paint handler, so you don’t see the back- // ground being erased before the paint handler is called. Add an empty erase // background handler, and call SetBackgroundStyle with wxBG_STYLE_CUSTOM to // hint to some systems not to clear the background automatically." EVT_ERASE_BACKGROUND(MainFrame::OnEraseBackground) EVT_MENU(ID_Quit, MainFrame::OnQuit) EVT_MENU(ID_About, MainFrame::OnAbout) EVT_MENU(ID_AttachCPUcontrollerDynLib, MainFrame::OnAttachCPUcontrollerDLL) EVT_MENU(ID_DetachCPUcontrollerDynamicLibrary, MainFrame::OnDetachCPUcontrollerDLL) EVT_MENU(ID_AttachCPUusageGetterDynLib, MainFrame::OnAttachCPUcoreUsageGetterDLL) EVT_MENU(ID_DetachCPUusageGetterDynLib, MainFrame::OnDetachCPUcoreUsageGetterDLL) //Pre-defined preprocessor macro under MSVC, MinGW for 32 and 64 bit Windows. #ifdef _WIN32 //Built-in macro for MSVC, MinGW (also for 64 bit Windows) EVT_MENU(ID_MinimizeToSystemTray, MainFrame::OnMinimizeToSystemTray) #endif #ifdef COMPILE_WITH_MSR_EXAMINATION EVT_MENU(ID_ShowExamineCPUregistersDialog, MainFrame::OnShowExamineCPUregistersDialog) EVT_MENU(ID_WriteToMSRdialog, MainFrame::OnShowCPUregistersReadAndWriteDialog) #endif //EVT_MENU( ID_MinAndMaxCPUcoreFreqInPercentOfMaxFreq , // MainFrame::OnDynamicallyCreatedUIcontrol ) EVT_MENU( ID_DisableOtherVoltageOrFrequencyAccess , MainFrame::OnDisableOtherVoltageOrFrequencyAccess ) EVT_MENU( ID_EnableOtherVoltageOrFrequencyAccess , MainFrame::OnEnableOtherVoltageOrFrequencyAccess ) EVT_MENU( ID_EnableOrDisableOwnDVFS , MainFrame::OnOwnDynFreqScaling ) EVT_MENU( ID_LoadDetectInstableCPUcoreVoltageDynLib, MainFrame::OnLoadDetectInstableCPUcoreVoltageDynLib) EVT_MENU( ID_UnloadDetectInstableCPUcoreVoltageDynLib, MainFrame::OnUnloadDetectInstableCPUcoreVoltageDynLib) EVT_MENU( ID_UpdateViewInterval , MainFrame::OnUpdateViewInterval ) EVT_MENU( ID_SetCPUcontrollerDynLibForThisCPU , MainFrame::OnSaveAsCPUcontrollerDynLibForThisCPU ) EVT_MENU( ID_SaveAsDefaultPstates , MainFrame::OnSaveVoltageForFrequencySettings ) EVT_MENU( ID_FindDifferentPstates , MainFrame::OnFindDifferentPstates ) EVT_MENU( ID_Collect_As_Default_Voltage_PerfStates , MainFrame::OnCollectAsDefaultVoltagePerfStates ) EVT_MENU( ID_ShowVoltageAndFrequencySettingsDialog , MainFrame:://OnShowVoltageAndFrequencySettingsDialog OnVoltageAndFrequencySettingsDialog) #ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL EVT_MENU( ID_ContinueService , MainFrame::OnContinueService ) EVT_MENU( ID_PauseService , MainFrame::OnPauseService ) EVT_MENU( ID_StartService , MainFrame::OnStartService ) EVT_MENU( ID_StopService , MainFrame::OnStopService ) EVT_MENU( ID_ConnectToService , MainFrame::OnConnectToService ) EVT_MENU( ID_ConnectToOrDisconnectFromService , MainFrame::OnConnectToOrDisconnectFromService ) EVT_MENU( ID_DisconnectFromService , MainFrame::OnDisconnectFromService ) #endif //#ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL //#endif //#ifdef _WINDOWS #ifdef COMPILE_WITH_SERVICE_CAPABILITY EVT_MENU(ID_Service, MainFrame::OnStartService) #endif //EVT_MENU(ID_SetPstate0ForBothCores, MyFrame::OnSetPstate0ForBothCores) //EVT_MENU(ID_SetPstate1ForBothCores, MyFrame::OnSetPstate1ForBothCores) //EVT_MENU(ID_SetPstate2ForBothCores, MyFrame::OnSetPstate2ForBothCores) //EVT_MENU(ID_FindLowestOperatingVoltage, MainFrame::OnFindLowestOperatingVoltage) #ifdef PRIVATE_RELEASE //hide the other possibilities EVT_MENU(ID_IncreaseVoltageForCurrentPstate, MainFrame::OnIncreaseVoltageForCurrentPstate) #endif //#ifdef PRIVATE_RELEASE //hide the other possibilities #ifdef wxHAS_POWER_EVENTS EVT_POWER_RESUME(MainFrame::OnResume) EVT_POWER_SUSPENDING(MainFrame::OnSuspending) EVT_POWER_SUSPENDED(MainFrame::OnSuspended) EVT_POWER_SUSPEND_CANCEL(MainFrame::OnSuspendCancel) #endif // wxHAS_POWER_EVENTS //For stopping the DynVoltAndFreqScal thread that accesses the wxApp. //So stop the DVFS thread before destroying the wxApp object to avoid //crashes. EVT_CLOSE( MainFrame::OnClose ) // EVT_INIT_DIALOG(MainFrame::OnInitDialog) //If no EVT_PAINT macro and Connect(wxEVT_PAINT, // wxPaintEventHandler(MyFrame::OnPaint)); // : 100% CPU load. EVT_PAINT (MainFrame::OnPaint) EVT_SIZE(MainFrame::OnSize) EVT_SIZING(MainFrame::OnSizing) EVT_MOTION(MainFrame::OnMoveMouse) EVT_LEFT_DOWN(MainFrame::OnLeftMouseButtonDown) //EVT_TIMER(-1,MainFrame::OnTimerEvent) EVT_TIMER(TIMER_ID, MainFrame::OnTimerEvent) //EVT_COMMAND_RIGHT_CLICK(FIRST_TRAYNOTIFY_ID, MainFrame::OnSysTrayIconClick) // EVT_MOUSE_EVENTS(FIRST_TRAYNOTIFY_ID, MainFrame::OnSysTrayIconClick) END_EVENT_TABLE() #define ATTACH_CPU_CONTROLLER_DYNAMIC_LIBRARY_T_STRING \ _T("Attach CPU &controller dynamic library...") #define ATTACH_CPU_CORE_USAGE_GETTER_DYNAMIC_LIBRARY_T_STRING \ _T("Attach CPU &usage getter dynamic library...") #define DETACH_CPU_CONTROLLER_DYNAMIC_LIBRARY_T_STRING \ _T("Detach CPU controller dynamic library") #define DETACH_CPU_CORE_USAGE_GETTER_DYNAMIC_LIBRARY_T_STRING \ _T("Detach CPU usage getter dynamic library") //for CPU_TEMP_IS_BELOW_CRITICAL, CPU_TEMP_IS_CRITICAL #include <Controller/CPU-related/CPU_core_temperature_defs.h> inline void MainFrame::CreateFileMenu() { LOGN(/*"CreateFileMenu()"*/ "begin") wxMenuItem * p_wxmenuitem ; mp_wxmenuFile = new wxMenu; //wxMenu * p_wxmenuCore1 = new wxMenu; // wxMenu * p_wxmenuNorthBridge = new wxMenu; mp_wxmenuFile->Append( ID_About, _T("&About...") ); mp_wxmenuFile->AppendSeparator(); p_wxmenuitem = mp_wxmenuFile->Append( ID_AttachCPUcontrollerDynLib, ATTACH_CPU_CONTROLLER_DYNAMIC_LIBRARY_T_STRING ); if( ! mp_wxx86infoandcontrolapp->GetCPUaccess() ) p_wxmenuitem->SetHelp ( //TODO more imformative/ user-friendly message (but may not be too long) wxT("No CPU access. See log file/ start this program as admin.") ) ; mp_wxmenuFile->Append( ID_DetachCPUcontrollerDynamicLibrary, DETACH_CPU_CONTROLLER_DYNAMIC_LIBRARY_T_STRING ); mp_wxmenuFile->Append( ID_SetCPUcontrollerDynLibForThisCPU, wxString::Format( wxT("save as CPU controller dynamic library for this CPU " "(vendor:%s family:%u model:%u stepping:%u)") , wxWidgets::getwxString( mp_model->m_cpucoredata.m_strVendorID.c_str() ).c_str() , mp_model->m_cpucoredata.m_wFamily , (WORD) mp_model->m_cpucoredata.m_byModel , (WORD) mp_model->m_cpucoredata.m_byStepping ) ); if( ! //gp_cpucontrolbase->mp_wxdynlibcpucontroller mp_wxx86infoandcontrolapp->m_p_cpucontrollerDynLib ) { mp_wxmenuFile->Enable( ID_SetCPUcontrollerDynLibForThisCPU, false ) ; mp_wxmenuFile->Enable( ID_DetachCPUcontrollerDynamicLibrary, false ) ; } mp_wxmenuFile->AppendSeparator(); p_wxmenuitem = mp_wxmenuFile->Append( ID_AttachCPUusageGetterDynLib, ATTACH_CPU_CORE_USAGE_GETTER_DYNAMIC_LIBRARY_T_STRING ); if( ! mp_wxx86infoandcontrolapp->GetCPUaccess() ) p_wxmenuitem->SetHelp ( //TODO more imformative/ user-friendly message (but may not be too long) wxT("No CPU access. See log file/ start this program as admin.") ) ; mp_wxmenuFile->Append( ID_DetachCPUusageGetterDynLib, DETACH_CPU_CORE_USAGE_GETTER_DYNAMIC_LIBRARY_T_STRING ); if( ! //gp_cpucontrolbase->mp_wxdynlibcpucoreusagegetter mp_wxx86infoandcontrolapp->m_p_cpucoreusagegetterDynLib ) mp_wxmenuFile->Enable( ID_DetachCPUusageGetterDynLib, false ) ; mp_wxmenuFile->AppendSeparator(); mp_wxmenuFile->Append( ID_SaveAsDefaultPstates, //wxT("Save &performance states settings...") wxT("Save \"&voltage at/for frequency\" settings...") ); //Only add menu item if creating the system tray icon succeeded: else one // can hide the window but can not restore it: if this process started //elevated one can't even close it! if( mp_wxx86infoandcontrolapp->ShowTaskBarIcon(this) ) { mp_wxmenuFile->AppendSeparator(); // mp_wxx86infoandcontrolapp->ShowTaskBarIcon(this) ; mp_wxmenuFile->Append( ID_MinimizeToSystemTray, _T("minimize this window to the " //"system tray" "task bar") ); } //#endif //COMPILE_WITH_TASKBAR mp_wxmenuFile->AppendSeparator(); //mp_wxmenuFile->Append( ID_Service, _T("Run As Service") ); mp_wxmenuFile->Append( ID_Quit, _T("E&xit") ); //p_wxmenuBar->Append( mp_wxmenuFile, _T("&File") ); //m_wxmenubar.Append( mp_wxmenuFile, _T("&File") ); mp_wxmenubar->Append( mp_wxmenuFile, _T("&File") ); LOG("after file menu creation"//\n" ) } /** @brief creates menu items for the "GUI" menu. */ inline void MainFrame::CreateGUImenuItems() { m_p_wxmenuGUI = NULL ; //#ifdef COMPILE_WITH_SERVICE_CONTROL #ifdef COMPILE_WITH_OTHER_DVFS_ACCESS if( ! m_p_wxmenuGUI ) m_p_wxmenuGUI = new wxMenu; mp_wxmenuitemOtherDVFS = m_p_wxmenuGUI->Append( //ID_MinAndMaxCPUcoreFreqInPercentOfMaxFreq ID_DisableOtherVoltageOrFrequencyAccess //_T("&CPU % min and max.") //_T("enable or disable OS's dynamic frequency scaling") , wxT("DISable OS's dynamic frequency scaling") ); mp_wxmenuitemOtherDVFS = m_p_wxmenuGUI->Append( ID_EnableOtherVoltageOrFrequencyAccess , wxT("ENable OS's dynamic frequency scaling") ); LOGN("after appending menu item \"disable OS's dynamic frequency scaling\"") //If one can not change the power scheme (Windows) etc. if( //mp_i_cpucontroller->mp_dynfreqscalingaccess-> mp_wxx86infoandcontrolapp->mp_dynfreqscalingaccess-> ChangeOtherDVFSaccessPossible() ) LOGN("Changing other DVFS is possible." ) else { LOGN("Changing other DVFS is not possible." ) mp_wxmenuitemOtherDVFS->Enable(false); mp_wxmenuitemOtherDVFS->SetHelp ( wxT("Start e.g. as administrator to gain access") ) ; //mp_wxmenuitemOtherDVFS->SetItemLabel (wxT("dd") ) ; LOGN("changing other DVFS not possible") } if( //mp_i_cpucontroller->mp_dynfreqscalingaccess->EnablingIsPossible() mp_wxx86infoandcontrolapp->mp_dynfreqscalingaccess->EnablingIsPossible() ) { LOGN("enabling other DVFS is possible") // std::tstring stdtstr = p_wxx86infoandcontrolapp->mp_dynfreqscalingaccess-> // GetEnableDescription() ; std::wstring stdwstr = mp_wxx86infoandcontrolapp->mp_dynfreqscalingaccess-> GetEnableDescription() ; mp_wxmenuitemOtherDVFS = m_p_wxmenuGUI->Append( ID_EnableOtherVoltageOrFrequencyAccess //_T("enable OS's dynamic frequency scaling") //GetDisableDescrpition() under Windows may return "activate 'performance' power scheme ". //Use GetwxString(...) because GetEnableDescription() may return // -std::wstring although wxString uses char strings. // -std::string although wxString uses wchar_t strings. , wxWidgets::getwxString( //mp_i_cpucontroller->mp_dynfreqscalingaccess->GetEnableDescription() // stdtstr stdwstr ) ); LOGN("after appending menu item \"" << GetStdString(stdwstr) << "\"") } #endif //#ifdef COMPILE_WITH_OTHER_DVFS_ACCESS LOG("after extras menu creation"//\n" ) if( ! m_p_wxmenuGUI ) m_p_wxmenuGUI = new wxMenu; std::string stdstr = "set update view interval" ; LOGN("before appending menu item " << stdstr ) m_p_wxmenuGUI->Append( ID_UpdateViewInterval, //_T("&CPU % min and max.") wxWidgets::getwxString( stdstr ) ); stdstr = "collect p-states as default voltage p-states" ; LOGN("before appending menu item " << stdstr ) mp_wxmenuitemCollectAsDefaultVoltagePerfStates = m_p_wxmenuGUI-> AppendCheckItem( ID_Collect_As_Default_Voltage_PerfStates, //_T("&CPU % min and max.") wxWidgets::getwxString( stdstr ) ); //#ifdef _WIN32 //Built-in macro for MSVC, MinGW (also for 64 bit Windows) //wxMenu * m_p_wxmenuGUI = new wxMenu; //#endif //if( ! p_cpucontroller->mp_model->m_cpucoredata. // m_stdsetvoltageandfreqDefault.empty() // ) { if( ! m_p_wxmenuGUI ) m_p_wxmenuGUI = new wxMenu;//(wxT("Graphical User Interface")); stdstr = "enable own Dynamic Voltage and Frequency Scaling" ; LOGN("before appending menu item " << stdstr ) mp_wxmenuitemOwnDVFS = m_p_wxmenuGUI->Append( ID_EnableOrDisableOwnDVFS , wxWidgets::getwxString( stdstr ) ); if( //p_cpucontroller->mp_model->m_cpucoredata. mp_model->m_cpucoredata. m_stdsetvoltageandfreqWanted.empty() ) { //Does not work. // mp_wxmenuitemOwnDVFS->Enable(false) ; // m_p_wxmenuGUI->Enable(ID_EnableOrDisableOwnDVFS , false ) ; // mp_wxmenuitemOwnDVFS->Enable(false) ; mp_wxmenuitemOwnDVFS->SetHelp( wxT("no desired voltages for frequencies" " available->no DVFS possible") ) ; } } //#endif //#ifdef _WIN32 #ifdef COMPILE_WITH_MSR_EXAMINATION if( ! m_p_wxmenuGUI ) m_p_wxmenuGUI = new wxMenu; m_p_wxmenuGUI->Append(ID_ShowExamineCPUregistersDialog, wxT("e&xamine CPUID and MSR CPU registers...") ); m_p_wxmenuGUI->Append(ID_WriteToMSRdialog, wxT("read from and write to MSR dialog...") ); #endif m_p_wxmenuGUI->Append( ID_LoadDetectInstableCPUcoreVoltageDynLib, wxT("Load dynamic library for detecting an instable CPU core voltage...") ); m_p_wxmenuitemUnloadDetectInstableCPUcoreVoltageDynLib = m_p_wxmenuGUI-> Append( ID_UnloadDetectInstableCPUcoreVoltageDynLib, wxT("Unload dynamic library for detecting an instable CPU core voltage") ); if( m_p_wxmenuGUI ) { LOGN("before adding menu \"GUI\"") mp_wxmenubar->Append(m_p_wxmenuGUI, //_T("E&xtras") wxT("&GUI") ); } } MainFrame::MainFrame( const wxString & cr_wxstrTitle, const wxPoint & cr_wxpointTopLeftCornerPosition, const wxSize & cr_wxsize , I_CPUcontroller * p_cpucontroller //, CPUcoreData * p_cpucoredata , Model * p_model , wxX86InfoAndControlApp * p_wxx86infoandcontrolapp ) : wxFrame( (wxFrame *) NULL, -1, cr_wxstrTitle, cr_wxpointTopLeftCornerPosition, cr_wxsize //http://docs.wxwidgets.org/2.6/wx_wxwindow.html#wxwindow: //"Use this style to force a complete redraw of the window whenever it is //resized instead of redrawing just the part of the window affected by //resizing. Note that this was the behaviour by default before 2.5.1 //release and that if you experience redraw problems with code which //previously used to work you may want to try this. Currently this style //applies on GTK+ 2 and Windows only, and full repainting is always done //on other platforms." //kurz: Stil ist notwendig, um das ganze Diagramm neu zu zeichnen , wxFULL_REPAINT_ON_RESIZE //| wxCLIP_CHILDREN //Necessary for showing a title bar | wxDEFAULT_FRAME_STYLE ) //, mp_cpucoredata(p_cpucoredata) //Initialize in the same order as textual in the declaration? //(to avoid g++ warnings) , m_bAllowCPUcontrollerAccess ( true ) , m_bCPUcoreUsageConsumed( true ) , m_bDiagramNotDrawn(true) , mp_ar_voltage_and_multi( NULL ) , m_bNotFirstTime(false) , m_bRangeBeginningFromMinVoltage ( true ) // , s_arfTemperatureInDegreesCelsius( NULL ) #ifdef COMPILE_WITH_CALC_THREAD , mp_calculationthread( NULL ) #endif , mp_cpucoredata( & p_model->m_cpucoredata ) , m_dwTimerIntervalInMilliseconds (1000) // , m_fPreviousCPUusage(0.0f) // , mp_freqandvoltagesettingdlg(NULL) , m_arp_freqandvoltagesettingdlg ( NULL ) , m_p_freqandvoltagesettingsdialog(NULL) , mp_i_cpucontroller ( p_cpucontroller) , mp_model ( p_model ) //, m_bConfirmedYet(true) , m_vbAnotherWindowIsActive(false) , m_wMaximumCPUcoreFrequency ( 0 ) , m_wMaxFreqInMHzTextWidth ( 0 ) , m_wMaxVoltageInVoltTextWidth ( 0 ) , m_wMaxTemperatureTextWidth ( 0 ) //, m_wxbufferedpaintdcStatic( this ) //Necessary for the timer to run: , mp_wxbitmap(NULL) , mp_wxbitmapStatic (NULL) , mp_wxbufferedpaintdcStatic( NULL) // , m_wxicon_drawer(16,16//,8 //// ,wxBITMAP_SCREEN_DEPTH // ) //, mp_wxdynlibcpucontroller ( NULL ) //, mp_wxdynlibcpucoreusagegetter ( NULL ) , m_wxstrTitle(cr_wxstrTitle) , m_wxtimer(this) , mp_wxx86infoandcontrolapp ( p_wxx86infoandcontrolapp ) // , m_xerces_voltage_for_frequency_configuration( p_model ) { LOGN("begin of main frame creation"//\n" ) wxIcon wxicon; if( p_wxx86infoandcontrolapp->GetX86IandCiconFromFile(wxicon) ) { SetIcon( wxicon); } else { // p_wxx86infoandcontrolapp->MessageWithTimeStamp( // GetStdWstring( wxT("setting icon for the main frame failed") ) // ); LOGN("setting icon from file for the main frame failed") wxIcon wxiconThisDialog( x86IandC_xpm ) ; SetIcon(x86IandC_xpm); } LOGN("# CPU cores: " << (WORD) mp_model->m_cpucoredata.m_byNumberOfCPUCores) // m_p_wxtimer = new wxTimer( this ) ; mp_ar_voltage_and_multi = new VoltageAndMulti[ mp_model->m_cpucoredata.m_byNumberOfCPUCores ] ; //"Cross-Platform GUI Programming with wxWidgets" // (Copyright © 2006 Pearson Education, Inc.) // ISBN 0-13-147381-6 "First printing, July 2005" //"CHAPTER 5 Drawing and Printing" -> //"UNDERSTANDING DEVICE CONTEXTS" -> "Drawing on Windows with wxPaintDC" : //"[...] call SetBackgroundStyle with wxBG_STYLE_CUSTOM to // hint to some systems not to clear the background automatically." SetBackgroundStyle(wxBG_STYLE_CUSTOM ); // m_bConfirmedYet = true ; mp_wxmenubar = new wxMenuBar; CreateFileMenu() ; //#ifdef COMPILE_WITH_OTHER_DVFS_ACCESS #ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL CreateServiceMenuItems() ; #endif // CreateAndInitMenuItemPointers() ; //p_wxmenuCore0->Append( ID_FindLowestOperatingVoltage, // _T("find lowest operating voltage") ); //p_wxmenuAllCores->Append( ID_FindLowestOperatingVoltage, //_T("find lowest operating voltage") ); //#ifdef PRIVATE_RELEASE //hide the other possibilities // p_wxmenuCore0->Append( ID_IncreaseVoltageForCurrentPstate, // _T("increase voltage for current p-state (stabilize machine)") ); //#endif //#ifdef PRIVATE_RELEASE //hide the other possibilities //UpdatePowerSettings(wxPOWER_UNKNOWN, wxBATTERY_UNKNOWN_STATE); CreateGUImenuItems(); if( mp_i_cpucontroller != NULL ) { CreateDynamicMenus(); } //#ifdef COMPILE_WITH_VISTA_POWERPROFILE_ACCESS // ////Connect the action, that is a class derived from class xx directly // ////with the menu item so that it is ensured to be the correct action // ////(calling the action in an event function is more error-prone) // ////TODO release memory // ////, new CalculationThread(byCoreID, HighALUloadThreadProc) // //, wxCommandEventHandler( MainFrame::OnOwnDynFreqScaling ) // //) ; // mp_wxmenubar->Append(m_p_wxmenuGUI, _T("E&xtras") ); //#endif //mp_wxmenubar->Append( p_wxmenuNorthBridge, _T("&NorthBridge") ); //TODO program crash here for unicode versions (for working versions // an OnSize() event was intermediate) LOGN("before setting menu bar " << mp_wxmenubar) //Just for testing. // wxSleep(5) ; //SetMenuBar( p_wxmenuBar ); //SetMenuBar( & m_wxmenubar ); SetMenuBar( mp_wxmenubar ); LOGN("before creating status bar") CreateStatusBar(); // const char bits [] = { // 0,0,0,0, // 1,1,1,1, // 0,0,0,0, // 1,1,1,1 // } ; // wxIcon wxicon(bits,4,4) ; // SetIcon(wxicon); // Connect(wxEVT_PAINT, wxPaintEventHandler(MainFrame::OnPaint)); //SetStatusText( _T("Welcome to wxWidgets!") ); LOGN("before starting the update view timer") //m_wxtimer.Start(1000); m_wxtimer.Start(m_dwTimerIntervalInMilliseconds); // m_p_wxtimer->Start(m_dwTimerIntervalInMilliseconds); //http://docs.wxwidgets.org/stable/wx_wxtimer.html#wxtimersetowner: //"Associates the timer with the given owner object. When the timer is //running, the owner will receive timer events with id equal to id //specified here." m_wxtimer.SetOwner(this, TIMER_ID) ; // Connect(wxEVT_SIZE, wxSizeEventHandler(MainFrame::OnSize)); if( mp_wxx86infoandcontrolapp->//mp_wxdynlibcpucontroller m_p_cpucontrollerDynLib ) { wxString wxstrCPUcontrollerDynLibPath( // //Use getwxString() to enable to compile with both unicode and ANSI. // getwxString( // mp_model->m_stdstrCPUcontrollerDynLibPath ) // ) ; //http://wiki.wxwidgets.org/Converting_everything_to_and_from_wxString#std::string_to_wxString: mp_model->m_stdstrCPUcontrollerDynLibPath.c_str(), wxConvUTF8 ); #if wxUSE_UNICODE == 1 DEBUGWN_WSPRINTF(L"CPU controller path as wide string:%ls", //wxstrCPUcontrollerDynLibPath.c_str() wxstrCPUcontrollerDynLibPath.wc_str() ) ; #endif CPUcontrollerDynLibAttached(wxstrCPUcontrollerDynLibPath) ; } if( mp_wxx86infoandcontrolapp->//mp_wxdynlibcpucoreusagegetter m_p_cpucoreusagegetterDynLib ) { wxString wxstrCPUcoreUsageGetterDynLibPath( //Use getwxString() to enable to compile with both unicode and ANSI. wxWidgets::getwxString( mp_model->m_stdstrCPUcoreUsageGetterDynLibPath) ) ; CPUcoreUsageGetterAttached(wxstrCPUcoreUsageGetterDynLibPath) ; } // mp_wxx86infoandcontrolapp->ShowTaskBarIcon(this) ; LOGN("end of main frame creation"//\n" ) // RedrawEverything() ; // Refresh() ; // InitDialog() ; } MainFrame::~MainFrame() { LOGN("begin" /*" of main frame's destructor"*/ ) //TODO Error here.the problem was with destructor of wxMenuBar.->create //wxMenuBar via "new"? //for(BYTE byCoreID = 0 ; byCoreID < //m_byCoreNumber // mp_cpucoredata->m_byNumberOfCPUCores ; ++ byCoreID ) //{ // //Release memory from the heap. // delete m_vecp_wxmenuCore.at(byCoreID) ; //} //Release memory for array of pointers. // delete [] m_arp_wxmenuitemPstate ; // delete [] marp_wxmenuItemHighLoadThread ; #ifdef COMPILE_WITH_CALC_THREAD if( mp_calculationthread ) delete mp_calculationthread ; #endif //Only terminates correctly when deleted from here (is also deleted in //the wxTopLevelWindow's (wxDialog's) destructor in wxWidgets' "tbtest.cpp" //from the "taskbar" sample. mp_wxx86infoandcontrolapp->DeleteTaskBarIcons(); LOGN("end" /*" of main frame's destructor"*/ ) } //void MyFrame::AddMenu() //{ // //wxEventTableEntry(type, winid, idLast, fn, obj) // EVT_MENU(ID_LastStaticEventID+1,MyFrame::OnDynamicMenu); //} // //void MyFrame::OnDynamicMenu(wxCommandEvent &event) //{ // //} //wxString MainFrame::BuildHighLoadThreadMenuText( // std::string str, // BYTE byPreviousAction) //{ // wxString wxstr = byPreviousAction == //ENDED ? // ICalculationThread::ended ? // //We need a _T() macro (wide char-> L"", char->"") for EACH // //line to make it compatible between char and wide char. // _T("Start") : // //We need a _T() macro (wide char-> L"", char->"") for EACH // //line to make it compatible between char and wide char. // _T("End") ; // ////Invert the menu item's checked state. // //marp_wxmenuItemHighLoadThread[byCoreID]->Check( // // ! marp_wxmenuItemHighLoadThread[byCoreID]->IsChecked () ) ; //// marp_wxmenuItemHighLoadThread[byCoreID]->SetText( //// wxstr + //// str //// ); // return wxstr + wxString( // //TODO this conversion may not work // (const wxChar*) str.c_str() ) ; //} //bool MainFrame::Confirm(const std::string & str) //{ // //::AfxMessageBox(str.c_str()); // // //To not show too many dialogs that the timer would bring up. //// if( m_bConfirmedYet ) //// { //// m_bConfirmedYet = false ; //// ::wxMessageBox(wxString( //// //TODO this conversion may not work //// (const wxChar * ) str.c_str() ) //// ); //// m_bConfirmedYet = true ; //// } // //m_bConfirmedYet = true ; // return true; //} //bool MainFrame::Confirm(std::ostrstream & r_ostrstream // //std::ostream & r_ostream // ) //{ // bool bReturn = true ; // DEBUGN("begin"); // //Must set this, else text may follow after the string we want. // //I had program crashes with the following method: // //pch[r_ostrstream.pcount()] = '\0' ; // //r_ostrstream.ends(); // r_ostrstream.put('\0'); //the same as "ends()" does. //// char *pch = r_ostrstream.str() ; // //r_ostrstream.flush(); // //To not show too many dialogs that the timer would bring up. //// if( m_bConfirmedYet ) //// { //// m_bConfirmedYet = false ; //// int nReturn = ::wxMessageBox( wxString( //// //TODO this conversion may not work //// (const wxChar * ) pch ) , //// //We need a _T() macro (wide char-> L"", char->"") for EACH //// //line to make it compatible between char and wide char. //// wxString( _T("Message") ) , wxCANCEL | wxOK ) ; //// if( nReturn == wxCANCEL ) //// bReturn = false ; //// m_bConfirmedYet = true ; //// } // //return true; // DEBUGN("end"); // return bReturn ; //} inline void MainFrame::ConnectToDataProvider_Inline() { mp_wxx86infoandcontrolapp->ConnectToDataProviderAndShowResult() ; } #ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL void MainFrame::CreateServiceMenuItems() { wxString wxstrConnectOrDisconnect ; p_wxmenuService = new wxMenu ; //TODO: set bitmap for item //http://docs.wxwidgets.org/trunk/classwx_menu_item.html#a2b5d6bcb820b992b1e4709facbf6d4fb: //"SetBitmap() must be called before the item is appended to the menu" // wxMenuItem * p_wxmenuitem = new wxMenuItem(); // p_wxmenuitem->SetBitmap(); if( ServiceBase::CanStartService() ) { p_wxmenuService->Append( ID_StartService , wxT("&start"), wxT("start the x86I&C service via the Service Control Manager") ) ; } else p_wxmenuService->Append( ID_StartService , wxT("&start"), wxT("insufficient rights to start the x86I&C service via the Service " "Control Manager") ) ; //Stopping a service can be done via Inter Process Communication. (Else if //via Service Control manager then needs the same? rights/ privileges as //starting a service). p_wxmenuService->Append( ID_StopService , wxT("s&top"), wxT("stop the x86I&C service via InterProcess Communication or via " "Service Control Manager") ); #ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE p_wxmenuService->Append( ID_ConnectToService, wxT("connect..."), wxT("connect to an arbitrary address to the (x86IandC) " "CPU core data provider/ server/ service") ); // if( mp_wxx86infoandcontrolapp->m_ipcclient.IsConnected() ) // wxstrConnectOrDisconnect = wxT("disconnect") ; // else wxstrConnectOrDisconnect = wxT("c&onnect to ") + wxWidgets::getwxString( mp_model->m_userinterfaceattributes.m_std_wstrServiceAddress); p_wxmenuService->Append( ID_ConnectToOrDisconnectFromService, wxstrConnectOrDisconnect, wxT("connect to the (x86IandC) " "CPU core data provider/ server/ service" // " specified in the x86IandC " // "config file" ) ); p_wxmenuService->Append( ID_DisconnectFromService, wxT("&DISCOnnect"), wxT("DISconnect from the (x86IandC) " "CPU core data provider/ server/ service if currently connected") ); #endif //#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE //pause and continue is possible via service ctrl mgr p_wxmenuService->Append( ID_ContinueService, wxT("&Continue"), wxT("continue " "the Dynamic Voltage and Frequency Scaling done by the x86IandC service/ " "server") ); p_wxmenuService->Append( ID_PauseService , wxT("&Pause"), wxT("pause " "the Dynamic Voltage and Frequency Scaling done by the x86IandC service/ " "server") ); // p_wxmenuService->Append( ID_StartService , _T("&Start") ); // p_wxmenuService->Append( ID_StopService , _T("Sto&p") ); mp_wxmenubar->Append( p_wxmenuService, wxT("&Service") ) ; LOGN("end" /*" of CreateServiceMenuItems"*/ ) } #endif //#ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL ////void //wxMenuItem * MainFrame::AddDynamicallyCreatedMenu( // wxMenu * p_wxmenu, // WORD & r_wMenuID, // const wxString & r_wxstr // ) //{ // wxMenuItem * p_wxmenuitemAppended = p_wxmenu->Append(r_wMenuID, r_wxstr ); // Connect( r_wMenuID ++ , //wxID_ANY, // wxEVT_COMMAND_MENU_SELECTED , // wxCommandEventHandler(MainFrame::OnDynamicallyCreatedUIcontrol) // ); // return p_wxmenuitemAppended ; //} //wxMenuItem * MainFrame::AddDynamicallyCreatedMenu( // wxMenu * p_wxmenu, // WORD & r_wMenuID, // const wxString & r_wxstr // , //void (wxEvtHandler::*wxEventFunction)(wxEvent&) // wxObjectEventFunction wxeee // , SpecificCPUcoreActionAttributes * p_scaa // ) //{ // m_stdmapwxuicontroldata.insert( // std::make_pair( // r_wMenuID , // //TODO release memory // p_scaa // ) // ) ; // wxMenuItem * p_wxmenuitemAppended = p_wxmenu->Append(r_wMenuID, r_wxstr ); // Connect( r_wMenuID ++ , //wxID_ANY, // wxEVT_COMMAND_MENU_SELECTED , // //wxCommandEventHandler( // //wxEventFunction //) // wxeee // ); // return p_wxmenuitemAppended ; //} //wxMenuItem * MainFrame::AddDynamicallyCreatedMenu( // wxMenu * p_wxmenu, // WORD & r_wMenuID, // const wxString & r_wxstr, // //Use a concrete class as parameter because this is more flexible than // //using a function with (a) fixed parameter type(s). // //Another option: use C functions: then parameter here would be: // //"void func(PVOID)" // //function A (PVOID pv) // //{ ActionAParamStruct * paramstr = (ActionAParamStruct) // // ActionAParamStruct: necessary parameters for execution (like CPU core ID) // // pv ; } // // // I_CPUcontrollerAction * icpuca // ) //{ // wxMenuItem * p_wxmenuitemAppended = p_wxmenu->Append(r_wMenuID, r_wxstr ); // m_stdmapwmenuid2i_cpucontrolleraction.insert( // std::make_pair (r_wMenuID,icpuca) // ) ; // Connect( r_wMenuID ++, wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, // wxCommandEventHandler(MainFrame::OnDynamicallyCreatedUIcontrol) // ); // return p_wxmenuitemAppended ; //} //void MainFrame::CreateAndInitMenuItemPointers() //{ // marp_wxmenuItemHighLoadThread = new wxMenuItem * [ // mp_cpucoredata->m_byNumberOfCPUCores ] ; // for( BYTE byIndex = 0 ; byIndex < mp_cpucoredata->m_byNumberOfCPUCores ; // ++ byIndex ) // marp_wxmenuItemHighLoadThread[ byIndex ] = NULL ; //} // ////void ////Return: TRUE: success. //BYTE MainFrame::AddSetPstateMenuItem( // wxMenu * p_wxmenuCore // , BYTE byCoreID // , BYTE byPstateID // //Must be a reference because changes to the variable should be // //maintained OUTside this function. // , WORD & r_wMenuID // ) //{ // BYTE byReturnValue = FALSE ; // return byReturnValue ; //} void MainFrame::Create1DialogAndMenuForAllCores() { wxMenu * p_wxmenuCore ; p_wxmenuCore = new wxMenu; if( p_wxmenuCore ) { m_p_wxmenuCore = p_wxmenuCore; p_wxmenuCore->Append(//ID_LastStaticEventID ID_ShowVoltageAndFrequencySettingsDialog, _T("set frequency and voltage ") ); mp_wxmenubar->Append( p_wxmenuCore, //We need a wxT() macro (wide char-> L"", char->"") for EACH //line to make it compatible between char and wide char. wxT("core(s)") ); // Connect( ID_LastStaticEventID, wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, // wxCommandEventHandler( // MainFrame::OnVoltageAndFrequencySettingsDialog ) // ); // LOGN("Connected event ID" << ID_LastStaticEventID << " to" << // "MainFrame::OnPstateDialog.") } } void MainFrame::CreateDialogAndMenuForEveryCore() { // BYTE byReturnValue ; WORD wMenuID = ID_LastStaticEventID; wxMenu * p_wxmenuCore ; m_arp_freqandvoltagesettingdlg = new FreqAndVoltageSettingDlg * [ mp_cpucoredata->m_byNumberOfCPUCores]; if(m_arp_freqandvoltagesettingdlg) { BYTE byPointerSize = sizeof( m_arp_freqandvoltagesettingdlg[0] ) ; //important: init pointers with NULL memset( m_arp_freqandvoltagesettingdlg , //NULL 0 , byPointerSize * mp_cpucoredata->m_byNumberOfCPUCores ); //TRACE("sizeof: %u\n", sizeof(m_arp_freqandvoltagesettingdlg)); #ifdef _DEBUG // int i = sizeof(m_arp_freqandvoltagesettingdlg) ; #endif for( BYTE byCoreID = 0 ; byCoreID < //m_byCoreNumber mp_cpucoredata->m_byNumberOfCPUCores ; ++ byCoreID ) { p_wxmenuCore = new wxMenu; //Memorize dynamically created menus in order to delete them of a // CPU controller DLL is attached more than once (else the wxWindows // are deleted automatically when the superordinate window is closed). m_vecp_wxmenuCore.push_back(p_wxmenuCore); p_wxmenuCore->Append(wMenuID, _T("set frequency and voltage ") ); //for(BYTE byDivisorID = 0 ; byDivisorID < FIRST_RESERVED_DIVISOR_ID ; // ++ byDivisorID ) //{ // Connect( wMenuID ++, wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, // wxCommandEventHandler(MyFrame::OnRuntimeCreatedMenu)//, & m_vecwxstring.back() // ); //} if( byCoreID == 0 ) m_nLowestIDForSetVIDnFIDnDID = wMenuID ; // wxCPUcoreID wxcpucoreid(byCoreID) ; // m_stdvectorwxuicontroldata.push_back( //wxCPUcoreID(byCoreID) // wxcpucoreid // //wxObject() // ) ; m_stdmapwxuicontroldata.insert( std::make_pair( wMenuID , //TODO release memory //new wxCPUcoreID(byCoreID) new SpecificCPUcoreActionAttributes(byCoreID) //wxcpucoreid //wxObject() ) ) ; #ifdef _DEBUG // wxCPUcoreID * p_wxcpucoreid = (wxCPUcoreID *) //wxevent.m_callbackUserData ; //& m_stdmapwxuicontroldata.find( wMenuID )->second ; //wxCPUcoreID & r_wxcpucoreid = (wxCPUcoreID &) //wxevent.m_callbackUserData ; // m_stdmapwxuicontroldata.find( wMenuID )->second ; #endif // Connect( wMenuID ++, wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, // wxCommandEventHandler( // //MainFrame::OnDynamicallyCreatedUIcontrol // MainFrame::OnVoltageAndFrequencySettingsDialog )//, & m_vecwxstring.back() // //new wx // //, & m_stdvectorwxuicontroldata.back() // ); // LOGN("connected event ID" << wMenuID - 1 << " to" << // "MainFrame::OnPstateDialog") p_wxmenuCore->Append(wMenuID, _T("find different p-states") ); Connect( wMenuID ++, wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrame::OnFindDifferentPstates ) ); LOGN("connected event ID" << wMenuID - 1 << " to" << "MainFrame::OnFindDifferentPstates") #ifdef COMPILE_WITH_CALC_THREAD marp_wxmenuItemHighLoadThread[byCoreID] = AddDynamicallyCreatedMenu( p_wxmenuCore, wMenuID, //_T("high load thread (for stability check)") BuildHighLoadThreadMenuText( "high FPU load thread (for stability check)" ) //Connect the action, that is a class derived from class xx directly //with the menu item so that it is ensured to be the correct action //(calling the action in an event function is more error-prone) //TODO release memory //, new CalculationThread(byCoreID, FPUcalculationThreadProc) , wxCommandEventHandler( MainFrame::OnHighLoadThread ) , new CalculationThread( byCoreID , FPUcalculationThreadProc , & ::wxGetApp() , ::wxGetApp().GetCPUcontroller() ) ) ; //#endif //#ifdef COMPILE_WITH_CALC_THREAD marp_wxmenuItemHighLoadThread[byCoreID] = AddDynamicallyCreatedMenu( p_wxmenuCore,wMenuID, //_T("high load thread (for stability check)") BuildHighLoadThreadMenuText( std::string( "high ALU load thread (for stability check)" ) ) //Connect the action, that is a class derived from class xx directly //with the menu item so that it is ensured to be the correct action //(calling the action in an event function is more error-prone) //TODO release memory //, new CalculationThread(byCoreID, HighALUloadThreadProc) , wxCommandEventHandler( MainFrame::OnHighLoadThread ) , new CalculationThread( byCoreID , HighALUloadThreadProc , & ::wxGetApp() , ::wxGetApp().GetCPUcontroller() ) ) ; #endif // #ifdef COMPILE_WITH_CALC_THREAD //marp_wxmenuItemHighLoadThread[byCoreID] = AddDynamicallyCreatedMenu( // p_wxmenuCore, // wMenuID, //_T("high load thread (for stability check)") // _T("own DVFS") // //Connect the action, that is a class derived from class xx directly // //with the menu item so that it is ensured to be the correct action // //(calling the action in an event function is more error-prone) // //TODO release memory // //, new CalculationThread(byCoreID, HighALUloadThreadProc) // , wxCommandEventHandler( MainFrame::OnOwnDynFreqScaling ) // , new SpecificCPUcoreActionAttributes(byCoreID) // ) ; //OnOwnDynFreqScaling //m_arp_wxmenuitemPstate[byCoreID * NUMBER_OF_PSTATES + 1] = // AddDynamicallyCreatedMenu(p_wxmenuCore,wMenuID, _T("Set p-state &1")) ; m_byNumberOfSettablePstatesPerCore = //NUMBER_OF_PSTATES ; 0 ; if( byCoreID == 0 ) m_byMenuIndexOf1stPstate = wMenuID - m_nLowestIDForSetVIDnFIDnDID ; //if( typeid (mp_i_cpucontroller ) == typeid(GriffinController) ) //{ // for( byPstateID = 0 ; byPstateID < //3 // m_byNumberOfSettablePstatesPerCore ; ++ byPstateID && // //if == TRUE // byReturnValue // ) // byReturnValue = AddSetPstateMenuItem( // p_wxmenuCore, byCoreID, byPstateID, wMenuID ) ; //} // if( byReturnValue ) { if( byCoreID == 0 ) { m_nNumberOfMenuIDsPerCPUcore = wMenuID - ID_LastStaticEventID ; //For removing per-core menus after unloading a CPU controller. m_byIndexOf1stCPUcontrollerRelatedMenu = mp_wxmenubar->GetMenuCount() ; } //marp_wxmenuItemHighLoadThread[byCoreID] = AddDynamicallyCreatedMenu( // p_wxmenuCore,wMenuID, _T("high load thread (for stability check)")) ; //m_wxmenubar.Append(p_wxmenuCore, _T("for core &")+ byCoreID); mp_wxmenubar->Append( p_wxmenuCore, wxString::Format( //We need a _T() macro (wide char-> L"", char->"") for EACH //line to make it compatible between char and wide char. _T("%s%u") //, _T("for core &") , _T("core &") , //_T('0'+byCoreID) byCoreID ) ); //marp_wxmenuItemHighLoadThread[byCoreID]->Check(true) ; //marp_wxmenuItemHighLoadThread[byCoreID]->Enable(false); } } //for-loop } } //void //Return value: BYTE MainFrame::CreateDynamicMenus() { // BYTE byPstateID = 0 ; BYTE byReturnValue = //Needs to be TRUE for the 1st loop condition evaluation. TRUE ; // WORD wMenuID = ID_LastStaticEventID; //m_vecwxstring.push_back(wxString) // wxMenu * p_wxmenuCore ; LOGN("CPU core menu creation--number of CPU cores: " << (WORD) mp_cpucoredata->m_byNumberOfCPUCores ) // byReturnValue = // CreateDialogAndMenuForEveryCore() ; Create1DialogAndMenuForAllCores() ; //SetMenuBar(&m_wxmenubar); return byReturnValue ; } void MainFrame::AllowCPUcontrollerAccess() { wxCriticalSectionLocker wxcriticalsectionlocker( m_wxcriticalsectionCPUctlAccess ) ; m_bAllowCPUcontrollerAccess = true ; } void MainFrame::DenyCPUcontrollerAccess() { DEBUGN("MainFrame::DenyCPUcontrollerAccess() begin" ) wxCriticalSectionLocker wxcriticalsectionlocker( m_wxcriticalsectionCPUctlAccess ) ; m_bAllowCPUcontrollerAccess = false ; DEBUGN("MainFrame::DenyCPUcontrollerAccess() end" ) } void MainFrame::DisableWindowsDynamicFreqScalingHint() { wxMessageBox( //We need a _T() macro (wide char-> L"", char->"") for EACH //line to make it compatible between char and wide char. _T("Remember: the OS' dynamic frequency scaling should be ") _T("deactivated the change to take effect\n") _T("see help/ disable by: ") _T("Start->control panel->energy options") _T("->change the current power plan") _T("->change extended energy options") _T("->set minimal and maximal CPU load to the same percentage") ); } void MainFrame::OnClose(wxCloseEvent & event ) { LOGN("begin" /*"Requested to close the main frame"*/) //Stop the timer (indirectly calls OnPaint()-> so another IPC thread could //be spawned). m_wxtimer.Stop() ; LOGN("Stopped the \"update view\" timer") // m_p_wxtimer->Stop() ; mp_wxx86infoandcontrolapp->EndGetCPUcoreDataViaIPCthread() ; //May be NULL at startup. if( mp_cpucoredata->m_arp_percpucoreattributes // CPU cores > 0 && mp_cpucoredata->m_byNumberOfCPUCores ) { PerCPUcoreAttributes * p_percpucoreattributes = & mp_cpucoredata-> m_arp_percpucoreattributes[ //p_atts->m_byCoreID 0 ] ; if ( p_percpucoreattributes->mp_dynfreqscalingthread ) { p_percpucoreattributes->mp_dynfreqscalingthread->Stop() ; LOGN("stopped the Dynamic Voltage and Frequency Scaling thread") //p_percpucoreattributes->mp_dynfreqscalingthread->Delete() ; p_percpucoreattributes->mp_dynfreqscalingthread = NULL ; } } mp_wxx86infoandcontrolapp->CheckForChangedVoltageForFrequencyConfiguration(); mp_wxx86infoandcontrolapp->DeleteTaskBarIcons(); LOGN("before destroying the mainframe") //see http://docs.wxwidgets.org/2.8/wx_windowdeletionoverview.html: this->Destroy() ; LOGN("after destroying the mainframe") } void MainFrame::OnCollectAsDefaultVoltagePerfStates( wxCommandEvent & WXUNUSED(event) ) { mp_model->m_bCollectPstatesAsDefault = mp_wxmenuitemCollectAsDefaultVoltagePerfStates->IsChecked () ; } void MainFrame::OnConnectToService( wxCommandEvent & WXUNUSED(event) ) { wxString wxstrTextFromUser = ::wxGetTextFromUser( wxT("enter server address") //const wxString & message, //const wxString & caption = "Input text", //const wxString & default_value = "", //wxWindow * parent = NULL, //int x = wxDefaultCoord, //int y = wxDefaultCoord, //bool centre = true ) ; // std::string strstrMessage ; mp_wxx86infoandcontrolapp->ConnectIPCclient( wxstrTextFromUser //, //strstrMessage ) ; } void MainFrame::OnConnectToOrDisconnectFromService( wxCommandEvent & WXUNUSED(event) ) { #ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE if( //::wxGetApp().m_ipcclient.IsConnected() mp_wxx86infoandcontrolapp->IPC_ClientIsConnected() ) ::wxMessageBox( //Use wxT() to enable to compile with both unicode and ANSI. wxT("already connected to the service") ) ; else { // if( ::wxGetApp().m_ipcclient.ConnectToDataProvider() ) // p_wxmenuService->SetLabel( ID_ConnectToOrDisconnectFromService , // wxT( "disconnect" ) // ) ; ConnectToDataProvider_Inline() ; } #endif } void MainFrame::OnContinueService(wxCommandEvent & WXUNUSED(event)) { LOGN(//"OnContinueService--" "begin") //ServiceBase::ContinueService( //mp_model->m_strServiceName.c_str() // "CPUcontrolService" ); #ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE wxString wxstrMessageFromDataProvider; if( ! mp_wxx86infoandcontrolapp-> ContinueServiceViaIPC(wxstrMessageFromDataProvider) ) // ::wxMessageBox( wxT("message from the service:\n") + // wxstrMessageFromDataProvider ) ; // else ::wxMessageBox( //Use wxT() to enable to compile with both unicode and ANSI. wxT("could not continue because not connected to the service") ) ; #endif //#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE } void MainFrame::OnDisableOtherVoltageOrFrequencyAccess( wxCommandEvent & WXUNUSED(event) ) { #ifdef COMPILE_WITH_OTHER_DVFS_ACCESS ::wxGetApp().mp_dynfreqscalingaccess->DisableFrequencyScalingByOS() ; #endif //#ifdef COMPILE_WITH_OTHER_DVFS_ACCESS } void MainFrame::OnDisconnectFromService( wxCommandEvent & WXUNUSED(event) ) { #ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE if( //mp_wxx86infoandcontrolapp->m_ipcclient.IsConnected() mp_wxx86infoandcontrolapp->IPC_ClientIsConnected() ) //mp_wxx86infoandcontrolapp->m_ipcclient.Disconnect_Inline() ; mp_wxx86infoandcontrolapp->IPCclientDisconnect() ; else { ::wxMessageBox( //Use wxT() to enable to compile with both unicode and ANSI. wxT("NOT connected to the service") ) ; } #endif } void MainFrame::OnEnableOtherVoltageOrFrequencyAccess( wxCommandEvent & WXUNUSED(event) ) { #ifdef COMPILE_WITH_OTHER_DVFS_ACCESS ::wxGetApp().mp_dynfreqscalingaccess->EnableFrequencyScalingByOS() ; #endif //#ifdef COMPILE_WITH_OTHER_DVFS_ACCESS } void MainFrame::OnFindDifferentPstates( wxCommandEvent & WXUNUSED(event) ) { //May be NULL at startup (before a controller DLL becomes attached). if( mp_i_cpucontroller ) { //wxString wxstrInput = ::wxGetTextFromUser( wxstrMessage , wxT("input"), // wxT("1000") ) ; ////::wxGetNumberFromUser ////If the user has input text (and has NOT pressed "cancel") //if( ! wxstrInput.empty() ) //{ // unsigned long ulMs ; // bool bSuccess = wxstrInput.ToULong(& ulMs) ; // if ( bSuccess ) // { // //ReadMsrEx() returned false results if used with a time and a 10 ms interval. // if( ulMs < 100 ) // wxMessageBox( wxT("the number is too low. " // "Getting the current CPU frequency returned wrong values with < 100 ms") ) ; // else // { // m_dwTimerIntervalInMilliseconds = ulMs ; // m_wxtimer.Stop() ; // m_wxtimer.Start(ulMs) ; // } // } // else // { // wxMessageBox( wxT("You did not enter a valid integer number") ) ; // } //} //Must create dynamically, else the CalculationThread is destroyed after leaving //this block. //if( ! mp_calculationthread ) //{ // mp_calculationthread = new CalculationThread( // 0 // , FindDifferentPstatesThreadProc // , & ::wxGetApp() // , ::wxGetApp().GetCPUcontroller() // ) ; //} //if( mp_calculationthread ) // mp_calculationthread->Execute() ; long lMin = ::wxGetNumberFromUser( wxT("input mininum frequency:"), wxT("prompt:"), wxT("caption:"), mp_i_cpucontroller->GetMinimumFrequencyInMHz() , 0 , mp_i_cpucontroller->GetMaximumFrequencyInMHz() ) ; //If the user enters an invalid value or cancels the dialog, the function will return -1. if( lMin == -1 ) ::wxMessageBox(wxT("either invalid value or cancel") ) ; else { long lMax = ::wxGetNumberFromUser( wxT("input maxinum frequency:"), wxT("prompt:"), wxT("caption:"), mp_i_cpucontroller->GetMaximumFrequencyInMHz() , lMin , mp_i_cpucontroller->GetMaximumFrequencyInMHz() ) ; if( lMax == -1 ) ::wxMessageBox(wxT("either invalid value or cancel") ) ; else { //TODO use available _mulipliers_ and call GetVoltageAndFrequency( // voltage, multiplier, refclock, ) //instead of frequencies // std::set<VoltageAndFreq> stdsetvoltageandfreq ; // std::set<VoltageAndFreq>::iterator iter ; // mp_i_cpucontroller->GetAllPossibleFrequencies( stdsetvoltageandfreq ) ; // //iter = stdsetvoltageandfreq.find(lMin) ; // iter = stdsetvoltageandfreq.begin() ; // while( iter != stdsetvoltageandfreq.end() ) // { // if( lMin >= iter->m_wFreqInMHz ) // break ; // iter ++ ; // } // // // //if( iter != stdsetvoltageandfreq.end() ) // { // float fVolt ; // WORD wFreq ; // //for( WORD wFreq = lMin ; wFreq < lMax ; wFreq += 50 ) // while( iter != stdsetvoltageandfreq.end() ) // { // //mp_i_cpucontroller->GetNearestHigherPossibleFreqInMHz( lMin ) ; // mp_i_cpucontroller->SetFreqAndVoltageFromFreq( //wFreq, // iter->m_wFreqInMHz , // mp_model->m_cpucoredata.m_stdsetvoltageandfreqDefault // //mp_model->m_cpucoredata.m_stdsetvoltageandfreqPossibleByCPU // //stdsetvoltageandfreq // , 0 ) ; // ::wxMilliSleep(100) ; // mp_i_cpucontroller->GetCurrentPstate( //wFreq, // wFreq , // fVolt // , 0 ) ; // if( wFreq == iter->m_wFreqInMHz ) // if( mp_model->m_cpucoredata.AddDefaultVoltageForFreq( fVolt, wFreq ) ) // RedrawEverything() ; // ++ iter ; // } // } } } //::wxMilliSleep() } //if( mp_i_cpucontroller ) } void MainFrame::OnLoadDetectInstableCPUcoreVoltageDynLib(wxCommandEvent & event) { #ifdef _WIN32 mp_wxx86infoandcontrolapp->LoadDetectInstableCPUcoreVoltageDynLib(); #endif } void MainFrame::OnUnloadDetectInstableCPUcoreVoltageDynLib(wxCommandEvent & event) { #ifdef _WIN32 mp_wxx86infoandcontrolapp->UnloadDetectInstableCPUcoreVoltageDynLib(); #endif } void MainFrame::OnMinimizeToSystemTray(wxCommandEvent & WXUNUSED(event)) { Hide() ; } void MainFrame::OnMoveMouse(wxMouseEvent & r_wxmouseevent) { LOGN( "begin") wxPoint wxpoint = r_wxmouseevent.GetPosition(); float fReferenceClockInMHz; const float fMultiplier = GetClosestMultiplier(wxpoint.x, fReferenceClockInMHz); const float fClosestFrequency = fMultiplier * fReferenceClockInMHz; const float fClosestVoltageToYcoordinate = GetClosestVoltageForYcoordinate( wxpoint.y); SetStatusText( wxString::Format( wxT("(%f Volt,%f MHz)"), fClosestVoltageToYcoordinate, fClosestFrequency ) ); LOGN( "end") } void MainFrame::OnLeftMouseButtonDown(wxMouseEvent & r_wxmouseevent) { const wxPoint & c_r_wxpointPos = r_wxmouseevent.GetPosition(); if( m_p_freqandvoltagesettingsdialog ) { float fVoltageInVolt = GetClosestVoltageForYcoordinate(c_r_wxpointPos.y); float fReferenceClockInMHz; float fMultiplier = GetClosestMultiplier(c_r_wxpointPos.x, fReferenceClockInMHz); m_p_freqandvoltagesettingsdialog->SetMultiplierSliderToClosestValue( fMultiplier); m_p_freqandvoltagesettingsdialog->HandleMultiplierValueChanged() ; BYTE byIndexForClosestVoltage = m_p_freqandvoltagesettingsdialog-> SetVoltageSliderToClosestValue(fVoltageInVolt) ; m_p_freqandvoltagesettingsdialog->ChangeVoltageSliderValue( byIndexForClosestVoltage) ; m_p_freqandvoltagesettingsdialog = NULL; SetCursor(wxNullCursor); } } void MainFrame::OnPauseService(wxCommandEvent & WXUNUSED(event)) { LOGN( //"OnPauseService" "begin") #ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE wxString wxstrMessageFromService; mp_wxx86infoandcontrolapp->PauseService(wxstrMessageFromService); // ::wxMessageBox( wxT("message from the service:\n") + wxstrMessageFromService // ) ; #endif //#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE } //void MainFrame::OnShowVoltageAndFrequencySettingsDialog( // wxCommandEvent & WXUNUSED(event) ) //{ // //} void MainFrame::OnStartService(wxCommandEvent & WXUNUSED(event)) { #ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL mp_wxx86infoandcontrolapp->StartService() ; #endif //#ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL } void MainFrame::OnStopService(wxCommandEvent & WXUNUSED(event)) { #ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL //ServiceBase::StopService( //mp_model->m_strServiceName.c_str() // "CPUcontrolService" ); mp_wxx86infoandcontrolapp->StopService() ; #endif //#ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL } void MainFrame::OnSysTrayIconClick(wxCommandEvent & WXUNUSED(event)) { ::wxMessageBox( wxT("OnSysTrayIconClick") ) ; } void MainFrame::OnAbout(wxCommandEvent& WXUNUSED(event)) { // wxString wxstrMessage ; // GetAboutMessage(wxstrMessage) ; // ::wxMessageBox( // wxstrMessage , // _T("About ") //_T(PROGRAM_NAME) // //+ mp_i_cpucontroller->mp_model->m_stdtstrProgramName // + mp_model->m_stdtstrProgramName // , // wxOK | wxICON_INFORMATION //, //// this // ); AboutDialog * p_aboutdialog = new AboutDialog( * mp_model, wxWidgets::getwxString( mp_model->m_stdtstrProgramName) ) ; p_aboutdialog->//Show() ; ShowModal(); p_aboutdialog->Destroy() ; } void MainFrame::OnAttachCPUcontrollerDLL (wxCommandEvent & event) { wxString wxstrExtension = wxT("") ; //Under Windows it returns ".dll" //wxstrExtension = wxDynamicLibrary::CanonicalizeName(wxstrExtension) ; wxstrExtension = wxDynamicLibrary::GetDllExt() ; //Get rid of the leading ".". wxstrExtension = wxstrExtension.Right( wxstrExtension.length() - 1 ) ; wxString wxstrCPUcontrollerDynLibFilePath = ::wxFileSelector( wxT("Select dynamic library for CPU info and/or control") , wxEmptyString //default_path , wxEmptyString //default_filename , wxstrExtension //default_extension , wxT("Dynamic Library files|*.") + wxstrExtension + wxT("|all files|*.*")//wildcard , wxFD_OPEN ) ; if ( ! wxstrCPUcontrollerDynLibFilePath.empty() ) { try { //wxDynLibCPUcontroller * p_wxdynlibcpucontroller = new //wxDynLibCPUcontroller( LOGN("before creating dyn lib controller object") DEBUGN("address of model: " << mp_model ) DEBUGN("address of cpucoredata: " << & mp_model->m_cpucoredata ) //Before creating a new controller the old one should be deleted. gp_cpucontrolbase->PossiblyDeleteCPUcontrollerDynLib() ; // gp_cpucontrolbase->mp_wxdynlibcpucontroller = new wxDynLibCPUcontroller( // wxstrFilePath // , mp_wxx86infoandcontrolapp->GetCPUaccess() // , mp_wxx86infoandcontrolapp // ) ; // mp_wxx86infoandcontrolapp->CreateDynLibCPUcontroller( //TODO ANSI string may fail if Chinese localization (->use wchar_t) std::string stdstrCPUcontrollerDynLibFilePath = wxWidgets::GetStdString( wxstrCPUcontrollerDynLibFilePath ) ; wxGetApp().m_wxstrCPUcontrollerDynLibFilePath = wxstrCPUcontrollerDynLibFilePath ; if( mp_wxx86infoandcontrolapp->m_dynlibhandler.CreateDynLibCPUcontroller( stdstrCPUcontrollerDynLibFilePath ) ) { LOGN("before setting dyn lib controller as CPU controller") mp_wxx86infoandcontrolapp->SetCPUcontroller( //p_wxdynlibcpucontroller // gp_cpucontrolbase->mp_wxdynlibcpucontroller mp_wxx86infoandcontrolapp->m_p_cpucontrollerDynLib ) ; LOGN("after setting dyn lib controller as CPU controller") CreateDynamicMenus() ; LOGN("after creating per CPU core menus " ) CPUcontrollerDynLibAttached(wxstrCPUcontrollerDynLibFilePath) ; //(Re-)start the "update view" timer. m_wxtimer.Start(m_dwTimerIntervalInMilliseconds); } } catch( const CPUaccessException & ex ) { ::wxMessageBox( wxT("Error message: ") + //wxString( //Use getwxString() to enable to compile with both unicode and ANSI. wxWidgets::getwxString( ex.m_stdstrErrorMessage) // ) , wxT("DLL error") ) ; } LOGN(//"OnAttachCPUcontrollerDLL " "end" ) } } void MainFrame::OnAttachCPUcoreUsageGetterDLL (wxCommandEvent & event) { wxString wxstrExtension = wxT("") ; //Under Windows it returns ".dll" //wxstrExtension = wxDynamicLibrary::CanonicalizeName(wxstrExtension) ; wxstrExtension = wxDynamicLibrary::GetDllExt() ; //Get rid of the leading ".". wxstrExtension = wxstrExtension.Right( wxstrExtension.length() - 1 ) ; wxString wxstrFilePath = ::wxFileSelector( wxT("Select CPU core usage getter dynamic library") , wxEmptyString , wxEmptyString , wxstrExtension , wxT("Dynamic Library files|*.") + wxstrExtension + wxT("|all files|*.*")//wildcard , wxFD_OPEN ) ; if ( ! wxstrFilePath.empty() ) { try { gp_cpucontrolbase->PossiblyDeleteCPUcoreUsageGetter() ; //wxDynLibCPUcontroller * p_wxdynlibcpucontroller = new wxDynLibCPUcontroller( // gp_cpucontrolbase->mp_wxdynlibcpucoreusagegetter = new // wxDynLibCPUcoreUsageGetter( // //std::string( // wxstrFilePath // //.//fn_str() // //c_str() ) // , mp_wxx86infoandcontrolapp->GetCPUaccess() // , * mp_cpucoredata // ) ; // mp_wxx86infoandcontrolapp->CreateDynLibCPUcoreUsageGetter( std::string stdstr = wxWidgets::GetStdString( wxstrFilePath) ; if( mp_wxx86infoandcontrolapp->m_dynlibhandler.CreateDynLibCPUcoreUsageGetter( stdstr ) ) { mp_wxx86infoandcontrolapp->//SetCPUcoreUsageGetter( //p_wxdynlibcpucontroller //mp_wxdynlibcpucoreusagegetter ) ; mp_cpucoreusagegetter = //gp_cpucontrolbase->mp_wxdynlibcpucoreusagegetter ; mp_wxx86infoandcontrolapp->m_p_cpucoreusagegetterDynLib ; //CreateDynamicMenus() ; CPUcoreUsageGetterAttached(wxstrFilePath) ; //TODO necessary? (because the CPU core number got from the usage //getter may change ) RedrawEverything() ; } } catch( CPUaccessException & ex ) { wxMessageBox( wxT("Error message: ") + //wxString( //Use getwxString() to enable to compile with both unicode and ANSI. wxWidgets::getwxString( ex.m_stdstrErrorMessage) , wxT("DLL error") ) ; } } } void MainFrame::CPUcontrollerDynLibAttached(const wxString & wxstrFilePath ) { // if( ! mp_ar_voltage_and_multi ) // mp_ar_voltage_and_multi = new VoltageAndMulti[ // mp_model->m_cpucoredata.m_byNumberOfCPUCores ] ; mp_wxmenuFile->Enable( ID_DetachCPUcontrollerDynamicLibrary , //const bool enable true ) ; mp_wxmenuFile->SetLabel( ID_DetachCPUcontrollerDynamicLibrary , wxT( //"detach" //"unload" is a better word because it expresses that the Dynamic //library is removed from the memory(?) "unload" " CPU controller ") + wxstrFilePath ) ; mp_wxmenuFile->Enable( ID_SetCPUcontrollerDynLibForThisCPU, true ) ; //If both CPU controller and the CPU usage getter exist, DVFS is possible. if( mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter ) m_p_wxmenuGUI->Enable( ID_EnableOrDisableOwnDVFS , //const bool enable true ) ; } void MainFrame::CPUcontrollerDeleted() { mp_i_cpucontroller = NULL; PossiblyReleaseMemForCPUcontrollerUIcontrols() ; //mp_model->m_cpucoredata.ClearCPUcontrollerSpecificAtts() ; mp_wxmenuFile->Enable( ID_DetachCPUcontrollerDynamicLibrary , //const bool enable false ) ; m_p_wxmenuGUI->Enable( ID_EnableOrDisableOwnDVFS , //const bool enable false ) ; } void MainFrame::CPUcoreUsageGetterAttached(const wxString & wxstrFilePath) { mp_wxmenuFile->Enable( ID_DetachCPUusageGetterDynLib , //const bool enable true ) ; mp_wxmenuFile->SetLabel( ID_DetachCPUusageGetterDynLib , wxT( //"detach" //"unload" is a better word because it expresses that the Dynamic //library is removed from the memory(?) "unload " " core usage getter ") + wxstrFilePath ) ; if( mp_wxx86infoandcontrolapp->GetCPUcontroller() ) m_p_wxmenuGUI->Enable( ID_EnableOrDisableOwnDVFS , //const bool enable true ) ; //TODO do the folowing in base class (CPUcontrolBase) WORD wNumberOfLogicalCPUcores = mp_wxx86infoandcontrolapp-> mp_cpucoreusagegetter->GetNumberOfLogicalCPUcores() ; if( wNumberOfLogicalCPUcores == 0 && ! mp_cpucoredata->m_byNumberOfCPUCores ) { wNumberOfLogicalCPUcores = 1 ; LOGN("setting # CPU cores to " << wNumberOfLogicalCPUcores) //TODO correct CPU core number //Set -> allocate array for OnPaint() mp_cpucoredata->SetCPUcoreNumber(wNumberOfLogicalCPUcores) ; } } void MainFrame::CPUcoreUsageGetterDeleted() { mp_wxmenuFile->Enable( ID_DetachCPUusageGetterDynLib , //const bool enable false ) ; m_p_wxmenuGUI->Enable( ID_EnableOrDisableOwnDVFS , //const bool enable false ) ; } void MainFrame::OnDetachCPUcontrollerDLL (wxCommandEvent & event) { gp_cpucontrolbase->PossiblyDeleteCPUcontrollerDynLib() ; } void MainFrame::OnDetachCPUcoreUsageGetterDLL (wxCommandEvent & event) { gp_cpucontrolbase->PossiblyDeleteCPUcoreUsageGetter() ; } void MainFrame::OnHighLoadThread( wxCommandEvent & //WXUNUSED(wxevent) wxevent ) { // WORD wEventID = wxevent.GetId() ; #ifdef COMPILE_WITH_CALC_THREAD // HighLoadThreadAttributes p_hlta = (HighLoadThreadAttributes * ) // m_stdmapwxuicontroldata.find( wEventID )->second ; CalculationThread * p_ct = (CalculationThread *) m_stdmapwxuicontroldata.find( wEventID )->second ; if( p_ct ) p_ct->Execute() ; #endif //#ifdef COMPILE_WITH_CALC_THREAD } void MainFrame::OnOwnDynFreqScaling( wxCommandEvent & //WXUNUSED(wxevent) wxevent ) { mp_wxx86infoandcontrolapp->StartDynamicVoltageAndFrequencyScaling() ; } void MainFrame::Show1VoltnFreqSettingsDialogForEveryCPUcore(wxCommandEvent & wxevent ) { WORD wEventID = wxevent.GetId() ; //wxCPUcoreID * p_wxcpucoreid = (wxCPUcoreID *) //wxevent.m_callbackUserData ; // & m_stdmapwxuicontroldata.find( wxevent.GetId() )->second ; //wxCPUcoreID & r_wxcpucoreid = (wxCPUcoreID &) //wxevent.m_callbackUserData ; // m_stdmapwxuicontroldata.find( wxevent.GetId() )->second ; //const wxObject & wxobj = //wxevent.m_callbackUserData ; // m_stdmapwxuicontroldata.find( wxevent.GetId() )->second ; //wxCPUcoreID & r_wxcpucoreid2 = (wxCPUcoreID &) wxobj ; //const wxCPUcoreID * p_wxcpucoreid2 = (const wxCPUcoreID *) & wxobj ; //std::map <WORD, wxObject> :: iterator iter = // m_stdmapwxuicontroldata.find( wxevent.GetId() ) ; //wxCPUcoreID wxcpucoreid = (wxCPUcoreID ) iter->second ; // wxCPUcoreID * p_wxcpucoreid = (wxCPUcoreID *) //wxevent.m_callbackUserData ; // //& // m_stdmapwxuicontroldata.find( wEventID )->second ; SpecificCPUcoreActionAttributes * p = (SpecificCPUcoreActionAttributes *) m_stdmapwxuicontroldata.find( wEventID )->second ; BYTE byCoreID = //p_wxcpucoreid->m_byID p->m_byCoreID ; //BYTE byCoreID = 0 ; if( m_arp_freqandvoltagesettingdlg[byCoreID] ) m_arp_freqandvoltagesettingdlg[byCoreID]->Show(true); else { //If created as local vaiable on stack the dialog would disappear //immediately. m_arp_freqandvoltagesettingdlg[byCoreID] = new FreqAndVoltageSettingDlg( this , mp_i_cpucontroller , byCoreID ); //Allocating succeeded. if( m_arp_freqandvoltagesettingdlg[byCoreID] ) m_arp_freqandvoltagesettingdlg[byCoreID]->Show(true); } } void MainFrame::OnVoltageAndFrequencySettingsDialog( wxCommandEvent & //WXUNUSED(event) wxevent ) { LOGN(/*"OnVoltageAndFrequencySettingsDialog"*/ "begin" ) //May be NULL at startup. if( mp_i_cpucontroller ) { #ifdef ONE_P_STATE_DIALOG_FOR_EVERY_CPU_CORE Show1VoltnFreqSettingsDialogForEveryCPUcore(); #else FreqAndVoltageSettingDlg * p_freqandvoltagesettingdlg = new FreqAndVoltageSettingDlg( this , mp_i_cpucontroller , 0 ); //Allocating succeeded. if( p_freqandvoltagesettingdlg ) { #ifdef USE_CRIT_SEC_FOR_FREQ_AND_VOLT_SETTINGS_DLG_CONTAINER m_crit_secVoltAndFreqDlgs.Enter(); m_stdvec_p_freqandvoltagesettingdlg.push_back( p_freqandvoltagesettingdlg) ; m_crit_secVoltAndFreqDlgs.Leave(); #endif //#ifdef USE_CRIT_SEC_FOR_FREQ_AND_VOLT_SETTINGS_DLG_CONTAINER p_freqandvoltagesettingdlg->Show(true); LOGN( "after showing the volt n freq dialog") } #endif } } void MainFrame::OnQuit(wxCommandEvent& //WXUNUSED(event) event) { Close(TRUE); } void MainFrame::DrawAllPossibleOperatingPoints( wxDC & r_wxdcDrawOn ) { //May be NULL at startup. if( mp_i_cpucontroller ) { //float fCurrentVoltageInVolt ; //WORD wXcoordinate ; //WORD wYcoordinate ; // WORD wMaxFreqInMHz = // mp_i_cpucontroller->mp_model->m_cpucoredata. // m_wMaxFreqInMHz ; // WORD wCurrentFreqInMHz = // mp_i_cpucontroller->mp_model->m_cpucoredata.m_wMaxFreqInMHz ; // BYTE byMinVoltageID = mp_cpucoredata->m_byMinVoltageID ; // BYTE byMaxVoltageID = mp_cpucoredata->m_byMaxVoltageID ; //BYTE byCurrentVoltageID ; //do //{ // for( byCurrentVoltageID = byMinVoltageID ; // byCurrentVoltageID <= byMaxVoltageID ; ++ byCurrentVoltageID ) // { // fCurrentVoltageInVolt = PState::GetVoltageInVolt( byCurrentVoltageID ) ; // wXcoordinate = // m_wXcoordOfBeginOfYaxis + // (float) wCurrentFreqInMHz / // (float) wMaxFreqInMHz * m_wDiagramWidth ; // wYcoordinate = // m_wDiagramHeight - fCurrentVoltageInVolt // / m_fMaxVoltage * m_wDiagramHeight ; // r_wxdcDrawOn.DrawLine( // //wCurrentXcoordinateInDiagram + m_wXcoordOfBeginOfYaxis, // wXcoordinate // , wYcoordinate // , //wCurrentXcoordinateInDiagram + m_wXcoordOfBeginOfYaxis // wXcoordinate // //"+ 1" because: http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcdrawline: // //"Note that the point (x2, y2) is not part of the line and is // //not drawn by this function (this is consistent with the // //behaviour of many other toolkits)." // + 1 // , //(200-fVoltage*100) // wYcoordinate // //"+ 1" because: http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcdrawline: // //"Note that the point (x2, y2) is not part of the line and is // //not drawn by this function (this is consistent with the // //behaviour of many other toolkits)." // + 1 // ) ; // } // mp_cpucontroller->GetNearestHigherPossibleFreqInMHz( // wCurrentFreqInMHz + 1 ) ; //} while( wCurrentFreqInMHz != mp_cpucoredata->m_wMaxFreqInMHz ) ; } } void MainFrame::DrawPerformanceStatesCrosses( wxDC & r_wxdc , const std::set<VoltageAndFreq> & cr_stdsetmaxvoltageforfreq , const wxColor * cp_wxcolor ) { LOGN(//"DrawPerformanceStatesCrosses " "begin") const wxPen wxpenCurrent = r_wxdc.GetPen() ; #ifdef _DEBUG const wxColor wxcolor = wxpenCurrent.GetColour() ; int nPenWidth = wxpenCurrent.GetWidth() ; #endif std::set<VoltageAndFreq>::const_iterator iter = cr_stdsetmaxvoltageforfreq.begin() ; while( iter != cr_stdsetmaxvoltageforfreq.end() ) { DrawVoltageFreqCross( r_wxdc , iter->m_fVoltageInVolt , iter->m_wFreqInMHz , cp_wxcolor ) ; ++ iter ; } #ifdef _DEBUG if( nPenWidth == 3 ) nPenWidth = 3 ; #endif //Restore the pen. r_wxdc.SetPen( wxpenCurrent ) ; } void MainFrame::DrawDiagramScale( wxDC & r_wxdc , //std::set<MaxVoltageForFreq>::iterator & iterstdsetmaxvoltageforfreq std::set<VoltageAndFreq>::iterator & r_iterstdsetvoltageandfreq ) { LOGN_DEBUG(//"DrawDiagramScale " "mp_i_cpucontroller:" << mp_i_cpucontroller) LOGN(//"DrawDiagramScale " "m_wMaximumCPUcoreFrequency:" << m_wMaximumCPUcoreFrequency) //May be NULL at startup. if( //mp_i_cpucontroller m_wMaximumCPUcoreFrequency ) { // WORD wXcoordinate = 0, wYcoordinate = 0; //float fMinVoltage ; //float fMaxMinusMinVoltage ; std::set<VoltageAndFreq> & r_stdsetvoltageandfreq = //mp_i_cpucontroller-> mp_model->m_cpucoredata.m_stdsetvoltageandfreqDefault ; //Prevents a concurrent modification e.g. by // "mp_model->m_cpucoredata.AddDefaultVoltageForFreq(...)" // in wxDynLibCPUcontroller::GetCurrentVoltageAndFrequency(...) wxCriticalSectionLocker wxcriticalsectionlockerVoltageAndFreq( mp_model->m_cpucoredata.m_wxcriticalsection) ; // std::set<WORD> setRightEndOfFreqString ; r_iterstdsetvoltageandfreq = r_stdsetvoltageandfreq.begin() ; #ifdef _DEBUG const wxPen & wxpenCurrent = r_wxdc.GetPen() ; const wxColor wxcolor = wxpenCurrent.GetColour() ; // int nPenWidth = wxpenCurrent.GetWidth() ; #endif LOGN( //"DrawDiagramScale " "m_wDiagramWidth:" << m_wDiagramWidth ) //fMinVoltage = mp_i_cpucontroller->GetMinimumVoltageInVolt() ; //fMaxMinusMinVoltage = m_fMaxVoltage - fMinVoltage ; // for( ; r_iterstdsetvoltageandfreq != // //mp_i_cpucontroller->mp_model-> // //m_setmaxvoltageforfreq.end() ; //++ iterstdvecmaxvoltageforfreq // r_stdsetvoltageandfreq.end() ; // //++ iterstdsetmaxvoltageforfreq // ++ r_iterstdsetvoltageandfreq // ) // { //// DrawFrequency( //// r_wxdc, //// //wFrequencyInMHz //// r_iterstdsetvoltageandfreq->m_wFreqInMHz , //// wxcoordWidth , //// wxcoordHeight , //// wLeftEndOfCurrFreqText , //// wxstrFreq , //// wXcoordinate , //// wYcoordinate , //// r_iterstdmapYcoord2RightEndOfFreqString , //// stdmapYcoord2RightEndOfFreqString , //// r_iterstdmap_ycoord2rightendoffreqstringToUse //// ) ; // wXcoordinate = GetXcoordinateForFrequency( r_iterstdsetvoltageandfreq-> // m_wFreqInMHz) ; //// wYcoordinate = r_iterstdmap_ycoord2rightendoffreqstringToUse->first ; // LOGN( "DrawDiagramScale //x coord:" << wXcoordinate // << "y coord:" << wYcoordinate ) // //mapRightEndOfFreqString2yCoord.insert( // // std::pair<WORD,WORD> ( wLeftEndOfCurrFreqText + wxcoordWidth, wYcoordinate ) ) ; // //Draw vertical line for current frequency mark. // //p_wxpaintdc->DrawLine(wXcoordinate, 0, wXcoordinate, wDiagramHeight) ; // //wxmemorydc.DrawLine(wXcoordinate, 0, wXcoordinate, wDiagramHeight) ; // r_wxdc.DrawLine(wXcoordinate, 0, wXcoordinate, m_wDiagramHeight // //wYcoordinate // ) ; //// DrawVoltage( //// r_wxdc , //// ( * r_iterstdsetvoltageandfreq).m_fVoltageInVolt //// ) ; // //Draw horizontal line for current voltage mark. // //p_wxpaintdc->DrawLine(wXcoordOfBeginOfYaxis, wYcoordinate, // //wxmemorydc.DrawLine(wXcoordOfBeginOfYaxis, wYcoordinate, // r_wxdc.DrawLine(m_wXcoordOfBeginOfYaxis, wYcoordinate, // m_wDiagramWidth + m_wXcoordOfBeginOfYaxis, wYcoordinate ) ; // } } //if( m_wMaximumCPUcoreFrequency ) // else //m_wMaximumCPUcoreFrequency = 0 // { // } WORD wMaximumYcoordinateForFrequency = 0; WORD wMaximumHeightForFrequencyMarks = 0; wxCoord wxcoordTextWidth, wxcoordTextHeight; r_wxdc.GetTextExtent( wxT("I") , & wxcoordTextWidth , & wxcoordTextHeight //, wxCoord *descent = NULL, wxCoord *externalLeading = NULL, wxFont *font = NULL ) ; // int nHalfTextHeightInPixels = wxcoordTextHeight / 2; if( mp_i_cpucontroller->m_fReferenceClockInMHz ) { //Do not draw: only calculate the max. (text) height of the frequency //scale. DrawFrequencyMarksAndLines(r_wxdc, wMaximumYcoordinateForFrequency); wMaximumHeightForFrequencyMarks = wMaximumYcoordinateForFrequency - m_wDiagramHeight //For the 1st line. + wxcoordTextHeight; } //->line for min./ lowest voltage/ 0V directly above frequency marks. m_wDiagramHeight += 50 - wMaximumHeightForFrequencyMarks //- //nHalfTextHeightInPixels ; DrawVoltageScale(r_wxdc); // //The frequency should start under min. voltage. // m_wDiagramHeight += nHalfTextHeightInPixels; if( mp_i_cpucontroller->m_fReferenceClockInMHz ) { //Now do really draw. DrawFrequencyMarksAndLines(r_wxdc, wMaximumYcoordinateForFrequency); } LOGN(//"DrawDiagramScale " "end") } void MainFrame::DrawLowestStableVoltageCurve( wxDC & wxdc , float fMaxVoltage ) { //May be NULL at startup. if( mp_i_cpucontroller ) { std::set<VoltageAndFreq>::const_iterator ciLower = mp_cpucoredata->m_stdsetvoltageandfreqLowestStable.begin() ; ////because of the "MaxVoltageForFreq::<" operator the set is sorted in ////DESCENDING order. ////Points BEYOND the last element now. //mp_cpucoredata->m_stdsetvoltageandfreqLowestStable.end() ; ////Now it should point to the last element. //-- ciLower ; if( ciLower != mp_cpucoredata->m_stdsetvoltageandfreqLowestStable.end() ) { std::set<VoltageAndFreq>::const_iterator ciHigher = ciLower ; ciHigher ++ ; //ciHigher -- ; if( ciHigher != mp_cpucoredata->m_stdsetvoltageandfreqLowestStable.end() ) { float fVoltage ; WORD wYcoordinate ; WORD wMaxFreqInMHz = //mp_i_cpucontroller->mp_model->m_cpucoredata.m_wMaxFreqInMHz ; m_wMaximumCPUcoreFrequency ; WORD wCurrentFreqInMHz ; for( WORD wCurrentXcoordinateInDiagram = //wXcoordOfBeginOfYaxis //0 //Begin with 1 to avoid div by zero. 1 ; wCurrentXcoordinateInDiagram < //wxcoordWidth m_wDiagramWidth ; ++ wCurrentXcoordinateInDiagram ) { wCurrentFreqInMHz = //Explicit cast to avoid (g++) warning. (WORD) ( (float) wMaxFreqInMHz / ( (float) m_wDiagramWidth / (float) wCurrentXcoordinateInDiagram ) ) ; if( ciHigher->m_wFreqInMHz < wCurrentFreqInMHz ) { std::set<VoltageAndFreq>::const_iterator ciBeyondHigher = ciHigher ; ++ ciBeyondHigher ; if( ciBeyondHigher != mp_cpucoredata-> m_stdsetvoltageandfreqLowestStable.end() ) { ++ ciLower ; ++ ciHigher ; //-- ciLower ; //-- ciHigher ; } } //If current freq is in between. if( ciHigher != mp_cpucoredata->m_stdsetvoltageandfreqLowestStable.end() && ciLower->m_wFreqInMHz <= wCurrentFreqInMHz && ciHigher->m_wFreqInMHz >= wCurrentFreqInMHz ) { //mp_i_cpucontroller->GetInterpolatedVoltageFromFreq( // wCurrentFreqInMHz // , *ciHigher // , *ciLower // , fVoltage // ) ; //mp_i_cpucontroller-> GetInterpolatedVoltageFromFreq( wCurrentFreqInMHz , fVoltage , mp_cpucoredata->m_stdsetvoltageandfreqLowestStable ) ; wYcoordinate = GetYcoordinateForVoltage(fVoltage); //p_wxpaintdc->DrawLine( wxdc.DrawLine( wCurrentXcoordinateInDiagram + m_wXcoordOfBeginOfYaxis, //wDiagramHeight - //fVoltage/ (*iterstdvecmaxvoltageforfreq).m_fVoltageInVolt //* wDiagramHeight , wYcoordinate , wCurrentXcoordinateInDiagram + m_wXcoordOfBeginOfYaxis //"+ 1" because: http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcdrawline: //"Note that the point (x2, y2) is not part of the line and is //not drawn by this function (this is consistent with the //behaviour of many other toolkits)." + 1 , wYcoordinate //"+ 1" because: http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcdrawline: //"Note that the point (x2, y2) is not part of the line and is //not drawn by this function (this is consistent with the //behaviour of many other toolkits)." + 1 ) ; } }// for } } } } void MainFrame::DrawVoltageGraph( //wxPaintDC * p_wxpaintdc wxDC & wxdc // , WORD wDiagramWidth // , WORD wDiagramHeight , float fMaxVoltage // , WORD wXcoordOfBeginOfYaxis , const std::set<VoltageAndFreq> & c_r_stdsetvoltageandfreq ) { LOGN(//"DrawOvervoltageProtectionCurve " "begin" ) //May be NULL at startup. if( mp_i_cpucontroller //and ref clock <> 0 && mp_i_cpucontroller->m_fReferenceClockInMHz ) { float fVoltage ; WORD wYcoordinate ; // std::set<float> & r_stdset_fMultipliers = mp_model->m_cpucoredata. // m_stdset_floatAvailableMultipliers ; // std::set<float>::const_reverse_iterator c_iter_stdset_fMultipliers = // r_stdset_fMultipliers.rbegin() ; // if( c_iter_stdset_fMultipliers != r_stdset_fMultipliers.rend() ) // float fMaxMulti = mp_model->m_cpucoredata.GetMaximumMultiplier() ; // if( fMaxMulti ) { WORD wMaxFreqInMHz = //mp_i_cpucontroller-> //mp_model->m_cpucoredata.m_wMaxFreqInMHz ; //max. freq = max. multi * ref clock //*c_iter_stdset_fMultipliers //fMaxMulti * mp_i_cpucontroller->m_fReferenceClockInMHz ; m_wMaximumCPUcoreFrequency ; for( WORD wCurrentXcoordinateInDiagram = //wXcoordOfBeginOfYaxis //0 //Begin with 1 to avoid div by zero. 1 ; wCurrentXcoordinateInDiagram < //wxcoordWidth m_wDiagramWidth ; ++ wCurrentXcoordinateInDiagram ) { //mp_i_cpucontroller-> GetInterpolatedVoltageFromFreq( //Explicit cast to avoid (g++) compiler warning. (WORD) ( (float) wMaxFreqInMHz / ( (float) m_wDiagramWidth / (float) wCurrentXcoordinateInDiagram ) ) , fVoltage , c_r_stdsetvoltageandfreq ) ; wYcoordinate = GetYcoordinateForVoltage(fVoltage); //p_wxpaintdc->DrawLine( //TODO draw lines from last point to current point. So gaps are avoided if //the angle is > 45 degrees wxdc.DrawLine( wCurrentXcoordinateInDiagram + m_wXcoordOfBeginOfYaxis, //wDiagramHeight - //fVoltage/ (*iterstdvecmaxvoltageforfreq).m_fVoltageInVolt //* wDiagramHeight , wYcoordinate , wCurrentXcoordinateInDiagram + m_wXcoordOfBeginOfYaxis //"+ 1" because: //http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcdrawline: //"Note that the point (x2, y2) is not part of the line and is //not drawn by this function (this is consistent with the //behaviour of many other toolkits)." + 1 , wYcoordinate //"+ 1" because: //http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcdrawline: //"Note that the point (x2, y2) is not part of the line and is //not drawn by this function (this is consistent with the //behaviour of many other toolkits)." + 1 ) ; } } } //if( mp_i_cpucontroller ) } //Purpose: the output for _all_ cores should be (left-)aligned. //So the max. width for the attribute values of the same attribute type //(MHz,...) needs to be known. void MainFrame::StoreCurrentVoltageAndFreqInArray( wxDC & r_wxdc // VoltageAndFreq * & r_ar_voltageandfreq , wxString r_ar_wxstrFreqInMHz [] , wxString r_ar_wxstrVoltageInVolt [] // , float r_ar_fTempInCelsius [] , wxString r_ar_wxstrTempInCelsius [] , I_CPUcontroller * p_cpucontroller ) { LOGN(//"StoreCurrentVoltageAndFreqInArray" "begin") if( //mp_i_cpucontroller p_cpucontroller ) { int nWidth ; PerCPUcoreAttributes * arp_percpucoreattributes = mp_model->m_cpucoredata. m_arp_percpucoreattributes ; // WORD wFreqInMHz = 0 ; wxCoord wxcoordWidth, wxcoordHeight ; wxString wxstr ; wxSize wxsize ; float fVoltageInVolt = 0.0f ; float fTempInCelsius ; float fThrottleLevel; float fMultiplier ; float fReferenceClockInMHz ; WORD wFrequencyInMHz ; // WORD wCoreID ; //mp_cpucoredata-> //respect # of cpu cores for( fastestUnsignedDataType CPUcoreID = 0 ; CPUcoreID < mp_cpucoredata->m_byNumberOfCPUCores ; ++ CPUcoreID ) { // wFreqInMHz = 0 ; // fVoltageInVolt = 0.0f ; // if( mp_i_cpucontroller->GetCurrentPstate(wFreqInMHz, fVoltageInVolt, // byCPUcoreID ) if( //mp_i_cpucontroller->GetCurrentVoltageAndFrequency( p_cpucontroller->//GetCurrentVoltageAndFrequency( //Storing in the array is needed for showing the multis in the task //bar icon. GetCurrentVoltageAndFrequencyAndStoreValues( // fVoltageInVolt // , fMultiplier // , fReferenceClockInMHz //, CPUcoreID ) ) { fVoltageInVolt = arp_percpucoreattributes[CPUcoreID].m_fVoltageInVolt; fThrottleLevel = arp_percpucoreattributes[CPUcoreID].m_fThrottleLevel; fMultiplier = arp_percpucoreattributes[CPUcoreID].m_fMultiplier; fReferenceClockInMHz = arp_percpucoreattributes[CPUcoreID]. m_fReferenceClockInMhz; wFrequencyInMHz = (WORD) ( fReferenceClockInMHz * fMultiplier ) ; // arp_percpucoreattributes[CPUcoreID].GetFreqInMHz(); if( wFrequencyInMHz > m_wMaximumCPUcoreFrequency ) m_wMaximumCPUcoreFrequency = wFrequencyInMHz ; LOGN("fMultiplier:" << fMultiplier ) mp_ar_voltage_and_multi[CPUcoreID ].m_fMultiplier = fMultiplier ; mp_ar_voltage_and_multi[CPUcoreID ].m_fVoltageInVolt = fVoltageInVolt; if(fThrottleLevel == -1.0f) r_ar_wxstrFreqInMHz[ CPUcoreID ] = wxT("?*"); else r_ar_wxstrFreqInMHz[ CPUcoreID ] = wxString::Format( wxT("%.3f*"), fThrottleLevel); { if( fMultiplier == 0.0f) r_ar_wxstrFreqInMHz[ CPUcoreID ] += wxString::Format( wxT("?*%.3fMHz=? MHz "), fThrottleLevel, fReferenceClockInMHz); else if( fReferenceClockInMHz == 0.0f ) r_ar_wxstrFreqInMHz[ CPUcoreID ] += wxString::Format( wxT("%.3f*?MHz=? MHz "), fThrottleLevel, fMultiplier); else { if(fThrottleLevel == -1.0f) r_ar_wxstrFreqInMHz[ CPUcoreID ] += wxString::Format( //Use wxT() to enable to compile with both unicode and ANSI. // wxT("%u MHz "), // wFreqInMHz ) ; wxT("%.3f*%.3fMHz=%.3f?MHz "), // wxT("%.3g*%.3gMHz=%.3gMHz "), // fThrottleLevel, fMultiplier , fReferenceClockInMHz , fMultiplier * fReferenceClockInMHz ) ; else r_ar_wxstrFreqInMHz[ CPUcoreID ] += wxString::Format( //Use wxT() to enable to compile with both unicode and ANSI. // wxT("%u MHz "), // wFreqInMHz ) ; wxT("%.3f*%.3fMHz=%.3fMHz "), // wxT("%.3g*%.3gMHz=%.3gMHz "), // fThrottleLevel, fMultiplier , fReferenceClockInMHz , fThrottleLevel * fMultiplier * fReferenceClockInMHz ) ; } } LOGN( "frequency string:\"" << wxWidgets::GetStdString( r_ar_wxstrFreqInMHz[ CPUcoreID ]) << "\"") // LOGN("r_ar_wxstrFreqInMHz[ CPUcoreID ]:" << GetStdString( // r_ar_wxstrFreqInMHz[ CPUcoreID ]) ) // wxstr = wxString::Format( wxT("%u"), wFreqInMHz ) ; // wxsize = r_wxdc.GetTextExtent(//wxstr // r_ar_wxstrFreqInMHz[ CPUcoreID ] ) ; // nWidth = wxsize.GetWidth() ; r_wxdc.GetTextExtent( r_ar_wxstrFreqInMHz[ CPUcoreID ] , & wxcoordWidth, & wxcoordHeight ) ; nWidth = wxcoordWidth ; //The max freq text widthcan not easyily be determined at startup: //if e.g. the documented max. multiplier is "10" and the reference //clock is 100MHz, then the freq can also get > 1000 MHz because the //reference clock can be a bittle higher frequented or increased via // BIOS etc. //So it's best to determine it at runtime. if( nWidth > m_wMaxFreqInMHzTextWidth ) m_wMaxFreqInMHzTextWidth = nWidth ; if( fVoltageInVolt == 0.0 ) r_ar_wxstrVoltageInVolt[ CPUcoreID ] = wxT("?V ") ; else r_ar_wxstrVoltageInVolt[ CPUcoreID ] = wxString::Format( //Use wxT() to enable to compile with both unicode and ANSI. wxT("%.4f" //"%.3g" "V "), fVoltageInVolt ) ; wxsize = r_wxdc.GetTextExtent(//wxstr r_ar_wxstrVoltageInVolt[ CPUcoreID ] ) ; nWidth = wxsize.GetWidth() ; if( nWidth > m_wMaxVoltageInVoltTextWidth ) m_wMaxVoltageInVoltTextWidth = nWidth ; // r_ar_voltageandfreq[byCPUcoreID].m_fVoltageInVolt = fVoltageInVolt ; // r_ar_voltageandfreq[byCPUcoreID].m_wFreqInMHz = wFreqInMHz ; } else { LOGN_ERROR("error getting the current CPU core voltage and frequency " "CPU controller via the CPU controller->not using their results" ) } fTempInCelsius = //mp_i_cpucontroller-> p_cpucontroller-> GetTemperatureInCelsius(CPUcoreID) ; s_arfTemperatureInDegreesCelsius[ CPUcoreID ] = fTempInCelsius ; // switch(fTempInCelsius) // { // case __FLT_MIN__ : // r_ar_wxstrTempInCelsius[ CPUcoreID ] = wxT("?°C "); // break; // case CPU_TEMP_IS_CRITICAL: // r_ar_wxstrTempInCelsius[ CPUcoreID ] = wxT("<C "); // break; // case CPU_TEMP_IS_BELOW_CRITICAL: // r_ar_wxstrTempInCelsius[ CPUcoreID ] = wxT(">C "); // break; // default: // //http://www.cplusplus.com/reference/clibrary/cstdio/printf/: // //"Use the shorter of %e or %f" // //-> if "%.3g" (max 3 digits after decimal point): // // for "60.0" it is "60" // // for "60.1755" it is "60.175" // r_ar_wxstrTempInCelsius[ CPUcoreID ] = wxString::Format( // //Use wxT() to enable to compile with both unicode and ANSI. // wxT("%.3g°C "), // fTempInCelsius ) ; // } wxGetApp().GetTemperatureString(fTempInCelsius, r_ar_wxstrTempInCelsius[ CPUcoreID ]); r_ar_wxstrTempInCelsius[ CPUcoreID ] += wxT(" "); // LOGN("r_ar_wxstrTempInCelsius[ CPUcoreID ]:" << GetStdString( // r_ar_wxstrTempInCelsius[ CPUcoreID ]) ) wxsize = r_wxdc.GetTextExtent(//wxstr r_ar_wxstrTempInCelsius[ CPUcoreID ] ) ; nWidth = wxsize.GetWidth() ; if( nWidth > m_wMaxTemperatureTextWidth ) m_wMaxTemperatureTextWidth = nWidth ; } } LOGN( "end") } void MainFrame::DrawCPUcoreIDs( wxDC & r_wxdc, wxCoord & wxcoordX, //must be call by reference wxCoord wxcoordTextHeight ) { LOGN("before drawing the CPU core numbers") static wxString wxstr; int nWidth ; wxSize wxsize ; WORD wMaxCoreNumberTextWidth = 0 ; for ( WORD wCoreID = 0 ; wCoreID < mp_cpucoredata->m_byNumberOfCPUCores ; ++ wCoreID ) { wxstr = wxString::Format( //We need a _T() macro (wide char-> L"", char->"") for EACH //line to make it compatible between char and wide char. wxT("core%u:") , wCoreID ) ; wxsize = r_wxdc.GetTextExtent( wxstr ) ; nWidth = wxsize.GetWidth() ; if( nWidth > wMaxCoreNumberTextWidth ) wMaxCoreNumberTextWidth = nWidth ; r_wxdc.DrawText( wxstr , wxcoordX //x-coord , wCoreID * //m_wTextHeight //y-coord wxcoordTextHeight ) ; } wxcoordX += wMaxCoreNumberTextWidth ; } void MainFrame::DrawCurrentCPUcoreFrequency( wxDC & r_wxdc, const wxString ar_wxstrFreqInMHz [], wxCoord & wxcoordX, wxCoord wxcoordTextHeight ) { LOGN("before drawing the CPU core frequency") for ( fastestUnsignedDataType wCoreID = 0 ; wCoreID < mp_cpucoredata->m_byNumberOfCPUCores ; ++ wCoreID ) { #ifdef _DEBUG const wxString & r_wxstr = ar_wxstrFreqInMHz[ wCoreID ] ; //Avoid g++ warning "unused variable ‘r_wxstr’" SUPPRESS_UNUSED_VARIABLE_WARNING(r_wxstr) #endif r_wxdc.DrawText( ar_wxstrFreqInMHz[ wCoreID ] , wxcoordX //x-coord , wCoreID * //m_wTextHeight //y-coord wxcoordTextHeight ) ; } wxcoordX += m_wMaxFreqInMHzTextWidth ; } void MainFrame::DrawCurrentCPUcoreTemperature( wxDC & r_wxdc, const wxString ar_wxstrCPUcoreTemperature [], wxCoord & wxcoordX, wxCoord wxcoordTextHeight ) { for ( WORD wCoreID = 0 ; wCoreID < mp_cpucoredata->m_byNumberOfCPUCores ; ++ wCoreID ) { r_wxdc.DrawText( ar_wxstrCPUcoreTemperature[ wCoreID ] , wxcoordX //x-coord , wCoreID * //m_wTextHeight //y-coord wxcoordTextHeight ) ; } wxcoordX += m_wMaxTemperatureTextWidth ; } void MainFrame::DrawCPUcoreVoltage( wxDC & r_wxdc, const wxString ar_wxstrCPUcoreVoltageInVolt [], wxCoord & wxcoordX, wxCoord wxcoordTextHeight ) { LOGN("before drawing the CPU core voltage") for ( WORD wCoreID = 0 ; wCoreID < mp_cpucoredata->m_byNumberOfCPUCores ; ++ wCoreID ) { r_wxdc.DrawText( ar_wxstrCPUcoreVoltageInVolt[ wCoreID ] , wxcoordX //x-coord , wCoreID * //m_wTextHeight //y-coord wxcoordTextHeight ) ; } wxcoordX += m_wMaxVoltageInVoltTextWidth ; } void MainFrame::DrawCPUcoreUsages( wxDC & r_wxdc, const ICPUcoreUsageGetter * p_cpucoreusagegetter, wxCoord wxcoordX, wxCoord wxcoordTextHeight ) { //mp_i_cpucontroller-> if( //mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter p_cpucoreusagegetter ) { float fCPUload ; wxSize wxsize ; fCPUload = -1.0 ; static wxString wxstr; for ( WORD wCoreID = 0 ; wCoreID < mp_cpucoredata->m_byNumberOfCPUCores ; ++ wCoreID ) { fCPUload = mp_cpucoredata->m_arfCPUcoreLoadInPercent[ wCoreID ] ; wxstr = wxString::Format( //#ifdef _WINDOWS #ifdef _MSC_VER //If MicroSoft compiler. _T("%.3f percent usage") #else //when compiled with MSVC and running under WinXP the executable //crashes with this format string (surely because of the 1st "%") //http://www.cplusplus.com/reference/clibrary/cstdio/printf/: //" A % followed by another % character will write % to stdout." wxT("%.3f%% usage") #endif , fCPUload * 100.0f ) ; r_wxdc.DrawText( wxstr , wxcoordX //x-coord , wCoreID * //m_wTextHeight //y-coord wxcoordTextHeight ) ; } } } /** * Draws current CPU core data onto a wxDC: * -core ID * -frequency * -voltage * -temperature * -usage */ void MainFrame::DrawCurrentCPUcoreInfo( wxDC & r_wxdc ) { LOGN(//"DrawCurrentCPUcoreData" "begin") // wxString wxstrCPUcoreUsage ; wxString wxstrCPUcoreVoltage ; wxString wxstrTemperature ; wxString wxstrFreqInMHz ; ICPUcoreUsageGetter * p_cpucoreusagegetter ; I_CPUcontroller * p_cpucontroller ; if( GetCPUcoreInfoDirectlyOrFromService( p_cpucoreusagegetter, p_cpucontroller //, // wxstrCPUcoreUsage , true ) ) { // DEBUGN("DrawCurrentCPUcoreInfo--Number of CPU cores:" << // (WORD) mp_cpucoredata->m_byNumberOfCPUCores ) //TODO do not create arrays every time this func is called wxString ar_wxstrCPUcoreVoltage [ mp_cpucoredata->m_byNumberOfCPUCores] ; wxString ar_wxstrCPUcoreTemperature [ mp_cpucoredata->m_byNumberOfCPUCores] ; wxString ar_wxstrCPUcoreFreqInMHz [ mp_cpucoredata->m_byNumberOfCPUCores] ; const wxFont & wxfont = r_wxdc.GetFont(); // int nFontPointSize = wxfont.GetPointSize(); if( mp_model->m_userinterfaceattributes.mainframe. m_nCurrentCPUcoreInfoSizeInPoint) { //TODO make font a member var and move font creation to the c'to wxFont wxfont2(wxfont); wxfont2.SetPointSize(mp_model->m_userinterfaceattributes.mainframe. m_nCurrentCPUcoreInfoSizeInPoint); r_wxdc.SetFont(wxfont2); } //if( m_wxfontCPUcoreInfo.GetPointSize() ) if( //mp_i_cpucontroller p_cpucontroller ) { // VoltageAndFreq ar_voltageandfreq[mp_cpucoredata->m_byNumberOfCPUCores] ; // float ar_fTempInDegCelsius [ mp_cpucoredata->m_byNumberOfCPUCores] ; LOGN(//"DrawCurrentCPUcoreData " "before StoreCurrentVoltageAndFreqInArray" ) StoreCurrentVoltageAndFreqInArray( // ar_voltageandfreq, // ar_fTempInDegCelsius r_wxdc , ar_wxstrCPUcoreFreqInMHz , ar_wxstrCPUcoreVoltage , ar_wxstrCPUcoreTemperature , p_cpucontroller ) ; // float fHighestTemperature = GetHighestTemperature( // s_arfTemperatureInDegreesCelsius) ; #ifdef _WIN32 //TODO use correct icon size for (both Windows and) Linux. ShowHighestCPUcoreTemperatureInTaskBar(p_cpucontroller) ; ShowCPUcoreUsagesInTaskBar(p_cpucontroller); ShowCPUcoresMultipliersInTaskBar(p_cpucontroller); #endif LOGN(//"DrawCurrentCPUcoreData " "after StoreCurrentVoltageAndFreqInArray" ) } else { for ( WORD wCoreID = 0 ; wCoreID < mp_cpucoredata->m_byNumberOfCPUCores ; ++ wCoreID ) { ar_wxstrCPUcoreVoltage [ wCoreID ] = wxT("?"); ar_wxstrCPUcoreTemperature [ wCoreID ] = wxT("?"); ar_wxstrCPUcoreFreqInMHz [ wCoreID ] = wxT("?"); } } LOGN(//"DrawCurrentCPUcoreData " "leaving IPC 2 in-program data crit sec") mp_cpucoredata->wxconditionIPC2InProgramData.Leave() ; LOGN(//"DrawCurrentCPUcoreData " "after leaving IPC 2 in-program data crit sec") //#ifdef _DEBUG // if ( fCPUload == 0.0 ) // { //// //Breakpoint possibility //// int i = 0 ; // } //#endif //wxmemorydc wxString wxstr ; wxCoord wxcoordX ; wxcoordX = //45 ; m_uiRightmostEndOfVoltageString; wxCoord wxcoordTextWidth, wxcoordTextHeight; r_wxdc.GetTextExtent( wxT("I") , & wxcoordTextWidth , & wxcoordTextHeight //, wxCoord *descent = NULL, wxCoord *externalLeading = NULL, wxFont *font = NULL ) ; DrawCPUcoreIDs(r_wxdc, wxcoordX, wxcoordTextHeight); if( //mp_i_cpucontroller p_cpucontroller ) { DrawCPUcoreVoltage(r_wxdc, ar_wxstrCPUcoreVoltage, wxcoordX, wxcoordTextHeight); DrawCurrentCPUcoreFrequency(r_wxdc, ar_wxstrCPUcoreFreqInMHz, wxcoordX, wxcoordTextHeight); DrawCurrentCPUcoreTemperature(r_wxdc, ar_wxstrCPUcoreTemperature, wxcoordX, wxcoordTextHeight); } DrawCPUcoreUsages(r_wxdc, p_cpucoreusagegetter, wxcoordX, wxcoordTextHeight); // } //for-loop if( mp_model->m_userinterfaceattributes.mainframe.m_nCurrentCPUcoreInfoSizeInPoint) { // wxfont.SetPointSize(nFontPointSize); r_wxdc.SetFont(wxfont); } } else { LOGN(//"DrawCurrentCPUcoreData " "before leaving IPC 2 in-program data crit sec") mp_cpucoredata->wxconditionIPC2InProgramData.Leave() ; LOGN(//"DrawCurrentCPUcoreData " "After leaving IPC 2 in-program data crit sec") } LOGN(//"DrawCurrentCPUcoreData " "end") } void MainFrame::DrawCurrentVoltageSettingsCurve( wxDC & wxdc , float fMaxVoltage ) { //May be NULL at startup. if( mp_i_cpucontroller ) { float fVoltage ; WORD wYcoordinate ; WORD wMaxFreqInMHz = //mp_i_cpucontroller-> //mp_model->m_cpucoredata.m_wMaxFreqInMHz ; m_wMaximumCPUcoreFrequency ; if( //If max. freq is assigned wMaxFreqInMHz != 0 ) for( WORD wCurrentXcoordinateInDiagram = //wXcoordOfBeginOfYaxis //0 //Begin with 1 to avoid div by zero. 1 ; wCurrentXcoordinateInDiagram < //wxcoordWidth m_wDiagramWidth ; ++ wCurrentXcoordinateInDiagram ) { //mp_i_cpucontroller->GetMinFreqToPreventOvervoltage( iter ) ; if( //mp_i_cpucontroller-> GetInterpolatedVoltageFromFreq( //Explicit cast to avoid (g++) compiler warning. (WORD) ( (float) wMaxFreqInMHz / ( (float) m_wDiagramWidth / (float) wCurrentXcoordinateInDiagram ) ) , fVoltage , mp_cpucoredata->m_stdsetvoltageandfreqWanted ) ) { wYcoordinate = GetYcoordinateForVoltage(fVoltage); //p_wxpaintdc->DrawLine( wxdc.DrawLine( wCurrentXcoordinateInDiagram + m_wXcoordOfBeginOfYaxis, //wDiagramHeight - //fVoltage/ (*iterstdvecmaxvoltageforfreq).m_fVoltageInVolt //* wDiagramHeight , wYcoordinate , wCurrentXcoordinateInDiagram + m_wXcoordOfBeginOfYaxis //"+ 1" because: http://docs.wxwidgets.org/stable/wx_wxdc.html // #wxdcdrawline: //"Note that the point (x2, y2) is not part of the line and is //not drawn by this function (this is consistent with the //behaviour of many other toolkits)." + 1 , wYcoordinate //"+ 1" because: http://docs.wxwidgets.org/stable/wx_wxdc.html // #wxdcdrawline: //"Note that the point (x2, y2) is not part of the line and is //not drawn by this function (this is consistent with the //behaviour of many other toolkits)." + 1 ) ; } }//for-loop } // if( mp_i_cpucontroller ) } void MainFrame::DrawFrequency( wxDC & r_wxdc , WORD wFrequencyInMHz , // WORD wMaxFreqInMHz , wxCoord wxcoordWidth , wxCoord wxcoordHeight , WORD wLeftEndOfCurrFreqText , wxString wxstrFreq , WORD & wXcoordinate , WORD & wYcoordinate , // stdmapYcoord2RightEndOfFreqString // std::set<WORD> & setRightEndOfFreqString // std::map<WORD,WORD> & mapRightEndOfFreqString2yCoord , // std::map<WORD,WORD>::const_reverse_iterator // r_iterstdmapRightEndOfFreqString2yCoord , std::map<WORD,WORD>::iterator & r_iterstdmapYcoord2RightEndOfFreqString , std::map<WORD,WORD> & stdmapYcoord2RightEndOfFreqString , std::map<WORD,WORD>::iterator & r_iterstdmap_ycoord2rightendoffreqstringToUse , bool bCalculateMaxTextHeight ) { wXcoordinate = GetXcoordinateForFrequency(wFrequencyInMHz) ; //Draw frequency mark. //p_wxpaintdc->DrawText( //wxmemorydc.DrawText( wxstrFreq = wxString::Format( //We need a _T() macro (wide char-> L"", char->"") for EACH //line to make it compatible between char and wide char. wxT("%u") , // (*r_iterstdsetvoltageandfreq).m_wFreqInMHz wFrequencyInMHz ) ; r_wxdc.GetTextExtent( wxstrFreq , & wxcoordWidth , & wxcoordHeight //, wxCoord *descent = NULL, wxCoord *externalLeading = NULL, wxFont *font = NULL ) ; wLeftEndOfCurrFreqText = wXcoordinate //Position the line at the horizontal middle of the text. - ( wxcoordWidth / 2 ) ; //If the iterator is not set::end() then there is at least 1 strings that would //overlap with the current string if all were drawn with the same y coordinate. //iterstdsetword = setRightEndOfFreqString. // //Finds the first element whose key greater than k. // upper_bound(wLeftEndOfCurrFreqText) ; //r_iterstdmapRightEndOfFreqString2yCoord = // mapRightEndOfFreqString2yCoord.rbegin() ; //while( r_iterstdmapRightEndOfFreqString2yCoord != // mapRightEndOfFreqString2yCoord.rend() // ) //{ // //If space between the right end is of a prev string and the left end // //of this string. // if( r_iterstdmapRightEndOfFreqString2yCoord->first < // wLeftEndOfCurrFreqText ) // break ; // ++ r_iterstdmapRightEndOfFreqString2yCoord ; //} ////Avoid overlapping of frequency strings. ////if( wLeftEndOfCurrFreqText < wRightEndOfPrevFreqText ) //// wYcoordinate = m_wDiagramHeight + wxcoordHeight ; //if( r_iterstdmapRightEndOfFreqString2yCoord != // mapRightEndOfFreqString2yCoord.rend() // ) // wYcoordinate = r_iterstdmapRightEndOfFreqString2yCoord->second ; //else // if( mapRightEndOfFreqString2yCoord.empty() ) // wYcoordinate = m_wDiagramHeight ; // else // no right text end that is left from the current text to draw. // { // //wYcoordinate = m_wDiagramHeight + wxcoordHeight ; // //e.g.: 500 // // 600 // // 650 // //Draw 1 line below the previous freq text. // wYcoordinate = mapRightEndOfFreqString2yCoord.rbegin()->second + // wxcoordHeight ; // } r_iterstdmapYcoord2RightEndOfFreqString = stdmapYcoord2RightEndOfFreqString.begin() ; r_iterstdmap_ycoord2rightendoffreqstringToUse = stdmapYcoord2RightEndOfFreqString.end() ; while( r_iterstdmapYcoord2RightEndOfFreqString != stdmapYcoord2RightEndOfFreqString.end() ) { //If space between the right end is of a prev string and the left end //of this string. //The first entry is the topmost. This is also the entry if( r_iterstdmapYcoord2RightEndOfFreqString->second < wLeftEndOfCurrFreqText ) { r_iterstdmap_ycoord2rightendoffreqstringToUse = r_iterstdmapYcoord2RightEndOfFreqString ; break ; } ++ r_iterstdmapYcoord2RightEndOfFreqString ; } if( r_iterstdmap_ycoord2rightendoffreqstringToUse != stdmapYcoord2RightEndOfFreqString.end() ) { //Update the new right end of string to draw. r_iterstdmap_ycoord2rightendoffreqstringToUse->second = wLeftEndOfCurrFreqText + wxcoordWidth ; wYcoordinate = r_iterstdmap_ycoord2rightendoffreqstringToUse->first ; } else { if( stdmapYcoord2RightEndOfFreqString.empty() ) wYcoordinate = m_wDiagramHeight ; else // no right text end that is left from the current text to draw. { //wYcoordinate = m_wDiagramHeight + wxcoordHeight ; //e.g.: 500 // 600 // 650 //Draw 1 line below the previous freq text. wYcoordinate = stdmapYcoord2RightEndOfFreqString.rbegin()->first + wxcoordHeight ; } stdmapYcoord2RightEndOfFreqString.insert( std::pair<WORD,WORD> ( wYcoordinate , wLeftEndOfCurrFreqText + wxcoordWidth ) ) ; } LOGN(//"DrawDiagramScale " "drawing " << wxWidgets::GetStdString( wxstrFreq ) << " at " << wLeftEndOfCurrFreqText << "," << wYcoordinate ) if( ! bCalculateMaxTextHeight) r_wxdc.DrawText( wxstrFreq , //wXcoordOfBeginOfYaxis + //(float) wMaxFreqInMHz * wDiagramWidth wLeftEndOfCurrFreqText , //m_wDiagramHeight wYcoordinate ) ; } void MainFrame::DrawFrequencyMarksAndLines(wxDC & r_wxdc, //0=calculate max height WORD & wMaximumYcoordinateForFrequency) { LOGN_DEBUG( "begin") WORD wInitialMaximumYcoordinateForFrequency = wMaximumYcoordinateForFrequency; wMaximumYcoordinateForFrequency = 0; //Initialize to avoid g++ warnings like //"'wLeftEndOfCurrFreqText' might be used uninitialized in this function" wxCoord wxcoordWidth = 0 ; wxCoord wxcoordHeight = 0 ; wxString wxstrFreq ; fastestUnsignedDataType wLeftEndOfCurrFreqText = 0 ; WORD wXcoordinate ; //Initialize to avoid g++ warning //"'wYcoordinate' may be used uninitialized in this function" WORD wYcoordinate = 0; std::map<WORD,WORD>::iterator r_iterstdmapYcoord2RightEndOfFreqString ; std::map<WORD,WORD> stdmapYcoord2RightEndOfFreqString ; std::map<WORD,WORD>::iterator r_iterstdmap_ycoord2rightendoffreqstringToUse ; float fReferenceClockInMHz = mp_i_cpucontroller->m_fReferenceClockInMHz ; WORD wFrequencyInMHz ; wxPen penLine( * wxLIGHT_GREY, 1); // pen of width 1 const wxPen & c_r_penCurrent = r_wxdc.GetPen(); const wxFont & wxfont = r_wxdc.GetFont(); // int nFontPointSize = wxfont.GetPointSize(); if( mp_model->m_userinterfaceattributes.mainframe. m_nCPUcoreFrequencyScaleSizeInPoint) { //TODO possibly create font in c'tor and not for every call to this function wxFont wxfont2(wxfont); wxfont2.SetPointSize(mp_model->m_userinterfaceattributes.mainframe. m_nCPUcoreFrequencyScaleSizeInPoint); r_wxdc.SetFont(wxfont2); } // wxCoord wxcoordTextWidth, wxcoordTextHeight; // r_wxdc.GetTextExtent( // wxT("I") // , & wxcoordTextWidth // , & wxcoordTextHeight // //, wxCoord *descent = NULL, wxCoord *externalLeading = NULL, wxFont *font = NULL // ) ; const fastestSignedDataType numMultipliers = mp_cpucoredata-> m_stdset_floatAvailableMultipliers.size(); for( fastestUnsignedDataType multiplierArrayIndex = 0 ; multiplierArrayIndex < numMultipliers ; ++ multiplierArrayIndex ) { wFrequencyInMHz = //Avoid g++ warning "converting to `WORD' from `float'" . (WORD) ( mp_cpucoredata->m_arfAvailableMultipliers[ multiplierArrayIndex ] * fReferenceClockInMHz ) ; LOGN("should draw frequency " << wFrequencyInMHz << " for frequency scale") DrawFrequency( r_wxdc, wFrequencyInMHz , wxcoordWidth , wxcoordHeight , wLeftEndOfCurrFreqText , wxstrFreq , wXcoordinate , wYcoordinate , r_iterstdmapYcoord2RightEndOfFreqString , stdmapYcoord2RightEndOfFreqString , r_iterstdmap_ycoord2rightendoffreqstringToUse, ! wInitialMaximumYcoordinateForFrequency ) ; if( wYcoordinate > wMaximumYcoordinateForFrequency ) wMaximumYcoordinateForFrequency = wYcoordinate; if( wInitialMaximumYcoordinateForFrequency > 0) { r_wxdc.SetPen(penLine); r_wxdc.DrawLine( wXcoordinate, 0, wXcoordinate, wYcoordinate); r_wxdc.SetPen(c_r_penCurrent); } } if( mp_model->m_userinterfaceattributes.mainframe. m_nCPUcoreFrequencyScaleSizeInPoint) { // wxfont.SetPointSize(nFontPointSize); r_wxdc.SetFont(wxfont); } } void MainFrame::DrawVoltage(wxDC & r_wxdc , float fVoltageInVolt) { // WORD wYcoordinate ; if( m_bRangeBeginningFromMinVoltage ) m_wYcoordinate = //Explicit cast to avoid (g++) warning. (WORD) ( m_wDiagramHeight - ( fVoltageInVolt - m_fMinVoltage ) / m_fMaxMinusMinVoltage * m_wDiagramHeight ) ; else m_wYcoordinate = //Explicit cast to avoid (g++) warning. (WORD) ( m_wDiagramHeight - //(*iterstdsetmaxvoltageforfreq).m_fVoltageInVolt fVoltageInVolt / m_fMaxVoltage * m_wDiagramHeight + m_wMinYcoordInDiagram ) ; //Draw voltage mark. //p_wxpaintdc->DrawText( //wxmemorydc.DrawText( r_wxdc.DrawText( wxString::Format( //We need a _T() macro (wide char-> L"", char->"") for EACH //line to make it compatible between char and wide char. _T("%.3f") , fVoltageInVolt ), 5 , //wDiagramHeight - /// fMaxVoltage * wDiagramHeight m_wYcoordinate ) ; } unsigned MainFrame::GetYcoordinateForVoltage(float fVoltageInVolt//, // unsigned uiHalfTextHeightInPixels ) { WORD wYcoordinate ; if( m_bRangeBeginningFromMinVoltage ) wYcoordinate = //Explicit cast to avoid (g++) warning. (WORD) ( m_wDiagramHeight - ( fVoltageInVolt - m_fMinVoltage ) / m_fMaxMinusMinVoltage * (m_wDiagramHeight //The highest voltage should start at the half pixel height of the //voltage string. - m_wMinYcoordInDiagram) // + //uiHalfTextHeightInPixels // m_wMinYcoordInDiagram ) ; else wYcoordinate = //Explicit cast to avoid (g++) warning. (WORD) ( m_wDiagramHeight - //(*iterstdsetmaxvoltageforfreq).m_fVoltageInVolt fVoltageInVolt / m_fMaxVoltage * (m_wDiagramHeight //The highest voltage should start at the half pixel height of the //voltage string. - m_wMinYcoordInDiagram) // + m_wMinYcoordInDiagram ) ; return wYcoordinate; } wxCoord MainFrame::DrawVoltage( wxDC & r_wxdc , float fVoltageInVolt, WORD wYcoordinate, unsigned uiXcoordinateInPixels ) { static wxCoord wxcoordTextWidth, wxcoordTextHeight; wxString wxstrVoltage = wxString::Format( //We need a _T() macro (wide char-> L"", char->"") for EACH //line to make it compatible between char and wide char. wxT("%.3f") , fVoltageInVolt ); unsigned uiBeginOfVoltageString = 3 + uiXcoordinateInPixels; //Draw voltage mark. //p_wxpaintdc->DrawText( //wxmemorydc.DrawText( r_wxdc.DrawText( wxstrVoltage , uiBeginOfVoltageString , //wDiagramHeight - /// fMaxVoltage * wDiagramHeight wYcoordinate ) ; r_wxdc.GetTextExtent( wxstrVoltage , & wxcoordTextWidth , & wxcoordTextHeight //, wxCoord *descent = NULL, wxCoord *externalLeading = NULL, wxFont *font = NULL ) ; return wxcoordTextWidth + uiBeginOfVoltageString; } void MainFrame::DrawVoltageFreqCross( wxDC & r_wxdc , float fVoltageInVolt , WORD wFreqInMHz , const wxColor * cp_wxcolor ) { LOGN("begin") WORD wXcoordinate = //Explicit cast to avoid (g++) warning. (WORD) ( m_wXcoordOfBeginOfYaxis + (float) //(*iterstdvecmaxvoltageforfreq).m_wFreqInMHz / //(*iterstdvecmaxvoltageforfreq).m_wFreqInMHz / wFreqInMHz / (float) //mp_cpucoredata->m_wMaxFreqInMHz m_wMaximumCPUcoreFrequency * m_wDiagramWidth ) ; WORD wYcoordinate = GetYcoordinateForVoltage(fVoltageInVolt); //wxPen pen(*wxBLUE, 3); // pen of width 3 wxPen pen(*cp_wxcolor, 3); // pen of width 3 r_wxdc.SetPen(pen); //Draw Cursor: r_wxdc.DrawLine( wXcoordinate - 3, wYcoordinate , wXcoordinate + 4, wYcoordinate ) ; r_wxdc.DrawLine( wXcoordinate , wYcoordinate - 3, wXcoordinate , wYcoordinate + 4 ) ; } void MainFrame::DrawVoltageScale(wxDC & r_wxdc ) { LOGN_DEBUG( "begin") WORD wPreviousYcoordinateForVoltage = MAXWORD ; const wxPen & c_r_penCurrent = r_wxdc.GetPen(); //TODO possibly create pen in c'tor and not for every call to this function wxPen penLine( * wxLIGHT_GREY, 1); // pen of width 1 r_wxdc.SetPen(penLine); const wxFont & cr_wxfontBefore = r_wxdc.GetFont(); //wxWidgets runtime error when calling GetPointSize. // int nFontPointSize = cr_wxfontBefore.GetPointSize(); if( mp_model->m_userinterfaceattributes.mainframe.m_nVoltageScaleSizeInPoint) { // cr_wxfontBefore.SetPointSize(mp_model->m_userinterfaceattributes. // m_nVoltageScaleSizeInPoint); //TODO possibly create font in c'tor and not for every call to this function //wxFont copy c'tor uses reference counting. wxFont wxfont(cr_wxfontBefore//.GetNativeFontInfoDesc() ); wxfont.SetPointSize(mp_model->m_userinterfaceattributes.mainframe. m_nVoltageScaleSizeInPoint); r_wxdc.SetFont(//cr_wxfontBefore wxfont); } wxCoord wxcoordTextWidth, wxcoordTextHeight; wxCoord wxcoordVoltageStringWidth = 0; r_wxdc.GetTextExtent( wxT("I") , & wxcoordTextWidth , & wxcoordTextHeight //, wxCoord *descent = NULL, wxCoord *externalLeading = NULL, wxFont *font = NULL ) ; int nHalfTextHeightInPixels = wxcoordTextHeight/2; m_wMinYcoordInDiagram = nHalfTextHeightInPixels; unsigned uiBeginOfVoltageString = 0; m_uiRightmostEndOfVoltageString = 0; for( WORD wVoltageIndex = 0 ; wVoltageIndex < mp_cpucoredata-> m_stdset_floatAvailableVoltagesInVolt.size() ; ++ wVoltageIndex ) { LOGN("should draw voltage " << mp_cpucoredata->m_arfAvailableVoltagesInVolt[ wVoltageIndex ] << " for voltage scale") m_wYcoordinate = GetYcoordinateForVoltage( mp_cpucoredata->m_arfAvailableVoltagesInVolt[ wVoltageIndex ]//, nHalfTextHeightInPixels ); // wYoordinate = m_wYoordinate ; if( //If y coord of current voltage <= y coord of prev voltage - text h //=if the voltage string _does not overlap_ with the previous voltage //string. m_wYcoordinate <= wPreviousYcoordinateForVoltage - //m_wTextHeight wxcoordTextHeight) { //uiBeginOfVoltageString = wxcoordVoltageStringWidth; // //Next time start at x pos 0. // wxcoordVoltageStringWidth = 0; //Draw at x pos 0. wxcoordVoltageStringWidth = 0; } else //Strings would overlap-> place right of previous voltage string. { // wxcoordVoltageStringWidth = 0; // uiBeginOfVoltageString = 0; // uiBeginOfVoltageString // wxcoordVoltageStringWidth = DrawVoltage( // r_wxdc, // mp_cpucoredata->m_arfAvailableVoltagesInVolt[ wVoltageIndex ] // , m_wYcoordinate - nHalfTextHeightInPixels // , //wXcoordinateForVoltageStringBegin // wxcoordVoltageStringWidth //// 0 // ) ; } //Next time start with x pos of end of this string. // wxcoordVoltageStringWidth = uiBeginOfVoltageString = DrawVoltage( r_wxdc, mp_cpucoredata->m_arfAvailableVoltagesInVolt[ wVoltageIndex ] , m_wYcoordinate - nHalfTextHeightInPixels , //wXcoordinateForVoltageStringBegin // 0 wxcoordVoltageStringWidth // uiBeginOfVoltageString ) ; if( wxcoordVoltageStringWidth ) //Next time start with x pos 0. wxcoordVoltageStringWidth = 0; else wxcoordVoltageStringWidth = uiBeginOfVoltageString; wPreviousYcoordinateForVoltage = m_wYcoordinate ; if( uiBeginOfVoltageString //wxcoordVoltageStringWidth > m_uiRightmostEndOfVoltageString) m_uiRightmostEndOfVoltageString = uiBeginOfVoltageString; //wxcoordVoltageStringWidth; r_wxdc.DrawLine( // m_wXcoordOfBeginOfYaxis, // wxcoordVoltageStringWidth, uiBeginOfVoltageString, m_wYcoordinate, //+ nHalfTextHeightInPixels, m_wXcoordOfBeginOfYaxis + m_wDiagramWidth, m_wYcoordinate //+ nHalfTextHeightInPixels ); if( uiBeginOfVoltageString) //Start at x pos 0 the next time. uiBeginOfVoltageString = 0; } r_wxdc.SetPen(c_r_penCurrent); if( mp_model->m_userinterfaceattributes.mainframe.m_nVoltageScaleSizeInPoint) { // cr_wxfontBefore.SetPointSize(nFontPointSize); r_wxdc.SetFont(cr_wxfontBefore); } LOGN_DEBUG( "end") } float MainFrame::GetClosestMultiplier(int nXcoordionate, float & fReferenceClockInMHz) { LOGN( "begin--mp_i_cpucontroller:" << mp_i_cpucontroller) if( mp_i_cpucontroller && nXcoordionate >= m_wXcoordOfBeginOfYaxis ) { unsigned uiFreqInMHz = (unsigned) ( (float) (nXcoordionate - m_wXcoordOfBeginOfYaxis) / (float) m_wDiagramWidth * (float) m_wMaximumCPUcoreFrequency ); // float fReferenceClockInMHz = mp_i_cpucontroller->m_fReferenceClockInMHz ; fReferenceClockInMHz = mp_i_cpucontroller->m_fReferenceClockInMHz ; float fMultiplierForYcoordinate = (float) uiFreqInMHz / fReferenceClockInMHz; float fAvailableMultiplier; float fLowerMultiplier = FLT_MIN, fHigherMultiplier = FLT_MAX; for( WORD wMultiplierIndex = 0 ; wMultiplierIndex < mp_cpucoredata-> m_stdset_floatAvailableMultipliers.size() ; ++ wMultiplierIndex ) { fAvailableMultiplier = mp_cpucoredata->m_arfAvailableMultipliers[ wMultiplierIndex ] ; if( fAvailableMultiplier < fMultiplierForYcoordinate) fLowerMultiplier = fAvailableMultiplier; else { fHigherMultiplier = fAvailableMultiplier; break; } } float fClosestAvailabeMultiplier = (fMultiplierForYcoordinate - fLowerMultiplier) < fHigherMultiplier - fMultiplierForYcoordinate ? fLowerMultiplier : fHigherMultiplier; return fClosestAvailabeMultiplier; } return -1.0; } float MainFrame::GetClosestVoltageForYcoordinate( //Y coordinate starts at 0,0 at top left corner. int nYcoordinate) { if( ! mp_cpucoredata->m_stdset_floatAvailableVoltagesInVolt.empty() ) { const std::set<float> & c_r_std_set_float = mp_cpucoredata-> m_stdset_floatAvailableVoltagesInVolt; // const float fLowestVoltage = * c_r_std_set_float.begin(); // const float fHighestVoltage = * ( -- c_r_std_set_float.end() ); // const float fVoltageDiff = fHighestVoltage - fLowestVoltage; // const float fYposToDiagramHeightRatio = (float) nYcoordinate / (float) // m_wDiagramHeight; // const float fVoltageAccordingToYcoordinate = // //The maximum voltage is at the top left corner. // m_fMaxVoltage - // ( fYposToDiagramHeightRatio * m_fMaxMinusMinVoltage) //fVoltageDiff // ; // GetVoltageAccordignToYcoordinate(); // { // uiYcoordinateForAvailableVoltage = GetYcoordinateForVoltage(* c_iter); // } // c_r_std_set_float.lower_bound(); upper_bound() float fClosestLowerVoltage = FLT_MIN, fClosestHigherVoltage = //If no voltage higher than "fVoltageAccordingToYcoordinate": then //fClosestHigherVoltage - fVoltageAccordingToYcoordinate is a very big //number. //http://www.cplusplus.com/reference/clibrary/cfloat/: FLT_MAX; std::set<float>::const_iterator c_iter = c_r_std_set_float.begin(); unsigned uiYcoordinateForAvailableVoltage = 0; unsigned uiClosestLowerYcoordinate = 0; unsigned uiClosestHigherYcoordinate = 0; while( c_iter != c_r_std_set_float.end() ) { uiYcoordinateForAvailableVoltage = GetYcoordinateForVoltage(* c_iter); if( //* c_iter < fVoltageAccordingToYcoordinate //Higher coordinates=lower voltages. uiYcoordinateForAvailableVoltage > nYcoordinate ) { uiClosestHigherYcoordinate = uiYcoordinateForAvailableVoltage; fClosestLowerVoltage = * c_iter; } else { fClosestHigherVoltage = * c_iter; uiClosestLowerYcoordinate = uiYcoordinateForAvailableVoltage; break; } ++ c_iter; } if( uiClosestHigherYcoordinate) { if( uiClosestLowerYcoordinate) { const float fClosestVoltageToYcoordinate = // ( fVoltageAccordingToYcoordinate - fClosestLowerVoltage ) < // ( fClosestHigherVoltage - fVoltageAccordingToYcoordinate ) ? //Distance (in pixels) to higher voltage. ( nYcoordinate - uiClosestLowerYcoordinate ) > //Distance (in pixels) to lower voltage. ( uiClosestHigherYcoordinate - nYcoordinate ) ? fClosestLowerVoltage : fClosestHigherVoltage; return fClosestVoltageToYcoordinate; } else return fClosestLowerVoltage; } else return //Lowest voltage. * c_r_std_set_float.begin(); } return -1.0; } /** * data provider: usually the x86I&C Windows service */ void MainFrame::GetCPUcoreInfoFromDataProvider( ICPUcoreUsageGetter * & p_cpucoreusagegetter , I_CPUcontroller * & p_cpucontroller //, ) { LOGN("begin") // LOGN("DrawCurrentPstateInfo: connected to the service") //TODO possibly make IPC communication into a separate thread because it // may freeze the whole GUI. // ::wxGetApp().m_ipcclient.SendCommandAndGetResponse(get_current_CPU_data) ; // ::wxGetApp().m_ipcclient.SendCommand(get_current_CPU_data) ; LOGN(//"MainFrame::DrawCurrentPstateInfo " "m_bCPUcoreUsageConsumed" #ifdef _DEBUG ": " << m_bCPUcoreUsageConsumed #endif ) LOGN("mp_wxx86infoandcontrolapp->m_vbGotCPUcoreData:" << mp_wxx86infoandcontrolapp->m_vbGotCPUcoreData ) //Do not run it more than once concurrently. // if( //m_bCPUcoreUsageConsumed // true // // if( // // //Do not call/ wait on the IPC thread if it is running right now. // // && mp_wxx86infoandcontrolapp->m_vbGotCPUcoreData // ) // { // //set to true when the thread has finished. // mp_wxx86infoandcontrolapp->m_vbGotCPUcoreData = false ; mp_wxx86infoandcontrolapp->GetCurrentCPUcoreDataViaIPCNonBlocking() ; m_bCPUcoreUsageConsumed = false ; // } // if( ::wxGetApp().m_ipcclient.m_arbyIPCdata ) // { #ifdef COMPILE_WITH_INTER_PROCESS_COMMUNICATION p_cpucontroller = & mp_wxx86infoandcontrolapp-> m_sax2_ipc_current_cpu_data_handler ; p_cpucoreusagegetter = & mp_wxx86infoandcontrolapp-> m_sax2_ipc_current_cpu_data_handler ; #endif //#ifdef COMPILE_WITH_INTER_PROCESS_COMMUNICATION //Prevent the modification of in-program data of either the the CPU core usage // or CPU controller data // else this may happen: // for some cores data may be from the previous retrieval. // or even the CPU usage may be from previous and so not match the CPU // controller data LOGN(//"DrawCurrent CPU core info: " "entering IPC 2 in-program data crit sec") //Prevent the concurrent modification of the # of log(ical?). cores in the //IPC data 2 in-program data thread. mp_cpucoredata->wxconditionIPC2InProgramData.Enter() ; LOGN(//"DrawCurrent CPU core info: " "After entering IPC 2 in-program data crit sec") //The number of CPU cores is known if the IPC data were got at first. WORD wNumCPUcores = p_cpucoreusagegetter->GetNumberOfLogicalCPUcores() ; LOGN(//"DrawCurrentCPUcoreData " "after GetNumberOfLogicalCPUcores" ) // if( wNumCPUcores > mp_cpucoredata->m_byNumberOfCPUCores ) mp_cpucoredata->SetCPUcoreNumber( wNumCPUcores ) ; wxString wxstrTitle = mp_wxx86infoandcontrolapp->m_wxstrDataProviderURL + (p_cpucontroller->m_bDVFSfromServiceIsRunning ? wxT(" [DVFS]--") : wxT(" [no DVFS]--") ); SetTitle( //wxT("--values from service") wxstrTitle + m_wxstrTitle ) ; } bool MainFrame::GetCPUcoreInfoDirectlyOrFromService( ICPUcoreUsageGetter * & p_cpucoreusagegetter , I_CPUcontroller * & p_cpucontroller //, // wxString & wxstrCPUcoreUsage , bool bGetCPUcoreUsage ) { LOGN("begin") bool bReturn = false ; p_cpucoreusagegetter = mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter ; p_cpucontroller = mp_i_cpucontroller ; // LOGN("DrawCurrentCPUcoreInfo") #ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE // #ifdef _DEBUG // bool bIsGettingCPUcoreData = mp_wxx86infoandcontrolapp->m_ipcclient. // m_vbIsGettingCPUcoreData ; // SUPPRESS_UNUSED_VARIABLE_WARNING(bIsGettingCPUcoreData) // #endif if( //::wxGetApp().m_ipcclient.IsConnected() mp_wxx86infoandcontrolapp->IPC_ClientIsConnected() //This flag should be (set to) "true" as long as writing and reading data //to the service is successful. // mp_wxx86infoandcontrolapp->m_ipcclient.m_vbIsGettingCPUcoreData // false ) { GetCPUcoreInfoFromDataProvider( p_cpucoreusagegetter, p_cpucontroller //, ); } else #endif //#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE { SetTitle( m_wxstrTitle //+ wxT("--values from CPU controller") ) ; p_cpucoreusagegetter = mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter ; //Prevent the modification of in-program data of either the the CPU core usage // or CPU controller data // else this may happen: // for some cores data may be from the previous retrieval. // or even the CPU usage may be from previous and so not match the CPU // controller data LOGN(//"DrawCurrent CPU core info: " "entering IPC 2 in-program data crit sec") mp_cpucoredata->wxconditionIPC2InProgramData.Enter() ; LOGN(//"DrawCurrent CPU core info: " "After entering IPC 2 in-program data crit sec") } // LOGN( p_cpucoreusagegetter << p_cpucontroller) // DEBUGN("DrawCurrentCPUcoreInfo CPU controller address:" << mp_i_cpucontroller ) //::wxGetApp().mp_cpucoreusagegetter-> if( //mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter p_cpucoreusagegetter // >= 1 CPU core && mp_cpucoredata->m_byNumberOfCPUCores ) { PerCPUcoreAttributes * p_percpucoreattributes = & mp_cpucoredata-> m_arp_percpucoreattributes[ //p_atts->m_byCoreID 0 ] ; //DynFreqScalingThread * p_dynfreqscalingthread //If the drawing thread and the dyn freq scaling thread both try to get //the CPU usage they could interfere/ the delay between the usage retrieval //could be too short-> So only try to get usage here if no DVFS thread. if ( ! p_percpucoreattributes->mp_dynfreqscalingthread ) { LOGN(//"DrawCurrentCPUcoreData " "before GetPercentalUsageForAllCores" ) if( bGetCPUcoreUsage ) // mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter-> p_cpucoreusagegetter-> GetPercentalUsageForAllCores( mp_cpucoredata->m_arfCPUcoreLoadInPercent) ; m_bCPUcoreUsageConsumed = true ; // DEBUGN("DrawCurrentCPUcoreInfo after GetPercentalUsageForAllCores" ) } } // else // wxstrCPUcoreUsage = wxT("usage in percent: ?") ; #ifdef _DEBUG //::wxGetApp().mp_cpucoreusagegetter->Init() ; #endif //May be NULL at startup. if( //mp_i_cpucontroller ( p_cpucontroller || //mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter p_cpucoreusagegetter ) // >= 1 CPU core && mp_cpucoredata->m_byNumberOfCPUCores ) { LOGN_WARNING( "before recreating the temperature array: mustn't be from another " "thread accessed during this time") if( s_arfTemperatureInDegreesCelsius ) delete [] s_arfTemperatureInDegreesCelsius ; s_arfTemperatureInDegreesCelsius = new float[ mp_cpucoredata-> m_byNumberOfCPUCores ] ; bReturn = true ; } LOGN("return " << bReturn << " I_CPUcontroller *:" << p_cpucontroller) return bReturn ; } WORD MainFrame::GetXcoordinateForFrequency(WORD wFrequencyInMHz) { LOGN(//"GetXcoordinateForFrequency(" << wFrequencyInMHz //<< ")" ) return //Explicit cast to avoid (g++) warning. (WORD) ( m_wXcoordOfBeginOfYaxis + (float) //(*iterstdvecmaxvoltageforfreq).m_wFreqInMHz / //(*iterstdvecmaxvoltageforfreq).m_wFreqInMHz / //(*iterstdsetmaxvoltageforfreq).m_wFreqInMHz / // (*r_iterstdsetvoltageandfreq).m_wFreqInMHz / wFrequencyInMHz / (float) m_wMaximumCPUcoreFrequency * m_wDiagramWidth ) ; } //"Cross-Platform GUI Programming with wxWidgets" // (Copyright © 2006 Pearson Education, Inc.) // ISBN 0-13-147381-6 "First printing, July 2005" //"CHAPTER 5 Drawing and Printing" -> //"UNDERSTANDING DEVICE CONTEXTS" -> "Drawing on Windows with wxPaintDC" : // "[...] another thing you can do to make // drawing smoother (particularly when resizing) is to paint the background in // your paint handler, and not in an erase background handler. All the painting // will then be done in your buffered paint handler, so you don’t see the back- // ground being erased before the paint handler is called. // Add an empty erase background handler [...]" // ->Empty implementation, to prevent flicker void MainFrame::OnEraseBackground(wxEraseEvent& event) { } void MainFrame::HandleResumeForAllVoltAndFreqDlgs() { LOGN( "begin") #ifdef USE_CRIT_SEC_FOR_FREQ_AND_VOLT_SETTINGS_DLG_CONTAINER m_crit_secVoltAndFreqDlgs.Enter(); std::vector<FreqAndVoltageSettingDlg * >::const_iterator c_iter = m_stdvec_p_freqandvoltagesettingdlg.begin(); // wxPowerEvent evt; while( c_iter != m_stdvec_p_freqandvoltagesettingdlg.end() ) { ( * c_iter)->ResumendFromStandByOrHibernate(); ++ c_iter; } m_crit_secVoltAndFreqDlgs.Leave(); #endif //#ifdef USE_CRIT_SEC_FOR_FREQ_AND_VOLT_SETTINGS_DLG_CONTAINER LOGN( "end") } void MainFrame::OnPaint(wxPaintEvent & r_wx_paint_event) { LOGN("begin") // DEBUGN("OnPaint CPU controller address:" << mp_i_cpucontroller << // "usage getter addr.:" << mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter // << "mp_wxbitmap:" << mp_wxbitmap ) I_CPUcontroller * p_cpucontroller ; ICPUcoreUsageGetter * p_cpucoreusagegetter ; #ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE if( //::wxGetApp().m_ipcclient.IsConnected() mp_wxx86infoandcontrolapp->IPC_ClientIsConnected() ) { p_cpucontroller = & mp_wxx86infoandcontrolapp->m_sax2_ipc_current_cpu_data_handler ; p_cpucoreusagegetter = & mp_wxx86infoandcontrolapp->m_sax2_ipc_current_cpu_data_handler ; } else #endif //#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE { p_cpucontroller = mp_i_cpucontroller ; p_cpucoreusagegetter = mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter ; } //May be NULL at startup. if( ( //mp_i_cpucontroller || p_cpucontroller || //mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter p_cpucoreusagegetter ) && //Is NULL if CPUcontroller is NULL at startup. mp_wxbitmap ) { //Control access to m_bAllowCPUcontrollerAccess between threads. //m_wxCriticalSectionCPUctlAccess.Enter() ; //wxCriticalSectionLocker wxcriticalsectionlocker( // m_wxcriticalsectionCPUctlAccess ) ; // bool bAllowCPUcontrollerAccess = IsCPUcontrollerAccessAllowedThreadSafe() ; // if( //m_bAllowCPUcontrollerAccess // bAllowCPUcontrollerAccess ) //TODO http://docs.wxwidgets.org/2.8/wx_wxbuffereddc.html: //"GTK+ 2.0 as well as OS X provide double buffering themselves natively" //if( IsDoubleBuffered() ) wxPaintDC * p_wxpaintdc = new wxPaintDC(this); //wxMemoryDC wxmemorydc(wxbitmap) ; wxBufferedPaintDC wxmemorydc( this //, wxbitmap , *mp_wxbitmap ) ; //"Cross-Platform GUI Programming with wxWidgets" // (Copyright © 2006 Pearson Education, Inc.) // ISBN 0-13-147381-6 "First printing, July 2005" //"CHAPTER 5 Drawing and Printing" -> //"UNDERSTANDING DEVICE CONTEXTS" -> "Drawing on Windows with wxPaintDC" : // "Shifts the device origin so we don’t have to worry // about the current scroll position ourselves" PrepareDC(wxmemorydc); //http://docs.wxwidgets.org/stable/wx_wxmemorydc.html#wxmemorydc: //"Use the IsOk member to test whether the constructor was //successful in creating a usable device context." if( wxmemorydc.IsOk() ) { wxCoord wxcoordCanvasWidth ; wxCoord wxcoordCanvasHeight ; // DEBUGN("OnPaint wxmemorydc.IsOk()" ) p_wxpaintdc->GetSize( & wxcoordCanvasWidth , & wxcoordCanvasHeight ) ; //Clears the device context using the current background brush. //(else black background?) wxmemorydc.Clear(); //TODO maybe "dc.Blit(dcDiagramScaleAndCurves)" is faster than DrawBitmap. //wxmemorydc.Blit(0, 0, wxcoordCanvasWidth , wxcoordCanvasHeight, // & m_wxbufferedpaintdcStatic, 0, 0 ); //if( mp_wxbufferedpaintdcStatic ) wxmemorydc.Blit(0, 0, wxcoordCanvasWidth , wxcoordCanvasHeight, //mp_wxbufferedpaintdcStatic & m_wxmemorydcStatic , 0, 0 ); //wxmemorydc.DrawBitmap( //mp_wxbitmapDiagramScaleAndCurves // *mp_wxbitmapStatic , 0, 0) ; // DrawCurrentVoltageSettingsCurve( // wxmemorydc , // m_fMaxVoltage // ) ; #ifdef __WXGTK__ /** The following lines are needed under Linux GTK for getting the text * extent correctly? (else the text extent width is to small-> * if e.g. drawing multiple text from left to right then the text * overlaps. */ // wxFont wxfont ; /** This line caused a runtime error in wxDC::GetTextExtent() within * DrawCurrentCPUcoreInfo(...) : * "../src/gtk/dcclient.cpp(1480): assert "fontToUse->IsOk()" failed in DoGetTextExtent(): invalid font" * respectively then it did not show any CPU * information like CPU core frequency. */ // wxmemorydc.SetFont( wxfont) ; #endif //#ifdef __WXGTK__ DrawCurrentCPUcoreInfo(wxmemorydc) ; //Just for testing: //wXcoordinate = wYcoordinate = 50 ; if( mp_i_cpucontroller ) { bool bAllowCPUcontrollerAccess = IsCPUcontrollerAccessAllowedThreadSafe() ; if( //m_bAllowCPUcontrollerAccess bAllowCPUcontrollerAccess ) { if( //m_bDrawFreqAndVoltagePointForCurrCoreSettings m_vbAnotherWindowIsActive ) { DrawVoltageFreqCross( wxmemorydc , m_fVoltageInVoltOfCurrentActiveCoreSettings , m_wFreqInMHzOfCurrentActiveCoreSettings , wxBLUE ) ; } else { // float fVoltageInVolt ; // WORD wFreqInMHz ; WORD wNumCPUcores = mp_cpucoredata->GetNumberOfCPUcores() ; float fRefClock = mp_i_cpucontroller->m_fReferenceClockInMHz ; for( //Use WORD data type for guaranteed future (if > 256 logical //CPU cores) WORD wCPUcoreID = 0 ; wCPUcoreID < wNumCPUcores ; ++ wCPUcoreID ) { // mp_i_cpucontroller->GetCurrentPstate(wFreqInMHz, // fVoltageInVolt, byCoreID); // PerCPUcoreAttributes & r_percpucoreattributes = mp_cpucoredata-> // m_arp_percpucoreattributes[ byCoreID] ; DrawVoltageFreqCross( wxmemorydc //, r_percpucoreattributes.m_fVoltageInVoltCalculatedFromCPUload , //fVoltageInVolt mp_ar_voltage_and_multi[wCPUcoreID ].m_fVoltageInVolt //, r_percpucoreattributes.m_wFreqInMHzCalculatedFromCPUload , //wFreqInMHz (WORD) ( mp_ar_voltage_and_multi[wCPUcoreID ].m_fMultiplier * fRefClock ) , wxBLUE ) ; } } } //if( bAllowCPUcontrollerAccess) } //m_bDrawFreqAndVoltagePointForCurrCoreSettings = // ! m_bDrawFreqAndVoltagePointForCurrCoreSettings ; //} }//if( wxmemorydc.IsOk() ) else { DEBUGN("NOT wxmemorydc.IsOk()" ) } delete p_wxpaintdc; //m_wxCriticalSectionCPUctlAccess.Leave() ; } // if( mp_i_cpucontroller ) else { wxPaintDC wxpaintdc(this); //Clears the device context using the current background brush. //(else black background?) wxpaintdc.Clear(); wxpaintdc.DrawText( wxT("no CPU controller available->e.g. attach a DLL") , 0 , 0 ) ; } LOGN("end") } //order of submenus/ menu items of "core x" menus. enum { Settings = 0, highLoadThread , highFPUloadThread }; void MainFrame::DynVoltnFreqScalingEnabled() { ////Stop the timer (else the timer redraws additionally to the scaling thread). //m_wxtimer.Stop() ; mp_wxmenuitemOwnDVFS->/*SetText*/SetItemLabel( /** We need a _T() macro (wide char-> L"", char->"") for EACH * line to make it compatible between char and wide char. */ wxT("disable Own Dynamic Voltage and Frequency Scaling") ) ; } void MainFrame::EndDynVoltAndFreqScalingThread( PerCPUcoreAttributes * p_percpucoreattributes ) { // LOGN("ending Dynamic Voltage and Frequency scaling thread") LOGN("begin") p_percpucoreattributes->mp_dynfreqscalingthread->Stop() ; //p_percpucoreattributes->mp_dynfreqscalingthread->Delete() ; p_percpucoreattributes->mp_dynfreqscalingthread = NULL ; ////Start the timer (it should have been stopped before else the timer had redrawn ////additonally to the scaling thread). // m_wxtimer.Start() ; mp_wxmenuitemOwnDVFS->/*SetText*/SetItemLabel( //We need a _T() macro (wide char-> L"", char->"") for EACH //line to make it compatible between char and wide char. wxT("enable Own DVFS") ) ; LOGN( "end") } void MainFrame::Notify() //overrides wxTimer::Notify() { LOGN(/*"Notify"*/ "begin") m_bDrawFreqAndVoltagePointForCurrCoreSettings = ! m_bDrawFreqAndVoltagePointForCurrCoreSettings ; Refresh() ; } //Called by the destructor and by OnDetachCPUcontrollerDLL() void MainFrame::PossiblyReleaseMemForCPUcontrollerUIcontrols() { // BYTE byMenuPosFor1stCPUcore = //2 // m_byIndexOf1stCPUcontrollerRelatedMenu ; LOGN(//"PossiblyReleaseMemForCPUcontrollerUIcontrols " "begin") #ifdef ONE_P_STATE_DIALOG_FOR_EVERY_CPU_CORE //May be NULL if the CPU controller is NULL. if( m_arp_freqandvoltagesettingdlg ) { //Release dynamically allocated memory (inside OnInit() ) : for( BYTE byCPUcoreID = 0 ; byCPUcoreID < mp_cpucoredata-> m_byNumberOfCPUCores ; ++ byCPUcoreID ) { if ( m_arp_freqandvoltagesettingdlg[ byCPUcoreID ] ) { m_arp_freqandvoltagesettingdlg[ byCPUcoreID ]-> //http://docs.wxwidgets.org/2.6/wx_wxwindow.html#wxwindowdestroy: //"Use this function instead of the delete operator[...]" //"true if the window has either been successfully deleted, or it //has been added to the list of windows pending real deletion." Destroy() ; } } //Delete the array containing the pointers delete [] m_arp_freqandvoltagesettingdlg ; m_arp_freqandvoltagesettingdlg = NULL ; LOGN(//"PossiblyReleaseMemForCPUcontrollerUIcontrols " "end") } //for( std::vector<wxMenu *>::const_iterator c_i = m_vecp_wxmenuCore.begin() // ; c_i != m_vecp_wxmenuCore.end() ; ++ c_i ) //{ // //(*c_i)->Destroy() ; // mp_wxmenubar->Remove(2) ; // delete (*c_i) ; //} //if( ! m_vecp_wxmenuCore.empty() ) for( BYTE byCoreID = mp_cpucoredata->m_byNumberOfCPUCores - 1 ; byCoreID != //gets 255 if it was 0 before and then 1 is subtracted. 255 ; -- byCoreID ) { wxMenu * p_wxmenu = mp_wxmenubar->Remove( byMenuPosFor1stCPUcore + byCoreID ) ; delete p_wxmenu ; } //for( std::vector<wxMenu *>::const_iterator c_i = m_stdvecp_wxmenuCore.begin() // ; c_i != m_vecp_wxmenuCore.end() ; ++ c_i // ) //{ //} #else //ONE_P_STATE_DIALOG_FOR_EVERY_CPU_CORE m_stdvec_p_freqandvoltagesettingdlg.clear() ; //TODO runtime error in Linux debug version const int numMenus = mp_wxmenubar->GetMenuCount(); wxMenu * p_wxmenu = mp_wxmenubar->Remove( //Linux does not have a "service menu"-> 1 index less than under Windows. //Remove the "core(s)" menu. // 3 numMenus - 1 ) ; delete p_wxmenu ; #endif //ONE_P_STATE_DIALOG_FOR_EVERY_CPU_CORE m_vecp_wxmenuCore.clear() ; } void MainFrame::PossiblyAskForOSdynFreqScalingDisabling() { LOGN("begin") #ifdef COMPILE_WITH_OTHER_DVFS_ACCESS bool bOtherDVFSisEnabled = //mp_i_cpucontroller->mp_dynfreqscalingaccess->OtherDVFSisEnabled() //mp_i_cpucontroller->OtherPerfCtrlMSRwriteIsActive() mp_wxx86infoandcontrolapp->mp_dynfreqscalingaccess->OtherDVFSisEnabled(); LOGN("bOtherDVFSisEnabled: " << bOtherDVFSisEnabled) if( bOtherDVFSisEnabled ) { if (::wxMessageBox( //We need a _T() macro (wide char-> L"", char->"") for EACH //line to make it compatible between char and wide char. _T("The OS's dynamic frequency scaling must be disabled ") _T("in order that the p-state isn' changed by the OS afterwards.") _T("If the OS's dynamic frequency isn't disabled, should it be done now?") , //We need a _T() macro (wide char-> L"", char->"") for EACH //line to make it compatible between char and wide char. _T("Question") , wxYES_NO | wxICON_QUESTION ) == wxYES ) //mp_i_cpucontroller->DisableFrequencyScalingByOS(); mp_wxx86infoandcontrolapp->mp_dynfreqscalingaccess-> DisableFrequencyScalingByOS() ; } #endif //#ifdef COMPILE_WITH_OTHER_DVFS_ACCESS LOGN("end") } //#ifdef _TEST_PENTIUM_M #ifdef COMPILE_WITH_MSR_EXAMINATION void MainFrame::OnShowExamineCPUregistersDialog(wxCommandEvent& WXUNUSED(event)) { ////May be NULL at startup. //if( mp_i_cpucontroller ) //{ wxExamineCPUregistersDialog * p_wxdlg = new wxExamineCPUregistersDialog( this , //msrdata //*mp_i_cpucontroller->mp_model, //mp_i_cpucontroller //mp_wxx86infoandcontrolapp->GetCPUaccess() //, mp_wxx86infoandcontrolapp ); //p_wxdlg->ShowModal() ; p_wxdlg->Show(true) ; //} // if( mp_i_cpucontroller ) } #endif void MainFrame::OnDynamicallyCreatedUIcontrol(wxCommandEvent & wxevent) { LOGN(//"on dyn created control" "begin") int nMenuEventID = wxevent.GetId() ; #ifdef COMPILE_WITH_OTHER_DVFS_ACCESS // if( nMenuEventID == ID_MinAndMaxCPUcoreFreqInPercentOfMaxFreq ) // { // //wxMessageDialog(); // //wxMessageBox("hh") ; // //wxString strCurrentValue = wxT("50") ; // //wxString sNewValue = wxGetTextFromUser(wxT("Enter min CPU %for // CURRENT power profile (scheme)"), ////#ifndef _DEBUG // // wxT("title"), strCurrentValue); // if( ::wxGetApp().mp_dynfreqscalingaccess->OtherDVFSisEnabled() // ) ////#endif // ::wxGetApp().mp_dynfreqscalingaccess->DisableFrequencyScalingByOS() ; ////#ifndef _DEBUG // else // ::wxGetApp().mp_dynfreqscalingaccess->EnableFrequencyScalingByOS() ; ////#endif //#ifdef _DEBUG // mp_wxmenuitemOtherDVFS->SetText(//_T("") // wxString::Format( // //We need a _T() macro (wide char-> L"", char->"") for EACH // //line to make it compatible between char and wide char. // _T("%sable DVFS") , // ::wxGetApp().mp_dynfreqscalingaccess->OtherDVFSisEnabled() ? // //We need a _T() macro (wide char-> L"", char->"") for EACH // //line to make it compatible between char and wide char. // _T("dis") : // //We need a _T() macro (wide char-> L"", char->"") for EACH // //line to make it compatible between char and wide char. // _T("en") // ) // ) ; // return ; //} #endif //#ifdef COMPILE_WITH_OTHER_DVFS_ACCESS //#endif BYTE byCoreID = ( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID ) / m_nNumberOfMenuIDsPerCPUcore ; //EventIDToDivisorIDandFrequencyID(nMenuEventID); if( //Array was successfully allocated. m_arp_freqandvoltagesettingdlg //&& ////menu item "set frequency and voltage" for any CPU core menu was selected. //( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID ) % //m_nNumberOfMenuIDsPerCPUcore == 0 ) { //FreqAndVoltageSettingDlg freqandvoltagesettingdlg(this); //freqandvoltagesettingdlg.Show(true); //if( mp_freqandvoltagesettingdlg ) //{ // //if(mp_freqandvoltagesettingdlg ) // mp_freqandvoltagesettingdlg->Show(true); //} //else //{ // //If created as local variable on stack the dialog would disappear // //immediately. // mp_freqandvoltagesettingdlg = new FreqAndVoltageSettingDlg(this); // if(mp_freqandvoltagesettingdlg ) // mp_freqandvoltagesettingdlg->Show(true); //} BYTE bySubmenuIndexWithinPerCoreMenu = ( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID ) % m_nNumberOfMenuIDsPerCPUcore ; switch( bySubmenuIndexWithinPerCoreMenu ) { case //0: Settings : if( mp_cpucoredata->m_arfAvailableMultipliers && mp_cpucoredata->m_arfAvailableVoltagesInVolt ) { if( m_arp_freqandvoltagesettingdlg[byCoreID] ) m_arp_freqandvoltagesettingdlg[byCoreID]->Show(true); } else { //TODO the dialog may be shown, but writing the p-state must be //prevented if there are no voltages and/ or multipliers because //_usually_ (voltage not for Nehalem/ i7 720 qm ) both are needed. if( ! mp_cpucoredata->m_arfAvailableMultipliers ) wxMessageBox( wxT("no multipliers available->no setting possible") ) ; if( ! mp_cpucoredata->m_arfAvailableVoltagesInVolt ) wxMessageBox( wxT("no multipliers available->no setting possible") ) ; } // else // { // //If created as local variable on stack the dialog would disappear // //immediately. // if( m_arp_freqandvoltagesettingdlg[byCoreID] ) // m_arp_freqandvoltagesettingdlg[byCoreID]->Show(true); // } break; // case setp_state2: // PossiblyAskForOSdynFreqScalingDisabling(); // Set the register where the VID and multiplier values for p-state 2 // reside as current (works at least for AMD Griffin) // mp_i_cpucontroller->SetPstate(2, // //1 = 1bin // 1 << // //=core ID: // //difference between current menu ID first menu ID for // //core settings // ( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID ) // / m_nNumberOfMenuIDsPerCPUcore); // break; case highLoadThread: { //m_byNumberOfSettablePstatesPerCore + 1: // BYTE byCoreID = // //=core ID: // //difference between current menu ID first menu ID for // //core settings // ( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID ) // / m_nNumberOfMenuIDsPerCPUcore ; //mp_i_cpucontroller->mp_calculationthread->StartCalculationThread( // //=core ID: // //difference between current menu ID first menu ID for // //core settings // ( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID ) // / m_nNumberOfMenuIDsPerCPUcore // ); //TODO uncomment //BYTE byAction = mp_i_cpucontroller->StartOrStopCalculationThread( // byCoreID // ); //BuildHighLoadThreadMenuText( // " high load thread (e.g. for stability check)" , byAction ) ; } break; default: m_stdmapwmenuid2i_cpucontrolleraction.find(nMenuEventID)-> second->Execute() ; //if( bySubmenuIndexWithinPerCoreMenu == m_byNumberOfSettablePstatesPerCore + 1) //{ //BYTE byCoreID = // //=core ID: // //difference between current menu ID first menu ID for // //core settings // ( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID ) // / m_nNumberOfMenuIDsPerCPUcore ; ////mp_i_cpucontroller->mp_calculationthread->StartCalculationThread( //// //=core ID: //// //difference between current menu ID first menu ID for //// //core settings //// ( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID ) //// / m_nNumberOfMenuIDsPerCPUcore //// ); //BYTE byAction = mp_i_cpucontroller->StartOrStopCalculationThread( // byCoreID // ); //wxString wxstr = byAction == ENDED ? "Start" : "End" ; //////Invert the menu item's checked state. ////marp_wxmenuItemHighLoadThread[byCoreID]->Check( //// ! marp_wxmenuItemHighLoadThread[byCoreID]->IsChecked () ) ; //marp_wxmenuItemHighLoadThread[byCoreID]->SetText( // wxstr + // " high load thread (e.g. for stability check)" // ); //} if( bySubmenuIndexWithinPerCoreMenu //> 0 >= m_byMenuIndexOf1stPstate && bySubmenuIndexWithinPerCoreMenu < //bySubmenuIndexWithinPerCoreMenu m_byMenuIndexOf1stPstate + m_byNumberOfSettablePstatesPerCore ) { // BYTE byCoreID = // //=core ID: // //difference between current menu ID first menu ID for // //core settings // ( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID ) // / m_nNumberOfMenuIDsPerCPUcore ; // BYTE byCoreBitMask = // //1 = 1bin // 1 << byCoreID ; PossiblyAskForOSdynFreqScalingDisabling(); //mp_i_cpucontroller->SetPstate( // bySubmenuIndexWithinPerCoreMenu - m_byMenuIndexOf1stPstate , // //byCoreBitMask // byCoreID // ); } break; } } } void MainFrame::OnFindLowestOperatingVoltage(wxCommandEvent& WXUNUSED(event)) { //TODO uncomment //mp_i_cpucontroller->FindLowestOperatingVoltage( // mp_i_cpucontroller->GetCurrentPstate(1),0); } #ifdef PRIVATE_RELEASE //hide the other possibilities void MainFrame::OnIncreaseVoltageForCurrentPstate(wxCommandEvent& WXUNUSED(event)) { mp_i_cpucontroller->IncreaseVoltageForCurrentPstate(); } #endif //#ifdef PRIVATE_RELEASE //hide the other possibilities void MainFrame::OnRedrawEverything(wxCommandEvent & evt ) { LOGN( "begin") RedrawEverything(); } #ifdef wxHAS_POWER_EVENTS void MainFrame::OnResume(wxPowerEvent & WXUNUSED(event) ) { LOGN( "resumed from standby/ hibernate") // HandleResumeForAllVoltAndFreqDlgs(); //May be NULL at startup. if( mp_i_cpucontroller ) { //mp_pumastatectrl->ApplyAllPStates() ; mp_i_cpucontroller->ResumeFromS3orS4() ; //After a resume (from standby) the counter value for CPU core 1 did not //change. //So re-initialize it now. if(::wxGetApp().mp_cpucoreusagegetter) ::wxGetApp().mp_cpucoreusagegetter->Init() ; //wxLogMessage(_T("System resumed from suspend.")); } // if( mp_i_cpucontroller ) LOGN( "end") } #endif // wxHAS_POWER_EVENTS //void MainFrame::OnInitDialog(wxInitDialogEvent& event ) //{ // LOGN("OnInitDialog") //// RedrawEverything() ; //// Update() ; //// Refresh() ; //} void MainFrame::OnSaveVoltageForFrequencySettings(wxCommandEvent & WXUNUSED(event) ) { std::string std_strCPUtypeRelativeDirPath; if( //wxGetApp().m_maincontroller.GetPstatesDirPath( mp_wxx86infoandcontrolapp->m_maincontroller.GetPstatesDirPath( std_strCPUtypeRelativeDirPath ) ) mp_wxx86infoandcontrolapp->SaveVoltageForFrequencySettings( std_strCPUtypeRelativeDirPath); } void MainFrame::OnSaveAsCPUcontrollerDynLibForThisCPU( wxCommandEvent & WXUNUSED(event) ) { mp_wxx86infoandcontrolapp->SaveAsCPUcontrollerDynLibForThisCPU(); } void MainFrame::OnSize( wxSizeEvent & //WXUNUSED( sizeevent//) ) { LOGN( "begin" ) RedrawEverything() ; } void MainFrame::OnSizing(wxSizeEvent & wxSizeEvent) { LOGN("begin") } #ifdef wxHAS_POWER_EVENTS void MainFrame::OnSuspending(wxPowerEvent & WXUNUSED(event)) { LOGN( "suspending power event") } void MainFrame::OnSuspended(wxPowerEvent & WXUNUSED(event)) { LOGN( "suspended power event") } void MainFrame::OnSuspendCancel(wxPowerEvent & WXUNUSED(event)) { LOGN("cancelled suspend power event") } #endif //#ifdef wxHAS_POWER_EVENTS //void GetCurrentPstateAndAddDefaultVoltage() //{ // //Do something // bool bNewVoltageAndFreqPair = false ; // float fVoltageInVolt ; // WORD wFreqInMHz ; // std::pair <std::set<VoltageAndFreq>::iterator, bool> // stdpairstdsetvoltageandfreq ; // for ( BYTE byCPUcoreID = 0 ; byCPUcoreID < // mp_cpucoredata->m_byNumberOfCPUCores ; ++ byCPUcoreID ) // { // if( mp_i_cpucontroller->GetCurrentPstate(wFreqInMHz, fVoltageInVolt, // byCPUcoreID ) ) // { // #ifdef _DEBUG // if( wFreqInMHz > 1800 ) // wFreqInMHz = wFreqInMHz ; // #endif // //stdpairstdsetvoltageandfreq = mp_model->m_cpucoredata. // // m_stdsetvoltageandfreqDefault.insert( // // VoltageAndFreq ( fVoltageInVolt , wFreqInMHz ) // // ) ; // if( mp_model->m_bCollectPstatesAsDefault ) // bNewVoltageAndFreqPair = mp_model->m_cpucoredata. // AddDefaultVoltageForFreq( // fVoltageInVolt , wFreqInMHz ) ; // ////New p-state inserted. // //if( stdpairstdsetvoltageandfreq.second ) // // bNewVoltageAndFreqPair = true ; // } // } // if( bNewVoltageAndFreqPair ) // { // std::set<VoltageAndFreq>::reverse_iterator reviter = // mp_model->m_cpucoredata.m_stdsetvoltageandfreqDefault.rbegin() ; // //Need to set the max freq. Else (all) the operating points are // // drawn at x-coord. "0". // mp_cpucoredata->m_wMaxFreqInMHz = (*reviter).m_wFreqInMHz ; // if( mp_model->m_cpucoredata.m_stdsetvoltageandfreqDefault.size() > 1 // //&& ! mp_wxmenuitemOwnDVFS->IsEnabled() // ) // mp_wxmenuitemOwnDVFS->Enable(true) ; // RedrawEverything() ; // } // else //} void MainFrame::OnTimerEvent(wxTimerEvent & event) { LOGN( "begin") // DEBUGN("OnTimerEvent CPU controller pointer:" << mp_i_cpucontroller ) // LOGN("OnTimerEvent " // "CPU controller pointer:" << mp_i_cpucontroller ) //May be NULL at startup. I_CPUcontroller * p_cpucontroller ; // ICPUcoreUsageGetter * p_cpucoreusagegetter ; #ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE if( //::wxGetApp().m_ipcclient.IsConnected() mp_wxx86infoandcontrolapp->IPC_ClientIsConnected() ) { p_cpucontroller = & mp_wxx86infoandcontrolapp->m_sax2_ipc_current_cpu_data_handler ; // p_cpucoreusagegetter = & // mp_wxx86infoandcontrolapp->m_sax2_ipc_current_cpu_data_handler ; if( ! mp_wxbitmap ) RecreateDisplayBuffers() ; } else #endif //#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE { p_cpucontroller = mp_i_cpucontroller ; // p_cpucoreusagegetter = mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter ; } if( //mp_i_cpucontroller p_cpucontroller ) { bool bAllowCPUcontrollerAccess = IsCPUcontrollerAccessAllowedThreadSafe() ; // DEBUGN("CPU controller access allowed:" << bAllowCPUcontrollerAccess ) if( //m_bAllowCPUcontrollerAccess bAllowCPUcontrollerAccess ) { static bool isIconized, isVisible; isIconized = IsIconized(); //TODO: returns true even if not visible (hidden bei other frames) -> // get window client update regions to decide whether to redraw. isVisible = IsVisible(); //Even if this window is not visible (iconized/ hidden) the highest //temperature should be shown in the task bar/ system tray. if( //If the window is hidden, "IsIconized()" returns "false"? isIconized || // ! // //"Returns true if this window is currently active, i.e. if the user // //is currently working with it." // IsActive() ! //IsVisible() returns true (even) if the window is iconized. isVisible ) { //If this window is iconized then OnPaint(...) isn't called and so //"StoreCurrentVoltageAndFreqInArray(...)" is _not_ being called //(indirectly), so get the current temperature here. // if( s_arfTemperatureInDegreesCelsius ) // delete [] s_arfTemperatureInDegreesCelsius ; // s_arfTemperatureInDegreesCelsius = new float[ mp_cpucoredata-> // m_byNumberOfCPUCores ] ; ICPUcoreUsageGetter * p_cpucoreusagegetter ; I_CPUcontroller * p_cpucontroller ; if( GetCPUcoreInfoDirectlyOrFromService( p_cpucoreusagegetter, p_cpucontroller //, // wxstrCPUcoreUsage , //bool bGetCPUcoreUsage // false mp_model->m_userinterfaceattributes. m_bShowCPUcoreUsagesIconInTaskBar ) ) { LOGN(//"DrawCurrentCPUcoreData " "leaving IPC 2 in-program data crit sec") mp_cpucoredata->wxconditionIPC2InProgramData.Leave() ; LOGN(//"DrawCurrentCPUcoreData " "after leaving IPC 2 in-program data crit sec") #ifdef COMPILE_WITH_SYSTEM_TRAY_ICON if( mp_wxx86infoandcontrolapp->m_p_HighestCPUcoreTemperatureTaskBarIcon ) { //respect # of cpu cores for ( WORD wCPUcoreID = 0 ; wCPUcoreID < mp_cpucoredata->m_byNumberOfCPUCores ; ++ wCPUcoreID ) { s_arfTemperatureInDegreesCelsius[ wCPUcoreID ] = p_cpucontroller-> GetTemperatureInCelsius(wCPUcoreID) ; } ShowHighestCPUcoreTemperatureInTaskBar(p_cpucontroller) ; } #endif //#ifdef COMPILE_WITH_SYSTEM_TRAY_ICON ShowCPUcoreUsagesInTaskBar(p_cpucontroller); if( mp_model->m_userinterfaceattributes.m_bShowCPUcoreUsagesIconInTaskBar ) { //respect # of cpu cores for ( WORD wCPUcoreID = 0 ; wCPUcoreID < mp_cpucoredata->m_byNumberOfCPUCores ; ++ wCPUcoreID ) p_cpucontroller->GetCurrentVoltageAndFrequencyAndStoreValues( wCPUcoreID); ShowCPUcoresMultipliersInTaskBar(p_cpucontroller); } } } else // !IsIconized() && IsVisible() { // GetCurrentPstateAndAddDefaultVoltage(); if( m_bDiagramNotDrawn //&& mp_i_cpucontroller && //mp_i_cpucontroller->m_fReferenceClockInMHz p_cpucontroller->m_fReferenceClockInMHz ) { LOGN("diagram not already drawn and reference clock <> 0 ") // bool bAllowCPUcontrollerAccess = // IsCPUcontrollerAccessAllowedThreadSafe() ; // if( //bAllowCPUcontrollerAccess && // mp_i_cpucontroller-> // m_fReferenceClockInMHz ) // { //The diagram is based on the CPU core frequency and can be drawn at //first when the reference clock is known. RedrawEverything() ; m_bDiagramNotDrawn = false ; // } } else //http://docs.wxwidgets.org/trunk/classwx_window.html // #29dc7251746154c821b17841b9877830: //"Causes this window, and all of its children recursively (except //under wxGTK1 where this is not implemented), to be repainted. //Note that repainting doesn't happen immediately but only during the //next event loop iteration, if you need to update the window //immediately you should use Update() instead." // -> EVT_PAINT -> MainFrame::OnPaint(...) is called. Refresh() ; } } //TRACE("OnTimerEvent\n") ; } // if( mp_i_cpucontroller ) else //if( mp_i_cpucontroller ) { if( mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter ) //Also refresh if just a core usage getter (for showing the usage per //core) Refresh() ; } LOGN( "end") } void MainFrame::OnUpdateViewInterval(wxCommandEvent & WXUNUSED(event)) { wxString wxstrMessage = wxT("Input update view interval in milliseconds") ; wxString wxstrInput = ::wxGetTextFromUser( wxstrMessage , wxT("input"), wxT("1000") ) ; //::wxGetNumberFromUser //If the user has input text (and has NOT pressed "cancel") if( ! wxstrInput.empty() ) { unsigned long ulMs ; bool bSuccess = wxstrInput.ToULong(& ulMs) ; if ( bSuccess ) { //ReadMsrEx() returned false results if used with a time and a 10 ms interval. if( ulMs < 100 ) wxMessageBox( wxT("the number is too low. ") wxT("Getting the current CPU frequency returned wrong values with < 100 ms") ) ; else { m_dwTimerIntervalInMilliseconds = ulMs ; m_wxtimer.Stop() ; m_wxtimer.Start(ulMs) ; // m_p_wxtimer->Stop() ; // m_p_wxtimer->Start(ulMs) ; } } else { wxMessageBox( wxT("You did not enter a valid integer number") ) ; } } } void MainFrame::OnShowCPUregistersReadAndWriteDialog( wxCommandEvent & WXUNUSED(event) ) { #ifndef _DEBUG //May be NULL at startup. if( mp_i_cpucontroller ) #endif { #ifdef COMPILE_WITH_MSR_EXAMINATION CPUregisterReadAndWriteDialog * p_wxdlg = new CPUregisterReadAndWriteDialog( this , //msrdata //*mp_i_cpucontroller->mp_model, * mp_model , mp_i_cpucontroller //mp_i_cpucontroller->mp_cpuaccess //, mp_wxx86infoandcontrolapp ); //p_wxdlg->ShowModal() ; p_wxdlg->Show(true) ; #endif //#ifdef COMPILE_WITH_MSR_EXAMINATION } //if( mp_i_cpucontroller ) } void MainFrame::RecreateDisplayBuffers() { LOGN(//"RecreateDisplayBuffers " "begin") if( mp_wxbitmap ) delete mp_wxbitmap ; wxRect rect = GetClientRect(); //wxCoord wxcoordCanvasWidth ; //wxCoord wxcoordCanvasHeight ; //p_wxpaintdc->GetSize( & wxcoordCanvasWidth , & wxcoordCanvasHeight ) ; m_wDiagramHeight = rect.height //Space for drawing scale and scale values below the x-axis. - 50 ; //WORD wXcoordOfBeginOfYaxis = 50 ; m_wXcoordOfBeginOfYaxis = 50 ; //WORD wDiagramWidth = wxcoordCanvasWidth - wXcoordOfBeginOfYaxis - 30 ; m_wDiagramWidth = rect.width - m_wXcoordOfBeginOfYaxis - 30 ; mp_wxbitmap = new wxBitmap( rect.width, rect.height , //http://docs.wxwidgets.org/stable/wx_wxbitmap.html#wxbitmapctor: //"A depth of -1 indicates the depth of the current screen or visual." -1) ; //if( mp_wxbufferedpaintdcStatic ) // delete mp_wxbufferedpaintdcStatic ; //create new objet so it uses internally an bitmap with the new client size. //mp_wxbufferedpaintdcStatic = new wxBufferedPaintDC(this) ; if( mp_wxbitmapStatic ) delete mp_wxbitmapStatic ; mp_wxbitmapStatic = new wxBitmap( rect.width, rect.height , //http://docs.wxwidgets.org/stable/wx_wxbitmap.html#wxbitmapctor: //"A depth of -1 indicates the depth of the current screen or visual." -1) ; m_wxmemorydcStatic.SelectObject(*mp_wxbitmapStatic) ; //Clears the device context using the current background brush. //(else black background?) m_wxmemorydcStatic.Clear(); m_wMinYcoordInDiagram = //Let the diagram begin at the vertical middle of the topmost voltage value. m_wxmemorydcStatic.GetCharHeight() / 2 ; } //in order to draw voltage and freq aligned if more than 1 core/ to draw at //the same pos for many intervals: //core 0: 0.9 V 1100 MHz //core 1: 1.11 V 550 MHz void MainFrame::DetermineMaxVoltageAndMaxFreqDrawWidth(wxDC & r_wxdc) { wxString wxstrMaxFreq = wxString::Format( //Use wxT() to enable to compile with both unicode and ANSI. wxT("%u"), mp_cpucoredata->m_wMaxFreqInMHz ) ; //the max. freq. usually has the max draw width. m_wMaxFreqWidth = r_wxdc.GetTextExtent(wxstrMaxFreq).GetWidth() ; //Because max. voltage ID is lowest voltage for AMD Griffin but highest //voltage for Pentium M. float fVoltageForMaxVoltageID = mp_i_cpucontroller->GetVoltageInVolt( mp_cpucoredata->m_byMaxVoltageID ) ; float fVoltageForMinVoltageID = mp_i_cpucontroller->GetVoltageInVolt( mp_cpucoredata->m_byMinVoltageID ) ; float fMaxVoltage = fVoltageForMaxVoltageID > fVoltageForMinVoltageID ? fVoltageForMaxVoltageID : fVoltageForMinVoltageID ; wxString wxstrMaxVolt = wxString::Format( //Use wxT() to enable to compile with both unicode and ANSI. wxT("%f"), fMaxVoltage ) ; //the max. voltage usually has the max draw width. m_wMaxVoltageWidth = r_wxdc.GetTextExtent(wxstrMaxFreq).GetWidth() ; } void MainFrame::DetermineTextHeight(wxDC & r_wxdc) { wxCoord wxcoordWidth ; wxCoord wxcoordHeight ; wxCoord wxcoordDescent ; r_wxdc.GetTextExtent( wxT("|"), & wxcoordWidth , //wxCoord *w, & wxcoordHeight , //wxCoord *h, & wxcoordDescent //wxCoord *descent = NULL, //wxCoord *externalLeading = NULL, wxFont *font = NULL ) ; m_wTextHeight = wxcoordHeight + wxcoordDescent ; } void MainFrame::RedrawEverything() { LOGN(//"RedrawEverything " "mp_i_cpucontroller:" << mp_i_cpucontroller) DetermineTextHeight(m_wxmemorydcStatic) ; //May be NULL at startup. if( mp_i_cpucontroller ) // I_CPUcontroller * p_cpucontroller ; // if( ::wxGetApp().m_ipcclient.IsConnected() ) // { // p_cpucontroller = & // mp_wxx86infoandcontrolapp->m_sax2_ipc_current_cpu_data_handler ; // if( !mp_wxbitmap ) // RecreateDisplayBuffers() ; // } // else // { // p_cpucontroller = mp_i_cpucontroller ; // } // if( p_cpucontroller ) { DetermineMaxVoltageAndMaxFreqDrawWidth(m_wxmemorydcStatic) ; //Control access to m_bAllowCPUcontrollerAccess between threads. //m_wxCriticalSectionCPUctlAccess.Enter() ; //wxCriticalSectionLocker wxcriticalsectionlocker( // m_wxcriticalsectionCPUctlAccess ) ; bool bAllowCPUcontrollerAccess = IsCPUcontrollerAccessAllowedThreadSafe() ; LOGN(//"RedrawEverything " "bAllowCPUcontrollerAccess:" << bAllowCPUcontrollerAccess) if( //m_bAllowCPUcontrollerAccess bAllowCPUcontrollerAccess ) { // int i = 0 ; m_fMinVoltage = //mp_i_cpucontroller->GetMinimumVoltageInVolt() ; mp_model->m_cpucoredata.GetMinimumVoltage() ; float fMaxMulti = mp_model->m_cpucoredata.GetMaximumMultiplier() ; m_wMaximumCPUcoreFrequency = (WORD) ( fMaxMulti * mp_i_cpucontroller->m_fReferenceClockInMHz ) ; LOGN(//"RedrawEverything " "m_wMaximumCPUcoreFrequency=" << m_wMaximumCPUcoreFrequency << "=" << mp_i_cpucontroller->m_fReferenceClockInMHz << "*" << fMaxMulti ) RecreateDisplayBuffers(//m_wxmemorydcStatic ) ; //m_wxbufferedpaintdcStatic.SelectObject(mp_wxbitmapStatic) ; // if( mp_wxbufferedpaintdc // wxBufferedPaintDC mp_wxbufferedpaintdc ( this ) ; //Drawing the curves (calculate and draw ~ 400 points) takes some time. //So do it only when the client size changes and store the drawn curves //into a image and DrawBitmap() or do "Blit()" with the DC drawn to and //the DC that shows it in the window. //if( mp_wxbufferedpaintdcStatic ) { std::set<VoltageAndFreq> & r_setvoltageforfreq = //mp_i_cpucontroller-> mp_model->m_cpucoredata.m_stdsetvoltageandfreqDefault ; // std::set<MaxVoltageForFreq>::iterator iterstdsetmaxvoltageforfreq = // std::set<VoltageAndFreq>::reverse_iterator iterstdsetvoltageandfreq = // //m_setmaxvoltageforfreq.begin() ; // r_setvoltageforfreq.rbegin() ; if( //mp_i_cpucontroller->mp_model-> //m_setmaxvoltageforfreq.end() // iterstdsetvoltageandfreq != // r_setvoltageforfreq.rend() ! mp_cpucoredata->m_stdset_floatAvailableVoltagesInVolt.empty() ) { m_fMaxVoltage = //(*iterstdvecmaxvoltageforfreq).m_fVoltageInVolt ; ////P-state 0 usually has the highest voltage. //(*iterstdsetvoltageandfreq).m_fVoltageInVolt ; mp_cpucoredata->m_arfAvailableVoltagesInVolt[ mp_cpucoredata-> //Last element/ highest voltage. m_stdset_floatAvailableVoltagesInVolt.size() - 1 ] ; //for g++: assign value to created iterator and pass this to the arg std::set<VoltageAndFreq>::iterator iter = r_setvoltageforfreq.begin() ; DrawDiagramScale( m_wxmemorydcStatic , //iterstdsetvoltageandfreq //r_setvoltageforfreq.begin() iter ) ; } m_fMaxMinusMinVoltage = m_fMaxVoltage - m_fMinVoltage ; DrawVoltageGraph( //m_wxbufferedpaintdcStatic //*mp_wxbufferedpaintdcStatic m_wxmemorydcStatic , m_fMaxVoltage , mp_cpucoredata->m_stdsetvoltageandfreqDefault ) ; DrawCurrentVoltageSettingsCurve( //m_wxbufferedpaintdcStatic //*mp_wxbufferedpaintdcStatic m_wxmemorydcStatic , m_fMaxVoltage //, mp_cpucoredata->m_stdsetvoltageandfreqWanted ) ; DrawLowestStableVoltageCurve( //m_wxbufferedpaintdcStatic //*mp_wxbufferedpaintdcStatic m_wxmemorydcStatic , m_fMaxVoltage ) ; // DrawAllPossibleOperatingPoints( m_wxmemorydcStatic ) ; DrawPerformanceStatesCrosses( m_wxmemorydcStatic , mp_cpucoredata->m_stdsetvoltageandfreqDefault , wxBLACK ) ; DrawPerformanceStatesCrosses( m_wxmemorydcStatic , mp_cpucoredata->m_stdsetvoltageandfreqWanted //The wanted voltage may be above the default voltage because the //default voltage may be too low (e.g. for AMD Turion X2 Ultra //2400 MHz) , wxGREEN ) ; DrawPerformanceStatesCrosses( m_wxmemorydcStatic , mp_cpucoredata->m_stdsetvoltageandfreqLowestStable , wxRED ) ; } } //if( bAllowCPUcontrollerAccess) //m_wxcriticalsectionCPUctlAccess.Leave() ; } // if( mp_i_cpucontroller ) else { if( #ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE //::wxGetApp().m_ipcclient.IsConnected() mp_wxx86infoandcontrolapp->IPC_ClientIsConnected() || #endif //#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter ) //Necessary for OnPaint() ; RecreateDisplayBuffers() ; } LOGN(//"RedrawEverything #" "end") } //Also called when CPU controller was changed. void MainFrame::SetCPUcontroller(I_CPUcontroller * p_cpucontroller ) { LOGN(//"SetCPUcontroller " "begin") mp_i_cpucontroller = p_cpucontroller ; m_wMaxFreqInMHzTextWidth = 0 ; m_wMaxVoltageInVoltTextWidth = 0 ; m_wMaxTemperatureTextWidth = 0 ; } void MainFrame::ShowCPUcoreUsagesInTaskBar( I_CPUcontroller * p_i_cpucontroller) { #ifdef COMPILE_WITH_SYSTEM_TRAY_ICON if( mp_model->m_userinterfaceattributes.m_bShowCPUcoreUsagesIconInTaskBar ) { LOGN_DEBUG("mp_taskbaricon:" << mp_wxx86infoandcontrolapp->m_p_CPUcoreUsagesTaskbarIcon ) if( mp_wxx86infoandcontrolapp->m_p_CPUcoreUsagesTaskbarIcon ) { //TODO make wxIcon (and other params) member variables of class TaskBarIcon //or wxicondrawer mp_wxx86infoandcontrolapp->m_p_CPUcoreUsagesTaskbarIcon-> m_p_wxicon_drawer->DrawColouredBarsIcon( s_wxiconCPUcoreUsages, mp_cpucoredata->m_arfCPUcoreLoadInPercent, mp_cpucoredata->m_byNumberOfCPUCores ); if( mp_wxx86infoandcontrolapp->m_p_CPUcoreUsagesTaskbarIcon->SetIcon( s_wxiconCPUcoreUsages, wxT("x86IandC--CPU cores usages") ) ) { #ifdef _DEBUG wxBitmap & wxbmp //(s_wxiconCPUcoreUsages); = * mp_wxx86infoandcontrolapp->m_p_CPUcoreUsagesTaskbarIcon-> m_p_wxicon_drawer->m_p_wxbitmapToDrawOn; wxbmp.SaveFile( // const wxString& name wxT("CPUcoreUsages.bmp") //wxBitmapType type , //wxBITMAP_TYPE_XPM did work on Windows wxBITMAP_TYPE_BMP ); #endif // if( ! mp_wxmenuFile->IsEnabled() ) //The menu item may be disabled if setting the icon failed for the //1st time (if started via the service on logon and the the task bar //was not ready). //TODO wx assert here if no menu item with ID "ID_MinimizeToSystemTray" //was added. // mp_wxmenuFile->Enable(ID_MinimizeToSystemTray, true); } else { //::wxMessageBox( wxT("Could not set task bar icon."), // getwxString(mp_wxx86infoandcontrolapp->m_stdtstrProgramName) ) ; // LOGN("Could not set task bar icon.") mp_wxmenuFile->Enable(ID_MinimizeToSystemTray, false); } } } #endif //#ifdef COMPILE_WITH_SYSTEM_TRAY_ICON } void MainFrame::ShowCPUcoresMultipliersInTaskBar( I_CPUcontroller * p_i_cpucontroller) { #ifdef COMPILE_WITH_SYSTEM_TRAY_ICON if( mp_model->m_userinterfaceattributes. m_bShowCPUcoresMultipliersIconInTaskBar ) { LOGN_DEBUG("mp_taskbaricon:" << mp_wxx86infoandcontrolapp-> m_p_CPUcoresMultipliersTaskbarIcon ) if( mp_wxx86infoandcontrolapp->m_p_CPUcoresMultipliersTaskbarIcon ) { BYTE byNumberOfCPUcores = mp_cpucoredata->m_byNumberOfCPUCores; float * CPUcoreMultipliersInPercentOfMinAndMax = new float [ byNumberOfCPUcores]; LOGN( "Number Of CPU cores:" << (WORD) byNumberOfCPUcores << "CPUcoreMultipliersInPercentOfMinAndMax:" << CPUcoreMultipliersInPercentOfMinAndMax) if( CPUcoreMultipliersInPercentOfMinAndMax ) { float fMaximumCPUcoreMultiplier = mp_cpucoredata->GetMaximumMultiplier(); float fMinimumCPUcoreMultiplier = mp_cpucoredata->GetMinimumMultiplier(); float fMaxMultiMinusMinMulti = fMaximumCPUcoreMultiplier - fMinimumCPUcoreMultiplier; // float fVoltageInVolt; float fMultiplier; // float fReferenceClockInMHz; // WORD wCPUcoreID; float currentMultiMinusMinMulti; float CPUcoreMultiplierInPercentOfMinAndMax; for( WORD wCPUcoreID = 0; wCPUcoreID < byNumberOfCPUcores; ++ wCPUcoreID) { fMultiplier = mp_cpucoredata->m_arp_percpucoreattributes[ wCPUcoreID].m_fMultiplier; //GetCurrentVoltageAndFrequency(...) should have been called right before. // if( p_i_cpucontroller->GetCurrentVoltageAndFrequency( // fVoltageInVolt // , fMultiplier // , fReferenceClockInMHz // , wCPUcoreID // ) // ) { //possible_multis: [min_multi ... max_multi]. //current_multi is_element_of possible_multis. // max_minus_min_multi = max_multi - min_multi = 1.0 = 100% // current_multi_minus_min_multi = current_multi - min_multi. currentMultiMinusMinMulti = fMultiplier - fMinimumCPUcoreMultiplier; // current_multi in percent of possible_multis = // current_multi_minus_min_multi / max_minus_min_multi CPUcoreMultiplierInPercentOfMinAndMax = // fMinimumCPUcoreMultiplier / currentMultiMinusMinMulti; currentMultiMinusMinMulti / fMaxMultiMinusMinMulti; if( currentMultiMinusMinMulti == 0.0f) // x / 0 = infinite CPUcoreMultipliersInPercentOfMinAndMax[wCPUcoreID] = 0; else CPUcoreMultipliersInPercentOfMinAndMax[wCPUcoreID] = CPUcoreMultiplierInPercentOfMinAndMax; LOGN( "multiplier for CPU core # " << (WORD) wCPUcoreID << " in percent in range of " "min and max=" << fMaxMultiMinusMinMulti << " / (" << fMultiplier << " - " << fMinimumCPUcoreMultiplier << " ) = " << currentMultiMinusMinMulti << " / " << fMaxMultiMinusMinMulti << " = " << CPUcoreMultiplierInPercentOfMinAndMax) } } mp_wxx86infoandcontrolapp->m_p_CPUcoresMultipliersTaskbarIcon-> m_p_wxicon_drawer->DrawColouredBarsIcon( s_wxiconCPUcoresMultipliers, CPUcoreMultipliersInPercentOfMinAndMax, mp_cpucoredata->m_byNumberOfCPUCores ); delete [] CPUcoreMultipliersInPercentOfMinAndMax; } if( mp_wxx86infoandcontrolapp->m_p_CPUcoresMultipliersTaskbarIcon-> SetIcon(s_wxiconCPUcoresMultipliers, wxT("x86IandC--CPU cores multipliers in % of max - min multiplier") ) ) { #ifdef _DEBUG wxBitmap & wxbmp //(s_wxiconCPUcoreUsages); = * mp_wxx86infoandcontrolapp->m_p_CPUcoresMultipliersTaskbarIcon-> m_p_wxicon_drawer->m_p_wxbitmapToDrawOn; wxbmp.SaveFile( // const wxString& name wxT("CPUcoreMultipliers.bmp") //wxBitmapType type , //wxBITMAP_TYPE_XPM did work on Windows wxBITMAP_TYPE_BMP ); #endif // if( ! mp_wxmenuFile->IsEnabled() ) //The menu item may be disabled if setting the icon failed for the //1st time (if started via the service on logon and the the task bar //was not ready). //TODO wxWidgets debug alert ("no such ID "ID_MinimizeToSystemTray"??) //here?! // mp_wxmenuFile->Enable(ID_MinimizeToSystemTray, true); } else { //::wxMessageBox( wxT("Could not set task bar icon."), // getwxString(mp_wxx86infoandcontrolapp->m_stdtstrProgramName) ) ; // LOGN("Could not set task bar icon.") mp_wxmenuFile->Enable(ID_MinimizeToSystemTray, false); } } } #endif //#ifdef COMPILE_WITH_SYSTEM_TRAY_ICON } void MainFrame::ShowHighestCPUcoreTemperatureInTaskBar( I_CPUcontroller * p_i_cpucontroller) { #ifdef COMPILE_WITH_SYSTEM_TRAY_ICON LOGN_DEBUG("mp_taskbaricon:" << mp_wxx86infoandcontrolapp->m_p_HighestCPUcoreTemperatureTaskBarIcon) if( mp_wxx86infoandcontrolapp->m_p_HighestCPUcoreTemperatureTaskBarIcon ) { static wxLongLong_t wxlonglong_tLocalTimeMillis; wxlonglong_tLocalTimeMillis = ::wxGetLocalTimeMillis(). GetValue(); static long long llDiffInMillis; llDiffInMillis = wxlonglong_tLocalTimeMillis - // mp_cpucoredata->m_llLastTimeTooHot; p_i_cpucontroller->m_llLastTimeTooHot; static std::basic_string<LOGGING_CHARACTER_TYPE> str; MAKE_STRING_FROM_STRING_STREAM( str, "diff between current time and last time too hot=" << wxlonglong_tLocalTimeMillis << "-" << p_i_cpucontroller->m_llLastTimeTooHot << "=" << llDiffInMillis ) // g_logger.Log_inline( //FULL_FUNC_NAME, // str); LOGN_DEBUG( str) //Adapted from http://www.cppreference.com/wiki/valarray/max: std::valarray<float> stdvalarray_float(s_arfTemperatureInDegreesCelsius, mp_cpucoredata->m_byNumberOfCPUCores); float fHighestTemperature = stdvalarray_float.max() ; mp_wxx86infoandcontrolapp->GetTemperatureString(fHighestTemperature, s_wxstrHighestCPUcoreTemperative); //TODO // const wxFont & wxfontBefore = r_wxdc.GetFont(); //// int nFontPointSize = wxfont.GetPointSize(); // if( mp_model->m_userinterfaceattributes.m_nCurrentCPUcoreInfoSizeInPoint) // { // wxFont wxfont2(wxfont); // wxfont2.SetPointSize(mp_model->m_userinterfaceattributes. // m_nCurrentCPUcoreInfoSizeInPoint); // mp_wxx86infoandcontrolapp->m_p_HighestCPUcoreTemperatureTaskBarIcon-> // m_wxdc.SetFont(wxfont2); // } if( llDiffInMillis < 5000 ) mp_wxx86infoandcontrolapp->m_p_HighestCPUcoreTemperatureTaskBarIcon->//m_wxicon_drawer.DrawText( DrawText( s_wxiconTemperature, s_wxstrHighestCPUcoreTemperative, wxRED//, //wxWHITE ); else // CreateTextIcon( s_wxiconTemperature, s_wxstrHighestCPUcoreTemperative ) ; mp_wxx86infoandcontrolapp->m_p_HighestCPUcoreTemperatureTaskBarIcon->//m_wxicon_drawer.DrawText( DrawText( s_wxiconTemperature, s_wxstrHighestCPUcoreTemperative, wxBLACK//, // wxWHITE ); //TODO runtime error: "../src/gtk/bitmap.cpp(1328): assert "IsOk()" failed // in wxBitmap::GetPixbuf(): invalid bitmap" if( mp_wxx86infoandcontrolapp->m_p_HighestCPUcoreTemperatureTaskBarIcon->SetIcon( s_wxiconTemperature, s_wxstrTaskBarIconToolTip ) ) { // if( ! mp_wxmenuFile->IsEnabled() ) //The menu item may be disabled if setting the icon failed for the //1st time (if started via the service on logon and the the task bar //was not ready). //TODO wxWidgets debug alert ("no such ID "ID_MinimizeToSystemTray"??) //here?! // mp_wxmenuFile->Enable(ID_MinimizeToSystemTray, true); } else { //::wxMessageBox( wxT("Could not set task bar icon."), // getwxString(mp_wxx86infoandcontrolapp->m_stdtstrProgramName) ) ; // LOGN("Could not set task bar icon.") mp_wxmenuFile->Enable(ID_MinimizeToSystemTray, false); } } LOGN("end") #endif //#ifdef COMPILE_WITH_SYSTEM_TRAY_ICON } //void MainFrame::UpdatePowerSettings( // wxPowerType powerType, // wxBatteryState batteryState // ) //{ // LOGN("UpdatePowerSettings") // wxString powerStr; // switch ( m_powerType = powerType ) // { // case wxPOWER_SOCKET: // powerStr = _T("wall"); // break; // case wxPOWER_BATTERY: // powerStr = _T("battery"); // break; // default: // wxFAIL_MSG(_T("unknown wxPowerType value")); // // fall through // case wxPOWER_UNKNOWN: // powerStr = _T("psychic"); // break; // } // // wxString batteryStr; // switch ( m_batteryState = batteryState ) // { // case wxBATTERY_NORMAL_STATE: // batteryStr = _T("charged"); // break; // case wxBATTERY_LOW_STATE: // batteryStr = _T("low"); // break; // case wxBATTERY_CRITICAL_STATE: // batteryStr = _T("critical"); // break; // case wxBATTERY_SHUTDOWN_STATE: // batteryStr = _T("empty"); // break; // default: // wxFAIL_MSG(_T("unknown wxBatteryState value")); // // fall through // case wxBATTERY_UNKNOWN_STATE: // batteryStr = _T("unknown"); // break; // } // SetStatusText( wxString::Format ( // _T("System is on %s power, battery state is %s"), // powerStr.c_str(), // batteryStr.c_str() // ) // ); //}
36.241453
119
0.677207
st-gb
c129ce3df2ac2821743791aa84229de703f3143c
5,187
cpp
C++
src/original-content/VirtualFileSystem.cpp
KirmesBude/REGoth-bs
2e13dc3b9005744fccd7cea9c7e7cc1f94809e4a
[ "MIT" ]
399
2019-01-06T17:55:18.000Z
2022-03-21T17:41:18.000Z
src/original-content/VirtualFileSystem.cpp
KirmesBude/REGoth-bs
2e13dc3b9005744fccd7cea9c7e7cc1f94809e4a
[ "MIT" ]
101
2019-04-18T21:03:53.000Z
2022-01-08T13:27:01.000Z
src/original-content/VirtualFileSystem.cpp
KirmesBude/REGoth-bs
2e13dc3b9005744fccd7cea9c7e7cc1f94809e4a
[ "MIT" ]
56
2019-04-10T10:18:27.000Z
2022-02-08T01:23:31.000Z
#include "VirtualFileSystem.hpp" #include <FileSystem/BsFileSystem.h> #include <exception/Throw.hpp> #include <log/logging.hpp> #include <vdfs/fileIndex.h> using namespace REGoth; class REGoth::InternalVirtualFileSystem { public: InternalVirtualFileSystem() = default; virtual ~InternalVirtualFileSystem() = default; VDFS::FileIndex fileIndex; bool isFinalized = false; bool isReadyToReadFiles() { if (!isFinalized) { return false; } else { return true; } } void finalizeFileIndex() { fileIndex.finalizeLoad(); isFinalized = true; } }; void VirtualFileSystem::setPathToEngineExecutable(const bs::String& argv0) { VDFS::FileIndex::initVDFS(argv0.c_str()); mInternal = bs::bs_shared_ptr_new<InternalVirtualFileSystem>(); } void VirtualFileSystem::mountDirectory(const bs::Path& path) { throwOnMissingInternalState(); if (mInternal->isFinalized) { REGOTH_THROW(InvalidStateException, "Cannot mount directories on finalized file index."); } REGOTH_LOG(Info, Uncategorized, "[VDFS] Mounting directory (recursive): {0}", path.toString()); auto onDirectory = [&](const bs::Path& p) { bs::Path relative = p.getRelative(path); REGOTH_LOG(Info, Uncategorized, "[VDFS] - {0}", relative.toString()); mInternal->fileIndex.mountFolder(p.toString().c_str()); return true; }; enum { Recursive = true, NonRecursive = false, }; bs::FileSystem::iterate(path, nullptr, onDirectory, Recursive); } bool VirtualFileSystem::loadPackage(const bs::Path& package) { throwOnMissingInternalState(); if (mInternal->isFinalized) { REGOTH_THROW(InvalidStateException, "Cannot load packages on finalized file index."); } return mInternal->fileIndex.loadVDF(package.toString().c_str()); } bs::Vector<bs::String> VirtualFileSystem::listAllFiles() { std::vector<std::string> allStl = mInternal->fileIndex.getKnownFiles(); bs::Vector<bs::String> all(allStl.size()); for (size_t i = 0; i < allStl.size(); i++) { all[i] = allStl[i].c_str(); // Internal file index will return the files in the casing they were stored in. // To be consistent, convert them all to uppercase here. bs::StringUtil::toUpperCase(all[i]); } return all; } bs::Vector<bs::String> REGoth::VirtualFileSystem::listByExtension(const bs::String& ext) { bs::Vector<bs::String> allFilesUpperCase = listAllFiles(); // Convert extension to UPPERCASE since all files returned by listAllFiles() are also // uppercase. That way, we make the extension-parameter case insensitive. bs::String extUpper = ext; bs::StringUtil::toUpperCase(extUpper); enum { RespectCase = false, LowerCase = true, }; bs::Vector<bs::String> result; for (const auto& fileName : allFilesUpperCase) { // Respect case here since our only option is converting everything to lower case // with endsWith(). Since all our input strings are known to be uppercase, we can // just compare them without changing cases. if (bs::StringUtil::endsWith(fileName, extUpper, RespectCase)) { result.push_back(fileName); } } return result; } bs::Vector<bs::UINT8> VirtualFileSystem::readFile(const bs::String& file) const { throwOnMissingInternalState(); if (!mInternal->isFinalized) { mInternal->finalizeFileIndex(); } if (!mInternal->isReadyToReadFiles()) { REGOTH_THROW(InvalidStateException, "VDFS is not ready to read files yet."); } std::vector<uint8_t> stlData; mInternal->fileIndex.getFileData(file.c_str(), stlData); // FIXME: Need some other way to get the file data so we don't have to copy the data here return bs::Vector<bs::UINT8>(stlData.begin(), stlData.end()); } bool REGoth::VirtualFileSystem::hasFile(const bs::String& file) const { if (!mInternal) { REGOTH_THROW(InvalidStateException, "VDFS internal state not available, call setPathToEngineExecutable()"); } return mInternal->fileIndex.hasFile(file.c_str()); } void REGoth::VirtualFileSystem::throwIfFileIsMissing(const bs::String& file, const bs::String& message) const { if (!hasFile(file)) { if (message.empty()) { REGOTH_THROW( InvalidStateException, bs::StringUtil::format("Expected file {0} inside VDFS, but it could not be found!", file)); } else { REGOTH_THROW(InvalidStateException, message); } } } bool REGoth::VirtualFileSystem::hasFoundGameFiles() const { throwOnMissingInternalState(); return mInternal->fileIndex.getKnownFiles().size() > 0; } const VDFS::FileIndex& VirtualFileSystem::getFileIndex() { throwOnMissingInternalState(); if (!mInternal->isFinalized) { mInternal->finalizeFileIndex(); } return mInternal->fileIndex; } void VirtualFileSystem::throwOnMissingInternalState() const { if (!mInternal) { REGOTH_THROW(InvalidStateException, "VDFS internal state not available, call setPathToEngineExecutable()"); } } VirtualFileSystem& REGoth::gVirtualFileSystem() { static VirtualFileSystem vdfs; return vdfs; }
23.903226
101
0.687295
KirmesBude
c12c43a49f468d3824e69f180c6af93dcd98ce37
4,289
hpp
C++
include/ptg/HybridMultiFractal.hpp
bobbaluba/PTG
c5d18b78aa84174e42e20a7b0ab8468bf4f2136f
[ "Zlib" ]
12
2016-01-15T15:44:54.000Z
2021-02-01T08:10:38.000Z
include/ptg/HybridMultiFractal.hpp
bobbaluba/PTG
c5d18b78aa84174e42e20a7b0ab8468bf4f2136f
[ "Zlib" ]
null
null
null
include/ptg/HybridMultiFractal.hpp
bobbaluba/PTG
c5d18b78aa84174e42e20a7b0ab8468bf4f2136f
[ "Zlib" ]
2
2017-07-15T12:20:36.000Z
2018-05-02T21:17:31.000Z
/** * @file HybridMultiFractal.hpp * @date 12. nov. 2012 * @author Johan Klokkhammer Helsing */ #ifndef HYBRIDMULTIFRACTAL_HPP #define HYBRIDMULTIFRACTAL_HPP #include <ptg/Continuous2DSignal.hpp> #include <vector> namespace ptg { /** @brief Fractal noise generated using hybrid fractional brownian motion * * As described in this paper: * http://www8.cs.umu.se/kurser/TDBD12/HT01/papers/MusgraveTerrain00.pdf * * THIS IS THE DOCUMENTATION FOR FRACTIONAL BROWNIAN MOTION. The hybrid fractal is a slightly modified version * * The algorithm takes a Continuous2DSignal as its source to create a fractal noise * The noise is scaled to different frequencies and amplitudes, and these are added together. * * The algorithm is an easy way to create more interesting noise out of simple smoothed white noise, * such as Perlin noise or value noise. * * Complexity * ---------- * The complexity depends greatly on the choice of noise function. * If the noise function's complexity is f(n), the complexity of fbm is: * * THETA(WIDTH^2*octaves*f(n)) * * Where octaves is the number "layers" added together. This will usually be a number between 3 and 9. * * Limitations and Artifacts when used as terrain * ---------------------------------------------- * Depending on the choice of noise function, there may be a number of visible artifacts. * If your noise signal is repeating over a relatively short period, there will be visible artifacts in * the resulting terrain. The reason for this, is that when we are shading terrain, the diffuse lighting * depends on the derivative of the terrain, and therefore small changes will be visible. * * To solve this, you might either: * * Adjust gain so it's low enough that the highest octaves barely change the terrain values. * * Reduce the number of octaves, so the terrain won't repeat itself too much in the visible distance. * * Add a post-filter with diamond-square displacement to do the smallest levels of displacement, * as diamond square doesn't repeat itself, even on the smallest layers. * * Reduce specular/diffuse lighting and rely more on textures to show the tiniest bumps in the terrain. */ class HybridMultiFractal: public ptg::Continuous2DSignal { public: explicit HybridMultiFractal(unsigned int seed=0); virtual ~HybridMultiFractal(); virtual float get(float x, float y); virtual void onReSeed(unsigned int seed); /** @brief Sets the base noise function for the algorithm * suitable choices are ValueNoise or Perlin Noise */ virtual void setBaseNoise(Continuous2DSignal* signal){baseNoise=signal;} /** @brief Set the "depth" of the fractal noise. * Sets how many "layers" of noise we are going to add together. * Typical values lie between 3 and 9. */ virtual void setOctaves(unsigned int octaves){this->octaves=octaves; initExponents();} // @brief Gets number of octaves, see setOctaves virtual unsigned int getOctaves() const {return octaves;} /** @brief sets the lacunarity * this is the relation between the frequency of succesive layers in fbm-like algorithms */ virtual void setLacunarity(float lacunarity){this->lacunarity=lacunarity; initExponents();} virtual float getLacunarity() const {return lacunarity;} /** @brief sets the offset. This value is added to the noise before multiplications * * Assuming the noise value varies from -1 to 1, 0.7 will probably be a decent value */ virtual void setOffset(float offset){this->offset=offset;} virtual float getOffset() const {return offset;} /** @brief sets the H value * * This value controls how the amplitude changes from octave to octave. * A high value means the amplitude will decrease faster * 0.25 will probably be a decent value */ virtual void setH(float H){this->H = H; initExponents();} virtual float getH() const {return H;} HybridMultiFractal(const HybridMultiFractal&) = default; //copies will share the same base noise, this means that seeding one, will seed both. HybridMultiFractal & operator=(const HybridMultiFractal&) = default; private: void initExponents(); Continuous2DSignal* baseNoise; unsigned int octaves; float lacunarity; float offset; float H; std::vector<float> exponents; }; } // namespace ptg #endif // HYBRIDMULTIFRACTAL_HPP
39.348624
143
0.743064
bobbaluba
c132c760ea22d8d2cdd1a7ff0b7ce971edc987fe
2,054
cpp
C++
unitTest/matrixDecomps.cpp
akrodger/numples-cpp
4f0cd7b5dd66251fd02189480f3917aaefcc53f4
[ "MIT" ]
null
null
null
unitTest/matrixDecomps.cpp
akrodger/numples-cpp
4f0cd7b5dd66251fd02189480f3917aaefcc53f4
[ "MIT" ]
null
null
null
unitTest/matrixDecomps.cpp
akrodger/numples-cpp
4f0cd7b5dd66251fd02189480f3917aaefcc53f4
[ "MIT" ]
null
null
null
/* * C Driver file Template by Bram Rodgers. * Original Draft Dated: 25, Feb 2018 */ /* * Macros and Includes go here: (Some common ones listed) */ #include<stdio.h> #include<stdlib.h> #include"../src/numples.h" #ifndef NULL #define NULL 0 #endif #define MIN_ALLOWED_ARGS 4 /* * Function declarations go here: */ using namespace numples; /* * Template main: */ int main(int argc, char** argv){ // Variable Declarations: // int, double, etc // Pre Built argv parsing: (argv[0] is executable title. e.g. "./a.out") char* pEnd = NULL; //Points to end of a parsed string /* * (intger) = atoi(argv[index]); * (double) = strtod(argv[index], &pEnd); * (long int) = strtol(argv[index], &pEnd, base_val) */ srand(time(NULL)); lapack_int m, n, numSV;//matrix dimensions and loop iterators. if(argc < MIN_ALLOWED_ARGS){ printf("\nA small script to test the various matrix products."); printf("\n==================================================="); printf("\n%s [m] [n] [numSV]",argv[0]); printf("\nDoes a test of SVD, obtaining only numSV singular vectors,\n" "and Schur Decomposition.\n"); exit(1); } m = (lapack_int) strtol(argv[1], &pEnd, 0); n = (lapack_int) strtol(argv[2], &pEnd, 0); numSV = (lapack_int) strtol(argv[3], &pEnd, 0); Matrix A = Matrix(m , n, 'U');//generate uniform random matrix. Matrix R, Z;//Schur decomposition matrices Matrix U, sig, Vt;//SVD matrices Matrix Resid; double residNorm, traceVal; A.svd(U, sig, Vt); Resid = A - U * sig.diag() * Vt; residNorm = Resid.norm2(); printf("\nSVD Residual: %le\n", residNorm); Z = A.getLeftSV(numSV); traceVal = (Z.transp() * U).trace(); residNorm = numSV - ABS(traceVal); printf("\n%le\n",residNorm); if(residNorm <= (double)numSV){ printf("\nGet Left Singular Vectors passed within eps_mach: 1\n"); }else{ printf("\nGet Left Singular Vectors failed within eps_mach: 0\n"); } A.schur(Z,R); Resid = A*Z - Z*R; residNorm = Resid.norm2(); printf("\nSchur Residual: %le\n", residNorm); printf("\n%s\n\n", argv[0]); return 0; }
28.527778
73
0.636319
akrodger
c13441334709fa1e0692b42be0dbe628a1e606fb
2,290
cpp
C++
leviathan_config.cpp
bkovacev/levd
f942946f4db7f8c2bad14c5c7025ac303855ced7
[ "MIT" ]
1
2020-04-23T11:28:55.000Z
2020-04-23T11:28:55.000Z
leviathan_config.cpp
bkovacev/levd
f942946f4db7f8c2bad14c5c7025ac303855ced7
[ "MIT" ]
null
null
null
leviathan_config.cpp
bkovacev/levd
f942946f4db7f8c2bad14c5c7025ac303855ced7
[ "MIT" ]
1
2020-04-23T11:28:59.000Z
2020-04-23T11:28:59.000Z
#include "leviathan_config.hpp" #include <exception> #include <algorithm> #include <glog/logging.h> #include <yaml-cpp/yaml.h> // TODO: Cleaner normalization LineFunction slope_function(const Point &a, const Point &b) { const auto ys = b.y - a.y; const auto xs = b.x - a.x; if (xs == 0) { throw std::runtime_error("Infinite slope detected"); } const auto slope = ys / xs; const auto bFac = b.y - (slope * b.x); return [slope, bFac](int32_t x) { const auto newY = (slope * x) + bFac; // Normalize to a multiple of 5 const auto evenDiff = newY % 5; return newY - evenDiff; // hit it on the nose == 0 }; } std::map<int32_t, LineFunction> configure_profile( const YAML::Node &fan_profile) { CHECK(fan_profile.IsSequence()) << "Expecting a sequence of pairs"; const auto point_compare = [](const Point &p, const Point &u) { return p.x > u.x; }; std::vector<Point> dataPoints { Point(0, 30) }; for (const auto &i : fan_profile.as<std::vector<std::vector<uint32_t>>>()) { CHECK(i.size() == 2) << "Expecting array of pairs for fan/pump profile"; CHECK(i.back() % 5 == 0) << "Fan/pump profile values must be divisible by 5"; dataPoints.emplace_back(i.front(), i.back()); } dataPoints.emplace_back(100, 100); std::sort(dataPoints.begin(), dataPoints.end(), point_compare); std::map<int32_t, LineFunction> temp_to_slope; for (auto i = 0; i < dataPoints.size() - 1; ++i) { const Point &cur_pt = dataPoints[i]; const Point &next_pt = dataPoints[i + 1]; temp_to_slope[cur_pt.x] = slope_function(cur_pt, next_pt); } return temp_to_slope; } leviathan_config parse_config_file(const char *const path) { leviathan_config options; try { YAML::Node config = YAML::LoadFile(path); options.temp_source_ = stringToTempSource(config["temperature_source"].as<std::string>()); options.fan_profile_ = configure_profile(config["fan_profile"]); options.pump_profile_ = config["pump_profile"] ? configure_profile(config["pump_profile"]) : options.fan_profile_; options.main_color_ = config["main_color"].as<uint32_t>(); options.interval_ = config["interval"].as<uint32_t>(); } catch (std::exception &e) { LOG(FATAL) << "Yaml parsing error: " << e.what(); } return options; }
37.540984
118
0.666376
bkovacev
c137b9f83b254eb1787e60740af4331570898fc8
12,019
cpp
C++
lib/src/AMRTools/NWOQuadCFInterp.cpp
rmrsk/Chombo-3.3
f2119e396460c1bb19638effd55eb71c2b35119e
[ "BSD-3-Clause-LBNL" ]
10
2018-02-01T20:57:36.000Z
2022-03-17T02:57:49.000Z
lib/src/AMRTools/NWOQuadCFInterp.cpp
rmrsk/Chombo-3.3
f2119e396460c1bb19638effd55eb71c2b35119e
[ "BSD-3-Clause-LBNL" ]
19
2018-10-04T21:37:18.000Z
2022-02-25T16:20:11.000Z
lib/src/AMRTools/NWOQuadCFInterp.cpp
rmrsk/Chombo-3.3
f2119e396460c1bb19638effd55eb71c2b35119e
[ "BSD-3-Clause-LBNL" ]
11
2019-01-12T23:33:32.000Z
2021-08-09T15:19:50.000Z
#ifdef CH_LANG_CC /* * _______ __ * / ___/ / ___ __ _ / / ___ * / /__/ _ \/ _ \/ V \/ _ \/ _ \ * \___/_//_/\___/_/_/_/_.__/\___/ * Please refer to Copyright.txt, in Chombo's root directory. */ #endif // #include <cstdio> //this one has getNearPeriodic #include "PiecewiseLinearFillPatch.H" #include "NWOQuadCFInterp.H" #include "IntVectSet.H" #include "DebugOut.H" #include "NamespaceHeader.H" void NWOQuadCFInterp:: define(/// layout at this level const DisjointBoxLayout& a_thisDisjointBoxLayout, /// layout at coarser level const DisjointBoxLayout& a_coarserDisjointBoxLayout, /// number of variables const int& a_numStates, /// problem domain on the coarser level const ProblemDomain& a_coarseDomain, /// refinement ratio between this level and the coarser level const int& a_refineCoarse, /// number of layers of ghost cells to fill by interpolation const int& a_interpRadius) { // Cache data m_numStates = a_numStates; m_coarseDomain = a_coarseDomain; m_refineCoarse = a_refineCoarse; m_interpRadius = a_interpRadius; m_layout = a_thisDisjointBoxLayout; m_coarseLayout = a_coarserDisjointBoxLayout; m_refineVect = m_refineCoarse * IntVect::Unit; ProblemDomain fineDomain = refine(m_coarseDomain, m_refineVect); coarsen(m_layoutCoarsened, m_layout, m_refineVect); int coarseGhost = a_interpRadius/a_refineCoarse + 2; m_coarsenedFineData.define(m_layoutCoarsened, m_numStates, coarseGhost*IntVect::Unit); m_cfivs.define(m_layout); for(DataIterator dit = m_layout.dataIterator(); dit.ok(); ++dit) { Box ghostBox = m_layout[dit()]; ghostBox.grow(a_interpRadius); ghostBox &= fineDomain; m_cfivs[dit].define(dit(), m_layout, ghostBox); } // Everything is defined now. m_defined = true; } ////////////////////////////////////////////////////////////////////////////// void NWOQuadCFInterp:: coarseFineInterp(/// interpolated solution on this level LevelData<FArrayBox>& a_fineData, /// solution on coarser level const LevelData<FArrayBox>& a_coarseData, /// starting coarse data component int a_srcComp, /// starting fine data component int a_dstComp, /// number of data components to interpolate int a_numComp) { CH_assert(m_defined); const Interval srcInterval(a_srcComp, a_srcComp + a_numComp-1); const Interval dstInterval(a_dstComp, a_dstComp + a_numComp-1); a_coarseData.copyTo(srcInterval, m_coarsenedFineData, dstInterval); int ibox = 0; for (DataIterator dit = m_layout.dataIterator();dit.ok(); ++dit) { interpOnPatch(a_fineData[dit()], m_coarsenedFineData[dit()], dit(), a_srcComp, a_dstComp, a_numComp); ibox++; } } ////////////////////////////////////////////////////////////////////////////// void NWOQuadCFInterp:: homogeneousCoarseFineInterp(/// interpolated solution on this level LevelData<FArrayBox>& a_fineData, /// solution on coarser level int a_srcComp, /// starting fine data component int a_dstComp, /// number of data components to interpolate int a_numComp) { CH_assert(m_defined); for(DataIterator dit = m_coarsenedFineData.dataIterator(); dit.ok(); ++dit) { m_coarsenedFineData[dit()].setVal(0.); } for (DataIterator dit = m_layout.dataIterator();dit.ok(); ++dit) { interpOnPatch(a_fineData[dit()], m_coarsenedFineData[dit()], dit(), a_srcComp, a_dstComp, a_numComp); } } ///////////// void NWOQuadCFInterp:: interpOnPatch(FArrayBox& a_fineData, const FArrayBox& a_coarseData, const DataIndex& a_dit, int a_srcComp, int a_dstComp, int a_numComp) { const IntVectSet& cfivsFine = m_cfivs[a_dit].getIVS(); //dumpIVS(&cfivsFine); Real dxFine = 1; Real dxCoar = m_refineCoarse; for(IVSIterator ivsit(cfivsFine); ivsit.ok(); ++ivsit) { const IntVect& ivFine = ivsit(); int ideb = 0; if((ivFine[0]==16) && (ivFine[1]==8)) { ideb = 1; } IntVect ivCoar = coarsen(ivFine, m_refineCoarse); RealVect fineLoc, coarLoc; for(int idir = 0; idir < SpaceDim; idir++) { fineLoc[idir] = dxFine*(ivFine[idir] + 0.5); coarLoc[idir] = dxCoar*(ivCoar[idir] + 0.5); } for(int icomp = 0; icomp < a_numComp; icomp++) { int srcComp = a_srcComp + icomp; int dstComp = a_dstComp + icomp; RealVect firstDerivs, secondDerivs, mixedDerivs; getDerivs(firstDerivs, secondDerivs, mixedDerivs, a_coarseData, ivCoar, dxCoar, icomp); Real coarValue = a_coarseData(ivCoar, srcComp); RealVect distance = fineLoc - coarLoc; Real fineValue; extrapolateValue(fineValue, coarValue, firstDerivs, secondDerivs, mixedDerivs, distance); a_fineData(ivFine, dstComp) = fineValue; } } } void NWOQuadCFInterp:: getDerivs(RealVect& firstDerivs, RealVect& secondDerivs, RealVect& mixedDerivs, const FArrayBox & a_data, const IntVect& a_ivCoar, const Real & a_dx, const int & a_icomp) { const IntVect& iv = a_ivCoar; int icomp = a_icomp; Real dx = a_dx; //single direction derivs--use centered diffs if possible, one-sided otherwise for(int idir = 0; idir < SpaceDim; idir++) { IntVect ivhi = iv + BASISV(idir); IntVect ivlo = iv - BASISV(idir); bool hasHi = m_coarseDomain.contains(ivhi); bool hasLo = m_coarseDomain.contains(ivlo); if(hasHi && hasLo) { firstDerivs[idir] = (a_data(ivhi, icomp) - a_data(ivlo, icomp))/(2.*a_dx); secondDerivs[idir] = (a_data(ivhi, icomp) + a_data(ivlo, icomp) - 2*a_data(iv, icomp))/(a_dx*a_dx); } else if(hasHi) { IntVect ivVeryHi = ivhi + BASISV(idir); firstDerivs[idir] = (a_data(ivhi, icomp) - a_data(iv , icomp))/(a_dx); secondDerivs[idir] = (a_data(ivVeryHi, icomp) + a_data(iv , icomp) - 2*a_data(ivhi, icomp))/(a_dx*a_dx); } else if(hasLo) { IntVect ivVeryLo = ivlo - BASISV(idir); firstDerivs[idir] = (a_data(iv , icomp) - a_data(ivlo, icomp))/(a_dx); secondDerivs[idir] = (a_data(ivVeryLo, icomp) + a_data(iv , icomp) - 2*a_data(ivlo, icomp))/(a_dx*a_dx); } else { firstDerivs[idir] = 0; secondDerivs[idir] = 0; } } //now for that evil mixed deriv stuff --- 2d only has one, 3d has 3 //this is to keep from doing each pair twice Vector<int> doneThisPair(SpaceDim, 0); for(int idir = 0; idir < SpaceDim; idir++) { for(int jdir = 0; jdir < SpaceDim; jdir++) { if(idir != jdir) { int index = getMixedIndex(idir, jdir); if(doneThisPair[index] == 0) { doneThisPair[index] = 1; IntVect ivhiI = iv + BASISV(idir); IntVect ivloI = iv - BASISV(idir); IntVect ivhiJ = iv + BASISV(jdir); IntVect ivloJ = iv - BASISV(jdir); IntVect ivhiIhiJ = iv + BASISV(idir) + BASISV(jdir); IntVect ivloIloJ = iv - BASISV(idir) - BASISV(jdir); IntVect ivloIhiJ = iv - BASISV(idir) + BASISV(jdir); IntVect ivhiIloJ = iv + BASISV(idir) - BASISV(jdir); bool hasIvhiIhiJ = m_coarseDomain.contains(ivhiIhiJ); bool hasIvloIloJ = m_coarseDomain.contains(ivloIloJ); bool hasIvloIhiJ = m_coarseDomain.contains(ivloIhiJ); bool hasIvhiIloJ = m_coarseDomain.contains(ivhiIloJ); //just go through the corners and compute each mixed deriv that you have Real derivSum = 0; int numDerivs = 0; if(hasIvhiIhiJ) { Real dathiIhiJ = a_data(ivhiIhiJ, icomp); Real dathiI = a_data(ivhiI , icomp); Real dathiJ = a_data(ivhiJ , icomp); Real datcen = a_data(iv , icomp); Real mixedD = ((dathiIhiJ - dathiJ) - (dathiI - datcen))/dx/dx; derivSum += mixedD; numDerivs++; } if(hasIvloIloJ) { Real datloIloJ = a_data(ivloIloJ, icomp); Real datloI = a_data(ivloI , icomp); Real datloJ = a_data(ivloJ , icomp); Real datcen = a_data(iv , icomp); Real mixedD = ((datcen - datloI) - (datloJ - datloIloJ))/dx/dx; derivSum += mixedD; numDerivs++; } if(hasIvhiIloJ) { Real dathiIloJ = a_data(ivhiIloJ, icomp); Real dathiI = a_data(ivhiI , icomp); Real datloJ = a_data(ivloJ , icomp); Real datcen = a_data(iv , icomp); Real mixedD = ((dathiI - datcen) - (dathiIloJ - datloJ))/dx/dx; derivSum += mixedD; numDerivs++; } if(hasIvloIhiJ) { Real datloIhiJ = a_data(ivloIhiJ, icomp); Real datloI = a_data(ivloI , icomp); Real dathiJ = a_data(ivhiJ , icomp); Real datcen = a_data(iv , icomp); Real mixedD = ((dathiJ - datloIhiJ) - (datcen - datloI))/dx/dx; derivSum += mixedD; numDerivs++; } Real derivAvg = 0; if(numDerivs > 0) { derivAvg = derivSum/numDerivs; } mixedDerivs[index] = derivAvg; } } } } } void NWOQuadCFInterp:: extrapolateValue(Real & a_fineValue, const Real & a_coarValue, const RealVect & a_firstDerivs, const RealVect & a_secondDerivs, const RealVect & a_mixedDerivs, const RealVect & a_distance) { a_fineValue = a_coarValue; //add in first and second derivative contributions for(int idir = 0; idir < SpaceDim; idir++) { Real dx = a_distance[idir]; a_fineValue += dx*a_firstDerivs[idir]; a_fineValue += (dx*dx/2.)*a_secondDerivs[idir]; } //now for the evil mixed derivatives #if CH_SPACEDIM==2 Real dxdy = a_distance[0]*a_distance[1]; a_fineValue += dxdy*a_mixedDerivs[0]; #else for(int iindex = 0; iindex < SpaceDim; iindex++) { int idir, jdir; getMixedDerivDirections(idir, jdir, iindex); Real dx = a_distance[idir]; Real dy = a_distance[jdir]; a_fineValue += dx*dy*a_mixedDerivs[iindex]; } #endif } #include "NamespaceFooter.H"
35.877612
116
0.52234
rmrsk