hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
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
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
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
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
dde01a22f535ffb628ff2fa7d630ffed7d6ccc1d
1,227
cpp
C++
DSA/Sorting/Merge_sort.cpp
ShrishtiAgarwal/DSA
8086cc31bef3aefc06a8ea5c7c36fa4aabe7c1df
[ "MIT" ]
null
null
null
DSA/Sorting/Merge_sort.cpp
ShrishtiAgarwal/DSA
8086cc31bef3aefc06a8ea5c7c36fa4aabe7c1df
[ "MIT" ]
null
null
null
DSA/Sorting/Merge_sort.cpp
ShrishtiAgarwal/DSA
8086cc31bef3aefc06a8ea5c7c36fa4aabe7c1df
[ "MIT" ]
null
null
null
#include <iostream> #include <bits/stdc++.h> using namespace std; void print(vector<int>&arr) { for(int i=0;i<arr.size();i++) { cout<<arr[i]<<" "; } } void merge(vector<int>&arr,int l,int m,int r) { int n1=m-(l+1); int n2=r-m; int i=0,j=0,k=l; int arr1[n1]; int arr2[n2]; for( i=0;i<n1;i++) arr1[i]=arr[l+i]; for (j = 0; j < n2; j++) arr2[j] = arr[m + 1 + j]; i=0,j=0,k=l; while(i<n1&&j<n2) { if (arr1[i] <= arr2[j]) { arr[k] = arr1[i]; i++; } else { arr[k] = arr2[j]; j++; } k++; } while (i < n1) { arr[k] = arr1[i]; i++; k++; } while (j < n2) { arr[k] = arr2[j]; j++; k++; } } void merge_Sort(vector<int>&arr,int l,int r) { if(l<r) { int m = l + (r - l) / 2; merge_Sort(arr,l,m); merge_Sort(arr,m+1,r); merge(arr,l,m,r); } } int main() { int n; cin>>n; vector<int>arr(n); for(int i=0;i<n;i++) { cin>>arr[i]; } merge_Sort(arr,0,arr.size()-1); print(arr); }
15.730769
45
0.378158
[ "vector" ]
dde2929114bcf1a1a392ce3b133be18710256825
333
cpp
C++
CMakeDemo/Demo/main.cpp
cestlascorpion/Practice
a2b1aec7d403d40a3d07130a1bb923c06d4c4d28
[ "MIT" ]
null
null
null
CMakeDemo/Demo/main.cpp
cestlascorpion/Practice
a2b1aec7d403d40a3d07130a1bb923c06d4c4d28
[ "MIT" ]
null
null
null
CMakeDemo/Demo/main.cpp
cestlascorpion/Practice
a2b1aec7d403d40a3d07130a1bb923c06d4c4d28
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; int main() { vector<int> vec(10); // 10 zero-initialized elements for (auto i = 0u; i < vec.size(); i++) vec[i] = i; cout << "vec contains:"; for (auto i = 0u; i < vec.size(); i++) cout << ' ' << vec[i]; cout << '\n'; return 0; }
18.5
56
0.507508
[ "vector" ]
ddead387cba69019c0bf674d4736b16f42ba88e4
1,127
cpp
C++
LexicographicalNumbers/solution.cpp
JasonLin6086/leetcode
e14e2fb6b600dc6f822c6e86899bf3289f0fa727
[ "MIT" ]
null
null
null
LexicographicalNumbers/solution.cpp
JasonLin6086/leetcode
e14e2fb6b600dc6f822c6e86899bf3289f0fa727
[ "MIT" ]
null
null
null
LexicographicalNumbers/solution.cpp
JasonLin6086/leetcode
e14e2fb6b600dc6f822c6e86899bf3289f0fa727
[ "MIT" ]
null
null
null
/* * solution.cpp * * Created on: Aug 31, 2016 * Author: jason */ #include <iostream> #include <vector> #include <algorithm> #include <cmath> using namespace std; class Solution { public: vector<int> lexicalOrder(int n) { vector<int> rs; int i = 1, j, k; while (true) { // append as many zeroes as possible to the previous number for(k = 0; i*pow(10,k) <= n; ++k) rs.push_back(i*pow(10,k)); // count continuously until we reach a number that ends with consecutive '9's for(j = rs.back()+1; j <= n && (j % 10) != 0; ++j) rs.push_back(j); // backtrace if(j % 10 == 0) { j--; } else { j /= 10; } // find the last non-'9' digit while(j % 10 == 9) j /= 10; // start a new sub-sequence i = j+1; if(rs.size() >= n) break; } return rs; } }; int main() { Solution s; vector<int> result = s.lexicalOrder(123); return 0; }
19.101695
89
0.450754
[ "vector" ]
ddecb7e644372371ca0ab559951ed74334446201
848
cpp
C++
src/solidMaterial.cpp
important-sample/path-tracer
a52c9e27563ea3d8bcc2b0f4c26bfebb22c9d8c1
[ "MIT" ]
null
null
null
src/solidMaterial.cpp
important-sample/path-tracer
a52c9e27563ea3d8bcc2b0f4c26bfebb22c9d8c1
[ "MIT" ]
null
null
null
src/solidMaterial.cpp
important-sample/path-tracer
a52c9e27563ea3d8bcc2b0f4c26bfebb22c9d8c1
[ "MIT" ]
null
null
null
#include "solidMaterial.hpp" #include "lambertBrdf.hpp" SolidMaterial::SolidMaterial(): BaseMaterial(), color(Vector(1, 1, 1)), emittance(Vector(0,0,0)) { brdf = new LambertBRDF(); } SolidMaterial::SolidMaterial(const Vector& col, float kDiffuse): BaseMaterial(), color(col), emittance(Vector(0,0,0)) { brdf = new LambertBRDF(kDiffuse); } SolidMaterial::SolidMaterial(const Vector& col, float kDiffuse, const Vector& emit): BaseMaterial(), color(col), emittance(emit) { brdf = new LambertBRDF(kDiffuse); } SolidMaterial::~SolidMaterial() { delete brdf; } Vector SolidMaterial::getColor(float, float) const { return color; } Vector SolidMaterial::getEmittance(float, float) const { return emittance; } bool SolidMaterial::isEmissive() const { return emittance.lengthSq() > 0.1; } BRDF* SolidMaterial::getBRDF() const { return brdf; }
31.407407
129
0.733491
[ "vector" ]
ddedaad5d6f06139fc48eeb9643b86aece1458dc
2,045
cpp
C++
source/Simulation.cpp
frmr/wizmatch
cf16207bea7b7d0dd9c7c18e74bae630c20ef796
[ "MIT" ]
null
null
null
source/Simulation.cpp
frmr/wizmatch
cf16207bea7b7d0dd9c7c18e74bae630c20ef796
[ "MIT" ]
null
null
null
source/Simulation.cpp
frmr/wizmatch
cf16207bea7b7d0dd9c7c18e74bae630c20ef796
[ "MIT" ]
null
null
null
#include <iostream> #include "Frustum.h" #include "Simulation.h" using std::cout; using std::endl; void Simulation::LoadBillboardAnimation( const string filename ) { } bool Simulation::ChangeMap( const string filename ) { UnloadCurrentMap(); LoadMap( filename ); return true; } PerspectiveCamera Simulation::GetActiveCamera() const { return activeCamera; } vector<Light> Simulation::GetStaticLights() const { return staticGeometry.GetStaticLights(); } ProjectionState Simulation::RenderLit() const { glPushMatrix(); activeCamera.ApplyTransformation(); ProjectionState cameraProjection; staticGeometry.Render( activeCamera.GetZoneNum(), cameraProjection, activeCamera.GetFrustum() ); glPopMatrix(); return cameraProjection; } ProjectionState Simulation::RenderShadowCasters( const PerspectiveCamera &lightView ) const { glPushMatrix(); lightView.ApplyTransformation(); ProjectionState cameraProjection; staticGeometry.Render( lightView.GetZoneNum(), cameraProjection, lightView.GetFrustum() ); glPopMatrix(); return cameraProjection; } bool Simulation::LoadMap( const string filename ) { return true; } void Simulation::UnloadCurrentMap() { } void Simulation::Update( const int32_t elapsedTime, const float deltaTime, const InputState &inputs, const float mouseSensitivity ) { spectator.Update( inputs, mouseSensitivity, deltaTime ); activeCamera = spectator.GetCamera(); } Simulation::Simulation( const AssetManager &assets ) : activeCamera( frmr::Vec3f(), frmr::Vec2f(), 0, 1.0f, 1.0f ), spectator( "Spectator", frmr::Vec3f( 30.0f, 0.0f, 0.0f ), frmr::Vec2f(), 0 ), staticGeometry( "../maps/twocubes.wzz", assets ) { //staticLights.push_back( Light( frmr::Vec3f( 80.0f, 0.0f, 0.0f ), frmr::Vec3f( 12.0f, 12.0f, 12.0f ), 0 ) ); //staticLights.push_back( Light( frmr::Vec3f( -80.0f, 0.0f, 0.0f ), frmr::Vec3f( 9.0f, 9.0f, 9.0f ), 0 ) ); } Simulation::~Simulation() { }
24.058824
132
0.690954
[ "render", "vector" ]
ddf334cb5071b9471276aa871d705487b7113104
30,146
cc
C++
core/main/server.cc
OxOOo/ntf
d110dddbf061fdd8f3788ace96faf740e30e7a12
[ "MIT" ]
null
null
null
core/main/server.cc
OxOOo/ntf
d110dddbf061fdd8f3788ace96faf740e30e7a12
[ "MIT" ]
null
null
null
core/main/server.cc
OxOOo/ntf
d110dddbf061fdd8f3788ace96faf740e30e7a12
[ "MIT" ]
null
null
null
#include <atomic> #include <list> #include <mutex> #include <set> #include <string> #include <vector> #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/time/time.h" #include "file/epoll.h" #include "file/filesystem.h" #include "file/nonblocking.h" #include "gflags/gflags.h" #include "glog/logging.h" #include "main/common/message.h" #include "main/common/thread_manager.h" #include "net/net.h" #include "nlohmann/json.hpp" #include "utils/status_macros.h" DECLARE_bool(logtostderr); DEFINE_string(listen_manage_sock, "", "The domain sock path which is used to communicate with web"); DEFINE_uint32(listen_net_port, 0, "The tcp port used to communicate with clients"); namespace { using namespace std::placeholders; using ::common::ThreadManager; using ::nlohmann::json; constexpr absl::string_view kManageThreadName = "manage"; constexpr absl::string_view kTcpForwardListenThreadName = "tcp_forward_listen"; constexpr absl::string_view kTimeoutCheckThreadName = "timeout_check"; constexpr absl::string_view kListenThreadName = "listen"; constexpr absl::string_view kClientThreadName = "client"; constexpr absl::string_view kClientForwardThreadName = "client_forward"; constexpr absl::string_view kManageCommandConfig = "CONFIG"; constexpr absl::string_view kManageCommandConfigOK = "CONFIG_OK"; constexpr absl::string_view kManageCommandFetchStatus = "FETCH_STATUS"; constexpr absl::string_view kManageCommandStatus = "STATUS"; class CallOnDestruct { public: CallOnDestruct(std::function<void()> func) : func_(std::move(func)) {} ~CallOnDestruct() { func_(); } private: std::function<void()> func_; }; struct Config { struct Client { std::string id; std::string key; }; struct TcpForward { std::string client_id; uint16_t listen_port; std::string forward_client_ip; uint16_t forward_client_port; }; std::vector<Client> clients; std::vector<TcpForward> tcp_forwards; }; absl::StatusOr<Config> ParseConfig(absl::string_view data) { const json j = json::parse(data); Config config; if (j.find("clients") == j.end()) { return absl::InvalidArgumentError( "The config does not have `clients`."); } if (!j.at("clients").is_array()) { return absl::InvalidArgumentError( "The `clients` in config is not an array."); } for (const auto& c : j.at("clients")) { if (!c.is_object()) { return absl::InvalidArgumentError( "The element in `clients` is not an object."); } for (const auto& key : {"id", "key"}) { if (c.find(key) == c.end()) { return absl::InvalidArgumentError(absl::StrFormat( "The element in `clients` does not have `%s`.", key)); } } config.clients.push_back({ .id = c.at("id").get<std::string>(), .key = c.at("key").get<std::string>(), }); } if (j.find("tcp_forwards") == j.end()) { return absl::InvalidArgumentError( "The config does not have `tcp_forwards`."); } if (!j.at("tcp_forwards").is_array()) { return absl::InvalidArgumentError( "The `tcp_forwards` in config is not an array."); } for (const auto& t : j.at("tcp_forwards")) { if (!t.is_object()) { return absl::InvalidArgumentError( "The element in `tcp_forwards` is not an object."); } for (const auto& key : {"client_id", "listen_port", "forward_client_ip", "forward_client_port"}) { if (t.find(key) == t.end()) { return absl::InvalidArgumentError(absl::StrFormat( "The element in `tcp_forwards` does not have `%s`.", key)); } } config.tcp_forwards.push_back({ .client_id = t.at("client_id").get<std::string>(), .listen_port = t.at("listen_port").get<uint16_t>(), .forward_client_ip = t.at("forward_client_ip").get<std::string>(), .forward_client_port = t.at("forward_client_port").get<uint16_t>(), }); } std::set<std::string> client_ids; for (const auto& c : config.clients) { if (client_ids.find(c.id) != client_ids.end()) { return absl::InvalidArgumentError( absl::StrFormat("Dup client id `%s`.", c.id)); } client_ids.insert(c.id); } std::set<uint16_t> listen_ports; for (const auto& t : config.tcp_forwards) { if (listen_ports.find(t.listen_port) != listen_ports.end()) { return absl::InvalidArgumentError( absl::StrFormat("Dup listen port `%d`.", t.listen_port)); } listen_ports.insert(t.listen_port); if (client_ids.find(t.client_id) == client_ids.end()) { return absl::InvalidArgumentError(absl::StrFormat( "Cannot find client with id `%s`.", t.client_id)); } } return config; } class Server { public: Server() : startup_time_(absl::Now()) { ended_ = 1; } absl::Status ManageMain(uint64_t tid, ThreadManager* tm) { RETURN_IF_ERROR(tm->SetThreadName(tid, kManageThreadName)); // listen domain sock ASSIGN_OR_RETURN(auto server, net::Socket(AF_UNIX, SOCK_STREAM, 0)); RETURN_IF_ERROR(server->SetReuseAddr()); ASSIGN_OR_RETURN(auto listen_addr, net::SocketAddr::NewUnix(FLAGS_listen_manage_sock)); file::Unlink(FLAGS_listen_manage_sock).IgnoreError(); RETURN_IF_ERROR(server->Bind(listen_addr)); RETURN_IF_ERROR(server->Listen(1024)); while (true) { if (ended_.load()) { std::lock_guard<std::mutex> lock(mtx_); ended_.store(0); // 变量初始化 tcp_incommings_.clear(); online_clients_.clear(); // 启动其他线程 tm->Launch( std::bind(&Server::TimeoutCheckThread, this, _1, _2)); tm->Launch(std::bind(&Server::ListenThread, this, _1, _2)); for (const auto& tcp : config_.tcp_forwards) { tm->Launch(std::bind(&Server::TcpForwardListenThread, this, _1, _2, tcp)); } } // accept new socket ASSIGN_OR_RETURN(auto socket, server->Accept()); RETURN_IF_ERROR( socket->SetSockOpt<int>(SOL_SOCKET, SO_KEEPALIVE, 1)); // manage一定是一问一答的形式,每次一行 while (true) { // readline std::string line; while (true) { ASSIGN_OR_RETURN(std::string chunk, socket->Read(1024)); if (chunk.empty()) { break; } absl::StrAppend(&line, chunk); if (chunk.find('\n') != chunk.npos) { break; } } if (line.empty()) { break; } LOG(INFO) << "manage line : " << line; // 分析 absl::string_view line_view = line; absl::string_view command; absl::string_view command_data; while (!line_view.empty() && std::isspace(*line_view.rbegin())) { line_view.remove_suffix(1); } if (size_t space_pos = line_view.find(' '); space_pos != line_view.npos) { command = line_view.substr(0, space_pos); command_data = line_view.substr(space_pos + 1); } else { command = line_view; } // CONFIG if (command == kManageCommandConfig) { auto config = ParseConfig(command_data); if (config.ok()) { // 先结束其他线程 ended_.store(1); RETURN_IF_ERROR(tm->WaitOnlyThreadsAlive( {std::string(kManageThreadName)})); // 在下一次循环,会检查ended_并启动其他线程 { std::lock_guard<std::mutex> lock(mtx_); config_ = *config; } RETURN_IF_ERROR(socket->Write(kManageCommandConfigOK)); } else { RETURN_IF_ERROR(socket->Write(absl::StrFormat( "ERR %s", config.status().ToString()))); } } else if (command == kManageCommandFetchStatus) { json j; absl::TimeZone tz = absl::FixedTimeZone(8 * 60 * 60); j["startup_time"] = absl::FormatTime(startup_time_, tz); j["online_clients"] = online_clients_; RETURN_IF_ERROR(socket->Write(absl::StrFormat( "%s %s", kManageCommandStatus, j.dump()))); } else { RETURN_IF_ERROR(socket->Write( absl::StrFormat("ERR unknow command `%s`", command))); } } } return absl::OkStatus(); } void ManageThread(uint64_t tid, ThreadManager* tm) { try { auto status = ManageMain(tid, tm); if (!status.ok()) { LOG(ERROR) << "manage thread error : " << status; exit(1); } else { LOG(INFO) << "manage thread exit"; } } catch (...) { LOG(ERROR) << "manage thread catched an error"; } exit(0); } absl::Status TcpForwardListenMain(uint64_t tid, ThreadManager* tm, Config::TcpForward tcp_forward) { RETURN_IF_ERROR(tm->SetThreadName( tid, absl::StrFormat("%s_%s_%d", kTcpForwardListenThreadName, tcp_forward.client_id, tcp_forward.listen_port))); // listen sock ASSIGN_OR_RETURN(auto server, net::Socket(AF_INET, SOCK_STREAM, 0)); RETURN_IF_ERROR(server->SetReuseAddr()); ASSIGN_OR_RETURN( auto listen_addr, net::SocketAddr::NewIPv4("0.0.0.0", tcp_forward.listen_port)); RETURN_IF_ERROR(server->Bind(listen_addr)); RETURN_IF_ERROR(server->Listen(1024)); ASSIGN_OR_RETURN(auto epoll, file::EPoll::Create()); RETURN_IF_ERROR(epoll->Add(server.get(), EPOLLIN)); while (true) { // wait event absl::Duration timeout = absl::Milliseconds(100); ASSIGN_OR_RETURN(auto events, epoll->Wait(1024, &timeout)); if (ended_.load()) { break; } if (events.empty()) { continue; } // accept new socket ASSIGN_OR_RETURN(auto socket, server->Accept()); RETURN_IF_ERROR( socket->SetSockOpt<int>(SOL_SOCKET, SO_KEEPALIVE, 1)); { std::lock_guard<std::mutex> lock(mtx_); tcp_incommings_.push_back({.socket = std::move(socket), .created_time = absl::Now(), .tcp_forward = tcp_forward, .have_sent_to_client = false}); } } return absl::OkStatus(); } void TcpForwardListenThread(uint64_t tid, ThreadManager* tm, Config::TcpForward tcp_forward) { try { auto status = TcpForwardListenMain(tid, tm, tcp_forward); if (!status.ok()) { LOG(ERROR) << "tcp forward thread error : " << status; exit(1); } else { LOG(INFO) << "tcp forward thread exit"; } } catch (...) { LOG(ERROR) << "tcp forward thread catched an error"; } } absl::Status TimeoutCheckMain(uint64_t tid, ThreadManager* tm) { RETURN_IF_ERROR(tm->SetThreadName(tid, kTimeoutCheckThreadName)); while (true) { absl::SleepFor(absl::Milliseconds(100)); if (ended_.load()) { break; } { std::lock_guard<std::mutex> lock(mtx_); auto it = tcp_incommings_.begin(); while (it != tcp_incommings_.end()) { if (absl::Now() - it->created_time > absl::Seconds(60)) { it = tcp_incommings_.erase(it); } else { it++; } } } } return absl::OkStatus(); } void TimeoutCheckThread(uint64_t tid, ThreadManager* tm) { try { auto status = TimeoutCheckMain(tid, tm); if (!status.ok()) { LOG(ERROR) << "timeout check thread error : " << status; exit(1); } else { LOG(INFO) << "timeout check thread exit"; } } catch (...) { LOG(ERROR) << "timeout check thread catched an error"; } } absl::Status ListenMain(uint64_t tid, ThreadManager* tm) { RETURN_IF_ERROR(tm->SetThreadName(tid, kListenThreadName)); // listen sock ASSIGN_OR_RETURN(auto server, net::Socket(AF_INET, SOCK_STREAM, 0)); RETURN_IF_ERROR(server->SetReuseAddr()); ASSIGN_OR_RETURN( auto listen_addr, net::SocketAddr::NewIPv4("0.0.0.0", FLAGS_listen_net_port)); RETURN_IF_ERROR(server->Bind(listen_addr)); RETURN_IF_ERROR(server->Listen(1024)); ASSIGN_OR_RETURN(auto epoll, file::EPoll::Create()); RETURN_IF_ERROR(epoll->Add(server.get(), EPOLLIN)); while (true) { // wait event absl::Duration timeout = absl::Milliseconds(100); ASSIGN_OR_RETURN(auto events, epoll->Wait(1024, &timeout)); if (ended_.load()) { break; } if (events.empty()) { continue; } // accept new socket ASSIGN_OR_RETURN(auto socket, server->Accept()); RETURN_IF_ERROR( socket->SetSockOpt<int>(SOL_SOCKET, SO_KEEPALIVE, 1)); tm->Launch(std::bind(&Server::ClientSocketThread, this, _1, _2, socket.release())); } return absl::OkStatus(); } void ListenThread(uint64_t tid, ThreadManager* tm) { try { auto status = ListenMain(tid, tm); if (!status.ok()) { LOG(ERROR) << "listen thread error : " << status; exit(1); } else { LOG(INFO) << "listen thread exit"; } } catch (...) { LOG(ERROR) << "listen thread catched an error"; } } absl::Status ClientSocketMain(uint64_t tid, ThreadManager* tm, std::unique_ptr<net::NetSocket> socket) { // client的连接有两种情况: // 1. 普通的控制线程 // 2. tcp转发线程 enum Status { UNKNOWN_ID_KEY, WAIT_FIRST_MESSAGE, NORMAL_CLIENT, TCP_FORWARD }; Status status = UNKNOWN_ID_KEY; std::string id; std::string key; absl::Time last_received_heartbeat = absl::Now(); absl::Time last_sent_heartbeat = absl::Now(); std::unique_ptr<CallOnDestruct> register_id_offline; ASSIGN_OR_RETURN(auto epoll, file::EPoll::Create()); ASSIGN_OR_RETURN(auto socket_io, file::NonblockingIO::Create(std::move(socket))); std::unique_ptr<file::NonblockingIO> tcp_forward_io; while (true) { if (absl::Now() - last_received_heartbeat > absl::Seconds(60)) { LOG(INFO) << "Heartbeat timeout"; break; } if (ended_.load()) { break; } // 准备epoll do { RETURN_IF_ERROR(epoll->DeleteIfExists(socket_io->file())); if (tcp_forward_io) { RETURN_IF_ERROR( epoll->DeleteIfExists(tcp_forward_io->file())); } if (socket_io->HasDataToWrite()) { RETURN_IF_ERROR(epoll->Add(socket_io->file(), EPOLLOUT)); break; } if (tcp_forward_io) { if (tcp_forward_io->HasDataToWrite()) { RETURN_IF_ERROR( epoll->Add(tcp_forward_io->file(), EPOLLOUT)); break; } } RETURN_IF_ERROR(epoll->Add(socket_io->file(), EPOLLIN)); if (tcp_forward_io) { RETURN_IF_ERROR( epoll->Add(tcp_forward_io->file(), EPOLLIN)); } } while (0); absl::Duration timeout = absl::Milliseconds(100); ASSIGN_OR_RETURN(auto events, epoll->Wait(1024, &timeout)); // 读或写buffer for (const auto event : events) { if (event.file->fd() == socket_io->file()->fd()) { if (event.events & EPOLLIN) { ASSIGN_OR_RETURN(auto read_bytes, socket_io->TryReadOnce(1024)); // 如果可以读数据但是并没有任何数据,那么表示closed if (read_bytes == 0) { return absl::OkStatus(); } } if (event.events & EPOLLOUT) { RETURN_IF_ERROR(socket_io->TryWriteOnce()); } } else if (tcp_forward_io && event.file->fd() == tcp_forward_io->file()->fd()) { if (event.events & EPOLLIN) { ASSIGN_OR_RETURN(auto read_bytes, tcp_forward_io->TryReadOnce(1024)); // 如果可以读数据但是并没有任何数据,那么表示closed if (read_bytes == 0) { return absl::OkStatus(); } } if (event.events & EPOLLOUT) { RETURN_IF_ERROR(tcp_forward_io->TryWriteOnce()); } } else { return absl::InternalError("Unknown epoll event"); } } // 检查是否有需要发送的TCP转发申请 if (status == NORMAL_CLIENT) { absl::optional<proto::TcpForward> send_forward = absl::nullopt; { std::lock_guard<std::mutex> lock(mtx_); for (auto& tcp_forward : tcp_incommings_) { if (!tcp_forward.have_sent_to_client && tcp_forward.tcp_forward.client_id == id) { tcp_forward.have_sent_to_client = true; proto::TcpForward tmp; ASSIGN_OR_RETURN( *tmp.mutable_remote_ip(), tcp_forward.socket->remote_addr().ip()); ASSIGN_OR_RETURN( auto remote_port, tcp_forward.socket->remote_addr().port()); tmp.set_remote_port(remote_port); ASSIGN_OR_RETURN( *tmp.mutable_accepted_ip(), tcp_forward.socket->local_addr().ip()); ASSIGN_OR_RETURN( auto accepted_port, tcp_forward.socket->local_addr().port()); tmp.set_accepted_port(accepted_port); tmp.set_to_ip( tcp_forward.tcp_forward.forward_client_ip); tmp.set_to_port( tcp_forward.tcp_forward.forward_client_port); send_forward = tmp; break; } } } if (send_forward.has_value()) { proto::Content content; *content.mutable_new_tcp_forward() = *send_forward; ASSIGN_OR_RETURN(auto send_data, common::message::Serialize( id, key, content)); socket_io->AppendWriteData(send_data); } } // 发送心跳 if (absl::Now() - last_sent_heartbeat > absl::Seconds(10)) { proto::HeartBeat heartbeat; proto::Content content; *content.mutable_heartbeat() = heartbeat; ASSIGN_OR_RETURN(auto send_data, common::message::Serialize(id, key, content)); socket_io->AppendWriteData(send_data); last_sent_heartbeat = absl::Now(); } if (status == UNKNOWN_ID_KEY) { ASSIGN_OR_RETURN(auto socket_id, common::message::TryParseID( socket_io->DataToRead())); if (!socket_id.has_value()) { continue; } { // find client id & key std::lock_guard<std::mutex> lock(mtx_); for (const auto& client : config_.clients) { if (*socket_id == client.id) { id = client.id; key = client.key; break; } } } if (id.empty()) { return absl::InternalError(absl::StrFormat( "ERR Cannot found id `%s`", *socket_id)); } status = WAIT_FIRST_MESSAGE; } if (status == WAIT_FIRST_MESSAGE) { uint64_t consumed_length; ASSIGN_OR_RETURN( auto content, common::message::TryParse(id, key, socket_io->DataToRead(), &consumed_length)); if (!content.has_value()) { continue; } socket_io->ConsumeReadData(consumed_length); if (content->has_ping()) { // 这是一个普通client { std::lock_guard<std::mutex> lock(mtx_); if (online_clients_.find(id) != online_clients_.end()) { return absl::InternalError(absl::StrFormat( "Client %s already online", id)); } online_clients_.insert(id); register_id_offline.reset(new CallOnDestruct( [this, id]() { online_clients_.erase(id); })); } RETURN_IF_ERROR(tm->SetThreadName( tid, absl::StrFormat("%s_%s", kClientThreadName, id))); LOG(INFO) << "New ping : " << content->DebugString(); status = NORMAL_CLIENT; } else if (content->has_accept_tcp_forward()) { // 这是一个TCP转发 std::lock_guard<std::mutex> lock(mtx_); absl::optional<TcpForwardIncomming> tcp_incomming = absl::nullopt; for (auto it = tcp_incommings_.begin(); it != tcp_incommings_.end(); it++) { if (it->tcp_forward.client_id != id) continue; if (*it->socket->remote_addr().ip() != content->accept_tcp_forward().remote_ip()) continue; if (*it->socket->remote_addr().port() != content->accept_tcp_forward().remote_port()) continue; tcp_incomming = std::move(*it); tcp_incommings_.erase(it); break; } if (!tcp_incomming.has_value()) { return absl::InternalError("Cannot find tcp forward"); } RETURN_IF_ERROR(tm->SetThreadName( tid, absl::StrFormat("%s_%s", kClientForwardThreadName, id))); ASSIGN_OR_RETURN(tcp_forward_io, file::NonblockingIO::Create( std::move(tcp_incomming->socket))); status = TCP_FORWARD; } else { return absl::InternalError( absl::StrFormat("Unsupported first message : %s", content->DebugString())); } } if (status == NORMAL_CLIENT) { while (socket_io->HasDataToRead()) { uint64_t consumed_length; ASSIGN_OR_RETURN(auto content, common::message::TryParse( id, key, socket_io->DataToRead(), &consumed_length)); if (!content.has_value()) { break; } socket_io->ConsumeReadData(consumed_length); if (content->has_heartbeat()) { last_received_heartbeat = absl::Now(); } else { return absl::InternalError(absl::StrFormat( "Unsupported normal client message : %s", content->DebugString())); } } } if (status == TCP_FORWARD) { while (true) { uint64_t consumed_length; ASSIGN_OR_RETURN(auto content, common::message::TryParse( id, key, socket_io->DataToRead(), &consumed_length)); if (!content.has_value()) { break; } socket_io->ConsumeReadData(consumed_length); if (content->has_tcp_packet()) { tcp_forward_io->AppendWriteData( content->tcp_packet().data()); } else if (content->has_heartbeat()) { last_received_heartbeat = absl::Now(); } else { return absl::InternalError(absl::StrFormat( "Unsupported tcp forward message : %s", content->DebugString())); } } if (tcp_forward_io->HasDataToRead()) { proto::TcpPacket packet; *packet.mutable_data() = std::string(tcp_forward_io->DataToRead()); tcp_forward_io->ConsumeReadData( tcp_forward_io->DataToRead().size()); proto::Content content; *content.mutable_tcp_packet() = packet; ASSIGN_OR_RETURN( std::string send_data, common::message::Serialize(id, key, content)); socket_io->AppendWriteData(send_data); } } } return absl::OkStatus(); } void ClientSocketThread(uint64_t tid, ThreadManager* tm, net::NetSocket* socket) { try { auto status = ClientSocketMain( tid, tm, std::unique_ptr<net::NetSocket>(socket)); if (!status.ok()) { LOG(ERROR) << "client socket thread error : " << status; } else { LOG(INFO) << "client socket thread exit"; } } catch (...) { LOG(ERROR) << "client socket thread catched an error"; } } private: const absl::Time startup_time_; struct TcpForwardIncomming { std::unique_ptr<net::NetSocket> socket; absl::Time created_time; Config::TcpForward tcp_forward; bool have_sent_to_client; }; std::atomic_int ended_; std::mutex mtx_; // 以下数据的读和写需要使用mtx_进行保护 Config config_; std::list<TcpForwardIncomming> tcp_incommings_; std::set<std::string> online_clients_; }; } // namespace int main(int argc, char* argv[]) { FLAGS_logtostderr = true; gflags::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); if (FLAGS_listen_manage_sock.empty()) { LOG(ERROR) << "--listen_manage_sock is required"; return 1; } if (FLAGS_listen_net_port == 0) { LOG(ERROR) << "--listen_net_port is required"; return 1; } absl::SleepFor(absl::Seconds(2)); LOG(INFO) << "Server started"; Server server; ThreadManager tm; tm.Launch(std::bind(&Server::ManageThread, &server, _1, _2)); tm.Start(); return 0; }
37.967254
80
0.476348
[ "object", "vector" ]
ddf5b3462f4f802dd4e733f164450e5d7975996f
17,812
cxx
C++
ds/adsi/winnt/cggi.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
ds/adsi/winnt/cggi.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
ds/adsi/winnt/cggi.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//--------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1992 - 1995 // // File: cggi.cxx // // Contents: This file contains the Group Object's // IADsGroup and IADsGroupOperation methods // // History: 11-1-95 krishnag Created. // //---------------------------------------------------------------------------- #include "winnt.hxx" #pragma hdrstop BOOL VerifyIfMember( BSTR bstrMember, VARIANT * VariantArray, ULONG cElementFetched ); BOOL IsStringSID(LPWSTR pszStringSID); // Class CWinNTGroup STDMETHODIMP CWinNTGroup::get_Description(THIS_ BSTR FAR* retval) { GET_PROPERTY_BSTR((IADsGroup *)this,Description); } STDMETHODIMP CWinNTGroup::put_Description(THIS_ BSTR bstrDescription) { PUT_PROPERTY_BSTR((IADsGroup *)this,Description); } STDMETHODIMP CWinNTGroup::Members( THIS_ IADsMembers FAR* FAR* ppMembers ) { HRESULT hr; WCHAR szHostServerName[MAX_PATH]; NET_API_STATUS nasStatus = 0; if (_ParentType == WINNT_DOMAIN_ID) { hr = WinNTGetCachedDCName( _DomainName, szHostServerName, _Credentials.GetFlags() ); BAIL_ON_FAILURE(hr); } if (_GroupType == WINNT_GROUP_GLOBAL) { hr = CWinNTGroupCollection::CreateGroupCollection( _Parent, _ParentType, _DomainName, _ParentType == WINNT_DOMAIN_ID ? (szHostServerName + 2) : _ServerName, _Name, _GroupType, IID_IADsMembers, _Credentials, (void **)ppMembers ); } else { hr = CWinNTLocalGroupCollection::CreateGroupCollection( _Parent, _ParentType, _DomainName, _ParentType == WINNT_DOMAIN_ID ? (szHostServerName + 2) : _ServerName, _Name, _GroupType, IID_IADsMembers, _Credentials, (void **)ppMembers ); } error: RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CWinNTGroup::IsMember( THIS_ BSTR bstrMember, VARIANT_BOOL FAR* bMember ) { IADsMembers FAR * pMembers = NULL; IUnknown FAR * pUnknown = NULL; IEnumVARIANT FAR * pEnumVar = NULL; DWORD i = 0; HRESULT hr = S_OK; VARIANT_BOOL fMember = FALSE; VARIANT VariantArray[10]; BOOL fContinue = TRUE; ULONG cElementFetched = 0; const DWORD dwMaxFailures = 1000; DWORD dwFailureCount = 0; hr = Members( &pMembers ); BAIL_ON_FAILURE(hr); hr = pMembers->get__NewEnum( &pUnknown ); BAIL_ON_FAILURE(hr); hr = pUnknown->QueryInterface( IID_IEnumVARIANT, (void **)&pEnumVar ); BAIL_ON_FAILURE(hr); while (fContinue) { IADs *pObject ; // // Reset the fetched count in case the function fails. // cElementFetched = 0; hr = pEnumVar->Next( 10, VariantArray, &cElementFetched ); if (FAILED(hr)) { // // An error occurred, if we have exceeded our maximum number // of failures, give up and return. Otherwise just ignore // the error and try again. // if (dwMaxFailures < ++dwFailureCount) { // // The rest of the processing in the loop can be done because // it doesn't do any harm and will clean up any allocated objects. // fContinue = FALSE; hr = S_FALSE; } else { // // Reset hr to S_OK because we may have been returned valid data, // we don't really care about the error and we don't want to return // an error code if the data that we were returned is a match. // Just in case we were returned valid data, continue with the // rest of the processing. // hr = S_OK; } } else if (hr == S_FALSE) { fContinue = FALSE; // // Reset hr to S_OK, we want to return success // hr = S_OK; } fMember = (VARIANT_BOOL)VerifyIfMember( bstrMember, VariantArray, cElementFetched ); if (fMember) { fContinue = FALSE; } for (i = 0; i < cElementFetched; i++ ) { IDispatch *pDispatch = NULL; pDispatch = VariantArray[i].pdispVal; pDispatch->Release(); } memset(VariantArray, 0, sizeof(VARIANT)*10); } error: *bMember = fMember? VARIANT_TRUE : VARIANT_FALSE; if (pEnumVar) { pEnumVar->Release(); } if (pUnknown) { pUnknown->Release(); } if (pMembers) { pMembers->Release(); } RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CWinNTGroup::Add(THIS_ BSTR bstrNewItem) { HRESULT hr; NET_API_STATUS nasStatus; LOCALGROUP_MEMBERS_INFO_3 Member; LPLOCALGROUP_MEMBERS_INFO_3 pMember = &Member; POBJECTINFO pObjectInfo = NULL; WCHAR szDomName[MAX_PATH]; WCHAR szHostServerName[MAX_PATH]; int iLastIndx = 0; BOOL fStringSID = FALSE; hr = BuildObjectInfo( bstrNewItem, &pObjectInfo ); BAIL_ON_FAILURE(hr); iLastIndx = pObjectInfo->NumComponents - 1; // // If there is only one component, it has to be in the SID form // or it has to be a Special SID like everyone. // if (pObjectInfo->NumComponents == 1) { // // Check to see if this is S-12-11 // fStringSID = IsStringSID(pObjectInfo->ComponentArray[0]); } memset(pMember, 0, sizeof(LOCALGROUP_MEMBERS_INFO_3)); if (_ParentType == WINNT_COMPUTER_ID) { hr = MakeUncName( _ServerName, szHostServerName ); BAIL_ON_FAILURE(hr); }else if (_ParentType == WINNT_DOMAIN_ID){ hr = WinNTGetCachedDCName( _DomainName, szHostServerName, _Credentials.GetFlags() ); BAIL_ON_FAILURE(hr); } if (_GroupType == WINNT_GROUP_GLOBAL) { #ifdef WIN95 if (_wcsicmp(pObjectInfo->ComponentArray[0], _DomainName)) { #else if (CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE, pObjectInfo->ComponentArray[0], -1, _DomainName, -1 ) != CSTR_EQUAL ) { #endif hr = E_ADS_INVALID_USER_OBJECT; BAIL_ON_FAILURE(hr); } nasStatus = NetGroupAddUser( szHostServerName, _Name, pObjectInfo->ComponentArray[( pObjectInfo->NumComponents - 1)] ); hr = HRESULT_FROM_WIN32(nasStatus); BAIL_ON_FAILURE(hr); }else if (_GroupType == WINNT_GROUP_LOCAL){ if (fStringSID) { hr = AddBySID( pObjectInfo->ComponentArray[0], szHostServerName ); goto error; } // // 0 implies special sid name. // if (iLastIndx != 0) { hr = MakeWinNTAccountName(pObjectInfo, szDomName, FALSE); BAIL_ON_FAILURE(hr); pMember->lgrmi3_domainandname = szDomName; } else { pMember->lgrmi3_domainandname = pObjectInfo->ComponentArray[iLastIndx]; } // // For performance reasos we will first assume that the // use has domain name // nasStatus = NetLocalGroupAddMembers( szHostServerName, _Name, 3, (LPBYTE)pMember, 1 ); if (nasStatus == ERROR_NO_SUCH_MEMBER) { // // Try with true to see if that makes a difference // hr = MakeWinNTAccountName(pObjectInfo, szDomName, TRUE); if (SUCCEEDED(hr)) { // // Try again with this value // pMember->lgrmi3_domainandname = szDomName; nasStatus = NetLocalGroupAddMembers( szHostServerName, _Name, 3, (LPBYTE)pMember, 1 ); } } // // Either way nasStatus will have the correct value // hr = HRESULT_FROM_WIN32(nasStatus); BAIL_ON_FAILURE(hr); } error: if (pObjectInfo) { FreeObjectInfo(pObjectInfo); } RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CWinNTGroup::Remove(THIS_ BSTR bstrItemToBeRemoved) { HRESULT hr; NET_API_STATUS nasStatus; LOCALGROUP_MEMBERS_INFO_3 Member; LPLOCALGROUP_MEMBERS_INFO_3 pMember = &Member; POBJECTINFO pObjectInfo = NULL; WCHAR szDomName[MAX_PATH]; WCHAR szHostServerName[MAX_PATH]; BOOL fSpecialName = FALSE; BOOL fStringSID = FALSE; hr = BuildObjectInfo( bstrItemToBeRemoved, &pObjectInfo ); BAIL_ON_FAILURE(hr); // // If there is only one component, it has to be in the SID form // or it has to be a Special SID like everyone. // if (pObjectInfo->NumComponents == 1) { // // Check to see if this is S-12-11 // fStringSID = IsStringSID(pObjectInfo->ComponentArray[0]); if (!fStringSID) { fSpecialName = TRUE; } } memset(pMember, 0, sizeof(LOCALGROUP_MEMBERS_INFO_3)); if (_ParentType == WINNT_COMPUTER_ID) { hr = MakeUncName( _ServerName, szHostServerName ); BAIL_ON_FAILURE(hr); }else if (_ParentType == WINNT_DOMAIN_ID){ hr = WinNTGetCachedDCName( _DomainName, szHostServerName, _Credentials.GetFlags() ); BAIL_ON_FAILURE(hr); } if (fStringSID) { hr = DeleteBySID( pObjectInfo->ComponentArray[0], szHostServerName ); goto error; } if (_GroupType == WINNT_GROUP_GLOBAL) { #ifdef WIN95 if (_wcsicmp(pObjectInfo->ComponentArray[0], _DomainName)) { #else if (CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE, pObjectInfo->ComponentArray[0], -1, _DomainName, -1 ) != CSTR_EQUAL ) { #endif hr = E_ADS_INVALID_USER_OBJECT; BAIL_ON_FAILURE(hr); } nasStatus = NetGroupDelUser( szHostServerName, _Name, pObjectInfo->ComponentArray[( pObjectInfo->NumComponents) - 1] ); hr = HRESULT_FROM_WIN32(nasStatus); BAIL_ON_FAILURE(hr); }else { if (!fSpecialName) { hr = MakeWinNTAccountName(pObjectInfo, szDomName, FALSE); BAIL_ON_FAILURE(hr); pMember->lgrmi3_domainandname = szDomName; } else { pMember->lgrmi3_domainandname = pObjectInfo->ComponentArray[0]; } nasStatus = NetLocalGroupDelMembers( szHostServerName, _Name, 3, (LPBYTE)pMember, 1 ); if (nasStatus == ERROR_NO_SUCH_MEMBER) { hr = MakeWinNTAccountName(pObjectInfo, szDomName, TRUE); if (SUCCEEDED(hr)) { pMember->lgrmi3_domainandname = szDomName; nasStatus = NetLocalGroupDelMembers( szHostServerName, _Name, 3, (LPBYTE)pMember, 1 ); } } hr = HRESULT_FROM_WIN32(nasStatus); BAIL_ON_FAILURE(hr); } error: if (pObjectInfo) { FreeObjectInfo(pObjectInfo); } RRETURN_EXP_IF_ERR(hr); } BOOL VerifyIfMember( BSTR bstrMember, VARIANT * VariantArray, ULONG cElementFetched ) { DWORD i = 0; HRESULT hr = S_OK; IADs FAR * pObject = NULL; IDispatch FAR * pDispatch = NULL; for (i = 0; i < cElementFetched; i++ ) { IDispatch *pDispatch = NULL; BSTR bstrName = NULL; pDispatch = VariantArray[i].pdispVal; hr = pDispatch->QueryInterface( IID_IADs, (VOID **) &pObject ); BAIL_ON_FAILURE(hr); hr = pObject->get_ADsPath(&bstrName); BAIL_ON_FAILURE(hr); #ifdef WIN95 if (!_wcsicmp(bstrName, bstrMember)) { #else if (CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE, bstrName, -1, bstrMember, -1 ) == CSTR_EQUAL ) { #endif SysFreeString(bstrName); bstrName = NULL; pObject->Release(); return(TRUE); } SysFreeString(bstrName); bstrName = NULL; pObject->Release(); } error: return(FALSE); } HRESULT CWinNTGroup::DeleteBySID( LPWSTR pszStringSID, LPWSTR pszServerName ) { HRESULT hr = S_OK; BOOL fRet = FALSE; PSID pSid = NULL; NET_API_STATUS nasStatus; LOCALGROUP_MEMBERS_INFO_0 member; // // SDDL.H is currently available only for Win2k // #if !defined(WIN95) if (!pszStringSID) { BAIL_ON_FAILURE(hr = E_FAIL); } fRet = ConvertStringSidToSidWrapper( pszStringSID, &pSid ); if (!pSid) { BAIL_ON_FAILURE(hr = HRESULT_FROM_WIN32(GetLastError())); } member.lgrmi0_sid = pSid; nasStatus = NetLocalGroupDelMembers( pszServerName, _Name, 0, (LPBYTE) &member, 1 ); BAIL_ON_FAILURE(hr = HRESULT_FROM_WIN32(nasStatus)); #else BAIL_ON_FAILURE(hr = E_FAIL); #endif error: if (pSid) { LocalFree(pSid); } RRETURN(hr); } // // Same as delete only this time to add by SID. // HRESULT CWinNTGroup::AddBySID( LPWSTR pszStringSID, LPWSTR pszServerName ) { HRESULT hr = S_OK; BOOL fRet = FALSE; PSID pSid = NULL; NET_API_STATUS nasStatus; LOCALGROUP_MEMBERS_INFO_0 member; // // SDDL.H is currently available only for Win2k // #if !defined(WIN95) if (!pszStringSID) { BAIL_ON_FAILURE(hr = E_FAIL); } fRet = ConvertStringSidToSidWrapper( pszStringSID, &pSid ); if (!pSid) { BAIL_ON_FAILURE(hr = HRESULT_FROM_WIN32(GetLastError())); } member.lgrmi0_sid = pSid; nasStatus = NetLocalGroupAddMembers( pszServerName, _Name, 0, (LPBYTE) &member, 1 ); BAIL_ON_FAILURE(hr = HRESULT_FROM_WIN32(nasStatus)); #else BAIL_ON_FAILURE(hr = E_FAIL); #endif error: if (pSid) { LocalFree(pSid); } RRETURN(hr); } // // Helper routine that checks if a string is a sid or not. // BOOL IsStringSID(LPWSTR pszStringSID) { BOOL fRet = FALSE; if (!pszStringSID || (wcslen(pszStringSID) < 4)) { return FALSE; } if (((*pszStringSID != L'S') && (*pszStringSID != L's')) || (*(pszStringSID + 1) != L'-') ) { return FALSE; } return TRUE; }
24.07027
84
0.468954
[ "object" ]
ddf79b2f410cdba1da5fc30ce4cef4f4562964cd
2,064
hh
C++
CommObjectRecognitionObjects/smartsoft/src-gen/CommObjectRecognitionObjects/CommObjectRecognitionObjectPropertiesData.hh
canonical-robots/DomainModelsRepositories
68b9286d84837e5feb7b200833b158ab9c2922a4
[ "BSD-3-Clause" ]
null
null
null
CommObjectRecognitionObjects/smartsoft/src-gen/CommObjectRecognitionObjects/CommObjectRecognitionObjectPropertiesData.hh
canonical-robots/DomainModelsRepositories
68b9286d84837e5feb7b200833b158ab9c2922a4
[ "BSD-3-Clause" ]
2
2020-08-20T14:49:47.000Z
2020-10-07T16:10:07.000Z
CommObjectRecognitionObjects/smartsoft/src-gen/CommObjectRecognitionObjects/CommObjectRecognitionObjectPropertiesData.hh
canonical-robots/DomainModelsRepositories
68b9286d84837e5feb7b200833b158ab9c2922a4
[ "BSD-3-Clause" ]
8
2018-06-25T08:41:28.000Z
2020-08-13T10:39:30.000Z
//-------------------------------------------------------------------------- // Code generated by the SmartSoft MDSD Toolchain // The SmartSoft Toolchain has been developed by: // // Service Robotics Research Center // University of Applied Sciences Ulm // Prittwitzstr. 10 // 89075 Ulm (Germany) // // Information about the SmartSoft MDSD Toolchain is available at: // www.servicerobotik-ulm.de // // Please do not modify this file. It will be re-generated // running the code generator. //-------------------------------------------------------------------------- #ifndef COMMOBJECTRECOGNITIONOBJECTS_COMMOBJECTRECOGNITIONOBJECTPROPERTIES_DATA_H_ #define COMMOBJECTRECOGNITIONOBJECTS_COMMOBJECTRECOGNITIONOBJECTPROPERTIES_DATA_H_ #include "CommObjectRecognitionObjects/CommObjectRelationData.hh" #include "CommObjectRecognitionObjects/CommObjectBeliefData.hh" #include "CommBasicObjects/CommPose3dData.hh" #include "CommBasicObjects/CommPosition3dData.hh" #include "CommObjectRecognitionObjects/CommTriMeshData.hh" #include <vector> #include <string> namespace CommObjectRecognitionObjectsIDL { typedef std::vector<CommObjectRecognitionObjectsIDL::CommObjectBelief> CommObjectRecognitionObjectProperties_beliefs_type; typedef std::vector<CommObjectRecognitionObjectsIDL::CommObjectRelation> CommObjectRecognitionObjectProperties_relations_type; typedef std::vector<CommBasicObjectsIDL::CommPose3d> CommObjectRecognitionObjectProperties_objectSurfacePoses_type; struct CommObjectRecognitionObjectProperties { bool is_valid; unsigned int object_id; std::string object_type; CommBasicObjectsIDL::CommPose3d pose; CommBasicObjectsIDL::CommPosition3d dimension; CommObjectRecognitionObjectProperties_beliefs_type beliefs; CommObjectRecognitionObjectsIDL::CommTriMesh mesh; CommObjectRecognitionObjectProperties_relations_type relations; double fill_level; CommObjectRecognitionObjectProperties_objectSurfacePoses_type objectSurfacePoses; }; }; #endif /* COMMOBJECTRECOGNITIONOBJECTS_COMMOBJECTRECOGNITIONOBJECTPROPERTIES_DATA_H_ */
42.122449
127
0.789729
[ "mesh", "vector" ]
ddffa46339fdf916f62a8f2aa791560a10e56874
5,554
cpp
C++
src/renderer/shader.cpp
hexoctal/zenith
eeef065ed62f35723da87c8e73a6716e50d34060
[ "MIT" ]
2
2021-03-18T16:25:04.000Z
2021-11-13T00:29:27.000Z
src/renderer/shader.cpp
hexoctal/zenith
eeef065ed62f35723da87c8e73a6716e50d34060
[ "MIT" ]
null
null
null
src/renderer/shader.cpp
hexoctal/zenith
eeef065ed62f35723da87c8e73a6716e50d34060
[ "MIT" ]
1
2021-11-13T00:29:30.000Z
2021-11-13T00:29:30.000Z
/** * @file * @author __AUTHOR_NAME__ <mail@host.com> * @copyright 2021 __COMPANY_LTD__ * @license <a href="https://opensource.org/licenses/MIT">MIT License</a> */ #include "shader.hpp" #include "utility.hpp" #include "../utils/map/contains.hpp" #include "renderer.hpp" #include <functional> namespace Zen { extern Renderer g_renderer; Shader::Shader (std::string name, std::string vertexShader, std::string fragmentShader, std::vector<PipelineAttributeConfig> attributes) : name (name) { createProgram(vertexShader, fragmentShader); createAttributes(attributes); createUniforms(); } void Shader::createProgram (std::string vertexShader, std::string fragmentShader) { const char *vsCode = vertexShader.c_str(); const char *fsCode = fragmentShader.c_str(); GLuint vs = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vs, 1, &vsCode, nullptr); glCompileShader(vs); checkCompileErrors(vs, "VERTEX"); GLuint fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs, 1, &fsCode, nullptr); glCompileShader(fs); checkCompileErrors(fs, "FRAGMENT"); // Shader program program = glCreateProgram(); glAttachShader(program, vs); glAttachShader(program, fs); glLinkProgram(program); checkCompileErrors(program, "PROGRAM"); // Delete the shaders as they're linked into our program now and no // longer necessery glDeleteShader(vs); glDeleteShader(fs); glUseProgram(program); } void Shader::checkCompileErrors (GLuint shader, std::string type) { GLint success; if (type != "PROGRAM") { glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { GLchar infoLog[1024]; glGetShaderInfoLog(shader, 1024, nullptr, infoLog); MessageError("Shader compilation failed for shader \"", name, "\" : ", type, " | ", infoLog); } } else { glGetProgramiv(shader, GL_LINK_STATUS, &success); if (!success) { GLchar infoLog[1024]; glGetShaderInfoLog(shader, 1024, nullptr, infoLog); MessageError("Program linking failed for shader \"", name, "\" : ", type, " | ", infoLog); } } } void Shader::createAttributes ( std::vector<PipelineAttributeConfig> attributes) { GLuint count = 0; GLuint offset = 0; std::vector<PipelineAttribute> result; vertexComponentCount = 0; for (size_t i = 0; i < attributes.size(); i++) { auto &element = attributes[i]; std::string name = element.name; int size = element.size; // 1 for float, 2 for vec2, 4 for vec4... GLenum type = element.type; // GL_FLOAT, GL_UNSIGNED_BYTE... std::size_t typeSize = GetGLTypeSize(type); // Size of the type in byte bool normalized = element.normalized; result.emplace_back( name, size, type, offset, normalized, false, -1 ); if (typeSize == 4) count += size; else count++; // offset in bytes = number of elements in component * byte size of type offset += size * typeSize; } this->vertexSize = offset; this->vertexComponentCount = count; this->attributes = result; } void Shader::bind (bool setAttributes, bool flush) { if (flush) emit("pipeline-flush"); g_renderer.setProgram(program); /* if (setAttributes) setAttribPointers(); */ } Shader* Shader::rebind () { g_renderer.setProgram(program); setAttribPointers(true); return this; } void Shader::setAttribPointers (bool reset) { for (size_t i = 0; i < attributes.size(); i++) { auto &element = attributes[i]; GLint attribLocation = i; glEnableVertexAttribArray(attribLocation); glVertexAttribPointer(attribLocation, element.size, element.type, element.normalized, vertexSize, reinterpret_cast<void*>(element.offset)); element.enabled = true; element.location = attribLocation; } /* for (size_t i = 0; i < attributes.size(); i++) { auto &element = attributes[i]; if (reset) { GLint attribLocation = i; glEnableVertexAttribArray(attribLocation); glVertexAttribPointer(attribLocation, element.size, element.type, element.normalized, vertexSize, reinterpret_cast<void*>(element.offset)); element.enabled = true; element.location = attribLocation; } else if (element.enabled) { glVertexAttribPointer(element.location, element.size, element.type, element.normalized, vertexSize, reinterpret_cast<void*>(element.offset)); } else if (!element.enabled && element.location > -1) { glDisableVertexAttribArray(element.location); element.location = -1; } } */ } void Shader::createUniforms () { GLint i = 0; GLint location; GLsizei length; GLint size; GLenum type; GLchar nameBuffer[512]; std::string name; // Look-up all active uniforms GLint totalUniforms; glGetProgramiv(program, GL_ACTIVE_UNIFORMS, &totalUniforms); for (i = 0; i < totalUniforms; i++) { glGetActiveUniform(program, i, 512, &length, &size, &type, nameBuffer); if (length > 0) { name = std::string(nameBuffer); // If array, remove the "[0]" std::size_t idx = name.find("["); if (idx != std::string::npos) { name = name.substr(0, idx); } location = glGetUniformLocation(program, name.c_str()); if (location >= 0) { uniforms[name] = { .name = name, .location = static_cast<GLuint>(location), .length = size, .type = type, .size = GetGLTypeSize(type) * size }; } } } } bool Shader::hasUniform (std::string name) { return uniforms.find(name) != uniforms.end(); } void Shader::resetUniform (std::string name) { if (uniforms.find(name) == uniforms.end()) return; auto &uniform = uniforms[name]; uniform.value.clear(); } } // namespace Zen
22.395161
81
0.687613
[ "vector" ]
fb072879c37f5a45d5fab072f4ce84ef534fcd74
677
cpp
C++
codeforces/1417B.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
codeforces/1417B.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
codeforces/1417B.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
// B. Two Arrays #include <iostream> #include <vector> using namespace std; int main(){ int t; cin >> t; while(t--){ int n, T; cin >> n >> T; int ans[n]; // Editorial - https://codeforces.com/blog/entry/83036 vector<int> x, y, z; int tmp; int flag = 0; for(int i=0; i<n; ++i){ cin >> tmp; if (T%2==0 and tmp == T/2) { ans[i] = (flag++)%2; } else if (tmp*2 < T) ans[i] = 0; else ans[i] = 1; } for (auto it: ans){ cout << it << ' '; } cout << endl; } return 0; }
15.744186
62
0.379616
[ "vector" ]
fb09174f0cedec3955ebf77d1238f272cc01882b
2,611
cpp
C++
TermRankingMethod/analysis.cpp
ifapmzadu6/TRankingMethod
aa5b02cb921537fd954bd80e0aa050c86b00d547
[ "MIT" ]
null
null
null
TermRankingMethod/analysis.cpp
ifapmzadu6/TRankingMethod
aa5b02cb921537fd954bd80e0aa050c86b00d547
[ "MIT" ]
null
null
null
TermRankingMethod/analysis.cpp
ifapmzadu6/TRankingMethod
aa5b02cb921537fd954bd80e0aa050c86b00d547
[ "MIT" ]
null
null
null
// // analysis.cpp // FireflyProject // // Created by Keisuke Karijuku on 2013/12/11. // Copyright (c) 2013年 Keisuke Karijuku. All rights reserved. // #include "analysis.h" #include<vector> #include<iostream> /* &flucP 周期揺らぎ sn 音声データ fsize 零点修正誤差範囲(秒) dsize 相関関数の幅(秒) dmin 求める周期幅の最小(秒) dmax 求める周期幅の最大(秒) sampPerSec サンプリング周波数(Hz) */ void GetFlucPeriod( std::vector<int>& flucP, const std::vector<double> sn,const double fsize, const double dsize, const double dmin, const double dmax,const unsigned int sampPerSec) { std::cout << "DFF now in progress..." << std::endl; flucP.clear(); std::vector<double> temp_x,temp_y,r; // 相関関数 std::vector<int> index,fixindex; // index:相関関数で求まる周期(index),fixindex:零点に修正した周期(index) int offset; int pmin,pmax,p; int fixsize; int n,m; double max; unsigned int count=0,max_count=0,miss_count=0; // 零点検出の連続回数 unsigned int zero_min_i=0,zero_max_i=0; offset = 0; temp_x.resize( (int)(sampPerSec * dsize) ); temp_y.resize( temp_x.size() ); fixsize = (int)(sampPerSec * fsize); pmin = (int)(sampPerSec * dmin); pmax = (int)(sampPerSec * dmax); r.resize(pmax+1); while( offset + pmax * 2 < sn.size() ) { for(n=0;n<temp_x.size();n++) { temp_x[n] = sn[offset + n]; } max = 0.0; p=pmin; // 相関関数 for(m=pmin;m<=pmax;m++) { for(n=0;n<temp_x.size();n++) { temp_y[n] = sn[offset+m+n]; } r[m]=0.0; for(n=0;n<temp_x.size();n++) { r[m]+=temp_x[n]*temp_y[n]; } if(r[m]>max) { max=r[m]; p=m; } } index.push_back(offset); offset += p; } offset = 0.0; // 零点修正 for( n=0;n<index.size();n++) { for(m=0;m<fixsize;m++) { if(index[n]+m+1 < sn.size()) { if(sn[index[n]+m] * sn[index[n]+m+1] <= 0.0) { fixindex.push_back(index[n]+m); count++; break; } } if(index[n]-m-1 > 0) { if(sn[index[n]-m] * sn[index[n]-m-1] <= 0.0) { fixindex.push_back(index[n]-m-1); count++; break; } } if(m==fixsize-1) { count = 0; miss_count++; break; } } if(max_count < count) { max_count = count; zero_max_i = n-miss_count; zero_min_i = zero_max_i-(max_count-1); } } std::cout << "零点検出率:" << (double)fixindex.size()/(double)index.size() * 100.0 << "%" << std::endl; //* for( n=0;n<fixindex.size()-1;n++ ) { flucP.push_back(fixindex[n+1]-fixindex[n]); } //*/ /* 零点連続部分のみ抽出する場合 for( n=zero_min_i+1;n<zero_max_i;n++) { flucP.push_back(fixindex[n+1]-fixindex[n]); } //*/ std::cout << "DFF finish." << std::endl; }
19.780303
106
0.569131
[ "vector" ]
fb0a317eb14b075d872fcaa7c6864f943d9a4a32
269
cpp
C++
XConsole/vector.cpp
vaxerski/XConsole
bd9138b66f28dba03ee003da6d196942446166a5
[ "MIT" ]
null
null
null
XConsole/vector.cpp
vaxerski/XConsole
bd9138b66f28dba03ee003da6d196942446166a5
[ "MIT" ]
null
null
null
XConsole/vector.cpp
vaxerski/XConsole
bd9138b66f28dba03ee003da6d196942446166a5
[ "MIT" ]
null
null
null
#include "vector.h" Vector2D::Vector2D(double xx, double yy) { x = xx; y = yy; } Vector2D::~Vector2D() {} double Vector2D::normalize() { //get max abs const auto max = abs(x) > abs(y) ? abs(x) : abs(y); x /= max; y /= max; return max; }
14.944444
55
0.539033
[ "vector" ]
fb1064c1cc2a2c3826cd17274b880e2864f07a8f
2,081
cpp
C++
DSA_Implementation/23. String/5. Longest Palindromic Substring.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
5
2021-02-14T17:48:21.000Z
2022-01-24T14:29:44.000Z
DSA_Implementation/23. String/5. Longest Palindromic Substring.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
null
null
null
DSA_Implementation/23. String/5. Longest Palindromic Substring.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; class Solution { public: string longestPalindrome(string str) { //approach-01: Brute Force: O(n^3) //approach-02: Expand Around Center: Time: O(n^2), Space: O(1) /* if(str=="" or str.size()<1) return ""; string res; for(int i=0;i<str.size();i++){ string tmp = expandFromMiddle(str, i, i); if(tmp.size()>res.size()) res = tmp; tmp = expandFromMiddle(str, i, i+1); if(tmp.size()>res.size()) res = tmp; } return res; */ //Approach-03: DP: Time: O(n^2), Space: O(1) int len = str.size(); if(len==0) return ""; vector<vector<bool>> dp(len, vector<bool> (len, false)); for(int i=0;i<len;i++){ dp[i][i] = true; if(i==len-1) break; dp[i][i+1] = (str[i]==str[i+1]); } //dp for(int i=len-3;i>=0;i--){ for(int j=i+2;j<len;j++){ dp[i][j] = (dp[i+1][j-1] and (str[i]==str[j])); } } //get maxstr result int mx = 0; string maxstr = ""; for(int i=0;i<len;i++){ for(int j=i;j<len;j++){ if(dp[i][j]==true and j-i+1>mx){ mx = j-i+1; maxstr = str.substr(i, j-i+1); } } } return maxstr; //Approach-04: Manacher's Algorithm, Time: O(n), Space: O(1) } private: string expandFromMiddle(string s, int left, int right){ if(right>s.size()) return ""; while(left>=0 and right<s.size() and s[left]==s[right]){ left--; right++; } return s.substr(left+1, right-left-1); } }; int main(){ Solution s; string str = "forgeeksskeegfor"; cout<<s.longestPalindrome(str)<<endl; return 0; }
22.868132
70
0.416146
[ "vector" ]
fb121306bd9e8e5dae267f55e66bc73fa761bb50
1,110
cpp
C++
HWyuzhuChapter10/Problem6/main.cpp
yzhu5/computational-physics
40c35aebecd2ebfac81f3d1e9c8de3eb9310895a
[ "MIT" ]
null
null
null
HWyuzhuChapter10/Problem6/main.cpp
yzhu5/computational-physics
40c35aebecd2ebfac81f3d1e9c8de3eb9310895a
[ "MIT" ]
null
null
null
HWyuzhuChapter10/Problem6/main.cpp
yzhu5/computational-physics
40c35aebecd2ebfac81f3d1e9c8de3eb9310895a
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; class Move { private: double x; double y; public: Move(double a = 0, double b = 0); // sets x, y to a, b void showmove() const; // shows current x, y values Move add(const Move & m) const; // this function adds x of m to x of invoking object to get new x, // adds y of m to y of invoking object to get new y, creates a new // move object initialized to new x, y values and returns it void reset(double a = 0, double b = 0); // resets x,y to a, b }; Move::Move(double a, double b) { x = a; y = b; } void Move::showmove() const { cout << "( " << x << " , " << y << " )" << endl; } Move Move::add(const Move &m) const { return (Move(x+m.x,y+m.y)); } void Move::reset(double a, double b) { x = a; y = b; } int main() { Move m1; m1.showmove(); m1.reset(88,88); m1.showmove(); Move m2 = Move(66,66); Move m3 = m2.add(m1); m3.showmove(); return 0; }
20.555556
78
0.498198
[ "object" ]
fb148098c6bda86a7d2b5293db96d4f049e22af1
1,219
cpp
C++
atcoder/agc037e.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
1
2020-04-04T14:56:12.000Z
2020-04-04T14:56:12.000Z
atcoder/agc037e.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
atcoder/agc037e.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // take u=s+t mx = most consective a // then each round ....aaaa | aaaa..... double size // rep of a = 2^(k-1) * mx // note in final round aa..a in start void solve() { int n, k; cin >> n >> k; string s; cin >> s; string t = s; reverse(t.begin(), t.end()); string u = s + t; char mi = 'z'; for (char x: s) { mi = min(mi, x); } int mx = 1; vector<int> len(2*n+1, 0); for (int i = 0; i < 2*n; i++) { len[i+1] = u[i] == mi ? len[i]+1 : 0; len[i+1] = min(len[i+1], n); mx = max(mx, len[i+1]); } if (k>15 || (1<<(k-1))*mx >= n) { for (int i = 0; i < n; i++) { cout << mi; } return; } int rep =(1<<(k-1)) * mx; int m = n - rep; string res = "{"; for (int i = n+1; i <= 2*n; i++) { if (len[i] == mx) { string tmp = u.substr(i-m-mx, m); reverse(tmp.begin(), tmp.end()); res = min(res, tmp); } } for (int i = 0; i < rep; i++) { cout << mi; } cout << res; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve(); cout << endl; }
22.163636
51
0.417555
[ "vector" ]
fb17ef3798ec20f728da2fc412a5a4c6a20c404f
2,753
cpp
C++
src/utils/Settings.cpp
oz117/wonder-space
daef954ef93af17ea692a26895ab7102e0696908
[ "BSD-2-Clause" ]
null
null
null
src/utils/Settings.cpp
oz117/wonder-space
daef954ef93af17ea692a26895ab7102e0696908
[ "BSD-2-Clause" ]
null
null
null
src/utils/Settings.cpp
oz117/wonder-space
daef954ef93af17ea692a26895ab7102e0696908
[ "BSD-2-Clause" ]
null
null
null
// COPYRIGHT (c) 2016 Andre Paulos // // BSD ISC License // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include <fstream> #include <iostream> #include "Settings.hpp" Settings::Settings(const sstring& path): _errors(0), _readLines(0) { loadFile(path); if (this->_errors == 0 || this->_readLines != 0) { return; } // This will be replaced by a logger later on :) std::cerr << "Configuration file is broken" << std::endl; this->_width = 629; this->_height = 600; } Settings::~Settings(void) {} // @description Read the configuration file line by line // @param std::string path to configuration file void Settings::loadFile(const sstring& path) { std::ifstream file(path); sstring line; while (!file.eof()) { std::getline(file, line); if (line.size() != 0) setConfiguration(line); line.clear(); } } // @description Inits the different parts of the Configuration // @param std::string path to configuration file // Check of file existence in main file void Settings::setConfiguration(const sstring& line) noexcept { size_t pos; this->_readLines++; pos = line.find("= ") + 2; if (!line.compare(0, 5, "title")) this->_title = line.substr(pos); else if (!line.compare(0, 10, "resolution")) extractResolution(line.substr(pos)); else this->_errors = 1; } // @description Parses the resolution // @param std::string line containing the resolution // @return int 0 if success. Test object->_errors for errors int Settings::extractResolution(const sstring& line) noexcept { size_t pos; if ((pos = line.find(" ")) == sstring::npos) return (this->_errors = 1); try { this->_height = stoi(line.substr(0, pos)); this->_width = stoi(line.substr(pos + 1)); } catch (std::exception e) { return (this->_errors = 1); } return (0); } const std::string& Settings::getTitle(void) const noexcept { return this->_title; } int Settings::getWidth(void) const noexcept { return this->_width; } int Settings::getHeight(void) const noexcept { return this->_height; }
29.602151
75
0.691609
[ "object" ]
fb23934b0ded4d9474ec3112ac476972a883bc04
16,182
cc
C++
icing/index/lite/lite-index.cc
PixelPlusUI-SnowCone/external_icing
206a7d6b4ab83c6acdb8b14565e2431751c9e4cf
[ "Apache-2.0" ]
null
null
null
icing/index/lite/lite-index.cc
PixelPlusUI-SnowCone/external_icing
206a7d6b4ab83c6acdb8b14565e2431751c9e4cf
[ "Apache-2.0" ]
null
null
null
icing/index/lite/lite-index.cc
PixelPlusUI-SnowCone/external_icing
206a7d6b4ab83c6acdb8b14565e2431751c9e4cf
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 "icing/index/lite/lite-index.h" #include <inttypes.h> #include <stddef.h> #include <stdint.h> #include <sys/mman.h> #include <algorithm> #include <cstdint> #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include "icing/text_classifier/lib3/utils/base/status.h" #include "icing/text_classifier/lib3/utils/base/statusor.h" #include "icing/absl_ports/canonical_errors.h" #include "icing/absl_ports/str_cat.h" #include "icing/file/filesystem.h" #include "icing/index/hit/doc-hit-info.h" #include "icing/index/hit/hit.h" #include "icing/index/term-property-id.h" #include "icing/legacy/core/icing-string-util.h" #include "icing/legacy/core/icing-timer.h" #include "icing/legacy/index/icing-array-storage.h" #include "icing/legacy/index/icing-dynamic-trie.h" #include "icing/legacy/index/icing-filesystem.h" #include "icing/legacy/index/icing-lite-index-header.h" #include "icing/legacy/index/icing-mmapper.h" #include "icing/proto/term.pb.h" #include "icing/schema/section.h" #include "icing/store/document-id.h" #include "icing/util/crc32.h" #include "icing/util/logging.h" #include "icing/util/status-macros.h" namespace icing { namespace lib { namespace { // Point at which we declare the trie full. constexpr double kTrieFullFraction = 0.95; std::string MakeHitBufferFilename(const std::string& filename_base) { return filename_base + "hb"; } size_t header_size() { return sizeof(IcingLiteIndex_HeaderImpl::HeaderData); } } // namespace const TermIdHitPair::Value TermIdHitPair::kInvalidValue = TermIdHitPair(0, Hit()).value(); libtextclassifier3::StatusOr<std::unique_ptr<LiteIndex>> LiteIndex::Create( const LiteIndex::Options& options, const IcingFilesystem* filesystem) { ICING_RETURN_ERROR_IF_NULL(filesystem); std::unique_ptr<LiteIndex> lite_index = std::unique_ptr<LiteIndex>(new LiteIndex(options, filesystem)); ICING_RETURN_IF_ERROR(lite_index->Initialize()); return std::move(lite_index); } // size is max size in elements. An appropriate lexicon and display // mapping size will be chosen based on hit buffer size. LiteIndex::LiteIndex(const LiteIndex::Options& options, const IcingFilesystem* filesystem) : hit_buffer_(*filesystem), hit_buffer_crc_(0), lexicon_(options.filename_base + "lexicon", MakeTrieRuntimeOptions(), filesystem), header_mmap_(false, MAP_SHARED), options_(options), filesystem_(filesystem) {} LiteIndex::~LiteIndex() { if (initialized()) { libtextclassifier3::Status unused = PersistToDisk(); } } IcingDynamicTrie::RuntimeOptions LiteIndex::MakeTrieRuntimeOptions() { return IcingDynamicTrie::RuntimeOptions().set_storage_policy( IcingDynamicTrie::RuntimeOptions::kMapSharedWithCrc); } libtextclassifier3::Status LiteIndex::Initialize() { // Size of hit buffer's header struct, rounded up to the nearest number of // system memory pages. const size_t header_padded_size = IcingMMapper::page_aligned_size(header_size()); // Variable declarations cannot cross goto jumps, so declare these up top. libtextclassifier3::Status status; uint64_t file_size; IcingTimer timer; if (!lexicon_.CreateIfNotExist(options_.lexicon_options) || !lexicon_.Init()) { return absl_ports::InternalError("Failed to initialize lexicon trie"); } hit_buffer_fd_.reset(filesystem_->OpenForWrite( MakeHitBufferFilename(options_.filename_base).c_str())); if (!hit_buffer_fd_.is_valid()) { status = absl_ports::InternalError("Failed to open hit buffer file"); goto error; } file_size = filesystem_->GetFileSize(hit_buffer_fd_.get()); if (file_size == IcingFilesystem::kBadFileSize) { status = absl_ports::InternalError("Failed to query hit buffer file size"); goto error; } if (file_size < header_padded_size) { if (file_size != 0) { status = absl_ports::InternalError(IcingStringUtil::StringPrintf( "Hit buffer had unexpected size %" PRIu64, file_size)); goto error; } ICING_VLOG(2) << "Creating new hit buffer"; // Make sure files are fresh. if (!lexicon_.Remove() || !lexicon_.CreateIfNotExist(options_.lexicon_options) || !lexicon_.Init()) { status = absl_ports::InternalError("Failed to refresh lexicon during clear"); goto error; } // Create fresh hit buffer by first emptying the hit buffer file and then // allocating header_padded_size of the cleared space. if (!filesystem_->Truncate(hit_buffer_fd_.get(), 0) || !filesystem_->Truncate(hit_buffer_fd_.get(), header_padded_size)) { status = absl_ports::InternalError("Failed to truncate hit buffer file"); goto error; } // Set up header. header_mmap_.Remap(hit_buffer_fd_.get(), 0, header_size()); header_ = std::make_unique<IcingLiteIndex_HeaderImpl>( reinterpret_cast<IcingLiteIndex_HeaderImpl::HeaderData*>( header_mmap_.address())); header_->Reset(); if (!hit_buffer_.Init(hit_buffer_fd_.get(), header_padded_size, true, sizeof(TermIdHitPair::Value), header_->cur_size(), options_.hit_buffer_size, &hit_buffer_crc_, true)) { status = absl_ports::InternalError("Failed to initialize new hit buffer"); goto error; } UpdateChecksum(); } else { header_mmap_.Remap(hit_buffer_fd_.get(), 0, header_size()); header_ = std::make_unique<IcingLiteIndex_HeaderImpl>( reinterpret_cast<IcingLiteIndex_HeaderImpl::HeaderData*>( header_mmap_.address())); if (!hit_buffer_.Init(hit_buffer_fd_.get(), header_padded_size, true, sizeof(TermIdHitPair::Value), header_->cur_size(), options_.hit_buffer_size, &hit_buffer_crc_, true)) { status = absl_ports::InternalError( "Failed to re-initialize existing hit buffer"); goto error; } // Check integrity. if (!header_->check_magic()) { status = absl_ports::InternalError("Lite index header magic mismatch"); goto error; } Crc32 crc = ComputeChecksum(); if (crc.Get() != header_->lite_index_crc()) { status = absl_ports::DataLossError( IcingStringUtil::StringPrintf("Lite index crc check failed: %u vs %u", crc.Get(), header_->lite_index_crc())); goto error; } } ICING_VLOG(2) << IcingStringUtil::StringPrintf("Lite index init ok in %.3fms", timer.Elapsed() * 1000); return status; error: header_ = nullptr; header_mmap_.Unmap(); lexicon_.Close(); hit_buffer_crc_ = 0; hit_buffer_.Reset(); hit_buffer_fd_.reset(); if (status.ok()) { return absl_ports::InternalError( "Error handling code ran but status was ok"); } return status; } Crc32 LiteIndex::ComputeChecksum() { IcingTimer timer; // Update crcs. uint32_t dependent_crcs[2]; hit_buffer_.UpdateCrc(); dependent_crcs[0] = hit_buffer_crc_; dependent_crcs[1] = lexicon_.UpdateCrc(); // Compute the master crc. // Header crc, excluding the actual crc field. Crc32 all_crc(header_->CalculateHeaderCrc()); all_crc.Append(std::string_view(reinterpret_cast<const char*>(dependent_crcs), sizeof(dependent_crcs))); ICING_VLOG(2) << IcingStringUtil::StringPrintf( "Lite index crc computed in %.3fms", timer.Elapsed() * 1000); return all_crc; } libtextclassifier3::Status LiteIndex::Reset() { IcingTimer timer; // TODO(b/140436942): When these components have been changed to return errors // they should be propagated from here. lexicon_.Clear(); hit_buffer_.Clear(); header_->Reset(); UpdateChecksum(); ICING_VLOG(2) << IcingStringUtil::StringPrintf("Lite index clear in %.3fms", timer.Elapsed() * 1000); return libtextclassifier3::Status::OK; } void LiteIndex::Warm() { hit_buffer_.Warm(); lexicon_.Warm(); } libtextclassifier3::Status LiteIndex::PersistToDisk() { bool success = true; if (!lexicon_.Sync()) { ICING_VLOG(1) << "Failed to sync the lexicon."; success = false; } hit_buffer_.Sync(); UpdateChecksum(); header_mmap_.Sync(); return (success) ? libtextclassifier3::Status::OK : absl_ports::InternalError( "Unable to sync lite index components."); } void LiteIndex::UpdateChecksum() { header_->set_lite_index_crc(ComputeChecksum().Get()); } libtextclassifier3::StatusOr<uint32_t> LiteIndex::InsertTerm( const std::string& term, TermMatchType::Code term_match_type, NamespaceId namespace_id) { uint32_t tvi; if (!lexicon_.Insert(term.c_str(), "", &tvi, false)) { return absl_ports::ResourceExhaustedError( absl_ports::StrCat("Unable to add term ", term, " to lexicon!")); } ICING_RETURN_IF_ERROR(UpdateTermProperties( tvi, term_match_type == TermMatchType::PREFIX, namespace_id)); return tvi; } libtextclassifier3::Status LiteIndex::UpdateTermProperties( uint32_t tvi, bool hasPrefixHits, NamespaceId namespace_id) { if (hasPrefixHits && !lexicon_.SetProperty(tvi, GetHasHitsInPrefixSectionPropertyId())) { return absl_ports::ResourceExhaustedError( "Insufficient disk space to create prefix property!"); } if (!lexicon_.SetProperty(tvi, GetNamespacePropertyId(namespace_id))) { return absl_ports::ResourceExhaustedError( "Insufficient disk space to create namespace property!"); } return libtextclassifier3::Status::OK; } libtextclassifier3::Status LiteIndex::AddHit(uint32_t term_id, const Hit& hit) { if (is_full()) { return absl_ports::ResourceExhaustedError("Hit buffer is full!"); } TermIdHitPair term_id_hit_pair(term_id, hit); uint32_t cur_size = header_->cur_size(); TermIdHitPair::Value* valp = hit_buffer_.GetMutableMem<TermIdHitPair::Value>(cur_size, 1); if (valp == nullptr) { return absl_ports::ResourceExhaustedError( "Allocating more space in hit buffer failed!"); } *valp = term_id_hit_pair.value(); header_->set_cur_size(cur_size + 1); return libtextclassifier3::Status::OK; } libtextclassifier3::StatusOr<uint32_t> LiteIndex::GetTermId( const std::string& term) const { char dummy; uint32_t tvi; if (!lexicon_.Find(term.c_str(), &dummy, &tvi)) { return absl_ports::NotFoundError( absl_ports::StrCat("Could not find ", term, " in the lexicon.")); } return tvi; } int LiteIndex::AppendHits(uint32_t term_id, SectionIdMask section_id_mask, bool only_from_prefix_sections, std::vector<DocHitInfo>* hits_out) { int count = 0; DocumentId last_document_id = kInvalidDocumentId; for (uint32_t idx = Seek(term_id); idx < header_->cur_size(); idx++) { TermIdHitPair term_id_hit_pair( hit_buffer_.array_cast<TermIdHitPair>()[idx]); if (term_id_hit_pair.term_id() != term_id) break; const Hit& hit = term_id_hit_pair.hit(); // Check sections. if (((1u << hit.section_id()) & section_id_mask) == 0) { continue; } // Check prefix section only. if (only_from_prefix_sections && !hit.is_in_prefix_section()) { continue; } DocumentId document_id = hit.document_id(); if (document_id != last_document_id) { ++count; if (hits_out != nullptr) { hits_out->push_back(DocHitInfo(document_id)); } last_document_id = document_id; } if (hits_out != nullptr) { hits_out->back().UpdateSection(hit.section_id(), hit.term_frequency()); } } return count; } int LiteIndex::CountHits(uint32_t term_id) { return AppendHits(term_id, kSectionIdMaskAll, /*only_from_prefix_sections=*/false, /*hits_out=*/nullptr); } bool LiteIndex::is_full() const { return (header_->cur_size() == options_.hit_buffer_size || lexicon_.min_free_fraction() < (1.0 - kTrieFullFraction)); } void LiteIndex::GetDebugInfo(int verbosity, std::string* out) const { absl_ports::StrAppend( out, IcingStringUtil::StringPrintf("Lite Index\nHit buffer %u/%u\n", header_->cur_size(), options_.hit_buffer_size)); // Lexicon. out->append("Lexicon stats:\n"); lexicon_.GetDebugInfo(verbosity, out); } libtextclassifier3::StatusOr<int64_t> LiteIndex::GetElementsSize() const { IndexStorageInfoProto storage_info = GetStorageInfo(IndexStorageInfoProto()); if (storage_info.lite_index_hit_buffer_size() == -1 || storage_info.lite_index_lexicon_size() == -1) { return absl_ports::AbortedError( "Failed to get size of LiteIndex's members."); } // On initialization, we grow the file to a padded size first. So this size // won't count towards the size taken up by elements size_t header_padded_size = IcingMMapper::page_aligned_size(header_size()); return storage_info.lite_index_hit_buffer_size() - header_padded_size + storage_info.lite_index_lexicon_size(); } IndexStorageInfoProto LiteIndex::GetStorageInfo( IndexStorageInfoProto storage_info) const { int64_t header_and_hit_buffer_file_size = filesystem_->GetFileSize(hit_buffer_fd_.get()); if (header_and_hit_buffer_file_size != Filesystem::kBadFileSize) { storage_info.set_lite_index_hit_buffer_size( header_and_hit_buffer_file_size); } else { storage_info.set_lite_index_hit_buffer_size(-1); } int64_t lexicon_disk_usage = lexicon_.GetElementsSize(); if (lexicon_disk_usage != Filesystem::kBadFileSize) { storage_info.set_lite_index_lexicon_size(lexicon_disk_usage); } else { storage_info.set_lite_index_lexicon_size(-1); } return storage_info; } uint32_t LiteIndex::Seek(uint32_t term_id) { // Make searchable by sorting by hit buffer. uint32_t sort_len = header_->cur_size() - header_->searchable_end(); if (sort_len > 0) { IcingTimer timer; auto* array_start = hit_buffer_.GetMutableMem<TermIdHitPair::Value>(0, header_->cur_size()); TermIdHitPair::Value* sort_start = array_start + header_->searchable_end(); std::sort(sort_start, array_start + header_->cur_size()); // Now merge with previous region. Since the previous region is already // sorted and deduplicated, optimize the merge by skipping everything less // than the new region's smallest value. if (header_->searchable_end() > 0) { std::inplace_merge(array_start, array_start + header_->searchable_end(), array_start + header_->cur_size()); } ICING_VLOG(2) << IcingStringUtil::StringPrintf( "Lite index sort and merge %u into %u in %.3fms", sort_len, header_->searchable_end(), timer.Elapsed() * 1000); // Now the entire array is sorted. header_->set_searchable_end(header_->cur_size()); // Update crc in-line. UpdateChecksum(); } // Binary search for our term_id. Make sure we get the first // element. Using kBeginSortValue ensures this for the hit value. TermIdHitPair term_id_hit_pair( term_id, Hit(Hit::kMaxDocumentIdSortValue, Hit::kDefaultTermFrequency)); const TermIdHitPair::Value* array = hit_buffer_.array_cast<TermIdHitPair::Value>(); const TermIdHitPair::Value* ptr = std::lower_bound( array, array + header_->cur_size(), term_id_hit_pair.value()); return ptr - array; } } // namespace lib } // namespace icing
34.429787
80
0.691138
[ "vector" ]
fb2ed8e69f53088aa17a512e64984358781b79f4
15,395
cc
C++
src/search/sym/old/bhs.cc
whitemech/SymBA-star
34e9fdd1dc25f9af15c54478e39bbab422cac91a
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/search/sym/old/bhs.cc
whitemech/SymBA-star
34e9fdd1dc25f9af15c54478e39bbab422cac91a
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/search/sym/old/bhs.cc
whitemech/SymBA-star
34e9fdd1dc25f9af15c54478e39bbab422cac91a
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
#include "bhs.h" #include "sym_hnode.h" #include "../debug.h" #include "sym_exploration.h" #include "../option_parser.h" #include "../plugin.h" BHS::BHS(const Options &opts) : SymEngine(opts), maxStepTime (opts.get<int> ("max_step_time")), maxStepNodes (opts.get<int> ("max_step_nodes")), maxStepTimeEnd (opts.get<int> ("max_step_time_end")), maxStepNodesEnd (opts.get<int> ("max_step_nodes_end")), timeEnd (opts.get<double> ("time_end")), minAllotedTime (opts.get<int> ("min_alloted_time")), minAllotedNodes (opts.get<int> ("min_alloted_nodes")), ratioAllotedTime (opts.get<double>("ratio_alloted_time")), ratioAllotedNodes (opts.get<double>("ratio_alloted_nodes")), ratioAbstractTime (opts.get<double>("ratio_abstract_time")), ratioAbstractNodes (opts.get<double>("ratio_abstract_nodes")), ratioAfterRelaxTime (opts.get<double> ("ratio_after_relax_time")), ratioAfterRelaxNodes(opts.get<double> ("ratio_after_relax_nodes")), relaxDir (RelaxDirStrategy(opts.get_enum ("relax_dir"))), percentageUseful (opts.get<double>("p_useful"))/*, forceHeuristic (opts.get<bool> ("force_heuristic")), heuristicAbstract (opts.get<bool> ("heuristic_abstract"))*/{ } void BHS::initialize(){ print_options(); SymEngine::initialize(); //if(forceHeuristic){ //TODO: generate all the hierarchy //} } int BHS::step(){ SymExploration * exp = getExploration(); //TODO: consider alternative exploration // int stepTime = max<int>(min<long>(maxStepTime, exp->nextStepTime()) *stepTimeMult, // minStepTime); // int stepNodes = max<int>(min<long>(maxStepNodes, exp->nextStepNodes())*stepNodesMult, // minStepNodes); int stepTime = getAllotedTime(exp->nextStepTime()); int stepNodes = getAllotedNodes(exp->nextStepNodes()); exp->stepImage(stepTime, stepNodes); return stepReturn(); } SymExploration * BHS:: getExploration(){ set <SymExploration *> aux; set<SymExploration *> usefulExplorations; //Initialize with explorations of the original state space //TODO: Better way to get the exploration of the original state space set<SymExploration *> explorations = originalSearch->getExps(); DEBUG_MSG(cout << "Select exploration" << " total time: " << g_timer << endl;); while(!explorations.empty()){ SymExploration * best = getBestExploration(explorations, false); if(best){ return best; } //In this iteraton, no exploration was considered explorable DEBUG_MSG(cout << "#BHS: No explorable exploration in this iteration " << " total time: " << g_timer << endl;); //Store every useful exploration in this level usefulExplorations.insert (explorations.begin(), explorations.end()); for(auto exp : explorations){ exp->getUsefulExplorations(aux, percentageUseful); } //explorations.swap(aux); set<SymExploration *>().swap(explorations); for(auto exp : aux){ explorations.insert(exp); } set<SymExploration *>().swap(aux); DEBUG_MSG(cout << "#BHS: still we have " << explorations.size() << " explorations" << endl;); } DEBUG_MSG(cout << "#BHS: No valid exploration, add a new exploration" << endl;); //No valid exploration according to the parameters //We need to add a new exploration //Start with the most abstracted useful explorations for(auto it =usefulExplorations.rbegin(); it != usefulExplorations.rend(); ++it){ SymExploration * exp = *it; if(!exp->getBDExp()->isAbstractable()){ continue; } DEBUG_MSG(cout << "#BHS: Useful exploration: " << *exp << endl;); Dir dir = Dir::BIDIR; switch (relaxDir){ case RelaxDirStrategy::FW: dir = Dir::FW; break; case RelaxDirStrategy::BW: dir = Dir::BW; break; case RelaxDirStrategy::BIDIR: dir = Dir::BIDIR; break; case RelaxDirStrategy::SWITCHBACK: if(exp->isFW()){ dir = Dir::BW; }else{ dir = Dir::FW; } } cout << "Call to relax" << endl; if(saveExploration) { exp->getBDExp()->write("save/"); exit(-1); } if(!timeBegin){ timeBegin = g_timer(); } SymBDExp * newBDExp = xxx.relax(exp->getBDExp(), dir, getMaxAfterRelaxTime(), getMaxAfterRelaxNodes(), percentageUseful); cout << "Relax done." << newBDExp << endl; if(newBDExp){ cout << " >> Abstracted " << *newBDExp << " from " << *exp << " total time: " << g_timer << endl; explorations = newBDExp->getExps(); return getBestExploration(explorations, true); } } DEBUG_MSG(cout << "BHS: I cannot create a new exploration, just search the easiest" << endl;); //exit(-1); //No valid abstraction according to the parameters //Select the exploration estimated to be easiest among all useful ones return getBestExploration(usefulExplorations, true); } bool BHS::canExplore(const SymExploration & exp) { /* cout << "Exploration abstracted " << exp.isAbstracted() << " forward: " << exp.isFW() << endl; if(!exp.isAbstracted() && ((exp.isFW() && searchDir == Dir::BW) || (!exp.isFW() && searchDir == Dir::FW))){ cout << "Forbidden " << endl; return false; }*/ return /*exp.getBDExp()->isAbstractable() &&*/ exp.nextStepNodes() <= maxStepNodes && exp.nextStepTime() <= ((double)maxStepTime)*(exp.isAbstracted() ? ratioAbstractTime : 1); } bool BHS::isBetter(const SymExploration & exp, const SymExploration & exp2){ return exp.nextStepTime()/(exp.isAbstracted() ? ratioAbstractTime : 1) < exp2.nextStepTime()/(exp2.isAbstracted() ? ratioAbstractTime : 1); } SymExploration * BHS::getBestExploration(set<SymExploration *> & exps, bool canExploreAll){ SymExploration * best = nullptr; for (auto exp : exps){ DEBUG_MSG(cout << "#BHS: Best candidate: " << *exp << endl;); if(canExploreAll || canExplore(*exp)){ if(!best || isBetter(*exp, *best)){ best = exp; } } } if(best){ DEBUG_MSG(cout << "#BHS: Best selected: " << *best << endl;); } /* else cout << "#BHS: Selected nullptr" << endl;*/ return best; } static SymEngine *_parse(OptionParser &parser) { SymEngine::add_options_to_parser(parser); parser.add_option<int>("max_step_time", 5e3, "maximum time per step"); parser.add_option<int>("max_step_nodes", 1e5, "maximum nodes per step"); parser.add_option<int>("max_step_time_end", 60e3, "maximum time per step at the end of the execution"); parser.add_option<int>("max_step_nodes_end", 10e6, "maximum nodes per step at the end of the execution"); parser.add_option<double>("time_end", 1800, "number of seconds in the execution"); parser.add_option<double>("ratio_abstract_time", 0.5, "multiplier to decide alloted time for a step"); parser.add_option<double>("p_useful", 0.0, "Percentage of nodes that can potentially prune in the frontier for an heuristic to be useful"); parser.add_option<int>("min_alloted_time", 45e3, "minimum alloted time for an step"); parser.add_option<int>("min_alloted_nodes", 10e6, "minimum alloted nodes for an step"); parser.add_option<double>("ratio_alloted_time", 2.0, "ratioiplier to decide alloted time for a step"); parser.add_option<double>("ratio_alloted_nodes", 2.0, "multiplier to decide alloted nodes for a step"); parser.add_option<double>("ratio_abstract_time", 0.5, "multiplier to decide alloted time for a step"); parser.add_option<double>("ratio_abstract_nodes", 1, "multiplier to decide alloted nodes for a step"); parser.add_option<double>("ratio_after_relax_time", 0.1, "allowed time to accept the abstraction after relaxing the search, compared to the original state space"); parser.add_option<double>("ratio_after_relax_nodes", 0.5, "allowed nodes to accept the abstraction after relaxing the search, compared to the original state space"); vector<string> dirs = {"FW", "BW", "BIDIR"}; parser.add_enum_option("relax_dir", dirs, "BIDIR", "direction allowed to relax"); parser.add_option<bool>("force_heuristic", false, "forces to compute the heuristic value of every state in the frontier"); parser.add_option<bool>("heuristic_abstract", false, "If abstract state spaces are allowed to use others as heuristic"); Options opts = parser.parse(); SymEngine *policy = 0; if (!parser.dry_run()) { policy = new BHS(opts); } return policy; } static Plugin<SymEngine> _plugin("bhs", _parse); static SymEngine *_parse_bd(OptionParser &parser) { SymEngine::add_options_to_parser(parser); parser.add_option<int>("min_alloted_time", 60000, "minimum alloted time for an step"); parser.add_option<int>("min_alloted_nodes", 1000000, "minimum alloted nodes for an step"); parser.add_option<double>("ratio_alloted_time", 2.0, "multiplier to decide alloted time for a step"); parser.add_option<double>("ratio_alloted_nodes", 2.0, "multiplier to decide alloted nodes for a step"); Options opts = parser.parse(); opts.set<int>("max_step_time", numeric_limits<int>::max()); opts.set<int>("max_step_nodes", numeric_limits<int>::max()); opts.set<int>("max_step_time_end", numeric_limits<int>::max()); opts.set<int>("max_step_nodes_end", numeric_limits<int>::max()); opts.set<double>("time_end", 1800); opts.set<int>("max_after_relax_time", 0); opts.set<int>("max_after_relax_nodes", 0); opts.set<int>("max_relax_time", 0); opts.set<int>("max_relax_nodes", 0); opts.set<double>("ratio_abstract_nodes", 1.0); opts.set<double>("ratio_abstract_time", 1.0); opts.set<double>("ratio_after_relax_nodes", 1.0); opts.set<double>("ratio_after_relax_time", 1.0); opts.set("relax_dir", 2); opts.set<bool>("force_heuristic", false); opts.set<bool>("heuristic_abstract", false); opts.set<double>("p_useful", 0.0); SymEngine *policy = 0; if (!parser.dry_run()) { policy = new BHS(opts); } return policy; } static Plugin<SymEngine> _plugin_bd("sym_bd", _parse_bd); //static Plugin<SymEngine> _plugin("sw", _parse); // SymEngine * BHS::create_default(){ // Options opts; // SymEngine::set_default_options(opts); // opts.set<int>("max_step_time", numeric_limits<int>::max()); // opts.set<int>("max_step_nodes", numeric_limits<int>::max()); // opts.set<int>("max_step_time_end", numeric_limits<int>::max()); // opts.set<int>("max_step_nodes_end", numeric_limits<int>::max()); // opts.set<double>("time_end", 1800); // opts.set<double>("ratio_abstract_time", 0.5); // opts.set<double>("p_useful", 0.0); // opts.set<int>("min_alloted_time", 1000); // opts.set<int>("min_alloted_nodes", 100000); // opts.set<double>("ratio_alloted_time", 2.0); // opts.set<double>("ratio_alloted_nodes", 2.0); // opts.set<double>("ratio_abstract_nodes", 1.0); // opts.set<double>("ratio_abstract_time", 1.0); // opts.set<double>("ratio_after_relax_nodes", 1.0); // opts.set<double>("ratio_after_relax_time", 1.0); // opts.set<int>("relax_dir", 2); // opts.set<bool>("force_heuristic", false); // opts.set<bool>("heuristic_abstract", false); // return new BHS(opts); // } void BHS::print_options() const{ cout << "PSEL: BHS" << endl; cout << "Search dir: "; switch (searchDir){ case Dir::FW: cout << "fw"; break; case Dir::BW: cout << "bw"; break; case Dir::BIDIR: cout << "bd"; break; } cout << " relax dir: "; switch (relaxDir){ case RelaxDirStrategy::FW: cout << "fw"; break; case RelaxDirStrategy::BW: cout << "bw"; break; case RelaxDirStrategy::BIDIR: cout << "bd"; break; case RelaxDirStrategy::SWITCHBACK: cout << "sw"; break; } cout << endl; cout << "Max step time: " << maxStepTime << " => " << maxStepTimeEnd << "(first-" << timeEnd << ")"<< endl; cout << "Max step nodes: " << maxStepNodes << " => " << maxStepNodesEnd << "(first-" << timeEnd << ")"<< endl; cout << "Min alloted time: " << minAllotedTime << " nodes: " << minAllotedNodes << endl; cout << "Mult alloted time: " << ratioAllotedTime << " nodes: " << ratioAllotedNodes << endl; //cout << "Max after relax time: " << maxAfterRelaxTime << " nodes: " << maxAfterRelaxNodes << endl; cout << "Ratio abstract time: " << ratioAbstractTime << " nodes: " << ratioAbstractNodes << endl; cout << "Ratio after relax time: " << ratioAfterRelaxTime << " nodes: " << ratioAfterRelaxNodes << endl; cout << "Percentage useful: " << percentageUseful << endl; //cout << "Force heuristic: " << forceHeuristic << endl; // cout << "Heuristic abstract: " << heuristicAbstract << endl << endl; } static SymEngine *_parse_test(OptionParser &parser) { SymEngine::add_options_to_parser(parser); parser.add_option<int>("max_step_time", 1e3, "maximum time per step"); parser.add_option<int>("max_step_nodes", 1e3, "maximum nodes per step"); parser.add_option<double>("ratio_abstract_time", 0.5, "multiplier to decide alloted time for a step"); parser.add_option<double>("ratio_abstract_nodes", 1, "multiplier to decide alloted nodes for a step"); parser.add_option<double>("p_useful", 0.0, "Percentage of nodes that can potentially prune in the frontier for an heuristic to be useful"); parser.add_option<int>("min_alloted_time", 1e3, "minimum alloted time for an step"); parser.add_option<int>("min_alloted_nodes", 1e3, "minimum alloted nodes for an step"); parser.add_option<double>("ratio_alloted_time", 2.0, "multiplier to decide alloted time for a step"); parser.add_option<double>("ratio_alloted_nodes", 2.0, "multiplier to decide alloted nodes for a step"); /*parser.add_option<int>("max_relax_time", 10e3, "allowed time to relax the search"); parser.add_option<int>("max_relax_nodes", 5e6, "allowed nodes to relax the search");*/ parser.add_option<double>("ratio_after_relax_time", 0.1, "allowed time to accept the abstraction after relaxing the search, compared to the original state space"); parser.add_option<double>("ratio_after_relax_nodes", 0.5, "allowed nodes to accept the abstraction after relaxing the search, compared to the original state space"); vector<string> dirs = {"FW", "BW", "BIDIR", "SWITCHBACK"}; parser.add_enum_option("relax_dir", dirs, "BIDIR", "direction allowed to relax"); parser.add_option<bool>("perimeter_pdbs", true, "initializes explorations with the one being relaxed"); parser.add_option<bool>("force_heuristic", false, "forces to compute the heuristic value of every state in the frontier"); parser.add_option<bool>("heuristic_abstract", false, "If abstract state spaces are allowed to use others as heuristic"); Options opts = parser.parse(); SymEngine *policy = 0; if (!parser.dry_run()) { policy = new BHS(opts); } return policy; } static Plugin<SymEngine> _plugin_test("bhst", _parse_test); double BHS::getMaxStepTime() const { if(!timeBegin){ return maxStepTime; } double ratio_time = (g_timer() - timeBegin)/(timeEnd - timeBegin); return ratio_time*maxStepTime; } double BHS::getMaxStepNodes() const{ if(!timeBegin){ return maxStepNodes; } double ratio_nodes = (g_timer() - timeBegin)/(timeEnd - timeBegin); return ratio_nodes*maxStepNodes; }
35.390805
115
0.668529
[ "vector" ]
fb38942eb6cbf4ceeaf8c99b3971479d3af68052
1,502
cpp
C++
cuda_tests/graph_tests/capture_test.cpp
ermig1979/mmosbs
e009644c3e8294435e7909fc0b58372b6bb23a03
[ "MIT" ]
29
2019-03-12T04:34:34.000Z
2020-04-21T19:02:30.000Z
cuda_tests/graph_tests/capture_test.cpp
ermig1979/Examples
729cfc82a28d3390314fab338d637549018ef6e1
[ "MIT" ]
null
null
null
cuda_tests/graph_tests/capture_test.cpp
ermig1979/Examples
729cfc82a28d3390314fab338d637549018ef6e1
[ "MIT" ]
4
2020-08-25T04:32:17.000Z
2021-12-18T09:47:51.000Z
#include "tests.h" #include "nodes.h" #include "tensor.h" #include "utils.h" void capture_test() { std::cout << "Start capture_test:" << std::endl; const size_t N = 1, C = 1, H = 32, W = 32; shape_t shape = to_shape(N, C, H, W); cpu_tensor_t ca(shape), cb(shape), cc(shape), cd(shape); init_rand(ca, 0.0f, 1.0f); init_rand(cb, 0.0f, 1.0f); init_rand(cc, -2.0f, -1.0f); add_cpu((int)ca.size, ca.data, cb.data, cd.data); cudaStream_t stream; CHECK(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking)); gpu_tensor_t ga(shape, stream), gb(shape, stream), gc(shape, stream); cublasHandle_t cublasHandle; CHECK(cublasCreate(&cublasHandle)); CHECK(cublasSetStream(cublasHandle, stream)); CHECK(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal)); copy(ca, ga); copy(cb, gb); add_cublas(cublasHandle, (int)ga.size, ga.data, gb.data, gc.data); copy(gc, cc); cudaGraph_t graph; CHECK(cudaStreamEndCapture(stream, &graph)); print_graph_info(graph); cudaGraphExec_t graphExec; CHECK(cudaGraphInstantiate(&graphExec, graph, NULL, NULL, 0)); CHECK(cudaGraphLaunch(graphExec, stream)); CHECK(cudaStreamSynchronize(stream)); cublasDestroy(cublasHandle); CHECK(cudaStreamDestroy(stream)); if (!check(cd, cc, "cublas_test")) return; std::cout << "capture_test is finished." << std::endl; }
24.622951
77
0.636485
[ "shape" ]
fb3b05fbcba69d9c20d525bfc0a03e739fd53644
4,693
cpp
C++
src/ui/model/database.cpp
jtymburski/halodoom-launcher
3d0c20599c79eb1a953b9be88dd68b53378cb571
[ "MIT" ]
1
2021-09-19T22:43:28.000Z
2021-09-19T22:43:28.000Z
src/ui/model/database.cpp
jtymburski/halodoom-launcher
3d0c20599c79eb1a953b9be88dd68b53378cb571
[ "MIT" ]
null
null
null
src/ui/model/database.cpp
jtymburski/halodoom-launcher
3d0c20599c79eb1a953b9be88dd68b53378cb571
[ "MIT" ]
null
null
null
/** * @class Database * * User interface database of commonly accessed and re-used components. */ #include "ui/model/database.h" /* Constructor */ Database::Database() { buildMaps(); buildModes(); } /* Build all available maps and cache internally */ void Database::buildMaps() { maps.insert(Map::WAREHOUSE, Selection::Builder() .setDescription("Lethbridge Industrial once operated out of several small " "facilities like this for the design and manufacture of their " "experimental armor and weaponry. Most of these sites were " "decomissioned in favor of having the raw storage space") ->setImagePath(":/image/map/warehouse.jpg") ->setName("Warehouse") ->setType(Map::WAREHOUSE) ->build()); maps.insert(Map::SUBMERGED, Selection::Builder() .setDescription("Beneath the seas of Installation 02 lie a variety of mysterious " "Forerunner structures, echoes of memories long since past " "reverberate off of these monolithic walls, mingling with the " "ambience of deep") ->setImagePath(":/image/map/submerged.jpg") ->setName("Submerged") ->setType(Map::SUBMERGED) ->build()); maps.insert(Map::REBELLION, Selection::Builder() .setDescription("Amidst the outskirts of the holy city, in the hall of the " "ancestors, a great heresy brews...") ->setImagePath(":/image/map/rebellion.jpg") ->setName("Rebellion") ->setType(Map::REBELLION) ->build()); maps.insert(Map::FLOOD_GULCH, Selection::Builder() .setDescription("The former inhabitants of this installation are now one with " "it's structures. Eradication protocols were activated as " "intended, but clearly something went very wrong") ->setImagePath(":/image/map/floodgulch.jpg") ->setName("Flood Gulch") ->setType(Map::FLOOD_GULCH) ->build()); maps.insert(Map::GHOST_SHIP, Selection::Builder() .setDescription("In the emptiness of space, this fragment of the past floats " "alone, silent, unnerving") ->setImagePath(":/image/map/ghostship.jpg") ->setName("Ghost Ship") ->setType(Map::GHOST_SHIP) ->build()); } /* Build all available modes and cache internally */ void Database::buildModes() { modes.insert(Mode::SLAYER, Selection::Builder() .setDescription("Kill as many of your opponents as you can. The player with the " "most points wins.") ->setImagePath(":/image/mode/slayer.jpg") ->setName("Slayer") ->setType(Mode::SLAYER) ->build()); modes.insert(Mode::SWAT, Selection::Builder() .setDescription("Aim for the head! Slayer with no shield, radar, or ordinance.") ->setImagePath(":/image/mode/swat.jpg") ->setName("SWAT") ->setType(Mode::SWAT) ->build()); modes.insert(Mode::SWORDS, Selection::Builder() .setDescription("Slice and dice your way to victory!") ->setImagePath(":/image/mode/swords.jpg") ->setName("Swords") ->setType(Mode::SWORDS) ->build()); modes.insert(Mode::SHOTTY_SHIPERS, Selection::Builder() .setDescription("Long and short range only, cut out the middleman.") ->setImagePath(":/image/mode/snipers.jpg") ->setName("Shotty Snipers") ->setType(Mode::SHOTTY_SHIPERS) ->build()); modes.insert(Mode::FIESTA, Selection::Builder() .setDescription("You never know what you'll get!") ->setImagePath(":/image/mode/fiesta.jpg") ->setName("Fiesta") ->setType(Mode::FIESTA) ->build()); } /* Return a UI selection for a given map */ Selection Database::getMap(Map map_id) { return maps.find(map_id).value(); } /* Return all available map UI selections */ QList<Selection> Database::getMaps() { return maps.values(); } /* Return a UI selection for a given mode */ Selection Database::getMode(Mode mode_id) { return modes.find(mode_id).value(); } /* Return all available mode UI selections */ QList<Selection> Database::getModes() { return modes.values(); }
39.436975
96
0.567867
[ "model" ]
fb3c5dd58f57ecb1e183ddd9f8a77ee74e09c43c
15,522
cpp
C++
CastleDoctrine/gameSource/EditHousePage.cpp
PhilipLudington/CastleDoctrine
443f2b6b0215a6d71515c8887c99b4322965622e
[ "Unlicense" ]
1
2020-01-16T00:07:11.000Z
2020-01-16T00:07:11.000Z
CastleDoctrine/gameSource/EditHousePage.cpp
PhilipLudington/CastleDoctrine
443f2b6b0215a6d71515c8887c99b4322965622e
[ "Unlicense" ]
null
null
null
CastleDoctrine/gameSource/EditHousePage.cpp
PhilipLudington/CastleDoctrine
443f2b6b0215a6d71515c8887c99b4322965622e
[ "Unlicense" ]
2
2019-09-17T12:08:20.000Z
2020-09-26T00:54:48.000Z
#include "EditHousePage.h" #include "message.h" #include "balance.h" #include "minorGems/game/Font.h" #include "minorGems/game/game.h" #include "minorGems/game/drawUtils.h" #include "minorGems/util/stringUtils.h" #include "minorGems/util/SettingsManager.h" extern Font *mainFont; extern int diffHighlightsOff; EditHousePage::EditHousePage() : mStartHouseMap( NULL ), mVaultContents( NULL ), mBackpackContents( NULL ), mPriceList( NULL ), // starts empty mPurchaseList( stringDuplicate( "#" ) ), mSellList( stringDuplicate( "#" ) ), mObjectPicker( 8, 5 ), mGridDisplay( 0, 0, &mObjectPicker ), mDoneButton( mainFont, 8, -5, translate( "doneEdit" ) ), mBackpackButton( mainFont, 8, -3, translate( "loadBackpack" ) ), mAuctionButton( mainFont, -8, -5, translate( "openAuctionList" ) ), mUndoButton( mainFont, 8, -0.5, translate( "undo" ), 'z', 'Z' ), mJumpToTapesButton( mainFont, 8, -1.75, translate( "jumpToTapes" ) ), mSuicideButton( mainFont, 8, -0.5, translate( "suicide" ) ), mSuicideConfirmCheckbox( 8, .375, 1/16.0 ), mDiffHighlightToggleButton( "diffHighlightsOn.tga", "diffHighlightsOff.tga", 8, -1.75, 1/16.0 ), mEyedropperStatus( 6.5, 5, 1/16.0 ), mBlockSuicideButton( false ), mGallery( mainFont, -8, 0 ), mNumberOfTapes( 0 ), mJumpToTapes( false ), mDone( false ), mDead( false ) { addComponent( &mDoneButton ); addComponent( &mJumpToTapesButton ); addComponent( &mSuicideButton ); addComponent( &mSuicideConfirmCheckbox ); addComponent( &mBackpackButton ); addComponent( &mAuctionButton ); addComponent( &mUndoButton ); addComponent( &mGridDisplay ); addComponent( &mDiffHighlightToggleButton ); addComponent( &mEyedropperStatus ); addComponent( &mObjectPicker ); mDoneButton.setMouseOverTip( "" ); mUndoButton.setMouseOverTip( translate( "undoTip" ) ); mBackpackButton.setMouseOverTip( translate( "loadBackpackTip" ) ); mAuctionButton.setMouseOverTip( translate( "openAuctionListTip" ) ); mJumpToTapesButton.setMouseOverTip( translate( "jumpToTapesTip" ) ); mSuicideButton.setMouseOverTip( translate( "unconfirmedSuicideTip" ) ); mSuicideConfirmCheckbox.setMouseOverTip( translate( "suicideConfirmTip" ) ); mSuicideConfirmCheckbox.setMouseOverTipB( translate( "suicideConfirmTip" ) ); mDoneButton.addActionListener( this ); mJumpToTapesButton.addActionListener( this ); mSuicideButton.addActionListener( this ); mSuicideConfirmCheckbox.addActionListener( this ); mBackpackButton.addActionListener( this ); mAuctionButton.addActionListener( this ); mUndoButton.addActionListener( this ); mUndoButton.setVisible( false ); mGridDisplay.addActionListener( this ); mObjectPicker.addActionListener( this ); mDiffHighlightToggleButton.addActionListener( this ); mDiffHighlightToggleButton.setMouseOverTip( translate( "diffHighlightsOff" ) ); mDiffHighlightToggleButton.setMouseOverTipB( translate( "diffHighlightsOn" ) ); addComponent( &mGallery ); } EditHousePage::~EditHousePage() { if( mStartHouseMap != NULL ) { delete [] mStartHouseMap; } if( mVaultContents != NULL ) { delete [] mVaultContents; } if( mBackpackContents != NULL ) { delete [] mBackpackContents; } if( mPriceList != NULL ) { delete [] mPriceList; } if( mPurchaseList != NULL ) { delete [] mPurchaseList; } if( mSellList != NULL ) { delete [] mSellList; } } void EditHousePage::setWifeName( const char *inWifeName ) { mGridDisplay.setWifeName( inWifeName ); mObjectPicker.setWifeName( inWifeName ); } void EditHousePage::setSonName( const char *inSonName ) { mGridDisplay.setSonName( inSonName ); } void EditHousePage::setDaughterName( const char *inDaughterName ) { mGridDisplay.setDaughterName( inDaughterName ); } char *EditHousePage::getWifeName() { return mGridDisplay.getWifeName(); } char *EditHousePage::getSonName() { return mGridDisplay.getSonName(); } char *EditHousePage::getDaughterName() { return mGridDisplay.getDaughterName(); } void EditHousePage::setHouseMap( const char *inHouseMap ) { if( mStartHouseMap != NULL ) { delete [] mStartHouseMap; } mStartHouseMap = stringDuplicate( inHouseMap ); mGridDisplay.setHouseMap( inHouseMap ); mUndoButton.setVisible( mGridDisplay.canUndo() ); mDoneButton.setVisible( mGridDisplay.areMandatoriesPlaced() && mGridDisplay.doAllFamilyObjectsHaveExitPath() ); mChangesCost = 0; mDiffHighlightToggleButton.setVisible( false ); mMapStartedOutEmpty = mGridDisplay.getMapStartedOutEmpty(); mBackpackOrVaultChanged = false; } char *EditHousePage::getHouseMap() { return mGridDisplay.getHouseMap(); } void EditHousePage::setVaultContents( const char *inVaultContents ) { if( mVaultContents != NULL ) { delete [] mVaultContents; } mVaultContents = stringDuplicate( inVaultContents ); } char *EditHousePage::getVaultContents() { return stringDuplicate( mVaultContents ); } void EditHousePage::setBackpackContents( const char *inBackpackContents ) { if( mBackpackContents != NULL ) { delete [] mBackpackContents; } mBackpackContents = stringDuplicate( inBackpackContents ); } char *EditHousePage::getBackpackContents() { return stringDuplicate( mBackpackContents ); } void EditHousePage::setGalleryContents( const char *inGalleryContents ) { mGallery.setGalleryContents( inGalleryContents ); } void EditHousePage::setNumberOfTapes( int inNumber ) { mNumberOfTapes = inNumber; } char *EditHousePage::getGalleryContents() { return mGallery.getGalleryContents(); } char *EditHousePage::getEditList() { return mGridDisplay.getEditList(); } char *EditHousePage::getFamilyExitPaths() { return mGridDisplay.getFamilyExitPaths(); } char EditHousePage::getWifeLiving() { return mGridDisplay.getWifeLiving(); } char *EditHousePage::getPurchaseList() { return stringDuplicate( mPurchaseList ); } void EditHousePage::setPurchaseList( const char *inPurchaseList ) { if( mPurchaseList != NULL ) { delete [] mPurchaseList; } mPurchaseList = stringDuplicate( inPurchaseList ); } char *EditHousePage::getSellList() { return stringDuplicate( mSellList ); } void EditHousePage::setSellList( const char *inSellList ) { if( mSellList != NULL ) { delete [] mSellList; } mSellList = stringDuplicate( inSellList ); } void EditHousePage::setPriceList( const char *inPriceList ) { if( mPriceList != NULL ) { delete [] mPriceList; } mPriceList = stringDuplicate( inPriceList ); mObjectPicker.setPriceList( inPriceList ); } char *EditHousePage::getPriceList() { return stringDuplicate( mPriceList ); } void EditHousePage::setLootValue( int inLootValue ) { mLootValue = inLootValue; mBlockSuicideButton = false; checkIfPlacementAllowed(); } void EditHousePage::setMustSelfTest( char inMustSelfTest ) { mMustSelfTest = inMustSelfTest; // if house damaged and needs a self test, don't allow auctions // (server blocks auction activities anyway in this case) mAuctionButton.setVisible( !mMustSelfTest ); } void EditHousePage::checkIfPlacementAllowed() { // always allow placement with new accounting method mGridDisplay.allowPlacement( true ); // can't afford to place anything, house not edited yet // allow suicide mSuicideButton.setVisible( ! mBlockSuicideButton && ! mUndoButton.isVisible() && mLootValue == 0 ); if( mSuicideButton.isVisible() ) { mSuicideConfirmCheckbox.setVisible( true ); mSuicideConfirmCheckbox.setToggled( false ); mSuicideButton.setMouseOverTip( translate( "unconfirmedSuicideTip" ) ); } else { mSuicideConfirmCheckbox.setVisible( false ); } checkIfTapesButtonVisible(); } void EditHousePage::checkIfDoneButtonVisible() { // can't click DONE if house has no goal set // or family blocked // or spent more than we have on changes to house mDoneButton.setVisible( mGridDisplay.areMandatoriesPlaced() && mGridDisplay.doAllFamilyObjectsHaveExitPath() && mLootValue >= mChangesCost ); } char EditHousePage::houseMapChanged() { char *editList = getEditList(); int comp = strcmp( editList, "" ); delete [] editList; if( comp != 0 ) { // some edits to report, whether or not map was actually changed // by edits, count it as changed return true; } if( mStartHouseMap == NULL || mMustSelfTest ) { return true; } char *newMap = mGridDisplay.getHouseMap(); comp = strcmp( newMap, mStartHouseMap ); if( comp != 0 ) { printf( "House maps differ. Old:\n%s\n\nNew:\n%s\n\n", mStartHouseMap, newMap ); } delete [] newMap; if( comp == 0 ) { return false; } return true; } void EditHousePage::recomputeChangeCost() { mChangesCost = 0; SimpleVector<GridDiffRecord> diffList = mGridDisplay.getEditDiff(); int numRecords = diffList.size(); for( int i=0; i<numRecords; i++ ) { GridDiffRecord *r = diffList.getElement( i ); mChangesCost += r->placementCount * mObjectPicker.getPrice( r->objectID ); } mGridDisplay.setTouchedHighlightRed( mChangesCost > mLootValue ); mDiffHighlightToggleButton.setVisible( !mMapStartedOutEmpty && mChangesCost > 0 ); } void EditHousePage::actionPerformed( GUIComponent *inTarget ) { if( inTarget == &mSuicideConfirmCheckbox ) { if( mSuicideConfirmCheckbox.getToggled() ) { mSuicideButton.setMouseOverTip( translate( "suicideTip" ) ); } else { mSuicideButton.setMouseOverTip( translate( "unconfirmedSuicideTip" ) ); } } else if( inTarget == &mGridDisplay ) { int cost = mObjectPicker.getPrice( mGridDisplay.getLastPlacedObject() ); mUndoButton.setVisible( mGridDisplay.canUndo() ); if( cost != -1 && ! mGridDisplay.wasLastActionPlayerMotion() ) { mObjectPicker.useSelectedObject(); checkIfPlacementAllowed(); } if( mGridDisplay.didLastActionChangeDiff() ) { recomputeChangeCost(); } checkIfDoneButtonVisible(); // change to house map actionHappened(); } else if( inTarget == &mDiffHighlightToggleButton ) { diffHighlightsOff = mDiffHighlightToggleButton.getToggled(); SettingsManager::setSetting( "diffHighlightsOff", diffHighlightsOff ); mGridDisplay.toggleTouchedHighlights( ! diffHighlightsOff ); } else if( inTarget == &mBackpackButton ) { mShowLoadBackpack = true; } else if( inTarget == &mAuctionButton ) { mShowAuctions = true; } else if( inTarget == &mJumpToTapesButton ) { mJumpToTapes = true; } else if( inTarget == &mDoneButton ) { // Reset any states // that were toggled by the last robber. // We show the house-as-robbed view to the owner once, // until they perform their first complete edit, and THEN toggle // everything back. mGridDisplay.resetToggledStates( 0 ); mDone = true; } else if( inTarget == &mSuicideButton ) { if( mSuicideConfirmCheckbox.isVisible() && ! mSuicideConfirmCheckbox.getToggled() ) { return; } mGridDisplay.resetToggledStates( 0 ); mDead = true; mDone = true; } else if( inTarget == &mObjectPicker ) { if( mObjectPicker.shouldShowGridView() ) { mShowGridObjectPicker = true; } else { // change in picked object checkIfPlacementAllowed(); } } else if( inTarget == &mUndoButton ) { mBlockSuicideButton = true; mGridDisplay.undo(); mUndoButton.setVisible( mGridDisplay.canUndo() ); checkIfPlacementAllowed(); recomputeChangeCost(); checkIfDoneButtonVisible(); // change to house map actionHappened(); } } void EditHousePage::makeActive( char inFresh ) { LiveHousePage::makeActive( inFresh ); if( !inFresh ) { return; } mGridDisplay.clearMovementKeyHolds(); mJumpToTapes = false; mDone = false; mDead = false; mShowLoadBackpack = false; mShowAuctions = false; mShowGridObjectPicker = false; checkIfDoneButtonVisible(); checkIfTapesButtonVisible(); blockQuitting( areRequestsPending() ); mDiffHighlightToggleButton.setToggled( diffHighlightsOff ); mGridDisplay.toggleTouchedHighlights( ! mMapStartedOutEmpty && ! diffHighlightsOff ); } void EditHousePage::step() { LiveHousePage::step(); checkIfTapesButtonVisible(); blockQuitting( areRequestsPending() ); } void EditHousePage::checkIfTapesButtonVisible() { // can jump to tapes as long as no editing done yet and no purchase/sale // done yet (so nothing will be lost when we abandon the house edit) // AND no background requests to server are pending mJumpToTapesButton.setVisible( ! areRequestsPending() && mNumberOfTapes > 0 && ! mUndoButton.isVisible() && ! mBackpackOrVaultChanged ); } extern Font *numbersFontFixed; void EditHousePage::drawUnderComponents( doublePair inViewCenter, double inViewSize ) { drawBalance( mLootValue, mChangesCost ); } void EditHousePage::draw( doublePair inViewCenter, double inViewSize ) { doublePair labelPos = { 0, 7 }; drawMessage( "editDescription", labelPos, false ); if( ! mGridDisplay.doAllFamilyObjectsHaveExitPath() ) { // explanation for why Done button hidden doublePair buttonPos = mDoneButton.getPosition(); buttonPos.y += 0.5; drawMessage( "familyExitMessage", buttonPos, true ); } } void EditHousePage::keyDown( unsigned char inASCII ) { if( inASCII == '+' ) { mGridDisplay.saveWholeMapImage(); } }
24.599049
79
0.615449
[ "object" ]
fb438f1b5b3e2d2784e90411767934ba38cce47e
6,683
cpp
C++
Win32xx/samples/FastGDI/src/View.cpp
mufunyo/VisionRGBApp
c09092770032150083eda171a22b1a3ef0914dab
[ "Unlicense" ]
2
2021-03-25T04:19:22.000Z
2021-05-03T03:23:30.000Z
Win32xx/samples/FastGDI/src/View.cpp
mufunyo/VisionRGBApp
c09092770032150083eda171a22b1a3ef0914dab
[ "Unlicense" ]
null
null
null
Win32xx/samples/FastGDI/src/View.cpp
mufunyo/VisionRGBApp
c09092770032150083eda171a22b1a3ef0914dab
[ "Unlicense" ]
1
2020-12-28T08:53:42.000Z
2020-12-28T08:53:42.000Z
////////////////////////////////////////////// // View.cpp // Definitions for the CView class #include "stdafx.h" #include "view.h" #include "FastGDIApp.h" #include "resource.h" CView::CView() { } CView::~CView() { } BOOL CView::LoadFileImage(LPCTSTR filename) { // Only bitmap images (bmp files) can be loaded m_image.DeleteObject(); CSize totalSize; if (filename) { if (!m_image.LoadImage(filename, LR_LOADFROMFILE)) { CString str("Failed to load file: "); str += filename; MessageBox(str, _T("File Load Error"), MB_ICONWARNING); } } if (m_image.GetHandle()) { // Set the image scroll size totalSize.cx = GetImageRect().Width(); totalSize.cy = GetImageRect().Height(); } else { // Disable scrolling totalSize = CSize(0, 0); Invalidate(); } SetScrollSizes(totalSize); return (m_image.GetHandle()!= 0); } // Select the printer, and call QuickPrint. void CView::Print(LPCTSTR docName) { CPrintDialog printDlg; // Bring up a dialog to choose the printer if (printDlg.DoModal(*this) == IDOK) // throws exception if there is no default printer { QuickPrint(docName); } } void CView::PrintPage(CDC& dc, UINT) { if (m_image.GetHandle() != 0) { BITMAP bitmap = m_image.GetBitmapData(); int bmWidth = bitmap.bmWidth; int bmHeight = bitmap.bmHeight; // Get the device context of the default or currently chosen printer CPrintDialog printDlg; CDC printDC = printDlg.GetPrinterDC(); CClientDC viewDC(*this); double viewPixelsX = double(viewDC.GetDeviceCaps(LOGPIXELSX)); double viewPixelsY = double(viewDC.GetDeviceCaps(LOGPIXELSY)); double printPixelsX = double(printDC.GetDeviceCaps(LOGPIXELSX)); double printPixelsY = double(printDC.GetDeviceCaps(LOGPIXELSY)); double scaleX = printPixelsX / viewPixelsX; double scaleY = printPixelsY / viewPixelsY; int scaledWidth = int(bmWidth * scaleX); int scaledHeight = int(bmHeight * scaleY); // Now we extract the Device Independent data from the Device Dependent Bitmap(DDB) CBitmapInfoPtr pbmi(m_image); CMemDC memDC(viewDC); int imageBytes = (((bmWidth * 32 + 31) & ~31) >> 3) * bmHeight; std::vector<byte> byteArray(imageBytes, 0); byte* pByteArray = &byteArray.front(); memDC.GetDIBits(m_image, 0, bmHeight, pByteArray, pbmi, DIB_RGB_COLORS); // Copy (stretch) the DI bits to the specified dc. dc.StretchDIBits(0, 0, scaledWidth, scaledHeight, 0, 0, bmWidth, bmHeight, pByteArray, pbmi, DIB_RGB_COLORS, SRCCOPY); } } void CView::QuickPrint(LPCTSTR docName) { // Create a DOCINFO structure. DOCINFO di; memset(&di, 0, sizeof(DOCINFO)); di.cbSize = sizeof(DOCINFO); di.lpszDocName = docName; CPrintDialog printDlg; CDC printDC = printDlg.GetPrinterDC(); printDC.StartDoc(&di); printDC.StartPage(); PrintPage(printDC); printDC.EndPage(); printDC.EndDoc(); } BOOL CView::SaveFileImage(LPCTSTR fileName) { CFile file; BOOL bResult = FALSE; try { file.Open(fileName, OPEN_ALWAYS); // Create our LPBITMAPINFO object CBitmapInfoPtr pbmi(m_image); // Create the reference DC for GetDIBits to use CMemDC memDC(NULL); // Use GetDIBits to create a DIB from our DDB, and extract the colour data memDC.GetDIBits(m_image, 0, pbmi->bmiHeader.biHeight, NULL, pbmi, DIB_RGB_COLORS); std::vector<byte> byteArray(pbmi->bmiHeader.biSizeImage, 0); byte* pByteArray = &byteArray.front(); memDC.GetDIBits(m_image, 0, pbmi->bmiHeader.biHeight, pByteArray, pbmi, DIB_RGB_COLORS); LPBITMAPINFOHEADER pbmih = &pbmi->bmiHeader; BITMAPFILEHEADER hdr; ZeroMemory(&hdr, sizeof(BITMAPFILEHEADER)); hdr.bfType = 0x4d42; // 0x42 = "B" 0x4d = "M" hdr.bfSize = static_cast<DWORD>(sizeof(BITMAPFILEHEADER) + pbmih->biSize + pbmih->biClrUsed * sizeof(RGBQUAD) + pbmih->biSizeImage); hdr.bfOffBits = static_cast<DWORD>(sizeof(BITMAPFILEHEADER) + pbmih->biSize + pbmih->biClrUsed * sizeof (RGBQUAD)); file.Write(&hdr, sizeof(BITMAPFILEHEADER)); file.Write(pbmih, sizeof(BITMAPINFOHEADER) + pbmih->biClrUsed * sizeof (RGBQUAD)); file.Write(pByteArray, pbmih->biSizeImage); bResult = TRUE; } catch (const CFileException& e) { CString str = CString("Failed to save file: ") + e.GetFilePath(); MessageBox(str, AtoT(e.what()), MB_OK); bResult = FALSE; } return bResult; } CRect CView::GetImageRect() { BITMAP bm = m_image.GetBitmapData(); CRect rc; rc.right = bm.bmWidth; rc.bottom = bm.bmHeight; return rc; } void CView::OnDraw(CDC& dc) { if (m_image.GetHandle()) { dc.SelectObject(m_image); } else { // There is no image, so display a hint to get one CRect rc = GetClientRect(); dc.DrawText(_T("Use the Menu or ToolBar to open a Bitmap File"), -1, rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE); } } LRESULT CView::OnDropFiles(UINT msg, WPARAM wparam, LPARAM lparam) { UNREFERENCED_PARAMETER(msg); UNREFERENCED_PARAMETER(lparam); HDROP hDrop = (HDROP)wparam; UINT length = DragQueryFile(hDrop, 0, 0, 0); if (length > 0) { CString fileName; DragQueryFile(hDrop, 0, fileName.GetBuffer(length), length+1); fileName.ReleaseBuffer(); DragFinish(hDrop); CMainFrame& Frame = GetFrameApp()->GetMainFrame(); if ( !Frame.LoadFile(fileName) ) { TRACE ("Failed to load "); TRACE(fileName); TRACE("\n"); SetScrollSizes(CSize(0,0)); Invalidate(); } } return 0; } // OnInitialUpdate is called after the window is created. void CView::OnInitialUpdate() { TRACE("View window created\n"); // Support Drag and Drop on this window DragAcceptFiles(TRUE); } void CView::PreCreate(CREATESTRUCT& cs) { // Set the Window Class name cs.lpszClass = _T("View"); cs.style = WS_CHILD | WS_HSCROLL | WS_VSCROLL ; // Set the extended style cs.dwExStyle = WS_EX_CLIENTEDGE; } LRESULT CView::WndProc(UINT msg, WPARAM wparam, LPARAM lparam) { switch (msg) { case WM_DROPFILES: return OnDropFiles(msg, wparam, lparam); } // Pass unhandled messages on for default processing return WndProcDefault(msg, wparam, lparam); }
26.625498
139
0.626365
[ "object", "vector" ]
fb52447f01b58e31160c96cff536887607246d5b
3,699
cpp
C++
library/tree/lcaSchieberVishkin.cpp
bluedawnstar/algorithm_library
4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6
[ "Unlicense" ]
40
2017-11-26T05:29:18.000Z
2020-11-13T00:29:26.000Z
library/tree/lcaSchieberVishkin.cpp
bluedawnstar/algorithm_library
4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6
[ "Unlicense" ]
101
2019-02-09T06:06:09.000Z
2021-12-25T16:55:37.000Z
library/tree/lcaSchieberVishkin.cpp
bluedawnstar/algorithm_library
4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6
[ "Unlicense" ]
6
2017-01-03T14:17:58.000Z
2021-01-22T10:37:04.000Z
#include <cmath> #include <queue> #include <vector> #include <algorithm> using namespace std; #include "lcaSchieberVishkin.h" /////////// For Testing /////////////////////////////////////////////////////// #include <time.h> #include <cassert> #include <string> #include <numeric> #include <iostream> #include "../common/iostreamhelper.h" #include "../common/profile.h" #include "../common/rand.h" #include "treeBasic.h" #define MAXN 10000 // TODO: modify the maximum number of nodes #define LOGN 15 // TODO: modify LCA table size (log2(MAXN)) static Tree makeLcaTree() { Tree tree(MAXN, LOGN); tree.addEdge(0, 1); tree.addEdge(0, 2); int i, p = 1; for (i = 3; i < tree.N / 4; i++) { tree.addEdge(p, i); p = i; } p = 1; for (; i < tree.N * 2 / 4; i++) { tree.addEdge(p, i); p = i; } p = 2; for (; i < tree.N * 3 / 4; i++) { tree.addEdge(p, i); p = i; } p = 2; for (; i < tree.N; i++) { tree.addEdge(p, i); p = i; } return tree; } void testLcaShieberVishkin() { return; //TODO: if you want to test, make this line a comment. cout << "-- LCA with Shieber Vishkin algorithm ------------------------------" << endl; { auto tree = makeLcaTree(); // make a test tree tree.build(0); PROFILE_START(0); int errCnt = 0; for (int i = 0; i < 100000; i++) { int u = RandInt32::get() % tree.N; int v = RandInt32::get() % tree.N; int lca = tree.findLCA(u, v); int lcaAns; if (u == 0 || v == 0) { lcaAns = 0; } else if ((u != 2 && u < tree.N / 2) != (v != 2 && v < tree.N / 2)) { lcaAns = 0; } else if (u != 2 && u < tree.N / 2) { if ((u >= tree.N / 4) != (v >= tree.N / 4)) lcaAns = 1; else lcaAns = min(u, v); } else { if ((u >= tree.N * 3 / 4) != (v >= tree.N * 3 / 4)) lcaAns = 2; else lcaAns = min(u, v); } if (lca != lcaAns) { cout << "mismatch : LCA(" << u << ", " << v << ") = " << lca << " (!= " << lcaAns << ")" << endl; errCnt++; } assert(lca == lcaAns); } PROFILE_STOP(0); } { auto tree = makeLcaTree(); // make a test tree LcaSchieberVishkin svLCA(tree.edges, 0); PROFILE_START(1); int errCnt = 0; for (int i = 0; i < 100000; i++) { int u = RandInt32::get() % tree.N; int v = RandInt32::get() % tree.N; int lca = svLCA.lca(u, v); int lcaAns; if (u == 0 || v == 0) { lcaAns = 0; } else if ((u != 2 && u < tree.N / 2) != (v != 2 && v < tree.N / 2)) { lcaAns = 0; } else if (u != 2 && u < tree.N / 2) { if ((u >= tree.N / 4) != (v >= tree.N / 4)) lcaAns = 1; else lcaAns = min(u, v); } else { if ((u >= tree.N * 3 / 4) != (v >= tree.N * 3 / 4)) lcaAns = 2; else lcaAns = min(u, v); } if (lca != lcaAns) { cout << "mismatch : LCA(" << u << ", " << v << ") = " << lca << " (!= " << lcaAns << ")" << endl; errCnt++; } assert(lca == lcaAns); } PROFILE_STOP(1); } cout << "OK!" << endl; }
27.4
113
0.382265
[ "vector" ]
fb5393a5407abe78773914ea9fdb1e775379ceee
14,679
cpp
C++
src/graphics/gui/font.cpp
tedle/blonstech
f5a221d1e08b408ccffcaee7f982ba00b497f4e0
[ "MIT" ]
3
2020-09-06T15:33:00.000Z
2021-06-28T08:37:14.000Z
src/graphics/gui/font.cpp
tedle/blonstech
f5a221d1e08b408ccffcaee7f982ba00b497f4e0
[ "MIT" ]
null
null
null
src/graphics/gui/font.cpp
tedle/blonstech
f5a221d1e08b408ccffcaee7f982ba00b497f4e0
[ "MIT" ]
1
2021-06-28T08:37:17.000Z
2021-06-28T08:37:17.000Z
//////////////////////////////////////////////////////////////////////////////// // blonstech // Copyright(c) 2017 Dominic Bowden // // 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 <blons/graphics/gui/font.h> // Includes #include <algorithm> #include <FreeType2/include/ft2build.h> #include FT_FREETYPE_H // Public Includes #include <blons/graphics/render/renderer.h> namespace blons { namespace gui { struct Font::Glyph { // Needed for vector.resize() Glyph() : width(0), height(0), tex_offset(0), x_offset(0), y_offset(0), x_advance(0) {} // This constructor's really just for refactoring code into smaller functions Glyph(unsigned char letter, FT_Face font_face, units::pixel texture_offset); // 8-bit monochrome bitmap of character data std::vector<unsigned char> pixels; // Width and height of bitmap units::pixel width, height; // Offset from origin in fontsheet texture units::pixel tex_offset; // Offset from cursor,line respectively units::pixel x_offset, y_offset; // Offset from previously rendered character units::pixel x_advance; }; Font::Glyph::Glyph(unsigned char letter, FT_Face font_face, units::pixel texture_offset) { unsigned int glyph_index = FT_Get_Char_Index(font_face, letter); if (!glyph_index) { throw "Couldn't locate character"; } if (FT_Load_Glyph(font_face, glyph_index, FT_LOAD_TARGET_NORMAL | FT_LOAD_FORCE_AUTOHINT) != 0) { throw "Couldn't load character"; } if (FT_Render_Glyph(font_face->glyph, FT_RENDER_MODE_NORMAL) != 0) { throw "Couldn't render character"; } if (font_face->glyph->format != FT_GLYPH_FORMAT_BITMAP || font_face->glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY) { throw "Incorrent format of character"; } FT_Bitmap bitmap = font_face->glyph->bitmap; width = bitmap.width; height = bitmap.rows; tex_offset = texture_offset; x_advance = font_face->glyph->advance.x / 64; x_offset = font_face->glyph->metrics.horiBearingX / 64; y_offset = font_face->glyph->metrics.horiBearingY / 64 - height; for (units::pixel y = 0; y < height; y++) { for (units::pixel x = 0; x < width; x++) { pixels.push_back(*(bitmap.buffer++)); } // Accounts for bitmap padding bitmap.buffer += (bitmap.pitch - bitmap.width); } } Font::Font(std::string font_filename, units::pixel pixel_size) { fontsheet_ = nullptr; current_batch_.reset(new BatchInstance); letter_height_ = 0; pixel_size_ = pixel_size; // std::map would be a lot cleaner than a vector, but we need very fast access :) size_t largest_char = *std::max_element(kAvailableCharacters.begin(), kAvailableCharacters.end()) + 1; charset_.resize(largest_char); FT_Library library; FT_Face face; if (FT_Init_FreeType(&library) != 0) { throw "Couldn't initialize font library"; } if (FT_New_Face(library, font_filename.c_str(), 0, &face) != 0) { throw "Couldn't load font file"; } if (FT_Set_Pixel_Sizes(face, 0, pixel_size_) != 0) { throw "Couldn't set pixel size"; } line_height_ = face->size->metrics.height / 64; // Used to find glyph in texture fontsheet later units::pixel tex_width = 0; // Used to determine how tall font texture must be units::pixel tex_height = 0; // For every drawable character, get a bitmap rendering of the letter and store it for (const auto& c : kAvailableCharacters) { Glyph g(c, face, tex_width); charset_[c] = g; tex_width += g.width; // Funky parentheses to appease the lord of windows macros tex_height = (std::max)(g.height, tex_height); if (c >= 'A' && c <= 'Z' && c != 'J' && c != 'Q') { letter_height_ = (std::max)(g.height, letter_height_); } } // Converge all our pixel data into a handy dandy struct PixelData font; // Generate a single texture containing every character // Zero the memory since not all glyphs have the same height font.pixels.resize(tex_width * tex_height, 0); // We have to do this as a second pass because we dont know the fontsheet width until // all of the glyphs have been rendered and stored for (const auto& glyph : charset_) { for (unsigned int i = 0; i < glyph.pixels.size(); i++) { units::pixel x = glyph.tex_offset + i % glyph.width; units::pixel y = i / glyph.width; font.pixels.data()[x + y * tex_width] = glyph.pixels[i]; } } font.width = tex_width; font.height = tex_height; // Single channel monochrome font.type.format = TextureType::A8; font.type.filter = TextureType::NEAREST; font.type.wrap = TextureType::CLAMP; // No compression or mipmaps font.type.compression = TextureType::RAW; // Make it a sprite! fontsheet_.reset(new Sprite(font)); if (FT_Done_FreeType(library) != 0) { throw "uh oh"; } return; } // Defined in .cpp to allow for destruction of glyphs Font::~Font() { } const Font::BatchInstance* Font::BuildBatchInstance(unsigned char letter, units::subpixel x, units::subpixel y, Box crop) { // Pointer to avoid expensive copying const Glyph* g; // In case someone tries to render a string using chars we dont have try { g = &charset_[letter]; } catch (...) { return nullptr; } // How far to advance cursor for next letter advance_ = g->x_advance; // Quad dimensions Box s(x + units::pixel_to_subpixel(g->x_offset), y - units::pixel_to_subpixel(g->y_offset + g->height), units::pixel_to_subpixel(g->width), units::pixel_to_subpixel(g->height)); // Texture dimensions Box t(g->tex_offset, 0, g->width, g->height); // TODO: Refactor these? Kind of annoying since they access diff struct members if (crop.w != 0) { // Is this letter completely cropped? if (s.x + s.w <= crop.x || s.x >= crop.x + crop.w) { return nullptr; } units::subpixel crop_left = crop.x - s.x; units::subpixel crop_right = (s.x + s.w) - (crop.x + crop.w); units::subpixel crop_max = std::max(crop_left, crop_right); s.x = std::max(s.x, crop.x); s.w = s.w - std::max(0.0f, crop_max); t.x = t.x + std::max(0.0f, crop_left); t.w = s.w; } if (crop.h != 0) { // Is this letter completely cropped? if (s.y + s.h <= crop.y || s.y >= crop.y + crop.h) { return nullptr; } units::subpixel crop_top = crop.y - s.y; units::subpixel crop_bottom = (s.y + s.h) - (crop.y + crop.h); units::subpixel crop_max = std::max(crop_top, crop_bottom); s.y = std::max(s.y, crop.y); s.h = s.h - std::max(0.0f, crop_max); t.y = t.y + std::max(0.0f, crop_top); t.h = s.h; } // Build batch instance and return current_batch_->pos = s; current_batch_->uv = t; return current_batch_.get(); } const Font::BatchInstance* Font::BuildBatchInstance(unsigned char letter, units::subpixel x, units::subpixel y) { static const Box no_crop = Box(0, 0, 0, 0); return BuildBatchInstance(letter, x, y, no_crop); } const MeshData* Font::BuildMesh(unsigned char letter, units::subpixel x, units::subpixel y, Box crop) { auto batch = BuildBatchInstance(letter, x, y, crop); // Setup the character sprites position and texture fontsheet_->set_pos(batch->pos); fontsheet_->set_subtexture(batch->uv); return &fontsheet_.get()->mesh(); } const MeshData* Font::BuildMesh(unsigned char letter, units::subpixel x, units::subpixel y) { static const Box no_crop = Box(0, 0, 0, 0); return BuildMesh(letter, x, y, no_crop); } units::pixel Font::cursor_offset(unsigned char letter) const { // In case someone tries to calculate a string using chars we dont have try { // Pointer to avoid expensive copying const Glyph* g = &charset_[letter]; return g->x_offset; } catch (...) { return 0; } } // TODO: Might need to make this const char* for perf later, if its used a lot units::pixel Font::string_width(std::string string, bool trim_whitespace) const { if (trim_whitespace) { while (string.size() > 0 && *string.begin() == ' ') { string.erase(string.begin()); } while (string.size() > 0 && *(string.end()-1) == ' ') { string.erase(string.end()-1); } } units::pixel pixel_width = 0; // Faster when done old way for (auto i = 0; i < string.length(); i++) { // Pointer to avoid expensive copying const Glyph* g; // In case someone tries to calculate a string using chars we dont have try { g = &charset_[string[i]]; } catch (...) { return 0; } // How far to advance cursor for next letter pixel_width += g->x_advance; if (trim_whitespace) { if (i == 0) { // Leftward padding of the first character pixel_width -= g->x_offset; } if (i == string.length() - 1) { // Rightward padding of the last character pixel_width -= g->x_advance - (g->x_offset + g->width); } } } return pixel_width; } units::pixel Font::string_width(std::string string) const { return string_width(string, true); } std::vector<std::string> Font::string_wrap(std::string string, units::pixel max_width) { std::vector<std::string> broken_strings; units::pixel pixel_width = 0; std::size_t last_break = 0; // Faster when done old way for (auto i = 0; i < string.length(); i++) { // Pointer to avoid expensive copying const Glyph* g; // In case someone tries to calculate a string using chars we dont have try { g = &charset_[string[i]]; } catch (...) { return std::vector<std::string>(); } // Out of bounds or newline, slice the string if ((pixel_width + g->x_advance > max_width && pixel_width > 0) || string[i] == '\n') { broken_strings.push_back(string.substr(last_break, i - last_break)); pixel_width = 0; last_break = i; } // How far to advance cursor for next letter pixel_width += g->x_advance; } // Still some left over string to append if (last_break < string.length()) { broken_strings.push_back(string.substr(last_break)); } return broken_strings; } std::vector<std::string> Font::string_wrap(ColourString string, units::pixel max_width) { std::vector<std::string> broken_strings; units::pixel pixel_width = 0; std::size_t last_break = 0; // Stores our position in "full_string", skipping ahead when we find colour codes int i = 0; const auto& full_string = string.raw_str(); Vector4 current_colour = string.base_colour(); bool current_base = true; for (const auto& f : string.fragments()) { for (const auto& c : f.text) { current_base = f.is_base; // Pointer to avoid expensive copying const Glyph* g; // In case someone tries to calculate a string using chars we dont have try { g = &charset_[full_string[i]]; } catch (...) { return std::vector<std::string>(); } // Out of bounds or newline, slice the string if ((pixel_width + g->x_advance > max_width && pixel_width > 0) || full_string[i] == '\n') { std::string prefix = (current_base ? "" : ColourString::MakeColourCode(current_colour)); broken_strings.push_back(prefix + full_string.substr(last_break, i - last_break)); pixel_width = 0; last_break = i; if (full_string[i] == '\n') { last_break++; } current_colour = f.colour; } // How far to advance cursor for next letter pixel_width += g->x_advance; i++; } // New fragment means skip 4 chars for colour code i += 4; } // Still some left over string to append if (last_break < full_string.length()) { std::string prefix = (current_base ? "" : ColourString::MakeColourCode(current_colour)); broken_strings.push_back(prefix + full_string.substr(last_break)); } return broken_strings; } int Font::advance() { units::pixel ret = advance_; advance_ = 0; return ret; } units::pixel Font::letter_height() const { return letter_height_; } units::pixel Font::line_height() const { return line_height_; } units::pixel Font::pixel_size() const { return pixel_size_; } const TextureResource* Font::texture() const { return fontsheet_->texture(); } const Texture::Info* Font::texture_info() const { return fontsheet_->texture_info(); } } // namespace gui } // namespace blons
30.773585
121
0.597725
[ "mesh", "render", "vector" ]
fb5698530b90eac2b8d2df53d6478941721102f0
1,131
cpp
C++
array/leetcode_array/73_set_matrix_zeroes.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
1
2020-10-12T19:18:19.000Z
2020-10-12T19:18:19.000Z
array/leetcode_array/73_set_matrix_zeroes.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
null
null
null
array/leetcode_array/73_set_matrix_zeroes.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
1
2020-10-12T19:18:04.000Z
2020-10-12T19:18:04.000Z
// // 73_set_matrix_zeroes.cpp // leetcode_array // // Created by Hadley on 03.10.20. // Copyright © 2020 Hadley. All rights reserved. // #include <stdio.h> #include "/usr/local/include/stdc++.h" using namespace std; class Solution { public: void setZeroes(vector<vector<int>>& matrix) { int m=matrix.size(); int n=matrix[0].size(); bool row=false, col=false; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(matrix[i][j]==0){ matrix[i][0]=0; matrix[0][j]=0; if(i==0)row=true; if(j==0)col=true; } } } for(int i=1;i<m;i++){ for(int j=1;j<n;j++){ if(matrix[i][0]==0||matrix[0][j]==0){ matrix[i][j]=0; } } } if(row){ for(int j=0;j<n;j++){ matrix[0][j]=0; } } if(col){ for(int i=0;i<m;i++){ matrix[i][0]=0; } } } };
22.176471
53
0.37931
[ "vector" ]
fb624bc71c3a48029e13803b01d6a3f157e112ad
795
cpp
C++
source/aufgabe_13.cpp
saJonMR/programmiersprachen-aufgabenblatt-3
db95d43008c7c8052c778fa1850b78a9d5b9ba4b
[ "MIT" ]
null
null
null
source/aufgabe_13.cpp
saJonMR/programmiersprachen-aufgabenblatt-3
db95d43008c7c8052c778fa1850b78a9d5b9ba4b
[ "MIT" ]
null
null
null
source/aufgabe_13.cpp
saJonMR/programmiersprachen-aufgabenblatt-3
db95d43008c7c8052c778fa1850b78a9d5b9ba4b
[ "MIT" ]
null
null
null
// // Created by Jonas Roquette on 2019-05-18. // #define CATCH_CONFIG_RUNNER #include <catch.hpp> #include <iostream> #include <vector> #include <algorithm> #include <cmath> bool is_even(int n) {return n % 2 == 0;} template<typename container, typename condition> std::vector<int> filter(container &cont, condition cond) { for (unsigned int i = 0; i < cont.size(); i++) { if (cond(cont.at(i)) == false) { cont.erase(cont.begin()+i); } } return cont; } TEST_CASE("Filter gerade Zahlen") { std::vector<int> v{1, 2, 3, 4, 5, 6}; std::vector<int> all_even = filter(v, is_even); REQUIRE(std::all_of(all_even.begin(), all_even.end(), is_even)); } int main(int argc, char* argv []) { return Catch::Session().run(argc, argv); }
20.384615
68
0.615094
[ "vector" ]
fb66e2bafda661e635268115d4239678d426cab7
1,591
cpp
C++
Problems/CodeForces/Rated/Div_2/Codeforces_Rounds/Round_670/C.Link_Cut_Centroids.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
2
2020-07-20T06:40:22.000Z
2021-11-20T01:23:26.000Z
Problems/CodeForces/Rated/Div_2/Codeforces_Rounds/Round_670/C.Link_Cut_Centroids.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
Problems/CodeForces/Rated/Div_2/Codeforces_Rounds/Round_670/C.Link_Cut_Centroids.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define fi first #define se second #define maxn 100003 #define pb push_back using namespace std; typedef pair<int,int> pi; int T,n; int best; int cnt[maxn]; pi edge[maxn]; vector<int> centers; vector<int> adj[maxn]; void reset() { best = INT_MAX; centers.clear(); for( int i = 1 ; i <= n ; i++ ) adj[i].clear(); } int dfs(int u , int dad) { cnt[u] = 0; int mx = INT_MIN; int deg = adj[u].size(); for( int i = 0 ; i < deg ; i++ ) { int v = adj[u][i]; if(v != dad) { int sz = dfs(v,u); mx = max(mx,sz); cnt[u] += sz; } } cnt[u]++; mx = max(mx,n-cnt[u]); if(mx < best) { best = mx; centers.clear(); centers.pb(u); } else if(mx == best) centers.pb(u); return cnt[u]; } int main() { scanf("%d",&T); for( int tc = 1 ; tc <= T ; tc++ ) { reset(); scanf("%d",&n); for( int i = 1 , u,v ; i < n ; i++ ) { scanf("%d%d",&u,&v); adj[u].pb(v); adj[v].pb(u); edge[i] = pi(u,v); } dfs(1,0); if(centers.size() == 1) { int u = edge[1].fi; int v = edge[1].se; printf("%d %d\n",u,v); printf("%d %d\n",u,v); } else { int u = centers[0]; int v = centers[1]; int degu = adj[u].size(); int degv = adj[v].size(); bool found = false; for( int i = 0 ; !found && i < degu ; i++ ) if(adj[u][i] != v) { printf("%d %d\n",u,adj[u][i]); printf("%d %d\n",v,adj[u][i]); found = true; } for( int i = 0 ; !found && i < degv ; i++ ) if(adj[v][i] != u) { printf("%d %d\n",v,adj[v][i]); printf("%d %d\n",u,adj[v][i]); found = true; } } } return 0; }
18.287356
46
0.484601
[ "vector" ]
fb7059f782a1fd43deed54b7f05c7afa9f6de567
8,162
hh
C++
src/c++/include/alignment/MatchSelector.hh
Illumina/Isaac4
0924fba8b467868da92e1c48323b15d7cbca17dd
[ "BSD-3-Clause" ]
13
2018-02-09T22:59:39.000Z
2021-11-29T06:33:22.000Z
src/c++/include/alignment/MatchSelector.hh
Illumina/Isaac4
0924fba8b467868da92e1c48323b15d7cbca17dd
[ "BSD-3-Clause" ]
17
2018-01-26T11:36:07.000Z
2022-02-03T18:48:43.000Z
src/c++/include/alignment/MatchSelector.hh
Illumina/Isaac4
0924fba8b467868da92e1c48323b15d7cbca17dd
[ "BSD-3-Clause" ]
4
2018-10-19T20:00:00.000Z
2020-10-29T14:44:06.000Z
/** ** Isaac Genome Alignment Software ** Copyright (c) 2010-2017 Illumina, Inc. ** All rights reserved. ** ** This software is provided under the terms and conditions of the ** GNU GENERAL PUBLIC LICENSE Version 3 ** ** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3 ** along with this program. If not, see ** <https://github.com/illumina/licenses/>. ** ** \file MatchSelector.hh ** ** \brief Selection the best matches among all possible candidates. ** ** \author Come Raczy **/ #ifndef iSAAC_ALIGNMENT_MATCH_SELECTOR_HH #define iSAAC_ALIGNMENT_MATCH_SELECTOR_HH #include <string> #include <vector> #include <boost/filesystem.hpp> #include <boost/noncopyable.hpp> #include <boost/ptr_container/ptr_vector.hpp> #include "flowcell/ReadMetadata.hh" #include "flowcell/TileMetadata.hh" #include "alignment/BclClusters.hh" #include "alignment/Cluster.hh" #include "alignment/templateBuilder/FragmentBuilder.hh" #include "alignment/TemplateBuilder.hh" #include "alignment/Match.hh" #include "alignment/TemplateLengthStatistics.hh" #include "alignment/matchFinder/TileClusterInfo.hh" #include "alignment/matchSelector/MatchSelectorStats.hh" #include "alignment/matchSelector/SemialignedEndsClipper.hh" #include "alignment/matchSelector/OverlappingEndsClipper.hh" #include "alignment/matchSelector/TemplateDetector.hh" #include "common/Threads.hpp" #include "flowcell/BarcodeMetadata.hh" #include "reference/Contig.hh" namespace isaac { namespace alignment { namespace bfs = boost::filesystem; class MatchSelector: boost::noncopyable { public: typedef flowcell::TileMetadataList TileMetadataList; typedef flowcell::ReadMetadataList ReadMetadataList; /// Construction of an instance for a given reference MatchSelector( unsigned int maxThreadCount, const flowcell::BarcodeMetadataList &barcodeMetadataList, const flowcell::FlowcellLayoutList &flowcellLayoutList, const reference::NumaContigLists &contigLists, const std::size_t candidateMatchesMax, const unsigned repeatThreshold, const std::vector<std::size_t> &clusterIdList, const int mateDriftRange, const TemplateLengthStatistics &defaultTemplateLengthStatistics, const int mapqThreshold, const bool perTileTls, const bool pfOnly, const unsigned seedLength, const unsigned maxSeedsPerMatch, const unsigned matchFinderTooManyRepeats, const unsigned matchFinderWayTooManyRepeats, const unsigned matchFinderShadowSplitRepeats, const bool collectCycleStats, const unsigned baseQualityCutoff, const bool keepUnaligned, const bool clipSemialigned, const bool clipOverlapping, const bool scatterRepeats, const bool rescueShadows, const bool trimPEAdapters, const bool anchorMate, const unsigned gappedMismatchesMax, const unsigned smitWatermanGapsMax, const bool smartSmithWaterman, const unsigned smithWatermanGapSizeMax, const bool splitAlignments, const AlignmentCfg &alignmentCfg, const TemplateBuilder::DodgyAlignmentScore dodgyAlignmentScore, const unsigned anomalousPairHandicap, const bool reserveBuffers, const unsigned detectTemplateBlockSize); /** * \brief frees the major memory reservations to make it safe to use dynamic memory allocations again */ void unreserve() { threadTemplateBuilders_.clear(); std::vector<Cluster>().swap(threadCluster_); std::vector<matchSelector::MatchSelectorStats>().swap(threadStats_); } void dumpStats(const boost::filesystem::path &statsXmlPath); void reserveMemory( const flowcell::TileMetadataList &tileMetadataList); template <typename MatchFinderT> void parallelSelect( alignment::matchFinder::TileClusterInfo &tileClusterInfo, std::vector<alignment::TemplateLengthStatistics> &barcodeTemplateLengthStatistics, const flowcell::TileMetadata &tileMetadata, const MatchFinderT &matchFinder, const BclClusters &bclData, matchSelector::FragmentStorage &fragmentStorage); private: // The threading code in selectTileMatches can not deal with exception cleanup. Let it just crash for now. common::UnsafeThreadVector computeThreads_; TileMetadataList tileMetadataList_; /** * \brief threadBclFilePaths_ gets resized for every tile total read length. If the tile read lengths * changes from lower to bigger, more threadBclFilePaths_ strings get allocated which breaks the whole * concept of allocating things once. For now this list contains tiles in the processing order so * that the total read length goes only down. TODO: cleanup this mess for example by creating * MatchSelector only for the group of tiles that have the same geometry. */ const flowcell::BarcodeMetadataList &barcodeMetadataList_; const flowcell::FlowcellLayoutList &flowcellLayoutList_; const reference::NumaContigLists &contigLists_; const unsigned repeatThreshold_; const std::vector<size_t> &clusterIdList_; const int mapqThreshold_; const bool pfOnly_; const bool collectCycleStats_; const unsigned baseQualityCutoff_; const bool keepUnaligned_; const bool clipSemialigned_; const bool clipOverlapping_; const std::vector<SequencingAdapterList> barcodeSequencingAdapters_; std::vector<matchSelector::MatchSelectorStats> allStats_; std::vector<matchSelector::MatchSelectorStats> threadStats_; std::vector<Cluster> threadCluster_; boost::ptr_vector<TemplateBuilder> threadTemplateBuilders_; std::vector<matchSelector::SemialignedEndsClipper> threadSemialignedEndsClippers_; std::vector<matchSelector::OverlappingEndsClipper> threadOverlappingEndsClippers_; // updated for barcodes relevant for the current tile std::vector<RestOfGenomeCorrection> restOfGenomeCorrections_; matchSelector::TemplateDetector templateDetector_; mutable boost::mutex mutex_; template <typename MatchFinderT> void alignThread( const unsigned threadNumber, const flowcell::TileMetadata & tileMetadata, const matchFinder::ClusterInfos &clusterInfos, unsigned &clusterId, const MatchFinderT &matchFinder, const BclClusters &bclData, const std::vector<TemplateLengthStatistics> & templateLengthStatistics, matchSelector::FragmentStorage &fragmentStorage); /** * \brief Construct the contig list from the SortedReference XML */ reference::ContigList getContigList( const reference::SortedReferenceMetadata &sortedReferenceMetadata) const; /** ** \brief Helper method to generate the 'rest of the genome' correction for ** uniquely aligned reads and fragments. ** ** There is one value for each individual reads in the readMetadataList (at ** the corresponding location) and one additional value for cases where all ** the reads match uniquely. **/ std::vector<double> getRestOfGenomeCorrectionList( const std::vector<flowcell::ReadMetadata> &readMetadataList) const; template <typename MatchFinderT> matchSelector::TemplateAlignmentType alignCluster( const reference::ContigList& barcodeContigList, const flowcell::ReadMetadataList& tileReads, const SequencingAdapterList& sequencingAdapters, const TemplateLengthStatistics& templateLengthStatistics, const uint64_t barcodeIndex, const MatchFinderT &matchFinder, const RestOfGenomeCorrection& restOfGenomeCorrection, const unsigned threadNumber, TemplateBuilder& templateBuilder, const Cluster& cluster, BamTemplate& bamTemplate, matchSelector::MatchSelectorStats& stats, matchSelector::FragmentStorage &fragmentStorage); static const unsigned CLUSTERS_AT_A_TIME = 10000; }; } // namespace alignment } // namespace isaac #endif // #ifndef iSAAC_ALIGNMENT_MATCH_SELECTOR_HH
38.682464
113
0.740995
[ "geometry", "vector" ]
fb75d8af97a0d793670d7ae3bf8e20ada10c4194
5,227
cpp
C++
orthogonal-planes/Volume_box_batch_processing/orthogonal_planes/include/graph/ParallelPlaneGraph_filtering.cpp
tamaslevente/trai
4bf68463b941f305d9b25a9374b6c2a2d51a8046
[ "MIT" ]
40
2020-01-22T12:57:09.000Z
2022-03-16T02:31:35.000Z
orthogonal-planes/Volume_box_batch_processing/orthogonal_planes/include/graph/ParallelPlaneGraph_filtering.cpp
tamaslevente/trai
4bf68463b941f305d9b25a9374b6c2a2d51a8046
[ "MIT" ]
5
2020-07-07T14:10:46.000Z
2021-12-14T08:10:01.000Z
orthogonal-planes/Volume_box_batch_processing/orthogonal_planes/include/graph/ParallelPlaneGraph_filtering.cpp
tamaslevente/trai
4bf68463b941f305d9b25a9374b6c2a2d51a8046
[ "MIT" ]
14
2020-03-13T19:53:41.000Z
2021-11-30T02:04:34.000Z
/** BSD 3-Clause License This file is part of the code accompanying the paper From Planes to Corners: Multi-Purpose Primitive Detection in Unorganized 3D Point Clouds by C. Sommer, Y. Sun, L. Guibas, D. Cremers and T. Birdal, accepted for Publication in IEEE Robotics and Automation Letters (RA-L) 2020. Copyright (c) 2019, Christiane Sommer. 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 holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ParallelPlaneGraph.h" /* * outlier filtering with normals and removal of planes with too few inliers - ply data */ void ParallelPlaneGraph::filter_outliers(const std::vector<Eigen::Vector3f>& points, const std::vector<Eigen::Vector3f>& normals, double truncation, int sampling) { // create counter for inliers std::vector<std::vector<size_t>> inliers; for (const auto& pps : vertices_) { inliers.push_back(std::vector<size_t>(pps.num_d(), 0)); } const double para_thresh = std::cos(M_PI * 20/180); const int num_points = points.size(); for (int k=0; k<num_points; k+=sampling) { int i_min = 0, j_min = 0; double res_min, res_min_abs = truncation; for (int i=0; i<num_vertices_; ++i) { // loop over all normal vectors double nTn = vertices_[i].n()[0] * normals[k][0] + vertices_[i].n()[1] * normals[k][1] + vertices_[i].n()[2] * normals[k][2]; if (std::abs(nTn) < para_thresh) { continue; } double nTp = vertices_[i].n()[0] * points[k][0] + vertices_[i].n()[1] * points[k][1] + vertices_[i].n()[2] * points[k][2]; double res_old, res_new, res_old_abs, res_new_abs = 1./0.; int j = 0; bool old_larger; int num_d = vertices_[i].num_d(); do { // for sorted d, only search until residual becomes larger again res_old = res_new; res_old_abs = res_new_abs; res_new = nTp + vertices_[i].ds()[j++]; res_new_abs = std::abs(res_new); old_larger = res_old_abs > res_new_abs; } while (old_larger && j < num_d); if (res_old_abs < res_min_abs || res_new_abs < res_min_abs) { // check if smallest residual < res_min i_min = i; if (old_larger) { res_min = res_new; res_min_abs = res_new_abs; j_min = j-1; // j-1 because j was already incremented in j++ } else { res_min = res_old; res_min_abs = res_old_abs; j_min = j-2; // j-2 because j was already incremented in j++ and res_old } } } if (res_min_abs < truncation) { ++inliers[i_min][j_min]; } } std::vector<ParallelPlaneSet> new_vertices; std::vector<int> new_index(num_vertices_, num_vertices_); int counter = 0; for (int i=0; i<num_vertices_; ++i) { int num_d = vertices_[i].num_d(); std::vector<double> ds; for (int j=0; j<num_d; ++j) { if (inliers[i][j]>0) { ds.push_back(vertices_[i].ds()[j]); } } if (ds.size()>0) { ParallelPlaneSet pps(vertices_[i].n(), ds); new_vertices.push_back(pps); new_index[i] = counter; ++counter; } } vertices_ = new_vertices; num_vertices_ = vertices_.size(); std::set<Edge> new_edges; for (auto const &e : edges_) { int i1 = new_index[e.first]; int i2 = new_index[e.second]; if (i1<i2 && i2<num_vertices_) new_edges.emplace(i1, i2); else if (i2<i1 && i1<num_vertices_) new_edges.emplace(i2, i1); } edges_ = new_edges; num_edges_ = edges_.size(); }
41.15748
164
0.626746
[ "vector", "3d" ]
fb799c9920d1e8ab1d20bb53bcb1a9f97331e68e
34,766
cpp
C++
src/ParticleFilter/ParticleFilter.cpp
TKUICLab-humanoid/localization_submodule
c43646919158b3b1432e6b45df28c5205ad245c2
[ "MIT" ]
null
null
null
src/ParticleFilter/ParticleFilter.cpp
TKUICLab-humanoid/localization_submodule
c43646919158b3b1432e6b45df28c5205ad245c2
[ "MIT" ]
null
null
null
src/ParticleFilter/ParticleFilter.cpp
TKUICLab-humanoid/localization_submodule
c43646919158b3b1432e6b45df28c5205ad245c2
[ "MIT" ]
1
2020-12-09T16:45:21.000Z
2020-12-09T16:45:21.000Z
#include "ParticleFilter/ParticleFilter.h" ParticleFilter::ParticleFilter() { rand_angle_init = 5; particlepoint_num = PARTICLNUM; excellent_particle_num = EXCELLENTPARTICLNUM; Robot_Position.postion.X = -1; //830 700 Robot_Position.postion.Y = -1; //640 370 Robot_Position.angle = -1.0; continuous_x = 0; continuous_y = 0; sendbodyauto_x = 0; sendbodyauto_y = 0; step_count = 0; //////////////////KLD////////////////// min_particlepoint_num = 50; kld_err = 0.45; //defalut 0.05 kld_z = 0.99; //defalut 0.99 //////////////////KLD////////////////// //////////////////Augmented_MCL////////////////// weight_avg = 0.0; //the average of the weight of particlepoint weight_slow = 0.0; //the long-term weight of particlepoint weight_fast = 0.0; //the short-term weight of particlepoint alpha_slow = 0.003;//0.062; alpha_fast = 0.1;//0.1; //////////////////Augmented_MCL////////////////// localization_flag = true; find_best_flag = true; AngleLUT(); } ParticleFilter::~ParticleFilter() { Angle_sin.clear(); Angle_cos.clear(); } void ParticleFilter::ParticlePointinit() { ROS_INFO("ParticlePointinit"); localization_flag = true; time_t t; srand((unsigned) time(&t)); ParticlePoint tmp; int rand_angle = rand_angle_init * 2 + 1; //粒子隨機角度//大數 rand()%40 - 20 = -20 ~ 20 for (int i = 0; i < particlepoint_num; i++) { tmp.angle = Angle_Adjustment(Robot_Position.angle + rand()%rand_angle - rand_angle_init); tmp.postion.X = Robot_Position.postion.X + (rand() % 31 - 15); //-3 ~ 3 tmp.postion.Y = Robot_Position.postion.Y + (rand() % 31 - 15); //tmp.angle = 135.0; //tmp.postion.X = 520; //-3 ~ 3 //tmp.postion.Y = 370; particlepoint.push_back(tmp); } } void ParticleFilter::CalcFOVArea(int focus, int top, int bottom, int top_width, int bottom_width, float horizontal_head_angle) { ROS_INFO("CalcFOVArea"); for(int i = 0; i < particlepoint_num; i++) { particlepoint[i].FOV_dir = Angle_Adjustment(particlepoint[i].angle + horizontal_head_angle); //coordinate Camera_Focus; float HFOV_2D_bottom = atan2(bottom_width,bottom) * 180 / PI; HFOV_2D_bottom = Angle_Adjustment(HFOV_2D_bottom); float HFOV_2D_top = atan2(top_width,top) * 180 / PI; HFOV_2D_top = Angle_Adjustment(HFOV_2D_top); //Camera_Focus.X = particlepoint[i].postion.X + focus * cos(FOV_dir * DEG2RAD); //Camera_Focus.Y = particlepoint[i].postion.Y + focus * sin(FOV_dir * DEG2RAD); float right_sight_top_angle = Angle_Adjustment(particlepoint[i].FOV_dir - HFOV_2D_top); float right_sight_bottom_angle = Angle_Adjustment(particlepoint[i].FOV_dir - HFOV_2D_bottom); float left_sight_top_angle = Angle_Adjustment(particlepoint[i].FOV_dir + HFOV_2D_top); float left_sight_bottom_angle = Angle_Adjustment(particlepoint[i].FOV_dir + HFOV_2D_bottom); float top_waist_length = sqrt(pow(top,2) + pow(top_width,2)); float bottom_waist_length = sqrt(pow(bottom,2) + pow(bottom_width,2)); particlepoint[i].FOV_Top_Right.X = particlepoint[i].postion.X + top_waist_length * cos(right_sight_top_angle * DEG2RAD); particlepoint[i].FOV_Top_Right.X = Frame_Area(particlepoint[i].FOV_Top_Right.X, MAP_LENGTH); particlepoint[i].FOV_Top_Right.Y = particlepoint[i].postion.Y - top_waist_length * sin(right_sight_top_angle * DEG2RAD); particlepoint[i].FOV_Top_Right.Y = Frame_Area(particlepoint[i].FOV_Top_Right.Y, MAP_WIDTH); particlepoint[i].FOV_Bottom_Right.X = particlepoint[i].postion.X + bottom_waist_length * cos(right_sight_bottom_angle * DEG2RAD); particlepoint[i].FOV_Bottom_Right.X = Frame_Area(particlepoint[i].FOV_Bottom_Right.X, MAP_LENGTH); particlepoint[i].FOV_Bottom_Right.Y = particlepoint[i].postion.Y - bottom_waist_length * sin(right_sight_bottom_angle * DEG2RAD); particlepoint[i].FOV_Bottom_Right.Y = Frame_Area(particlepoint[i].FOV_Bottom_Right.Y, MAP_WIDTH); particlepoint[i].FOV_Top_Left.X = particlepoint[i].postion.X + top_waist_length * cos(left_sight_top_angle * DEG2RAD); particlepoint[i].FOV_Top_Left.X = Frame_Area(particlepoint[i].FOV_Top_Left.X, MAP_LENGTH); particlepoint[i].FOV_Top_Left.Y = particlepoint[i].postion.Y - top_waist_length * sin(left_sight_top_angle * DEG2RAD); particlepoint[i].FOV_Top_Left.Y = Frame_Area(particlepoint[i].FOV_Top_Left.Y, MAP_WIDTH); particlepoint[i].FOV_Bottom_Left.X = particlepoint[i].postion.X + bottom_waist_length * cos(left_sight_bottom_angle * DEG2RAD); particlepoint[i].FOV_Bottom_Left.X = Frame_Area(particlepoint[i].FOV_Bottom_Left.X, MAP_LENGTH); particlepoint[i].FOV_Bottom_Left.Y = particlepoint[i].postion.Y - bottom_waist_length * sin(left_sight_bottom_angle * DEG2RAD); particlepoint[i].FOV_Bottom_Left.Y = Frame_Area(particlepoint[i].FOV_Bottom_Left.Y, MAP_WIDTH); } } void ParticleFilter::CalcFOVArea_averagepos(int focus, int top, int bottom, int top_width, int bottom_width, float horizontal_head_angle) { Robot_Position.FOV_dir = Angle_Adjustment(Robot_Position.angle + horizontal_head_angle); //coordinate Camera_Focus; float HFOV_2D_bottom = atan2(bottom_width,bottom) * 180 / PI; HFOV_2D_bottom = Angle_Adjustment(HFOV_2D_bottom); float HFOV_2D_top = atan2(top_width,top) * 180 / PI; HFOV_2D_top = Angle_Adjustment(HFOV_2D_top); //Camera_Focus.X = Robot_Position.postion.X + focus * cos(FOV_dir * DEG2RAD); //Camera_Focus.Y = Robot_Position.postion.Y + focus * sin(FOV_dir * DEG2RAD); float right_sight_top_angle = Angle_Adjustment(Robot_Position.FOV_dir - HFOV_2D_top); float right_sight_bottom_angle = Angle_Adjustment(Robot_Position.FOV_dir - HFOV_2D_bottom); float left_sight_top_angle = Angle_Adjustment(Robot_Position.FOV_dir + HFOV_2D_top); float left_sight_bottom_angle = Angle_Adjustment(Robot_Position.FOV_dir + HFOV_2D_bottom); float top_waist_length = sqrt(pow(top,2) + pow(top_width,2)); float bottom_waist_length = sqrt(pow(bottom,2) + pow(bottom_width,2)); Robot_Position.FOV_Top_Right.X = Robot_Position.postion.X + top_waist_length * cos(right_sight_top_angle * DEG2RAD); Robot_Position.FOV_Top_Right.X = Frame_Area(Robot_Position.FOV_Top_Right.X, MAP_LENGTH); Robot_Position.FOV_Top_Right.Y = Robot_Position.postion.Y - top_waist_length * sin(right_sight_top_angle * DEG2RAD); Robot_Position.FOV_Top_Right.Y = Frame_Area(Robot_Position.FOV_Top_Right.Y, MAP_WIDTH); Robot_Position.FOV_Bottom_Right.X = Robot_Position.postion.X + bottom_waist_length * cos(right_sight_bottom_angle * DEG2RAD); Robot_Position.FOV_Bottom_Right.X = Frame_Area(Robot_Position.FOV_Bottom_Right.X, MAP_LENGTH); Robot_Position.FOV_Bottom_Right.Y = Robot_Position.postion.Y - bottom_waist_length * sin(right_sight_bottom_angle * DEG2RAD); Robot_Position.FOV_Bottom_Right.Y = Frame_Area(Robot_Position.FOV_Bottom_Right.Y, MAP_WIDTH); Robot_Position.FOV_Top_Left.X = Robot_Position.postion.X + top_waist_length * cos(left_sight_top_angle * DEG2RAD); Robot_Position.FOV_Top_Left.X = Frame_Area(Robot_Position.FOV_Top_Left.X, MAP_LENGTH); Robot_Position.FOV_Top_Left.Y = Robot_Position.postion.Y - top_waist_length * sin(left_sight_top_angle * DEG2RAD); Robot_Position.FOV_Top_Left.Y = Frame_Area(Robot_Position.FOV_Top_Left.Y, MAP_WIDTH); Robot_Position.FOV_Bottom_Left.X = Robot_Position.postion.X + bottom_waist_length * cos(left_sight_bottom_angle * DEG2RAD); Robot_Position.FOV_Bottom_Left.X = Frame_Area(Robot_Position.FOV_Bottom_Left.X, MAP_LENGTH); Robot_Position.FOV_Bottom_Left.Y = Robot_Position.postion.Y - bottom_waist_length * sin(left_sight_bottom_angle * DEG2RAD); Robot_Position.FOV_Bottom_Left.Y = Frame_Area(Robot_Position.FOV_Bottom_Left.Y, MAP_WIDTH); } bool ParticleFilter::CheckPointArea(ParticlePoint *tmp, int x, int y) { int a = (tmp->FOV_Top_Left.X - tmp->FOV_Bottom_Left.X) * (y - tmp->FOV_Bottom_Left.Y) - (tmp->FOV_Top_Left.Y - tmp->FOV_Bottom_Left.Y) * (x - tmp->FOV_Bottom_Left.X); int b = (tmp->FOV_Top_Right.X - tmp->FOV_Top_Left.X) * (y - tmp->FOV_Top_Left.Y) - (tmp->FOV_Top_Right.Y - tmp->FOV_Top_Left.Y) * (x - tmp->FOV_Top_Left.X); int c = (tmp->FOV_Bottom_Right.X - tmp->FOV_Top_Right.X) * (y - tmp->FOV_Top_Right.Y) - (tmp->FOV_Bottom_Right.Y - tmp->FOV_Top_Right.Y) * (x - tmp->FOV_Top_Right.X); int d = (tmp->FOV_Bottom_Left.X - tmp->FOV_Bottom_Right.X) * (y - tmp->FOV_Bottom_Right.Y) - (tmp->FOV_Bottom_Left.Y - tmp->FOV_Bottom_Right.Y) * (x - tmp->FOV_Bottom_Right.X); if((a > 0 && b > 0 && c > 0 && d > 0) || (a < 0 && b < 0 && c < 0 && d < 0)) { return true; } else { return false; } } void ParticleFilter::FindFeaturePoint() { ROS_INFO("FindFeaturePoint"); for(int i = 0; i < particlepoint_num; i++) { if(particlepoint[i].featurepoint_scan_line.size() != 0) { particlepoint[i].featurepoint_scan_line.clear(); } int InnerMsg = 5; int OuterMsg = 800; int centerx = (particlepoint[i].FOV_Bottom_Right.X + particlepoint[i].FOV_Bottom_Left.X) / 2; int centery = (particlepoint[i].FOV_Bottom_Right.Y + particlepoint[i].FOV_Bottom_Left.Y) / 2; int Top_Left_dis = (int)(sqrt(pow((particlepoint[i].FOV_Top_Left.X - centerx),2) + pow((particlepoint[i].FOV_Top_Left.Y - centery),2))); int Top_Right_dis = (int)(sqrt(pow((particlepoint[i].FOV_Top_Right.X - centerx),2) + pow((particlepoint[i].FOV_Top_Right.Y - centery),2))); if(Top_Left_dis > Top_Right_dis) { OuterMsg = Top_Left_dis + 10; } else { OuterMsg = Top_Right_dis + 10; } int scan_line_cnt = 0; //the number of scan_line for (float angle = particlepoint[i].FOV_dir + - 90.0; angle <= particlepoint[i].FOV_dir + 91.0; angle = angle + 5.0) { bool find_feature_flag = false; int angle_be = (int)(Angle_Adjustment(angle)); scan_line scan_tmp; for (int r = InnerMsg; r <= OuterMsg; r++) { int x_ = r * Angle_cos[angle_be]; int y_ = r * Angle_sin[angle_be]; int x = Frame_Area(centerx + x_, Soccer_Filed.cols); int y = Frame_Area(centery - y_, Soccer_Filed.rows); if(x == 0 || x == (Soccer_Filed.cols - 1) || y == 0 || y == (Soccer_Filed.rows - 1)) { if(!find_feature_flag) { featuredata tmp; tmp.X = -1; tmp.Y = -1; tmp.dis = -1; scan_tmp.feature_point.push_back(tmp); } particlepoint[i].featurepoint_scan_line.push_back(scan_tmp); scan_line_cnt++; break; } else { if(CheckPointArea(&particlepoint[i], x, y)) { if(Soccer_Filed.data[(y * Soccer_Filed.cols + x) * 3 + 0] == 255) { featuredata tmp; if(scan_tmp.feature_point.size() != 0) { int x_dis = x - scan_tmp.feature_point[scan_tmp.feature_point.size() - 1].X; int y_dis = y - scan_tmp.feature_point[scan_tmp.feature_point.size() - 1].Y; int p2p_dis = sqrt(pow(x_dis, 2) + pow(y_dis, 2)); if(p2p_dis > 10) { tmp.X = x; tmp.Y = y; tmp.dis = sqrt(pow((x - particlepoint[i].postion.X),2) + pow((y - particlepoint[i].postion.Y),2)); tmp.x_dis = abs(x - particlepoint[i].postion.X); tmp.y_dis = abs(y - particlepoint[i].postion.Y); scan_tmp.feature_point.push_back(tmp); } } else { tmp.X = x; tmp.Y = y; tmp.dis = sqrt(pow((x - particlepoint[i].postion.X),2) + pow((y - particlepoint[i].postion.Y),2)); tmp.x_dis = abs(x - particlepoint[i].postion.X); tmp.y_dis = abs(y - particlepoint[i].postion.Y); scan_tmp.feature_point.push_back(tmp); } find_feature_flag = true; } } else { if(!find_feature_flag) { featuredata tmp; tmp.X = -1; tmp.Y = -1; tmp.dis = -1; scan_tmp.feature_point.push_back(tmp); } particlepoint[i].featurepoint_scan_line.push_back(scan_tmp); scan_line_cnt++; break; } } } } } } void ParticleFilter::FindBestParticle(scan_line *feature_point_observation_data) { ROS_INFO("FindBestParticle"); float x_avg = 0.0; float y_avg = 0.0; for(int i = 0; i < particlepoint_num; i++) { particlepoint[i].fitness_value = 0; particlepoint[i].weight = 0.0; int real_feature_point_cnt = 0; x_avg += particlepoint[i].postion.X; y_avg += particlepoint[i].postion.Y; for(int j = 0; j < particlepoint[i].featurepoint_scan_line.size(); j++) { real_feature_point_cnt += (*(feature_point_observation_data + j)).feature_point.size(); if(particlepoint[i].featurepoint_scan_line[j].feature_point.size() == (*(feature_point_observation_data + j)).feature_point.size()) { int scan_line_fitness = 0.0; for(int k = 0; k < particlepoint[i].featurepoint_scan_line[j].feature_point.size(); k++) { if((*(feature_point_observation_data + j)).feature_point[k].dis < 0) { if(particlepoint[i].featurepoint_scan_line[j].feature_point[k].dis < 0) { scan_line_fitness += MAP_MAX_LENGTH; } } else { if(particlepoint[i].featurepoint_scan_line[j].feature_point[k].dis > 0) { int Dis_error = abs((*(feature_point_observation_data + j)).feature_point[k].dis - particlepoint[i].featurepoint_scan_line[j].feature_point[k].dis); Dis_error = abs(MAP_MAX_LENGTH - Dis_error); scan_line_fitness = scan_line_fitness + Dis_error; } } } particlepoint[i].fitness_value += (scan_line_fitness / particlepoint[i].featurepoint_scan_line[j].feature_point.size()); } else if(particlepoint[i].featurepoint_scan_line[j].feature_point.size() > (*(feature_point_observation_data + j)).feature_point.size()) { int scan_line_fitness = 0; for(int k = 0; k < (*(feature_point_observation_data + j)).feature_point.size(); k++) { if((*(feature_point_observation_data + j)).feature_point[k].dis < 0) { if(particlepoint[i].featurepoint_scan_line[j].feature_point[k].dis < 0) { scan_line_fitness += MAP_MAX_LENGTH; } } else { if(particlepoint[i].featurepoint_scan_line[j].feature_point[k].dis > 0) { int Dis_error = abs((*(feature_point_observation_data + j)).feature_point[k].dis - particlepoint[i].featurepoint_scan_line[j].feature_point[k].dis); Dis_error = abs(MAP_MAX_LENGTH - Dis_error); scan_line_fitness = scan_line_fitness + Dis_error; } } } particlepoint[i].fitness_value += (scan_line_fitness / particlepoint[i].featurepoint_scan_line[j].feature_point.size()); } else { int scan_line_fitness = 0; for(int k = 0; k < particlepoint[i].featurepoint_scan_line[j].feature_point.size(); k++) { if((*(feature_point_observation_data + j)).feature_point[k].dis < 0) { if(particlepoint[i].featurepoint_scan_line[j].feature_point[k].dis < 0) { scan_line_fitness += MAP_MAX_LENGTH; } } else { if(particlepoint[i].featurepoint_scan_line[j].feature_point[k].dis > 0) { int Dis_error = abs((*(feature_point_observation_data + j)).feature_point[k].dis - particlepoint[i].featurepoint_scan_line[j].feature_point[k].dis); Dis_error = abs(MAP_MAX_LENGTH - Dis_error); scan_line_fitness = scan_line_fitness + Dis_error; } } } particlepoint[i].fitness_value += (scan_line_fitness / (*(feature_point_observation_data + j)).feature_point.size()); } } particlepoint[i].weight = (float)particlepoint[i].fitness_value / (float)(real_feature_point_cnt * MAP_MAX_LENGTH); weight_avg = weight_avg + particlepoint[i].weight; } x_avg = x_avg / (float)particlepoint_num; y_avg = y_avg / (float)particlepoint_num; weight_avg = weight_avg / (float)particlepoint_num; ROS_INFO("weight_avg:%f", weight_avg); weight_slow = weight_slow + alpha_slow * (weight_avg - weight_slow); weight_fast = weight_fast + alpha_fast * (weight_avg - weight_fast); ROS_INFO("weight_slow:%f", weight_slow); ROS_INFO("weight_fast:%f", weight_fast); particlepoint_compare = particlepoint; sort(particlepoint_compare.begin(), particlepoint_compare.end(), greater<ParticlePoint>()); FindRobotPosition(x_avg, y_avg); ROS_INFO("weight:%f", particlepoint[0].weight); ROS_INFO("weight_low:%f", particlepoint[particlepoint.size() - 1].weight); ROS_INFO("x:%d", Robot_Position.postion.X); ROS_INFO("y:%d", Robot_Position.postion.Y); //-------------判斷適應值太高的狀況就不更新--------- if(particlepoint_compare[0].weight < 0.28) { find_best_flag = false; } else { find_best_flag = true; } //-------------判斷適應值太高的狀況就不更新--------- } void ParticleFilter::FindRobotPosition(float x_avg, float y_avg) { ROS_INFO("FindRobotPosition"); ROS_INFO("x_avg = %f",x_avg); ROS_INFO("y_avg = %f",y_avg); float x_varience = 0.0; float y_varience = 0.0; for(int i = 0; i < particlepoint_num; i++) { float x_ = particlepoint_compare[i].postion.X - x_avg; float y_ = particlepoint_compare[i].postion.Y - y_avg; x_varience = x_varience + pow(x_, 2); y_varience = y_varience + pow(y_, 2); } x_varience = x_varience / (float)particlepoint_num; y_varience = y_varience / (float)particlepoint_num; ROS_INFO("x_varience = %f",x_varience); ROS_INFO("y_varience = %f",y_varience); if((x_varience <= 0.5) && (y_varience <= 0.5)) { ROS_INFO("varience is very small"); Robot_Position = particlepoint_compare[0]; return; } for(int i = 0; i < particlepoint_num; i++) { float x_to_avg_error = particlepoint_compare[i].postion.X - x_avg; float y_to_avg_error = particlepoint_compare[i].postion.Y - y_avg; x_to_avg_error = pow(x_to_avg_error, 2); y_to_avg_error = pow(y_to_avg_error, 2); if((x_to_avg_error < x_varience) && (y_to_avg_error < y_varience)) { ROS_INFO("The best number = %d",i); Robot_Position = particlepoint_compare[i]; break; } else if(i == (particlepoint_num - 1)) { ROS_INFO("No find the best"); Robot_Position.postion.X = x_avg; Robot_Position.postion.Y = y_avg; Robot_Position.angle = particlepoint_compare[0].angle; } } /*int x_tmp[particlepoint_num] = {0}; int y_tmp[particlepoint_num] = {0}; float angle_tmp[particlepoint_num] = {0.0}; for(int i = 0; i < particlepoint_num; i++) { x_tmp[i] = particlepoint[i].postion.X; y_tmp[i] = particlepoint[i].postion.Y; angle_tmp[i] = particlepoint[i].angle; } sort(x_tmp, x_tmp + particlepoint_num); sort(y_tmp, y_tmp + particlepoint_num); sort(angle_tmp,angle_tmp + particlepoint_num); Robot_Position.postion.X = x_tmp[particlepoint_num / 2]; Robot_Position.postion.Y = y_tmp[particlepoint_num / 2]; Robot_Position.angle = angle_tmp[particlepoint_num / 2];*/ } int ParticleFilter::TournamentResample(int excellent_particle_num) { int tournament_particle_num[excellent_particle_num] = {0}; int best_particle_num = 0; float best_weight_value = 0.0; for(int i = 0; i < excellent_particle_num; ++i) { tournament_particle_num[i] = rand()%particlepoint_num; for(int j = 0; j < i; j++) { if(tournament_particle_num[i] == tournament_particle_num[j]) { tournament_particle_num[i] = rand()%particlepoint_num; j = -1; } } if(particlepoint[tournament_particle_num[i]].weight > best_weight_value) { best_weight_value = particlepoint[tournament_particle_num[i]].weight; best_particle_num = tournament_particle_num[i]; } } return best_particle_num; } void ParticleFilter::StatePredict() { ROS_INFO("StatePredict"); int rand_angle = rand_angle_init * 2 + 1; int value_sum = 0; float sum = 0.0; int particle_num = 0; if(excellent_particle_num > particlepoint_num) { excellent_particle_num = particlepoint_num; } ///////////////////////////Augmented_MCL /////////////////////////// std::random_device rd, x_rd, y_rd; //產生亂數種子 //Produce the random seed std::mt19937 generator(rd()); //使用梅森旋轉演算法產生亂數 //Use Mersenne Twister to produce the random std::mt19937 x_generator(x_rd()); std::mt19937 y_generator(y_rd()); std::uniform_real_distribution<float> add_random_distribution(0.0, 1.0); //設定機率分佈範圍(連續型均勻分佈) //Set the random distribution range(continuous) std::uniform_real_distribution<float> x_random_distribution(550, MAP_LENGTH - 105), y_random_distribution(10, MAP_WIDTH - 10); float reset_random_threshold = std::max(0.0, 1.0 - (weight_fast / weight_slow)); int rand_particle_cnt = 0; ROS_INFO("reset_random_threshold = %f",reset_random_threshold); ///////////////////////////Augmented_MCL /////////////////////////// vector<ParticlePoint> tmp; //ROS_INFO("continuous_x = %d",continuous_x); for(int i = 0; i < particlepoint_num; ++i) { double random = ((double)rand() / (RAND_MAX)); ParticlePoint current_particle; if(random < reset_random_threshold) { ROS_INFO("Kidnapped"); find_best_flag = true; current_particle.postion.X = x_random_distribution(x_generator); current_particle.postion.Y = y_random_distribution(y_generator); current_particle.angle = Angle_Adjustment(Robot_Position.angle + rand()%rand_angle - rand_angle_init); tmp.push_back(current_particle); } else { int best_particle_num = TournamentResample(excellent_particle_num); current_particle.angle = Angle_Adjustment(Robot_Position.angle + rand()%rand_angle - rand_angle_init); if(Step_flag) { float move_x = 0.0; float move_y = 0.0; float y_dir_angle = 0.0; if(continuous_y > 0) { float y_dir_angle = Angle_Adjustment(current_particle.angle + 90.0); } else { float y_dir_angle = Angle_Adjustment(current_particle.angle - 90.0); } move_x = cos(current_particle.angle * DEG2RAD) * continuous_x / 1000 + cos(y_dir_angle * DEG2RAD) * continuous_y / 1000; move_y = -(sin(current_particle.angle * DEG2RAD) * continuous_x / 1000 + sin(y_dir_angle * DEG2RAD) * continuous_y / 1000); move_x = 6.5 * move_x; move_y = 6.5 * move_y; /*if(i == 1) { ROS_INFO("move_x = %f",move_x); ROS_INFO("move_y = %f",move_y); }*/ if(step_count == 0) { current_particle.postion.X = particlepoint[best_particle_num].postion.X + (int)(move_x) + (rand() % 11 - 5); current_particle.postion.Y = particlepoint[best_particle_num].postion.Y + (int)(move_y) + (rand() % 11 - 5); } else { current_particle.postion.X = particlepoint[best_particle_num].postion.X + (int)(move_x) * step_count + (rand() % 11 - 5); current_particle.postion.Y = particlepoint[best_particle_num].postion.Y + (int)(move_y) * step_count + (rand() % 11 - 5); } } else { current_particle.postion.X = particlepoint[best_particle_num].postion.X; //+ (rand() % 11 - 5); current_particle.postion.Y = particlepoint[best_particle_num].postion.Y; //+ (rand() % 11 - 5); //particlepoint[particle_num].postion.X = f_iter->postion.X + (rand() % 17 - 8); //particlepoint[particle_num].postion.Y = f_iter->postion.Y + (rand() % 17 - 8); } tmp.push_back(current_particle); } } particlepoint.clear(); particlepoint = tmp; ROS_INFO("particlepoint size = %d",particlepoint.size()); step_count = 0; Step_flag = false; } void ParticleFilter::NoLookFiled() { ROS_INFO("NoLookFiled"); if(Step_flag) { float move_x = 0.0; float move_y = 0.0; float y_dir_angle = 0.0; for(int i = 0; i < particlepoint_num; ++i) { particlepoint[i].angle = Angle_Adjustment(Robot_Position.angle); if(continuous_y > 0) { float y_dir_angle = Angle_Adjustment(particlepoint[i].angle + 90.0); } else { float y_dir_angle = Angle_Adjustment(particlepoint[i].angle - 90.0); } move_x = cos(particlepoint[i].angle * DEG2RAD) * continuous_x / 1000 + cos(y_dir_angle * DEG2RAD) * continuous_y / 1000; move_y = -(sin(particlepoint[i].angle * DEG2RAD) * continuous_x / 1000 + sin(y_dir_angle * DEG2RAD) * continuous_y / 1000); move_x = 6.5 * move_x; move_y = 6.5 * move_y; if(step_count == 0) { particlepoint[i].postion.X = particlepoint[i].postion.X + (int)(move_x); particlepoint[i].postion.Y = particlepoint[i].postion.Y + (int)(move_y); //ROS_INFO("add the step"); } else { particlepoint[i].postion.X = particlepoint[i].postion.X + (int)(move_x) * step_count; particlepoint[i].postion.Y = particlepoint[i].postion.Y + (int)(move_y) * step_count; //ROS_INFO("add the step"); //step_count = 0; } } Robot_Position.angle = Angle_Adjustment(Robot_Position.angle); if(continuous_y > 0) { float y_dir_angle = Angle_Adjustment(Robot_Position.angle + 90.0); } else { float y_dir_angle = Angle_Adjustment(Robot_Position.angle - 90.0); } move_x = cos(Robot_Position.angle * DEG2RAD) * continuous_x / 1000 + cos(y_dir_angle * DEG2RAD) * continuous_y / 1000; move_y = -(sin(Robot_Position.angle * DEG2RAD) * continuous_x / 1000 + sin(y_dir_angle * DEG2RAD) * continuous_y / 1000); move_x = 6.5 * move_x; move_y = 6.5 * move_y; if(step_count == 0) { Robot_Position.postion.X = Robot_Position.postion.X + (int)(move_x); Robot_Position.postion.Y = Robot_Position.postion.Y + (int)(move_y); //ROS_INFO("add the step"); } else { Robot_Position.postion.X = Robot_Position.postion.X + (int)(move_x) * step_count; Robot_Position.postion.Y = Robot_Position.postion.Y + (int)(move_y) * step_count; //ROS_INFO("add the step"); //step_count = 0; } Step_flag = false; } localization_flag = false; } void ParticleFilter::KLD_Sampling() { ROS_INFO("KLD_Sampling"); int current_num = 0; int particlepoint_num_finish = min_particlepoint_num + 10; non_empty_bin.clear(); //ROS_INFO("particle number is %d !!!!!!!!!!!!!!!!!!!!!!!!",particlepoint_num); while(current_num < particlepoint_num && current_num < particlepoint_num_finish) { pointdata current_point; current_point.pos.X = particlepoint[current_num].postion.X; current_point.pos.Y = particlepoint[current_num].postion.Y; current_point.theta = int(particlepoint[current_num].angle); if(non_empty_bin.size() != 0) { for(int i = 0; i < non_empty_bin.size(); i++) { int dis_x = abs(current_point.pos.X - non_empty_bin[i].pos.X); int dis_y = abs(current_point.pos.Y - non_empty_bin[i].pos.Y); int dis = sqrt(pow(dis_x,2) + pow(dis_y,2)); //ROS_INFO("dis = %d",dis); // ROS_INFO("current_point.pos.X = %d",current_point.pos.X); // ROS_INFO("current_point.pos.Y = %d",current_point.pos.Y); // ROS_INFO("particlepoint[current_num].postion.X = %d",particlepoint[current_num].postion.X); // ROS_INFO("particlepoint[current_num].postion.Y = %d",particlepoint[current_num].postion.Y); if(dis > 3) { non_empty_bin.push_back(current_point); if(current_num >= min_particlepoint_num) { //ROS_INFO("non_empty_bin.size = %d",non_empty_bin.size()); float kld_equation_1 = float((non_empty_bin.size() - 1)) / (2.0 * kld_err); //ROS_INFO("kld_equation_1 is %f !!!!!!!!!!!!!!!!!!!!!!!!",kld_equation_1); float kld_equation_2 = 1.0 - 2.0 / (9.0 * float((non_empty_bin.size() - 1))); //ROS_INFO("kld_equation_2 is %f !!!!!!!!!!!!!!!!!!!!!!!!",kld_equation_2); float kld_equation_3 = sqrt(2.0 / (9.0 * (non_empty_bin.size() - 1))) * kld_z; //ROS_INFO("kld_equation_3 is %f !!!!!!!!!!!!!!!!!!!!!!!!",kld_equation_3); particlepoint_num_finish = int(kld_equation_1 * pow((kld_equation_2 + kld_equation_3),3)); } break; /*if(current_point.pos.Y != non_empty_bin[i].pos.Y) { if(current_point.theta != non_empty_bin[i].theta) { non_empty_bin.push_back(current_point); if(current_num >= min_particlepoint_num) { ROS_INFO("non_empty_bin.size = %d",non_empty_bin.size()); float kld_equation_1 = float((non_empty_bin.size() - 1)) / (2.0 * kld_err); //ROS_INFO("kld_equation_1 is %f !!!!!!!!!!!!!!!!!!!!!!!!",kld_equation_1); float kld_equation_2 = 1.0 - 2.0 / (9.0 * float((non_empty_bin.size() - 1))); //ROS_INFO("kld_equation_2 is %f !!!!!!!!!!!!!!!!!!!!!!!!",kld_equation_2); float kld_equation_3 = sqrt(2.0 / (9.0 * (non_empty_bin.size() - 1))) * kld_z; //ROS_INFO("kld_equation_3 is %f !!!!!!!!!!!!!!!!!!!!!!!!",kld_equation_3); particlepoint_num = int(kld_equation_1 * pow((kld_equation_2 + kld_equation_3),3)); } break; } }*/ } } } else { non_empty_bin.push_back(current_point); } current_num++; //ROS_INFO("particle number is %d !!!!!!!!!!!!!!!!!!!!!!!!",particlepoint_num); } non_empty_bin.clear(); particlepoint_num = particlepoint_num_finish; if(particlepoint_num < min_particlepoint_num) { particlepoint_num = min_particlepoint_num; } else if(particlepoint_num > PARTICLNUM) { particlepoint_num = PARTICLNUM; } excellent_particle_num = particlepoint_num * 0.1; if(excellent_particle_num > EXCELLENTPARTICLNUM) { excellent_particle_num = EXCELLENTPARTICLNUM; } ROS_INFO("particle number is %d !!!!!!!!!!!!!!!!!!!!!!!!",particlepoint_num); ROS_INFO("KLD_Sampling end!!"); }
47.689986
180
0.56771
[ "vector" ]
fb7fae7901720865734afa9bcbaedb3797b9435b
27,942
cpp
C++
src/game/PathFinder.cpp
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
1
2017-11-16T19:04:07.000Z
2017-11-16T19:04:07.000Z
src/game/PathFinder.cpp
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
null
null
null
src/game/PathFinder.cpp
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
null
null
null
/* * Copyright (C) 2005-2011 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "MoveMap.h" #include "GridMap.h" #include "Creature.h" #include "PathFinder.h" #include "../recastnavigation/Detour/Include/DetourCommon.h" ////////////////// PathInfo ////////////////// PathInfo::PathInfo(const Unit* owner, const float destX, const float destY, const float destZ, bool useStraightPath) : m_pathPolyRefs(NULL), m_polyLength(0), m_type(PATHFIND_BLANK), m_useStraightPath(useStraightPath), m_sourceUnit(owner), m_navMesh(NULL), m_navMeshQuery(NULL) { PathNode endPoint(destX, destY, destZ); setEndPosition(endPoint); float x,y,z; m_sourceUnit->GetPosition(x, y, z); PathNode startPoint(x, y, z); setStartPosition(startPoint); PATH_DEBUG("++ PathInfo::PathInfo for %u \n", m_sourceUnit->GetGUID()); uint32 mapId = m_sourceUnit->GetMapId(); if (MMAP::MMapFactory::IsPathfindingEnabled(mapId)) { MMAP::MMapManager* mmap = MMAP::MMapFactory::createOrGetMMapManager(); m_navMesh = mmap->GetNavMesh(mapId); m_navMeshQuery = mmap->GetNavMeshQuery(mapId); } if (m_navMesh && m_navMeshQuery && !m_sourceUnit->hasUnitState(UNIT_STAT_IGNORE_PATHFINDING)) { BuildPolyPath(startPoint, endPoint); } else { BuildShortcut(); m_type = PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH); } } PathInfo::~PathInfo() { PATH_DEBUG("++ PathInfo::~PathInfo() for %u \n", m_sourceUnit->GetGUID()); if (m_pathPolyRefs) delete [] m_pathPolyRefs; } bool PathInfo::Update(const float destX, const float destY, const float destZ, bool useStraightPath) { PathNode newDest(destX, destY, destZ); PathNode oldDest = getEndPosition(); setEndPosition(newDest); float x, y, z; m_sourceUnit->GetPosition(x, y, z); PathNode newStart(x, y, z); PathNode oldStart = getStartPosition(); setStartPosition(newStart); m_useStraightPath = useStraightPath; PATH_DEBUG("++ PathInfo::Update() for %u \n", m_sourceUnit->GetGUID()); // make sure navMesh works - we can run on map w/o mmap if (!m_navMesh || !m_navMeshQuery || m_sourceUnit->hasUnitState(UNIT_STAT_IGNORE_PATHFINDING)) { BuildShortcut(); m_type = PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH); return true; } float dist = m_sourceUnit->GetObjectBoundingRadius(); bool oldDestInRange = inRange(oldDest, newDest, dist, dist); // this can happen only if caller did a bad job calculating the need for path update if (oldDestInRange && inRange(newStart, oldStart, dist, dist)) { setEndPosition(oldDest); setStartPosition(oldStart); return false; } // check if destination moved - if not we can optimize something here // we are following old, precalculated path? if (oldDestInRange && m_pathPoints.size() > 2) { // our target is not moving - we just coming closer // we are moving on precalculated path - enjoy the ride PATH_DEBUG("++ PathInfo::Update:: precalculated path\n"); m_pathPoints.crop(1, 0); setNextPosition(m_pathPoints[1]); return false; } else { // target moved, so we need to update the poly path BuildPolyPath(newStart, newDest); return true; } } dtPolyRef PathInfo::getPathPolyByPosition(dtPolyRef *polyPath, uint32 polyPathSize, const float* point, float *distance) { if (!polyPath || !polyPathSize) return INVALID_POLYREF; dtPolyRef nearestPoly = INVALID_POLYREF; float minDist2d = FLT_MAX; float minDist3d = 0.0f; for (uint32 i = 0; i < polyPathSize; ++i) { float closestPoint[VERTEX_SIZE]; if (DT_SUCCESS != m_navMeshQuery->closestPointOnPoly(polyPath[i], point, closestPoint)) continue; float d = dtVdist2DSqr(point, closestPoint); if (d < minDist2d) { minDist2d = d; nearestPoly = m_pathPolyRefs[i]; minDist3d = dtVdistSqr(point, closestPoint); } if(minDist2d < 1.0f) // shortcut out - close enough for us break; } if (distance) *distance = dtSqrt(minDist3d); return (minDist2d < 4.0f) ? nearestPoly : INVALID_POLYREF; } dtPolyRef PathInfo::getPolyByLocation(const float* point, float *distance) { // first we check the current path // if the current path doesn't contain the current poly, // we need to use the expensive navMesh.findNearestPoly dtPolyRef polyRef = getPathPolyByPosition(m_pathPolyRefs, m_polyLength, point, distance); if(polyRef != INVALID_POLYREF) return polyRef; // we don't have it in our old path // try to get it by findNearestPoly() // first try with low search box float extents[VERTEX_SIZE] = {3.0f, 5.0f, 3.0f}; // bounds of poly search area dtQueryFilter filter = createFilter(); float closestPoint[VERTEX_SIZE] = {0.0f, 0.0f, 0.0f}; dtStatus result = m_navMeshQuery->findNearestPoly(point, extents, &filter, &polyRef, closestPoint); if(DT_SUCCESS == result && polyRef != INVALID_POLYREF) { *distance = dtVdist(closestPoint, point); return polyRef; } // still nothing .. // try with bigger search box extents[1] = 200.0f; result = m_navMeshQuery->findNearestPoly(point, extents, &filter, &polyRef, closestPoint); if(DT_SUCCESS == result && polyRef != INVALID_POLYREF) { *distance = dtVdist(closestPoint, point); return polyRef; } return INVALID_POLYREF; } void PathInfo::BuildPolyPath(PathNode startPos, PathNode endPos) { // *** getting start/end poly logic *** float distToStartPoly, distToEndPoly; float startPoint[VERTEX_SIZE] = {startPos.y, startPos.z, startPos.x}; float endPoint[VERTEX_SIZE] = {endPos.y, endPos.z, endPos.x}; dtPolyRef startPoly = getPolyByLocation(startPoint, &distToStartPoly); dtPolyRef endPoly = getPolyByLocation(endPoint, &distToEndPoly); // we have a hole in our mesh // make shortcut path and mark it as NOPATH ( with flying exception ) // its up to caller how he will use this info if (startPoly == INVALID_POLYREF || endPoly == INVALID_POLYREF) { PATH_DEBUG("++ BuildPolyPath :: (startPoly == 0 || endPoly == 0)\n"); BuildShortcut(); m_type = (m_sourceUnit->GetTypeId() == TYPEID_UNIT && ((Creature*)m_sourceUnit)->CanFly()) ? PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH) : PATHFIND_NOPATH; return; } // we may need a better number here bool farFromPoly = (distToStartPoly > 7.0f || distToEndPoly > 7.0f); if (farFromPoly) { PATH_DEBUG("++ BuildPolyPath :: farFromPoly distToStartPoly=%.3f distToEndPoly=%.3f\n", distToStartPoly, distToEndPoly); bool buildShotrcut = false; if (m_sourceUnit->GetTypeId() == TYPEID_UNIT) { Creature* owner = (Creature*)m_sourceUnit; PathNode p = (distToStartPoly > 7.0f) ? startPos : endPos; if (m_sourceUnit->GetTerrain()->IsUnderWater(p.x, p.y, p.z)) { PATH_DEBUG("++ BuildPolyPath :: underWater case\n"); if (owner->CanSwim() || owner->IsPet()) buildShotrcut = true; } else { PATH_DEBUG("++ BuildPolyPath :: flying case\n"); if (owner->CanFly()) buildShotrcut = true; } } if (buildShotrcut) { BuildShortcut(); m_type = PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH); return; } else { float closestPoint[VERTEX_SIZE]; // we may want to use closestPointOnPolyBoundary instead if (DT_SUCCESS == m_navMeshQuery->closestPointOnPoly(endPoly, endPoint, closestPoint)) { dtVcopy(endPoint, closestPoint); setActualEndPosition(PathNode(endPoint[2],endPoint[0],endPoint[1])); } m_type = PATHFIND_INCOMPLETE; } } // *** poly path generating logic *** // start and end are on same polygon // just need to move in straight line if (startPoly == endPoly) { PATH_DEBUG("++ BuildPolyPath :: (startPoly == endPoly)\n"); BuildShortcut(); m_pathPolyRefs = new dtPolyRef[1]; m_pathPolyRefs[0] = startPoly; m_polyLength = 1; m_type = farFromPoly ? PATHFIND_INCOMPLETE : PATHFIND_NORMAL; PATH_DEBUG("++ BuildPolyPath :: path type %d\n", m_type); return; } // look for startPoly/endPoly in current path // TODO: we can merge it with getPathPolyByPosition() loop bool startPolyFound = false; bool endPolyFound = false; uint32 pathStartIndex, pathEndIndex; if (m_polyLength) { for (pathStartIndex = 0; pathStartIndex < m_polyLength; ++pathStartIndex) if (m_pathPolyRefs[pathStartIndex] == startPoly) { startPolyFound = true; break; } for (pathEndIndex = m_polyLength-1; pathEndIndex > pathStartIndex; --pathEndIndex) if (m_pathPolyRefs[pathEndIndex] == endPoly) { endPolyFound = true; break; } } if (startPolyFound && endPolyFound) { PATH_DEBUG("++ BuildPolyPath :: (startPolyFound && endPolyFound)\n"); // we moved along the path and the target did not move out of our old poly-path // our path is a simple subpath case, we have all the data we need // just "cut" it out m_polyLength = pathEndIndex - pathStartIndex + 1; dtPolyRef* newPolyRefs = new dtPolyRef[m_polyLength]; memcpy(newPolyRefs, m_pathPolyRefs+pathStartIndex, m_polyLength*sizeof(dtPolyRef)); delete [] m_pathPolyRefs; m_pathPolyRefs = newPolyRefs; } else if (startPolyFound && !endPolyFound) { PATH_DEBUG("++ BuildPolyPath :: (startPolyFound && !endPolyFound)\n"); // we are moving on the old path but target moved out // so we have atleast part of poly-path ready m_polyLength -= pathStartIndex; // try to adjust the suffix of the path instead of recalculating entire length // at given interval the target cannot get too far from its last location // thus we have less poly to cover // sub-path of optimal path is optimal // take ~80% of the original length // TODO : play with the values here uint32 prefixPolyLength = uint32(m_polyLength*0.8f + 0.5f); dtPolyRef prefixPathPolys[MAX_PATH_LENGTH]; memcpy(prefixPathPolys, m_pathPolyRefs+pathStartIndex, prefixPolyLength*sizeof(dtPolyRef)); dtPolyRef suffixStartPoly = prefixPathPolys[prefixPolyLength-1]; // we need any point on our suffix start poly to generate poly-path, so we need last poly in prefix data float suffixEndPoint[VERTEX_SIZE]; if (DT_SUCCESS != m_navMeshQuery->closestPointOnPoly(suffixStartPoly, endPoint, suffixEndPoint)) { // suffixStartPoly is invalid somehow, or the navmesh is broken => error state sLog.outError("%u's Path Build failed: invalid polyRef in path", m_sourceUnit->GetGUID()); BuildShortcut(); m_type = PATHFIND_NOPATH; return; } // generate suffix dtQueryFilter filter = createFilter(); dtPolyRef suffixPathPolys[MAX_PATH_LENGTH]; uint32 suffixPolyLength = 0; dtStatus dtResult = m_navMeshQuery->findPath( suffixStartPoly, // start polygon endPoly, // end polygon suffixEndPoint, // start position endPoint, // end position &filter, // polygon search filter suffixPathPolys, // [out] path (int*)&suffixPolyLength, MAX_PATH_LENGTH-prefixPolyLength); // max number of polygons in output path if (!suffixPolyLength || dtResult != DT_SUCCESS) { // this is probably an error state, but we'll leave it // and hopefully recover on the next Update // we still need to copy our preffix sLog.outError("%u's Path Build failed: 0 length path", m_sourceUnit->GetGUID()); } PATH_DEBUG("++ m_polyLength=%u prefixPolyLength=%u suffixPolyLength=%u \n",m_polyLength, prefixPolyLength, suffixPolyLength); // new path = prefix + suffix - overlap m_polyLength = prefixPolyLength + suffixPolyLength - 1; delete [] m_pathPolyRefs; m_pathPolyRefs = new dtPolyRef[m_polyLength]; // copy the part of the old path we keep - prefix memcpy(m_pathPolyRefs, prefixPathPolys, prefixPolyLength*sizeof(dtPolyRef)); // copy the newly created suffix - skip first poly, we have it at prefix end if (suffixPathPolys) memcpy(m_pathPolyRefs+prefixPolyLength, suffixPathPolys+1, (suffixPolyLength-1)*sizeof(dtPolyRef)); } else { PATH_DEBUG("++ BuildPolyPath :: (!startPolyFound && !endPolyFound)\n"); // either we have no path at all -> first run // or something went really wrong -> we aren't moving along the path to the target // just generate new path // free and invalidate old path data clear(); dtQueryFilter filter = createFilter(); // use special filter so we use proper terrain types dtPolyRef pathPolys[MAX_PATH_LENGTH]; m_polyLength = 0; dtStatus dtResult = m_navMeshQuery->findPath( startPoly, // start polygon endPoly, // end polygon startPoint, // start position endPoint, // end position &filter, // polygon search filter pathPolys, // [out] path (int*)&m_polyLength, MAX_PATH_LENGTH); // max number of polygons in output path if (!m_polyLength || dtResult != DT_SUCCESS) { // only happens if we passed bad data to findPath(), or navmesh is messed up sLog.outError("%u's Path Build failed: 0 length path", m_sourceUnit->GetGUID()); BuildShortcut(); m_type = PATHFIND_NOPATH; return; } m_pathPolyRefs = new dtPolyRef[m_polyLength]; memcpy(m_pathPolyRefs, pathPolys, m_polyLength*sizeof(dtPolyRef)); } // by now we know what type of path we can get if (m_pathPolyRefs[m_polyLength - 1] == endPoly && !(m_type & PATHFIND_INCOMPLETE)) m_type = PATHFIND_NORMAL; else m_type = PATHFIND_INCOMPLETE; // generate the point-path out of our up-to-date poly-path BuildPointPath(startPoint, endPoint); } void PathInfo::BuildPointPath(float *startPoint, float *endPoint) { // get the actual reachable point on last poly in path float closestPoint[VERTEX_SIZE]; if ((m_type & PATHFIND_INCOMPLETE) && DT_SUCCESS == m_navMeshQuery->closestPointOnPoly(m_pathPolyRefs[m_polyLength-1], endPoint, closestPoint)) { dtVcopy(endPoint, closestPoint); setActualEndPosition(PathNode(endPoint[2],endPoint[0],endPoint[1])); } float pathPoints[MAX_POINT_PATH_LENGTH*VERTEX_SIZE]; uint32 pointCount = 0; dtStatus dtResult = DT_FAILURE; if (m_useStraightPath) { dtResult = m_navMeshQuery->findStraightPath( startPoint, // start position endPoint, // end position m_pathPolyRefs, // current path m_polyLength, // lenth of current path pathPoints, // [out] path corner points NULL, // [out] flags NULL, // [out] shortened path (int*)&pointCount, MAX_POINT_PATH_LENGTH); // maximum number of points/polygons to use } else { dtResult = findSmoothPath( startPoint, // start position endPoint, // end position m_pathPolyRefs, // current path m_polyLength, // length of current path pathPoints, // [out] path corner points (int*)&pointCount, MAX_POINT_PATH_LENGTH); // maximum number of points } if (pointCount < 2 || dtResult != DT_SUCCESS) { // only happens if pass bad data to findStraightPath or navmesh is broken // single point paths can be generated here // TODO : check the exact cases PATH_DEBUG("++ PathInfo::BuildPointPath FAILED! path sized %d returned\n", pointCount); BuildShortcut(); m_type = PATHFIND_NOPATH; return; } m_pathPoints.resize(pointCount); for (uint32 i = 0; i < pointCount; ++i) m_pathPoints.set(i, PathNode(pathPoints[i*VERTEX_SIZE+2], pathPoints[i*VERTEX_SIZE], pathPoints[i*VERTEX_SIZE+1])); // first point is always our current location - we need the next one setNextPosition(m_pathPoints[1]); PATH_DEBUG("++ PathInfo::BuildPointPath path type %d size %d poly-size %d\n", m_type, pointCount, m_polyLength); } void PathInfo::BuildShortcut() { PATH_DEBUG("++ BuildShortcut :: making shortcut\n"); clear(); // make two point path, our curr pos is the start, and dest is the end m_pathPoints.resize(2); // set start and a default next position m_pathPoints.set(0, getStartPosition()); m_pathPoints.set(1, getActualEndPosition()); setNextPosition(getActualEndPosition()); m_type = PATHFIND_SHORTCUT; } dtQueryFilter PathInfo::createFilter() { dtQueryFilter filter; if (m_sourceUnit->GetTypeId() != TYPEID_UNIT) return filter; Creature* creature = (Creature*)m_sourceUnit; unsigned short includeFlags = 0; unsigned short excludeFlags = 0; if (creature->CanWalk()) includeFlags |= NAV_GROUND; // walk // creatures don't take environmental damage if (creature->CanSwim() || creature->IsPet()) includeFlags |= (NAV_WATER | NAV_MAGMA | NAV_SLIME); // swim // allow creatures to cheat and use different movement types if they are moved // forcefully into terrain they can't normally move in if (creature->IsInWater() || creature->IsUnderWater()) includeFlags |= getNavTerrain(creature->GetPositionX(),creature->GetPositionY(),creature->GetPositionZ()); filter.setIncludeFlags(includeFlags); filter.setExcludeFlags(excludeFlags); return filter; } NavTerrain PathInfo::getNavTerrain(float x, float y, float z) { GridMapLiquidData data; m_sourceUnit->GetTerrain()->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &data); switch (data.type) { case MAP_LIQUID_TYPE_WATER: case MAP_LIQUID_TYPE_OCEAN: return NAV_WATER; case MAP_LIQUID_TYPE_MAGMA: return NAV_MAGMA; case MAP_LIQUID_TYPE_SLIME: return NAV_SLIME; default: return NAV_EMPTY; } } uint32 PathInfo::fixupCorridor(dtPolyRef* path, const uint32 npath, const uint32 maxPath, const dtPolyRef* visited, const uint32 nvisited) { int32 furthestPath = -1; int32 furthestVisited = -1; // Find furthest common polygon. for (int32 i = npath-1; i >= 0; --i) { bool found = false; for (int32 j = nvisited-1; j >= 0; --j) { if (path[i] == visited[j]) { furthestPath = i; furthestVisited = j; found = true; } } if (found) break; } // If no intersection found just return current path. if (furthestPath == -1 || furthestVisited == -1) return npath; // Concatenate paths. // Adjust beginning of the buffer to include the visited. uint32 req = nvisited - furthestVisited; uint32 orig = uint32(furthestPath+1) < npath ? furthestPath+1 : npath; uint32 size = npath-orig > 0 ? npath-orig : 0; if (req+size > maxPath) size = maxPath-req; if (size) memmove(path+req, path+orig, size*sizeof(dtPolyRef)); // Store visited for (uint32 i = 0; i < req; ++i) path[i] = visited[(nvisited-1)-i]; return req+size; } bool PathInfo::getSteerTarget(const float* startPos, const float* endPos, const float minTargetDist, const dtPolyRef* path, const uint32 pathSize, float* steerPos, unsigned char& steerPosFlag, dtPolyRef& steerPosRef) { // Find steer target. static const uint32 MAX_STEER_POINTS = 3; float steerPath[MAX_STEER_POINTS*VERTEX_SIZE]; unsigned char steerPathFlags[MAX_STEER_POINTS]; dtPolyRef steerPathPolys[MAX_STEER_POINTS]; uint32 nsteerPath = 0; dtStatus dtResult = m_navMeshQuery->findStraightPath(startPos, endPos, path, pathSize, steerPath, steerPathFlags, steerPathPolys, (int*)&nsteerPath, MAX_STEER_POINTS); if (!nsteerPath || DT_SUCCESS != dtResult) return false; // Find vertex far enough to steer to. uint32 ns = 0; while (ns < nsteerPath) { // Stop at Off-Mesh link or when point is further than slop away. if ((steerPathFlags[ns] & DT_STRAIGHTPATH_OFFMESH_CONNECTION) || !inRangeYZX(&steerPath[ns*VERTEX_SIZE], startPos, minTargetDist, 1000.0f)) break; ns++; } // Failed to find good point to steer to. if (ns >= nsteerPath) return false; dtVcopy(steerPos, &steerPath[ns*VERTEX_SIZE]); steerPos[1] = startPos[1]; // keep Z value steerPosFlag = steerPathFlags[ns]; steerPosRef = steerPathPolys[ns]; return true; } dtStatus PathInfo::findSmoothPath(const float* startPos, const float* endPos, const dtPolyRef* polyPath, const uint32 polyPathSize, float* smoothPath, int* straightPathCount, const uint32 maxSmoothPathSize) { MANGOS_ASSERT(polyPathSize <= MAX_PATH_LENGTH); *straightPathCount = 0; uint32 nsmoothPath = 0; dtPolyRef polys[MAX_PATH_LENGTH]; memcpy(polys, polyPath, sizeof(dtPolyRef)*polyPathSize); uint32 npolys = polyPathSize; float iterPos[VERTEX_SIZE], targetPos[VERTEX_SIZE]; if(DT_SUCCESS != m_navMeshQuery->closestPointOnPolyBoundary(polys[0], startPos, iterPos)) return DT_FAILURE; if(DT_SUCCESS != m_navMeshQuery->closestPointOnPolyBoundary(polys[npolys-1], endPos, targetPos)) return DT_FAILURE; dtVcopy(&smoothPath[nsmoothPath*VERTEX_SIZE], iterPos); nsmoothPath++; // Move towards target a small advancement at a time until target reached or // when ran out of memory to store the path. while (npolys && nsmoothPath < maxSmoothPathSize) { // Find location to steer towards. float steerPos[VERTEX_SIZE]; unsigned char steerPosFlag; dtPolyRef steerPosRef = INVALID_POLYREF; if (!getSteerTarget(iterPos, targetPos, SMOOTH_PATH_SLOP, polys, npolys, steerPos, steerPosFlag, steerPosRef)) break; bool endOfPath = (steerPosFlag & DT_STRAIGHTPATH_END); bool offMeshConnection = (steerPosFlag & DT_STRAIGHTPATH_OFFMESH_CONNECTION); // Find movement delta. float delta[VERTEX_SIZE]; dtVsub(delta, steerPos, iterPos); float len = dtSqrt(dtVdot(delta,delta)); // If the steer target is end of path or off-mesh link, do not move past the location. if ((endOfPath || offMeshConnection) && len < SMOOTH_PATH_STEP_SIZE) len = 1.0f; else len = SMOOTH_PATH_STEP_SIZE / len; float moveTgt[VERTEX_SIZE]; dtVmad(moveTgt, iterPos, delta, len); // Move float result[VERTEX_SIZE]; const static uint32 MAX_VISIT_POLY = 16; dtPolyRef visited[MAX_VISIT_POLY]; dtQueryFilter filter = createFilter(); uint32 nvisited = 0; m_navMeshQuery->moveAlongSurface(polys[0], iterPos, moveTgt, &filter, result, visited, (int*)&nvisited, MAX_VISIT_POLY); npolys = fixupCorridor(polys, npolys, MAX_PATH_LENGTH, visited, nvisited); m_navMeshQuery->getPolyHeight(polys[0], result, &result[1]); dtVcopy(iterPos, result); // Handle end of path and off-mesh links when close enough. if (endOfPath && inRangeYZX(iterPos, steerPos, SMOOTH_PATH_SLOP, 2.0f)) { // Reached end of path. dtVcopy(iterPos, targetPos); if (nsmoothPath < maxSmoothPathSize) { dtVcopy(&smoothPath[nsmoothPath*VERTEX_SIZE], iterPos); nsmoothPath++; } break; } else if (offMeshConnection && inRangeYZX(iterPos, steerPos, SMOOTH_PATH_SLOP, 2.0f)) { // Reached off-mesh connection. float startPos[VERTEX_SIZE], endPos[VERTEX_SIZE]; // Advance the path up to and over the off-mesh connection. dtPolyRef prevRef = INVALID_POLYREF; dtPolyRef polyRef = polys[0]; uint32 npos = 0; while (npos < npolys && polyRef != steerPosRef) { prevRef = polyRef; polyRef = polys[npos]; npos++; } for (uint32 i = npos; i < npolys; ++i) polys[i-npos] = polys[i]; npolys -= npos; // Handle the connection. if (DT_SUCCESS == m_navMesh->getOffMeshConnectionPolyEndPoints(prevRef, polyRef, startPos, endPos)) { if (nsmoothPath < maxSmoothPathSize) { dtVcopy(&smoothPath[nsmoothPath*VERTEX_SIZE], startPos); nsmoothPath++; // Hack to make the dotted path not visible during off-mesh connection. if (nsmoothPath & 1) { dtVcopy(&smoothPath[nsmoothPath*VERTEX_SIZE], startPos); nsmoothPath++; } } // Move position at the other side of the off-mesh link. dtVcopy(iterPos, endPos); m_navMeshQuery->getPolyHeight(polys[0], iterPos, &iterPos[1]); } } // Store results. if (nsmoothPath < maxSmoothPathSize) { dtVcopy(&smoothPath[nsmoothPath*VERTEX_SIZE], iterPos); nsmoothPath++; } } *straightPathCount = nsmoothPath; return DT_SUCCESS; }
36.054194
134
0.614917
[ "mesh" ]
fb81f32ea31861332e2a347cf69f15154ce48a35
10,531
cpp
C++
GTE/Samples/Graphics/ShaderReflection/ShaderReflectionConsole.cpp
lakinwecker/GeometricTools
cff3e3fcb52d714afe0b6789839c460437c10b27
[ "BSL-1.0" ]
null
null
null
GTE/Samples/Graphics/ShaderReflection/ShaderReflectionConsole.cpp
lakinwecker/GeometricTools
cff3e3fcb52d714afe0b6789839c460437c10b27
[ "BSL-1.0" ]
1
2022-03-18T00:34:13.000Z
2022-03-18T00:34:13.000Z
GTE/Samples/Graphics/ShaderReflection/ShaderReflectionConsole.cpp
lakinwecker/GeometricTools
cff3e3fcb52d714afe0b6789839c460437c10b27
[ "BSL-1.0" ]
1
2022-03-17T21:54:55.000Z
2022-03-17T21:54:55.000Z
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #include "ShaderReflectionConsole.h" #if defined(GTE_USE_DIRECTX) #include <Graphics/DX11/HLSLShaderFactory.h> #endif #if defined(GTE_USE_OPENGL) #include <Graphics/GL45/GLSLVisualProgram.h> #include <Graphics/GL45/GLSLComputeProgram.h> #endif ShaderReflectionConsole::ShaderReflectionConsole(Parameters& parameters) : Console(parameters), #if defined(GTE_USE_DIRECTX) mCompileFlags(D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_IEEE_STRICTNESS | D3DCOMPILE_PACK_MATRIX_ROW_MAJOR | D3DCOMPILE_OPTIMIZATION_LEVEL3), #endif mIOPath(""), mExt("") { if (!SetEnvironment()) { parameters.created = false; return; } } void ShaderReflectionConsole::Execute() { ReflectVertexColoring(); ReflectTexturing(); ReflectBillboards(); ReflectNestedStruct(); ReflectTextureArrays(); ReflectSimpleBuffers(); ReflectAppendConsume(); } bool ShaderReflectionConsole::SetEnvironment() { std::string path = GetGTEPath(); if (path == "") { return false; } mIOPath = path + "/Samples/Graphics/ShaderReflection/Shaders/"; mEnvironment.Insert(mIOPath); #if defined(GTE_USE_DIRECTX) mExt = ".hlsl"; #else mExt = ".glsl"; #endif std::vector<std::string> inputs = { "AppendConsume.cs" + mExt, "Billboards.gs" + mExt, "Billboards.ps" + mExt, "Billboards.vs" + mExt, "NestedStruct.cs" + mExt, "SimpleBuffers.cs" + mExt, "TextureArrays.ps" + mExt, "TextureArrays.vs" + mExt, "Texturing.ps" + mExt, "Texturing.vs" + mExt, "VertexColoring.ps" + mExt, "VertexColoring.vs" + mExt }; for (auto const& input : inputs) { if (mEnvironment.GetPath(input) == "") { LogError("Cannot find file " + input); return false; } } return true; } void ShaderReflectionConsole::ReflectVertexColoring() { std::string vsPath = mIOPath + "VertexColoring.vs" + mExt; std::string psPath = mIOPath + "VertexColoring.ps" + mExt; #if defined(GTE_USE_DIRECTX) HLSLReflection vshader = HLSLShaderFactory::CreateFromFile( vsPath, "VSMain", "vs_5_0", ProgramDefines(), mCompileFlags); if (vshader.IsValid()) { std::ofstream vsout(mIOPath + "VertexColoring.vsreflect.txt"); if (vsout) { vshader.Print(vsout); vsout.close(); } } HLSLReflection pshader = HLSLShaderFactory::CreateFromFile( psPath, "PSMain", "ps_5_0", ProgramDefines(), mCompileFlags); if (pshader.IsValid()) { std::ofstream psout(mIOPath + "VertexColoring.psreflect.txt"); if (psout) { pshader.Print(psout); psout.close(); } } #endif #if defined(GTE_USE_OPENGL) auto program = std::dynamic_pointer_cast<GLSLVisualProgram>( mProgramFactory->CreateFromFiles(vsPath, psPath, "")); if (program) { std::ofstream out(mIOPath + "VertexColoring.glslreflect.txt"); if (out) { auto& reflection = program->GetReflector(); reflection.Print(out); out.close(); } } #endif } void ShaderReflectionConsole::ReflectTexturing() { std::string vsPath = mIOPath + "Texturing.vs" + mExt; std::string psPath = mIOPath + "Texturing.ps" + mExt; #if defined(GTE_USE_DIRECTX) HLSLReflection vshader = HLSLShaderFactory::CreateFromFile( vsPath, "VSMain", "vs_5_0", ProgramDefines(), mCompileFlags); if (vshader.IsValid()) { std::ofstream vsout(mIOPath + "Texturing.vsreflect.txt"); if (vsout) { vshader.Print(vsout); vsout.close(); } } HLSLReflection pshader = HLSLShaderFactory::CreateFromFile( psPath, "PSMain", "ps_5_0", ProgramDefines(), mCompileFlags); if (pshader.IsValid()) { std::ofstream psout(mIOPath + "Texturing.psreflect.txt"); if (psout) { pshader.Print(psout); psout.close(); } } #endif #if defined(GTE_USE_OPENGL) auto program = std::dynamic_pointer_cast<GLSLVisualProgram>( mProgramFactory->CreateFromFiles(vsPath, psPath, "")); if (program) { std::ofstream out(mIOPath + "Texturing.glslreflect.txt"); if (out) { auto& reflection = program->GetReflector(); reflection.Print(out); out.close(); } } #endif } void ShaderReflectionConsole::ReflectBillboards() { std::string vsPath = mIOPath + "Billboards.vs" + mExt; std::string gsPath = mIOPath + "Billboards.gs" + mExt; std::string psPath = mIOPath + "Billboards.ps" + mExt; #if defined(GTE_USE_DIRECTX) HLSLReflection vshader = HLSLShaderFactory::CreateFromFile( vsPath, "VSMain", "vs_5_0", ProgramDefines(), mCompileFlags); if (vshader.IsValid()) { std::ofstream vsout("Shaders/Billboards.vsreflect.txt"); if (vsout) { vshader.Print(vsout); vsout.close(); } } HLSLReflection gshader = HLSLShaderFactory::CreateFromFile( gsPath, "GSMain", "gs_5_0", ProgramDefines(), mCompileFlags); if (gshader.IsValid()) { std::ofstream gsout("Shaders/Billboards.gsreflect.txt"); if (gsout) { gshader.Print(gsout); gsout.close(); } } HLSLReflection pshader = HLSLShaderFactory::CreateFromFile( psPath, "PSMain", "ps_5_0", ProgramDefines(), mCompileFlags); if (pshader.IsValid()) { std::ofstream psout("Shaders/Billboards.psreflect.txt"); if (psout) { pshader.Print(psout); psout.close(); } } #endif #if defined(GTE_USE_OPENGL) auto program = std::dynamic_pointer_cast<GLSLVisualProgram>( mProgramFactory->CreateFromFiles(vsPath, psPath, gsPath)); if (program) { std::ofstream out(mIOPath + "Billboards.glslreflect.txt"); if (out) { auto& reflection = program->GetReflector(); reflection.Print(out); out.close(); } } #endif } void ShaderReflectionConsole::ReflectNestedStruct() { std::string csPath = mIOPath + "NestedStruct.cs" + mExt; #if defined(GTE_USE_DIRECTX) HLSLReflection cshader = HLSLShaderFactory::CreateFromFile( csPath, "CSMain", "cs_5_0", ProgramDefines(), mCompileFlags); if (cshader.IsValid()) { std::ofstream csout(mIOPath + "NestedStruct.csreflect.txt"); if (csout) { cshader.Print(csout); csout.close(); } } #endif #if defined(GTE_USE_OPENGL) auto program = std::dynamic_pointer_cast<GLSLComputeProgram>( mProgramFactory->CreateFromFile(csPath)); if (program) { std::ofstream out(mIOPath + "NestedStruct.glslreflect.txt"); if (out) { auto& reflection = program->GetReflector(); reflection.Print(out); out.close(); } } #endif } void ShaderReflectionConsole::ReflectTextureArrays() { std::string vsPath = mIOPath + "TextureArrays.vs" + mExt; std::string psPath = mIOPath + "TextureArrays.ps" + mExt; #if defined(GTE_USE_DIRECTX) HLSLReflection vshader = HLSLShaderFactory::CreateFromFile( vsPath, "VSMain", "vs_5_0", ProgramDefines(), mCompileFlags); if (vshader.IsValid()) { std::ofstream vsout(mIOPath + "TextureArrays.vsreflect.txt"); if (vsout) { vshader.Print(vsout); vsout.close(); } } HLSLReflection pshader = HLSLShaderFactory::CreateFromFile( psPath, "PSMain", "ps_5_0", ProgramDefines(), mCompileFlags); if (pshader.IsValid()) { std::ofstream psout(mIOPath + "TextureArrays.psreflect.txt"); if (psout) { pshader.Print(psout); psout.close(); } } #endif #if defined(GTE_USE_OPENGL) auto program = std::dynamic_pointer_cast<GLSLVisualProgram>( mProgramFactory->CreateFromFiles(vsPath, psPath, "")); if (program) { std::ofstream out(mIOPath + "TextureArrays.glslreflect.txt"); if (out) { auto& reflection = program->GetReflector(); reflection.Print(out); out.close(); } } #endif } void ShaderReflectionConsole::ReflectSimpleBuffers() { std::string csPath = mIOPath + "SimpleBuffers.cs" + mExt; #if defined(GTE_USE_DIRECTX) HLSLReflection cshader = HLSLShaderFactory::CreateFromFile( csPath, "CSMain", "cs_5_0", ProgramDefines(), mCompileFlags); if (cshader.IsValid()) { std::ofstream csout(mIOPath + "SimpleBuffers.csreflect.txt"); if (csout) { cshader.Print(csout); csout.close(); } } #endif #if defined(GTE_USE_OPENGL) auto program = std::dynamic_pointer_cast<GLSLComputeProgram>( mProgramFactory->CreateFromFile(csPath)); if (program) { std::ofstream out(mIOPath + "SimpleBuffers.glslreflect.txt"); if (out) { auto& reflection = program->GetReflector(); reflection.Print(out); out.close(); } } #endif } void ShaderReflectionConsole::ReflectAppendConsume() { std::string csPath = mIOPath + "AppendConsume.cs" + mExt; #if defined(GTE_USE_DIRECTX) HLSLReflection cshader = HLSLShaderFactory::CreateFromFile( csPath, "CSMain", "cs_5_0", ProgramDefines(), mCompileFlags); if (cshader.IsValid()) { std::ofstream csout(mIOPath + "AppendConsume.csreflect.txt"); if (csout) { cshader.Print(csout); csout.close(); } } #endif #if defined(GTE_USE_OPENGL) auto program = std::dynamic_pointer_cast<GLSLComputeProgram>( mProgramFactory->CreateFromFile(csPath)); if (program) { std::ofstream out(mIOPath + "AppendConsume.glslreflect.txt"); if (out) { auto& reflection = program->GetReflector(); reflection.Print(out); out.close(); } } #endif }
26.002469
145
0.608014
[ "vector" ]
fb833874c6b78e4709d3601e9c4bde881dcbb483
9,891
cpp
C++
GIDI/Src/GIDI_Ys1d.cpp
Mathnerd314/gidiplus
ed4c48ab399a964fe782f73d0a065849b00090bb
[ "MIT-0", "MIT" ]
null
null
null
GIDI/Src/GIDI_Ys1d.cpp
Mathnerd314/gidiplus
ed4c48ab399a964fe782f73d0a065849b00090bb
[ "MIT-0", "MIT" ]
null
null
null
GIDI/Src/GIDI_Ys1d.cpp
Mathnerd314/gidiplus
ed4c48ab399a964fe782f73d0a065849b00090bb
[ "MIT-0", "MIT" ]
null
null
null
/* # <<BEGIN-copyright>> # Copyright 2019, Lawrence Livermore National Security, LLC. # See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: MIT # <<END-copyright>> */ #include <stdlib.h> #include "GIDI.hpp" #include <HAPI.hpp> namespace GIDI { namespace Functions { /*! \class Ys1d * Class to store GNDS <**Ys1d**> node. */ /* *********************************************************************************************************//** * * @param a_axes [in] The axes to copy for *this*. * @param a_interpolation [in] The interpolation flag. * @param a_index [in] If imbedded in a two dimensional function, the index of this instance. * @param a_outerDomainValue [in] If imbedded in a two dimensional function, the domain value for *x2*. ***********************************************************************************************************/ Ys1d::Ys1d( Axes const &a_axes, ptwXY_interpolation a_interpolation, int a_index, double a_outerDomainValue ) : Function1dForm( GIDI_Ys1dChars, FormType::Ys1d, a_axes, a_interpolation, a_index, a_outerDomainValue ), m_start( 0 ) { } /* *********************************************************************************************************//** * * @param a_axes [in] The axes to copy for *this*. * @param a_interpolation [in] The interpolation flag. * @param a_start [in] The index of the x1 value the **Ys** data start at. * @param a_Ys [in] The list of y values. * @param a_index [in] If imbedded in a two dimensional function, the index of this instance. * @param a_outerDomainValue [in] If imbedded in a two dimensional function, the domain value for *x2*. ***********************************************************************************************************/ Ys1d::Ys1d( Axes const &a_axes, ptwXY_interpolation a_interpolation, std::size_t a_start, std::vector<double> const &a_Ys, int a_index, double a_outerDomainValue ) : Function1dForm( GIDI_Ys1dChars, FormType::Ys1d, a_axes, a_interpolation, a_index, a_outerDomainValue ), m_start( a_start ), m_Ys( a_Ys ) { } /* *********************************************************************************************************//** * Constructs the instance from a **HAPI::Nodee** instance. * * @param a_construction [in] Used to pass user options for parsing. * @param a_node [in] The Ys1d HAPI::Node to be parsed and to construct the instance. * @param a_setupInfo [in] Information create my the Protare constructor to help in parsing. * @param a_parent [in] If imbedded in a two dimensional function, its pointers. ***********************************************************************************************************/ Ys1d::Ys1d( Construction::Settings const &a_construction, HAPI::Node const &a_node, SetupInfo &a_setupInfo, Suite *a_parent ) : Function1dForm( a_construction, a_node, a_setupInfo, FormType::Ys1d, a_parent ), m_start( a_node.child( "values" ).attribute( "start" ).as_int( ) ), // as_int returns 0 if "start" not present. m_Ys( ) { HAPI::Node values = a_node.child("values"); nf_Buffer<double> data; parseValuesOfDoubles( a_construction, values, a_setupInfo, data ); m_Ys.resize( (long) data.size() ); for( size_t i1 = 0; i1 < data.size(); ++i1 ) m_Ys[i1] = data[i1]; } /* *********************************************************************************************************//** * The Ys1d copy constructor. * * @param a_Ys1d ***********************************************************************************************************/ Ys1d::Ys1d( Ys1d const &a_Ys1d ) : Function1dForm( a_Ys1d ), m_start( a_Ys1d.start( ) ), m_Ys( a_Ys1d.Ys( ) ) { } /* *********************************************************************************************************//** ***********************************************************************************************************/ Ys1d::~Ys1d( ) { } /* *********************************************************************************************************//** * Adds two **Ys1d** instances and returns the result. * * @param a_rhs [in] The **Ys1d** instance to add to this instance. * @return An **Ys1d** instance that is the sum of this and *a_rhs*. ***********************************************************************************************************/ Ys1d Ys1d::operator+( Ys1d const &a_rhs ) const { Ys1d _Ys1d( *this ); _Ys1d += a_rhs; return( _Ys1d ); } /* *********************************************************************************************************//** * Adds an **Ys1d** instance to this. * * @param a_rhs [in] The **Ys1d** instance to add to this instance. * @return This instance. ***********************************************************************************************************/ Ys1d &Ys1d::operator+=( Ys1d const &a_rhs ) { if( length( ) == 0 ) m_start = a_rhs.length( ); // Allow for empty (uninitialized) this. if( length( ) != a_rhs.length( ) ) throw Exception( "Ys1d::operator+=: lengths not equal." ); long deltaStart = (long) a_rhs.start( ); deltaStart -= (long) m_start; if( deltaStart >= 0 ) { for( std::size_t i1 = 0; i1 < a_rhs.size( ); ++i1 ) m_Ys[i1+deltaStart] += a_rhs[i1]; } else { std::vector<double> _Ys( a_rhs.Ys( ) ); for( std::size_t i1 = 0; i1 < size( ); ++i1 ) _Ys[i1-deltaStart] += m_Ys[i1]; m_Ys = _Ys; m_start = a_rhs.start( ); } return( *this ); } /* *********************************************************************************************************//** * This is currently not implemented. * * @return The domain minimum for the instance. ***********************************************************************************************************/ double Ys1d::domainMin( ) const { #ifndef __NVCC__ throw Exception( "Ys1d::domainMin: not implemented" ); #endif return( 0. ); } /* *********************************************************************************************************//** * This is currently not implemented. * * @return The domain maximum for the instance. ***********************************************************************************************************/ double Ys1d::domainMax( ) const { #ifndef __NVCC__ throw Exception( "Ys1d::domainMax: not implemented" ); #endif return( 0. ); } /* *********************************************************************************************************//** * This is currently not implemented. * * @param a_x1 [in] Domain value to evaluate this at. * @return ***********************************************************************************************************/ double Ys1d::evaluate( double a_x1 ) const { #ifndef __NVCC__ throw Exception( "Ys1d::evaluate: not implemented" ); #endif return( 0. ); } /* *********************************************************************************************************//** * Fills the argument *a_writeInfo* with the XML lines that represent *this*. Recursively enters each sub-node. * * @param a_writeInfo [in/out] Instance containing incremental indentation and other information and stores the appended lines. * @param a_indent [in] The amount to indent *this* node. * @param a_embedded [in] If *true*, *this* function is embedded in a higher dimensional function. * @param a_inRegions [in] If *true*, *this* is in a Regions1d container. ***********************************************************************************************************/ void Ys1d::toXMLList_func( WriteInfo &a_writeInfo, std::string const &a_indent, bool a_embedded, bool a_inRegions ) const { std::string indent2 = a_writeInfo.incrementalIndent( a_indent ); std::string attributes = a_writeInfo.addAttribute( GIDI_labelChars, label( ) ); a_writeInfo.addNodeStarter( a_indent, moniker( ), attributes ); axes( ).toXMLList( a_writeInfo, indent2 ); doublesToXMLList( a_writeInfo, indent2, m_Ys, m_start ); a_writeInfo.addNodeEnder( moniker( ) ); } /* *********************************************************************************************************//** * Prints the pair (index, y) values to stdout. The format string must have a long and a double conversion specifiers (e.g., " %10ld %.6f"). * * @param a_format [in] The format string passed to the C printf function. ***********************************************************************************************************/ void Ys1d::print( char const *a_format ) { long size = static_cast<long>( m_Ys.size( ) ); for( long index = 0; index < size; ++index ) printf( a_format, index + m_start, m_Ys[index] ); } /* *********************************************************************************************************//** * Prints the pair (index, y) values to stdout. The format string must have a long and a double conversion specifiers (e.g., " %10ld %.6f"). * * @param a_format [in] The format string passed to the C printf function. ***********************************************************************************************************/ void Ys1d::print( std::string const &a_format ) { print( a_format.c_str( ) ); } } // End namespace Functions. } // End namespace GIDI.
43.19214
165
0.443939
[ "vector" ]
fb86a83e30ae9c65fdaae6621ca1c1db3d352ae6
5,069
cpp
C++
src/rdxclib/caching.cpp
elasota/rdx2
e08ca09a07d3ac8675f7f950a7bdf838a9f5f907
[ "MIT" ]
null
null
null
src/rdxclib/caching.cpp
elasota/rdx2
e08ca09a07d3ac8675f7f950a7bdf838a9f5f907
[ "MIT" ]
null
null
null
src/rdxclib/caching.cpp
elasota/rdx2
e08ca09a07d3ac8675f7f950a7bdf838a9f5f907
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include "../lua/src/lua.h" #include "../rdx/rdx_basictypes.hpp" #define MAX_FILES 4096 enum { ValueType_Table, ValueType_String, ValueType_Number, }; struct CacheFileInfo { struct CacheFileDictionary { char contentsHash[8]; char terminatorByte; bool corrupt; // Flagged until the file is closed. If set, a parse error occurred and the file is unusable. int numFiles; long fileTableOffset; } dict; FILE *f; }; // filename, contents hash, force rebuild int createCacheFile(lua_State *L) { CacheFileInfo *cfi = static_cast<CacheFileInfo*>(lua_newuserdata(L, sizeof(CacheFileInfo))); memcpy(cfi->dict.contentsHash, lua_tostring(L, 2), 8); cfi->dict.terminatorByte = '\0'; int forceRebuild = lua_toboolean(L, 3); cfi->f = fopen(lua_tostring(L, 1), "rb"); if(cfi->f) { CacheFileInfo::CacheFileDictionary dict; dict.terminatorByte = '\0'; fread(&dict, sizeof(dict), 1, cfi->f); fclose(cfi->f); if(lua_toboolean(L, 3)) dict.corrupt = true; if(!dict.corrupt && !memcmp(cfi->dict.contentsHash, dict.contentsHash, 8)) { lua_pushnil(L); lua_pushinteger(L, dict.numFiles); return 2; } } cfi->f = fopen(lua_tostring(L, 1), "wb"); cfi->dict.corrupt = true; fwrite(&cfi->dict, sizeof(CacheFileInfo::CacheFileDictionary), 1, cfi->f); // newuserdata will spill through return 1; } // cfi, object list int writeCacheObject(lua_State *L) { CacheFileInfo *cfi = static_cast<CacheFileInfo*>(lua_touserdata(L, 1)); int numObjects = static_cast<int>(lua_objlen(L, 2)); long foffs = ftell(cfi->f); fwrite(&numObjects, sizeof(int), 1, cfi->f); for(int i=0;i<numObjects;i++) { lua_pushinteger(L, i+1); lua_gettable(L, 2); int tt = lua_type(L, -1); fwrite(&tt, sizeof(int), 1, cfi->f); switch(tt) { case LUA_TBOOLEAN: { int b = lua_toboolean(L, -1); fwrite(&b, sizeof(b), 1, cfi->f); } break; case LUA_TNUMBER: { lua_Number v = lua_tonumber(L, -1); fwrite(&v, sizeof(v), 1, cfi->f); } break; case LUA_TSTRING: { size_t l; const char *str = lua_tolstring(L, -1, &l); fwrite(&l, sizeof(l), 1, cfi->f); fwrite(str, l, 1, cfi->f); } break; case LUA_TTABLE: { int numValues = static_cast<int>(lua_objlen(L, -1)); fwrite(&numValues, sizeof(numValues), 1, cfi->f); for(int i=0;i<numValues;i++) { lua_pushinteger(L, i+1); lua_gettable(L, -2); int vindex = lua_tointeger(L, -1); fwrite(&vindex, sizeof(vindex), 1, cfi->f); lua_pop(L, 1); } } break; } lua_pop(L, 1); } lua_pushinteger(L, foffs); return 1; } // filename, file table index int readCacheObject(lua_State *L) { CacheFileInfo::CacheFileDictionary dict; FILE *f = fopen(lua_tostring(L, 1), "rb"); fread(&dict, sizeof(dict), 1, f); size_t objectOffset; fseek(f, lua_tointeger(L, 2) * static_cast<long>(sizeof(size_t)) + dict.fileTableOffset, SEEK_SET); fread(&objectOffset, sizeof(size_t), 1, f); fseek(f, static_cast<long>(objectOffset), SEEK_SET); int numObjects; fread(&numObjects, sizeof(int), 1, f); lua_createtable(L, numObjects, 0); for(int i=0;i<numObjects;i++) { lua_pushinteger(L, i+1); int tt; fread(&tt, sizeof(int), 1, f); switch(tt) { case LUA_TBOOLEAN: { int b; fread(&b, sizeof(b), 1, f); lua_pushboolean(L, b); } break; case LUA_TNUMBER: { lua_Number v; fread(&v, sizeof(v), 1, f); lua_pushnumber(L, v); } break; case LUA_TSTRING: { size_t l; fread(&l, sizeof(l), 1, f); char *str = static_cast<char*>(malloc(l+1)); str[l] = '\0'; fread(str, l, 1, f); lua_pushlstring(L, str, l); free(str); } break; case LUA_TTABLE: { int numValues; fread(&numValues, sizeof(numValues), 1, f); lua_createtable(L, numValues, 0); for(int i=0;i<numValues;i++) { lua_pushinteger(L, i+1); int vindex; fread(&vindex, sizeof(vindex), 1, f); lua_pushinteger(L, vindex); lua_settable(L, -3); } } break; } lua_settable(L, -3); } fclose(f); return 1; } // filename, offset table int closeCacheFile(lua_State *L) { CacheFileInfo *cfi = static_cast<CacheFileInfo*>(lua_touserdata(L, 1)); cfi->dict.corrupt = false; cfi->dict.fileTableOffset = ftell(cfi->f); int numFiles = static_cast<int>(lua_objlen(L, 2)); cfi->dict.numFiles = numFiles; // Write file offsets for(int i=0;i<numFiles;i++) { lua_pushinteger(L, i+1); lua_gettable(L, 2); size_t offs = static_cast<size_t>(lua_tointeger(L, -1)); lua_pop(L, 1); fwrite(&offs, sizeof(size_t), 1, cfi->f); } // Rewrite the header fseek(cfi->f, 0, SEEK_SET); fwrite(&cfi->dict, sizeof(cfi->dict), 1, cfi->f); fclose(cfi->f); return 0; }
20.689796
113
0.60071
[ "object" ]
fb8c61b6b5978825c0694cf718780fd48167dec8
40,579
cpp
C++
source/NavigationMesh.cpp
mackron/GTGameEngine
380d1e01774fe6bc2940979e4e5983deef0bf082
[ "BSD-3-Clause" ]
31
2015-03-19T08:44:48.000Z
2021-12-15T20:52:31.000Z
source/NavigationMesh.cpp
mackron/GTGameEngine
380d1e01774fe6bc2940979e4e5983deef0bf082
[ "BSD-3-Clause" ]
19
2015-07-09T09:02:44.000Z
2016-06-09T03:51:03.000Z
source/NavigationMesh.cpp
mackron/GTGameEngine
380d1e01774fe6bc2940979e4e5983deef0bf082
[ "BSD-3-Clause" ]
3
2017-10-04T23:38:18.000Z
2022-03-07T08:27:13.000Z
// Copyright (C) 2011 - 2014 David Reid. See included LICENCE. #include <GTGE/NavigationMesh.hpp> #include <GTGE/Scene.hpp> #include <GTGE/GTEngine.hpp> #include <GTGE/Recast/RecastAlloc.h> namespace GT { // A function taken from the Recast/Detour source for use when drawing the navigation mesh. float distancePtLine2d(const float* pt, const float* p, const float* q) { float pqx = q[0] - p[0]; float pqz = q[2] - p[2]; float dx = pt[0] - p[0]; float dz = pt[2] - p[2]; float d = pqx*pqx + pqz*pqz; float t = pqx*dx + pqz*dz; if (d != 0) t /= d; dx = p[0] + t*pqx - pt[0]; dz = p[2] + t*pqz - pt[2]; return dx*dx + dz*dz; } NavigationMesh::NavigationMesh() : config(), m_mesh(nullptr), detailMesh(nullptr), detourNavMesh(nullptr), navMeshQuery(nullptr), walkableHeight(2.0f), walkableRadius(0.85f), walkableSlope(27.5f), walkableClimb(0.25f), visualVA(Renderer::CreateVertexArray(VertexArrayUsage_Static, VertexFormat::P3T2N3)) { memset(&this->config, 0, sizeof(this->config)); this->SetCellSize(0.25f); this->config.tileSize = 32; this->config.maxSimplificationError = 2.0f; this->config.maxVertsPerPoly = 3; // Triangles. Good for rendering. this->config.detailSampleDist = 1.0f; this->config.detailSampleMaxError = 1.0f; this->config.minRegionArea = static_cast<int>(rcSqr(8.0f)); this->config.mergeRegionArea = static_cast<int>(rcSqr(20.0f)); } NavigationMesh::~NavigationMesh() { rcFreePolyMesh(m_mesh); rcFreePolyMeshDetail(this->detailMesh); dtFreeNavMesh(this->detourNavMesh); dtFreeNavMeshQuery(this->navMeshQuery); Renderer::DeleteVertexArray(this->visualVA); } bool NavigationMesh::Build(const Scene &scene) { bool successful = false; glm::vec3 aabbMin; glm::vec3 aabbMax; scene.GetAABB(aabbMin, aabbMax); this->config.walkableHeight = static_cast<int>(ceilf( this->walkableHeight / this->config.ch)); this->config.walkableRadius = static_cast<int>(floorf(this->walkableRadius / this->config.cs)); this->config.walkableSlopeAngle = this->walkableSlope; this->config.walkableClimb = static_cast<int>(ceilf(this->walkableClimb / this->config.ch)); //this->config.borderSize = this->config.walkableRadius + 3; //this->config.width = this->config.tileSize + this->config.borderSize * 2; //this->config.height = this->config.tileSize + this->config.borderSize * 2; rcVcopy(this->config.bmin, &aabbMin[0]); rcVcopy(this->config.bmax, &aabbMax[0]); rcCalcGridSize(this->config.bmin, this->config.bmax, this->config.cs, &this->config.width, &this->config.height); rcFreePolyMesh(m_mesh); m_mesh = nullptr; rcFreePolyMeshDetail(this->detailMesh); this->detailMesh = nullptr; // The context. This only exists so we can pass it around to the rc* functions. We get a failed assertion if we pass null, unfortunately. rcContext context; // NOTE: WE WILL CRASH IF THERE IS A STATIC PLANE IN THE SCENE. NEED TO FIX. // We need a heightfield... auto heightfield = rcAllocHeightfield(); assert(heightfield != nullptr); if (rcCreateHeightfield(&context, *heightfield, this->config.width, this->config.height, this->config.bmin, this->config.bmax, this->config.cs, this->config.ch)) { // Here is where we create the geometric data for the applicable scene nodes. For now we will look only at static meshes, but we will consider // obstacles later on. auto &nodes = scene.GetSceneNodes(); for (size_t i = 0; i < nodes.GetCount(); ++i) { auto node = nodes.GetSceneNodeAtIndex(i); assert(node != nullptr); { auto dynamics = node->GetComponent<DynamicsComponent>(); if (dynamics != nullptr && dynamics->IsNavigationMeshGenerationEnabled()) { CollisionShapeMeshBuilder mesh; mesh.Build(dynamics->GetCollisionShape(), dynamics->GetNode().GetWorldTransformWithoutScale()); // Don't want to include the scale in the transform because shapes are already pre-scaled. // With the mesh information retrieved we can now rasterize the mesh on the heightfield. auto vertices = mesh.GetVertexData(); auto vertexCount = mesh.GetVertexCount(); auto indices = reinterpret_cast<const int*>(mesh.GetIndexData()); auto indexCount = mesh.GetIndexCount(); auto triangleCount = indexCount / 3; //auto walkableAreas = new unsigned char[triangleCount]; auto walkableAreas = static_cast<unsigned char*>(malloc(sizeof(unsigned char) * triangleCount)); memset(walkableAreas, 0, triangleCount * sizeof(unsigned char)); rcMarkWalkableTriangles(&context, this->config.walkableSlopeAngle, vertices, vertexCount, indices, triangleCount, walkableAreas); rcRasterizeTriangles(&context, vertices, vertexCount, indices, walkableAreas, triangleCount, *heightfield, this->config.walkableClimb); free(walkableAreas); //delete [] walkableAreas; //auto mesh = dynamics->CreateCollisionShapeMesh(true); // <-- 'true' means to apply the scene node's transformation. //if (mesh != nullptr) { //delete mesh; } } } } // By this point we will have the triangles rasterized. Now we filter a bunch of stuff. rcFilterLowHangingWalkableObstacles(&context, this->config.walkableClimb, *heightfield); rcFilterLedgeSpans(&context, this->config.walkableHeight, this->config.walkableClimb, *heightfield); rcFilterWalkableLowHeightSpans(&context, this->config.walkableHeight, *heightfield); // Here is where we create the compact heightfield. After this is done we won't need the original heightfield anymore. auto compactHeightfield = rcAllocCompactHeightfield(); assert(compactHeightfield != nullptr); if (rcBuildCompactHeightfield(&context, this->config.walkableHeight, this->config.walkableClimb, *heightfield, *compactHeightfield)) { rcErodeWalkableArea(&context, this->config.walkableRadius, *compactHeightfield); rcBuildDistanceField(&context, *compactHeightfield); rcBuildRegions(&context, *compactHeightfield, this->config.borderSize, this->config.minRegionArea, this->config.mergeRegionArea); // In order to build the polygond mesh we'll need contours. auto contours = rcAllocContourSet(); assert(contours != nullptr); if (rcBuildContours(&context, *compactHeightfield, this->config.maxSimplificationError, this->config.maxEdgeLen, *contours)) { m_mesh = rcAllocPolyMesh(); assert(m_mesh != nullptr); if (rcBuildPolyMesh(&context, *contours, this->config.maxVertsPerPoly, *m_mesh)) { // Now we create the detail mesh. this->detailMesh = rcAllocPolyMeshDetail(); assert(this->detailMesh != nullptr); if (rcBuildPolyMeshDetail(&context, *m_mesh, *compactHeightfield, this->config.detailSampleDist, this->config.detailSampleMaxError, *this->detailMesh)) { // Update poly flags from areas. for (int i = 0; i < m_mesh->npolys; ++i) { if (m_mesh->areas[i] == RC_WALKABLE_AREA) { m_mesh->areas[i] = 1; m_mesh->flags[i] = 1; } } // If we've made it here we can now create the detour navigation mesh. dtNavMeshCreateParams params; memset(&params, 0, sizeof(params)); params.cs = this->config.cs; params.ch = this->config.ch; params.buildBvTree = true; params.verts = m_mesh->verts; params.vertCount = m_mesh->nverts; params.polys = m_mesh->polys; params.polyAreas = m_mesh->areas; params.polyFlags = m_mesh->flags; params.polyCount = m_mesh->npolys; params.nvp = m_mesh->nvp; params.detailMeshes = this->detailMesh->meshes; params.detailVerts = this->detailMesh->verts; params.detailVertsCount = this->detailMesh->nverts; params.detailTris = this->detailMesh->tris; params.detailTriCount = this->detailMesh->ntris; params.walkableHeight = this->walkableHeight; params.walkableRadius = this->walkableRadius; params.walkableClimb = this->walkableClimb; rcVcopy(params.bmin, m_mesh->bmin); rcVcopy(params.bmax, m_mesh->bmax); unsigned char* navData = nullptr; int navDataSize = 0; if (dtCreateNavMeshData(&params, &navData, &navDataSize)) { dtFreeNavMesh(this->detourNavMesh); this->detourNavMesh = dtAllocNavMesh(); assert(this->detourNavMesh != nullptr); dtStatus status = this->detourNavMesh->init(navData, navDataSize, DT_TILE_FREE_DATA); if (!dtStatusFailed(status)) { // Finally we're going to create the query object so we can do pathfinding queries. dtFreeNavMeshQuery(this->navMeshQuery); this->navMeshQuery = dtAllocNavMeshQuery(); assert(this->navMeshQuery); if (this->navMeshQuery->init(this->detourNavMesh, 512)) { successful = true; } else { g_Context->LogErrorf("NavigationMesh: Failed to init nav mesh query object."); } } else { dtFree(navData); g_Context->LogErrorf("NavigationMesh: Failed to init detail nav mesh."); } } else { dtFree(navData); g_Context->LogErrorf("NavigationMesh: Error creating Detour nav mesh data."); } } else { g_Context->LogErrorf("NavigationMesh: Error creating detail mesh."); } } else { g_Context->LogErrorf("NavigationMesh: Error creating main navigation mesh."); } } else { g_Context->LogErrorf("NavigationMesh: Error creating contours."); } rcFreeContourSet(contours); } else { g_Context->LogErrorf("NavigationMesh: Error creating compact heightfield."); } rcFreeCompactHeightfield(compactHeightfield); } else { g_Context->LogErrorf("NavigationMesh: Error creating heightfield."); } rcFreeHeightField(heightfield); // Here we will rebuild the visual vertex array. if (successful) { this->RebuildVisualVA(); } return successful; } void NavigationMesh::SetCellSize(float size) { this->config.cs = size; this->config.ch = size; } void NavigationMesh::SetWalkableHeight(float height) { this->walkableHeight = height; } void NavigationMesh::SetWalkableRadius(float radius) { this->walkableRadius = radius; } void NavigationMesh::SetWalkableSlope(float angle) { this->walkableSlope = angle; } void NavigationMesh::SetWalkableClimb(float height) { this->walkableClimb = height; } float NavigationMesh::GetWalkableHeight() const { return this->walkableHeight; } float NavigationMesh::GetWalkableRadius() const { return this->walkableRadius; } float NavigationMesh::GetWalkableSlope() const { return this->walkableSlope; } float NavigationMesh::GetWalkableClimb() const { return this->walkableClimb; } bool NavigationMesh::FindPath(const glm::vec3 &start, const glm::vec3 &end, Vector<glm::vec3> &output) { bool success = false; if (this->navMeshQuery != nullptr) { dtQueryFilter filter; glm::vec3 extents(this->walkableRadius * 2.0f, this->walkableHeight * 2.0f, this->walkableRadius * 2.0f); // We first need to find the polygons we should start and end on. dtPolyRef nearestPolyStart; dtPolyRef nearestPolyEnd; float nearestPointStart[3]; float nearestPointEnd[3]; if (!dtStatusFailed(this->navMeshQuery->findNearestPoly(&start[0], &extents[0], &filter, &nearestPolyStart, nearestPointStart))) { if (!dtStatusFailed(this->navMeshQuery->findNearestPoly(&end[0], &extents[0], &filter, &nearestPolyEnd, nearestPointEnd))) { // We have our start and end points, so now we need to find the polys making up a path between the two points. dtPolyRef path[128]; int pathCount; if (!dtStatusFailed(this->navMeshQuery->findPath(nearestPolyStart, nearestPolyEnd, nearestPointStart, nearestPointEnd, &filter, path, &pathCount, 128))) { // We have the path, so now we find a straight line between the path. This will return the points that we can use for output. float* straightPath = new float[pathCount * 3]; int straightPathCount; if (!dtStatusFailed(this->navMeshQuery->findStraightPath(nearestPointStart, nearestPointEnd, path, pathCount, straightPath, nullptr, nullptr, &straightPathCount, pathCount))) { // Now we need to append our results to the output list. for (int i = 0; i < straightPathCount; ++i) { auto sourcePoint = straightPath + (i * 3); output.PushBack(glm::vec3(sourcePoint[0], sourcePoint[1], sourcePoint[2])); } // If nearestPolyStart and nearestPolyEnd are both the same, it means we're navigating over the same poly. In this case, straightPathCount will // be set to 1 which means the end point will not be copied over by default. To fix, we just do the appropriate checks here and do it manually. if (nearestPolyStart == nearestPolyEnd && straightPathCount == 1) { output.PushBack(glm::vec3(nearestPointEnd[0], nearestPointEnd[1], nearestPointEnd[2])); } success = true; } delete [] straightPath; } } } } return success; } void NavigationMesh::BuildMeshVisualization(MeshBuilderP3 &mainMesh, MeshBuilderP3 &innerEdgeMesh, MeshBuilderP3 &outerEdgeMesh) const { mainMesh.Clear(); innerEdgeMesh.Clear(); outerEdgeMesh.Clear(); if (this->detourNavMesh != nullptr) { for (int i = 0; i < this->detourNavMesh->getMaxTiles(); ++i) { auto tile = const_cast<const dtNavMesh*>(this->detourNavMesh)->getTile(i); if (tile->header != nullptr) { // Main mesh. for (int j = 0; j < tile->header->polyCount; ++j) { auto &poly = tile->polys[j]; auto &pd = tile->detailMeshes[j]; if (poly.getType() != DT_POLYTYPE_OFFMESH_CONNECTION) { // Main mesh. for (int k = 0; k < pd.triCount; ++k) { const unsigned char* t = &tile->detailTris[(pd.triBase+k) * 4]; for (int l = 0; l < 3; ++l) { float* vertex = nullptr; if (t[l] < poly.vertCount) { vertex = &tile->verts[poly.verts[t[l]] * 3]; } else { vertex = &tile->detailVerts[(pd.vertBase + t[l] - poly.vertCount) * 3]; } mainMesh.EmitVertex(glm::vec3(vertex[0], vertex[1], vertex[2])); } } // Inner edges mesh. for (int iVert = 0; iVert < poly.vertCount; ++iVert) { const auto v0 = &tile->verts[poly.verts[iVert] * 3]; const auto v1 = &tile->verts[poly.verts[(iVert + 1) % poly.vertCount] * 3]; for (int k = 0; k < pd.triCount; ++k) { const auto t = &tile->detailTris[(pd.triBase + k) * 4]; const float* tv[3]; for (int m = 0; m < 3; ++m) { if (t[m] < poly.vertCount) { tv[m] = &tile->verts[poly.verts[t[m]] * 3]; } else { tv[m] = &tile->detailVerts[(pd.vertBase+(t[m] - poly.vertCount)) * 3]; } } for (int m = 0, n = 2; m < 3; n = m++) { if (((t[3] >> (n * 2)) & 0x3) != 0) // Skip inner detail edges. { if (distancePtLine2d(tv[n], v0, v1) < 0.01f && distancePtLine2d(tv[m], v0, v1) < 0.01f) { innerEdgeMesh.EmitVertex(glm::vec3(tv[n][0], tv[n][1], tv[n][2])); innerEdgeMesh.EmitVertex(glm::vec3(tv[m][0], tv[m][1], tv[m][2])); } } } } } // Outer edges mesh. for (int iVert = 0; iVert < poly.vertCount; ++iVert) { if (poly.neis[iVert] == 0) { const auto v0 = &tile->verts[poly.verts[iVert] * 3]; const auto v1 = &tile->verts[poly.verts[(iVert + 1) % poly.vertCount] * 3]; for (int k = 0; k < pd.triCount; ++k) { const auto t = &tile->detailTris[(pd.triBase + k) * 4]; const float* tv[3]; for (int m = 0; m < 3; ++m) { if (t[m] < poly.vertCount) { tv[m] = &tile->verts[poly.verts[t[m]] * 3]; } else { tv[m] = &tile->detailVerts[(pd.vertBase+(t[m] - poly.vertCount)) * 3]; } } for (int m = 0, n = 2; m < 3; n = m++) { if (((t[3] >> (n * 2)) & 0x3) != 0) // Skip inner detail edges. { if (distancePtLine2d(tv[n], v0, v1) < 0.01f && distancePtLine2d(tv[m], v0, v1) < 0.01f) { outerEdgeMesh.EmitVertex(glm::vec3(tv[n][0], tv[n][1], tv[n][2])); outerEdgeMesh.EmitVertex(glm::vec3(tv[m][0], tv[m][1], tv[m][2])); } } } } } } } } } } } } ///////////////////////////////////////////// // Serialization/Deserialization void NavigationMesh::Serialize(Serializer &serializer) const { BasicSerializer intermediarySerializer; Serialization::ChunkHeader header; // General variables. { intermediarySerializer.Clear(); intermediarySerializer.Write(this->config); intermediarySerializer.Write(this->walkableHeight); intermediarySerializer.Write(this->walkableRadius); intermediarySerializer.Write(this->walkableSlope); intermediarySerializer.Write(this->walkableClimb); header.id = Serialization::ChunkID_NavigationMesh_Main; header.version = 1; header.sizeInBytes = intermediarySerializer.GetBufferSizeInBytes(); serializer.Write(header); serializer.Write(intermediarySerializer.GetBuffer(), header.sizeInBytes); } // The recast poly-mesh. if (m_mesh != nullptr) { intermediarySerializer.Clear(); intermediarySerializer.Write(static_cast<int32_t>(m_mesh->nverts)); intermediarySerializer.Write(static_cast<int32_t>(m_mesh->npolys)); intermediarySerializer.Write(static_cast<int32_t>(m_mesh->maxpolys)); intermediarySerializer.Write(static_cast<int32_t>(m_mesh->nvp)); intermediarySerializer.Write(static_cast<float>(m_mesh->bmin[0])); intermediarySerializer.Write(static_cast<float>(m_mesh->bmin[1])); intermediarySerializer.Write(static_cast<float>(m_mesh->bmin[2])); intermediarySerializer.Write(static_cast<float>(m_mesh->bmax[0])); intermediarySerializer.Write(static_cast<float>(m_mesh->bmax[1])); intermediarySerializer.Write(static_cast<float>(m_mesh->bmax[2])); intermediarySerializer.Write(static_cast<float>(m_mesh->cs)); intermediarySerializer.Write(static_cast<float>(m_mesh->ch)); intermediarySerializer.Write(static_cast<int32_t>(m_mesh->borderSize)); intermediarySerializer.Write(m_mesh->verts, sizeof(uint16_t) * m_mesh->nverts * 3); // <-- 3 components for each vertex (x, y, z). intermediarySerializer.Write(m_mesh->polys, sizeof(uint16_t) * m_mesh->maxpolys * 2 * m_mesh->nvp); intermediarySerializer.Write(m_mesh->regs, sizeof(uint16_t) * m_mesh->maxpolys); intermediarySerializer.Write(m_mesh->flags, sizeof(uint16_t) * m_mesh->maxpolys); intermediarySerializer.Write(m_mesh->areas, sizeof(uint8_t) * m_mesh->maxpolys); header.id = Serialization::ChunkID_NavigationMesh_RecastPolyMesh; header.version = 1; header.sizeInBytes = intermediarySerializer.GetBufferSizeInBytes(); serializer.Write(header); serializer.Write(intermediarySerializer.GetBuffer(), header.sizeInBytes); } // The detour nav-mesh if (this->detourNavMesh != nullptr) { intermediarySerializer.Clear(); int32_t tileCount = 0; for (int iTile = 0; iTile < this->detourNavMesh->getMaxTiles(); ++iTile) { auto tile = const_cast<const dtNavMesh*>(this->detourNavMesh)->getTile(iTile); if (tile != nullptr && tile->header != nullptr && tile->dataSize > 0) { tileCount += 1; } } auto params = this->detourNavMesh->getParams(); assert(params != nullptr); { intermediarySerializer.Write(params->orig[0]); intermediarySerializer.Write(params->orig[1]); intermediarySerializer.Write(params->orig[2]); intermediarySerializer.Write(params->tileWidth); intermediarySerializer.Write(params->tileHeight); intermediarySerializer.Write(static_cast<int32_t>(params->maxTiles)); intermediarySerializer.Write(static_cast<int32_t>(params->maxPolys)); } intermediarySerializer.Write(tileCount); for (int iTile = 0; iTile < this->detourNavMesh->getMaxTiles(); ++iTile) { auto tile = const_cast<const dtNavMesh*>(this->detourNavMesh)->getTile(iTile); if (tile != nullptr && tile->header != nullptr && tile->dataSize > 0) { intermediarySerializer.Write(static_cast<uint32_t>(this->detourNavMesh->getTileRef(tile))); intermediarySerializer.Write(static_cast<uint32_t>(tile->dataSize)); intermediarySerializer.Write(tile->data, static_cast<size_t>(tile->dataSize)); } } header.id = Serialization::ChunkID_NavigationMesh_DetourNavMesh; header.version = 1; header.sizeInBytes = intermediarySerializer.GetBufferSizeInBytes(); serializer.Write(header); serializer.Write(intermediarySerializer.GetBuffer(), header.sizeInBytes); } // Null-terminating chunk. { header.id = Serialization::ChunkID_Null; header.version = 1; header.sizeInBytes = 0; serializer.Write(header); } } bool NavigationMesh::Deserialize(Deserializer &deserializer) { bool successful = true; // We keep looping until we hit the null-terminating chunk. Serialization::ChunkHeader header; while (deserializer.Read(&header, sizeof(header)) == sizeof(header) && header.id != Serialization::ChunkID_Null) { switch (header.id) { case Serialization::ChunkID_NavigationMesh_Main: { if (header.version == 1) { //deserializer.Seek(header.sizeInBytes); deserializer.Read(this->config); deserializer.Read(this->walkableHeight); deserializer.Read(this->walkableRadius); deserializer.Read(this->walkableSlope); deserializer.Read(this->walkableClimb); } else { g_Context->Logf("Error deserializing main chunk of navigation mesh. Unsupported version (%d).", header.version); successful = false; } break; } case Serialization::ChunkID_NavigationMesh_RecastPolyMesh: { if (header.version == 1) { //deserializer.Seek(header.sizeInBytes); // Old mesh must be deleted. if (m_mesh != nullptr) { rcFreePolyMesh(m_mesh); } // New mesh must be created. m_mesh = rcAllocPolyMesh(); int32_t nverts; int32_t npolys; int32_t maxpolys; int32_t nvp; deserializer.Read(nverts); deserializer.Read(npolys); deserializer.Read(maxpolys); deserializer.Read(nvp); float bmin[3]; float bmax[3]; deserializer.Read(bmin[0]); deserializer.Read(bmin[1]); deserializer.Read(bmin[2]); deserializer.Read(bmax[0]); deserializer.Read(bmax[1]); deserializer.Read(bmax[2]); float cs; float ch; deserializer.Read(cs); deserializer.Read(ch); int32_t borderSize; deserializer.Read(borderSize); Vector<uint16_t> verts; Vector<uint16_t> polys; Vector<uint16_t> regs; Vector<uint16_t> flags; Vector<uint8_t> areas; verts.Resize(nverts * 3); deserializer.Read(verts.buffer, sizeof(uint16_t) * verts.count); polys.Resize(npolys * 2 * nvp); deserializer.Read(polys.buffer, sizeof(uint16_t) * polys.count); regs.Resize(npolys); deserializer.Read(regs.buffer, sizeof(uint16_t) * regs.count); flags.Resize(npolys); deserializer.Read(flags.buffer, sizeof(uint16_t) * flags.count); areas.Resize(npolys); deserializer.Read(areas.buffer, sizeof(uint8_t) * areas.count); // I'm unaware of a public API for creating a mesh from raw data like this, so we're going to copy the implementation of // rcCopyPolyMesh(). We use the same memory allocation routines as that function. m_mesh->nverts = static_cast<int>(nverts); m_mesh->npolys = static_cast<int>(npolys); m_mesh->maxpolys = static_cast<int>(maxpolys); m_mesh->nvp = static_cast<int>(nvp); m_mesh->bmin[0] = bmin[0]; m_mesh->bmin[1] = bmin[1]; m_mesh->bmin[2] = bmin[2]; m_mesh->bmax[0] = bmax[0]; m_mesh->bmax[1] = bmax[1]; m_mesh->bmax[2] = bmax[2]; m_mesh->cs = cs; m_mesh->ch = ch; m_mesh->borderSize = static_cast<int>(borderSize); m_mesh->verts = static_cast<unsigned short*>(rcAlloc(sizeof(unsigned short) * verts.count, RC_ALLOC_PERM)); m_mesh->polys = static_cast<unsigned short*>(rcAlloc(sizeof(unsigned short) * polys.count, RC_ALLOC_PERM)); m_mesh->regs = static_cast<unsigned short*>(rcAlloc(sizeof(unsigned short) * regs.count, RC_ALLOC_PERM)); m_mesh->flags = static_cast<unsigned short*>(rcAlloc(sizeof(unsigned short) * flags.count, RC_ALLOC_PERM)); m_mesh->areas = static_cast<unsigned char* >(rcAlloc(sizeof(unsigned char) * areas.count, RC_ALLOC_PERM)); memcpy(m_mesh->verts, verts.buffer, sizeof(unsigned short) * verts.count); memcpy(m_mesh->polys, polys.buffer, sizeof(unsigned short) * polys.count); memcpy(m_mesh->regs, regs.buffer, sizeof(unsigned short) * regs.count); memcpy(m_mesh->flags, flags.buffer, sizeof(unsigned short) * flags.count); memcpy(m_mesh->areas, areas.buffer, sizeof(unsigned char) * areas.count); } else { g_Context->Logf("Error deserializing Recast Poly Mesh chunk of navigation mesh. Unsupported version (%d).", header.version); successful = false; } break; } case Serialization::ChunkID_NavigationMesh_DetourNavMesh: { if (header.version == 1) { //deserializer.Seek(header.sizeInBytes); // Old mesh must be deleted. if (this->detourNavMesh != nullptr) { dtFreeNavMesh(this->detourNavMesh); } // New mesh must be created. this->detourNavMesh = dtAllocNavMesh(); dtNavMeshParams params; deserializer.Read(params.orig[0]); deserializer.Read(params.orig[1]); deserializer.Read(params.orig[2]); deserializer.Read(params.tileWidth); deserializer.Read(params.tileHeight); int32_t maxTiles; int32_t maxPolys; deserializer.Read(maxTiles); deserializer.Read(maxPolys); params.maxTiles = static_cast<int>(maxTiles); params.maxPolys = static_cast<int>(maxPolys); if (this->detourNavMesh->init(&params)) { int32_t tileCount; deserializer.Read(tileCount); for (int32_t iTile = 0; iTile < tileCount; ++iTile) { uint32_t tileRef; deserializer.Read(tileRef); uint32_t dataSize; deserializer.Read(dataSize); auto data = rcAlloc(dataSize, RC_ALLOC_PERM); assert(data != nullptr); { deserializer.Read(data, dataSize); // Everything has been read, now we just read the tile. this->detourNavMesh->addTile(reinterpret_cast<unsigned char*>(data), static_cast<int>(dataSize), DT_TILE_FREE_DATA, static_cast<dtTileRef>(tileRef), nullptr); } } } else { // Failed to initialize the nav mesh for whatever reason. We'll skip over the rest of the chunk. deserializer.Seek(header.sizeInBytes - 28); } } else { g_Context->Logf("Error deserializing Detour Nav Mesh chunk of navigation mesh. Unsupported version (%d).", header.version); successful = false; } break; } default: { // We don't know the chunk. It needs to be skipped. assert(false); deserializer.Seek(header.sizeInBytes); break; } } } return successful; } ///////////////////////////////////////////// // Private void NavigationMesh::RebuildVisualVA() { // We use a mesh builder here. MeshBuilderP3T2N3 builder; for (int i = 0; i < this->detourNavMesh->getMaxTiles(); ++i) { auto tile = const_cast<const dtNavMesh*>(this->detourNavMesh)->getTile(i); if (tile->header != nullptr) { for (int j = 0; j < tile->header->polyCount; ++j) { auto &poly = tile->polys[j]; if (poly.getType() != DT_POLYTYPE_OFFMESH_CONNECTION) { auto &pd = tile->detailMeshes[j]; for (int k = 0; k < pd.triCount; ++k) { const unsigned char* t = &tile->detailTris[(pd.triBase+k)*4]; for (int l = 0; l < 3; ++l) { float* vertex = nullptr; if (t[l] < poly.vertCount) { vertex = &tile->verts[poly.verts[t[l]] * 3]; } else { vertex = &tile->detailVerts[(pd.vertBase + t[l] - poly.vertCount) * 3]; } builder.EmitVertex(glm::vec3(vertex[0], vertex[1], vertex[2]), glm::vec2(0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); } } } } } } // Now we can set the VA data. this->visualVA->SetData(builder.GetVertexData(), builder.GetVertexCount(), builder.GetIndexData(), builder.GetIndexCount()); } }
44.543359
214
0.466325
[ "mesh", "object", "vector", "transform" ]
651efd3ad6a3fe0e83596d92164854b19a2bd88c
3,708
cpp
C++
Pod/Classes/algorithms/standard/spline.cpp
jbloit/iosEssentia
785ba29e8178942b396575dd3872bdf3d5d63cd5
[ "MIT" ]
null
null
null
Pod/Classes/algorithms/standard/spline.cpp
jbloit/iosEssentia
785ba29e8178942b396575dd3872bdf3d5d63cd5
[ "MIT" ]
null
null
null
Pod/Classes/algorithms/standard/spline.cpp
jbloit/iosEssentia
785ba29e8178942b396575dd3872bdf3d5d63cd5
[ "MIT" ]
null
null
null
/* * Copyright (C) 2006-2013 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation (FSF), either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include "spline.h" using namespace std; using namespace essentia; using namespace standard; const char* Spline::name = "Spline"; const char* Spline::description = DOC("Evaluates a piecewise spline of type b, beta or quadratic.\n" "The input value, i.e. the point at which the spline is to be evaluated typically should be between xPoins[0] and xPoinst[size-1]. If the value lies outside this range, extrapolation is used." "\n" "Regarding spline types:\n" " - B: evaluates a cubic B spline approximant.\n" " - Beta: evaluates a cubic beta spline approximant. For beta splines parameters 'beta1' and 'beta2' can be supplied. For no bias set beta1 to 1 and for no tension set beta2 to 0. Note that if beta1=1 and beta2=0, the cubic beta becomes a cubic B spline. On the other hand if beta1=1 and beta2 is large the beta spline turns into a linear spline.\n" " - Quadratic: evaluates a piecewise quadratic spline at a point. Note that size of input must be odd.\n" "\n" "References:\n" " [1] Spline interpolation - Wikipedia, the free encyclopedia,\n" " http://en.wikipedia.org/wiki/Spline_interpolation"); void Spline::compute() { const double& xInput = _xInput.get(); Real& yOutput = _yOutput.get(); switch (_type) { case B: yOutput=(Real)spline_b_val(_xPoints.size(), &_xPoints[0], &_yPoints[0], xInput); return; case BETA: yOutput=(Real)spline_beta_val(_beta1, _beta2, (int)_xPoints.size(), &_xPoints[0], &_yPoints[0], xInput); return; case QUADRATIC: double y; double dy; //first_derivative (not used) spline_quadratic_val((int)_xPoints.size(), &_xPoints[0], &_yPoints[0], xInput, &y, &dy); yOutput=(Real)y; return; default: // should never get here throw EssentiaException("Spline: unknown spline type"); } } void Spline::configure() { string type = parameter("type").toString(); if (type == "b") _type = B; else if (type == "beta") _type = BETA; else _type = QUADRATIC;/*if (type == "quadratic")*/ // check already done in declareParameter vector<Real> x = parameter("xPoints").toVectorReal(); vector<Real> y = parameter("yPoints").toVectorReal(); if (x.size() != y.size() ) { throw EssentiaException("parameter 'xPoints' must have the same size than parameter 'yPoints')"); } int size = x.size(); for (int i=0; i<size-1; ++i) { if (x[i]>=x[i+1]) { throw EssentiaException("parameter 'xPoints' must be in ascendant order and cannot contain duplicates)"); } } _xPoints.resize(size); _yPoints.resize(size); if ((size&1)==0 && _type==QUADRATIC) { throw EssentiaException("size of input must be odd when spline type is quadratic"); } for (int i=0; i<size; ++i) { _xPoints[i] = double(x[i]); _yPoints[i] = double(y[i]); } // only used for type beta: _beta1 = (double)parameter("beta1").toReal(); _beta2 = (double)parameter("beta2").toReal(); }
39.870968
350
0.68959
[ "vector" ]
651f08bd6f2abd6839191087a63c14707338fbb9
4,662
cpp
C++
src/file/rlsm.cpp
moonshadow565/bincollector
e627bd858aa6da4c4fccf7f671e00d400a6576cd
[ "MIT" ]
null
null
null
src/file/rlsm.cpp
moonshadow565/bincollector
e627bd858aa6da4c4fccf7f671e00d400a6576cd
[ "MIT" ]
null
null
null
src/file/rlsm.cpp
moonshadow565/bincollector
e627bd858aa6da4c4fccf7f671e00d400a6576cd
[ "MIT" ]
1
2021-04-25T09:46:07.000Z
2021-04-25T09:46:07.000Z
#include <common/bt_error.hpp> #include <common/mmap.hpp> #include <file/hashlist.hpp> #include <file/raw.hpp> #include <file/rlsm.hpp> #include <file/rlsm/manifest.hpp> using namespace file; struct FileRLSM::Reader final : IReader { Reader(rlsm::FileInfo const& info, fs::path const& path) : info_(info) , path_(path) { bt_trace(u8"path: {}", path.generic_u8string()); bt_rethrow(data_.open(path).unwrap()); } std::size_t size() const override { return info_.size_uncompressed; } std::span<char const> read(std::size_t offset, std::size_t size) override { bt_assert(data_.span().size() >= offset + size); bt_assert(size + offset == 0 || data_.data()); // empty files don't need to be open return data_.span().subspan(offset, size); } private: rlsm::FileInfo info_; fs::path path_; MMap<char const> data_; }; FileRLSM::FileRLSM(rlsm::FileInfo const& info, fs::path const& base, std::shared_ptr<Location> source_location) : info_(info) , base_(base) , location_(std::make_shared<Location>(source_location, fs::path(u8"releases") / info_.version.string() / u8"files" / info_.name)) {} std::u8string FileRLSM::find_name([[maybe_unused]] HashList& hashes) { return info_.name; } std::uint64_t FileRLSM::find_hash(HashList& hashes) { return hashes.find_hash_by_name(info_.name); } std::u8string FileRLSM::find_extension(HashList& hashes) { return hashes.find_extension_by_name(info_.name); } std::u8string FileRLSM::get_link() { return {}; } std::size_t FileRLSM::size() const { return info_.size_uncompressed; } std::u8string FileRLSM::id() const { std::uint64_t c[2]; std::memcpy(&c, &info_.checksum, 16); auto result = fmt::format(u8"{:016x}{:016x}", c[1], c[0]); std::reverse(result.begin(), result.end()); return fmt::format(u8"{}.md5", result); } std::shared_ptr<Location> FileRLSM::location() const { return location_; } std::shared_ptr<IReader> FileRLSM::open() { if (auto result = reader_.lock()) { return result; } else { reader_ = (result = std::make_shared<Reader>(info_, base_ / location_->path)); return result; } } bool FileRLSM::is_wad() { auto const& name = info_.name; return name.ends_with(u8".wad") || name.ends_with(u8".client") || name.ends_with(u8".mobile"); } ManagerRLSM::ManagerRLSM(std::shared_ptr<IReader> source, fs::path const& cdn, std::set<std::u8string> const& langs, std::shared_ptr<Location> source_location) : location_(std::make_shared<Location>(source_location)) { auto manifest = rlsm::RLSMManifest::read(source->read()); auto const& project_name = manifest.names[manifest.header.project_name]; base_ = cdn / u8"projects" / project_name; location_->path = fs::path("projects") / project_name / u8"releases" / manifest.header.release_version.string() / "releasemanifest"; files_ = manifest.list_files(); (void)langs; } std::vector<std::shared_ptr<IFile>> ManagerRLSM::list() { auto result = std::vector<std::shared_ptr<IFile>>{}; result.reserve(files_.size()); for (auto const& entry: files_) { result.emplace_back(std::make_shared<FileRLSM>(entry, base_, location_)); } return result; } ManagerSLN::ManagerSLN(std::shared_ptr<IReader> source, fs::path const& cdn, std::set<std::u8string> const& langs, std::shared_ptr<Location> source_location) : location_(std::make_shared<Location>(source_location)) { auto manifest = sln::SLNManifest::read(source->read()); location_->path = fs::path("solutions") / manifest.solution_name / u8"releases" / manifest.solution_version / "solutionmanifest"; for (auto const& project: manifest.list_projects()) { if (!project.has_locale(langs)) { continue; } auto const path = cdn / u8"projects" / project.name / u8"releases" / project.version / u8"releasemanifest"; auto project_source = FileRAW::make_reader(path); managers_.emplace_back(std::make_unique<ManagerRLSM>(project_source, cdn, std::set<std::u8string>{}, location_)); } } std::vector<std::shared_ptr<IFile>> ManagerSLN::list() { auto result = std::vector<std::shared_ptr<IFile>>{}; for (auto const& manager: managers_) { auto files = manager->list(); result.insert(result.end(), files.begin(), files.end()); } return result; }
33.782609
136
0.634921
[ "vector" ]
6521115c5431b8c388845694585e426ba722f7cb
2,273
cpp
C++
monitor/ActionMonitor/ActiveDefaultAction.cpp
FFMG/myoddweb.piger
6c5e9dff6ab8e2e02d6990c1959450f087acf371
[ "MIT" ]
18
2016-03-04T15:44:24.000Z
2021-12-31T11:06:25.000Z
monitor/ActionMonitor/ActiveDefaultAction.cpp
FFMG/myoddweb.piger
6c5e9dff6ab8e2e02d6990c1959450f087acf371
[ "MIT" ]
49
2016-02-29T17:59:52.000Z
2019-05-05T04:59:26.000Z
monitor/ActionMonitor/ActiveDefaultAction.cpp
FFMG/myoddweb.piger
6c5e9dff6ab8e2e02d6990c1959450f087acf371
[ "MIT" ]
2
2016-07-30T10:17:12.000Z
2016-08-11T20:31:46.000Z
//This file is part of Myoddweb.Piger. // // Myoddweb.Piger is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Myoddweb.Piger is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Myoddweb.Piger. If not, see<https://www.gnu.org/licenses/gpl-3.0.en.html>. #include "stdafx.h" #include "ActiveDefaultAction.h" /** * \brief The Default active constructor * \param src the action that is now active. * \param hTopHWnd the window that was on top at the time the command was given. * \param szCommandLine the given command line that is, the words after the command itself * \param isPrivileged if this action is privileged or not. */ ActiveDefaultAction::ActiveDefaultAction(IApplication& application, const IAction& src, const HWND hTopHWnd, const std::wstring& szCommandLine, bool isPrivileged) : ActiveAction( application, src, hTopHWnd, szCommandLine, isPrivileged ) { } ActiveDefaultAction::~ActiveDefaultAction() { } bool ActiveDefaultAction::OnDeInitialize() { // nothing to do. return true; } bool ActiveDefaultAction::OnInitialize() { // all good return true; } void ActiveDefaultAction::OnExecuteInThread() { // we need to log that we are going to run this as a default. // we should always try and create an ActiveAction for each known extensions. // otherwise, who knows how this will run, (for example and swf extension might not be able to run). const auto szFile = File(); auto szExt = myodd::files::GetExtension( szFile );; auto szCommand = Command(); myodd::log::LogWarning(_T("Will try and execute the command '%s' from file '%s'"), szExt.c_str(), szCommand.c_str()); // join the two items together. std::vector<MYODD_STRING> argv; argv.push_back( szFile); argv.push_back( GetCommandLine() ); Execute(argv, IsPrivileged(), nullptr ); }
36.66129
164
0.731632
[ "vector" ]
65233b1ebde9838f3dfe74cb694f38b998e93f8f
3,827
hpp
C++
inc/UI/Button.hpp
barne856/3DSWMM
60dd2702c82857dcf4358b8d42a1fb430a568e90
[ "MIT" ]
null
null
null
inc/UI/Button.hpp
barne856/3DSWMM
60dd2702c82857dcf4358b8d42a1fb430a568e90
[ "MIT" ]
null
null
null
inc/UI/Button.hpp
barne856/3DSWMM
60dd2702c82857dcf4358b8d42a1fb430a568e90
[ "MIT" ]
null
null
null
#ifndef BUTTON #define BUTTON #include "Application/Application.hpp" #include "Meshes/Rectangle.hpp" #include "Materials/Flat.hpp" #include "Application/Renderer.hpp" #include "Meshes/Text.hpp" #include <iostream> #include <functional> class Button : public UIElement { public: Button(std::string label) { button_base = new Rectangle(); button_label = new Text(label); flat_material = new Flat(); } ~Button() { delete button_base; delete button_label; delete flat_material; } virtual void on_key(int key, int action) { } virtual void on_mouse_button(int button, int action) { if (button == GLFW_MOUSE_BUTTON_LEFT) { if (action == GLFW_PRESS) { input.left_mouse_down = true; if (is_inside(input.world_pos)) { callback_func(true); } } if (action == GLFW_RELEASE) { input.left_mouse_down = false; } } } virtual void on_mouse_move(int x, int y) { input.world_pos = screen_to_world_2D(x, y); } virtual void on_mouse_wheel(int pos) { // scroll widgets } virtual void render() { rescale(); Renderer::BEGIN(UI_camera()); flat_material->set_color(button_color_dark); Renderer::submit(button_base, flat_material); flat_material->set_color(button_color_light); Renderer::submit(button_label, flat_material); // no END() because this will be called inside END() } void rescale() { if (input.left_mouse_down && is_inside(input.world_pos)) { current_width -= click_speed * (current_width - button_click_width); current_height -= click_speed * (current_height - button_click_height); } else { current_width += click_speed * (button_width - current_width); current_height += click_speed * (button_height - current_height); } //scale meshes based on the bounds button_base->set_scale({current_width, current_height, 0.0f}); button_base->set_position({get_center(), 0.0f}); button_label->set_scale({label_scale, 2.0f * label_scale, 0.0f}); button_label->set_center({get_center(), 0.0f}); } void set_callback(void (*func)(bool)) { callback_func = func; } void reset_state() { input.world_pos = glm::vec2(0.0f); input.left_mouse_down = false; } bool is_inside(glm::vec2 world_pos) { glm::vec2 center = get_center(); if (world_pos.x >= (center.x - current_width/2.0f) && world_pos.x <= (center.x + current_width/2.0f) && world_pos.y >= (center.y - current_height/2.0f) && world_pos.y <= (center.y + current_height/2.0f) ) { return true; } return false; } private: // Button Rectangle *button_base; Text *button_label; float button_width = 128.0f * UI_scale(); float button_height = 32.0f * UI_scale(); float label_scale = 8.0f * UI_scale(); float button_click_width = 0.9f * button_width; float button_click_height = 0.9f * button_height; float current_width = button_width; float current_height = button_height; float click_speed = 0.4f; void (*callback_func)(bool); // Inputs from Callbacks struct WidgetInput { bool left_mouse_down = false; glm::vec2 world_pos; } input; // Colors Flat *flat_material; glm::vec4 button_color_light = glm::vec4(223 / 255.0, 230 / 255.0, 233 / 255.0, 1.0f); glm::vec4 button_color_dark = glm::vec4(45 / 255.0, 52 / 255.0, 54 / 255.0, 1.0f); }; #endif
28.992424
212
0.593154
[ "render" ]
6526f977708e538da60753e9053cebb2c2843e07
8,549
cpp
C++
deps/libgeos/geos/src/operation/IsSimpleOp.cpp
AmristarSolutions/node-gdal-next
8c0a7d9b26c240bf04abbf1b1de312b0691b3d88
[ "Apache-2.0" ]
57
2020-02-08T17:52:17.000Z
2021-10-14T03:45:09.000Z
deps/libgeos/geos/src/operation/IsSimpleOp.cpp
AmristarSolutions/node-gdal-next
8c0a7d9b26c240bf04abbf1b1de312b0691b3d88
[ "Apache-2.0" ]
47
2020-02-12T16:41:40.000Z
2021-09-28T22:27:56.000Z
deps/libgeos/geos/src/operation/IsSimpleOp.cpp
AmristarSolutions/node-gdal-next
8c0a7d9b26c240bf04abbf1b1de312b0691b3d88
[ "Apache-2.0" ]
8
2020-03-17T11:18:07.000Z
2021-10-14T03:45:15.000Z
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2009 Sandro Santilli <strk@kbt.io> * Copyright (C) 2001-2002 Vivid Solutions Inc. * Copyright (C) 2005 Refractions Research Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: operation/IsSimpleOp.java rev. 1.22 (JTS-1.10) * **********************************************************************/ #include <geos/operation/IsSimpleOp.h> //#include <geos/operation/EndpointInfo.h> #include <geos/algorithm/BoundaryNodeRule.h> #include <geos/algorithm/LineIntersector.h> #include <geos/geomgraph/GeometryGraph.h> #include <geos/geomgraph/Edge.h> #include <geos/geomgraph/EdgeIntersection.h> #include <geos/geomgraph/index/SegmentIntersector.h> #include <geos/geom/Geometry.h> #include <geos/geom/MultiPoint.h> #include <geos/geom/MultiLineString.h> #include <geos/geom/Polygon.h> #include <geos/geom/LinearRing.h> #include <geos/geom/Point.h> #include <geos/geom/GeometryCollection.h> #include <geos/geom/Coordinate.h> #include <geos/geom/util/LinearComponentExtracter.h> #include <set> #include <cassert> using namespace std; using namespace geos::algorithm; using namespace geos::geomgraph; using namespace geos::geomgraph::index; using namespace geos::geom; using namespace geos::geom::util; namespace geos { namespace operation { // geos.operation // This is supposedly a private of IsSimpleOp... class EndpointInfo { public: Coordinate pt; bool isClosed; int degree; EndpointInfo(const geom::Coordinate& newPt); const Coordinate& getCoordinate() const { return pt; } void addEndpoint(bool newIsClosed) { degree++; isClosed |= newIsClosed; } }; EndpointInfo::EndpointInfo(const Coordinate& newPt) { pt = newPt; isClosed = false; degree = 0; } // ----------------------------------------------------- /*public*/ IsSimpleOp::IsSimpleOp() : isClosedEndpointsInInterior(true), geom(nullptr), nonSimpleLocation() {} /*public*/ IsSimpleOp::IsSimpleOp(const Geometry& g) : isClosedEndpointsInInterior(true), geom(&g), nonSimpleLocation() {} /*public*/ IsSimpleOp::IsSimpleOp(const Geometry& g, const BoundaryNodeRule& boundaryNodeRule) : isClosedEndpointsInInterior(! boundaryNodeRule.isInBoundary(2)), geom(&g), nonSimpleLocation() {} /*public*/ bool IsSimpleOp::isSimple() { nonSimpleLocation.reset(); return computeSimple(geom); } /*public*/ bool IsSimpleOp::isSimple(const LineString* p_geom) { return isSimpleLinearGeometry(p_geom); } /*public*/ bool IsSimpleOp::isSimple(const MultiLineString* p_geom) { return isSimpleLinearGeometry(p_geom); } /*public*/ bool IsSimpleOp::isSimple(const MultiPoint* mp) { return isSimpleMultiPoint(*mp); } /*private*/ bool IsSimpleOp::isSimpleMultiPoint(const MultiPoint& mp) { if(mp.isEmpty()) { return true; } set<const Coordinate*, CoordinateLessThen> points; for(std::size_t i = 0, n = mp.getNumGeometries(); i < n; ++i) { const Point* pt = dynamic_cast<const Point*>(mp.getGeometryN(i)); assert(pt); const Coordinate* p = pt->getCoordinate(); if(points.find(p) != points.end()) { nonSimpleLocation.reset(new Coordinate(*p)); return false; } points.insert(p); } return true; } bool IsSimpleOp::isSimpleLinearGeometry(const Geometry* p_geom) { if(p_geom->isEmpty()) { return true; } GeometryGraph graph(0, p_geom); LineIntersector li; std::unique_ptr<SegmentIntersector> si(graph.computeSelfNodes(&li, true)); // if no self-intersection, must be simple if(!si->hasIntersection()) { return true; } if(si->hasProperIntersection()) { nonSimpleLocation.reset( new Coordinate(si->getProperIntersectionPoint()) ); return false; } if(hasNonEndpointIntersection(graph)) { return false; } if(isClosedEndpointsInInterior) { if(hasClosedEndpointIntersection(graph)) { return false; } } return true; } /*private*/ bool IsSimpleOp::hasNonEndpointIntersection(GeometryGraph& graph) { vector<Edge*>* edges = graph.getEdges(); for(vector<Edge*>::iterator i = edges->begin(); i < edges->end(); i++) { Edge* e = *i; auto maxSegmentIndex = e->getMaximumSegmentIndex(); EdgeIntersectionList& eiL = e->getEdgeIntersectionList(); for(const EdgeIntersection& ei : eiL) { if(!ei.isEndPoint(maxSegmentIndex)) { nonSimpleLocation.reset( new Coordinate(ei.getCoordinate()) ); return true; } } } return false; } /*private*/ bool IsSimpleOp::computeSimple(const geom::Geometry* g) { nonSimpleLocation.reset(); if(dynamic_cast<const LineString*>(g)) { return isSimpleLinearGeometry(g); } if(dynamic_cast<const LinearRing*>(g)) { return isSimpleLinearGeometry(g); } if(dynamic_cast<const MultiLineString*>(g)) { return isSimpleLinearGeometry(g); } if(dynamic_cast<const Polygon*>(g)) { return isSimplePolygonal(g); } const MultiPoint* mp = dynamic_cast<const MultiPoint*>(g); if(mp) { return isSimpleMultiPoint(*mp); } // This must be after MultiPoint test, as MultiPoint can // cast cleanly into GeometryCollection const GeometryCollection* gc = dynamic_cast<const GeometryCollection*>(g); if(gc) { return isSimpleGeometryCollection(gc); } // all other geometry types are simple by definition return true; } /*private*/ bool IsSimpleOp::isSimpleGeometryCollection(const geom::GeometryCollection* col) { for(const auto& g : *col) { if(!computeSimple(g.get())) { return false; } } return true; } /*private*/ bool IsSimpleOp::isSimplePolygonal(const geom::Geometry* g) { LineString::ConstVect rings; LinearComponentExtracter::getLines(*g, rings); for(const geom::LineString* ring : rings) { if(!isSimpleLinearGeometry(ring)) { return false; } } return true; } /*private*/ bool IsSimpleOp::hasClosedEndpointIntersection(GeometryGraph& graph) { map<const Coordinate*, EndpointInfo*, CoordinateLessThen> endPoints; vector<Edge*>* edges = graph.getEdges(); for(vector<Edge*>::iterator i = edges->begin(); i < edges->end(); i++) { Edge* e = *i; //int maxSegmentIndex=e->getMaximumSegmentIndex(); bool isClosed = e->isClosed(); const Coordinate* p0 = &e->getCoordinate(0); addEndpoint(endPoints, p0, isClosed); const Coordinate* p1 = &e->getCoordinate(e->getNumPoints() - 1); addEndpoint(endPoints, p1, isClosed); } map<const Coordinate*, EndpointInfo*, CoordinateLessThen>::iterator it = endPoints.begin(); for(; it != endPoints.end(); ++it) { EndpointInfo* eiInfo = it->second; if(eiInfo->isClosed && eiInfo->degree != 2) { nonSimpleLocation.reset( new Coordinate(eiInfo->getCoordinate()) ); it = endPoints.begin(); for(; it != endPoints.end(); ++it) { EndpointInfo* ep = it->second; delete ep; } return true; } } it = endPoints.begin(); for(; it != endPoints.end(); ++it) { EndpointInfo* ep = it->second; delete ep; } return false; } /*private*/ void IsSimpleOp::addEndpoint( map<const Coordinate*, EndpointInfo*, CoordinateLessThen>& endPoints, const Coordinate* p, bool isClosed) { map<const Coordinate*, EndpointInfo*, CoordinateLessThen>::iterator it = endPoints.find(p); EndpointInfo* eiInfo; if(it == endPoints.end()) { eiInfo = nullptr; } else { eiInfo = it->second; } if(eiInfo == nullptr) { eiInfo = new EndpointInfo(*p); endPoints[p] = eiInfo; } eiInfo->addEndpoint(isClosed); } } // namespace geos::operation } // namespace geos
24.21813
95
0.617967
[ "geometry", "vector" ]
653607b797c7ad53fd8f372f42468cad85cec9ed
4,607
cpp
C++
Source/Core/RenderAPI_old/VulkanAPI/Wrapper/VulkanBuffer.cpp
Cube219/CubeEngine_old2
d251d540a4fdbc993ec5c9183eb30ac4dc81d5be
[ "MIT" ]
null
null
null
Source/Core/RenderAPI_old/VulkanAPI/Wrapper/VulkanBuffer.cpp
Cube219/CubeEngine_old2
d251d540a4fdbc993ec5c9183eb30ac4dc81d5be
[ "MIT" ]
null
null
null
Source/Core/RenderAPI_old/VulkanAPI/Wrapper/VulkanBuffer.cpp
Cube219/CubeEngine_old2
d251d540a4fdbc993ec5c9183eb30ac4dc81d5be
[ "MIT" ]
null
null
null
#include "VulkanBuffer.h" #include <memory.h> #include "VulkanDevice.h" #include "EngineCore/Assertion.h" namespace cube { namespace render { VkBufferUsageFlags GetVkBufferUsageFlags(BufferTypeFlags typeBits) { VkBufferUsageFlags f = 0; if(typeBits.IsSet(BufferTypeFlag::Uniform)) f |= VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; if(typeBits.IsSet(BufferTypeFlag::Vertex)) f |= VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; if(typeBits.IsSet(BufferTypeFlag::Index)) f |= VK_BUFFER_USAGE_INDEX_BUFFER_BIT; if(typeBits.IsSet(BufferTypeFlag::TransferSource)) f |= VK_BUFFER_USAGE_TRANSFER_SRC_BIT; return f; } VulkanBuffer::VulkanBuffer(const SPtr<VulkanDevice>& device, BufferInitializer& initializer) : mDevice_ref(device), mMappedData(nullptr) { VkResult res; // Get total of aligned data size uint64_t totalDataSize = 0; uint64_t align = device->GetProperties().limits.minUniformBufferOffsetAlignment; uint64_t bufDataNum = initializer.bufferDatas.size(); mDataOffsets.resize(bufDataNum); mDataSizes.resize(bufDataNum); for(uint64_t i = 0; i < bufDataNum; i++) { mDataOffsets[i] = totalDataSize; mDataSizes[i] = initializer.bufferDatas[i].size; uint64_t alignedSize = initializer.bufferDatas[i].size + align - 1; alignedSize /= align; alignedSize *= align; totalDataSize += alignedSize; } mSize = totalDataSize; // Create buffer VkBufferCreateInfo bufferCreateInfo = {}; bufferCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferCreateInfo.pNext = nullptr; bufferCreateInfo.flags = 0; bufferCreateInfo.usage = GetVkBufferUsageFlags(initializer.type); bufferCreateInfo.size = totalDataSize; bufferCreateInfo.queueFamilyIndexCount = 0; bufferCreateInfo.pQueueFamilyIndices = nullptr; bufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; res = vkCreateBuffer(device->GetHandle(), &bufferCreateInfo, nullptr, &mBuffer); CheckVkResult("Cannot create a VulkanBuffer", res); // Allocate memory VkMemoryRequirements memRequire; vkGetBufferMemoryRequirements(device->GetHandle(), mBuffer, &memRequire); mAllocatedMemory = device->AllocateMemory(memRequire, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); mMappedSize = memRequire.size; // Bind res = vkBindBufferMemory(device->GetHandle(), mBuffer, mAllocatedMemory, 0); CheckVkResult("Cannot bind the memory", res); // Update buffer data for(uint64_t i = 0; i < bufDataNum; i++) { if(initializer.bufferDatas[i].data != nullptr) { Map(); UpdateBufferData(i, initializer.bufferDatas[i].data, initializer.bufferDatas[i].size); } } Unmap(); } VulkanBuffer::~VulkanBuffer() { if(mMappedData != nullptr) vkUnmapMemory(mDevice_ref->GetHandle(), mAllocatedMemory); vkFreeMemory(mDevice_ref->GetHandle(), mAllocatedMemory, nullptr); vkDestroyBuffer(mDevice_ref->GetHandle(), mBuffer, nullptr); } void VulkanBuffer::Map() { if(mMappedData != nullptr) return; VkResult res; res = vkMapMemory(mDevice_ref->GetHandle(), mAllocatedMemory, 0, mMappedSize, 0, &mMappedData); CheckVkResult("Cannot map to the memory", res); mMappedOffset = 0; } void VulkanBuffer::Map(uint64_t startIndex, uint64_t endIndex) { if(mMappedData != nullptr) return; VkResult res; uint64_t startOffset = mDataOffsets[startIndex]; uint64_t size = mDataOffsets[endIndex] + mDataSizes[endIndex] - startOffset; res = vkMapMemory(mDevice_ref->GetHandle(), mAllocatedMemory, startOffset, size, 0, &mMappedData); CheckVkResult("Cannot map to the memory", res); mMappedOffset = startOffset; } void VulkanBuffer::UpdateBufferData(uint64_t index, const void* data, size_t size) { #ifdef _DEBUG if(size != mDataSizes[index]) { CUBE_LOG(cube::LogType::Warning, "Wrong data size. (Expected: {0} / Actual: {1})", mDataSizes[index], size); } #endif // _DEBUG CHECK(mMappedData != nullptr, "Failed to update buffer data. It is not mapped."); char* p = (char*)mMappedData + mDataOffsets[index] - mMappedOffset; memcpy(p, data, size); } void VulkanBuffer::Unmap() { if(mMappedData == nullptr) return; vkUnmapMemory(mDevice_ref->GetHandle(), mAllocatedMemory); mMappedData = nullptr; } BufferInfo VulkanBuffer::GetInfo(uint64_t index) const { BufferInfo info; info.buffer = shared_from_this(); info.offset = mDataOffsets[index]; info.range = mDataSizes[index]; return info; } } // namespace render } // namespace cube
28.438272
112
0.72086
[ "render" ]
6539eff7ce45f8a4a707ac50644ac668378b1ecb
1,332
cpp
C++
calc-sheet-column-number/calc-sheet-column-number.cpp
fatihcansu/kripton
e680d9fd24a632167f5a8ac71924ef636dcd567c
[ "Unlicense" ]
13
2021-01-24T20:03:35.000Z
2022-03-15T00:49:10.000Z
calc-sheet-column-number/calc-sheet-column-number.cpp
fatihcansu/kripton
e680d9fd24a632167f5a8ac71924ef636dcd567c
[ "Unlicense" ]
null
null
null
calc-sheet-column-number/calc-sheet-column-number.cpp
fatihcansu/kripton
e680d9fd24a632167f5a8ac71924ef636dcd567c
[ "Unlicense" ]
8
2021-01-18T21:10:27.000Z
2021-03-27T11:31:17.000Z
// Build instruction: g++ -g calc-sheet-column-number.cpp -o calc-sheet-column-number.o #include <iostream> #include <vector> #include <cmath> using namespace std; class Solution { public: int titleToNumber(string s) { string sLetters("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); int nSum = 0; int nDigitNum = s.size(); // Hangi basamakta olduğumuzun bilgisini tutmak için tanımlandı. /* sLetters.find(s[i])+1 sırası gelen harfin sLetters içindeki konumunu döndürecektir. * Bu aynı zamanda harfin değeri anlamına da gelir. * find fonksiyonu A'nın konumunu 0 döndürür. 1 den balşaması gerektiğinden +1 eklenmiştir. * * C++ -- ++ operatörünü başta ve sonda kullanmanın farkı şöyledir. * int x = 5; * cout << x-- Çıktısı 5 olacaktır. Eksiltilmiş değer kullanım anına yansımaz. Sonraki satırlarda artık 4 olarak görülebilir. * * int y = 5; * cout << --y; Çıktısı 4 olacaktır. Eksiltilmiş değer tam kullanım anına yansır. */ for(int i = 0; i< s.size(); i++) nSum += pow(26, --nDigitNum) * (sLetters.find(s[i])+1); return nSum; } }; int main() { Solution sObj; string s1("KRPT"); cout << "nSum: " << sObj.titleToNumber(s1) << endl; return 0; }
29.6
136
0.607357
[ "vector" ]
6548a81f94020f98f34da2481281fab543aece71
2,643
cc
C++
ros_node/urdf_reader.cc
Foued70/StaticMapping
1ca31318386de954702ad88804e1cb41d5ee0486
[ "MIT" ]
264
2019-08-08T08:39:39.000Z
2022-03-27T09:46:42.000Z
ros_node/urdf_reader.cc
Foued70/StaticMapping
1ca31318386de954702ad88804e1cb41d5ee0486
[ "MIT" ]
26
2019-08-26T13:35:05.000Z
2022-03-14T10:16:55.000Z
ros_node/urdf_reader.cc
Foued70/StaticMapping
1ca31318386de954702ad88804e1cb41d5ee0486
[ "MIT" ]
62
2019-08-20T17:14:14.000Z
2022-03-16T12:18:35.000Z
// MIT License // Copyright (c) 2019 Edward Liu // 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 "ros_node/urdf_reader.h" #include <string> #include <vector> #include "glog/logging.h" #include "urdf/model.h" namespace static_map_ros { std::vector<geometry_msgs::TransformStamped> ReadStaticTransformsFromUrdf( const std::string& urdf_filename, tf2_ros::Buffer* const tf_buffer) { urdf::Model model; CHECK(model.initFile(urdf_filename)); #if URDFDOM_HEADERS_HAS_SHARED_PTR_DEFS std::vector<urdf::LinkSharedPtr> links; #else std::vector<boost::shared_ptr<urdf::Link> > links; #endif model.getLinks(links); std::vector<geometry_msgs::TransformStamped> transforms; for (const auto& link : links) { if (!link->getParent() || link->parent_joint->type != urdf::Joint::FIXED) { continue; } const urdf::Pose& pose = link->parent_joint->parent_to_joint_origin_transform; geometry_msgs::TransformStamped transform; transform.transform.rotation.w = pose.rotation.w; transform.transform.rotation.x = pose.rotation.x; transform.transform.rotation.y = pose.rotation.y; transform.transform.rotation.z = pose.rotation.z; transform.transform.translation.x = pose.position.x; transform.transform.translation.y = pose.position.y; transform.transform.translation.z = pose.position.z; transform.child_frame_id = link->name; transform.header.frame_id = link->getParent()->name; tf_buffer->setTransform(transform, "urdf", true /* is_static */); transforms.push_back(transform); } return transforms; } } // namespace static_map_ros
37.757143
80
0.745743
[ "vector", "model", "transform" ]
656e8acbbabfa9911937b8ff606e62d01e62bc7a
3,736
hpp
C++
Code/Source/Tools/Browse3D/GraphicsWidget.hpp
sidch/Thea
d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7
[ "BSD-3-Clause" ]
77
2016-11-06T17:25:54.000Z
2022-03-29T16:30:34.000Z
Code/Source/Tools/Browse3D/GraphicsWidget.hpp
sidch/Thea
d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7
[ "BSD-3-Clause" ]
1
2017-04-22T16:47:04.000Z
2017-04-22T16:47:04.000Z
Code/Source/Tools/Browse3D/GraphicsWidget.hpp
sidch/Thea
d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7
[ "BSD-3-Clause" ]
20
2015-10-17T20:38:50.000Z
2022-02-18T09:56:27.000Z
//============================================================================ // // This file is part of the Thea toolkit. // // This software is distributed under the BSD license, as detailed in the // accompanying LICENSE.txt file. Portions are derived from other works: // their respective licenses and copyright information are reproduced in // LICENSE.txt and/or in the relevant source files. // // Author: Siddhartha Chaudhuri // First version: 2011 // //============================================================================ #ifndef __Browse3D_GraphicsWidget_hpp__ #define __Browse3D_GraphicsWidget_hpp__ #include "Common.hpp" #include "../../AxisAlignedBox3.hpp" #include "../../Graphics/IDrawable.hpp" namespace Thea { namespace Graphics { class IShader; } // namespace Graphics } // namespace Thea namespace Browse3D { /** A drawable widget. */ class GraphicsWidget : public Graphics::IDrawable { public: THEA_DECL_SMART_POINTERS(GraphicsWidget) /** Get the bounding box of the model. */ virtual AxisAlignedBox3 const & getBounds() const { static AxisAlignedBox3 const dummy; return dummy; } /** Update the bounding box of the part. */ virtual void updateBounds() {} /** Select an appropriate shader for surface rendering. Prefers matcap over Phong if both are available. */ static bool setSurfaceShader(Graphics::IRenderSystem & render_system); /** Select the Phong shader for rendering. */ static bool setPhongShader(Graphics::IRenderSystem & render_system); /** Select the matcap shader for rendering. */ static bool setMatcapShader(Graphics::IRenderSystem & render_system); /** Get the shader currently being used. */ static Graphics::IShader * getShader(); /** Set the lighting parameters for shaders that support these settings. */ static void setLight(Vector3 const & dir, ColorRgb const & color, ColorRgb const & ambient_color_); /** Set two-sided lighting on/off, for shaders that support these settings. */ static void setTwoSided(bool value); /** Set flat shading on/off. */ static void setFlatShaded(bool value); /** Get the direction of incident light. */ static Vector3 const & getLightDirection() { return light_dir; } /** Get the color of incident light. */ static ColorRgb const & getLightColor() { return light_color; } /** Get the color of ambient light. */ static ColorRgb const & getAmbientColor() { return ambient_color; } /** Check if two-sided lighting is on or off. */ static bool isTwoSided() { return two_sided; } /** Check if flat shading is on or off. */ static bool isFlatShaded() { return flat_shaded; } private: /** Get the wrapped Phong shader, or a null pointer if it could not be initialized. */ static Graphics::IShader * getPhongShader(Graphics::IRenderSystem & render_system); /** Get the wrapped matcap shader, or a null pointer if it could not be initialized. */ static Graphics::IShader * getMatcapShader(Graphics::IRenderSystem & render_system); /** Set shader uniforms related to Phong shading (including the surface material). Returns null on error. */ static Graphics::IShader * setPhongUniforms(Graphics::IRenderSystem & render_system); /** Set shader uniforms related to matcap materials (including the matcap texture itself). Returns null on error. */ static Graphics::IShader * setMatcapUniforms(Graphics::IRenderSystem & render_system); static Graphics::IShader * shader; static Vector3 light_dir; static ColorRgb light_color; static ColorRgb ambient_color; static bool two_sided; static bool flat_shaded; }; // class GraphicsWidget } // namespace Browse3D #endif
35.580952
120
0.69031
[ "model" ]
657a7dadf17ad76d7b320ddb4b8aedfda02d8924
2,253
cpp
C++
competitive programming/leetcode/380. Insert Delete GetRandom O(1).cpp
kashyap99saksham/Code
96658d0920eb79c007701d2a3cc9dbf453d78f96
[ "MIT" ]
16
2020-06-02T19:22:45.000Z
2022-02-05T10:35:28.000Z
competitive programming/leetcode/380. Insert Delete GetRandom O(1).cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
null
null
null
competitive programming/leetcode/380. Insert Delete GetRandom O(1).cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
2
2020-08-27T17:40:06.000Z
2022-02-05T10:33:52.000Z
class RandomizedSet { public: unordered_map<int, int> m; vector<int>v; /** Initialize your data structure here. */ RandomizedSet() { } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ bool insert(int val) { if(m.find(val)!=m.end()) return false; v.push_back(val); m.insert({val, v.size()-1}); return true; } /** Removes a value from the set. Returns true if the set contained the specified element. */ bool remove(int val) { if(m.find(val)==m.end()) return false; int pos=m[val]; v[pos]=v[v.size()-1]; m[v[pos]]=pos; v.pop_back(); m.erase(val); return true; } /** Get a random element from the set. */ int getRandom() { return v[rand()%v.size()]; } }; /** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet* obj = new RandomizedSet(); * bool param_1 = obj->insert(val); * bool param_2 = obj->remove(val); * int param_3 = obj->getRandom(); */ class RandomizedSet { public: unordered_map<int, int> m; vector<int>v; /** Initialize your data structure here. */ RandomizedSet() { } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ bool insert(int val) { if(m.find(val)!=m.end()) return false; v.push_back(val); m.insert({val, v.size()-1}); return true; } /** Removes a value from the set. Returns true if the set contained the specified element. */ bool remove(int val) { if(m.find(val)==m.end()) return false; int pos=m[val]; v[pos]=v[v.size()-1]; m[v[pos]]=pos; v.pop_back(); m.erase(val); return true; } /** Get a random element from the set. */ int getRandom() { return v[rand()%v.size()]; } }; /** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet* obj = new RandomizedSet(); * bool param_1 = obj->insert(val); * bool param_2 = obj->remove(val); * int param_3 = obj->getRandom(); */
23.226804
109
0.564581
[ "object", "vector" ]
657b23236aff8928e8ea7a6d64e353b1bc88c506
6,482
cpp
C++
src/World.cpp
jaydonhansen/predator-prey-simulator
5aa4e6e1d0af1f15ea6316aee2c3a0bff5fd178b
[ "MIT" ]
null
null
null
src/World.cpp
jaydonhansen/predator-prey-simulator
5aa4e6e1d0af1f15ea6316aee2c3a0bff5fd178b
[ "MIT" ]
null
null
null
src/World.cpp
jaydonhansen/predator-prey-simulator
5aa4e6e1d0af1f15ea6316aee2c3a0bff5fd178b
[ "MIT" ]
null
null
null
#include <vector> #include <algorithm> #include <iostream> #include "Rand.h" #include "World.h" using namespace std; World::World(int size, int initial_predators, int initial_prey, float predator_reproduction_chance, float prey_reproduction_chance, int predator_hunger_limit): grid(size, vector<int>(size, -1)) { num_predators = initial_predators; num_prey = initial_prey; this->predator_reproduction_chance = predator_reproduction_chance; this->prey_reproduction_chance = prey_reproduction_chance; this->predator_hunger_limit = predator_hunger_limit; } vector<Agent>::iterator World::getAgentAt(int x, int y) { int id = grid[x][y]; if (id == -1) { return agents.end(); } auto found = find_if(begin(agents), end(agents), [id](Agent const& agent) { return agent.id == id;}); return found; } void World::placeIDAt(int id, int x, int y) { grid[x][y] = id; } void World::removeIDAt(int x, int y) { grid[x][y] = -1; } // The basic iterative process of the game void World::tick() { int delta_x; int delta_y; vector<int> toDelete; vector<tuple<int, int>> toClear; int newPredators = 0; int newPrey = 0; #pragma omp parallel shared(toDelete, toClear, delta_x, delta_y, generator) #pragma omp for for (int i = 0; i < agents.size(); i++) { Agent *agent = &agents[i]; int direction = generator() % 4; // Generate a random direction // Predator eat step if (agent->predator) { // Determine the direction to eat switch (direction) { case 0: // North delta_x = 0; delta_y = 1; break; case 1: // East delta_x = 1; delta_y = 0; break; case 2: // South delta_x = 0; delta_y = -1; break; case 3: // West delta_x = -1; delta_y = 0; break; default: delta_y = 0; delta_x = 0; } // Attempt to eat the prey at the location int eaten = agent->eat(delta_x, delta_y); // If there's a prey at the position, mark it for deletion #pragma omp critical if (eaten != -1 && num_prey > 0) { agent->hunger = 0; // yum // mark the prey for deletion toDelete.push_back(eaten); // Calculate positions to clear int new_x = agent->x_pos + delta_x; int new_y = agent->y_pos + delta_x; // Out of bounds check. This will segfault if not done! if (new_x < grid.size() && new_x >= 0 && new_y < grid.size() && new_y >= 0) toClear.push_back(std::make_tuple(new_x, new_y)); // Add to the list of agents to remove from the board (ids) num_prey -= 1; } #pragma omp critical // If the predator is starving, mark it for deletion if (agent->hunger > predator_hunger_limit && num_predators > 0) { toDelete.push_back(agent->id); toClear.push_back(std::make_tuple(agent->x_pos, agent->y_pos)); num_predators -= 1; } } } // Remove agents if their ID matches the IDs to be removed for (int id : toDelete) { agents.erase(remove_if(agents.begin(), agents.end(), [id](Agent const& agent) { return agent.id == id;}), agents.end()); } for (tuple<int, int> tup : toClear) { grid[get<0>(tup)][get<1>(tup)] = -1; } #pragma omp for for (int i = 0; i < agents.size(); i++) { Agent *agent = &agents[i]; int direction = generator() % 4; // Generate a random direction for each agent to attempt to eat/move // Determine the direction to move switch (direction) { case 0: // North delta_x = 0; delta_y = 1; break; case 1: // East delta_x = 1; delta_y = 0; break; case 2: // South delta_x = 0; delta_y = -1; break; case 3: // West delta_x = -1; delta_y = 0; break; default: delta_y = 0; delta_x = 0; } #pragma omp critical agent->move(delta_x, delta_y); } #pragma omp for for (int i = 0; i < num_predators; i++) { if ((dis(generator) < predator_reproduction_chance && num_predators > 1)) { #pragma omp critical newPredators++; } } #pragma omp for for (int i = 0; i < num_prey; i++) { if ((dis(generator) < prey_reproduction_chance && num_prey > 1)) { #pragma omp critical newPrey++; } } // Spawn and place IDs of new predators for (int i = 0; i < newPredators; i++) { spawn_predator(); } for (auto const& agent : agents) { placeIDAt(agent.id, agent.x_pos, agent.y_pos); } // Spawn and place IDs of new prey for (int i = 0; i < newPrey; i++) { spawn_prey(); } // Update the grid positions for (auto const& agent : agents) { placeIDAt(agent.id, agent.x_pos, agent.y_pos); } } // Generate a new prey if the probability roll is less than the reproduction rate void World::spawn_prey() { int x_pos = generator() % grid.size(); int y_pos = generator() % grid.size(); if (grid[x_pos][y_pos] == -1) { agents.emplace_back(this, false, x_pos, y_pos); num_prey++; } } void World::spawn_predator() { int x_pos = generator() % grid.size(); int y_pos = generator() % grid.size(); if (grid[x_pos][y_pos] == -1) { agents.emplace_back(this, true, x_pos, y_pos); num_predators++; } }
30.575472
125
0.489509
[ "vector" ]
657cf98e3ac274ab3b2fc0f317eeb0d10dc044bc
9,735
cpp
C++
compiler/compiler.cpp
NREL/Spawn
2f6861db6b147b2ee60a7b1e8bae81ba755f2dfe
[ "BSD-3-Clause" ]
6
2020-05-10T20:48:36.000Z
2022-01-18T14:59:07.000Z
compiler/compiler.cpp
NREL/Spawn
2f6861db6b147b2ee60a7b1e8bae81ba755f2dfe
[ "BSD-3-Clause" ]
29
2020-05-13T12:40:43.000Z
2022-01-24T00:50:21.000Z
compiler/compiler.cpp
NREL/Spawn
2f6861db6b147b2ee60a7b1e8bae81ba755f2dfe
[ "BSD-3-Clause" ]
null
null
null
#include "clang/Basic/DiagnosticOptions.h" #include "clang/CodeGen/CodeGenAction.h" #include "clang/CodeGen/ObjectFilePCHContainerOperations.h" #include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" #include "clang/Driver/Options.h" #include "clang/Driver/Tool.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/CompilerInvocation.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "clang/Frontend/TextDiagnosticBuffer.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "clang/FrontendTool/Utils.h" #include "llvm/ADT/SmallString.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/IR/Module.h" #include "llvm/IR/PassManager.h" #include "llvm/Linker/Linker.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Host.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/Path.h" #include "llvm/Support/Program.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/Timer.h" #include "llvm/Support/raw_os_ostream.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Bitcode/BitcodeWriter.h" #include "llvm/Target/TargetMachine.h" #include "lld/Common/Driver.h" #include "lld/Common/ErrorHandler.h" #include <fmt/format.h> #include <spdlog/spdlog.h> #include "../util/filesystem.hpp" #include "../util/temp_directory.hpp" #include <iostream> #if defined _WIN32 #include <windows.h> #else #include <dlfcn.h> #include <stdio.h> #endif #include <codecvt> #include <iterator> #include <sstream> #include <stdexcept> #include "compiler.hpp" std::string toString(const std::wstring &utf16_string) { #if _MSC_VER >= 1900 std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> convert; return convert.to_bytes(utf16_string.data(), utf16_string.data() + utf16_string.size()); #else std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert; const std::u16string u16string{utf16_string.begin(), utf16_string.end()}; return convert.to_bytes(u16string); #endif } std::string toString(const std::string &str) { return str; } std::string toString(const fs::path &path) { return toString(path.native()); } std::string getExecutablePath() { #if defined _WIN32 TCHAR szPath[MAX_PATH]; if (GetModuleFileName(nullptr, szPath, MAX_PATH)) { return std::string(szPath); } #else Dl_info info; if (dladdr("main", &info)) { return std::string(info.dli_fname); } #endif return std::string(); } namespace spawn { void Compiler::write_shared_object_file( const fs::path &loc, const fs::path &sysroot, std::vector<fs::path> additional_libs ) { util::Temp_Directory td; const auto temporary_object_file_location = td.dir() / "temporary_object.o"; write_object_file(temporary_object_file_location); std::stringstream out_ss; std::stringstream err_ss; std::vector<std::string> str_args { "ld.lld-10", "-shared", fmt::format("--sysroot={}", toString(sysroot)), fmt::format("-L{}", toString(sysroot / "usr/lib/")), fmt::format("-L{}", toString(sysroot / "usr/lib/x86_64-linux-gnu/")), toString(temporary_object_file_location) }; for (const auto &lib : additional_libs) { str_args.push_back(toString(lib)); } str_args.insert(str_args.end(), { "-lm", "-lc", "-ldl", "-lpthread", "-o", toString(loc), }); for (const auto &arg : str_args) { spdlog::trace("embedded lld argument: {}", arg); } clang::SmallVector<const char *, 64> Args{}; std::transform( str_args.begin(), str_args.end(), std::back_inserter(Args), [](const auto &str) { return str.c_str(); }); spdlog::info("linking to: {}", toString(loc)); bool success = true; { // scope to ensure error stream buffer is flushed llvm::raw_os_ostream err(err_ss); llvm::raw_os_ostream out(out_ss); success = lld::elf::link(Args, false /*canExitEarly*/, out, err); if (!success) { spdlog::error("Linking errors with {} errors", lld::errorHandler().errorCount); } } const auto errors = err_ss.str(); if (!success) { throw std::runtime_error(fmt::format("Error with linking {}, errors '{}'", toString(loc), errors)); } if (success && !errors.empty()) { spdlog::warn("Linking warnings: '{}'", errors); } } void Compiler::compile_and_link(const fs::path &source) { auto do_compile = [&]() { return compile(source, *m_context.getContext(), m_include_paths, m_flags); }; if (!m_currentCompilation) { m_currentCompilation = do_compile(); } else { llvm::Linker::linkModules(*m_currentCompilation, do_compile()); } } void Compiler::write_bitcode(const fs::path &loc) { if (!m_currentCompilation) { throw std::runtime_error("No current compilation available to write"); } std::ofstream ofs(loc.native()); llvm::raw_os_ostream ros(ofs); llvm::WriteBitcodeToFile(*m_currentCompilation, ros); } void Compiler::write_object_file(const fs::path &loc) { if (!m_currentCompilation) { throw std::runtime_error("No current compilation available to write"); } std::string err; llvm::legacy::PassManager pass; std::string error; llvm::CodeGenFileType ft = llvm::CGFT_ObjectFile; std::error_code EC; std::string sloc = toString(loc); llvm::raw_fd_ostream destination(sloc.c_str(), EC, llvm::sys::fs::OF_None); if (m_target_machine->addPassesToEmitFile(pass, destination, nullptr, ft)) { throw std::runtime_error("TargetMachine can't emit a file of this type"); } pass.run(*m_currentCompilation); destination.flush(); } std::unique_ptr<llvm::Module> Compiler::compile(const fs::path &source, llvm::LLVMContext &ctx, const std::vector<fs::path> &include_paths, const std::vector<std::string> &flags) { void *MainAddr = (void *)(intptr_t)getExecutablePath; std::string Path = getExecutablePath(); clang::IntrusiveRefCntPtr<clang::DiagnosticOptions> DiagOpts{new clang::DiagnosticOptions()}; clang::TextDiagnosticPrinter *DiagClient{new clang::TextDiagnosticPrinter(llvm::errs(), &*DiagOpts)}; clang::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagID{new clang::DiagnosticIDs()}; clang::DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient); // Examples say to use ELF on Windows, but that doesn't actually work, so we are not clang::driver::Driver TheDriver(Path, llvm::sys::getProcessTriple(), Diags); TheDriver.setTitle("clang interpreter"); TheDriver.setCheckInputsExist(false); // a place for the strings to live std::vector<std::string> str_args; str_args.push_back(toString(source)); std::transform(include_paths.begin(), include_paths.end(), std::back_inserter(str_args), [](const auto &str) { return "-I" + toString(str); }); str_args.push_back("-fsyntax-only"); str_args.push_back("-fPIC"); str_args.push_back("-g"); str_args.push_back("-Wno-incomplete-setjmp-declaration"); str_args.push_back("-Wno-expansion-to-defined"); str_args.push_back("-Wno-nullability-completeness"); std::copy(flags.begin(), flags.end(), std::back_inserter(str_args)); str_args.push_back(toString(source)); // the strings to pass to the compiler driver clang::SmallVector<const char *, 64> Args; //(argv, argv + argc); std::transform( str_args.begin(), str_args.end(), std::back_inserter(Args), [](const auto &str) { return str.c_str(); }); std::unique_ptr<clang::driver::Compilation> C(TheDriver.BuildCompilation(Args)); if (!C) { return {}; } // FIXME: This is copied from ASTUnit.cpp; simplify and eliminate. // We expect to get back exactly one command job, if we didn't something // failed. Extract that job from the compilation. const auto &Jobs = C->getJobs(); if (Jobs.size() != 1 || !clang::isa<clang::driver::Command>(*Jobs.begin())) { clang::SmallString<256> Msg; llvm::raw_svector_ostream OS(Msg); Jobs.Print(OS, "; ", true); Diags.Report(clang::diag::err_fe_expected_compiler_job) << OS.str(); return {}; } const auto &Cmd = clang::cast<clang::driver::Command>(*Jobs.begin()); if (llvm::StringRef(Cmd.getCreator().getName()) != "clang") { Diags.Report(clang::diag::err_fe_expected_clang_command); return {}; } // Initialize a compiler invocation object from the clang (-cc1) arguments. const auto &CCArgs = Cmd.getArguments(); std::unique_ptr<clang::CompilerInvocation> CI{new clang::CompilerInvocation}; clang::CompilerInvocation::CreateFromArgs( *CI, CCArgs, Diags); // Show the invocation, with -v. if (CI->getHeaderSearchOpts().Verbose) { llvm::errs() << "clang invocation:\n"; Jobs.Print(llvm::errs(), "\n", true); llvm::errs() << "\n"; } // FIXME: This is copied from cc1_main.cpp; simplify and eliminate. // Create a compiler instance to handle the actual work. clang::CompilerInstance Clang; Clang.setInvocation(std::move(CI)); // Create the compilers actual diagnostics engine. Clang.createDiagnostics(); if (!Clang.hasDiagnostics()) return {}; // Infer the builtin include path if unspecified. // if (Clang.getHeaderSearchOpts().UseBuiltinIncludes && // Clang.getHeaderSearchOpts().ResourceDir.empty()) Clang.getHeaderSearchOpts().ResourceDir = clang::CompilerInvocation::GetResourcesPath(getExecutablePath().c_str(), MainAddr); // Create and execute the frontend to generate an LLVM bitcode module. std::unique_ptr<clang::CodeGenAction> Act(new clang::EmitLLVMOnlyAction(&ctx)); if (!Clang.ExecuteAction(*Act)) { return {}; } return Act->takeModule(); } } // namespace spawn
29.953846
112
0.692553
[ "object", "vector", "transform" ]
657d7be290acd05a4aebe6425b6efbc8d86097fa
773
cpp
C++
dataStructure/DisjointSet.cpp
qwer312132/competive-programing
05ea48900c827753a7b5723ef54a0852f7e7cbc1
[ "CECILL-B" ]
1
2022-03-19T16:52:31.000Z
2022-03-19T16:52:31.000Z
dataStructure/DisjointSet.cpp
qwer312132/competive-programing
05ea48900c827753a7b5723ef54a0852f7e7cbc1
[ "CECILL-B" ]
null
null
null
dataStructure/DisjointSet.cpp
qwer312132/competive-programing
05ea48900c827753a7b5723ef54a0852f7e7cbc1
[ "CECILL-B" ]
null
null
null
struct DisjointSet{ // save() is like recursive // undo() is like return int n, fa[ N ], sz[ N ]; vector< pair<int*,int> > h; vector<int> sp; void init( int tn ){ n=tn; for( int i = 0 ; i < n ; i ++ ){ fa[ i ]=i; sz[ i ]=1; } sp.clear(); h.clear(); } void assign( int *k, int v ){ h.PB( {k, *k} ); *k = v; } void save(){ sp.PB(SZ(h)); } void undo(){ assert(!sp.empty()); int last=sp.back(); sp.pop_back(); while( SZ(h)!=last ){ auto x=h.back(); h.pop_back(); *x.first = x.second; } } void uni( int x , int y ){ x = f( x ); y = f( y ); if( x == y ) return; if( sz[ x ] < sz[ y ] ) swap( x, y ); assign( &sz[ x ] , sz[ x ] + sz[ y ] ); assign( &fa[ y ] , x); } }djs;
22.735294
43
0.438551
[ "vector" ]
65815305e31cc6d0c2de26de7836eb7ae6b9353d
7,597
cpp
C++
rank_server/src/RankModule.cpp
zyb2013/shiny-engine
4d615975e778522499c1699929867c711456c23a
[ "MIT" ]
17
2018-04-24T03:47:19.000Z
2022-02-25T15:41:10.000Z
rank_server/src/RankModule.cpp
ericyonng/shiny-engine
96a8eb0fae36471570ae0fc61741bbc8c26c7139
[ "MIT" ]
null
null
null
rank_server/src/RankModule.cpp
ericyonng/shiny-engine
96a8eb0fae36471570ae0fc61741bbc8c26c7139
[ "MIT" ]
7
2018-09-10T12:02:15.000Z
2021-09-13T02:36:24.000Z
/* * File: RankModule.cpp * Author: Jehu Shaw * * Created on 2014_7_9, 16:00 */ #include "RankModule.h" #include "NodeDefines.h" #include "ThreadPool.h" #include "Log.h" #include "BodyMessage.h" #include "ChannelManager.h" #include "WorkerOperateHelper.h" #include "CacheOperateHelper.h" #include "TimestampManager.h" #include "GuidFactory.h" #include "CacheRecordManager.h" #include "AppConfig.h" #include "FillPacketHelper.h" #include "RankData.h" #include "msg_rank_update.pb.h" #include "msg_rank_request.pb.h" using namespace mdl; using namespace util; using namespace evt; using namespace thd; CRankModule::CRankModule(const char* name) : CModule(name), m_rankSet(), m_bLoad(false) { AppConfig::PTR_T pConfig(AppConfig::Pointer()); m_nRankCacheId = (uint16_t)pConfig->GetInt(APPCONFIG_RANKCACHEID); m_rankSet.Init(pConfig->GetInt(APPCONFIG_MAXSIZELIMIT), pConfig->GetInt(APPCONFIG_FLOORLIMIT)); //util::CAutoPointer<CRankData> pRankData; //uint64_t userId = 1; //m_rankSet.GetItem(pRankData, userId); //m_rankSet.GetRank(userId); //m_rankSet.GetSize(); //RANK_SET_T::NodeRankType items[REQEST_RANK_TOP_SIZE]; //m_rankSet.GetFirstMoreNodes(items, REQEST_RANK_TOP_SIZE, userId); //m_rankSet.GetLastMoreNodes(items, REQEST_RANK_TOP_SIZE, userId); //m_rankSet.GetMidMoreNodes(items, REQEST_RANK_TOP_SIZE, userId); //m_rankSet.GetNodeByRank(1); //m_rankSet.GetFirstMoreNodesByRank(items, REQEST_RANK_TOP_SIZE, 1); //m_rankSet.GetLastMoreNodesByRank(items, REQEST_RANK_TOP_SIZE, 1); //m_rankSet.GetMidMoreNodesByRank(items, REQEST_RANK_TOP_SIZE, 1); } CRankModule::~CRankModule() { WaitForDone(); } void CRankModule::OnRegister(){ OutputBasic("OnRegister"); } void CRankModule::OnRemove(){ OutputBasic("OnRemove"); } std::vector<int> CRankModule::ListNotificationInterests() { std::vector<int> interests; interests.push_back(N_CMD_NODE_REGISTER); interests.push_back(N_CMD_C_RANK_UPDATE); interests.push_back(N_CMD_C_RANK_REQUEST); return interests; } IModule::InterestList CRankModule::ListProtocolInterests() { InterestList interests; return interests; } void CRankModule::HandleNotification(const CWeakPointer<INotification>& request, CWeakPointer<IResponse>& reply) { int32_t nCmd = request->GetName(); switch(nCmd) { case N_CMD_C_RANK_UPDATE: HandleRankUpdate(request, reply); break; case N_CMD_C_RANK_REQUEST: HandleRankRequest(request, reply); break; case N_CMD_NODE_REGISTER: if((uint16_t)request->GetType() == GetRankCacheId()) { if(atomic_cmpxchg8(&m_bLoad, true, false) == (char)false) { ThreadPool.ExecuteTask(this); } } break; default: break; } } bool CRankModule::Run() { LoadFromDB(); return false; } void CRankModule::LoadFromDB() { util::CValueStream strKeys; CResponseRows outRecords; CCacheRecordManager::PTR_T pCacheRecordMgr(CCacheRecordManager::Pointer()); int nCount = LOAD_EACH_PAGE_SIZE; if(nCount < 1) { nCount = 1; } int nPage = 0; do { CRankData::LoadAllRecord(outRecords, GetRankCacheId(), strKeys, nCount, nPage*nCount); int nSize = outRecords.GetSize(); for(int i = 0; i < nSize; ++i) { util::CValueStream tsKeys(outRecords.GetKey(i)); uint64_t userId; tsKeys.Parse(userId); CAutoPointer<CRankData> pRankData(new CRankData); util::CValueStream tsValues(outRecords.GetValue(i)); pRankData->Parse(std::string(tsValues.GetData(), tsValues.GetLength()), outRecords.GetCas(i)); CAutoPointer<CRankData> pRemoveData; if(m_rankSet.InsertItem(pRemoveData, userId, pRankData)) { if(pRankData != pRemoveData) { strKeys.Serialize(userId); pCacheRecordMgr->AddCacheRecord(userId, strKeys, pRankData); strKeys.Reset(); if(!pRemoveData.IsInvalid()) { pCacheRecordMgr->RemoveCacheRecord(userId, pRemoveData->ObjectId()); } } } else { if(!pRemoveData.IsInvalid()) { pCacheRecordMgr->RemoveCacheRecord(userId, pRemoveData->ObjectId()); } } } if(nSize < nCount) { break; } outRecords.Clear(); } while(true); } void CRankModule::HandleRankUpdate(const CWeakPointer<mdl::INotification>& request, CWeakPointer<mdl::IResponse>& reply) { CWeakPointer<::node::DataPacket> pRequest(GetWorkerRequestPacket(request)); if(pRequest.IsInvalid()) { return; } CWeakPointer<::node::DataPacket> pResponse(GetWorkerResponsePacket(reply)); if(pResponse.IsInvalid()) { return; } uint64_t userId = pRequest->route(); ::rank::UpdateRankPacket updateRank; if(!ParseWorkerData(updateRank, pRequest)) { OutputError("!ParseWorkerData userId = "I64FMTD, userId); pResponse->set_result(PARSE_PACKAGE_FAIL); return; } util::CAutoPointer<CRankData> pAddData; util::CAutoPointer<CRankData> pRemoveData; m_rankSet.ReplaceItem(pAddData, pRemoveData, userId, updateRank.score()); if(pAddData != pRemoveData) { if(!pAddData.IsInvalid()) { util::CValueStream strKeys; strKeys.Serialize(userId); CCacheRecordManager::PTR_T pCacheRecordMgr(CCacheRecordManager::Pointer()); pCacheRecordMgr->AddCacheRecord(userId, strKeys, pAddData); } if(!pRemoveData.IsInvalid()) { CCacheRecordManager::PTR_T pCacheRecordMgr(CCacheRecordManager::Pointer()); pCacheRecordMgr->RemoveCacheRecord(userId, pRemoveData->ObjectId()); } } pResponse->set_result(TRUE); } void CRankModule::HandleRankRequest(const CWeakPointer<mdl::INotification>& request, CWeakPointer<mdl::IResponse>& reply) { CWeakPointer<::node::DataPacket> pRequest(GetWorkerRequestPacket(request)); if(pRequest.IsInvalid()) { return; } CWeakPointer<::node::DataPacket> pResponse(GetWorkerResponsePacket(reply)); if(pResponse.IsInvalid()) { return; } uint64_t userId = pRequest->route(); ::rank::RequestRankPacket requestRank; if(!ParseWorkerData(requestRank, pRequest)) { OutputError("!ParseWorkerData userId = "I64FMTD, userId); pResponse->set_result(PARSE_PACKAGE_FAIL); return; } int32_t nRequestRankType = requestRank.rank_type(); ::rank::RequestRankResultPacket requestRankResult; requestRankResult.set_rank_type(nRequestRankType); if(REQUEST_RANK_PRIVATE == nRequestRankType) { unsigned long nRank; int32_t nScore; m_rankSet.GetRankAndScore(nRank, nScore, userId); ::rank::RankItemPacket* pRankItemPacket = requestRankResult.add_items(); FillRankItem(*pRankItemPacket, userId, nRank, nScore); } else if(REQUEST_RANK_TOP == nRequestRankType) { RANK_SET_T::NodeRankType items[REQEST_RANK_TOP_SIZE]; if(m_rankSet.GetTopRanks(items, REQEST_RANK_TOP_SIZE)) { for(int i = 0; i < REQEST_RANK_TOP_SIZE; ++i) { RANK_SET_T::NodeRankType& item = items[i]; ::rank::RankItemPacket* pRankItemPacket = requestRankResult.add_items(); FillRankItem(*pRankItemPacket, item.pNode->GetValue(), item.uRank, item.pNode->GetKey().GetScore()); } } } else if(REQUEST_RANK_AROUND == nRequestRankType) { RANK_SET_T::NodeRankType items[REQEST_RANK_AROUND_SIZE]; if(m_rankSet.GetMidMoreNodes(items, REQEST_RANK_AROUND_SIZE, userId)) { for(int i = 0; i < REQEST_RANK_AROUND_SIZE; ++i) { RANK_SET_T::NodeRankType& item = items[i]; ::rank::RankItemPacket* pRankItemPacket = requestRankResult.add_items(); FillRankItem(*pRankItemPacket, item.pNode->GetValue(), item.uRank, item.pNode->GetKey().GetScore()); } } } pResponse->set_result(TRUE); SerializeWorkerData(pResponse, requestRankResult); }
29.332046
97
0.721864
[ "vector" ]
65828429a636eb7ebc68620bcb0776d87f932ffd
567
cpp
C++
Cplus/EditDistance.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
1
2018-01-22T12:06:28.000Z
2018-01-22T12:06:28.000Z
Cplus/EditDistance.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
null
null
null
Cplus/EditDistance.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
null
null
null
#include <algorithm> #include <string> #include <vector> using namespace std; class Solution { public: int minDistance(string word1, string word2) { int M = word1.size(), N = word2.size(); vector<int> dp(N + 1); for (int j = 0; j < N; ++j) dp[j + 1] = dp[j] + 1; for (int i = 0; i < M; ++i) { int pre = dp[0]; dp[0] = i + 1; for (int j = 0; j < N; ++j) { int next = dp[j + 1]; if (word1[i] == word2[j]) dp[j + 1] = pre; else dp[j + 1] = min({pre, dp[j], dp[j + 1]}) + 1; pre = next; } } return dp[N]; } };
18.290323
50
0.485009
[ "vector" ]
658c40283526ea3cbdc55f0d002f7db018da261d
3,214
cc
C++
src/funct.cc
ManfredMaennle/fzymodel
fa4a07ce06b0e410f1032f45c8555f1edd4c5220
[ "MIT" ]
null
null
null
src/funct.cc
ManfredMaennle/fzymodel
fa4a07ce06b0e410f1032f45c8555f1edd4c5220
[ "MIT" ]
null
null
null
src/funct.cc
ManfredMaennle/fzymodel
fa4a07ce06b0e410f1032f45c8555f1edd4c5220
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 1999, 2020 Manfred Maennle * * 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. * * $Id: funct.cc,v 2.9 2020-08-29 10:47:36+00:00:02 manfred Exp $ */ #include <assert.h> #include "global.hh" #include "param.hh" #include "funct.hh" std::ostream& operator << (std::ostream& strm, const Function& f) { strm << f.dim() << " " << f.value() << " "; vector<Parameter*>::const_iterator p = f.parameters().begin(); while (p != f.parameters().end()) { strm << **(p++) << " " ; } return strm; } // ////////////////////////////////////////////////////////////////////// Real EllipsoidFunction::calculate() { assert(parameters_.size() == dim_); const Real c = 1.0/9.0; Real temp1 = parameters_[0]->value() - parameters_[1]->value(); Real temp2 = parameters_[0]->value() + parameters_[1]->value() - 10.0; value_ = temp1*temp1 + c*temp2*temp2; return value_; } void EllipsoidFunction::derivate() { assert(parameters_.size() == dim_); const Real c = 1.0/9.0; Parameter* p0 = parameters_[0]; Parameter* p1 = parameters_[1]; Real temp1 = p0->value() - p1->value(); Real temp2 = p0->value() + p1->value() - 10.0; p0->grad_1() = p0->grad(); p1->grad_1() = p1->grad(); p0->grad() = 2.0 * (temp1 + c*temp2); p1->grad() = 2.0 * (-temp1 + c*temp2); return; } /************************************************* * * Class: BananaFunction * * Added by Steffen Bloedt * Date: 31.01.2000 * ************************************************* */ Real BananaFunction::calculate() { assert(parameters_.size() == dim_); Real x0 = parameters_[0]->value(); Real x1 = parameters_[1]->value(); value_ = (100*(x0*x0-x1)*(x0*x0-x1)+(1-x0)*(1-x0)); return value_; } void BananaFunction::derivate() { assert(parameters_.size() == dim_); Parameter* p0 = parameters_[0]; Parameter* p1 = parameters_[1]; Real x0 = p0->value(); Real x1 = p1->value(); p0->grad_1() = p0->grad(); p1->grad_1() = p1->grad(); p0->grad() = 400*x0*(x0*x0-x1)-2*(1-x0); p1->grad() = -200*(x0*x0-x1); return; }
30.903846
82
0.597698
[ "vector" ]
659102f0a3238983a2a7399e4fcfc029719130a5
2,562
cpp
C++
Crypto/EdDSAKey.cpp
artur00231/webauthn
445e9042330d724dc58e95e53799d62011687375
[ "BSL-1.0" ]
null
null
null
Crypto/EdDSAKey.cpp
artur00231/webauthn
445e9042330d724dc58e95e53799d62011687375
[ "BSL-1.0" ]
null
null
null
Crypto/EdDSAKey.cpp
artur00231/webauthn
445e9042330d724dc58e95e53799d62011687375
[ "BSL-1.0" ]
null
null
null
#include "EdDSAKey.h" #include <memory> #include <openssl/evp.h> #include <openssl/param_build.h> #include <openssl/core_names.h> #include <iostream> std::optional<webauthn::crypto::EdDSAKey> webauthn::crypto::EdDSAKey::create(const std::vector<std::byte>& bin_x, const COSE::EdDSA_EC ec) { EdDSAKey EdDSA_key{}; switch (ec) { case COSE::EdDSA_EC::Ed25519: EdDSA_key.pkey = EVP_PKEY_new_raw_public_key(EVP_PKEY_ED25519, nullptr, reinterpret_cast<const unsigned char*>(bin_x.data()), bin_x.size()); break; case COSE::EdDSA_EC::Ed448: EdDSA_key.pkey = EVP_PKEY_new_raw_public_key(EVP_PKEY_ED448, nullptr, reinterpret_cast<const unsigned char*>(bin_x.data()), bin_x.size()); break; default: return {}; } if (EdDSA_key.pkey == nullptr) { return {}; } return EdDSA_key; } std::optional<bool> webauthn::crypto::EdDSAKey::verify(const std::string& data, const std::string& signature) const { return verify(reinterpret_cast<const unsigned char*>(data.data()), data.size(), reinterpret_cast<const unsigned char*>(signature.data()), signature.size()); } std::optional<bool> webauthn::crypto::EdDSAKey::verify(const std::vector<std::byte>& data, const std::vector<std::byte>& signature) const { return verify(reinterpret_cast<const unsigned char*>(data.data()), data.size(), reinterpret_cast<const unsigned char*>(signature.data()), signature.size()); } std::optional<bool> webauthn::crypto::EdDSAKey::verify(const unsigned char* data, std::size_t data_size, const unsigned char* signature, std::size_t signature_size) const { std::unique_ptr<EVP_MD_CTX, decltype([](EVP_MD_CTX* ptr) { if (ptr) EVP_MD_CTX_free(ptr);})>mdctx{ EVP_MD_CTX_new() }; if (!mdctx) return {}; auto result = EVP_DigestVerifyInit(mdctx.get(), NULL, NULL, NULL, pkey); if (result != 1) { return {}; } result = EVP_DigestVerify(mdctx.get(), signature, signature_size, data, data_size); if (result == 1) { return true; } if (result == 0) { return false; } return {}; } webauthn::crypto::EdDSAKey::EdDSAKey(EdDSAKey&& key) noexcept : pkey{ key.pkey } { key.pkey = nullptr; } webauthn::crypto::EdDSAKey& webauthn::crypto::EdDSAKey::operator=(EdDSAKey&& key) noexcept { pkey = key.pkey; key.pkey = nullptr; return *this; } webauthn::crypto::EdDSAKey::~EdDSAKey() { EVP_PKEY_free(pkey); }
28.786517
171
0.645589
[ "vector" ]
4f1dc1eefff184834a26dfa4cffb229c8ed98a7b
32,946
cpp
C++
src/util.cpp
farsider350/AUTX-Core
6d00d1e027a5a6dffb3b0815a155e4515ced007b
[ "MIT" ]
null
null
null
src/util.cpp
farsider350/AUTX-Core
6d00d1e027a5a6dffb3b0815a155e4515ced007b
[ "MIT" ]
null
null
null
src/util.cpp
farsider350/AUTX-Core
6d00d1e027a5a6dffb3b0815a155e4515ced007b
[ "MIT" ]
1
2021-01-03T02:35:54.000Z
2021-01-03T02:35:54.000Z
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2014-2019 The autx Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/autx-config.h" #endif #include "util.h" #include "support/allocators/secure.h" #include "chainparamsbase.h" #include "ctpl.h" #include "fs.h" #include "random.h" #include "serialize.h" #include "stacktraces.h" #include "utilstrencodings.h" #include "utiltime.h" #include <stdarg.h> #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)) #include <pthread.h> #include <pthread_np.h> #endif #ifndef WIN32 // for posix_fallocate #ifdef __linux__ #ifdef _POSIX_C_SOURCE #undef _POSIX_C_SOURCE #endif #define _POSIX_C_SOURCE 200112L #endif // __linux__ #include <algorithm> #include <fcntl.h> #include <sys/resource.h> #include <sys/stat.h> #else #ifdef _MSC_VER #pragma warning(disable:4786) #pragma warning(disable:4804) #pragma warning(disable:4805) #pragma warning(disable:4717) #endif #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include <io.h> /* for _commit */ #include <shlobj.h> #endif #ifdef HAVE_SYS_PRCTL_H #include <sys/prctl.h> #endif #ifdef HAVE_MALLOPT_ARENA_MAX #include <malloc.h> #endif #include <boost/algorithm/string/case_conv.hpp> // for to_lower() #include <boost/algorithm/string/join.hpp> #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith() #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/classification.hpp> #include <boost/program_options/detail/config_file.hpp> #include <boost/program_options/parsers.hpp> #include <boost/thread.hpp> #include <openssl/crypto.h> #include <openssl/rand.h> #include <openssl/conf.h> // Application startup time (used for uptime calculation) const int64_t nStartupTime = GetTime(); //autx only features bool fMasternodeMode = false; bool fLiteMode = false; /** nWalletBackups: 1..10 - number of automatic backups to keep 0 - disabled by command-line -1 - disabled because of some error during run-time -2 - disabled because wallet was locked and we were not able to replenish keypool */ int nWalletBackups = 10; const char * const BITCOIN_CONF_FILENAME = "autx.conf"; const char * const BITCOIN_PID_FILENAME = "autxd.pid"; ArgsManager gArgs; bool fPrintToConsole = false; bool fPrintToDebugLog = true; bool fLogTimestamps = DEFAULT_LOGTIMESTAMPS; bool fLogTimeMicros = DEFAULT_LOGTIMEMICROS; bool fLogThreadNames = DEFAULT_LOGTHREADNAMES; bool fLogIPs = DEFAULT_LOGIPS; std::atomic<bool> fReopenDebugLog(false); CTranslationInterface translationInterface; /** Log categories bitfield. */ std::atomic<uint64_t> logCategories(0); /** Init OpenSSL library multithreading support */ static std::unique_ptr<CCriticalSection[]> ppmutexOpenSSL; void locking_callback(int mode, int i, const char* file, int line) NO_THREAD_SAFETY_ANALYSIS { if (mode & CRYPTO_LOCK) { ENTER_CRITICAL_SECTION(ppmutexOpenSSL[i]); } else { LEAVE_CRITICAL_SECTION(ppmutexOpenSSL[i]); } } // Singleton for wrapping OpenSSL setup/teardown. class CInit { public: CInit() { // Init OpenSSL library multithreading support ppmutexOpenSSL.reset(new CCriticalSection[CRYPTO_num_locks()]); CRYPTO_set_locking_callback(locking_callback); // OpenSSL can optionally load a config file which lists optional loadable modules and engines. // We don't use them so we don't require the config. However some of our libs may call functions // which attempt to load the config file, possibly resulting in an exit() or crash if it is missing // or corrupt. Explicitly tell OpenSSL not to try to load the file. The result for our libs will be // that the config appears to have been loaded and there are no modules/engines available. OPENSSL_no_config(); #ifdef WIN32 // Seed OpenSSL PRNG with current contents of the screen RAND_screen(); #endif // Seed OpenSSL PRNG with performance counter RandAddSeed(); } ~CInit() { // Securely erase the memory used by the PRNG RAND_cleanup(); // Shutdown OpenSSL library multithreading support CRYPTO_set_locking_callback(nullptr); // Clear the set of locks now to maintain symmetry with the constructor. ppmutexOpenSSL.reset(); } } instance_of_cinit; /** * LogPrintf() has been broken a couple of times now * by well-meaning people adding mutexes in the most straightforward way. * It breaks because it may be called by global destructors during shutdown. * Since the order of destruction of static/global objects is undefined, * defining a mutex as a global object doesn't work (the mutex gets * destroyed, and then some later destructor calls OutputDebugStringF, * maybe indirectly, and you get a core dump at shutdown trying to lock * the mutex). */ static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT; /** * We use boost::call_once() to make sure mutexDebugLog and * vMsgsBeforeOpenLog are initialized in a thread-safe manner. * * NOTE: fileout, mutexDebugLog and sometimes vMsgsBeforeOpenLog * are leaked on exit. This is ugly, but will be cleaned up by * the OS/libc. When the shutdown sequence is fully audited and * tested, explicit destruction of these objects can be implemented. */ static FILE* fileout = nullptr; static boost::mutex* mutexDebugLog = nullptr; static std::list<std::string>* vMsgsBeforeOpenLog; static int FileWriteStr(const std::string &str, FILE *fp) { return fwrite(str.data(), 1, str.size(), fp); } static void DebugPrintInit() { assert(mutexDebugLog == nullptr); mutexDebugLog = new boost::mutex(); vMsgsBeforeOpenLog = new std::list<std::string>; } void OpenDebugLog() { boost::call_once(&DebugPrintInit, debugPrintInitFlag); boost::mutex::scoped_lock scoped_lock(*mutexDebugLog); assert(fileout == nullptr); assert(vMsgsBeforeOpenLog); fs::path pathDebug = GetDataDir() / "debug.log"; fileout = fsbridge::fopen(pathDebug, "a"); if (fileout) { setbuf(fileout, nullptr); // unbuffered // dump buffered messages from before we opened the log while (!vMsgsBeforeOpenLog->empty()) { FileWriteStr(vMsgsBeforeOpenLog->front(), fileout); vMsgsBeforeOpenLog->pop_front(); } } delete vMsgsBeforeOpenLog; vMsgsBeforeOpenLog = nullptr; } struct CLogCategoryDesc { uint64_t flag; std::string category; }; const CLogCategoryDesc LogCategories[] = { {BCLog::NONE, "0"}, {BCLog::NET, "net"}, {BCLog::TOR, "tor"}, {BCLog::MEMPOOL, "mempool"}, {BCLog::HTTP, "http"}, {BCLog::BENCHMARK, "bench"}, {BCLog::ZMQ, "zmq"}, {BCLog::DB, "db"}, {BCLog::RPC, "rpc"}, {BCLog::ESTIMATEFEE, "estimatefee"}, {BCLog::ADDRMAN, "addrman"}, {BCLog::SELECTCOINS, "selectcoins"}, {BCLog::REINDEX, "reindex"}, {BCLog::CMPCTBLOCK, "cmpctblock"}, {BCLog::RANDOM, "rand"}, {BCLog::PRUNE, "prune"}, {BCLog::PROXY, "proxy"}, {BCLog::MEMPOOLREJ, "mempoolrej"}, {BCLog::LIBEVENT, "libevent"}, {BCLog::COINDB, "coindb"}, {BCLog::QT, "qt"}, {BCLog::LEVELDB, "leveldb"}, {BCLog::ALL, "1"}, {BCLog::ALL, "all"}, //Start autx {BCLog::CHAINLOCKS, "chainlocks"}, {BCLog::GOBJECT, "gobject"}, {BCLog::INSTANTSEND, "instantsend"}, {BCLog::KEEPASS, "keepass"}, {BCLog::LLMQ, "llmq"}, {BCLog::LLMQ_DKG, "llmq-dkg"}, {BCLog::LLMQ_SIGS, "llmq-sigs"}, {BCLog::MNPAYMENTS, "mnpayments"}, {BCLog::MNSYNC, "mnsync"}, {BCLog::PRIVATESEND, "privatesend"}, {BCLog::SPORK, "spork"}, //End autx }; bool GetLogCategory(uint64_t *f, const std::string *str) { if (f && str) { if (*str == "") { *f = BCLog::ALL; return true; } if (*str == "autx") { *f = BCLog::CHAINLOCKS | BCLog::GOBJECT | BCLog::INSTANTSEND | BCLog::KEEPASS | BCLog::LLMQ | BCLog::LLMQ_DKG | BCLog::LLMQ_SIGS | BCLog::MNPAYMENTS | BCLog::MNSYNC | BCLog::PRIVATESEND | BCLog::SPORK; return true; } for (unsigned int i = 0; i < ARRAYLEN(LogCategories); i++) { if (LogCategories[i].category == *str) { *f = LogCategories[i].flag; return true; } } } return false; } std::string ListLogCategories() { std::string ret; int outcount = 0; for (unsigned int i = 0; i < ARRAYLEN(LogCategories); i++) { // Omit the special cases. if (LogCategories[i].flag != BCLog::NONE && LogCategories[i].flag != BCLog::ALL) { if (outcount != 0) ret += ", "; ret += LogCategories[i].category; outcount++; } } return ret; } std::vector<CLogCategoryActive> ListActiveLogCategories() { std::vector<CLogCategoryActive> ret; for (unsigned int i = 0; i < ARRAYLEN(LogCategories); i++) { // Omit the special cases. if (LogCategories[i].flag != BCLog::NONE && LogCategories[i].flag != BCLog::ALL) { CLogCategoryActive catActive; catActive.category = LogCategories[i].category; catActive.active = LogAcceptCategory(LogCategories[i].flag); ret.push_back(catActive); } } return ret; } std::string ListActiveLogCategoriesString() { if (logCategories == BCLog::NONE) return "0"; if (logCategories == BCLog::ALL) return "1"; std::string ret; int outcount = 0; for (unsigned int i = 0; i < ARRAYLEN(LogCategories); i++) { // Omit the special cases. if (LogCategories[i].flag != BCLog::NONE && LogCategories[i].flag != BCLog::ALL && LogAcceptCategory(LogCategories[i].flag)) { if (outcount != 0) ret += ", "; ret += LogCategories[i].category; outcount++; } } return ret; } /** * fStartedNewLine is a state variable held by the calling context that will * suppress printing of the timestamp when multiple calls are made that don't * end in a newline. Initialize it to true, and hold/manage it, in the calling context. */ static std::string LogTimestampStr(const std::string &str, std::atomic_bool *fStartedNewLine) { std::string strStamped; if (!fLogTimestamps) return str; if (*fStartedNewLine) { int64_t nTimeMicros = GetTimeMicros(); strStamped = DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nTimeMicros/1000000); if (fLogTimeMicros) strStamped += strprintf(".%06d", nTimeMicros%1000000); int64_t mocktime = GetMockTime(); if (mocktime) { strStamped += " (mocktime: " + DateTimeStrFormat("%Y-%m-%d %H:%M:%S", mocktime) + ")"; } strStamped += ' ' + str; } else strStamped = str; return strStamped; } /** * fStartedNewLine is a state variable held by the calling context that will * suppress printing of the thread name when multiple calls are made that don't * end in a newline. Initialize it to true, and hold/manage it, in the calling context. */ static std::string LogThreadNameStr(const std::string &str, std::atomic_bool *fStartedNewLine) { std::string strThreadLogged; if (!fLogThreadNames) return str; std::string strThreadName = GetThreadName(); if (*fStartedNewLine) strThreadLogged = strprintf("%16s | %s", strThreadName.c_str(), str.c_str()); else strThreadLogged = str; return strThreadLogged; } int LogPrintStr(const std::string &str) { int ret = 0; // Returns total number of characters written static std::atomic_bool fStartedNewLine(true); std::string strThreadLogged = LogThreadNameStr(str, &fStartedNewLine); std::string strTimestamped = LogTimestampStr(strThreadLogged, &fStartedNewLine); if (!str.empty() && str[str.size()-1] == '\n') fStartedNewLine = true; else fStartedNewLine = false; if (fPrintToConsole) { // print to console ret = fwrite(strTimestamped.data(), 1, strTimestamped.size(), stdout); fflush(stdout); } else if (fPrintToDebugLog) { boost::call_once(&DebugPrintInit, debugPrintInitFlag); boost::mutex::scoped_lock scoped_lock(*mutexDebugLog); // buffer if we haven't opened the log yet if (fileout == nullptr) { assert(vMsgsBeforeOpenLog); ret = strTimestamped.length(); vMsgsBeforeOpenLog->push_back(strTimestamped); } else { // reopen the log file, if requested if (fReopenDebugLog) { fReopenDebugLog = false; fs::path pathDebug = GetDataDir() / "debug.log"; if (fsbridge::freopen(pathDebug,"a",fileout) != nullptr) setbuf(fileout, nullptr); // unbuffered } ret = FileWriteStr(strTimestamped, fileout); } } return ret; } /** Interpret string as boolean, for argument parsing */ static bool InterpretBool(const std::string& strValue) { if (strValue.empty()) return true; return (atoi(strValue) != 0); } /** Turn -noX into -X=0 */ static void InterpretNegativeSetting(std::string& strKey, std::string& strValue) { if (strKey.length()>3 && strKey[0]=='-' && strKey[1]=='n' && strKey[2]=='o') { strKey = "-" + strKey.substr(3); strValue = InterpretBool(strValue) ? "0" : "1"; } } void ArgsManager::ParseParameters(int argc, const char* const argv[]) { LOCK(cs_args); mapArgs.clear(); mapMultiArgs.clear(); for (int i = 1; i < argc; i++) { std::string str(argv[i]); std::string strValue; size_t is_index = str.find('='); if (is_index != std::string::npos) { strValue = str.substr(is_index+1); str = str.substr(0, is_index); } #ifdef WIN32 boost::to_lower(str); if (boost::algorithm::starts_with(str, "/")) str = "-" + str.substr(1); #endif if (str[0] != '-') break; // Interpret --foo as -foo. // If both --foo and -foo are set, the last takes effect. if (str.length() > 1 && str[1] == '-') str = str.substr(1); InterpretNegativeSetting(str, strValue); mapArgs[str] = strValue; mapMultiArgs[str].push_back(strValue); } } std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg) { LOCK(cs_args); if (IsArgSet(strArg)) return mapMultiArgs.at(strArg); return {}; } bool ArgsManager::IsArgSet(const std::string& strArg) { LOCK(cs_args); return mapArgs.count(strArg); } std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault) { LOCK(cs_args); if (mapArgs.count(strArg)) return mapArgs[strArg]; return strDefault; } int64_t ArgsManager::GetArg(const std::string& strArg, int64_t nDefault) { LOCK(cs_args); if (mapArgs.count(strArg)) return atoi64(mapArgs[strArg]); return nDefault; } bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) { LOCK(cs_args); if (mapArgs.count(strArg)) return InterpretBool(mapArgs[strArg]); return fDefault; } bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue) { LOCK(cs_args); if (mapArgs.count(strArg)) return false; ForceSetArg(strArg, strValue); return true; } bool ArgsManager::SoftSetBoolArg(const std::string& strArg, bool fValue) { if (fValue) return SoftSetArg(strArg, std::string("1")); else return SoftSetArg(strArg, std::string("0")); } void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strValue) { LOCK(cs_args); mapArgs[strArg] = strValue; mapMultiArgs[strArg].clear(); mapMultiArgs[strArg].push_back(strValue); } void ArgsManager::ForceSetMultiArgs(const std::string& strArg, const std::vector<std::string>& values) { LOCK(cs_args); mapMultiArgs[strArg] = values; } void ArgsManager::ForceRemoveArg(const std::string& strArg) { LOCK(cs_args); mapArgs.erase(strArg); mapMultiArgs.erase(strArg); } static const int screenWidth = 79; static const int optIndent = 2; static const int msgIndent = 7; std::string HelpMessageGroup(const std::string &message) { return std::string(message) + std::string("\n\n"); } std::string HelpMessageOpt(const std::string &option, const std::string &message) { return std::string(optIndent,' ') + std::string(option) + std::string("\n") + std::string(msgIndent,' ') + FormatParagraph(message, screenWidth - msgIndent, msgIndent) + std::string("\n\n"); } static std::string FormatException(const std::exception_ptr pex, const char* pszThread) { return GetPrettyExceptionStr(pex); } void PrintExceptionContinue(const std::exception_ptr pex, const char* pszThread) { std::string message = FormatException(pex, pszThread); LogPrintf("\n\n************************\n%s\n", message); fprintf(stderr, "\n\n************************\n%s\n", message.c_str()); } fs::path GetDefaultDataDir() { // Windows < Vista: C:\Documents and Settings\Username\Application Data\autxCore // Windows >= Vista: C:\Users\Username\AppData\Roaming\autxCore // Mac: ~/Library/Application Support/autxCore // Unix: ~/.autxcore #ifdef WIN32 // Windows return GetSpecialFolderPath(CSIDL_APPDATA) / "autxCore"; #else fs::path pathRet; char* pszHome = getenv("HOME"); if (pszHome == nullptr || strlen(pszHome) == 0) pathRet = fs::path("/"); else pathRet = fs::path(pszHome); #ifdef MAC_OSX // Mac return pathRet / "Library/Application Support/autxCore"; #else // Unix return pathRet / ".autxcore"; #endif #endif } static fs::path pathCached; static fs::path pathCachedNetSpecific; static CCriticalSection csPathCached; const fs::path &GetDataDir(bool fNetSpecific) { LOCK(csPathCached); fs::path &path = fNetSpecific ? pathCachedNetSpecific : pathCached; // This can be called during exceptions by LogPrintf(), so we cache the // value so we don't have to do memory allocations after that. if (!path.empty()) return path; if (gArgs.IsArgSet("-datadir")) { path = fs::system_complete(gArgs.GetArg("-datadir", "")); if (!fs::is_directory(path)) { path = ""; return path; } } else { path = GetDefaultDataDir(); } if (fNetSpecific) path /= BaseParams().DataDir(); fs::create_directories(path); return path; } fs::path GetBackupsDir() { if (!gArgs.IsArgSet("-walletbackupsdir")) return GetDataDir() / "backups"; return fs::absolute(gArgs.GetArg("-walletbackupsdir", "")); } void ClearDatadirCache() { LOCK(csPathCached); pathCached = fs::path(); pathCachedNetSpecific = fs::path(); } fs::path GetConfigFile(const std::string& confPath) { fs::path pathConfigFile(confPath); if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile; return pathConfigFile; } void ArgsManager::ReadConfigFile(const std::string& confPath) { fs::ifstream streamConfig(GetConfigFile(confPath)); if (!streamConfig.good()){ // Create empty autx.conf if it does not excist FILE* configFile = fopen(GetConfigFile(confPath).string().c_str(), "a"); if (configFile != nullptr) fclose(configFile); return; // Nothing to read, so just return } { LOCK(cs_args); std::set<std::string> setOptions; setOptions.insert("*"); for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it) { // Don't overwrite existing settings so command line settings override autx.conf std::string strKey = std::string("-") + it->string_key; std::string strValue = it->value[0]; InterpretNegativeSetting(strKey, strValue); if (mapArgs.count(strKey) == 0) mapArgs[strKey] = strValue; mapMultiArgs[strKey].push_back(strValue); } } // If datadir is changed in .conf file: ClearDatadirCache(); } #ifndef WIN32 fs::path GetPidFile() { fs::path pathPidFile(gArgs.GetArg("-pid", BITCOIN_PID_FILENAME)); if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile; return pathPidFile; } void CreatePidFile(const fs::path &path, pid_t pid) { FILE* file = fsbridge::fopen(path, "w"); if (file) { fprintf(file, "%d\n", pid); fclose(file); } } #endif bool RenameOver(fs::path src, fs::path dest) { #ifdef WIN32 return MoveFileExA(src.string().c_str(), dest.string().c_str(), MOVEFILE_REPLACE_EXISTING) != 0; #else int rc = std::rename(src.string().c_str(), dest.string().c_str()); return (rc == 0); #endif /* WIN32 */ } /** * Ignores exceptions thrown by Boost's create_directories if the requested directory exists. * Specifically handles case where path p exists, but it wasn't possible for the user to * write to the parent directory. */ bool TryCreateDirectories(const fs::path& p) { try { return fs::create_directories(p); } catch (const fs::filesystem_error&) { if (!fs::exists(p) || !fs::is_directory(p)) throw; } // create_directories didn't create the directory, it had to have existed already return false; } void FileCommit(FILE *file) { fflush(file); // harmless if redundantly called #ifdef WIN32 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file)); FlushFileBuffers(hFile); #else #if defined(__linux__) || defined(__NetBSD__) fdatasync(fileno(file)); #elif defined(__APPLE__) && defined(F_FULLFSYNC) fcntl(fileno(file), F_FULLFSYNC, 0); #else fsync(fileno(file)); #endif #endif } bool TruncateFile(FILE *file, unsigned int length) { #if defined(WIN32) return _chsize(_fileno(file), length) == 0; #else return ftruncate(fileno(file), length) == 0; #endif } /** * this function tries to raise the file descriptor limit to the requested number. * It returns the actual file descriptor limit (which may be more or less than nMinFD) */ int RaiseFileDescriptorLimit(int nMinFD) { #if defined(WIN32) return 2048; #else struct rlimit limitFD; if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) { if (limitFD.rlim_cur < (rlim_t)nMinFD) { limitFD.rlim_cur = nMinFD; if (limitFD.rlim_cur > limitFD.rlim_max) limitFD.rlim_cur = limitFD.rlim_max; setrlimit(RLIMIT_NOFILE, &limitFD); getrlimit(RLIMIT_NOFILE, &limitFD); } return limitFD.rlim_cur; } return nMinFD; // getrlimit failed, assume it's fine #endif } /** * this function tries to make a particular range of a file allocated (corresponding to disk space) * it is advisory, and the range specified in the arguments will never contain live data */ void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) { #if defined(WIN32) // Windows-specific version HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file)); LARGE_INTEGER nFileSize; int64_t nEndPos = (int64_t)offset + length; nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF; nFileSize.u.HighPart = nEndPos >> 32; SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN); SetEndOfFile(hFile); #elif defined(MAC_OSX) // OSX specific version fstore_t fst; fst.fst_flags = F_ALLOCATECONTIG; fst.fst_posmode = F_PEOFPOSMODE; fst.fst_offset = 0; fst.fst_length = (off_t)offset + length; fst.fst_bytesalloc = 0; if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) { fst.fst_flags = F_ALLOCATEALL; fcntl(fileno(file), F_PREALLOCATE, &fst); } ftruncate(fileno(file), fst.fst_length); #elif defined(__linux__) // Version using posix_fallocate off_t nEndPos = (off_t)offset + length; posix_fallocate(fileno(file), 0, nEndPos); #else // Fallback version // TODO: just write one byte per block static const char buf[65536] = {}; fseek(file, offset, SEEK_SET); while (length > 0) { unsigned int now = 65536; if (length < now) now = length; fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway length -= now; } #endif } void ShrinkDebugFile() { // Amount of debug.log to save at end when shrinking (must fit in memory) constexpr size_t RECENT_DEBUG_HISTORY_SIZE = 10 * 1000000; // Scroll debug.log if it's getting too big fs::path pathLog = GetDataDir() / "debug.log"; FILE* file = fsbridge::fopen(pathLog, "r"); // If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE // trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes if (file && fs::file_size(pathLog) > 11 * (RECENT_DEBUG_HISTORY_SIZE / 10)) { // Restart the file with some of the end std::vector<char> vch(RECENT_DEBUG_HISTORY_SIZE, 0); fseek(file, -((long)vch.size()), SEEK_END); int nBytes = fread(vch.data(), 1, vch.size(), file); fclose(file); file = fsbridge::fopen(pathLog, "w"); if (file) { fwrite(vch.data(), 1, nBytes, file); fclose(file); } } else if (file != nullptr) fclose(file); } #ifdef WIN32 fs::path GetSpecialFolderPath(int nFolder, bool fCreate) { char pszPath[MAX_PATH] = ""; if(SHGetSpecialFolderPathA(nullptr, pszPath, nFolder, fCreate)) { return fs::path(pszPath); } LogPrintf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n"); return fs::path(""); } #endif void runCommand(const std::string& strCommand) { int nErr = ::system(strCommand.c_str()); if (nErr) LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr); } void RenameThread(const char* name) { #if defined(PR_SET_NAME) // Only the first 15 characters are used (16 - NUL terminator) ::prctl(PR_SET_NAME, name, 0, 0, 0); #elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)) pthread_set_name_np(pthread_self(), name); #elif defined(MAC_OSX) pthread_setname_np(name); #else // Prevent warnings for unused parameters... (void)name; #endif LogPrintf("%s: thread new name %s\n", __func__, name); } std::string GetThreadName() { char name[16]; #if defined(PR_GET_NAME) // Only the first 15 characters are used (16 - NUL terminator) ::prctl(PR_GET_NAME, name, 0, 0, 0); #elif defined(MAC_OSX) pthread_getname_np(pthread_self(), name, 16); // #elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)) // #else // no get_name here #endif return std::string(name); } void RenameThreadPool(ctpl::thread_pool& tp, const char* baseName) { auto cond = std::make_shared<std::condition_variable>(); auto mutex = std::make_shared<std::mutex>(); std::atomic<int> doneCnt(0); std::map<int, std::future<void> > futures; for (int i = 0; i < tp.size(); i++) { futures[i] = tp.push([baseName, i, cond, mutex, &doneCnt](int threadId) { RenameThread(strprintf("%s-%d", baseName, i).c_str()); std::unique_lock<std::mutex> l(*mutex); doneCnt++; cond->wait(l); }); } do { // Always sleep to let all threads acquire locks MilliSleep(10); // `doneCnt` should be at least `futures.size()` if tp size was increased (for whatever reason), // or at least `tp.size()` if tp size was decreased and queue was cleared // (which can happen on `stop()` if we were not fast enough to get all jobs to their threads). } while (doneCnt < futures.size() && doneCnt < tp.size()); cond->notify_all(); // Make sure no one is left behind, just in case for (auto& pair : futures) { auto& f = pair.second; if (f.valid() && f.wait_for(std::chrono::milliseconds(2000)) == std::future_status::timeout) { LogPrintf("%s: %s-%d timed out\n", __func__, baseName, pair.first); // Notify everyone again cond->notify_all(); break; } } } void SetupEnvironment() { #ifdef HAVE_MALLOPT_ARENA_MAX // glibc-specific: On 32-bit systems set the number of arenas to 1. // By default, since glibc 2.10, the C library will create up to two heap // arenas per core. This is known to cause excessive virtual address space // usage in our usage. Work around it by setting the maximum number of // arenas to 1. if (sizeof(void*) == 4) { mallopt(M_ARENA_MAX, 1); } #endif // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale // may be invalid, in which case the "C" locale is used as fallback. #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__) try { std::locale(""); // Raises a runtime error if current locale is invalid } catch (const std::runtime_error&) { setenv("LC_ALL", "C", 1); } #endif // The path locale is lazy initialized and to avoid deinitialization errors // in multithreading environments, it is set explicitly by the main thread. // A dummy locale is used to extract the internal default locale, used by // fs::path, which is then used to explicitly imbue the path. std::locale loc = fs::path::imbue(std::locale::classic()); fs::path::imbue(loc); } bool SetupNetworking() { #ifdef WIN32 // Initialize Windows Sockets WSADATA wsadata; int ret = WSAStartup(MAKEWORD(2,2), &wsadata); if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2) return false; #endif return true; } int GetNumCores() { #if BOOST_VERSION >= 105600 return boost::thread::physical_concurrency(); #else // Must fall back to hardware_concurrency, which unfortunately counts virtual cores return boost::thread::hardware_concurrency(); #endif } std::string CopyrightHolders(const std::string& strPrefix, unsigned int nStartYear, unsigned int nEndYear) { std::string strCopyrightHolders = strPrefix + strprintf(" %u-%u ", nStartYear, nEndYear) + strprintf(_(COPYRIGHT_HOLDERS), _(COPYRIGHT_HOLDERS_SUBSTITUTION)); // Check for untranslated substitution to make sure Bitcoin Core copyright is not removed by accident if (strprintf(COPYRIGHT_HOLDERS, COPYRIGHT_HOLDERS_SUBSTITUTION).find("Bitcoin Core") == std::string::npos) { strCopyrightHolders += "\n" + strPrefix + strprintf(" %u-%u ", 2009, nEndYear) + "The Bitcoin Core developers"; } return strCopyrightHolders; } uint32_t StringVersionToInt(const std::string& strVersion) { std::vector<std::string> tokens; boost::split(tokens, strVersion, boost::is_any_of(".")); if(tokens.size() != 3) throw std::bad_cast(); uint32_t nVersion = 0; for(unsigned idx = 0; idx < 3; idx++) { if(tokens[idx].length() == 0) throw std::bad_cast(); uint32_t value = boost::lexical_cast<uint32_t>(tokens[idx]); if(value > 255) throw std::bad_cast(); nVersion <<= 8; nVersion |= value; } return nVersion; } std::string IntVersionToString(uint32_t nVersion) { if((nVersion >> 24) > 0) // MSB is always 0 throw std::bad_cast(); if(nVersion == 0) throw std::bad_cast(); std::array<std::string, 3> tokens; for(unsigned idx = 0; idx < 3; idx++) { unsigned shift = (2 - idx) * 8; uint32_t byteValue = (nVersion >> shift) & 0xff; tokens[idx] = boost::lexical_cast<std::string>(byteValue); } return boost::join(tokens, "."); } std::string SafeIntVersionToString(uint32_t nVersion) { try { return IntVersionToString(nVersion); } catch(const std::bad_cast&) { return "invalid_version"; } } // Obtain the application startup time (used for uptime calculation) int64_t GetStartupTime() { return nStartupTime; }
29.654365
162
0.644206
[ "object", "vector" ]
4f1e02bb777a13471aafafdc846a4be095a95362
6,312
cpp
C++
src/patterngen/pattern_extractor/types/symbol_pattern.cpp
mehrdad-shokri/retdec
a82f16e97b163afe789876e0a819489c5b9b358e
[ "MIT", "Zlib", "BSD-3-Clause" ]
4,816
2017-12-12T18:07:09.000Z
2019-04-17T02:01:04.000Z
src/patterngen/pattern_extractor/types/symbol_pattern.cpp
mehrdad-shokri/retdec
a82f16e97b163afe789876e0a819489c5b9b358e
[ "MIT", "Zlib", "BSD-3-Clause" ]
514
2017-12-12T18:22:52.000Z
2019-04-16T16:07:11.000Z
src/patterngen/pattern_extractor/types/symbol_pattern.cpp
mehrdad-shokri/retdec
a82f16e97b163afe789876e0a819489c5b9b358e
[ "MIT", "Zlib", "BSD-3-Clause" ]
579
2017-12-12T18:38:02.000Z
2019-04-11T13:32:53.000Z
/** * @file src/patterngen/pattern_extractor/types/symbol_pattern.cpp * @brief Class representing pattern of one symbol. * @copyright (c) 2017 Avast Software, licensed under the MIT license */ #include <set> #include "retdec/utils/container.h" #include "retdec/utils/conversion.h" #include "retdec/utils/string.h" #include "retdec/patterngen/pattern_extractor/types/symbol_pattern.h" #include "yaramod/builder/yara_expression_builder.h" #include "yaramod/builder/yara_file_builder.h" #include "yaramod/builder/yara_rule_builder.h" using namespace retdec::utils; using namespace yaramod; namespace retdec { namespace patterngen { /** * Format string of references as offset-name pairs. * * @return string with references */ std::string SymbolPattern::getReferenceString() const { std::string result; std::vector<std::string> used; for (const auto &ref : refs) { // Accept only valid C language identifiers. if (!ref.name.empty() && isPrintable(ref.name)) { // Only first reference is printed. if (!hasItem(used, ref.name)) { result += intToHexString(ref.offset, false, 4) + " " + ref.name + " "; used.push_back(ref.name); } } } if (!result.empty()) { // Pop space after last reference name. result.pop_back(); } return result; } /** * Get hexadecimal pattern. * * @return shared pointer to HexString pattern */ std::shared_ptr<HexString> SymbolPattern::getHexPattern() const { YaraHexStringBuilder patternBuilder; // Create relocation map (no relocations by default - 0x00). std::vector<std::uint8_t> relocMap(data.size(), 0x00); for (const auto &r : refs) { for (std::size_t i = 0, e = r.mask.size(); i < e; ++i) { // We have to read mask in reverse order if big endian. relocMap[r.offset + i] |= isLittle ? r.mask[i] : r.mask[e - i - 1]; } } // Create hexadecimal pattern. for (std::size_t i = 0, e = data.size(); i < e; ++i) { createBytePattern(relocMap[i], data[i], patternBuilder); } return patternBuilder.get(); } /** * Create pattern for one byte. * * @param mask relocation mask * @param byte source byte * @param builder builder to add byte pattern to */ void SymbolPattern::createBytePattern( std::uint8_t mask, std::uint8_t byte, YaraHexStringBuilder &builder) const { if (!mask) { // No mask - no relocation. builder.add(byte); return; } if (mask & 0xF0) { if (mask & 0x0F) { // Both high and low nibbles are relocated - full wildcard. builder.add(wildcard()); } else { // Only high nibble is affected. builder.add(wildcardHigh(byte & 0x0F)); } } else { // Only low nibble is affected. builder.add(wildcardLow((byte & 0xF0) >> 4)); } } /** * Default constructor. * * @param isLittleEndian byte endianness * @param wordBitWidth word length in bits */ SymbolPattern::SymbolPattern( bool isLittleEndian, std::size_t wordBitWidth) : isLittle(isLittleEndian), bitWidth(wordBitWidth) { } /** * Set symbol name. * * If not provided, string 'unknown_symbol' is used. * * @param symbolName name of symbol */ void SymbolPattern::setName( const std::string &symbolName) { this->symbolName = symbolName; } /** * Set rule name. * * If not provided, string 'unknown_rule' is used. Only alpha-numeric chars are * allowed, others are replaced with underscore. * * @param ruleName name of rule */ void SymbolPattern::setRuleName( const std::string &ruleName) { this->ruleName = replaceNonalnumCharsWith(ruleName, '_'); } /** * Set source path. * * If not provided, attribute is omitted. * * @param filePath path to source file */ void SymbolPattern::setSourcePath( const std::string &filePath) { metas.emplace_back("source", filePath); } /** * Set architecture name path. * * If not provided, attribute is omitted. * * @param archName architecture name */ void SymbolPattern::setArchitectureName( const std::string &archName) { metas.emplace_back("architecture", archName); } /** * Load symbol data by move. * * @param symbolData symbol data */ void SymbolPattern::loadData( std::vector<unsigned char> &&symbolData) { data = std::move(symbolData); } /** * Load symbol data. * * @param symbolData symbol data */ void SymbolPattern::loadData( const std::vector<unsigned char> &symbolData) { data = symbolData; } /** * Add one symbol relocation/reference. * * @param refName name of referenced symbol * @param offset offset of reference in symbol data * @param mask relocation mask vector */ void SymbolPattern::addReference( const std::string &refName, const std::size_t &offset, const std::vector<std::uint8_t> &mask) { refs.push_back(Reference{refName, offset, mask}); } /** * Print pattern as YARA rule to stream. * * @param outputStream stream to print information to * @param withNote optional note that will be added to the rule */ void SymbolPattern::printYaraRule( std::ostream &outputStream, const std::string &withNote) const { if (data.empty()) { return; } YaraFileBuilder newFile; addRuleToBuilder(newFile, withNote); outputStream << newFile.get(false)->getText() << "\n"; } /** * Add pattern to yaramod file builder. * * @param yaraBuilder builder to add rule to * @param withNote optional note that will be added to the rule */ void SymbolPattern::addRuleToBuilder( YaraFileBuilder &yaraBuilder, const std::string &withNote) const { YaraRuleBuilder ruleBuilder; // Names. ruleBuilder.withName(ruleName.empty() ? "unknown_rule" : ruleName); ruleBuilder.withStringMeta("name", symbolName.empty() ? "unknown_symbol" : symbolName); // Basic architecture info. ruleBuilder.withIntMeta("size", data.size()); ruleBuilder.withIntMeta("bitWidth", bitWidth); ruleBuilder.withStringMeta("endianness", isLittle ? "little" : "big"); // Optional metas. for (const auto &meta : metas) { ruleBuilder.withStringMeta(meta.first, meta.second); } // Optional notes. if (!withNote.empty()) { ruleBuilder.withStringMeta("notes", withNote); } // Condition. ruleBuilder.withHexString("$1", getHexPattern()); ruleBuilder.withCondition(stringRef("$1").get()); // References. auto refList = getReferenceString(); if (!refList.empty()) { ruleBuilder.withStringMeta("refs", refList); } yaraBuilder.withRule(ruleBuilder.get()); } } // namespace patterngen } // namespace retdec
22.542857
79
0.700412
[ "vector" ]
4f20b197725c0076331049678f18473a4b322c97
60,298
cpp
C++
pcm.cpp
CrabJounrnal/pcm
3756d595b2e0e69d7fa04eab194fcc70048aba62
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
pcm.cpp
CrabJounrnal/pcm
3756d595b2e0e69d7fa04eab194fcc70048aba62
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
pcm.cpp
CrabJounrnal/pcm
3756d595b2e0e69d7fa04eab194fcc70048aba62
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2009-2020, Intel Corporation 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 Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // written by Roman Dementiev, // Thomas Willhalm, // Patrick Ungerer /*! \file pcm.cpp \brief Example of using CPU counters: implements a simple performance counter monitoring utility */ #include <iostream> #ifdef _MSC_VER #include <windows.h> #include "../PCM_Win/windriver.h" #else #include <unistd.h> #include <signal.h> // for atexit() #include <sys/time.h> // for gettimeofday() #endif #include <math.h> #include <iomanip> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <cstring> #include <sstream> #include <assert.h> #include <bitset> #include "cpucounters.h" #include "utils.h" #define SIZE (10000000) #define PCM_DELAY_DEFAULT 1.0 // in seconds #define PCM_DELAY_MIN 0.015 // 15 milliseconds is practical on most modern CPUs #define MAX_CORES 4096 using namespace std; using namespace pcm; template <class IntType> double float_format(IntType n) { return double(n) / 1e6; } std::string temp_format(int32 t) { char buffer[1024]; if (t == PCM_INVALID_THERMAL_HEADROOM) return "N/A"; snprintf(buffer, 1024, "%2d", t); return buffer; } std::string l3cache_occ_format(uint64 o) { char buffer[1024]; if (o == PCM_INVALID_QOS_MONITORING_DATA) return "N/A"; snprintf(buffer, 1024, "%6d", (uint32) o); return buffer; } template <class UncoreStateType> double getAverageUncoreFrequencyGhz(const UncoreStateType& before, const UncoreStateType& after) // in GHz { return getAverageUncoreFrequency(before, after) / 1e9; } void print_help(const string prog_name) { cerr << "\n Usage: \n " << prog_name << " --help | [delay] [options] [-- external_program [external_program_options]]\n"; cerr << " <delay> => time interval to sample performance counters.\n"; cerr << " If not specified, or 0, with external program given\n"; cerr << " will read counters only after external program finishes\n"; cerr << " Supported <options> are: \n"; cerr << " -h | --help | /h => print this help and exit\n"; #ifdef _MSC_VER cerr << " --uninstallDriver | --installDriver=> (un)install driver\n"; #endif cerr << " -r | --reset | /reset => reset PMU configuration (at your own risk)\n"; cerr << " -nc | --nocores | /nc => hide core related output\n"; cerr << " -yc | --yescores | /yc => enable specific cores to output\n"; cerr << " -ns | --nosockets | /ns => hide socket related output\n"; cerr << " -nsys | --nosystem | /nsys => hide system related output\n"; cerr << " -m | --multiple-instances | /m => allow multiple PCM instances running in parallel\n"; cerr << " -csv[=file.csv] | /csv[=file.csv] => output compact CSV format to screen or\n" << " to a file, in case filename is provided\n" << " the format used is documented here: https://www.intel.com/content/www/us/en/developer/articles/technical/intel-pcm-column-names-decoder-ring.html\n"; cerr << " -i[=number] | /i[=number] => allow to determine number of iterations\n"; print_help_force_rtm_abort_mode(37); cerr << " Examples:\n"; cerr << " " << prog_name << " 1 -nc -ns => print counters every second without core and socket output\n"; cerr << " " << prog_name << " 1 -i=10 => print counters every second 10 times and exit\n"; cerr << " " << prog_name << " 0.5 -csv=test.log => twice a second save counter values to test.log in CSV format\n"; cerr << " " << prog_name << " /csv 5 2>/dev/null => one sampe every 5 seconds, and discard all diagnostic output\n"; cerr << "\n"; } template <class State> void print_basic_metrics(const PCM * m, const State & state1, const State & state2) { cout << " " << getExecUsage(state1, state2) << " " << getIPC(state1, state2) << " " << getRelativeFrequency(state1, state2); if (m->isActiveRelativeFrequencyAvailable()) cout << " " << getActiveRelativeFrequency(state1, state2); if (m->isL3CacheMissesAvailable()) cout << " " << unit_format(getL3CacheMisses(state1, state2)); if (m->isL2CacheMissesAvailable()) cout << " " << unit_format(getL2CacheMisses(state1, state2)); if (m->isL3CacheHitRatioAvailable()) cout << " " << getL3CacheHitRatio(state1, state2); if (m->isL2CacheHitRatioAvailable()) cout << " " << getL2CacheHitRatio(state1, state2); if (m->isL3CacheMissesAvailable()) cout << " " << double(getL3CacheMisses(state1, state2)) / getInstructionsRetired(state1, state2); if (m->isL2CacheMissesAvailable()) cout << " " << double(getL2CacheMisses(state1, state2)) / getInstructionsRetired(state1, state2); } template <class State> void print_other_metrics(const PCM * m, const State & state1, const State & state2) { if (m->L3CacheOccupancyMetricAvailable()) cout << " " << setw(6) << l3cache_occ_format(getL3CacheOccupancy(state2)); if (m->CoreLocalMemoryBWMetricAvailable()) cout << " " << setw(6) << getLocalMemoryBW(state1, state2); if (m->CoreRemoteMemoryBWMetricAvailable()) cout << " " << setw(6) << getRemoteMemoryBW(state1, state2); cout << " " << temp_format(state2.getThermalHeadroom()) << "\n"; } void print_output(PCM * m, const std::vector<CoreCounterState> & cstates1, const std::vector<CoreCounterState> & cstates2, const std::vector<SocketCounterState> & sktstate1, const std::vector<SocketCounterState> & sktstate2, const std::bitset<MAX_CORES> & ycores, const SystemCounterState& sstate1, const SystemCounterState& sstate2, const int cpu_model, const bool show_core_output, const bool show_partial_core_output, const bool show_socket_output, const bool show_system_output ) { cout << "\n"; cout << " EXEC : instructions per nominal CPU cycle\n"; cout << " IPC : instructions per CPU cycle\n"; cout << " FREQ : relation to nominal CPU frequency='unhalted clock ticks'/'invariant timer ticks' (includes Intel Turbo Boost)\n"; if (m->isActiveRelativeFrequencyAvailable()) cout << " AFREQ : relation to nominal CPU frequency while in active state (not in power-saving C state)='unhalted clock ticks'/'invariant timer ticks while in C0-state' (includes Intel Turbo Boost)\n"; if (m->isL3CacheMissesAvailable()) cout << " L3MISS: L3 (read) cache misses \n"; if (m->isL2CacheHitsAvailable()) { if (m->isAtom() || cpu_model == PCM::KNL) cout << " L2MISS: L2 (read) cache misses \n"; else cout << " L2MISS: L2 (read) cache misses (including other core's L2 cache *hits*) \n"; } if (m->isL3CacheHitRatioAvailable()) cout << " L3HIT : L3 (read) cache hit ratio (0.00-1.00)\n"; if (m->isL2CacheHitRatioAvailable()) cout << " L2HIT : L2 cache hit ratio (0.00-1.00)\n"; if (m->isL3CacheMissesAvailable()) cout << " L3MPI : number of L3 (read) cache misses per instruction\n"; if (m->isL2CacheMissesAvailable()) cout << " L2MPI : number of L2 (read) cache misses per instruction\n"; if (m->memoryTrafficMetricsAvailable()) cout << " READ : bytes read from main memory controller (in GBytes)\n"; if (m->memoryTrafficMetricsAvailable()) cout << " WRITE : bytes written to main memory controller (in GBytes)\n"; if (m->localMemoryRequestRatioMetricAvailable()) cout << " LOCAL : ratio of local memory requests to memory controller in %\n"; if (m->LLCReadMissLatencyMetricsAvailable()) cout << "LLCRDMISSLAT: average latency of last level cache miss for reads and prefetches (in ns)\n"; if (m->PMMTrafficMetricsAvailable()) cout << " PMM RD : bytes read from PMM memory (in GBytes)\n"; if (m->PMMTrafficMetricsAvailable()) cout << " PMM WR : bytes written to PMM memory (in GBytes)\n"; if (m->MCDRAMmemoryTrafficMetricsAvailable()) cout << " MCDRAM READ : bytes read from MCDRAM controller (in GBytes)\n"; if (m->MCDRAMmemoryTrafficMetricsAvailable()) cout << " MCDRAM WRITE : bytes written to MCDRAM controller (in GBytes)\n"; if (m->memoryIOTrafficMetricAvailable()) { cout << " IO : bytes read/written due to IO requests to memory controller (in GBytes); this may be an over estimate due to same-cache-line partial requests\n"; cout << " IA : bytes read/written due to IA requests to memory controller (in GBytes); this may be an over estimate due to same-cache-line partial requests\n"; cout << " GT : bytes read/written due to GT requests to memory controller (in GBytes); this may be an over estimate due to same-cache-line partial requests\n"; } if (m->L3CacheOccupancyMetricAvailable()) cout << " L3OCC : L3 occupancy (in KBytes)\n"; if (m->CoreLocalMemoryBWMetricAvailable()) cout << " LMB : L3 cache external bandwidth satisfied by local memory (in MBytes)\n"; if (m->CoreRemoteMemoryBWMetricAvailable()) cout << " RMB : L3 cache external bandwidth satisfied by remote memory (in MBytes)\n"; cout << " TEMP : Temperature reading in 1 degree Celsius relative to the TjMax temperature (thermal headroom): 0 corresponds to the max temperature\n"; cout << " energy: Energy in Joules\n"; cout << "\n"; cout << "\n"; const char * longDiv = "---------------------------------------------------------------------------------------------------------------\n"; cout.precision(2); cout << std::fixed; if (cpu_model == PCM::KNL) cout << " Proc Tile Core Thread |"; else cout << " Core (SKT) |"; cout << " EXEC | IPC | FREQ |"; if (m->isActiveRelativeFrequencyAvailable()) cout << " AFREQ |"; if (m->isL3CacheMissesAvailable()) cout << " L3MISS |"; if (m->isL2CacheMissesAvailable()) cout << " L2MISS |"; if (m->isL3CacheHitRatioAvailable()) cout << " L3HIT |"; if (m->isL2CacheHitRatioAvailable()) cout << " L2HIT |"; if (m->isL3CacheMissesAvailable()) cout << " L3MPI |"; if (m->isL2CacheMissesAvailable()) cout << " L2MPI | "; if (m->L3CacheOccupancyMetricAvailable()) cout << " L3OCC |"; if (m->CoreLocalMemoryBWMetricAvailable()) cout << " LMB |"; if (m->CoreRemoteMemoryBWMetricAvailable()) cout << " RMB |"; cout << " TEMP\n\n"; if (show_core_output) { for (uint32 i = 0; i < m->getNumCores(); ++i) { if (m->isCoreOnline(i) == false || (show_partial_core_output && ycores.test(i) == false)) continue; if (cpu_model == PCM::KNL) cout << setfill(' ') << internal << setw(5) << i << setw(5) << m->getTileId(i) << setw(5) << m->getCoreId(i) << setw(7) << m->getThreadId(i); else cout << " " << setw(3) << i << " " << setw(2) << m->getSocketId(i); print_basic_metrics(m, cstates1[i], cstates2[i]); print_other_metrics(m, cstates1[i], cstates2[i]); } } if (show_socket_output) { if (!(m->getNumSockets() == 1 && (m->isAtom() || cpu_model == PCM::KNL))) { cout << longDiv; for (uint32 i = 0; i < m->getNumSockets(); ++i) { cout << " SKT " << setw(2) << i; print_basic_metrics(m, sktstate1[i], sktstate2[i]); print_other_metrics(m, sktstate1[i], sktstate2[i]); } } } cout << longDiv; if (show_system_output) { if (cpu_model == PCM::KNL) cout << setw(22) << left << " TOTAL" << internal << setw(7-5); else cout << " TOTAL *"; print_basic_metrics(m, sstate1, sstate2); if (m->L3CacheOccupancyMetricAvailable()) cout << " N/A "; if (m->CoreLocalMemoryBWMetricAvailable()) cout << " N/A "; if (m->CoreRemoteMemoryBWMetricAvailable()) cout << " N/A "; cout << " N/A\n"; cout << "\n Instructions retired: " << unit_format(getInstructionsRetired(sstate1, sstate2)) << " ; Active cycles: " << unit_format(getCycles(sstate1, sstate2)) << " ; Time (TSC): " << unit_format(getInvariantTSC(cstates1[0], cstates2[0])) << "ticks ; C0 (active,non-halted) core residency: " << (getCoreCStateResidency(0, sstate1, sstate2)*100.) << " %\n"; cout << "\n"; for (int s = 1; s <= PCM::MAX_C_STATE; ++s) { if (m->isCoreCStateResidencySupported(s)) { std::cout << " C" << s << " core residency: " << (getCoreCStateResidency(s, sstate1, sstate2)*100.) << " %;"; } } cout << "\n"; std::vector<StackedBarItem> CoreCStateStackedBar, PackageCStateStackedBar; for (int s = 0; s <= PCM::MAX_C_STATE; ++s) { std::ostringstream sstr(std::ostringstream::out); sstr << std::hex << s; const char fill = sstr.str().c_str()[0]; if (m->isCoreCStateResidencySupported(s)) { CoreCStateStackedBar.push_back(StackedBarItem(getCoreCStateResidency(s, sstate1, sstate2), "", fill)); } if (m->isPackageCStateResidencySupported(s)) { std::cout << " C" << s << " package residency: " << (getPackageCStateResidency(s, sstate1, sstate2)*100.) << " %;"; PackageCStateStackedBar.push_back(StackedBarItem(getPackageCStateResidency(s, sstate1, sstate2), "", fill)); } } cout << "\n"; drawStackedBar(" Core C-state distribution", CoreCStateStackedBar, 80); drawStackedBar(" Package C-state distribution", PackageCStateStackedBar, 80); if (m->getNumCores() == m->getNumOnlineCores()) { cout << "\n PHYSICAL CORE IPC : " << getCoreIPC(sstate1, sstate2) << " => corresponds to " << 100. * (getCoreIPC(sstate1, sstate2) / double(m->getMaxIPC())) << " % utilization for cores in active state"; cout << "\n Instructions per nominal CPU cycle: " << getTotalExecUsage(sstate1, sstate2) << " => corresponds to " << 100. * (getTotalExecUsage(sstate1, sstate2) / double(m->getMaxIPC())) << " % core utilization over time interval\n"; } if (m->isHWTMAL1Supported()) { cout << " Pipeline stalls: Frontend bound: " << int(100. * getFrontendBound(sstate1, sstate2)) << " %, bad Speculation: " << int(100. * getBadSpeculation(sstate1, sstate2)) << " %, Backend bound: " << int(100. * getBackendBound(sstate1, sstate2)) << " %, Retiring: " << int(100. * getRetiring(sstate1, sstate2)) << " %\n"; std::vector<StackedBarItem> TMAStackedBar; TMAStackedBar.push_back(StackedBarItem(getFrontendBound(sstate1, sstate2), "", 'F')); TMAStackedBar.push_back(StackedBarItem(getBadSpeculation(sstate1, sstate2), "", 'S')); TMAStackedBar.push_back(StackedBarItem(getBackendBound(sstate1, sstate2), "", 'B')); TMAStackedBar.push_back(StackedBarItem(getRetiring(sstate1, sstate2), "", 'R')); drawStackedBar(" Pipeline stall distribution ", TMAStackedBar, 80); cout << "\n"; } cout << " SMI count: " << getSMICount(sstate1, sstate2) << "\n"; } if (show_socket_output) { if (m->getNumSockets() > 1 && m->incomingQPITrafficMetricsAvailable()) // QPI info only for multi socket systems { cout << "\nIntel(r) " << m->xPI() << " data traffic estimation in bytes (data traffic coming to CPU/socket through " << m->xPI() << " links):\n\n"; const uint32 qpiLinks = (uint32)m->getQPILinksPerSocket(); cout << " "; for (uint32 i = 0; i < qpiLinks; ++i) cout << " " << m->xPI() << i << " "; if (m->qpiUtilizationMetricsAvailable()) { cout << "| "; for (uint32 i = 0; i < qpiLinks; ++i) cout << " " << m->xPI() << i << " "; } cout << "\n" << longDiv; for (uint32 i = 0; i < m->getNumSockets(); ++i) { cout << " SKT " << setw(2) << i << " "; for (uint32 l = 0; l < qpiLinks; ++l) cout << unit_format(getIncomingQPILinkBytes(i, l, sstate1, sstate2)) << " "; if (m->qpiUtilizationMetricsAvailable()) { cout << "| "; for (uint32 l = 0; l < qpiLinks; ++l) cout << setw(3) << std::dec << int(100. * getIncomingQPILinkUtilization(i, l, sstate1, sstate2)) << "% "; } cout << "\n"; } } } if (show_system_output) { cout << longDiv; if (m->getNumSockets() > 1 && m->incomingQPITrafficMetricsAvailable()) // QPI info only for multi socket systems cout << "Total " << m->xPI() << " incoming data traffic: " << unit_format(getAllIncomingQPILinkBytes(sstate1, sstate2)) << " " << m->xPI() << " data traffic/Memory controller traffic: " << getQPItoMCTrafficRatio(sstate1, sstate2) << "\n"; } if (show_socket_output) { if (m->getNumSockets() > 1 && (m->outgoingQPITrafficMetricsAvailable())) // QPI info only for multi socket systems { cout << "\nIntel(r) " << m->xPI() << " traffic estimation in bytes (data and non-data traffic outgoing from CPU/socket through " << m->xPI() << " links):\n\n"; const uint32 qpiLinks = (uint32)m->getQPILinksPerSocket(); cout << " "; for (uint32 i = 0; i < qpiLinks; ++i) cout << " " << m->xPI() << i << " "; cout << "| "; for (uint32 i = 0; i < qpiLinks; ++i) cout << " " << m->xPI() << i << " "; cout << "\n" << longDiv; for (uint32 i = 0; i < m->getNumSockets(); ++i) { cout << " SKT " << setw(2) << i << " "; for (uint32 l = 0; l < qpiLinks; ++l) cout << unit_format(getOutgoingQPILinkBytes(i, l, sstate1, sstate2)) << " "; cout << "| "; for (uint32 l = 0; l < qpiLinks; ++l) cout << setw(3) << std::dec << int(100. * getOutgoingQPILinkUtilization(i, l, sstate1, sstate2)) << "% "; cout << "\n"; } cout << longDiv; cout << "Total " << m->xPI() << " outgoing data and non-data traffic: " << unit_format(getAllOutgoingQPILinkBytes(sstate1, sstate2)) << "\n"; } } if (show_socket_output) { cout << "MEM (GB)->|"; if (m->memoryTrafficMetricsAvailable()) cout << " READ | WRITE |"; if (m->localMemoryRequestRatioMetricAvailable()) cout << " LOCAL |"; if (m->PMMTrafficMetricsAvailable()) cout << " PMM RD | PMM WR |"; if (m->MCDRAMmemoryTrafficMetricsAvailable()) cout << " MCDRAM READ | MCDRAM WRITE |"; if (m->memoryIOTrafficMetricAvailable()) cout << " IO |"; if (m->memoryIOTrafficMetricAvailable()) cout << " IA |"; if (m->memoryIOTrafficMetricAvailable()) cout << " GT |"; if (m->packageEnergyMetricsAvailable()) cout << " CPU energy |"; if (m->dramEnergyMetricsAvailable()) cout << " DIMM energy |"; if (m->LLCReadMissLatencyMetricsAvailable()) cout << " LLCRDMISSLAT (ns)"; if (m->uncoreFrequencyMetricAvailable()) cout << " UncFREQ (Ghz)"; cout << "\n"; cout << longDiv; for (uint32 i = 0; i < m->getNumSockets(); ++i) { cout << " SKT " << setw(2) << i; if (m->memoryTrafficMetricsAvailable()) cout << " " << setw(5) << getBytesReadFromMC(sktstate1[i], sktstate2[i]) / double(1e9) << " " << setw(5) << getBytesWrittenToMC(sktstate1[i], sktstate2[i]) / double(1e9); if (m->localMemoryRequestRatioMetricAvailable()) cout << " " << setw(3) << int(100.* getLocalMemoryRequestRatio(sktstate1[i], sktstate2[i])) << " %"; if (m->PMMTrafficMetricsAvailable()) cout << " " << setw(5) << getBytesReadFromPMM(sktstate1[i], sktstate2[i]) / double(1e9) << " " << setw(5) << getBytesWrittenToPMM(sktstate1[i], sktstate2[i]) / double(1e9); if (m->MCDRAMmemoryTrafficMetricsAvailable()) cout << " " << setw(11) << getBytesReadFromEDC(sktstate1[i], sktstate2[i]) / double(1e9) << " " << setw(11) << getBytesWrittenToEDC(sktstate1[i], sktstate2[i]) / double(1e9); if (m->memoryIOTrafficMetricAvailable()) cout << " " << setw(5) << getIORequestBytesFromMC(sktstate1[i], sktstate2[i]) / double(1e9); if (m->memoryIOTrafficMetricAvailable()) cout << " " << setw(5) << getIARequestBytesFromMC(sktstate1[i], sktstate2[i]) / double(1e9); if (m->memoryIOTrafficMetricAvailable()) cout << " " << setw(5) << getGTRequestBytesFromMC(sktstate1[i], sktstate2[i]) / double(1e9); cout << " "; if(m->packageEnergyMetricsAvailable()) { cout << setw(6) << getConsumedJoules(sktstate1[i], sktstate2[i]); } cout << " "; if(m->dramEnergyMetricsAvailable()) { cout << setw(6) << getDRAMConsumedJoules(sktstate1[i], sktstate2[i]); } cout << " "; if (m->LLCReadMissLatencyMetricsAvailable()) { cout << setw(6) << getLLCReadMissLatency(sktstate1[i], sktstate2[i]); } cout << " "; if (m->uncoreFrequencyMetricAvailable()) { cout << setw(4) << getAverageUncoreFrequencyGhz(sktstate1[i], sktstate2[i]); } cout << "\n"; } cout << longDiv; if (m->getNumSockets() > 1) { cout << " *"; if (m->memoryTrafficMetricsAvailable()) cout << " " << setw(5) << getBytesReadFromMC(sstate1, sstate2) / double(1e9) << " " << setw(5) << getBytesWrittenToMC(sstate1, sstate2) / double(1e9); if (m->localMemoryRequestRatioMetricAvailable()) cout << " " << setw(3) << int(100.* getLocalMemoryRequestRatio(sstate1, sstate2)) << " %"; if (m->PMMTrafficMetricsAvailable()) cout << " " << setw(5) << getBytesReadFromPMM(sstate1, sstate2) / double(1e9) << " " << setw(5) << getBytesWrittenToPMM(sstate1, sstate2) / double(1e9); if (m->memoryIOTrafficMetricAvailable()) cout << " " << setw(5) << getIORequestBytesFromMC(sstate1, sstate2) / double(1e9); cout << " "; if (m->packageEnergyMetricsAvailable()) { cout << setw(6) << getConsumedJoules(sstate1, sstate2); } cout << " "; if (m->dramEnergyMetricsAvailable()) { cout << setw(6) << getDRAMConsumedJoules(sstate1, sstate2); } cout << " "; if (m->LLCReadMissLatencyMetricsAvailable()) { cout << setw(6) << getLLCReadMissLatency(sstate1, sstate2); } cout << " "; if (m->uncoreFrequencyMetricAvailable()) { cout << setw(4) << getAverageUncoreFrequencyGhz(sstate1, sstate2); } cout << "\n"; } } } void print_basic_metrics_csv_header(const PCM * m) { cout << "EXEC,IPC,FREQ,"; if (m->isActiveRelativeFrequencyAvailable()) cout << "AFREQ,"; if (m->isL3CacheMissesAvailable()) cout << "L3MISS,"; if (m->isL2CacheMissesAvailable()) cout << "L2MISS,"; if (m->isL3CacheHitRatioAvailable()) cout << "L3HIT,"; if (m->isL2CacheHitRatioAvailable()) cout << "L2HIT,"; if (m->isL3CacheMissesAvailable()) cout << "L3MPI,"; if (m->isL2CacheMissesAvailable()) cout << "L2MPI,"; if (m->isHWTMAL1Supported()) cout << "Frontend_bound(%),Bad_Speculation(%),Backend_Bound(%),Retiring(%),"; } void print_csv_header_helper(string header, int count=1){ for(int i = 0; i < count; i++){ cout << header << ","; } } void print_basic_metrics_csv_semicolons(const PCM * m, string header) { print_csv_header_helper(header, 3); // EXEC;IPC;FREQ; if (m->isActiveRelativeFrequencyAvailable()) print_csv_header_helper(header); // AFREQ; if (m->isL3CacheMissesAvailable()) print_csv_header_helper(header); // L3MISS; if (m->isL2CacheMissesAvailable()) print_csv_header_helper(header); // L2MISS; if (m->isL3CacheHitRatioAvailable()) print_csv_header_helper(header); // L3HIT if (m->isL2CacheHitRatioAvailable()) print_csv_header_helper(header); // L2HIT; if (m->isL3CacheMissesAvailable()) print_csv_header_helper(header); // L3MPI; if (m->isL2CacheMissesAvailable()) print_csv_header_helper(header); // L2MPI; if (m->isHWTMAL1Supported()) cout << ",,,,"; // Frontend_bound(%),Bad_Speculation(%),Backend_Bound(%),Retiring(%) } void print_csv_header(PCM * m, const std::bitset<MAX_CORES> & ycores, const int /*cpu_model*/, const bool show_core_output, const bool show_partial_core_output, const bool show_socket_output, const bool show_system_output ) { // print first header line string header; header = "System"; print_csv_header_helper(header,2); if (show_system_output) { print_basic_metrics_csv_semicolons(m,header); if (m->memoryTrafficMetricsAvailable()) print_csv_header_helper(header,2); if (m->localMemoryRequestRatioMetricAvailable()) print_csv_header_helper(header); if (m->PMMTrafficMetricsAvailable()) print_csv_header_helper(header,2); if (m->MCDRAMmemoryTrafficMetricsAvailable()) print_csv_header_helper(header,2); print_csv_header_helper(header,7); if (m->getNumSockets() > 1) { // QPI info only for multi socket systems if (m->incomingQPITrafficMetricsAvailable()) print_csv_header_helper(header,2); if (m->outgoingQPITrafficMetricsAvailable()) print_csv_header_helper(header); } header = "System Core C-States"; for (int s = 0; s <= PCM::MAX_C_STATE; ++s) if (m->isCoreCStateResidencySupported(s)) print_csv_header_helper(header); header = "System Pack C-States"; for (int s = 0; s <= PCM::MAX_C_STATE; ++s) if (m->isPackageCStateResidencySupported(s)) print_csv_header_helper(header); if (m->packageEnergyMetricsAvailable()) print_csv_header_helper(header); if (m->dramEnergyMetricsAvailable()) print_csv_header_helper(header); if (m->LLCReadMissLatencyMetricsAvailable()) print_csv_header_helper(header); if (m->uncoreFrequencyMetricAvailable()) print_csv_header_helper(header); } if (show_socket_output) { for (uint32 i = 0; i < m->getNumSockets(); ++i) { header = "Socket " + std::to_string(i); print_csv_header_helper(header); print_basic_metrics_csv_semicolons(m,header); if (m->L3CacheOccupancyMetricAvailable()) print_csv_header_helper(header); if (m->CoreLocalMemoryBWMetricAvailable()) print_csv_header_helper(header); if (m->CoreRemoteMemoryBWMetricAvailable()) print_csv_header_helper(header); if (m->memoryTrafficMetricsAvailable()) print_csv_header_helper(header,2); if (m->localMemoryRequestRatioMetricAvailable()) print_csv_header_helper(header); if (m->PMMTrafficMetricsAvailable()) print_csv_header_helper(header,2); if (m->MCDRAMmemoryTrafficMetricsAvailable()) print_csv_header_helper(header,2); print_csv_header_helper(header,7); //ACYC,TIME(ticks),PhysIPC,PhysIPC%,INSTnom,INSTnom%, } if (m->getNumSockets() > 1 && (m->incomingQPITrafficMetricsAvailable())) // QPI info only for multi socket systems { const uint32 qpiLinks = (uint32)m->getQPILinksPerSocket(); for (uint32 s = 0; s < m->getNumSockets(); ++s) { header = "SKT" + std::to_string(s) + "dataIn"; print_csv_header_helper(header,qpiLinks); if (m->qpiUtilizationMetricsAvailable()) { header = "SKT" + std::to_string(s) + "dataIn (percent)"; print_csv_header_helper(header,qpiLinks); } } } if (m->getNumSockets() > 1 && (m->outgoingQPITrafficMetricsAvailable())) // QPI info only for multi socket systems { const uint32 qpiLinks = (uint32)m->getQPILinksPerSocket(); for (uint32 s = 0; s < m->getNumSockets(); ++s) { header = "SKT" + std::to_string(s) + "trafficOut"; print_csv_header_helper(header,qpiLinks); header = "SKT" + std::to_string(s) + "trafficOut (percent)"; print_csv_header_helper(header,qpiLinks); } } for (uint32 i = 0; i < m->getNumSockets(); ++i) { header = "SKT" + std::to_string(i) + " Core C-State"; for (int s = 0; s <= PCM::MAX_C_STATE; ++s) if (m->isCoreCStateResidencySupported(s)) print_csv_header_helper(header); header = "SKT" + std::to_string(i) + " Package C-State"; for (int s = 0; s <= PCM::MAX_C_STATE; ++s) if (m->isPackageCStateResidencySupported(s)) print_csv_header_helper(header); } if (m->packageEnergyMetricsAvailable()) { header = "Proc Energy (Joules)"; print_csv_header_helper(header,m->getNumSockets()); } if (m->dramEnergyMetricsAvailable()) { header = "DRAM Energy (Joules)"; print_csv_header_helper(header,m->getNumSockets()); } if (m->LLCReadMissLatencyMetricsAvailable()) { header = "LLCRDMISSLAT (ns)"; print_csv_header_helper(header,m->getNumSockets()); } if (m->uncoreFrequencyMetricAvailable()) { header = "UncFREQ (Ghz)"; print_csv_header_helper(header, m->getNumSockets()); } } if (show_core_output) { for (uint32 i = 0; i < m->getNumCores(); ++i) { if (show_partial_core_output && ycores.test(i) == false) continue; std::stringstream hstream; hstream << "Core" << i << " (Socket" << setw(2) << m->getSocketId(i) << ")"; header = hstream.str(); print_basic_metrics_csv_semicolons(m,header); if (m->L3CacheOccupancyMetricAvailable()) print_csv_header_helper(header); if (m->CoreLocalMemoryBWMetricAvailable()) print_csv_header_helper(header); if (m->CoreRemoteMemoryBWMetricAvailable()) print_csv_header_helper(header); for (int s = 0; s <= PCM::MAX_C_STATE; ++s) if (m->isCoreCStateResidencySupported(s)) print_csv_header_helper(header); print_csv_header_helper(header);// TEMP print_csv_header_helper(header,7); //ACYC,TIME(ticks),PhysIPC,PhysIPC%,INSTnom,INSTnom%, } } // print second header line cout << "\n"; printDateForCSV(Header2); if (show_system_output) { print_basic_metrics_csv_header(m); if (m->memoryTrafficMetricsAvailable()) cout << "READ,WRITE,"; if (m->localMemoryRequestRatioMetricAvailable()) cout << "LOCAL,"; if (m->PMMTrafficMetricsAvailable()) cout << "PMM_RD,PMM_WR,"; if (m->MCDRAMmemoryTrafficMetricsAvailable()) cout << "MCDRAM_READ,MCDRAM_WRITE,"; cout << "INST,ACYC,TIME(ticks),PhysIPC,PhysIPC%,INSTnom,INSTnom%,"; if (m->getNumSockets() > 1) { // QPI info only for multi socket systems if (m->incomingQPITrafficMetricsAvailable()) cout << "Total" << m->xPI() << "in," << m->xPI() << "toMC,"; if (m->outgoingQPITrafficMetricsAvailable()) cout << "Total" << m->xPI() << "out,"; } for (int s = 0; s <= PCM::MAX_C_STATE; ++s) if (m->isCoreCStateResidencySupported(s)) cout << "C" << s << "res%,"; for (int s = 0; s <= PCM::MAX_C_STATE; ++s) if (m->isPackageCStateResidencySupported(s)) cout << "C" << s << "res%,"; if (m->packageEnergyMetricsAvailable()) cout << "Proc Energy (Joules),"; if (m->dramEnergyMetricsAvailable()) cout << "DRAM Energy (Joules),"; if (m->LLCReadMissLatencyMetricsAvailable()) cout << "LLCRDMISSLAT (ns),"; if (m->uncoreFrequencyMetricAvailable()) cout << "UncFREQ (Ghz),"; } if (show_socket_output) { for (uint32 i = 0; i < m->getNumSockets(); ++i) { print_basic_metrics_csv_header(m); if (m->L3CacheOccupancyMetricAvailable()) cout << "L3OCC,"; if (m->CoreLocalMemoryBWMetricAvailable()) cout << "LMB,"; if (m->CoreRemoteMemoryBWMetricAvailable()) cout << "RMB,"; if (m->memoryTrafficMetricsAvailable()) cout << "READ,WRITE,"; if (m->localMemoryRequestRatioMetricAvailable()) cout << "LOCAL,"; if (m->PMMTrafficMetricsAvailable()) cout << "PMM_RD,PMM_WR,"; if (m->MCDRAMmemoryTrafficMetricsAvailable()) cout << "MCDRAM_READ,MCDRAM_WRITE,"; cout << "TEMP,"; cout << "INST,ACYC,TIME(ticks),PhysIPC,PhysIPC%,INSTnom,INSTnom%,"; } if (m->getNumSockets() > 1 && (m->incomingQPITrafficMetricsAvailable())) // QPI info only for multi socket systems { const uint32 qpiLinks = (uint32)m->getQPILinksPerSocket(); for (uint32 s = 0; s < m->getNumSockets(); ++s) { for (uint32 i = 0; i < qpiLinks; ++i) cout << m->xPI() << i << ","; if (m->qpiUtilizationMetricsAvailable()) for (uint32 i = 0; i < qpiLinks; ++i) cout << m->xPI() << i << ","; } } if (m->getNumSockets() > 1 && (m->outgoingQPITrafficMetricsAvailable())) // QPI info only for multi socket systems { const uint32 qpiLinks = (uint32)m->getQPILinksPerSocket(); for (uint32 s = 0; s < m->getNumSockets(); ++s) { for (uint32 i = 0; i < qpiLinks; ++i) cout << m->xPI() << i << ","; for (uint32 i = 0; i < qpiLinks; ++i) cout << m->xPI() << i << ","; } } for (uint32 i = 0; i < m->getNumSockets(); ++i) { for (int s = 0; s <= PCM::MAX_C_STATE; ++s) if (m->isCoreCStateResidencySupported(s)) cout << "C" << s << "res%,"; for (int s = 0; s <= PCM::MAX_C_STATE; ++s) if (m->isPackageCStateResidencySupported(s)) cout << "C" << s << "res%,"; } if (m->packageEnergyMetricsAvailable()) { for (uint32 i = 0; i < m->getNumSockets(); ++i) cout << "SKT" << i << ","; } if (m->dramEnergyMetricsAvailable()) { for (uint32 i = 0; i < m->getNumSockets(); ++i) cout << "SKT" << i << ","; } if (m->LLCReadMissLatencyMetricsAvailable()) { for (uint32 i = 0; i < m->getNumSockets(); ++i) cout << "SKT" << i << ","; } if (m->uncoreFrequencyMetricAvailable()) { for (uint32 i = 0; i < m->getNumSockets(); ++i) cout << "SKT" << i << ","; } } if (show_core_output) { for (uint32 i = 0; i < m->getNumCores(); ++i) { if (show_partial_core_output && ycores.test(i) == false) continue; print_basic_metrics_csv_header(m); if (m->L3CacheOccupancyMetricAvailable()) cout << "L3OCC,"; if (m->CoreLocalMemoryBWMetricAvailable()) cout << "LMB,"; if (m->CoreRemoteMemoryBWMetricAvailable()) cout << "RMB,"; for (int s = 0; s <= PCM::MAX_C_STATE; ++s) if (m->isCoreCStateResidencySupported(s)) cout << "C" << s << "res%,"; cout << "TEMP,"; cout << "INST,ACYC,TIME(ticks),PhysIPC,PhysIPC%,INSTnom,INSTnom%,"; } } } template <class State> void print_basic_metrics_csv(const PCM * m, const State & state1, const State & state2, const bool print_last_semicolon = true) { cout << getExecUsage(state1, state2) << ',' << getIPC(state1, state2) << ',' << getRelativeFrequency(state1, state2); if (m->isActiveRelativeFrequencyAvailable()) cout << ',' << getActiveRelativeFrequency(state1, state2); if (m->isL3CacheMissesAvailable()) cout << ',' << float_format(getL3CacheMisses(state1, state2)); if (m->isL2CacheMissesAvailable()) cout << ',' << float_format(getL2CacheMisses(state1, state2)); if (m->isL3CacheHitRatioAvailable()) cout << ',' << getL3CacheHitRatio(state1, state2); if (m->isL2CacheHitRatioAvailable()) cout << ',' << getL2CacheHitRatio(state1, state2); if (m->isL3CacheMissesAvailable()) cout << ',' << double(getL3CacheMisses(state1, state2)) / getInstructionsRetired(state1, state2); if (m->isL2CacheMissesAvailable()) cout << ',' << double(getL2CacheMisses(state1, state2)) / getInstructionsRetired(state1, state2); if (m->isHWTMAL1Supported()) { cout << ',' << int(100. * getFrontendBound(state1, state2)); cout << ',' << int(100. * getBadSpeculation(state1, state2)); cout << ',' << int(100. * getBackendBound(state1, state2)); cout << ',' << int(100. * getRetiring(state1, state2)); } if (print_last_semicolon) cout << ","; } template <class State> void print_other_metrics_csv(const PCM * m, const State & state1, const State & state2) { if (m->L3CacheOccupancyMetricAvailable()) cout << ',' << l3cache_occ_format(getL3CacheOccupancy(state2)); if (m->CoreLocalMemoryBWMetricAvailable()) cout << ',' << getLocalMemoryBW(state1, state2); if (m->CoreRemoteMemoryBWMetricAvailable()) cout << ',' << getRemoteMemoryBW(state1, state2); } void print_csv(PCM * m, const std::vector<CoreCounterState> & cstates1, const std::vector<CoreCounterState> & cstates2, const std::vector<SocketCounterState> & sktstate1, const std::vector<SocketCounterState> & sktstate2, const std::bitset<MAX_CORES> & ycores, const SystemCounterState& sstate1, const SystemCounterState& sstate2, const int /*cpu_model*/, const bool show_core_output, const bool show_partial_core_output, const bool show_socket_output, const bool show_system_output ) { cout << "\n"; printDateForCSV(CsvOutputType::Data); if (show_system_output) { print_basic_metrics_csv(m, sstate1, sstate2); if (m->memoryTrafficMetricsAvailable()) cout << getBytesReadFromMC(sstate1, sstate2) / double(1e9) << ',' << getBytesWrittenToMC(sstate1, sstate2) / double(1e9) << ','; if (m->localMemoryRequestRatioMetricAvailable()) cout << int(100. * getLocalMemoryRequestRatio(sstate1, sstate2)) << ','; if (m->PMMTrafficMetricsAvailable()) cout << getBytesReadFromPMM(sstate1, sstate2) / double(1e9) << ',' << getBytesWrittenToPMM(sstate1, sstate2) / double(1e9) << ','; if (m->MCDRAMmemoryTrafficMetricsAvailable()) cout << getBytesReadFromEDC(sstate1, sstate2) / double(1e9) << ',' << getBytesWrittenToEDC(sstate1, sstate2) / double(1e9) << ','; cout << float_format(getInstructionsRetired(sstate1, sstate2)) << "," << float_format(getCycles(sstate1, sstate2)) << "," << float_format(getInvariantTSC(cstates1[0], cstates2[0])) << "," << getCoreIPC(sstate1, sstate2) << "," << 100. * (getCoreIPC(sstate1, sstate2) / double(m->getMaxIPC())) << "," << getTotalExecUsage(sstate1, sstate2) << "," << 100. * (getTotalExecUsage(sstate1, sstate2) / double(m->getMaxIPC())) << ","; if (m->getNumSockets() > 1) { // QPI info only for multi socket systems if (m->incomingQPITrafficMetricsAvailable()) cout << float_format(getAllIncomingQPILinkBytes(sstate1, sstate2)) << "," << getQPItoMCTrafficRatio(sstate1, sstate2) << ","; if (m->outgoingQPITrafficMetricsAvailable()) cout << float_format(getAllOutgoingQPILinkBytes(sstate1, sstate2)) << ","; } for (int s = 0; s <= PCM::MAX_C_STATE; ++s) if (m->isCoreCStateResidencySupported(s)) cout << getCoreCStateResidency(s, sstate1, sstate2) * 100 << ","; for (int s = 0; s <= PCM::MAX_C_STATE; ++s) if (m->isPackageCStateResidencySupported(s)) cout << getPackageCStateResidency(s, sstate1, sstate2) * 100 << ","; if (m->packageEnergyMetricsAvailable()) cout << getConsumedJoules(sstate1, sstate2) << ","; if (m->dramEnergyMetricsAvailable()) cout << getDRAMConsumedJoules(sstate1, sstate2) << ","; if (m->LLCReadMissLatencyMetricsAvailable()) cout << getLLCReadMissLatency(sstate1, sstate2) << ","; if (m->uncoreFrequencyMetricAvailable()) cout << getAverageUncoreFrequencyGhz(sstate1, sstate2) << ","; } if (show_socket_output) { for (uint32 i = 0; i < m->getNumSockets(); ++i) { print_basic_metrics_csv(m, sktstate1[i], sktstate2[i], false); print_other_metrics_csv(m, sktstate1[i], sktstate2[i]); if (m->memoryTrafficMetricsAvailable()) cout << ',' << getBytesReadFromMC(sktstate1[i], sktstate2[i]) / double(1e9) << ',' << getBytesWrittenToMC(sktstate1[i], sktstate2[i]) / double(1e9); if (m->localMemoryRequestRatioMetricAvailable()) cout << ',' << int(100. * getLocalMemoryRequestRatio(sktstate1[i], sktstate2[i])); if (m->PMMTrafficMetricsAvailable()) cout << ',' << getBytesReadFromPMM(sktstate1[i], sktstate2[i]) / double(1e9) << ',' << getBytesWrittenToPMM(sktstate1[i], sktstate2[i]) / double(1e9); if (m->MCDRAMmemoryTrafficMetricsAvailable()) cout << ',' << getBytesReadFromEDC(sktstate1[i], sktstate2[i]) / double(1e9) << ',' << getBytesWrittenToEDC(sktstate1[i], sktstate2[i]) / double(1e9); cout << ',' << temp_format(sktstate2[i].getThermalHeadroom()) << ','; cout << float_format(getInstructionsRetired(sktstate1[i], sktstate2[i])) << "," << float_format(getCycles(sktstate1[i], sktstate2[i])) << "," << float_format(getInvariantTSC(cstates1[0], cstates2[0])) << "," << getCoreIPC(sktstate1[i], sktstate2[i]) << "," << 100. * (getCoreIPC(sktstate1[i], sktstate2[i]) / double(m->getMaxIPC())) << "," << getTotalExecUsage(sktstate1[i], sktstate2[i]) << "," << 100. * (getTotalExecUsage(sktstate1[i], sktstate2[i]) / double(m->getMaxIPC())) << ","; } if (m->getNumSockets() > 1 && (m->incomingQPITrafficMetricsAvailable())) // QPI info only for multi socket systems { const uint32 qpiLinks = (uint32)m->getQPILinksPerSocket(); for (uint32 i = 0; i < m->getNumSockets(); ++i) { for (uint32 l = 0; l < qpiLinks; ++l) cout << float_format(getIncomingQPILinkBytes(i, l, sstate1, sstate2)) << ","; if (m->qpiUtilizationMetricsAvailable()) { for (uint32 l = 0; l < qpiLinks; ++l) cout << setw(3) << std::dec << int(100. * getIncomingQPILinkUtilization(i, l, sstate1, sstate2)) << "%,"; } } } if (m->getNumSockets() > 1 && (m->outgoingQPITrafficMetricsAvailable())) // QPI info only for multi socket systems { const uint32 qpiLinks = (uint32)m->getQPILinksPerSocket(); for (uint32 i = 0; i < m->getNumSockets(); ++i) { for (uint32 l = 0; l < qpiLinks; ++l) cout << float_format(getOutgoingQPILinkBytes(i, l, sstate1, sstate2)) << ","; for (uint32 l = 0; l < qpiLinks; ++l) cout << setw(3) << std::dec << int(100. * getOutgoingQPILinkUtilization(i, l, sstate1, sstate2)) << "%,"; } } for (uint32 i = 0; i < m->getNumSockets(); ++i) { for (int s = 0; s <= PCM::MAX_C_STATE; ++s) if (m->isCoreCStateResidencySupported(s)) cout << getCoreCStateResidency(s, sktstate1[i], sktstate2[i]) * 100 << ","; for (int s = 0; s <= PCM::MAX_C_STATE; ++s) if (m->isPackageCStateResidencySupported(s)) cout << getPackageCStateResidency(s, sktstate1[i], sktstate2[i]) * 100 << ","; } if (m->packageEnergyMetricsAvailable()) { for (uint32 i = 0; i < m->getNumSockets(); ++i) cout << getConsumedJoules(sktstate1[i], sktstate2[i]) << ","; } if (m->dramEnergyMetricsAvailable()) { for (uint32 i = 0; i < m->getNumSockets(); ++i) cout << getDRAMConsumedJoules(sktstate1[i], sktstate2[i]) << " ,"; } if (m->LLCReadMissLatencyMetricsAvailable()) { for (uint32 i = 0; i < m->getNumSockets(); ++i) cout << getLLCReadMissLatency(sktstate1[i], sktstate2[i]) << " ,"; } if (m->uncoreFrequencyMetricAvailable()) { for (uint32 i = 0; i < m->getNumSockets(); ++i) cout << getAverageUncoreFrequencyGhz(sktstate1[i], sktstate2[i]) << ","; } } if (show_core_output) { for (uint32 i = 0; i < m->getNumCores(); ++i) { if (show_partial_core_output && ycores.test(i) == false) continue; print_basic_metrics_csv(m, cstates1[i], cstates2[i], false); print_other_metrics_csv(m, cstates1[i], cstates2[i]); cout << ','; for (int s = 0; s <= PCM::MAX_C_STATE; ++s) if (m->isCoreCStateResidencySupported(s)) cout << getCoreCStateResidency(s, cstates1[i], cstates2[i]) * 100 << ","; cout << temp_format(cstates2[i].getThermalHeadroom()) << ','; cout << float_format(getInstructionsRetired(cstates1[i], cstates2[i])) << "," << float_format(getCycles(cstates1[i], cstates2[i])) << "," << float_format(getInvariantTSC(cstates1[0], cstates2[0])) << "," << getCoreIPC(cstates1[i], cstates2[i]) << "," << 100. * (getCoreIPC(cstates1[i], cstates2[i]) / double(m->getMaxIPC())) << "," << getTotalExecUsage(cstates1[i], cstates2[i]) << "," << 100. * (getTotalExecUsage(cstates1[i], cstates2[i]) / double(m->getMaxIPC())) << ","; } } } int main(int argc, char * argv[]) { set_signal_handlers(); #ifdef PCM_FORCE_SILENT null_stream nullStream1, nullStream2; std::cout.rdbuf(&nullStream1); std::cerr.rdbuf(&nullStream2); #endif cerr << "\n"; cerr << " Processor Counter Monitor " << PCM_VERSION << "\n"; cerr << "\n"; cerr << "\n"; // if delay is not specified: use either default (1 second), // or only read counters before or after PCM started: keep PCM blocked double delay = -1.0; char *sysCmd = NULL; char **sysArgv = NULL; bool show_core_output = true; bool show_partial_core_output = false; bool show_socket_output = true; bool show_system_output = true; bool csv_output = false; bool reset_pmu = false; bool allow_multiple_instances = false; bool disable_JKT_workaround = false; // as per http://software.intel.com/en-us/articles/performance-impact-when-sampling-certain-llc-events-on-snb-ep-with-vtune MainLoop mainLoop; std::bitset<MAX_CORES> ycores; string program = string(argv[0]); PCM * m = PCM::getInstance(); if (argc > 1) do { argv++; argc--; if (strncmp(*argv, "--help", 6) == 0 || strncmp(*argv, "-h", 2) == 0 || strncmp(*argv, "/h", 2) == 0) { print_help(program); exit(EXIT_FAILURE); } else if (strncmp(*argv, "--yescores", 10) == 0 || strncmp(*argv, "-yc", 3) == 0 || strncmp(*argv, "/yc", 3) == 0) { argv++; argc--; show_partial_core_output = true; if(*argv == NULL) { cerr << "Error: --yescores requires additional argument.\n"; exit(EXIT_FAILURE); } std::stringstream ss(*argv); while(ss.good()) { string s; int core_id; std::getline(ss, s, ','); if(s.empty()) continue; core_id = atoi(s.c_str()); if(core_id > MAX_CORES) { cerr << "Core ID:" << core_id << " exceed maximum range " << MAX_CORES << ", program abort\n"; exit(EXIT_FAILURE); } ycores.set(core_id, true); } if(m->getNumCores() > MAX_CORES) { cerr << "Error: --yescores option is enabled, but #define MAX_CORES " << MAX_CORES << " is less than m->getNumCores() = " << m->getNumCores() << "\n"; cerr << "There is a potential to crash the system. Please increase MAX_CORES to at least " << m->getNumCores() << " and re-enable this option.\n"; exit(EXIT_FAILURE); } continue; } if (strncmp(*argv, "--nocores", 9) == 0 || strncmp(*argv, "-nc", 3) == 0 || strncmp(*argv, "/nc", 3) == 0) { show_core_output = false; continue; } else if (strncmp(*argv, "--nosockets", 11) == 0 || strncmp(*argv, "-ns", 3) == 0 || strncmp(*argv, "/ns", 3) == 0) { show_socket_output = false; continue; } else if (strncmp(*argv, "--nosystem", 10) == 0 || strncmp(*argv, "-nsys", 5) == 0 || strncmp(*argv, "/nsys", 5) == 0) { show_system_output = false; continue; } else if (strncmp(*argv, "--multiple-instances", 20) == 0 || strncmp(*argv, "-m", 2) == 0 || strncmp(*argv, "/m", 2) == 0) { allow_multiple_instances = true; continue; } else if (strncmp(*argv, "-csv", 4) == 0 || strncmp(*argv, "/csv", 4) == 0) { csv_output = true; string cmd = string(*argv); size_t found = cmd.find('=', 4); if (found != string::npos) { string filename = cmd.substr(found + 1); if (!filename.empty()) { m->setOutput(filename); } } continue; } else if (mainLoop.parseArg(*argv)) { continue; } else if (strncmp(*argv, "-reset", 6) == 0 || strncmp(*argv, "-r", 2) == 0 || strncmp(*argv, "/reset", 6) == 0) { reset_pmu = true; continue; } else if (CheckAndForceRTMAbortMode(*argv, m)) { continue; } else if (strncmp(*argv, "--noJKTWA", 9) == 0) { disable_JKT_workaround = true; continue; } #ifdef _MSC_VER else if (strncmp(*argv, "--uninstallDriver", 17) == 0) { Driver tmpDrvObject; tmpDrvObject.uninstall(); cerr << "msr.sys driver has been uninstalled. You might need to reboot the system to make this effective.\n"; exit(EXIT_SUCCESS); } else if (strncmp(*argv, "--installDriver", 15) == 0) { Driver tmpDrvObject = Driver(Driver::msrLocalPath()); if (!tmpDrvObject.start()) { wcerr << "Can not access CPU counters\n"; wcerr << "You must have a signed driver at " << tmpDrvObject.driverPath() << " and have administrator rights to run this program\n"; exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); } #endif else if (strncmp(*argv, "--", 2) == 0) { argv++; sysCmd = *argv; sysArgv = argv; break; } else { // any other options positional that is a floating point number is treated as <delay>, // while the other options are ignored with a warning issues to stderr double delay_input; std::istringstream is_str_stream(*argv); is_str_stream >> noskipws >> delay_input; if (is_str_stream.eof() && !is_str_stream.fail() && delay == -1) { delay = delay_input; cerr << "Delay: " << delay << "\n"; } else { cerr << "WARNING: unknown command-line option: \"" << *argv << "\". Ignoring it.\n"; print_help(program); exit(EXIT_FAILURE); } continue; } } while (argc > 1); // end of command line partsing loop if (disable_JKT_workaround) m->disableJKTWorkaround(); if (reset_pmu) { cerr << "\n Resetting PMU configuration\n"; m->resetPMU(); } if (allow_multiple_instances) { m->allowMultipleInstances(); } // program() creates common semaphore for the singleton, so ideally to be called before any other references to PCM PCM::ErrorCode status = m->program(); switch (status) { case PCM::Success: break; case PCM::MSRAccessDenied: cerr << "Access to Processor Counter Monitor has denied (no MSR or PCI CFG space access).\n"; exit(EXIT_FAILURE); case PCM::PMUBusy: cerr << "Access to Processor Counter Monitor has denied (Performance Monitoring Unit is occupied by other application). Try to stop the application that uses PMU.\n"; cerr << "Alternatively you can try running PCM with option -r to reset PMU.\n"; exit(EXIT_FAILURE); default: cerr << "Access to Processor Counter Monitor has denied (Unknown error).\n"; exit(EXIT_FAILURE); } print_cpu_details(); std::vector<CoreCounterState> cstates1, cstates2; std::vector<SocketCounterState> sktstate1, sktstate2; SystemCounterState sstate1, sstate2; const auto cpu_model = m->getCPUModel(); if ((sysCmd != NULL) && (delay <= 0.0)) { // in case external command is provided in command line, and // delay either not provided (-1) or is zero m->setBlocked(true); } else { m->setBlocked(false); } // in case delay is not provided in command line => set default if (delay <= 0.0) delay = PCM_DELAY_DEFAULT; // cerr << "DEBUG: Delay: " << delay << " seconds. Blocked: " << m->isBlocked() << "\n"; if (csv_output) { print_csv_header(m, ycores, cpu_model, show_core_output, show_partial_core_output, show_socket_output, show_system_output); } m->getAllCounterStates(sstate1, sktstate1, cstates1); if (sysCmd != NULL) { MySystem(sysCmd, sysArgv); } mainLoop([&]() { if (!csv_output) cout << std::flush; calibratedSleep(delay, sysCmd, mainLoop, m); m->getAllCounterStates(sstate2, sktstate2, cstates2); if (csv_output) print_csv(m, cstates1, cstates2, sktstate1, sktstate2, ycores, sstate1, sstate2, cpu_model, show_core_output, show_partial_core_output, show_socket_output, show_system_output); else print_output(m, cstates1, cstates2, sktstate1, sktstate2, ycores, sstate1, sstate2, cpu_model, show_core_output, show_partial_core_output, show_socket_output, show_system_output); std::swap(sstate1, sstate2); std::swap(sktstate1, sktstate2); std::swap(cstates1, cstates2); if (m->isBlocked()) { // in case PCM was blocked after spawning child application: break monitoring loop here return false; } return true; }); exit(EXIT_SUCCESS); }
42.255081
754
0.553153
[ "vector" ]
4f20e1efbd87309492ddd41fd5d1604402cfb048
14,283
cpp
C++
main.cpp
Ian-Parberry/opticalillusions
3c65fdaea567ea06ff97a2b60886978b185c0c4e
[ "MIT" ]
null
null
null
main.cpp
Ian-Parberry/opticalillusions
3c65fdaea567ea06ff97a2b60886978b185c0c4e
[ "MIT" ]
null
null
null
main.cpp
Ian-Parberry/opticalillusions
3c65fdaea567ea06ff97a2b60886978b185c0c4e
[ "MIT" ]
null
null
null
/// \file main.cpp /// \brief Generate a pair of optical illusions in SVG format. // MIT License // // Copyright (c) 2021 Ian Parberry // // 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. #define _USE_MATH_DEFINES #include <math.h> #include <stdio.h> #include <string> const float PI = 3.14159265358979323846f; ///< Pi. ////////////////////////////////////////////////////////////////////////// // Helper fuctions. #pragma region helpers /// \brief Open SVG file. /// /// Open an SVG file for writing and print the header tag and an /// open `svg` tag. /// \param output [out] Reference to output file pointer. /// \param fname File name without extension. /// \param w Image width. /// \param h Image height. /// \return true if open succeeded. bool OpenSVG(FILE*& output, const std::string& fname, size_t w, size_t h){ const std::string s = fname + ".svg"; #ifdef _MSC_VER //Visual Studio fopen_s(&output, s.c_str(), "wt"); #else output = fopen(s.c_str(), "wt"); #endif if(output != nullptr){ //write header to file fprintf(output, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); //xml tag fprintf(output, "<svg width=\"%lu\" height=\"%lu\" ", w, w); //svg tag fprintf(output, "viewBox=\"0 0 %lu %lu\" ", w, w); fprintf(output, "xmlns=\"http://www.w3.org/2000/svg\">\n"); fprintf(output, "<!-- Created by Ian Parberry -->\n"); //author comment return true; //success } //if return false; //failure } //OpenSVG /// \brief Close SVG file. /// /// Print a close `svg` tag and close the SVG file. /// \param output Reference to file pointer. void CloseSVG(FILE*& output){ if(output != nullptr){ fprintf(output, "</svg>\n"); //close the svg tag fclose(output); output = nullptr; } //if } //CloseSVG #pragma endregion helpers ////////////////////////////////////////////////////////////////////////// // Optical Illusion 1 - circles of squares. #pragma region Illusion1 /// \brief Draw a circle of squares to a file in SVG format. /// /// This function outputs SVG `transform` and SVG `rect` tags to the output /// file, alternating between black and white. The squares are spaced apart by /// approximately half a square width and tilted slightly from the perpendicular /// to a line drawn from the center of the circle to the center of the square. /// The number of squares is chosen so as to fit the spacing constraint, /// which need not be exact for the optical illusion to work. /// Used for optical illusion 1. /// /// \image html OneRingOfSquares.svg height=240 /// /// \param output File pointer. /// \param cx Image center x. /// \param cy Image center y. /// \param r Circle radius in pixels. /// \param sw Square width and height. /// \param parity Square initial orientation parity. void DrawCircleOfSquares(FILE* output, size_t cx, size_t cy, float r, size_t sw, bool parity) { //number of squares on circle, must be even const size_t n = (size_t)ceil((2*PI*r)/(1.5f*sw)) & 0xFFFFFFFE; const float dtheta = 2*PI/n; //angle delta to next square float theta = 0; //angle to current square for(size_t i=0; i<n; i++){ //for each square const float x = r*cosf(theta); //square center x const float y = r*sinf(theta); //square center y const float phi = 12*(parity? 1: -1) + 180*theta/PI; //square orientation fprintf(output, "<g transform=\"translate(%0.1f %0.1f)", x + sw/2, y + sw/2); //translate fprintf(output, "rotate(%0.1f %lu %lu)\">", phi, cx, cy); //rotate fprintf(output, "<rect width=\"%lu\" height=\"%lu\" ", sw, sw); //rectangle if(i&1)fprintf(output, "class=\"b\""); //black else fprintf(output, "class=\"w\""); //white fprintf(output, "/>"); //close rect tag fprintf(output, "</g>\n"); //close group theta += dtheta; //next square } //for } //DrawCircleOfSquares /// \brief Draw the first optical illusion to a file in SVG format. /// /// The image consists of four concentric circles of tilted squares, /// alternating between light and dark squares. This function outputs an SVG /// `style` tag (the use of which refices the SVG file size) and the /// background `rectangle` tag, then calls DrawCircleOfSquares() /// once for each circle of squares required. /// /// \image html output1.svg height=250 /// /// \param fname File name without extension. /// \param w Width and height of image in pixels. /// \param n Number of circles. /// \param r0 Initial circle radius. /// \param dr Radius delta. /// \param sw Width of squares. /// \param dark A dark SVG color. /// \param light A light SVG color. /// \param bgclr A mid-range SVG color for the background. void OpticalIllusion1(const std::string& fname, size_t w, size_t n, float r0, float dr, size_t sw, const char dark[], const char light[], const char bgclr[]) { const size_t cx = w/2 - sw/2; //center x coordinate const size_t cy = cx; //center y coordinate FILE* output = nullptr; //output file pointer if(OpenSVG(output, fname, w, w)){ //style tag fprintf(output, "<style>"); //open style tag fprintf(output, "rect{fill:none;stroke-width:3}"); //rectangle fprintf(output, "rect.b{x:%lu;y:%lu;stroke:%s;}", cx, cy, dark); //black rect fprintf(output, "rect.w{x:%lu;y:%lu;stroke:%s;}", cx, cy, light); //white rect fprintf(output, "</style>\n"); //close style tag //background fprintf(output, "<rect width=\"%lu\" height=\"%lu\" ", w, w); //rectangle fprintf(output, "style=\"fill:%s\"/>\n", bgclr); //fill for(size_t i=0; i<n; i++) //for each circle of squares DrawCircleOfSquares(output, cx, cy, r0 + i*dr, sw, i&1); //draw it CloseSVG(output); //clean up and exit } //if } //OpticalIllusion1 #pragma endregion Illusion1 ////////////////////////////////////////////////////////////////////////// // Optical Illusion 2 - circles of circles of ellipses. #pragma region Illusion2 /// \brief Select ellipse color based on index. /// /// If parity is true, ellipse is black when i%4=0, white when ji%4==2, and /// blank when i%4==1 and i%4==3. If parity is false, black and white are /// flipped. This function outputs the appropriate class name, `class="b"` for /// black and `class="w"` for white, to the output file. Used for optical /// illusion 2. /// /// \param output Output file pointer. /// \param i Ellipse index about circle. /// \param parity True if first ellipse is black, false if white. void SelectEllipseColor(FILE* output, size_t i, bool parity){ const size_t j = i%4; if((parity && j == 0) || (!parity && j == 2)) fprintf(output, "class=\"b\""); //black ellipse else if((parity && j == 2) || (!parity && j == 0)) fprintf(output, "class=\"w\""); //white ellipse } //SelectEllipseColor /// \brief Draw circle of ellipses to a file in SVG format. /// /// Draw a circle of elipses oriented so that the long axis of each ellipse is /// perpendicular to a line drawn from the center of the circles to the center /// of the ellipse. This function outputs SVG `transform` and SVG `ellipse` tags /// to the output file. Used for optical illusion 2. /// /// \param output Output file pointer. /// \param cx X coordinate of center of image in pixels. /// \param cy Y coordinate of center of image in pixels. /// \param r Radius of circle. /// \param r0 Long radius of ellipses. /// \param r1 Short radius of ellipses. /// \param n Number of ellipses in ring. /// \param theta Angle to first ellipse. /// \param dtheta Angle delta. /// \param parity True if first ellipse is black, false if white. /// \param flip True to clip the ordering of colots of ellipses. void DrawCircleOfEllipses(FILE* output, size_t cx, size_t cy, float r, float r0, float r1, size_t n, float theta, float dtheta, bool parity, size_t flip=999999) { for(size_t i=0; i<n; i++){ //for each ellipse const float x = r*cosf(theta); //ellipse center x const float y = r*sinf(theta); //ellipse center y const float phi = 90 + 180*theta/PI; //ellipse orientation fprintf(output, "<g transform=\"translate(%0.1f %0.1f)", x, y); //translate fprintf(output, "rotate(%0.1f %lu %lu)\">", phi, cx, cy); //rotate fprintf(output, "<ellipse rx=\"%0.1f\" ry=\"%0.1f\" ", r0, r1); //ellipse SelectEllipseColor(output, i, parity); fprintf(output, "/>"); //close ellipse tag fprintf(output, "</g>\n"); //close group theta += dtheta; //next ellipse if(i == flip)parity = !parity; //flip parity if we need to } //for } //DrawCircleOfEllipses /// \brief Draw 3 concentric circles of ellipses to a file in SVG format. /// /// This function calls DrawCircleOfEllipses() three times, once for each /// circle of ellipses. The middle circle is drawn first, then /// the inner circle, then the outer circle. The parameters for the calls /// DrawCircleOfEllipses() are chosen so as to achieve the following. /// /// The inner circle starts with a black ellipse centered at the top and /// alternates with white ellipses each spaced roughly one ellipse long-axis /// apart for a total of 36 ellipses as shown in the next image. /// /// \image html ring1-middle.svg height=250 /// /// The inner circle also has 36 ellipses, but it starts with a gap centered /// at the top with black ellipses to the left and right and a gap centered at /// the bottom with white ellipses to the left and right. Black and white /// alternate for the rest of the circle. /// /// \image html ring2-inner.svg height=250 /// /// The outer circle of a ring is similar to the inner circle /// but has black and white interchanged. /// /// \image html ring3-outer.svg height=250 /// /// Used for optical illusion 2. /// /// \param output Pointer to output file. /// \param cx X coordinate of center of image in pixels. /// \param cy Y coordinate of center of image in pixels. /// \param r Radius of braid. /// \param r0 Long radius of ellipses. /// \param r1 Short radius of ellipses. /// \param n Number of ellipses in ring. /// \param flip True to flip the ordering of colors of ellipses. void DrawTripleCircle(FILE* output, size_t cx, size_t cy, float r, float r0, float r1, size_t n, bool flip=false) { const float dtheta = PI/n; //angle delta to next ellipse float theta = (flip? PI: -PI)/2; //angle to next ellipse n *= 2; //include spaces DrawCircleOfEllipses(output, cx, cy, r, r0, r1, n, theta, dtheta, true); DrawCircleOfEllipses(output, cx, cy, r - r1, r0, r1, n, theta + dtheta, dtheta, true, n/2 - 1); DrawCircleOfEllipses(output, cx, cy, r + r1, r0, r1, n, theta + dtheta, dtheta, false, n/2 - 2); } //DrawTripleCircle /// \brief Draw the second optical illusion to a file in SVG format. /// /// The image consists of a pair of concentric rings, each of which is made /// up of three concentric circles of ellipses. This function outputs an SVG /// `style` tag (the use of which refices the SVG file size) and the /// background `rectangle` tag, then calls DrawTripleCircle() /// twice, once for each triplet of circles. /// /// \image html output2.svg height=250 /// /// \param fname File name without extension. /// \param w Width and height of image in pixels. /// \param n Number of ellipses in ring. /// \param r Radius of braid. /// \param r0 Long radius of ellipses. /// \param r1 Short radius of ellipses. /// \param dark A dark SVG color. /// \param light A light SVG color. /// \param bgclr A mid-range SVG color for the background. void OpticalIllusion2(const std::string& fname, size_t w, size_t n, float r, float r0, float r1, const char dark[], const char light[], const char bgclr[]) { const size_t cx = w/2; //center x coordinate const size_t cy = cx; //center y coordinate FILE* output = nullptr; //output file pointer if(OpenSVG(output, fname, w, w)){ //style tag fprintf(output, "<style>"); //open style tag fprintf(output, "ellipse{fill:none;stroke-width:3}"); //ellipse fprintf(output, "ellipse.b{cx:%lu;cy:%lu;stroke:none;fill:%s;}", cx, cy, dark); //dark ellipse fprintf(output, "ellipse.w{cx:%lu;cy:%lu;stroke:none;fill:%s;}", cx, cy, light); //light ellipse fprintf(output, "</style>\n"); //close style tag //background fprintf(output, "<rect width=\"%lu\" height=\"%lu\" ", w, w); //rectangle fprintf(output, "style=\"fill:%s\"/>\n", bgclr); //fill DrawTripleCircle(output, cx, cy, r, r0, r1, 36); DrawTripleCircle(output, cx, cy, r - 64, 0.8f*r0, 0.8f*r1, 36, true); CloseSVG(output); //clean up and exit } //if } //OpticalIllusion2 #pragma region Illusion2 ////////////////////////////////////////////////////////////////////////// /// \brief Main. /// /// Create two optical illusions and save them as SVG files. The actual work is /// done by functions OpticalIllusion1() and OpticalIllusion2(), called with /// various parameters. /// \return 0. int main(){ OpticalIllusion1("output1", 800, 4, 100.0f, 72.0f, 24, "black", "white", "gray"); OpticalIllusion1("output1a", 800, 4, 100.0f, 72.0f, 24, "blue", "yellow", "forestgreen"); OpticalIllusion2("output2", 800, 3, 300.0f, 12.0f, 6.0f, "black", "white", "gray"); OpticalIllusion2("output2a", 800, 3, 300.0f, 12.0f, 6.0f, "blue", "yellow", "forestgreen"); return 0; } //main
37.785714
93
0.657845
[ "transform" ]
4f242a0af67702964ebcdbfd979e13e7e333ea62
2,845
cpp
C++
src/PhysicsEngine/PhysicsEngineMath.cpp
ThePythonator/PhysicsEngine
8ee0d275df9674554697f25f9d782079c8a41596
[ "MIT" ]
5
2022-01-20T16:01:52.000Z
2022-03-19T23:07:23.000Z
src/PhysicsEngine/PhysicsEngineMath.cpp
ThePythonator/PhysicsEngine
8ee0d275df9674554697f25f9d782079c8a41596
[ "MIT" ]
null
null
null
src/PhysicsEngine/PhysicsEngineMath.cpp
ThePythonator/PhysicsEngine
8ee0d275df9674554697f25f9d782079c8a41596
[ "MIT" ]
null
null
null
#include "PhysicsEngineMath.hpp" namespace PhysicsEngine { const float PI = 3.14159265f; //const float EPSILON = 0.0001f; // todo: check if reasonable float length_squared(vec2 v) { return linalg::length2(v); } vec2 normalise(vec2 v) { return linalg::normalize(v); } float deg_to_rad(float degrees) { return PI * degrees / 180.0f; } float rad_to_deg(float radians) { return 180.0f * radians / PI; } mat22 rotation_matrix(float angle) { // Anticlockwise rotation float s = std::sin(angle); float c = std::cos(angle); return mat22{ {c, s}, {-s, c} }; } // Convert world space to model space (in model space, shape is as if angle = 0) vec2 to_model_space(vec2 point, vec2 model_centre, mat22 rotation_matrix) { return mul(inverse(rotation_matrix), point - model_centre); } vec2 to_model_space(vec2 point, mat22 rotation_matrix) { return mul(inverse(rotation_matrix), point); } // Convert model space to world space (in world space, shape is at actual angle) vec2 to_world_space(vec2 point, vec2 model_centre, mat22 rotation_matrix) { return mul(rotation_matrix, point) + model_centre; } vec2 to_world_space(vec2 point, mat22 rotation_matrix) { return mul(rotation_matrix, point); } vec2 find_support_point(vec2 direction, std::vector<vec2>& points) { float maximum_distance = -FLT_MAX; uint16_t point_index = 0; for (uint16_t i = 0; i < points.size(); i++) { float distance = dot(direction, points[i]); if (distance > maximum_distance) { maximum_distance = distance; point_index = i; } } return points[point_index]; } vec2 perpendicular_acw(vec2 vector) { return vec2{ -vector.y, vector.x }; } vec2 perpendicular_cw(vec2 vector) { return vec2{ vector.y, -vector.x }; } ClipResult clip_edge_to_line(vec2 edge[2], vec2 line_normal, float origin_distance) { ClipResult result; // Calculate signed distance along normal from line float signed_distance[2] = { dot(edge[0], line_normal) - origin_distance, dot(edge[1], line_normal) - origin_distance }; if (signed_distance[0] <= 0.0f) { result.points[result.points_count++] = edge[0]; } if (signed_distance[1] <= 0.0f) { result.points[result.points_count++] = edge[1]; } // Is the sign of the distances different? // We also check that points_count is < 2 so that we don't accidentally add a third point (although it should be impossible) if (signed_distance[0] * signed_distance[1] < 0.0f && result.points_count < 2) { // Edge passes through the clamping line // One of the distances was negative, so we need to add the intersection point // Calculate intersection float ratio = signed_distance[0] / (signed_distance[0] + signed_distance[1]); result.points[result.points_count++] = edge[0] + ratio * (edge[1] - edge[0]); } return result; } }
27.621359
126
0.698418
[ "shape", "vector", "model" ]
4f24d3f285753057537f9f7078d7bf5f97a281a8
5,458
hpp
C++
networkit/cpp/randomization/CurveballImpl.hpp
kmc-kk/networkit
28c1208104acae8ef70911340bf88b3e3dd08db7
[ "MIT" ]
null
null
null
networkit/cpp/randomization/CurveballImpl.hpp
kmc-kk/networkit
28c1208104acae8ef70911340bf88b3e3dd08db7
[ "MIT" ]
null
null
null
networkit/cpp/randomization/CurveballImpl.hpp
kmc-kk/networkit
28c1208104acae8ef70911340bf88b3e3dd08db7
[ "MIT" ]
1
2020-02-05T17:39:47.000Z
2020-02-05T17:39:47.000Z
/* * CurveballImpl.h * * Author: Hung Tran <htran@ae.cs.uni-frankfurt.de> */ // networkit-format #ifndef RANDOMIZATION_CURVEBALL_IMPL_H #define RANDOMIZATION_CURVEBALL_IMPL_H #include <cassert> #include <utility> #include <networkit/Globals.hpp> #include <networkit/graph/Graph.hpp> namespace NetworKit { namespace CurveballDetails { // Global Definitions using trade_descriptor = std::pair<node, node>; using tradeid = node; using count = node; using trade_vector = std::vector<trade_descriptor>; using nodepair_vector = std::vector<std::pair<node, node>>; constexpr node INVALID_NODE = std::numeric_limits<node>::max(); constexpr count LISTROW_END = std::numeric_limits<count>::max(); constexpr tradeid TRADELIST_END = std::numeric_limits<tradeid>::max(); class CurveballAdjacencyList { public: using degree_vector = std::vector<count>; using neighbour_vector = std::vector<node>; using pos_vector = std::vector<edgeid>; using pos_it = pos_vector::iterator; using neighbour_it = neighbour_vector::iterator; using cneighbour_it = neighbour_vector::const_iterator; using nodepair_vector = std::vector<std::pair<node, node>>; protected: neighbour_vector neighbours; degree_vector offsets; pos_vector begins; edgeid degreeCount; public: CurveballAdjacencyList() = default; // Receives the degree_vector to initialize // As trades permute neighbours the degrees don't change CurveballAdjacencyList(const degree_vector &degrees, const edgeid degree_count); void initialize(const degree_vector &degrees, const edgeid degree_count); void restructure(); // No Copy Constructor CurveballAdjacencyList(const CurveballAdjacencyList &) = delete; neighbour_it begin(const node node_id) { return neighbours.begin() + begins[node_id]; } neighbour_it end(const node node_id) { return neighbours.begin() + begins[node_id] + offsets[node_id]; } cneighbour_it cbegin(const node node_id) const { return neighbours.cbegin() + begins[node_id]; } cneighbour_it cend(const node node_id) const { return neighbours.cbegin() + begins[node_id] + offsets[node_id]; } nodepair_vector getEdges() const; void insertNeighbour(const node node_id, const node neighbour) { auto pos = begin(node_id) + offsets[node_id]; assert(*pos != LISTROW_END); *pos = neighbour; offsets[node_id]++; } node numberOfNodes() const { return static_cast<node>(offsets.size()); } node numberOfEdges() const { return static_cast<edgeid>(degreeCount); } void resetRow(const node node_id) { assert(node_id < static_cast<node>(offsets.size())); offsets[node_id] = 0; return; } count degreeAt(node node_id) const { assert(node_id < static_cast<node>(offsets.size())); return begins[node_id + 1] - begins[node_id] - 1; } }; class CurveballMaterialization { protected: const CurveballAdjacencyList &adjacencyList; public: CurveballMaterialization(const CurveballAdjacencyList &adj_list); Graph toGraph(bool parallel); protected: void toGraphParallel(Graph &G); void toGraphSequential(Graph &G); }; class TradeList { public: using edge_vector = std::vector<std::pair<node, node>>; using offset_vector = std::vector<tradeid>; using tradeid_vector = std::vector<tradeid>; using trade = trade_descriptor; using trade_vector = std::vector<trade>; using tradeid_it = tradeid_vector::const_iterator; protected: tradeid_vector tradeList; offset_vector offsets; const node numNodes; public: TradeList(const node num_nodes); // Receives the edge_vector to initialize TradeList(const trade_vector &trades, const node num_nodes); // Initialize method void initialize(const trade_vector &trades); // No Copy Constructor TradeList(const TradeList &) = delete; tradeid_it getTrades(const node nodeid) const { assert(nodeid < numNodes); return tradeList.begin() + offsets[nodeid]; } void incrementOffset(const node nodeid) { assert(nodeid < numNodes); assert(1 <= offsets[nodeid + 1] - offsets[nodeid]); offsets[nodeid]++; } node numberOfNodes() const { return numNodes; } }; class CurveballIM { public: CurveballIM(const Graph &G); void run(const trade_vector &trades); count getNumberOfAffectedEdges() const { assert(hasRun); return numAffectedEdges; } Graph getGraph(bool parallel) const; nodepair_vector getEdges() const; protected: const Graph &G; const node numNodes; bool hasRun; CurveballAdjacencyList adjList; TradeList tradeList; count maxDegree; edgeid numAffectedEdges; // affected half-edges void loadFromGraph(const trade_vector &trades); void restructureGraph(const trade_vector &trades); inline void update(const node a, const node b) { const tradeid ta = *(tradeList.getTrades(a)); const tradeid tb = *(tradeList.getTrades(b)); if (ta < tb) { adjList.insertNeighbour(a, b); return; } if (ta > tb) { adjList.insertNeighbour(b, a); return; } // ta == tb { adjList.insertNeighbour(a, b); } } }; } // namespace CurveballDetails } // namespace NetworKit #endif // ! RANDOMIZATION_CURVEBALL_IMPL_H
25.867299
100
0.687248
[ "vector" ]
4f24fb152ca59176f03004a582efcd4a00a80e7f
3,109
cpp
C++
Geom/Mesh.cpp
danheeks/PyCAD
711543aaa88c88a82d909f329b6ee36a9b96ae79
[ "BSD-3-Clause" ]
17
2018-07-30T17:38:02.000Z
2022-02-03T10:35:38.000Z
Geom/Mesh.cpp
danheeks/PyCAD
711543aaa88c88a82d909f329b6ee36a9b96ae79
[ "BSD-3-Clause" ]
2
2020-06-11T10:29:06.000Z
2020-06-11T15:42:00.000Z
Geom/Mesh.cpp
danheeks/PyCAD
711543aaa88c88a82d909f329b6ee36a9b96ae79
[ "BSD-3-Clause" ]
null
null
null
#include "Mesh.h" #include "Tris.h" int face_id = 1; CMesh::CMesh(const CTris& tris) { face_id = 1; for (std::list<CTri>::const_iterator It = tris.m_tris.begin(); It != tris.m_tris.end(); It++) { const CTri& tri = *It; AddTri(tri.x[0]); } } CMeshVertex* CMesh::AddGetVertex(const float* x) { CMeshVertex* v = NULL; std::map<float, std::list<CMeshVertex*> >::iterator FindIt = m_vertices.find(x[0]); if (FindIt == m_vertices.end()) { std::list<CMeshVertex*> empty_list; FindIt = m_vertices.insert(std::make_pair(x[0], empty_list)).first; v = new CMeshVertex(x); FindIt->second.push_back(v); } else { std::list<CMeshVertex*>& list = FindIt->second; for (std::list<CMeshVertex*>::iterator It = list.begin(); It != list.end(); It++) { v = *It; if (v->m_x[1] == x[1] && v->m_x[2] == x[2]) return v; } v = new CMeshVertex(x); list.push_back(v); } return v; } void CMesh::AddTri(const float* x) { CMeshFace* face = new CMeshFace(); face->m_id = face_id; face_id++; m_faces.push_back(face); CMeshVertex* vertices[3]; for (int i = 0; i < 3; i++) { CMeshVertex* v = AddGetVertex(&x[3 * i]); face->m_vertices.push_back(v); vertices[i] = v; vertices[i]->m_f.insert(face); } CMeshEdgeAndDir edges[3]; edges[0] = AddEdge(vertices[0], vertices[1]); edges[1] = AddEdge(vertices[1], vertices[2]); edges[2] = AddEdge(vertices[2], vertices[0]); for (int i = 0; i < 3; i++) { face->m_edges.push_back(edges[i]); edges[i].AddFace(face); } } void CMeshEdgeAndDir::AddFace(CMeshFace* face) { if (m_dir) m_edge->m_f[0] = face; else m_edge->m_f[1] = face; } bool CMeshFace::GetNormal(Point3d &norm)const { if (m_vertices.size() < 3) return false; Point3d p[3]; for (int i = 0; i < 3; i++) { p[i] = Point3d(m_vertices[i]->m_x[0], m_vertices[i]->m_x[1], m_vertices[i]->m_x[2]); } norm = Point3d(p[0], p[1]) ^ Point3d(p[0], p[2]); norm.normalise(); return true; } void CMeshFace::GetJoiningFaces(std::list<CMeshFace*> &joining_faces)const { for (std::vector<CMeshEdgeAndDir>::const_iterator It = m_edges.begin(); It != m_edges.end(); It++) { const CMeshEdgeAndDir& e = *It; for (int i = 0; i < 2; i++) { if (e.m_edge->m_f[i] != this)joining_faces.push_back(e.m_edge->m_f[i]); } } } void CMeshFace::GetTri(CTri& tri)const { for (unsigned int i = 0; i < m_vertices.size(); i++) { tri.x[i][0] = m_vertices[i]->m_x[0]; tri.x[i][1] = m_vertices[i]->m_x[1]; tri.x[i][2] = m_vertices[i]->m_x[2]; } } CMeshEdgeAndDir CMesh::AddEdge(CMeshVertex* v0, CMeshVertex* v1) { for (std::list<CMeshEdgeAndDir>::iterator It = v0->m_e.begin(); It != v0->m_e.end(); It++) { CMeshEdgeAndDir& edge_and_dir = *It; if (edge_and_dir.End() == v1) return edge_and_dir; } CMeshEdge* e = new CMeshEdge; m_edges.push_back(e); e->m_v[0] = v0; e->m_v[1] = v1; v0->m_e.push_back(CMeshEdgeAndDir(e, true)); v1->m_e.push_back(CMeshEdgeAndDir(e, false)); return CMeshEdgeAndDir(e, true); }
23.02963
100
0.599871
[ "mesh", "vector" ]
4f273676d995ab67ec9a6ab6041b0adc87b328a1
5,010
hpp
C++
CvGameCoreDLL/Boost-1.32.0/include/boost/signals/detail/signal_base.hpp
macaurther/DOCUSA
40586727c351d1b1130c05c2d4648cca3a8bacf5
[ "MIT" ]
93
2015-11-20T04:13:36.000Z
2022-03-24T00:03:08.000Z
CvGameCoreDLL/Boost-1.32.0/include/boost/signals/detail/signal_base.hpp
macaurther/DOCUSA
40586727c351d1b1130c05c2d4648cca3a8bacf5
[ "MIT" ]
206
2015-11-09T00:27:15.000Z
2021-12-04T19:05:18.000Z
CvGameCoreDLL/Boost-1.32.0/include/boost/signals/detail/signal_base.hpp
dguenms/Dawn-of-Civilization
1c4f510af97a869637cddb4c0859759158cea5ce
[ "MIT" ]
117
2015-11-08T02:43:46.000Z
2022-02-12T06:29:00.000Z
// Boost.Signals library // Copyright Douglas Gregor 2001-2004. Use, modification and // distribution is subject to the Boost Software License, Version // 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // For more information, see http://www.boost.org #ifndef BOOST_SIGNALS_SIGNAL_BASE_HEADER #define BOOST_SIGNALS_SIGNAL_BASE_HEADER #include <boost/signals/detail/config.hpp> #include <boost/signals/detail/signals_common.hpp> #include <boost/signals/detail/named_slot_map.hpp> #include <boost/signals/connection.hpp> #include <boost/signals/trackable.hpp> #include <boost/signals/slot.hpp> #include <boost/smart_ptr.hpp> #include <boost/any.hpp> #include <boost/utility.hpp> #include <boost/function/function2.hpp> #include <utility> #include <vector> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace BOOST_SIGNALS_NAMESPACE { namespace detail { // Must be constructed before calling the slots, because it safely // manages call depth class BOOST_SIGNALS_DECL call_notification { public: call_notification(const shared_ptr<signal_base_impl>&); ~call_notification(); shared_ptr<signal_base_impl> impl; }; // Implementation of base class for all signals. It handles the // management of the underlying slot lists. class BOOST_SIGNALS_DECL signal_base_impl { public: friend class call_notification; typedef function2<bool, any, any> compare_type; // Make sure that an exception does not cause the "clearing" flag to // remain set class temporarily_set_clearing { public: temporarily_set_clearing(signal_base_impl* b) : base(b) { base->flags.clearing = true; } ~temporarily_set_clearing() { base->flags.clearing = false; } private: signal_base_impl* base; }; friend class temporarily_set_clearing; signal_base_impl(const compare_type&, const any&); ~signal_base_impl(); // Disconnect all slots connected to this signal void disconnect_all_slots(); // Are there any connected slots? bool empty() const; // The number of connected slots std::size_t num_slots() const; // Disconnect all slots in the given group void disconnect(const any&); // We're being notified that a slot has disconnected static void slot_disconnected(void* obj, void* data); connection connect_slot(const any& slot, const any& name, shared_ptr<slot_base::data_t> data, connect_position at); private: // Remove all of the slots that have been marked "disconnected" void remove_disconnected_slots() const; public: // Our call depth when invoking slots (> 1 when we have a loop) mutable int call_depth; struct { // True if some slots have disconnected, but we were not able to // remove them from the list of slots because there are valid // iterators into the slot list mutable bool delayed_disconnect:1; // True if we are disconnecting all disconnected slots bool clearing:1; } flags; // Slots mutable named_slot_map slots_; any combiner_; // Types typedef named_slot_map::iterator iterator; }; class BOOST_SIGNALS_DECL signal_base : public noncopyable { public: typedef signal_base_impl::compare_type compare_type; friend class call_notification; signal_base(const compare_type& comp, const any& combiner); ~signal_base(); public: // Disconnect all slots connected to this signal void disconnect_all_slots() { impl->disconnect_all_slots(); } // Are there any connected slots? bool empty() const { return impl->empty(); } // How many slots are connected? std::size_t num_slots() const { return impl->num_slots(); } protected: connection connect_slot(const any& slot, const any& name, shared_ptr<slot_base::data_t> data, connect_position at) { return impl->connect_slot(slot, name, data, at); } typedef named_slot_map::iterator iterator; shared_ptr<signal_base_impl> impl; }; } // end namespace detail } // end namespace BOOST_SIGNALS_NAMESPACE } // end namespace boost #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_SIGNALS_SIGNAL_BASE_HEADER
31.118012
77
0.618563
[ "vector" ]
4f28103370771248a447b4808617853a97163cce
878
cpp
C++
XmlParser/XmlParser/xml_node.cpp
startrunner/fmi-intro-programming-xml-parser
461b0f740c507a53f7e272232476d5bd3a1c5c1e
[ "MIT" ]
1
2019-06-05T06:44:42.000Z
2019-06-05T06:44:42.000Z
XmlParser/XmlParser/xml_node.cpp
startrunner/fmi-intro-programming-xml-parser
461b0f740c507a53f7e272232476d5bd3a1c5c1e
[ "MIT" ]
null
null
null
XmlParser/XmlParser/xml_node.cpp
startrunner/fmi-intro-programming-xml-parser
461b0f740c507a53f7e272232476d5bd3a1c5c1e
[ "MIT" ]
null
null
null
#include "pch.h" #include "xml_node.h" using namespace std; xml_node::xml_node(string name) { name = name; } xml_node::xml_node(string name, map<string, string> attributes, string content) { this->name = name; this->attributes = attributes; this->content = content; } xml_node::xml_node(string name, map<string, string> attributes, vector<xml_node> children) { this->name = name; this->attributes = attributes; this->children = children; } xml_node::xml_node(const xml_node & toCopy) { this->name = toCopy.name; this->attributes = toCopy.attributes; this->children = toCopy.children; this->content = toCopy.content; } bool xml_node::operator!=(const xml_node & node) const { if (name != node.name)return true; if (children != node.children)return true; if (attributes != node.attributes)return true; return false; }
23.72973
90
0.686788
[ "vector" ]
4f2908fac4f568515a51f5aa444c02dcfa50fd7c
24,384
cpp
C++
src/turtlebot_tag.cpp
ikhatri/turtlebot-tag
ebdf15bb8738fdd82ff0a028e0b759f6f9224631
[ "MIT" ]
null
null
null
src/turtlebot_tag.cpp
ikhatri/turtlebot-tag
ebdf15bb8738fdd82ff0a028e0b759f6f9224631
[ "MIT" ]
null
null
null
src/turtlebot_tag.cpp
ikhatri/turtlebot-tag
ebdf15bb8738fdd82ff0a028e0b759f6f9224631
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <ros/ros.h> #include <std_msgs/String.h> #include <sstream> #include <math.h> #include <eigen3/Eigen/Dense> #include <geometry_msgs/Point32.h> #include <geometry_msgs/Point.h> #include <sensor_msgs/LaserScan.h> #include <sensor_msgs/PointCloud.h> #include <geometry_msgs/Twist.h> #include <nav_msgs/Odometry.h> #include <visualization_msgs/Marker.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <opencv2/opencv.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <message_filters/subscriber.h> #include <message_filters/synchronizer.h> #include <message_filters/sync_policies/approximate_time.h> #include "turtlebot_tag/CheckPointSrv.h" #include "turtlebot_tag/GetFreePathSrv.h" #include "turtlebot_tag/ObstacleLaserScanSrv.h" #include "turtlebot_tag/GetCommandVelSrv.h" #include "turtlebot_tag/GetTransformationSrv.h" using Eigen::Matrix3f; using Eigen::MatrixXf; using Eigen::MatrixXd; using Eigen::Vector3f; using Eigen::Vector2f; using geometry_msgs::Point32; using geometry_msgs::Point; using geometry_msgs::Twist; using nav_msgs::Odometry; using visualization_msgs::Marker; using sensor_msgs::LaserScan; using sensor_msgs::PointCloud; using std::cout; using std::vector; using namespace std; using turtlebot_tag::CheckPointSrv; using turtlebot_tag::GetFreePathSrv; using turtlebot_tag::ObstacleLaserScanSrv; using turtlebot_tag::GetCommandVelSrv; using turtlebot_tag::GetTransformationSrv; // Services and Subscribers // ros::ServiceServer checkPointServer; // ros::ServiceServer getFreePathServer; // ros::ServiceServer transformPointsServer; // ros::ServiceServer getCommandVelocityServer; ros::Subscriber laserScanSubscriber; ros::Subscriber odometrySubscriber; ros::ServiceClient getTransformClient; ros::Publisher driveMsgPublisher; ros::Publisher rvizPublisher; image_transport::Subscriber image_sub_; // Robot Params float robotRadius = 0.18; // 0.18 meters float maxLinearVelocity = 0.5; // [meters / second] float minLinearVelocity = 0.0; float maxLinearAcceleration = 0.5; // [meters / (second^2)] float maxAngularVelocity = 1.5; // [radians / second] float minAngularVelocity = -maxAngularVelocity; float maxAngularAcceleration = 2.0; // [radians / (second^2)] float velocityCommandUpdateRate = 0.05; // (new command every 0.05 seconds = 20 hz) float k_pi = 3.141592653589793; // Robot State Variables float currLinearVelocity = 0.0; float currAngularVelocity = 0.0; float currHeading = 0.0; float desiredHeading = 0.0; vector<Point32> currPoints; float currMaxDistance = 4.0; // Weights for objective function float angularWeight = 0.0; float freePathWeight = 0.0; float speedWeight = 0.0; float clearanceWeight = 0.0; float stopDistanceOffset = 0.0; Point32 target; bool finished = false; /* // Global Parameters const float gRobotRadius = 0.18; const float gRobotHeight = 0.36; const float gEpsilon = 0.15; const float gAMaxLin = 1 * 0.5; // m/s^2 const float gAMaxRot = 1 * 2.0; // rad/s^2 const float gVMaxLin = 0.5; // m/s const float gVMaxRot = 1.5; // rad/s const float gDT = 0.02; // s */ // general helper float constrainHeading(float heading) { // corrections for if you've turned past pi radians (180 degrees) // and you are now turning back towards the target instead of away. if (heading > k_pi) { return heading - (2 * k_pi); } else if (heading < -k_pi) { return heading + (2 * k_pi); } return heading; } // helper for visualization Marker getMarker(float r, float g, float b) { Marker marker; marker.header.frame_id = "/base_footprint"; marker.header.stamp = ros::Time(); marker.ns = "my_namespace"; marker.id = 0; marker.type = Marker::SPHERE_LIST; marker.action = Marker::ADD; marker.pose.position.x = 0; marker.pose.position.y = 0; marker.pose.position.z = 0; marker.pose.orientation.x = 0.0; marker.pose.orientation.y = 0.0; marker.pose.orientation.z = 0.0; marker.pose.orientation.w = 1.0; marker.scale.x = 0.1; marker.scale.y = 0.1; marker.scale.z = 0.1; marker.color.a = 1.0; marker.color.r = r; marker.color.g = g; marker.color.b = b; return marker; } // helper for checkPoint Point32 constructPoint(float x, float y, float z) { Point32 returnVal; returnVal.x = x; returnVal.y = y; returnVal.z = z; return returnVal; } // helper for checkPoint float distanceFormula(const Point32& a, const Point32& b) { float deltaX = b.x - a.x; float deltaY = b.y - a.y; return sqrt((deltaX * deltaX) + (deltaY * deltaY)); } // helper for checkPoint float lawOfCosines(float sideA, float sideB, float sideC) { float numerator = (sideA * sideA) + (sideB * sideB) - (sideC * sideC); float denominator = 2 * sideA * sideB; float theta = acos(numerator / denominator); return theta; } // helper for checkPoint bool isAlongStraightPath(Point32& p) { return (-robotRadius <= p.y && p.y <= robotRadius); } // helper for checkPoint bool isAlongCurvedPath(float robotCurvature, float pointCurvature) { float minRadiusOfCurvature = robotCurvature - robotRadius; float maxRadiusOfCurvature = robotCurvature + robotRadius; return (minRadiusOfCurvature <= pointCurvature) && (pointCurvature <= maxRadiusOfCurvature); } // Callback for "/COMPSCI403/CheckPoint" bool checkPoint(CheckPointSrv::Request& input, CheckPointSrv::Response& output) { /* in the event that the given point isn't on the path of the robot, then the free_path_length that's returned is the point's distance from the robot's path */ if (input.w == 0) { if (isAlongStraightPath(input.P)) { output.is_obstacle = true; output.free_path_length = input.P.x - sqrt((robotRadius * robotRadius) - (input.P.y * input.P.y)); } else { output.is_obstacle = false; output.free_path_length = fabs(input.P.y) - robotRadius; } } else if (input.w != 0) { // calculate radii of curvature (note: omega * r = v) Point32 centerOfCurvature = constructPoint(0, (input.v / input.w), 0); float radiusOfCurvature_robot = fabs(centerOfCurvature.y); float radiusOfCurvature_obstacle = distanceFormula(centerOfCurvature, input.P); // if there's potential for collision, calculate free path length if (isAlongCurvedPath(radiusOfCurvature_robot, radiusOfCurvature_obstacle)) { output.is_obstacle = true; // start by calculating the angle to the point along the current path float euclideanDistance = distanceFormula(constructPoint(0, 0, 0), input.P); float angleToPoint = lawOfCosines(radiusOfCurvature_robot, radiusOfCurvature_obstacle, euclideanDistance); if (input.P.x < 0) { angleToPoint = (2 * k_pi) - angleToPoint; } // then calculate angle to point when the point is in contact with the robot // (i.e. the minimum allowable angle to the point without colliding with it) float angleOfIntersection = lawOfCosines(radiusOfCurvature_robot, radiusOfCurvature_obstacle, robotRadius); // the difference in these two angles is the angle through which the robot // can travel without colliding with the point. output.free_path_length = (angleToPoint - angleOfIntersection) * radiusOfCurvature_robot; } else { // obstacle isn't on circular path output.is_obstacle = false; output.free_path_length = fabs(radiusOfCurvature_obstacle - radiusOfCurvature_robot) - robotRadius; } } return true; } // general function to get points from laser scan vector<Point32> laserScanToPoints(const LaserScan& scan, Point32& translation) { vector<Point32> returnVal; // angles in the range [angle_min, angle_max) int numOfDataPoints = (scan.angle_max - scan.angle_min) / scan.angle_increment; // convert all points that are within the range of the // laser scanner to (x, y, z) coordinates for (int i = 0; i < numOfDataPoints; i++) { float range = scan.ranges[i]; if (scan.range_min <= range && range <= scan.range_max) { // simultaneously calculate coordinates of currPoint in frame of scanner, // and apply the given transformation float currAngle = scan.angle_min + i * (scan.angle_increment); Point32 currPoint; currPoint.x = (range * cos(currAngle)) + translation.x; currPoint.y = (range * sin(currAngle)) + translation.y; currPoint.z = 0 + translation.z; // z (before translation) = height of points relative to laser scanner. // assuming a horizontal scanner, z (before translation) is always 0. returnVal.push_back(currPoint); } } return returnVal; } // general function to get info about a set of points for a given v and w vector<CheckPointSrv> checkAllPoints(const vector<Point32>& points, float v, float w) { vector<CheckPointSrv> output; for (unsigned int i = 0; i < points.size(); i++) { CheckPointSrv srv; srv.request.P = points[i]; srv.request.v = v; srv.request.w = w; checkPoint(srv.request, srv.response); output.push_back(srv); } return output; } // general function to get the point info with the min distance for a given v and w along a selected path GetFreePathSrv::Response getShortestDistance(const vector<CheckPointSrv>& pointInfo, float maxDistance, bool alongPath) { // init output GetFreePathSrv::Response output; output.is_obstacle = false; output.free_path_length = maxDistance; // find min distance for (unsigned int i = 0; i < pointInfo.size(); i++) { CheckPointSrv::Response currPoint = pointInfo[i].response; // if the point is an obstacle, it lies along the trajectory of the robot if ((currPoint.is_obstacle == alongPath) && (currPoint.free_path_length < output.free_path_length)) { output.is_obstacle = currPoint.is_obstacle; output.free_path_length = currPoint.free_path_length; } } return output; } // Callback for "/COMPSCI403/GetFreePath" bool getFreePath(GetFreePathSrv::Request& input, GetFreePathSrv::Response& output) { Point32 noTransform = constructPoint(0, 0, 0); vector<Point32> points = laserScanToPoints(input.laser_scan, noTransform); vector<CheckPointSrv> pointInfo = checkAllPoints(points, input.v, input.w); output = getShortestDistance(pointInfo, input.laser_scan.range_max, true); return true; } bool transformPoints(ObstacleLaserScanSrv::Request& input, ObstacleLaserScanSrv::Response& output) { output.S_prime = laserScanToPoints(input.S, input.T); return true; } bool hasEnoughRoomToStop(float v, float w, const vector<Point32>& points) { vector<CheckPointSrv> pointInfo = checkAllPoints(points, v, w); GetFreePathSrv::Response freePathInfo = getShortestDistance(pointInfo, currMaxDistance, true); if (!freePathInfo.is_obstacle) { return true; } // this check assumes a path of constant radius. // in order for that to be true, the ratio (v/w) must be the same throughout the maneuver // in order to keep it the same, v and w must change at the same rate. // therefore, we use the biggest acceleration that can be achieved // both linearly and angularly to calculate the stopping distance, // as this is the biggest acceleration that will keep a constant radius. float maxLinearAccelerationOfConstantRadius = std::min(maxLinearAcceleration, maxAngularAcceleration); float distanceNeededToStop = (-1 * (v * v)) / (2 * -maxLinearAccelerationOfConstantRadius); distanceNeededToStop += stopDistanceOffset; /* bool returnVal = (!srv.response.is_obstacle) || (distanceNeededToStop <= srv.response.free_path_length); if (!returnVal) { ROS_INFO("REJECTED V: %f, W: %f", v, w); ROS_INFO("OBSTACLE DETECTED: %d", srv.response.is_obstacle); ROS_INFO("STOPPING DISTANCE: %f", distanceNeededToStop); ROS_INFO("FPL: %f\n", srv.response.free_path_length); }*/ return (distanceNeededToStop <= freePathInfo.free_path_length); } // objective function float calculateScore(float v, float w, const vector<Point32>& points, bool print) { // get free path for the given v & w. (note that currScan is updated in publishToObstaclesTopic()) // distance score (high score = longest free path) vector<CheckPointSrv> pointInfo = checkAllPoints(points, v, w); float freePathLength = getShortestDistance(pointInfo, currMaxDistance, true).free_path_length; float distanceToObstaclesScore = freePathLength * freePathWeight; // get the shortest distance of an obstacle not on the current path to the robot // clearance score (high score = most clearance) // get the shortest distance of an obstacle not on the current path to the robot // clearance score (high score = most clearance) float sizeBefore = pointInfo.size(); if (w != 0) { // eliminate points that are beyond the FPL Point32 centerOfCurvature = constructPoint(0, (v / w), 0); float robotTurningRadius = fabs(centerOfCurvature.y); float freeAngle = freePathLength / robotTurningRadius; for (int i = pointInfo.size()-1; i >= 0; i--) { // calculate angle to point float pointTurningRadius = distanceFormula(centerOfCurvature, pointInfo[i].request.P); float euclideanDistance = distanceFormula(constructPoint(0, 0, 0), pointInfo[i].request.P); float angleToPoint = lawOfCosines(robotTurningRadius, pointTurningRadius, euclideanDistance); if (pointInfo[i].request.P.x < 0) { angleToPoint = (2 * k_pi) - angleToPoint; } if (angleToPoint > freeAngle) { pointInfo.erase(pointInfo.begin() + i); } } } float sizeAfter = pointInfo.size(); if (print) { ROS_INFO("SIZE DIFFERENCE: %f", (sizeBefore - sizeAfter)); } float clearance = getShortestDistance(pointInfo, currMaxDistance, false).free_path_length; if(clearance < .2) { return -1; } float clearanceScore = clearance * clearanceWeight; // angle score (highest score is heading of 0, score gets worse as heading deviates from 0) float headingToTarget = atan2(target.y, target.x); float proposedHeading = constrainHeading(headingToTarget - w * velocityCommandUpdateRate); //float angleToTarget = (k_pi - fabs(proposedHeading)); float angularScore = (k_pi - fabs(proposedHeading)) * angularWeight; // speed cost (high score = high speed) float speedScore = v * speedWeight; float totalScore = angularScore + distanceToObstaclesScore + speedScore + clearanceScore; if (print) { ROS_INFO("V: %f, W: %f", v, w); ROS_INFO("ANGULAR SCORE: %f", angularScore); ROS_INFO("DISTANCE SCORE: %f", distanceToObstaclesScore); ROS_INFO("FPL: %f", freePathLength); ROS_INFO("SPEED SCORE: %f", speedScore); ROS_INFO("CLEARANCE SCORE: %f", clearanceScore); ROS_INFO("TOTAL SCORE: %f\n", totalScore); Marker obstacles = getMarker(1, 0, 0); Marker freePoints = getMarker(0, 1, 0); for (unsigned int i = 0; i < pointInfo.size(); i++) { geometry_msgs::Point toPush; toPush.x = pointInfo[i].request.P.x; toPush.y = pointInfo[i].request.P.y; toPush.z = pointInfo[i].request.P.z; if (pointInfo[i].response.is_obstacle) { obstacles.points.push_back(toPush); } else { freePoints.points.push_back(toPush); } } rvizPublisher.publish(obstacles); //rvizPublisher.publish(freePoints); } return totalScore; } bool getCommandVelocity(GetCommandVelSrv::Request& input, GetCommandVelSrv::Response& output) { // calculate bounds of dynamic window float maxDeltaV = maxLinearAcceleration * velocityCommandUpdateRate; float maxDeltaW = maxAngularAcceleration * velocityCommandUpdateRate; float linearVelocityUpperBound = std::min(maxLinearVelocity, input.v_0 + maxDeltaV); float linearVelocityLowerBound = std::max(minLinearVelocity, input.v_0 - maxDeltaV); float angularVelocityUpperBound = std::min(maxAngularVelocity, input.w_0 + maxDeltaW); float angularVelocityLowerBound = std::max(minAngularVelocity, input.w_0 - maxDeltaW); // init output command to just be achieveable velocities closest to 0 output.C_v = linearVelocityLowerBound; if (angularVelocityLowerBound <= 0 && 0 <= angularVelocityUpperBound) { output.C_w = 0; } else { output.C_w = (fabs(angularVelocityLowerBound) < fabs(angularVelocityUpperBound)) ? angularVelocityLowerBound : angularVelocityUpperBound; } // calculate initial score ROS_INFO("INITIAL SCORE CALCULATION"); float maxScore = calculateScore(output.C_v, output.C_w, currPoints, true); // set dynamic window stepsize (resolution) float numOfSteps = 10.0; // actual number of discrete velocites checked should theoretically this value squared. // however, this wasn't alwasy observed, likely because ranges aren't just between integers. float linearVelocityStepSize = (linearVelocityUpperBound - linearVelocityLowerBound) / numOfSteps; float angularVelocityStepSize = (angularVelocityUpperBound - angularVelocityLowerBound) / numOfSteps; // iterate through all discretized combinations of V and W for (float currV = linearVelocityLowerBound; currV <= linearVelocityUpperBound; currV += linearVelocityStepSize) { for (float currW = angularVelocityLowerBound; currW <= angularVelocityUpperBound; currW += angularVelocityStepSize) { if (hasEnoughRoomToStop(currV, currW, currPoints)) { float score = calculateScore(currV, currW, currPoints, false); if (score > maxScore) { maxScore = score; output.C_v = currV; output.C_w = currW; } } } } ROS_INFO("MAX SCORE FOUND"); calculateScore(output.C_v, output.C_w, currPoints, true); // this is here just to print individual scores return true; } void updateWorldView(const LaserScan& scan) { GetTransformationSrv srv1; getTransformClient.call(srv1); ObstacleLaserScanSrv srv2; srv2.request.S = scan; srv2.request.R = srv1.response.R; srv2.request.T = srv1.response.T; transformPoints(srv2.request, srv2.response); currPoints = srv2.response.S_prime; currMaxDistance = scan.range_max; } void updateVelocity() { GetCommandVelSrv srv; srv.request.v_0 = currLinearVelocity; srv.request.w_0 = currAngularVelocity; getCommandVelocity(srv.request, srv.response); geometry_msgs::Twist output; output.linear.x = srv.response.C_v; output.linear.y = 0; output.linear.z = 0; output.angular.x = 0; output.angular.y = 0; output.angular.z = srv.response.C_w; if (finished) { output.linear.x = 0; output.angular.z = 0; ROS_INFO("PLAYED TIL COMPLETION. COMPLETION IS HERE <3"); driveMsgPublisher.publish(output); //ROS_INFO("DRIVE MESSAGE PUBLISHED:\nV = %f, W = %f\n\n\n\n", driveMsg.v, driveMsg.w); return; } driveMsgPublisher.publish(output); ROS_INFO("DRIVE MESSAGE PUBLISHED:\nV = %f, W = %f\n\n\n\n", srv.response.C_v, srv.response.C_w); // update state variables currLinearVelocity = srv.response.C_v; currAngularVelocity = srv.response.C_w; currHeading = constrainHeading(currHeading + (currAngularVelocity * velocityCommandUpdateRate)); if (srv.response.C_w != 0) { float deltaAngle = -1 * srv.response.C_w * velocityCommandUpdateRate; // step 1: translate to the center target.x = target.x - 0; target.y = target.y - (srv.response.C_v / srv.response.C_w); // step 2: rotate by deltaAngle float xRotated = target.x * cos(deltaAngle) - target.y * sin(deltaAngle); float yRotated = target.x * sin(deltaAngle) + target.y * cos(deltaAngle); target.x = xRotated; target.y = yRotated; // step 3: translate back to where you were before target.x = target.x + 0; target.y = target.y + (srv.response.C_v / srv.response.C_w); } if(distanceFormula(target, constructPoint(0,0,0)) <= .5){ finished = true; } } void laserScanCallback(const LaserScan& scan) { updateWorldView(scan); updateVelocity(); } void odometeryCallback(const Odometry& odom) { /* currLinearVelocity = odom.twist.twist.linear.x; currAngularVelocity = odom.twist.twist.angular.z; currHeading = constrainHeading(currHeading + (currAngularVelocity * velocityCommandUpdateRate)); */ } void callback(const sensor_msgs::ImageConstPtr& i1, const sensor_msgs::ImageConstPtr& i2){ cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(i1, sensor_msgs::image_encodings::BGR8); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } cv::Mat orange_image; cv::Scalar lower(0, 0, 55); cv::Scalar upper(20, 20, 255); cv::inRange(cv_ptr->image, lower, upper, orange_image); // Setup SimpleBlobDetector parameters. cv::SimpleBlobDetector::Params params; // Change thresholds params.minThreshold = 10; params.maxThreshold = 200; // Filter by Area. params.filterByArea = true; params.minArea = 10; // Filter by Circularity params.filterByCircularity = true; params.minCircularity = 0.3; params.maxCircularity = 0.8; // Filter by Convexity params.filterByConvexity = true; params.minConvexity = 0.87; // Filter by Inertia params.filterByInertia = true; params.minInertiaRatio = 0.01; cv::Ptr<cv::SimpleBlobDetector> detector = cv::SimpleBlobDetector::create(params); std::vector<cv::KeyPoint> keypoints; detector->detect(orange_image, keypoints); float x_total = 0; float y_total = 0; for(auto& k : keypoints){ x_total += k.pt.x; y_total += k.pt.y; } std::vector<cv::KeyPoint> the_keypoint; the_keypoint.push_back(cv::KeyPoint(x_total/keypoints.size(), y_total/keypoints.size(), 100)); // cv::Mat im_with_keypoints; // cv::drawKeypoints( cv_ptr->image, the_keypoint, im_with_keypoints, cv::Scalar(0,255,0), cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS ); // Encoding the depth image to be read in easily cv_bridge::CvImagePtr cv_ptr2; try { cv_ptr2 = cv_bridge::toCvCopy(i2, sensor_msgs::image_encodings::TYPE_16UC1); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } float depth = cv_ptr2->image.at<short int>(cv::Point(x_total/keypoints.size(), y_total/keypoints.size())); // Set the new goal point // Need to check if this is actually correct target.x = x_total/keypoints.size(); target.y = -1*y_total/keypoints.size(); target.z = depth; } int main(int argc, char **argv) { ros::init(argc, argv, "assignment5"); ros::NodeHandle n; if (argc != 6) { ROS_INFO("LOL U DIDN'T GIVE ANY INPUT ARGS"); ROS_INFO("CHECK MAIN TO SEE WHAT U NEED TO INPUT LOL"); return 0; } angularWeight = float(atof(argv[1])); // 4 // 500 // 200 freePathWeight = float(atof(argv[2])); // 1 // 1 // 1 speedWeight = float(atof(argv[3])); // 1 // 150 // 50 clearanceWeight = float(atof(argv[4])); // 0 // 10 // 1 stopDistanceOffset = float(atof(argv[5])); // 0.25 // target.x = float(atof(argv[6])); // target.y = float(atof(argv[7])); // init services and subscribers // checkPointServer = n.advertiseService("/COMPSCI403/CheckPoint", checkPoint); // getFreePathServer = n.advertiseService("/COMPSCI403/GetFreePath", getFreePath); // transformPointsServer = n.advertiseService("/COMPSCI403/ObstacleLaserScan", transformPoints); // getCommandVelocityServer = n.advertiseService("/COMPSCI403/GetCommandVel", getCommandVelocity); // Blob Detection callback image_transport::ImageTransport it_(n); typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::Image, sensor_msgs::Image> sync_policy_classification; message_filters::Subscriber<sensor_msgs::Image> image_sub_(n, "/camera/rgb/image_color", 10); message_filters::Subscriber<sensor_msgs::Image> points(n, "/camera/depth/image", 10); message_filters::Synchronizer<sync_policy_classification> sync(sync_policy_classification(10), image_sub_, points); sync.registerCallback(boost::bind(&callback, _1, _2)); laserScanSubscriber = n.subscribe("/COMPSCI403/LaserScan", 10000, laserScanCallback); odometrySubscriber = n.subscribe("/odom", 10000, odometeryCallback); getTransformClient = n.serviceClient<GetTransformationSrv>("/COMPSCI403/GetTransformation"); driveMsgPublisher = n.advertise<geometry_msgs::Twist>("/cmd_vel_mux/input/navi", 10000); rvizPublisher = n.advertise<Marker>("visualization_marker", 0); ros::spin(); return 0; }
35.753666
141
0.718258
[ "vector" ]
4f2eaa145976dabe7d5ca8863479bd7623e174ab
3,151
cpp
C++
3d_walk/nodes/spherenode.cpp
ivan-uskov/graphics
dbcfa9db45fb8ba362209470bbae95452b7bfe75
[ "MIT" ]
null
null
null
3d_walk/nodes/spherenode.cpp
ivan-uskov/graphics
dbcfa9db45fb8ba362209470bbae95452b7bfe75
[ "MIT" ]
2
2015-10-26T08:18:53.000Z
2016-01-11T18:05:00.000Z
3d_walk/nodes/spherenode.cpp
ivan-uskov/graphics
dbcfa9db45fb8ba362209470bbae95452b7bfe75
[ "MIT" ]
null
null
null
#include "spherenode.h" #include "../utils/mycast.h" #include <vector> using namespace MyMath; using namespace std; SphereNode::SphereNode(SceneNode * parent, Sphere const& sphere, int accuracy) : ModifiedSceneNode(parent) , m_sphere(sphere) , m_accuracy(accuracy) { } void SphereNode::render(QPainter &) { auto tetrahedron = m_sphere.getTetrahedron(); auto verticeses = tetrahedron.getVertices(); vector<Triangle> faceses = { {0, 1, 2}, {0, 2, 3}, {3, 1, 0}, {1, 3, 2} }; triangulate(faceses, verticeses); auto vertices = MyMath::vector3DToSimpleVertexArray(verticeses); auto faces = MyMath::triangleToVertexIndexArray(faceses); auto normales = fillNormales(verticeses); prepareVertexArray(vertices); glVertexPointer(VECTOR_3_SIZE, GL_FLOAT, sizeof(SimpleVertex), &vertices[0].pos); glColorPointer(VECTOR_4_SIZE, GL_UNSIGNED_BYTE, sizeof(SimpleVertex), &vertices[0].color); glNormalPointer(GL_FLOAT, sizeof(Vec3), normales.data()); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glDrawElements(GL_TRIANGLES, (GLsizei)faces.size(), GL_UNSIGNED_INT, faces.data()); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); } void SphereNode::triangulate(vector<Triangle> & triangles, vector<QVector3D> & vertices) const { auto accuracy = m_accuracy; while (accuracy-- > 0) { triangulateOnce(triangles, vertices); } } void SphereNode::triangulateOnce(vector<Triangle> & triangles, vector<QVector3D> & vertices) const { vector<Triangle> newTriangles; for (Triangle const& tr : triangles) { auto p1 = vertices[tr.p1]; auto p2 = vertices[tr.p2]; auto p3 = vertices[tr.p3]; auto p12 = middle(p1, p2); auto p13 = middle(p1, p3); auto p23 = middle(p2, p3); auto ip12 = (VertexIndex) vertices.size(); vertices.push_back(sphereProject(p12)); auto ip13 = (VertexIndex) vertices.size(); vertices.push_back(sphereProject(p13)); auto ip23 = (VertexIndex) vertices.size(); vertices.push_back(sphereProject(p23)); newTriangles.push_back({tr.p1, ip12, ip13}); newTriangles.push_back({ip12, tr.p2, ip23}); newTriangles.push_back({ip12, ip23, ip13}); newTriangles.push_back({ip13, ip23, tr.p3}); } triangles.clear(); triangles = newTriangles; } QVector3D SphereNode::sphereProject(QVector3D const& vertex) const { auto vertexVector = (vertex - m_sphere.position()).normalized(); return vertexVector * m_sphere.radius(); } vector<Vec3> SphereNode::fillNormales(vector<QVector3D> const& vertices) { vector<Vec3> normales; for (auto const& vertex : vertices) { auto n = (vertex - m_sphere.position()).normalized(); normales.push_back({n.x(), n.y(), n.z()}); } return normales; }
29.448598
99
0.648366
[ "render", "vector" ]
4f30202db28135c91d29fde62cdec2937361cc1b
1,493
cc
C++
src/device/bluetooth/bluetooth_utils.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
9
2018-09-21T05:36:12.000Z
2021-11-15T15:14:36.000Z
device/bluetooth/bluetooth_utils.cc
devasia1000/chromium
919a8a666862fb866a6bb7aa7f3ae8c0442b4828
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
device/bluetooth/bluetooth_utils.cc
devasia1000/chromium
919a8a666862fb866a6bb7aa7f3ae8c0442b4828
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2018-11-28T14:54:13.000Z
2020-07-02T07:36:07.000Z
// Copyright (c) 2012 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 "device/bluetooth/bluetooth_utils.h" #include <vector> #include "base/basictypes.h" #include "base/logging.h" #include "base/string_util.h" namespace { static const char* kCommonUuidPostfix = "-0000-1000-8000-00805f9b34fb"; static const char* kCommonUuidPrefix = "0000"; static const int kUuidSize = 36; } // namespace namespace device { namespace bluetooth_utils { std::string CanonicalUuid(std::string uuid) { if (uuid.empty()) return std::string(); if (uuid.size() < 11 && uuid.find("0x") == 0) uuid = uuid.substr(2); if (!(uuid.size() == 4 || uuid.size() == 8 || uuid.size() == 36)) return std::string(); if (uuid.size() == 4 || uuid.size() == 8) { for (size_t i = 0; i < uuid.size(); ++i) { if (!IsHexDigit(uuid[i])) return std::string(); } if (uuid.size() == 4) return kCommonUuidPrefix + uuid + kCommonUuidPostfix; return uuid + kCommonUuidPostfix; } std::string uuid_result(uuid); for (int i = 0; i < kUuidSize; ++i) { if (i == 8 || i == 13 || i == 18 || i == 23) { if (uuid[i] != '-') return std::string(); } else { if (!IsHexDigit(uuid[i])) return std::string(); uuid_result[i] = tolower(uuid[i]); } } return uuid_result; } } // namespace bluetooth_utils } // namespace device
24.883333
73
0.610181
[ "vector" ]
4f309aaccaaf5469c333b4e5a0197d5dae8f0823
1,152
hpp
C++
hw3-Constructing Abstract Syntax Trees/src/include/AST/ast.hpp
banne2266/compiler-NCTU-2020
d8a642479bc0d62611773591af844b7daebcc99a
[ "MIT" ]
1
2021-08-03T13:45:31.000Z
2021-08-03T13:45:31.000Z
hw3-Constructing Abstract Syntax Trees/src/include/AST/ast.hpp
banne2266/compiler-NCTU-2020
d8a642479bc0d62611773591af844b7daebcc99a
[ "MIT" ]
null
null
null
hw3-Constructing Abstract Syntax Trees/src/include/AST/ast.hpp
banne2266/compiler-NCTU-2020
d8a642479bc0d62611773591af844b7daebcc99a
[ "MIT" ]
1
2021-06-17T07:13:52.000Z
2021-06-17T07:13:52.000Z
#ifndef __AST_H #define __AST_H #include <cstdint> #include <cstring> #include <string> #include<vector> #include "visitor/AstNodeVisitor.hpp" struct Location { Location(const uint32_t line, const uint32_t col) : line(line), col(col) {} uint32_t line; uint32_t col; }; enum p_type{ int_, real_, char_, boolean_, void_ }; union value{ int value; double real_value; std::string string_value; bool boolean_value; }; struct array_part{ std::vector<int> structed_part_list; enum p_type type; }; struct const_value{ int value; double real_value; std::string string_value; bool boolean_value; enum p_type type; int col; }; struct id_list{ std::vector<char *> name_list; std::vector<int> col_list; enum p_type type; }; class AstNode { public: AstNode(const uint32_t line, const uint32_t col); virtual ~AstNode() = 0; const Location &getLocation() const; virtual void print() = 0; virtual void visitChildNodes(AstNodeVisitor &p_visitor) = 0; virtual void accept(AstNodeVisitor &p_visitor) = 0; protected: const Location location; }; #endif
16.457143
79
0.681424
[ "vector" ]
4f345abafd654998252ba6bcdf624fea7865ea95
21,015
cc
C++
tests/unittests/plugin_unittest.cc
Exstream-OpenSource/Chromium-Embedded-Framework
74cf22c97ad16b56a37c9362c47a04425615dc28
[ "BSD-3-Clause" ]
1
2020-06-30T01:18:35.000Z
2020-06-30T01:18:35.000Z
tests/unittests/plugin_unittest.cc
Exstream-OpenSource/Chromium-Embedded-Framework
74cf22c97ad16b56a37c9362c47a04425615dc28
[ "BSD-3-Clause" ]
null
null
null
tests/unittests/plugin_unittest.cc
Exstream-OpenSource/Chromium-Embedded-Framework
74cf22c97ad16b56a37c9362c47a04425615dc28
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2015 The Chromium Embedded Framework 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 "include/base/cef_bind.h" #include "include/cef_pack_resources.h" #include "include/cef_resource_bundle.h" #include "include/wrapper/cef_closure_task.h" #include "include/wrapper/cef_stream_resource_handler.h" #include "tests/cefclient/browser/client_app_browser.h" #include "tests/cefclient/browser/resource_util.h" #include "tests/unittests/routing_test_handler.h" #include "testing/gtest/include/gtest/gtest.h" namespace { std::string GetDataResourceAsString(int resource_id) { void* data; size_t data_size; if (CefResourceBundle::GetGlobal()->GetDataResource(resource_id, data, data_size)) { return std::string(static_cast<char*>(data), data_size); } return std::string(); } // Browser-side app delegate. class PluginBrowserTest : public client::ClientAppBrowser::Delegate { public: PluginBrowserTest() {} void OnBeforeCommandLineProcessing( CefRefPtr<client::ClientAppBrowser> app, CefRefPtr<CefCommandLine> command_line) override { // Allow all plugin loading by default. command_line->AppendSwitchWithValue("plugin-policy", "allow"); } private: IMPLEMENT_REFCOUNTING(PluginBrowserTest); }; const char kPdfHtmlUrl[] = "http://tests/pdf.html"; const char kPdfDirectUrl[] = "http://tests/pdf.pdf"; // Delay waiting for the plugin placeholder to load. const int64 kPlaceholderLoadDelayMs = 1000; // Delay waiting for iframe tests to load the PDF file. #if defined(OS_LINUX) const int64 kPdfLoadDelayMs = 7000; #else const int64 kPdfLoadDelayMs = 5000; #endif // Browser-side test handler. class PluginTestHandler : public RoutingTestHandler, public CefContextMenuHandler { public: enum Mode { // No specified context or handler (implicitly uses the global context). GLOBAL_DEFAULT, // Global context with no handler. GLOBAL_NO_HANDLER, // Global context with handler that allows plugin load. GLOBAL_ALLOW, // Global context with handler that blocks plugin load. Then, load the // plugin via the context menu. GLOBAL_BLOCK_LOAD, // Global context with handler that blocks plugin load. Then, hide the // plugin via the context menu. GLOBAL_BLOCK_HIDE, // Global context with handler that disables plugin load. Then, hide the // plugin via the context menu. GLOBAL_DISABLE_HIDE, // Global context with handler that removes the plugin from the // `navigator.plugins` list and consequently disables plugin load. GLOBAL_NO_LIST, // Custom context with no handler. CUSTOM_NO_HANDLER, // Custom context with handler that allows plugin load. CUSTOM_ALLOW, // Custom context with handler that blocks plugin load. Then, load the // plugin via the context menu. CUSTOM_BLOCK_LOAD, // Custom context with handler that blocks plugin load. Then, hide the // plugin via the context menu. CUSTOM_BLOCK_HIDE, // Custom context with handler that disables plugin load. Then, hide the // plugin via the context menu. CUSTOM_DISABLE_HIDE, // Custom context with handler that removes the plugin from the // `navigator.plugins` list and consequently disables plugin load. CUSTOM_NO_LIST, }; class RequestContextHandler : public CefRequestContextHandler { public: explicit RequestContextHandler(PluginTestHandler* handler) : handler_(handler) {} bool OnBeforePluginLoad(const CefString& mime_type, const CefString& plugin_url, const CefString& top_origin_url, CefRefPtr<CefWebPluginInfo> plugin_info, PluginPolicy* plugin_policy) override { const std::string& mime_type_str = mime_type; if (top_origin_url.empty()) { handler_->got_on_before_plugin_empty_origin_.yes(); if (mime_type_str == "application/pdf" && handler_->HasNoList()) { // Remove the PDF plugin from the `navigator.plugins` list. *plugin_policy = PLUGIN_POLICY_DISABLE; return true; } else { // Ignore requests for building the plugin list. return false; } } if (mime_type_str == "application/pdf") { if (!handler_->got_on_before_plugin_load_pdf1_) handler_->got_on_before_plugin_load_pdf1_.yes(); else if (!handler_->got_on_before_plugin_load_pdf2_) handler_->got_on_before_plugin_load_pdf2_.yes(); else NOTREACHED(); } else { NOTREACHED(); } if (handler_->HasAllow()) { *plugin_policy = PLUGIN_POLICY_ALLOW; return true; } else if (handler_->HasBlock()) { *plugin_policy = PLUGIN_POLICY_BLOCK; return true; } else if (handler_->HasDisable()) { *plugin_policy = PLUGIN_POLICY_DISABLE; return true; } return false; } void Detach() { handler_ = NULL; } private: PluginTestHandler* handler_; IMPLEMENT_REFCOUNTING(RequestContextHandler); }; PluginTestHandler(Mode mode, const std::string& url) : mode_(mode), url_(url) { } // Has a specified RequestContext but not necessarily a custom handler. bool HasRequestContext() const { return mode_ != GLOBAL_DEFAULT; } // Has a specified RequestContext and custom handler. bool HasRequestContextHandler() const { return mode_ != GLOBAL_DEFAULT && mode_ != GLOBAL_NO_HANDLER && mode_ != CUSTOM_NO_HANDLER; } // Using the global request context, either directly or with a custom handler. bool HasGlobalRequestContext() const { return mode_ >= GLOBAL_DEFAULT && mode_ <= GLOBAL_NO_LIST; } // Should allow the plugin load via the custom handler. bool HasAllow() const { return mode_ == GLOBAL_ALLOW || mode_ == CUSTOM_ALLOW; } // Should block the plugin load via the custom handler. bool HasBlock() const { return mode_ == GLOBAL_BLOCK_LOAD || mode_ == GLOBAL_BLOCK_HIDE || mode_ == CUSTOM_BLOCK_LOAD || mode_ == CUSTOM_BLOCK_HIDE; } // Should disable the plugin load via the custom handler. bool HasDisable() const { return mode_ == GLOBAL_DISABLE_HIDE || mode_ == CUSTOM_DISABLE_HIDE; } // Should exclude the plugin from the `navigator.plugins` list. bool HasNoList() const { return mode_ == GLOBAL_NO_LIST || mode_ == CUSTOM_NO_LIST; } // Should load the plugin via the context menu. bool HasContextLoad() const { return mode_ == GLOBAL_BLOCK_LOAD || mode_ == CUSTOM_BLOCK_LOAD; } // Should hide the plugin via the context menu. bool HasContextHide() const { return mode_ == GLOBAL_BLOCK_HIDE || mode_ == GLOBAL_DISABLE_HIDE || mode_ == CUSTOM_BLOCK_HIDE || mode_ == CUSTOM_DISABLE_HIDE; } std::string GetPluginNode() const { return "document.getElementsByTagName('embed')[0]"; } void WaitForNavigatorPlugins(CefRefPtr<CefFrame> frame) const { // Test if the `navigator.plugins` list includes the PDF extension. const std::string& code = " if (navigator.plugins['Chrome PDF Viewer'].filename == " " 'mhjfbmdgcfjbbpaeojofohoefgiehjai') {" " window.testQuery({request:'pdf_plugin_found'});" "} else {" " window.testQuery({request:'pdf_plugin_missing'});" "}"; frame->ExecuteJavaScript(code, frame->GetURL(), 0); } void WaitForPlaceholderLoad(CefRefPtr<CefFrame> frame) { // Waits for the placeholder to load. CefPostDelayedTask(TID_UI, base::Bind(&PluginTestHandler::TriggerContextMenu, this, frame->GetBrowser()), kPlaceholderLoadDelayMs); } void WaitForPlaceholderHide(CefRefPtr<CefFrame> frame) const { // Waits for the placeholder to be hidden (style set to display:none). // See PluginPlaceholderBase::HidePlugin. const std::string& code = "var plugin = " + GetPluginNode() +";" "var observer = new MutationObserver(function(mutations) {" " mutations.forEach(function(mutationRecord) {" " window.testQuery({request:'placeholder_hidden'});" " observer.disconnect();" " });" "});" "observer.observe(plugin, " " { attributes : true, attributeFilter : ['style'] });"; frame->ExecuteJavaScript(code, frame->GetURL(), 0); } void WaitForPluginLoad(CefRefPtr<CefFrame> frame) { if (url_ == kPdfHtmlUrl) { // PDFScriptingAPI does not work with iframes (the LoadCallback will // never be executed). Use a timeout instead. if (got_context_menu_dismissed_) { // After context menu display. Destroy the test. CefPostDelayedTask(TID_UI, base::Bind(&PluginTestHandler::DestroyTest, this), kPdfLoadDelayMs); } else { // Trigger the context menu. CefPostDelayedTask(TID_UI, base::Bind(&PluginTestHandler::TriggerContextMenu, this, frame->GetBrowser()), kPdfLoadDelayMs); } return; } // Wait for the PDF file to load. // See chrome/browser/pdf/pdf_extension_test_util.cc. const std::string& scripting_api_js = GetDataResourceAsString(IDR_PDF_PDF_SCRIPTING_API_JS); EXPECT_TRUE(!scripting_api_js.empty()); frame->ExecuteJavaScript(scripting_api_js, frame->GetURL(), 0); const std::string& code = "var scriptingAPI = new PDFScriptingAPI(window, "+ GetPluginNode() +");" "scriptingAPI.setLoadCallback(function(success) {" " window.testQuery({request:'plugin_ready'});" "});"; frame->ExecuteJavaScript(code, frame->GetURL(), 0); } void EndTest() { CefPostTask(TID_UI, base::Bind(&PluginTestHandler::DestroyTest, this)); } CefRefPtr<CefContextMenuHandler> GetContextMenuHandler() override { return this; } void RunTest() override { CefRefPtr<CefRequestContext> request_context; if (HasRequestContext()) { if (HasRequestContextHandler()) context_handler_ = new RequestContextHandler(this); if (HasGlobalRequestContext()) { // Use the global request context. request_context = CefRequestContext::CreateContext( CefRequestContext::GetGlobalContext(), context_handler_.get()); } else { // Create the request context that will use an in-memory cache. CefRequestContextSettings settings; request_context = CefRequestContext::CreateContext( settings, context_handler_.get()); } } // Create the browser. CreateBrowser(url_, request_context); // Time out the test after a reasonable period of time. SetTestTimeout(5000 + kPdfLoadDelayMs); } CefRefPtr<CefResourceHandler> GetResourceHandler( CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefRequest> request) override { const std::string& url = request->GetURL(); if (url == kPdfHtmlUrl) { CefRefPtr<CefStreamReader> stream = client::GetBinaryResourceReader("pdf.html"); return new CefStreamResourceHandler("text/html", stream); } else if (url == kPdfDirectUrl) { CefRefPtr<CefStreamReader> stream = client::GetBinaryResourceReader("pdf.pdf"); return new CefStreamResourceHandler("application/pdf", stream); } NOTREACHED(); return NULL; } void OnLoadEnd(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int httpStatusCode) override { bool is_pdf1 = false; const std::string& url = frame->GetURL(); if (url == kPdfHtmlUrl) { if (!got_on_load_end_html_) got_on_load_end_html_.yes(); else NOTREACHED(); } else if (url == kPdfDirectUrl) { if (!got_on_load_end_pdf1_) { got_on_load_end_pdf1_.yes(); is_pdf1 = true; } else if (!got_on_load_end_pdf2_) { got_on_load_end_pdf2_.yes(); } else { NOTREACHED(); } } else { NOTREACHED(); } if (HasNoList()) { // If the plugin is not listed then the PDF documents will never load. EXPECT_STREQ(kPdfHtmlUrl, url.c_str()); WaitForNavigatorPlugins(frame); } else if (is_pdf1) { // The first PDF document has loaded. WaitForNavigatorPlugins(frame); } } bool OnQuery(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int64 query_id, const CefString& request, bool persistent, CefRefPtr<Callback> callback) override { if (request == "pdf_plugin_found" || request == "pdf_plugin_missing") { if (request == "pdf_plugin_found") got_pdf_plugin_found_.yes(); else got_pdf_plugin_missing_.yes(); if (HasNoList()) { // The plugin will not load. End the test. EndTest(); } else if (HasBlock() || HasDisable()) { // Wait for the plugin placeholder for the first PDF file to load. The // test will continue from OnQuery. WaitForPlaceholderLoad(frame); } else { // Wait for the first PDF file to load. WaitForPluginLoad(frame); } } else if (request == "placeholder_hidden") { EXPECT_FALSE(got_placeholder_hidden_); got_placeholder_hidden_.yes(); // The plugin placeholder has been hidden. End the test. EndTest(); } else if (request == "plugin_ready") { EXPECT_FALSE(got_plugin_ready_); got_plugin_ready_.yes(); // The plugin has loaded the PDF file. if (got_context_menu_dismissed_) { // After context menu display. End the test. EndTest(); } else { // Trigger the context menu. CefPostTask(TID_UI, base::Bind(&PluginTestHandler::TriggerContextMenu, this, browser)); } } else { NOTREACHED(); } return true; } void TriggerContextMenu(CefRefPtr<CefBrowser> browser) { CefMouseEvent mouse_event; // Somewhere in the first plugin. mouse_event.x = 100; mouse_event.y = 100; // Send right-click mouse down and mouse up to tigger context menu. browser->GetHost()->SendMouseClickEvent(mouse_event, MBT_RIGHT, false, 0); browser->GetHost()->SendMouseClickEvent(mouse_event, MBT_RIGHT, true, 0); } bool RunContextMenu(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefContextMenuParams> params, CefRefPtr<CefMenuModel> model, CefRefPtr<CefRunContextMenuCallback> callback) override { EXPECT_FALSE(got_run_context_menu_); got_run_context_menu_.yes(); if (HasContextLoad() || HasContextHide()) { // Should have 4 elements -- plugin name, separator, run, hide. EXPECT_EQ(4, model->GetCount()); int command_id; if (HasContextLoad()) { // Execute the run command. command_id = model->GetCommandIdAt(2); } else { // Wait for the plugin to be hidden. WaitForPlaceholderHide(frame); // Execute the hide command. command_id = model->GetCommandIdAt(3); } EXPECT_GE(command_id, MENU_ID_CUSTOM_FIRST); EXPECT_LE(command_id, MENU_ID_CUSTOM_LAST); callback->Continue(command_id, static_cast<EventFlags>(0)); } else { // Do nothing with the context menu. callback->Cancel(); } return true; } void OnContextMenuDismissed(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame) { EXPECT_FALSE(got_context_menu_dismissed_); got_context_menu_dismissed_.yes(); if (HasContextHide()) { // Nothing to do here. The test will continue from OnQuery. return; } if (HasContextLoad()) { // Wait for the PDF plugin to load. WaitForPluginLoad(frame); return; } EndTest(); } void DestroyTest() override { if (context_handler_.get()) { context_handler_->Detach(); context_handler_ = NULL; } if (HasContextHide()) { EXPECT_TRUE(got_placeholder_hidden_); EXPECT_FALSE(got_plugin_ready_); } else { EXPECT_FALSE(got_placeholder_hidden_); if (url_ == kPdfDirectUrl) EXPECT_TRUE(got_plugin_ready_); else EXPECT_FALSE(got_plugin_ready_); } if (HasRequestContextHandler()) EXPECT_TRUE(got_on_before_plugin_empty_origin_); if (HasNoList()) { EXPECT_FALSE(got_pdf_plugin_found_); EXPECT_TRUE(got_pdf_plugin_missing_); EXPECT_FALSE(got_run_context_menu_); EXPECT_FALSE(got_context_menu_dismissed_); } else { EXPECT_TRUE(got_pdf_plugin_found_); EXPECT_FALSE(got_pdf_plugin_missing_); EXPECT_TRUE(got_run_context_menu_); EXPECT_TRUE(got_context_menu_dismissed_); } if (url_ == kPdfHtmlUrl) { // The HTML file will load the PDF twice in iframes. EXPECT_TRUE(got_on_load_end_html_); if (!HasNoList()) { EXPECT_TRUE(got_on_load_end_pdf1_); EXPECT_TRUE(got_on_load_end_pdf2_); if (HasRequestContextHandler()) { EXPECT_TRUE(got_on_before_plugin_load_pdf1_); EXPECT_TRUE(got_on_before_plugin_load_pdf2_); } } } else if (url_ == kPdfDirectUrl) { // Load the PDF file directly. EXPECT_FALSE(got_on_load_end_html_); EXPECT_TRUE(got_on_load_end_pdf1_); EXPECT_FALSE(got_on_load_end_pdf2_); if (HasRequestContextHandler()) { EXPECT_TRUE(got_on_before_plugin_load_pdf1_); EXPECT_FALSE(got_on_before_plugin_load_pdf2_); } } else { NOTREACHED(); } if (!HasRequestContextHandler() || HasNoList()) { EXPECT_FALSE(got_on_before_plugin_load_pdf1_); EXPECT_FALSE(got_on_before_plugin_load_pdf2_); } TestHandler::DestroyTest(); } const Mode mode_; const std::string url_; TrackCallback got_on_before_plugin_empty_origin_; TrackCallback got_on_before_plugin_load_pdf1_; TrackCallback got_on_before_plugin_load_pdf2_; TrackCallback got_on_load_end_html_; TrackCallback got_on_load_end_pdf1_; TrackCallback got_on_load_end_pdf2_; TrackCallback got_pdf_plugin_found_; TrackCallback got_pdf_plugin_missing_; TrackCallback got_placeholder_hidden_; TrackCallback got_plugin_ready_; TrackCallback got_run_context_menu_; TrackCallback got_context_menu_dismissed_; CefRefPtr<RequestContextHandler> context_handler_; IMPLEMENT_REFCOUNTING(PluginTestHandler); }; } // namespace #define RUN_TEST(name, type, url) \ TEST(PluginTest, name) { \ CefRefPtr<PluginTestHandler> handler = \ new PluginTestHandler(PluginTestHandler::type, url); \ handler->ExecuteTest(); \ ReleaseAndWaitForDestructor(handler); \ } RUN_TEST(GlobalDefaultPdfDirect, GLOBAL_DEFAULT, kPdfDirectUrl); RUN_TEST(GlobalDefaultPdfHtml, GLOBAL_DEFAULT, kPdfHtmlUrl); RUN_TEST(GlobalNoHandlerPdfDirect, GLOBAL_NO_HANDLER, kPdfDirectUrl); RUN_TEST(GlobalNoHandlerPdfHtml, GLOBAL_NO_HANDLER, kPdfHtmlUrl); RUN_TEST(GlobalAllowPdfDirect, GLOBAL_ALLOW, kPdfDirectUrl); RUN_TEST(GlobalAllowPdfHtml, GLOBAL_ALLOW, kPdfHtmlUrl); RUN_TEST(GlobalBlockThenLoadPdfDirect, GLOBAL_BLOCK_LOAD, kPdfDirectUrl); RUN_TEST(GlobalBlockThenLoadPdfHtml, GLOBAL_BLOCK_LOAD, kPdfHtmlUrl); RUN_TEST(GlobalBlockThenHidePdfDirect, GLOBAL_BLOCK_HIDE, kPdfDirectUrl); RUN_TEST(GlobalBlockThenHidePdfHtml, GLOBAL_BLOCK_HIDE, kPdfHtmlUrl); RUN_TEST(GlobalDisableThenHidePdfDirect, GLOBAL_DISABLE_HIDE, kPdfDirectUrl); RUN_TEST(GlobalDisableThenHidePdfHtml, GLOBAL_DISABLE_HIDE, kPdfHtmlUrl); RUN_TEST(GlobalNoListHtml, GLOBAL_NO_LIST, kPdfHtmlUrl); RUN_TEST(CustomNoHandlerPdfDirect, CUSTOM_NO_HANDLER, kPdfDirectUrl); RUN_TEST(CustomNoHandlerPdfHtml, CUSTOM_NO_HANDLER, kPdfHtmlUrl); RUN_TEST(CustomAllowPdfDirect, CUSTOM_ALLOW, kPdfDirectUrl); RUN_TEST(CustomAllowPdfHtml, CUSTOM_ALLOW, kPdfHtmlUrl); RUN_TEST(CustomBlockThenLoadPdfDirect, CUSTOM_BLOCK_LOAD, kPdfDirectUrl); RUN_TEST(CustomBlockThenLoadPdfHtml, CUSTOM_BLOCK_LOAD, kPdfHtmlUrl); RUN_TEST(CustomBlockThenHidePdfDirect, CUSTOM_BLOCK_HIDE, kPdfDirectUrl); RUN_TEST(CustomBlockThenHidePdfHtml, CUSTOM_BLOCK_HIDE, kPdfHtmlUrl); RUN_TEST(CustomDisableThenHidePdfDirect, CUSTOM_DISABLE_HIDE, kPdfDirectUrl); RUN_TEST(CustomDisableThenHidePdfHtml, CUSTOM_DISABLE_HIDE, kPdfHtmlUrl); RUN_TEST(CustomNoListHtml, CUSTOM_NO_LIST, kPdfHtmlUrl); // Entry point for creating plugin browser test objects. // Called from client_app_delegates.cc. void CreatePluginBrowserTests( client::ClientAppBrowser::DelegateSet& delegates) { delegates.insert(new PluginBrowserTest); }
32.990581
80
0.678896
[ "model" ]
4f3a034c6512d505a20bdb987de7dd8e451f2161
1,249
cpp
C++
src/caffe/layers/tanh_layer.cpp
Luoyadan/dgx-1_caffe
ca2c8a7c94d528d68f9630106a415f93be620dd4
[ "BSD-2-Clause" ]
17
2018-06-13T06:33:52.000Z
2022-02-05T18:43:14.000Z
src/caffe/layers/tanh_layer.cpp
Luoyadan/dgx-1_caffe
ca2c8a7c94d528d68f9630106a415f93be620dd4
[ "BSD-2-Clause" ]
1
2019-04-17T02:19:39.000Z
2019-04-17T02:19:39.000Z
src/caffe/layers/tanh_layer.cpp
Luoyadan/dgx-1_caffe
ca2c8a7c94d528d68f9630106a415f93be620dd4
[ "BSD-2-Clause" ]
9
2018-06-14T07:56:56.000Z
2021-04-29T08:32:31.000Z
// TanH neuron activation function layer. // Adapted from ReLU layer code written by Yangqing Jia #include <vector> #include "caffe/layers/tanh_layer.hpp" namespace caffe { template <typename Ftype, typename Btype> void TanHLayer<Ftype, Btype>::Forward_cpu(const vector<Blob*>& bottom, const vector<Blob*>& top) { const Ftype* bottom_data = bottom[0]->cpu_data<Ftype>(); Ftype* top_data = top[0]->mutable_cpu_data<Ftype>(); const int count = bottom[0]->count(); for (int i = 0; i < count; ++i) { top_data[i] = tanh(bottom_data[i]); } } template <typename Ftype, typename Btype> void TanHLayer<Ftype, Btype>::Backward_cpu(const vector<Blob*>& top, const vector<bool>& propagate_down, const vector<Blob*>& bottom) { if (propagate_down[0]) { const Btype* top_data = top[0]->cpu_data<Btype>(); const Btype* top_diff = top[0]->cpu_diff<Btype>(); Btype* bottom_diff = bottom[0]->mutable_cpu_diff<Btype>(); const int count = bottom[0]->count(); float tanhx; for (int i = 0; i < count; ++i) { tanhx = top_data[i]; bottom_diff[i] = top_diff[i] * (Btype(1.) - tanhx * tanhx); } } } #ifdef CPU_ONLY STUB_GPU(TanHLayer); #endif INSTANTIATE_CLASS_FB(TanHLayer); } // namespace caffe
27.755556
70
0.666934
[ "vector" ]
4f3a298bee0c651b4e031ff015a608869622011a
33,442
cc
C++
src/yb/client/transaction.cc
Arnav15/yugabyte-db
e4675ba8be2409af7e89634f7f68a63440eb3874
[ "Apache-2.0" ]
1
2022-01-31T20:38:23.000Z
2022-01-31T20:38:23.000Z
src/yb/client/transaction.cc
Arnav15/yugabyte-db
e4675ba8be2409af7e89634f7f68a63440eb3874
[ "Apache-2.0" ]
null
null
null
src/yb/client/transaction.cc
Arnav15/yugabyte-db
e4675ba8be2409af7e89634f7f68a63440eb3874
[ "Apache-2.0" ]
null
null
null
// // Copyright (c) YugaByte, 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 "yb/client/transaction.h" #include <unordered_set> #include "yb/client/async_rpc.h" #include "yb/client/client.h" #include "yb/client/in_flight_op.h" #include "yb/client/meta_cache.h" #include "yb/client/tablet_rpc.h" #include "yb/client/transaction_manager.h" #include "yb/client/transaction_rpc.h" #include "yb/client/yb_op.h" #include "yb/common/transaction.h" #include "yb/rpc/messenger.h" #include "yb/rpc/rpc.h" #include "yb/rpc/scheduler.h" #include "yb/util/logging.h" #include "yb/util/random_util.h" #include "yb/util/result.h" #include "yb/util/strongly_typed_bool.h" using namespace std::literals; using namespace std::placeholders; DEFINE_uint64(transaction_heartbeat_usec, 500000, "Interval of transaction heartbeat in usec."); DEFINE_bool(transaction_disable_heartbeat_in_tests, false, "Disable heartbeat during test."); DEFINE_bool(transaction_disable_proactive_cleanup_in_tests, false, "Disable cleanup of intents in abort path."); DECLARE_uint64(max_clock_skew_usec); namespace yb { namespace client { namespace { YB_STRONGLY_TYPED_BOOL(Child); YB_DEFINE_ENUM(TransactionState, (kRunning)(kAborted)(kCommitted)); } // namespace Result<ChildTransactionData> ChildTransactionData::FromPB(const ChildTransactionDataPB& data) { ChildTransactionData result; auto metadata = TransactionMetadata::FromPB(data.metadata()); RETURN_NOT_OK(metadata); result.metadata = std::move(*metadata); result.read_time = ReadHybridTime::FromReadTimePB(data); for (const auto& entry : data.local_limits()) { result.local_limits.emplace(entry.first, HybridTime(entry.second)); } return result; } YB_DEFINE_ENUM(MetadataState, (kMissing)(kMaybePresent)(kPresent)); class YBTransaction::Impl final { public: Impl(TransactionManager* manager, YBTransaction* transaction) : manager_(manager), transaction_(transaction), read_point_(manager->clock()), child_(Child::kFalse) { metadata_.transaction_id = GenerateTransactionId(); metadata_.priority = RandomUniformInt<uint64_t>(); CompleteConstruction(); VLOG_WITH_PREFIX(2) << "Started, metadata: " << metadata_; } Impl(TransactionManager* manager, YBTransaction* transaction, ChildTransactionData data) : manager_(manager), transaction_(transaction), read_point_(manager->clock()), child_(Child::kTrue), child_had_read_time_(data.read_time) { // For serializable isolation we use read intents, so could always read most recent // version of DB. // Otherwise there is possible case when we miss value change that happened after transaction // start. if (data.metadata.isolation == IsolationLevel::SNAPSHOT_ISOLATION) { read_point_.SetReadTime(std::move(data.read_time), std::move(data.local_limits)); } metadata_ = std::move(data.metadata); CompleteConstruction(); VLOG_WITH_PREFIX(2) << "Started child, metadata: " << metadata_; ready_ = true; } ~Impl() { manager_->rpcs().Abort({&heartbeat_handle_, &commit_handle_, &abort_handle_}); LOG_IF_WITH_PREFIX(DFATAL, !waiters_.empty()) << "Non empty waiters"; } YBTransactionPtr CreateSimilarTransaction() { return std::make_shared<YBTransaction>(manager_); } CHECKED_STATUS Init(IsolationLevel isolation, const ReadHybridTime& read_time) { if (read_point_.GetReadTime().read.is_valid()) { return STATUS_FORMAT(IllegalState, "Read point already specified: $0", read_point_.GetReadTime()); } if (read_time.read.is_valid()) { read_point_.SetReadTime(read_time, ConsistentReadPoint::HybridTimeMap()); } metadata_.isolation = isolation; if (read_point_.GetReadTime()) { metadata_.DEPRECATED_start_time = read_point_.GetReadTime().read; } else { metadata_.DEPRECATED_start_time = read_point_.Now(); } return Status::OK(); } void InitWithReadPoint(IsolationLevel isolation, ConsistentReadPoint&& read_point) { metadata_.isolation = isolation; read_point_ = std::move(read_point); } const IsolationLevel isolation() const { return metadata_.isolation; } // This transaction is a restarted transaction, so we set it up with data from original one. CHECKED_STATUS FillRestartedTransaction(Impl* other) { VLOG_WITH_PREFIX(1) << "Setup restart to " << other->ToString(); auto transaction = transaction_->shared_from_this(); { std::lock_guard<std::mutex> lock(mutex_); auto state = state_.load(std::memory_order_acquire); if (state != TransactionState::kRunning) { return STATUS_FORMAT( IllegalState, "Restart of completed transaction $0: $1", metadata_.transaction_id, state); } if (!read_point_.IsRestartRequired()) { return STATUS_FORMAT( IllegalState, "Restart of transaction that does not require restart: $0", metadata_.transaction_id); } other->read_point_ = std::move(read_point_); other->read_point_.Restart(); other->metadata_.isolation = metadata_.isolation; if (metadata_.isolation == IsolationLevel::SNAPSHOT_ISOLATION) { other->metadata_.DEPRECATED_start_time = other->read_point_.GetReadTime().read; } else { other->metadata_.DEPRECATED_start_time = other->read_point_.Now(); } state_.store(TransactionState::kAborted, std::memory_order_release); } DoAbort(Status::OK(), transaction); return Status::OK(); } bool Prepare(const std::unordered_set<internal::InFlightOpPtr>& ops, ForceConsistentRead force_consistent_read, Waiter waiter, TransactionMetadata* metadata, bool* may_have_metadata) { VLOG_WITH_PREFIX(2) << "Prepare"; bool has_tablets_without_metadata = false; { std::unique_lock<std::mutex> lock(mutex_); if (!ready_) { if (waiter) { waiters_.push_back(std::move(waiter)); } lock.unlock(); RequestStatusTablet(); VLOG_WITH_PREFIX(2) << "Prepare, rejected (not ready, requesting status tablet)"; return false; } bool single_tablet = true; internal::RemoteTablet* tablet = nullptr; for (const auto& op : ops) { VLOG_WITH_PREFIX(3) << "Prepare, op: " << op->ToString(); DCHECK(op->tablet != nullptr); if (single_tablet) { if (tablet == nullptr) { tablet = op->tablet.get(); } else if (tablet != op->tablet.get()) { single_tablet = false; } } auto it = tablets_.find(op->tablet->tablet_id()); if (it == tablets_.end()) { it = tablets_.emplace(op->tablet->tablet_id(), TabletState()).first; has_tablets_without_metadata = true; } else { // It is possible that after restart tablet does not know that he already stored metadata // so we should tell him, that he should check RocksDB before creating transaction state // from received metadata. // // It is important because otherwise he could lose write id. // // Also it is better to avoid doing such check each time, because it has significant // impact on performance. So we are doing this optimization. auto metadata_state = it->second.metadata_state; has_tablets_without_metadata = has_tablets_without_metadata || metadata_state != InvolvedTabletMetadataState::EXIST; if (metadata_state != InvolvedTabletMetadataState::MISSING) { if (may_have_metadata) { *may_have_metadata = true; } } } // Prepare is invoked when we are going to send request to tablet server. // So after that tablet may have metadata, and we reflect it in our local state. if (it->second.metadata_state == InvolvedTabletMetadataState::MISSING && !op->yb_op->read_only()) { it->second.metadata_state = InvolvedTabletMetadataState::MAY_EXIST; } } // For serializable isolation we never choose read time, since it always reads latest // snapshot. // For snapshot isolation, if read time was not yet picked, we have to choose it now, if there // multiple tablets that will process first request. SetReadTimeIfNeeded(!single_tablet || force_consistent_read); } VLOG_WITH_PREFIX(3) << "Prepare, has_tablets_without_metadata: " << has_tablets_without_metadata; if (metadata) { if (has_tablets_without_metadata) { *metadata = metadata_; } else { metadata->transaction_id = metadata_.transaction_id; } } return true; } void Flushed( const internal::InFlightOps& ops, const ReadHybridTime& used_read_time, const Status& status) { VLOG_WITH_PREFIX(5) << "Flushed: " << yb::ToString(ops) << ", used_read_time: " << used_read_time << ", status: " << status; if (status.ok()) { std::lock_guard<std::mutex> lock(mutex_); if (used_read_time && metadata_.isolation == IsolationLevel::SNAPSHOT_ISOLATION) { LOG_IF_WITH_PREFIX(DFATAL, read_point_.GetReadTime()) << "Read time already picked (" << read_point_.GetReadTime() << ", but server replied with used read time: " << used_read_time; read_point_.SetReadTime(used_read_time, ConsistentReadPoint::HybridTimeMap()); } TabletStates::iterator it = tablets_.end(); for (const auto& op : ops) { if (op->yb_op->wrote_data()) { const std::string& tablet_id = op->tablet->tablet_id(); // Usually all ops belong to the same tablet. So we can avoid repeating lookup. if (it == tablets_.end() || it->first != tablet_id) { auto it = tablets_.find(tablet_id); CHECK(it != tablets_.end()); it->second.metadata_state = InvolvedTabletMetadataState::EXIST; } } } } else if (status.IsTryAgain()) { SetError(status); } // We should not handle other errors, because it is just notification that batch was failed. // And they are handled during processing of that batch. } void Commit(CommitCallback callback) { auto transaction = transaction_->shared_from_this(); { std::unique_lock<std::mutex> lock(mutex_); auto status = CheckRunning(&lock); if (!status.ok()) { callback(status); return; } if (child_) { callback(STATUS(IllegalState, "Commit of child transaction is not allowed")); return; } if (IsRestartRequired()) { callback(STATUS( IllegalState, "Commit of transaction that requires restart is not allowed")); return; } state_.store(TransactionState::kCommitted, std::memory_order_release); commit_callback_ = std::move(callback); if (!ready_) { waiters_.emplace_back(std::bind(&Impl::DoCommit, this, _1, transaction)); lock.unlock(); RequestStatusTablet(); return; } } DoCommit(Status::OK(), transaction); } void Abort() { auto transaction = transaction_->shared_from_this(); { std::unique_lock<std::mutex> lock(mutex_); auto state = state_.load(std::memory_order_acquire); if (state != TransactionState::kRunning) { LOG_IF(DFATAL, state != TransactionState::kAborted) << "Abort of committed transaction"; return; } if (child_) { LOG(DFATAL) << "Abort of child transaction"; return; } state_.store(TransactionState::kAborted, std::memory_order_release); if (!ready_) { waiters_.emplace_back(std::bind(&Impl::DoAbort, this, _1, transaction)); lock.unlock(); RequestStatusTablet(); return; } } DoAbort(Status::OK(), transaction); } bool IsRestartRequired() const { return read_point_.IsRestartRequired(); } bool HasOperations() { std::lock_guard<std::mutex> lock(mutex_); return !tablets_.empty(); } std::shared_future<TransactionMetadata> TEST_GetMetadata() { std::unique_lock<std::mutex> lock(mutex_); if (metadata_future_.valid()) { return metadata_future_; } metadata_future_ = std::shared_future<TransactionMetadata>(metadata_promise_.get_future()); if (!ready_) { auto transaction = transaction_->shared_from_this(); waiters_.push_back([this, transaction](const Status& status) { // OK to crash here, because we are in test CHECK_OK(status); metadata_promise_.set_value(metadata_); }); lock.unlock(); RequestStatusTablet(); } metadata_promise_.set_value(metadata_); return metadata_future_; } void PrepareChild(ForceConsistentRead force_consistent_read, PrepareChildCallback callback) { auto transaction = transaction_->shared_from_this(); std::unique_lock<std::mutex> lock(mutex_); auto status = CheckRunning(&lock); if (!status.ok()) { callback(status); return; } if (IsRestartRequired()) { lock.unlock(); callback(STATUS(IllegalState, "Restart required")); return; } SetReadTimeIfNeeded(force_consistent_read); if (!ready_) { waiters_.emplace_back(std::bind( &Impl::DoPrepareChild, this, _1, transaction, std::move(callback), nullptr /* lock */)); lock.unlock(); RequestStatusTablet(); return; } DoPrepareChild(Status::OK(), transaction, std::move(callback), &lock); } Result<ChildTransactionResultPB> FinishChild() { std::unique_lock<std::mutex> lock(mutex_); RETURN_NOT_OK(CheckRunning(&lock)); if (!child_) { return STATUS(IllegalState, "Finish child of non child transaction"); } state_.store(TransactionState::kCommitted, std::memory_order_release); ChildTransactionResultPB result; auto& tablets = *result.mutable_tablets(); tablets.Reserve(tablets_.size()); for (const auto& tablet : tablets_) { auto& out = *tablets.Add(); out.set_tablet_id(tablet.first); tablet.second.ToPB(&out); } read_point_.FinishChildTransactionResult(HadReadTime(child_had_read_time_), &result); return result; } Status ApplyChildResult(const ChildTransactionResultPB& result) { std::unique_lock<std::mutex> lock(mutex_); RETURN_NOT_OK(CheckRunning(&lock)); if (child_) { return STATUS(IllegalState, "Apply child result of child transaction"); } for (const auto& tablet : result.tablets()) { tablets_[tablet.tablet_id()].MergeFromPB(tablet); } read_point_.ApplyChildTransactionResult(result); return Status::OK(); } const std::string& LogPrefix() { return log_prefix_; } std::string ToString() { std::lock_guard<std::mutex> lock(mutex_); return Format("{ metadata: $0 state: $1 }", metadata_, state_.load(std::memory_order_acquire)); } const TransactionId& id() const { return metadata_.transaction_id; } ConsistentReadPoint& read_point() { return read_point_; } private: void CompleteConstruction() { log_prefix_ = Format("$0: ", to_string(metadata_.transaction_id)); heartbeat_handle_ = manager_->rpcs().InvalidHandle(); commit_handle_ = manager_->rpcs().InvalidHandle(); abort_handle_ = manager_->rpcs().InvalidHandle(); } void SetReadTimeIfNeeded(bool do_it) { if (!read_point_.GetReadTime() && do_it && metadata_.isolation == IsolationLevel::SNAPSHOT_ISOLATION) { read_point_.SetCurrentReadTime(); } } CHECKED_STATUS CheckRunning(std::unique_lock<std::mutex>* lock) { if (state_.load(std::memory_order_acquire) != TransactionState::kRunning) { auto status = error_; lock->unlock(); if (status.ok()) { status = STATUS(IllegalState, "Transaction already completed"); } return status; } return Status::OK(); } void DoCommit(const Status& status, const YBTransactionPtr& transaction) { VLOG_WITH_PREFIX(1) << Format("Commit, tablets: $0, status: $1", tablets_, status); if (!status.ok()) { commit_callback_(status); return; } // tablets_.empty() means that transaction does not have writes, so just abort it. // But notify caller that commit was successful, so it is transparent for him. if (tablets_.empty()) { DoAbort(Status::OK(), transaction); commit_callback_(Status::OK()); return; } tserver::UpdateTransactionRequestPB req; req.set_tablet_id(status_tablet_->tablet_id()); req.set_propagated_hybrid_time(manager_->Now().ToUint64()); auto& state = *req.mutable_state(); state.set_transaction_id(metadata_.transaction_id.begin(), metadata_.transaction_id.size()); state.set_status(TransactionStatus::COMMITTED); for (const auto& tablet : tablets_) { state.add_tablets(tablet.first); } manager_->rpcs().RegisterAndStart( UpdateTransaction( TransactionRpcDeadline(), status_tablet_.get(), manager_->client(), &req, std::bind(&Impl::CommitDone, this, _1, _2, transaction)), &commit_handle_); } void DoAbort(const Status& status, const YBTransactionPtr& transaction) { VLOG_WITH_PREFIX(1) << Format("Abort, status: $1", status); if (!status.ok()) { // We already stopped to send heartbeats, so transaction would be aborted anyway. LOG(WARNING) << "Failed to abort transaction: " << status; return; } tserver::AbortTransactionRequestPB req; req.set_tablet_id(status_tablet_->tablet_id()); req.set_propagated_hybrid_time(manager_->Now().ToUint64()); req.set_transaction_id(metadata_.transaction_id.begin(), metadata_.transaction_id.size()); manager_->rpcs().RegisterAndStart( AbortTransaction( TransactionRpcDeadline(), status_tablet_.get(), manager_->client(), &req, std::bind(&Impl::AbortDone, this, _1, _2, transaction)), &abort_handle_); DoAbortCleanup(transaction); } void DoAbortCleanup(const YBTransactionPtr& transaction) { if (FLAGS_transaction_disable_proactive_cleanup_in_tests) { return; } VLOG_WITH_PREFIX(1) << "Cleaning up intents for " << metadata_.transaction_id; std::vector<std::string> tablet_ids; { std::unique_lock<std::mutex> lock(mutex_); tablet_ids.reserve(tablets_.size()); for (const auto& tablet : tablets_) { tablet_ids.push_back(tablet.first); } } for (const auto& tablet_id : tablet_ids) { manager_->client()->LookupTabletById( tablet_id, TransactionRpcDeadline(), std::bind(&Impl::LookupTabletForCleanupDone, this, _1, transaction), client::UseCache::kTrue); } } void LookupTabletForCleanupDone(const Result<internal::RemoteTabletPtr>& remote_tablet, const YBTransactionPtr& transaction) { VLOG_WITH_PREFIX(1) << "Lookup tablet for cleanup done: " << remote_tablet; if (!remote_tablet.ok()) { // Intents will be cleaned up later in this case. LOG(WARNING) << "Tablet lookup failed: " << remote_tablet.status(); return; } std::vector<internal::RemoteTabletServer*> remote_tablet_servers; (**remote_tablet).GetRemoteTabletServers(&remote_tablet_servers); constexpr auto kCallTimeout = 15s; auto now = manager_->Now().ToUint64(); { std::unique_lock<std::mutex> lock(mutex_); abort_requests_.reserve(abort_requests_.size() + remote_tablet_servers.size()); for (auto* server : remote_tablet_servers) { auto status = server->InitProxy(manager_->client()); if (!status.ok()) { LOG(WARNING) << "Failed to init proxy to " << server->ToString() << ": " << status; continue; } abort_requests_.emplace_back(); auto& abort_request = abort_requests_.back(); auto& request = abort_request.request; request.set_tablet_id((**remote_tablet).tablet_id()); request.set_propagated_hybrid_time(now); auto& state = *request.mutable_state(); state.set_transaction_id(metadata_.transaction_id.begin(), metadata_.transaction_id.size()); state.set_status(TransactionStatus::CLEANUP); abort_request.controller.set_timeout(kCallTimeout); server->proxy()->UpdateTransactionAsync( request, &abort_request.response, &abort_request.controller, std::bind(&Impl::ProcessResponse, this, transaction)); } } } void ProcessResponse(const YBTransactionPtr& transaction) { VLOG_WITH_PREFIX(3) << "Cleanup intents for Abort done"; } void CommitDone(const Status& status, HybridTime propagated_hybrid_time, const YBTransactionPtr& transaction) { VLOG_WITH_PREFIX(1) << "Committed: " << status; manager_->UpdateClock(propagated_hybrid_time); manager_->rpcs().Unregister(&commit_handle_); commit_callback_(status.IsAlreadyPresent() ? Status::OK() : status); } void AbortDone(const Status& status, const tserver::AbortTransactionResponsePB& response, const YBTransactionPtr& transaction) { VLOG_WITH_PREFIX(1) << "Aborted: " << status; if (response.has_propagated_hybrid_time()) { manager_->UpdateClock(HybridTime(response.propagated_hybrid_time())); } manager_->rpcs().Unregister(&abort_handle_); } void RequestStatusTablet() { bool expected = false; if (!requested_status_tablet_.compare_exchange_strong( expected, true, std::memory_order_acq_rel)) { return; } manager_->PickStatusTablet( std::bind(&Impl::StatusTabletPicked, this, _1, transaction_->shared_from_this())); } void StatusTabletPicked(const Result<std::string>& tablet, const YBTransactionPtr& transaction) { VLOG_WITH_PREFIX(2) << "Picked status tablet: " << tablet; if (!tablet.ok()) { NotifyWaiters(tablet.status()); return; } manager_->client()->LookupTabletById( *tablet, TransactionRpcDeadline(), std::bind(&Impl::LookupTabletDone, this, _1, transaction), client::UseCache::kTrue); } void LookupTabletDone(const Result<client::internal::RemoteTabletPtr>& result, const YBTransactionPtr& transaction) { VLOG_WITH_PREFIX(1) << "Lookup tablet done: " << yb::ToString(result); if (!result.ok()) { NotifyWaiters(result.status()); return; } { std::lock_guard<std::mutex> lock(mutex_); status_tablet_ = std::move(*result); metadata_.status_tablet = status_tablet_->tablet_id(); } SendHeartbeat(TransactionStatus::CREATED, metadata_.transaction_id, transaction_->shared_from_this()); } void NotifyWaiters(const Status& status) { std::vector<Waiter> waiters; { std::lock_guard<std::mutex> lock(mutex_); SetError(status, &lock); waiters_.swap(waiters); } for (const auto& waiter : waiters) { waiter(status); } } void SendHeartbeat(TransactionStatus status, const TransactionId& id, std::weak_ptr<YBTransaction> weak_transaction) { auto transaction = weak_transaction.lock(); if (!transaction || state_.load(std::memory_order_acquire) != TransactionState::kRunning) { VLOG(1) << id << " Send heartbeat cancelled: " << yb::ToString(transaction); return; } if (status != TransactionStatus::CREATED && GetAtomicFlag(&FLAGS_transaction_disable_heartbeat_in_tests)) { HeartbeatDone(Status::OK(), HybridTime::kInvalid, status, transaction); return; } tserver::UpdateTransactionRequestPB req; req.set_tablet_id(status_tablet_->tablet_id()); req.set_propagated_hybrid_time(manager_->Now().ToUint64()); auto& state = *req.mutable_state(); state.set_transaction_id(metadata_.transaction_id.begin(), metadata_.transaction_id.size()); state.set_status(status); manager_->rpcs().RegisterAndStart( UpdateTransaction( TransactionRpcDeadline(), status_tablet_.get(), manager_->client(), &req, std::bind(&Impl::HeartbeatDone, this, _1, _2, status, transaction)), &heartbeat_handle_); } void HeartbeatDone(const Status& status, HybridTime propagated_hybrid_time, TransactionStatus transaction_status, const YBTransactionPtr& transaction) { manager_->UpdateClock(propagated_hybrid_time); manager_->rpcs().Unregister(&heartbeat_handle_); if (status.ok()) { if (transaction_status == TransactionStatus::CREATED) { std::vector<Waiter> waiters; { std::lock_guard<std::mutex> lock(mutex_); DCHECK(!ready_); ready_ = true; waiters_.swap(waiters); } VLOG_WITH_PREFIX(1) << "Created, notifying waiters: " << waiters.size(); for (const auto& waiter : waiters) { waiter(Status::OK()); } } std::weak_ptr<YBTransaction> weak_transaction(transaction); manager_->client()->messenger()->scheduler().Schedule( [this, weak_transaction](const Status&) { SendHeartbeat(TransactionStatus::PENDING, metadata_.transaction_id, weak_transaction); }, std::chrono::microseconds(FLAGS_transaction_heartbeat_usec)); } else { LOG_WITH_PREFIX(WARNING) << "Send heartbeat failed: " << status; if (status.IsExpired()) { SetError(status); // If state is aborted, then we already requested this cleanup. // If state is committed, then we should not cleanup. if (state_.load(std::memory_order_acquire) == TransactionState::kRunning) { DoAbortCleanup(transaction); } return; } // Other errors could have different causes, but we should just retry sending heartbeat // in this case. SendHeartbeat(transaction_status, metadata_.transaction_id, transaction); } } void SetError(const Status& status, std::lock_guard<std::mutex>* lock = nullptr) { VLOG_WITH_PREFIX(1) << "Failed: " << status; if (!lock) { std::lock_guard<std::mutex> new_lock(mutex_); SetError(status, &new_lock); return; } if (error_.ok()) { error_ = status; state_.store(TransactionState::kAborted, std::memory_order_release); } } void DoPrepareChild(const Status& status, const YBTransactionPtr& transaction, PrepareChildCallback callback, std::unique_lock<std::mutex>* parent_lock) { if (!status.ok()) { callback(status); return; } std::unique_lock<std::mutex> lock(mutex_, std::defer_lock); if (!parent_lock) { lock.lock(); } ChildTransactionDataPB data; metadata_.ToPB(data.mutable_metadata()); read_point_.PrepareChildTransactionData(&data); callback(data); } // Manager is created once per service. TransactionManager* const manager_; // Transaction related to this impl. YBTransaction* const transaction_; TransactionMetadata metadata_; ConsistentReadPoint read_point_; std::string log_prefix_; std::atomic<bool> requested_status_tablet_{false}; internal::RemoteTabletPtr status_tablet_; std::atomic<TransactionState> state_{TransactionState::kRunning}; // Transaction is successfully initialized and ready to process intents. const bool child_; bool child_had_read_time_ = false; bool ready_ = false; CommitCallback commit_callback_; Status error_; rpc::Rpcs::Handle heartbeat_handle_; rpc::Rpcs::Handle commit_handle_; rpc::Rpcs::Handle abort_handle_; // RPC data for abort requests. struct AbortRequest { tserver::UpdateTransactionRequestPB request; tserver::UpdateTransactionResponsePB response; rpc::RpcController controller; }; boost::container::stable_vector<AbortRequest> abort_requests_; struct TabletState { InvolvedTabletMetadataState metadata_state = InvolvedTabletMetadataState::MISSING; void ToPB(TransactionInvolvedTabletPB* out) const { out->set_metadata_state(metadata_state); } void MergeFromPB(const TransactionInvolvedTabletPB& source) { switch (source.metadata_state()) { case InvolvedTabletMetadataState::MISSING: break; case InvolvedTabletMetadataState::EXIST: metadata_state = InvolvedTabletMetadataState::EXIST; break; case InvolvedTabletMetadataState::MAY_EXIST: if (metadata_state == InvolvedTabletMetadataState::MISSING) { metadata_state = InvolvedTabletMetadataState::MAY_EXIST; } break; } } std::string ToString() const { return Format("{ metadata_state $0 }", InvolvedTabletMetadataState_Name(metadata_state)); } }; typedef std::unordered_map<std::string, TabletState> TabletStates; std::mutex mutex_; TabletStates tablets_; std::vector<Waiter> waiters_; std::promise<TransactionMetadata> metadata_promise_; std::shared_future<TransactionMetadata> metadata_future_; }; YBTransaction::YBTransaction(TransactionManager* manager) : impl_(new Impl(manager, this)) { } YBTransaction::YBTransaction(TransactionManager* manager, ChildTransactionData data) : impl_(new Impl(manager, this, std::move(data))) { } YBTransaction::~YBTransaction() { } Status YBTransaction::Init(IsolationLevel isolation, const ReadHybridTime& read_time) { return impl_->Init(isolation, read_time); } void YBTransaction::InitWithReadPoint( IsolationLevel isolation, ConsistentReadPoint&& read_point) { return impl_->InitWithReadPoint(isolation, std::move(read_point)); } bool YBTransaction::Prepare(const std::unordered_set<internal::InFlightOpPtr>& ops, ForceConsistentRead force_consistent_read, Waiter waiter, TransactionMetadata* metadata, bool* may_have_metadata) { return impl_->Prepare( ops, force_consistent_read, std::move(waiter), metadata, may_have_metadata); } void YBTransaction::Flushed( const internal::InFlightOps& ops, const ReadHybridTime& used_read_time, const Status& status) { impl_->Flushed(ops, used_read_time, status); } void YBTransaction::Commit(CommitCallback callback) { impl_->Commit(std::move(callback)); } const TransactionId& YBTransaction::id() const { return impl_->id(); } const IsolationLevel YBTransaction::isolation() const { return impl_->isolation(); } const ConsistentReadPoint& YBTransaction::read_point() const { return impl_->read_point(); } ConsistentReadPoint& YBTransaction::read_point() { return impl_->read_point(); } std::future<Status> YBTransaction::CommitFuture() { return MakeFuture<Status>([this](auto callback) { impl_->Commit(std::move(callback)); }); } void YBTransaction::Abort() { impl_->Abort(); } bool YBTransaction::IsRestartRequired() const { return impl_->IsRestartRequired(); } bool YBTransaction::HasOperations() const { return impl_->HasOperations(); } Result<YBTransactionPtr> YBTransaction::CreateRestartedTransaction() { auto result = impl_->CreateSimilarTransaction(); RETURN_NOT_OK(impl_->FillRestartedTransaction(result->impl_.get())); return result; } Status YBTransaction::FillRestartedTransaction(const YBTransactionPtr& dest) { return impl_->FillRestartedTransaction(dest->impl_.get()); } void YBTransaction::PrepareChild( ForceConsistentRead force_consistent_read, PrepareChildCallback callback) { return impl_->PrepareChild(force_consistent_read, std::move(callback)); } std::future<Result<ChildTransactionDataPB>> YBTransaction::PrepareChildFuture( ForceConsistentRead force_consistent_read) { return MakeFuture<Result<ChildTransactionDataPB>>([this, force_consistent_read](auto callback) { impl_->PrepareChild(force_consistent_read, std::move(callback)); }); } Result<ChildTransactionResultPB> YBTransaction::FinishChild() { return impl_->FinishChild(); } std::shared_future<TransactionMetadata> YBTransaction::TEST_GetMetadata() const { return impl_->TEST_GetMetadata(); } Status YBTransaction::ApplyChildResult(const ChildTransactionResultPB& result) { return impl_->ApplyChildResult(result); } std::string YBTransaction::ToString() const { return impl_->ToString(); } } // namespace client } // namespace yb
34.36999
100
0.668441
[ "vector" ]
4f3b1f3b3dd32e9572cc967555388a3722ae58f3
8,743
cpp
C++
src/plugins/graphcut/graphcut.cpp
circlingthesun/cloudclean
4b9496bc3b52143c35f0ad83ee68bbc5e8aa32d5
[ "MIT" ]
2
2018-10-18T16:10:21.000Z
2020-05-28T01:52:24.000Z
src/plugins/graphcut/graphcut.cpp
circlingthesun/cloudclean
4b9496bc3b52143c35f0ad83ee68bbc5e8aa32d5
[ "MIT" ]
null
null
null
src/plugins/graphcut/graphcut.cpp
circlingthesun/cloudclean
4b9496bc3b52143c35f0ad83ee68bbc5e8aa32d5
[ "MIT" ]
4
2017-12-13T07:39:18.000Z
2021-05-29T13:13:48.000Z
#include "plugins/graphcut/graphcut.h" #include <QDebug> #include <QEvent> #include <QKeyEvent> #include <QAction> #include <QGLShaderProgram> #include <QGLBuffer> #include <QTabWidget> #include <QApplication> #include <QToolBar> #include <QVBoxLayout> #include <QDoubleSpinBox> #include <QLabel> #include <QSpacerItem> #include <QStackedWidget> #include <QSlider> #include <QDockWidget> #include <QMessageBox> #include <QDoubleSpinBox> #include <QSpinBox> #include <QProgressDialog> #include <boost/serialization/shared_ptr.hpp> #include "model/layerlist.h" #include "model/cloudlist.h" #include "gui/glwidget.h" #include "gui/flatview.h" #include "gui/mainwindow.h" #include "utilities/pointpicker.h" #include "commands/select.h" #include "pluginsystem/core.h" #include "plugins/graphcut/mincut.h" QString GraphCut::getName(){ return "graph_cut"; } GraphCut::~GraphCut(){ qDebug() << "Destroyed graph cut"; } void GraphCut::initialize(Core *core){ core_= core; cl_ = core_->cl_; ll_ = core_->ll_; glwidget_ = core_->mw_->glwidget_; flatview_ = core_->mw_->flatview_; mw_ = core_->mw_; enable_ = new QAction(QIcon(":/images/graph_cut.png"), "Graph cut tool", 0); enable_->setCheckable(true); enable_->setChecked(false); is_enabled_ = false; radius_ = 0.5f; connect(enable_, SIGNAL(triggered()), this, SLOT(enable())); connect(this, SIGNAL(enabling()), core_, SIGNAL(endEdit())); mw_->addMenu(enable_, "Edit"); mw_->toolbar_->addAction(enable_); settings_ = new QWidget(); QGridLayout * layout = new QGridLayout(settings_); settings_->setLayout(layout); mw_->tooloptions_->addWidget(settings_); QSpinBox * kconnect = new QSpinBox(settings_); QDoubleSpinBox * sigma = new QDoubleSpinBox(settings_); QDoubleSpinBox * source_weight = new QDoubleSpinBox(settings_); QDoubleSpinBox * radius = new QDoubleSpinBox(settings_); k_connect_ = 14; sigma_ = 0.25; source_weight_ = 0.80; radius_ = 3; kconnect->setValue(k_connect_); sigma->setValue(sigma_); source_weight->setValue(source_weight_); radius->setValue(radius_); QLabel * label_kcon = new QLabel("K connectivity", settings_); QLabel * label_sigma = new QLabel("Sigma (Density)", settings_); QLabel * label_source_w = new QLabel("Source weight", settings_); QLabel * label_radius = new QLabel("Radius (meters)", settings_); layout->addWidget(label_kcon); layout->addWidget(kconnect); layout->addWidget(label_sigma); layout->addWidget(sigma); layout->addWidget(label_source_w); layout->addWidget(source_weight); layout->addWidget(label_radius); layout->addWidget(radius); connect(kconnect, (void (QSpinBox:: *)(int)) &QSpinBox::valueChanged, [this] (int val) { k_connect_ = val; }); connect(sigma, (void (QDoubleSpinBox:: *)(double)) &QDoubleSpinBox::valueChanged, [this] (double val) { sigma_ = val; }); connect(source_weight, (void (QDoubleSpinBox:: *)(double)) &QDoubleSpinBox::valueChanged, [this] (double val) { radius_ = val; }); connect(radius, (void (QDoubleSpinBox:: *)(double)) &QDoubleSpinBox::valueChanged, [this] (double val) { radius_ = val; }); } void GraphCut::cleanup(){ disable(); disconnect(this, SIGNAL(enabling()), core_, SIGNAL(endEdit())); disconnect(enable_, SIGNAL(triggered()), this, SLOT(enable())); disconnect(); mw_->toolbar_->removeAction(enable_); mw_->removeMenu(enable_, "Edit"); mw_->tooloptions_->removeWidget(settings_); delete settings_; delete enable_; } void GraphCut::completeSegment(Select * select) { if(select != nullptr) { core_->us_->beginMacro("Min cut"); core_->us_->push(select); core_->us_->endMacro(); core_->cl_->updated(); core_->mw_->stopBgAction("Graph cut completed."); } else { core_->mw_->stopBgAction("Too few points selected for graph cut."); } core_->mw_->setEnabled(true); } void GraphCut::segment(int idx){ MinCut mc; pcl::PointCloud<pcl::PointXYZI>::Ptr ptr(cl_->active_.get(), boost::serialization::null_deleter()); mc.setInputCloud(ptr); pcl::IndicesPtr source_indices(new std::vector<int>); for(uint idx2 = 0; idx2 < cl_->active_->flags_.size(); idx2++){ PointFlags & flag = cl_->active_->flags_[idx2]; if((uint8_t)flag && (uint8_t)PointFlags::selected) source_indices->push_back(idx2); } if(source_indices->size() < 10) { qDebug() << "Less than 10 source points. Aborting"; qRegisterMetaType<Select *>("Select *"); QMetaObject::invokeMethod(this, "completeSegment", Qt::QueuedConnection, Q_ARG( Select *, nullptr)); return; } mc.setIndices(source_indices); pcl::PointCloud<pcl::PointXYZI>::Ptr foreground_points(new pcl::PointCloud<pcl::PointXYZI> ()); foreground_points->points.push_back(cl_->active_->points[idx]); // What? There can be more than one? mc.setForegroundPoints (foreground_points); mc.setRadius (radius_); mc.setSigma (sigma_); // This is density? mc.setNumberOfNeighbours (k_connect_); mc.setSourceWeight (source_weight_); std::vector <pcl::PointIndices> clusters; mc.extract (clusters); auto select = boost::make_shared<std::vector<int>>(clusters[1].indices.size()); auto deselect = boost::make_shared<std::vector<int>>(clusters[0].indices.size()); std::copy(clusters[0].indices.begin(), clusters[0].indices.end(), deselect->begin()); std::copy(clusters[1].indices.begin(), clusters[1].indices.end(), select->begin()); Select * selectcmd = new Select(cl_->active_, select); Select * deselectcmd = new Select(cl_->active_, select, true); qRegisterMetaType<Select *>("Select *"); QMetaObject::invokeMethod(this, "completeSegment", Qt::QueuedConnection, Q_ARG( Select *, selectcmd)); QMetaObject::invokeMethod(this, "completeSegment", Qt::QueuedConnection, Q_ARG( Select *, deselectcmd)); } bool GraphCut::mouseClickEvent(QMouseEvent * event){ return true; } bool GraphCut::mousePressEvent(QMouseEvent * event) { if(event->buttons() != Qt::LeftButton) return false; if(cl_->clouds_.size() == 0) return false; last_mouse_pos_ << event->x(), event->y(); mouse_down_pos_ = last_mouse_pos_; return true; } bool GraphCut::mouseReleaseEvent(QMouseEvent * event){ last_mouse_pos_ << event->x(), event->y(); float dist = (last_mouse_pos_ - mouse_down_pos_).norm(); if(dist < 2){ //return mouseClickEvent(event); } int idx = pick(event->x(), event->y(), glwidget_->width(), glwidget_->height(), 1e-04, glwidget_->camera_.projectionMatrix(), glwidget_->camera_.modelviewMatrix(), cl_->active_); if(idx == -1) return true; core_->mw_->setEnabled(false); core_->mw_->startBgAction("Graph cut in progress..."); std::thread(&GraphCut::segment, this, idx).detach(); return true; } void GraphCut::enable() { if(is_enabled_){ disable(); return; } QTabWidget * tabs = qobject_cast<QTabWidget *>(glwidget_->parent()->parent()); tabs->setCurrentWidget(glwidget_); enable_->setChecked(true); mw_->options_dock_->show(); mw_->tooloptions_->setCurrentWidget(settings_); emit enabling(); glwidget_->installEventFilter(this); connect(core_, SIGNAL(endEdit()), this, SLOT(disable())); is_enabled_ = true; // Let the user know what to do QMessageBox::information(nullptr, tr("Make a selection"), tr("Select the center of an object..."), QMessageBox::Ok, QMessageBox::Ok); } void GraphCut::disable() { enable_->setChecked(false); disconnect(core_, SIGNAL(endEdit()), this, SLOT(disable())); glwidget_->removeEventFilter(this); is_enabled_ = false; } bool GraphCut::eventFilter(QObject *object, QEvent *event){ // Bypass plugin via shift if(QApplication::keyboardModifiers() == Qt::SHIFT) return false; switch(event->type()){ case QEvent::MouseButtonPress: return mousePressEvent(static_cast<QMouseEvent*>(event)); case QEvent::MouseButtonRelease: return mouseReleaseEvent(static_cast<QMouseEvent*>(event)); case QEvent::KeyPress: if(static_cast<QKeyEvent*>(event)->key() == Qt::Key_Control) return true; default: return false; } } Q_PLUGIN_METADATA(IID "za.co.circlingthesun.cloudclean.iplugin")
30.252595
115
0.653437
[ "object", "vector", "model" ]
4f3cb011bac31681a3407ec41c24d0a614dfb7ed
25,655
cpp
C++
src/hasp_gui.cpp
yuzi40277738/openHASP
e5332a3aad19a399194bcf31add3bcacf3e2c130
[ "MIT" ]
1
2021-11-26T08:55:31.000Z
2021-11-26T08:55:31.000Z
src/hasp_gui.cpp
yuzi40277738/openHASP
e5332a3aad19a399194bcf31add3bcacf3e2c130
[ "MIT" ]
null
null
null
src/hasp_gui.cpp
yuzi40277738/openHASP
e5332a3aad19a399194bcf31add3bcacf3e2c130
[ "MIT" ]
null
null
null
/* MIT License - Copyright (c) 2019-2022 Francis Van Roie For full license information read the LICENSE file in the project folder */ #include "hasplib.h" #include "lv_drv_conf.h" // Filesystem Driver #include "lv_misc/lv_fs.h" #include "lv_fs_if.h" // Device Drivers #include "dev/device.h" #include "drv/tft/tft_driver.h" #include "drv/touch/touch_driver.h" //#include "drv/hasp_drv_display.h" //#include "drv/old/hasp_drv_touch.h" //#include "drv/old/hasp_drv_tft_espi.h" #include "hasp_debug.h" #include "hasp_config.h" #include "hasp_gui.h" #include "hasp_oobe.h" //#include "tpcal.h" //#include "Ticker.h" #include "lv_freetype.h" #if HASP_USE_PNGDECODE > 0 #include "lv_png.h" #endif #if HASP_USE_BMPDECODE > 0 #include "lv_bmp.h" #endif #if HASP_USE_GIFDECODE > 0 #include "lv_gif.h" #endif #if HASP_USE_JPGDECODE > 0 #include "lv_sjpg.h" #endif #define BACKLIGHT_CHANNEL 0 // pwm channel 0-15 #if HASP_USE_SPIFFS > 0 || HASP_USE_LITTLEFS > 0 File pFileOut; #endif #define LVGL_TICK_PERIOD 20 #ifndef TFT_BCKL #define TFT_BCKL -1 // No Backlight Control #endif #ifndef TFT_ROTATION #define TFT_ROTATION 0 #endif #ifndef INVERT_COLORS #define INVERT_COLORS 0 #endif // HASP_ATTRIBUTE_FAST_MEM static void lv_tick_handler(void); gui_conf_t gui_settings = {.show_pointer = false, .backlight_pin = TFT_BCKL, .rotation = TFT_ROTATION, .invert_display = INVERT_COLORS, .cal_data = {0, 65535, 0, 65535, 0}}; lv_obj_t* cursor; uint16_t tft_width = TFT_WIDTH; uint16_t tft_height = TFT_HEIGHT; static lv_disp_buf_t disp_buf; // #if defined(ARDUINO_ARCH_ESP32) || defined(ARDUINO_ARCH_ESP8266) // static Ticker tick; /* timer for interrupt handler */ // #else // static Ticker tick(lv_tick_handler, LVGL_TICK_PERIOD); // guiTickPeriod); // #endif /* **************************** GUI TICKER ************************************** */ /* Interrupt driven periodic handler */ // static void ICACHE_RAM_ATTR lv_tick_handler(void) // { // lv_tick_inc(LVGL_TICK_PERIOD); // } static inline void gui_init_lvgl() { LOG_VERBOSE(TAG_LVGL, F("Version : %u.%u.%u %s"), LVGL_VERSION_MAJOR, LVGL_VERSION_MINOR, LVGL_VERSION_PATCH, PSTR(LVGL_VERSION_INFO)); lv_init(); #if LV_USE_LOG != 0 // Register logger to capture lvgl_init output lv_log_register_print_cb(debugLvglLogEvent); #endif /* Create the Virtual Device Buffers */ // #if defined(ARDUINO_ARCH_ESP32) // // #ifdef USE_DMA_TO_TFT // // DMA: len must be less than 32767 // const size_t guiVDBsize = 15 * 1024u; // 30 KBytes // guiVdbBuffer1 = (lv_color_t*)heap_caps_calloc(guiVDBsize, sizeof(lv_color_t), MALLOC_CAP_DMA); // // guiVdbBuffer2 = (lv_color_t *)heap_caps_malloc(sizeof(lv_color_t) * guiVDBsize, MALLOC_CAP_DMA); // // lv_disp_buf_init(&disp_buf, guiVdbBuffer1, guiVdbBuffer2, guiVDBsize); // #else // const size_t guiVDBsize = 8 * 1024u; // 32 KBytes // if(0 && psramFound()) { // guiVdbBuffer1 = (lv_color_t*)ps_calloc(guiVDBsize, sizeof(lv_color_t)); // too slow for VDB // } else { // guiVdbBuffer1 = (lv_color_t*)calloc(guiVDBsize, sizeof(lv_color_t)); // } // #endif // // static lv_color_t * guiVdbBuffer2 = (lv_color_t *)malloc(sizeof(lv_color_t) * guiVDBsize); // // lv_disp_buf_init(&disp_buf, guiVdbBuffer1, guiVdbBuffer2, guiVDBsize); // #elif defined(ARDUINO_ARCH_ESP8266) // /* allocate on heap */ // // static lv_color_t guiVdbBuffer1[2 * 512u]; // 4 KBytes // // size_t guiVDBsize = sizeof(guiVdbBuffer1) / sizeof(guiVdbBuffer1[0]); // // lv_disp_buf_init(&disp_buf, guiVdbBuffer1, NULL, guiVDBsize); // const size_t guiVDBsize = 2 * 512u; // 4 KBytes * 2 // guiVdbBuffer1 = (lv_color_t*)malloc(sizeof(lv_color_t) * guiVDBsize); // #elif defined(WINDOWS) || defined(POSIX) // const size_t guiVDBsize = LV_HOR_RES_MAX * 10; // // static lv_color_t guiVdbBuffer1[guiVDBsize]; /*Declare a buffer for 10 lines*/ // guiVdbBuffer1 = (lv_color_t*)calloc(guiVDBsize, sizeof(lv_color_t)); // #else // static lv_color_t guiVdbBuffer1[16 * 512u]; // 16 KBytes // // static lv_color_t guiVdbBuffer2[16 * 512u]; // 16 KBytes // size_t guiVDBsize = sizeof(guiVdbBuffer1) / sizeof(guiVdbBuffer1[0]); // // lv_disp_buf_init(&disp_buf, guiVdbBuffer1, guiVdbBuffer2, guiVDBsize); // #endif /* Dynamic VDB allocation */ const size_t guiVDBsize = LV_VDB_SIZE / 2; static lv_color_t* guiVdbBuffer1 = (lv_color_t*)malloc(sizeof(lv_color_t) * guiVDBsize); /* Static VDB allocation */ // static lv_color_t guiVdbBuffer1[LV_VDB_SIZE * 512u]; // const size_t guiVDBsize = sizeof(guiVdbBuffer1) / sizeof(lv_color_t); /* Initialize VDB */ if(guiVdbBuffer1 && guiVDBsize > 0) { lv_disp_buf_init(&disp_buf, guiVdbBuffer1, NULL, guiVDBsize); } else { LOG_FATAL(TAG_GUI, F(D_ERROR_OUT_OF_MEMORY)); } #ifdef LV_MEM_SIZE LOG_VERBOSE(TAG_LVGL, F("MEM size : %d"), LV_MEM_SIZE); #endif LOG_VERBOSE(TAG_LVGL, F("VFB size : %d"), (size_t)sizeof(lv_color_t) * guiVDBsize); } void gui_hide_pointer(bool hidden) { if(cursor) lv_obj_set_hidden(cursor, hidden || !gui_settings.show_pointer); } IRAM_ATTR void gui_flush_cb(lv_disp_drv_t* disp, const lv_area_t* area, lv_color_t* color_p) { haspTft.flush_pixels(disp, area, color_p); } IRAM_ATTR bool gui_touch_read(lv_indev_drv_t* indev_driver, lv_indev_data_t* data) { return haspTouch.read(indev_driver, data); } void guiCalibrate(void) { #if TOUCH_DRIVER == 0x2046 && defined(USER_SETUP_LOADED) #ifdef TOUCH_CS haspTouch.calibrate(gui_settings.cal_data); #endif for(int i = 0; i < 5; i++) { Serial.print(gui_settings.cal_data[i]); if(i < 4) Serial.print(", "); } delay(500); lv_obj_invalidate(lv_disp_get_layer_sys(NULL)); #endif } // fast init void gui_start_tft(void) { /* Setup Backlight Control Pin */ haspDevice.set_backlight_pin(gui_settings.backlight_pin); haspTft.init(tft_width, tft_height); haspTft.set_rotation(gui_settings.rotation); haspTft.set_invert(gui_settings.invert_display); } static inline void gui_init_tft(void) { // Initialize TFT LOG_TRACE(TAG_TFT, F(D_SERVICE_STARTING)); gui_start_tft(); haspTft.show_info(); #ifdef USE_DMA_TO_TFT LOG_VERBOSE(TAG_TFT, F("DMA : " D_SETTING_ENABLED)); #else LOG_VERBOSE(TAG_TFT, F("DMA : " D_SETTING_DISABLED)); #endif LOG_INFO(TAG_TFT, F(D_SERVICE_STARTED)); } // initialize the image decoders static inline void gui_init_images() { #if HASP_USE_PNGDECODE > 0 lv_png_init(); // Initialize PNG decoder #endif #if HASP_USE_BMPDECODE > 0 lv_bmp_init(); // Initialize BMP decoder #endif #if HASP_USE_GIFDECODE > 0 lv_gif_init(); // Initialize GIF decoder #endif #if HASP_USE_JPGDECODE > 0 lv_split_jpeg_init(); // Initialize JPG decoder #endif #if defined(ARDUINO_ARCH_ESP32) if(hasp_use_psram()) lv_img_cache_set_size(LV_IMG_CACHE_DEF_SIZE_PSRAM); #endif } // initialize the FreeType renderer static inline void gui_init_freetype() { // #ifdef 1 || USE_LVGL_FREETYPE #if defined(ARDUINO_ARCH_ESP32) if(lv_freetype_init(USE_LVGL_FREETYPE_MAX_FACES, USE_LVGL_FREETYPE_MAX_SIZES, hasp_use_psram() ? USE_LVGL_FREETYPE_MAX_BYTES_PSRAM : USE_LVGL_FREETYPE_MAX_BYTES)) { LOG_VERBOSE(TAG_FONT, F("FreeType v%d.%d.%d " D_SERVICE_STARTED), FREETYPE_MAJOR, FREETYPE_MINOR, FREETYPE_PATCH); } else { LOG_ERROR(TAG_FONT, F("FreeType " D_SERVICE_START_FAILED)); } #elif defined(WINDOWS) || defined(POSIX) #else #endif } static inline void gui_init_filesystems() { #if LV_USE_FS_IF != 0 //_lv_fs_init(); // lvgl File System -- not needed, it done in lv_init() when LV_USE_FILESYSTEM is set LOG_VERBOSE(TAG_LVGL, F("Filesystem : " D_SETTING_ENABLED)); lv_fs_if_init(); // auxilary file system drivers // filesystem_list_path("L:/"); lv_fs_file_t f; lv_fs_res_t res; res = lv_fs_open(&f, "L:/config.json", LV_FS_MODE_RD); if(res == LV_FS_RES_OK) { LOG_VERBOSE(TAG_HASP, F("TEST Opening config.json OK")); lv_fs_close(&f); } else { LOG_ERROR(TAG_HASP, F("TEST Opening config.json from FS failed %d"), res); } #else LOG_VERBOSE(TAG_LVGL, F("Filesystem : " D_SETTING_DISABLED)); #endif } void guiSetup() { // Initialize hardware drivers gui_init_tft(); // Initialize LVGL LOG_TRACE(TAG_LVGL, F(D_SERVICE_STARTING)); gui_init_lvgl(); gui_init_images(); gui_init_filesystems(); gui_init_freetype(); font_setup(); /* Initialize the LVGL display driver with correct orientation */ #if(TOUCH_DRIVER == 0x2046) || defined(LGFX_USE_V1) // Use native display driver to rotate display and touch static lv_disp_drv_t disp_drv; lv_disp_drv_init(&disp_drv); disp_drv.buffer = &disp_buf; disp_drv.flush_cb = gui_flush_cb; if(gui_settings.rotation % 2) { disp_drv.hor_res = tft_height; disp_drv.ver_res = tft_width; } else { disp_drv.hor_res = tft_width; disp_drv.ver_res = tft_height; } lv_disp_t* display = lv_disp_drv_register(&disp_drv); lv_disp_set_rotation(display, LV_DISP_ROT_NONE); /* #elif defined(LANBONL8) // Screen is 0 deg. rotated static lv_disp_drv_t disp_drv; lv_disp_drv_init(&disp_drv); disp_drv.buffer = &disp_buf; disp_drv.flush_cb = gui_flush_cb; disp_drv.hor_res = tft_width; disp_drv.ver_res = tft_height; lv_disp_rot_t rotation[] = {LV_DISP_ROT_NONE, LV_DISP_ROT_270, LV_DISP_ROT_180, LV_DISP_ROT_90}; lv_disp_t* display = lv_disp_drv_register(&disp_drv); lv_disp_set_rotation(display, rotation[(4 + gui_settings.rotation - TFT_ROTATION) % 4]); */ #elif defined(M5STACK) // Screen is 90 deg. rotated static lv_disp_drv_t disp_drv; lv_disp_drv_init(&disp_drv); disp_drv.buffer = &disp_buf; disp_drv.flush_cb = gui_flush_cb; disp_drv.hor_res = tft_height; disp_drv.ver_res = tft_width; lv_disp_rot_t rotation[] = {LV_DISP_ROT_NONE, LV_DISP_ROT_270, LV_DISP_ROT_180, LV_DISP_ROT_90}; lv_disp_t* display = lv_disp_drv_register(&disp_drv); lv_disp_set_rotation(display, rotation[(4 + gui_settings.rotation - TFT_ROTATION) % 4]); #else // Use lvgl transformations static lv_disp_drv_t disp_drv; lv_disp_drv_init(&disp_drv); disp_drv.buffer = &disp_buf; disp_drv.flush_cb = gui_flush_cb; disp_drv.hor_res = tft_width; disp_drv.ver_res = tft_height; lv_disp_rot_t rotation[] = {LV_DISP_ROT_NONE, LV_DISP_ROT_270, LV_DISP_ROT_180, LV_DISP_ROT_90}; lv_disp_t* display = lv_disp_drv_register(&disp_drv); lv_disp_set_rotation(display, rotation[(4 + gui_settings.rotation - TFT_ROTATION) % 4]); #endif /* Initialize the touch pad */ static lv_indev_drv_t indev_drv; lv_indev_drv_init(&indev_drv); indev_drv.type = LV_INDEV_TYPE_POINTER; #if defined(WINDOWS) || defined(POSIX) indev_drv.read_cb = mouse_read; #else indev_drv.read_cb = gui_touch_read; #endif lv_indev_t* mouse_indev = lv_indev_drv_register(&indev_drv); mouse_indev->driver.type = LV_INDEV_TYPE_POINTER; /*Set a cursor for the mouse*/ LOG_TRACE(TAG_GUI, F("Initialize Cursor")); lv_obj_t* mouse_layer = lv_disp_get_layer_sys(NULL); // default display #if defined(ARDUINO_ARCH_ESP32) LV_IMG_DECLARE(mouse_cursor_icon); /*Declare the image file.*/ cursor = lv_img_create(mouse_layer, NULL); /*Create an image object for the cursor */ lv_img_set_src(cursor, &mouse_cursor_icon); /*Set the image source*/ #else cursor = lv_obj_create(mouse_layer, NULL); // show cursor object on every page lv_obj_set_size(cursor, 9, 9); lv_obj_set_style_local_radius(cursor, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, LV_RADIUS_CIRCLE); lv_obj_set_style_local_bg_color(cursor, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_RED); lv_obj_set_style_local_bg_opa(cursor, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, LV_OPA_COVER); #endif gui_hide_pointer(false); lv_indev_set_cursor(mouse_indev, cursor); /*Connect the image object to the driver*/ #if !(defined(WINDOWS) || defined(POSIX)) // drv_touch_init(gui_settings.rotation); // Touch driver haspTouch.init(tft_width, tft_height); haspTouch.set_rotation(gui_settings.rotation); #endif /* Initialize Global progress bar*/ lv_obj_user_data_t udata = (lv_obj_user_data_t){10, 0, 10}; lv_obj_t* bar = lv_bar_create(lv_layer_sys(), NULL); lv_obj_set_user_data(bar, udata); lv_obj_set_hidden(bar, true); lv_bar_set_range(bar, 0, 100); lv_bar_set_value(bar, 10, LV_ANIM_OFF); lv_obj_set_size(bar, 200, 15); lv_obj_align(bar, lv_layer_sys(), LV_ALIGN_CENTER, 0, -10); lv_obj_set_style_local_value_color(bar, LV_BAR_PART_BG, LV_STATE_DEFAULT, LV_COLOR_WHITE); lv_obj_set_style_local_value_align(bar, LV_BAR_PART_BG, LV_STATE_DEFAULT, LV_ALIGN_CENTER); lv_obj_set_style_local_value_ofs_y(bar, LV_BAR_PART_BG, LV_STATE_DEFAULT, 20); lv_obj_set_style_local_value_font(bar, LV_BAR_PART_BG, LV_STATE_DEFAULT, LV_FONT_DEFAULT); lv_obj_set_style_local_bg_color(lv_layer_sys(), LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_BLACK); lv_obj_set_style_local_bg_opa(lv_layer_sys(), LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, LV_OPA_0); // guiStart(); // Ticker LOG_INFO(TAG_LVGL, F(D_SERVICE_STARTED)); } IRAM_ATTR void guiLoop(void) { lv_task_handler(); // process animations #if defined(STM32F4xx) // tick.update(); #endif #if !(defined(WINDOWS) || defined(POSIX)) // haspTouch.loop(); #endif } void guiEverySecond(void) { // nothing } void guiStart() { /*Initialize the graphics library's tick*/ // #if defined(ARDUINO_ARCH_ESP32) || defined(ARDUINO_ARCH_ESP8266) // tick.attach_ms(LVGL_TICK_PERIOD, lv_tick_handler); // #else // tick.start(); // #endif } void guiStop() { /*Deinitialize the graphics library's tick*/ // #if defined(ARDUINO_ARCH_ESP32) || defined(ARDUINO_ARCH_ESP8266) // tick.detach(); // #else // tick.stop(); // #endif } //////////////////////////////////////////////////////////////////////////////////////////////////// #if HASP_USE_CONFIG > 0 bool guiGetConfig(const JsonObject& settings) { bool changed = false; uint16_t guiSleepTime1; uint16_t guiSleepTime2; hasp_get_sleep_time(guiSleepTime1, guiSleepTime2); // if(guiTickPeriod != settings[FPSTR(FP_GUI_TICKPERIOD)].as<uint8_t>()) changed = true; // settings[FPSTR(FP_GUI_TICKPERIOD)] = guiTickPeriod; if(guiSleepTime1 != settings[FPSTR(FP_GUI_IDLEPERIOD1)].as<uint16_t>()) changed = true; settings[FPSTR(FP_GUI_IDLEPERIOD1)] = guiSleepTime1; if(guiSleepTime2 != settings[FPSTR(FP_GUI_IDLEPERIOD2)].as<uint16_t>()) changed = true; settings[FPSTR(FP_GUI_IDLEPERIOD2)] = guiSleepTime2; if(gui_settings.backlight_pin != settings[FPSTR(FP_GUI_BACKLIGHTPIN)].as<int8_t>()) changed = true; settings[FPSTR(FP_GUI_BACKLIGHTPIN)] = gui_settings.backlight_pin; if(gui_settings.rotation != settings[FPSTR(FP_GUI_ROTATION)].as<uint8_t>()) changed = true; settings[FPSTR(FP_GUI_ROTATION)] = gui_settings.rotation; if(gui_settings.show_pointer != settings[FPSTR(FP_GUI_POINTER)].as<bool>()) changed = true; settings[FPSTR(FP_GUI_POINTER)] = (uint8_t)gui_settings.show_pointer; if(gui_settings.invert_display != settings[FPSTR(FP_GUI_INVERT)].as<bool>()) changed = true; settings[FPSTR(FP_GUI_INVERT)] = (uint8_t)gui_settings.invert_display; /* Check CalData array has changed */ JsonArray array = settings[FPSTR(FP_GUI_CALIBRATION)].as<JsonArray>(); uint8_t i = 0; for(JsonVariant v : array) { LOG_VERBOSE(TAG_GUI, F("GUI CONF: %d: %d <=> %d"), i, gui_settings.cal_data[i], v.as<uint16_t>()); if(i < 5) { if(gui_settings.cal_data[i] != v.as<uint16_t>()) changed = true; v.set(gui_settings.cal_data[i]); } else { changed = true; #if TOUCH_DRIVER == 0x2046 && defined(USER_SETUP_LOADED) && defined(TOUCH_CS) // tft_espi_set_touch(gui_settings.cal_data); haspTft.tft.setTouch(gui_settings.cal_data); #endif } i++; } /* Build new CalData array if the count is not correct */ if(i != 5) { array = settings[FPSTR(FP_GUI_CALIBRATION)].to<JsonArray>(); // Clear JsonArray for(int i = 0; i < 5; i++) { array.add(gui_settings.cal_data[i]); } changed = true; #if TOUCH_DRIVER == 0x2046 && defined(USER_SETUP_LOADED) && defined(TOUCH_CS) // tft_espi_set_touch(gui_settings.cal_data); haspTft.tft.setTouch(gui_settings.cal_data); #endif } if(changed) configOutput(settings, TAG_GUI); return changed; } /** Set GUI Configuration. * * Read the settings from json and sets the application variables. * * @note: data pixel should be formated to uint32_t RGBA. Imagemagick requirements. * * @param[in] settings JsonObject with the config settings. **/ bool guiSetConfig(const JsonObject& settings) { configOutput(settings, TAG_GUI); bool changed = false; uint16_t guiSleepTime1; uint16_t guiSleepTime2; hasp_get_sleep_time(guiSleepTime1, guiSleepTime2); // changed |= configSet(guiTickPeriod, settings[FPSTR(FP_GUI_TICKPERIOD)], F("guiTickPeriod")); changed |= configSet(gui_settings.backlight_pin, settings[FPSTR(FP_GUI_BACKLIGHTPIN)], F("guiBacklightPin")); changed |= configSet(guiSleepTime1, settings[FPSTR(FP_GUI_IDLEPERIOD1)], F("guiSleepTime1")); changed |= configSet(guiSleepTime2, settings[FPSTR(FP_GUI_IDLEPERIOD2)], F("guiSleepTime2")); changed |= configSet(gui_settings.rotation, settings[FPSTR(FP_GUI_ROTATION)], F("gui_settings.rotation")); changed |= configSet(gui_settings.invert_display, settings[FPSTR(FP_GUI_INVERT)], F("guiInvertDisplay")); hasp_set_sleep_time(guiSleepTime1, guiSleepTime2); if(!settings[FPSTR(FP_GUI_POINTER)].isNull()) { if(gui_settings.show_pointer != settings[FPSTR(FP_GUI_POINTER)].as<bool>()) { LOG_VERBOSE(TAG_GUI, F("guiShowPointer set")); } changed |= gui_settings.show_pointer != settings[FPSTR(FP_GUI_POINTER)].as<bool>(); gui_settings.show_pointer = settings[FPSTR(FP_GUI_POINTER)].as<bool>(); gui_hide_pointer(false); } if(!settings[FPSTR(FP_GUI_CALIBRATION)].isNull()) { bool status = false; int i = 0; JsonArray array = settings[FPSTR(FP_GUI_CALIBRATION)].as<JsonArray>(); for(JsonVariant v : array) { if(i < 5) { if(gui_settings.cal_data[i] != v.as<uint16_t>()) status = true; gui_settings.cal_data[i] = v.as<uint16_t>(); } i++; } if(gui_settings.cal_data[0] != 0 || gui_settings.cal_data[1] != 65535 || gui_settings.cal_data[2] != 0 || gui_settings.cal_data[3] != 65535) { LOG_VERBOSE(TAG_GUI, F("calData set [%u, %u, %u, %u, %u]"), gui_settings.cal_data[0], gui_settings.cal_data[1], gui_settings.cal_data[2], gui_settings.cal_data[3], gui_settings.cal_data[4]); oobeSetAutoCalibrate(false); } else { LOG_TRACE(TAG_GUI, F("First Touch Calibration enabled")); oobeSetAutoCalibrate(true); } #if TOUCH_DRIVER == 0x2046 && defined(USER_SETUP_LOADED) && defined(TOUCH_CS) if(status) // tft_espi_set_touch(gui_settings.cal_data); haspTft.tft.setTouch(gui_settings.cal_data); #endif changed |= status; } return changed; } #endif // HASP_USE_CONFIG /* **************************** SCREENSHOTS ************************************** */ #if HASP_USE_SPIFFS > 0 || HASP_USE_LITTLEFS > 0 || HASP_USE_HTTP > 0 static void guiSetBmpHeader(uint8_t* buffer_p, int32_t data) { *buffer_p++ = data & 0xFF; *buffer_p++ = (data >> 8) & 0xFF; *buffer_p++ = (data >> 16) & 0xFF; *buffer_p++ = (data >> 24) & 0xFF; } /** Send Bitmap Header. * * Sends a header in BMP format for the size of the screen. * * @note: send header before refreshing the whole screen * **/ static void gui_get_bitmap_header(uint8_t* buffer, size_t bufsize) { lv_obj_t* scr = lv_disp_get_scr_act(NULL); lv_coord_t width = lv_obj_get_width(scr); lv_coord_t height = lv_obj_get_height(scr); const char* bm = "BM"; memcpy(buffer, bm, strlen(bm)); buffer += strlen(bm); bmp_header_t* bmp = (bmp_header_t*)buffer; bmp->bfSize = (uint32_t)(width * height * LV_COLOR_DEPTH / 8); bmp->bfReserved = 0; bmp->bfOffBits = 66; bmp->biSize = 40; bmp->biWidth = width; bmp->biHeight = -height; bmp->biPlanes = 1; bmp->biBitCount = LV_COLOR_DEPTH; bmp->biCompression = 3; // BI_BITFIELDS bmp->biSizeImage = bmp->bfSize; bmp->biXPelsPerMeter = 2836; bmp->biYPelsPerMeter = 2836; bmp->biClrUsed = 0; bmp->biClrImportant = 0; bmp->bdMask[0] = 0xF800; // Red bitmask : 1111 1000 | 0000 0000 bmp->bdMask[1] = 0x07E0; // Green bitmask: 0000 0111 | 1110 0000 bmp->bdMask[2] = 0x001F; // Blue bitmask : 0000 0000 | 0001 1111 } void gui_flush_not_complete() { LOG_WARNING(TAG_GUI, F("Pixelbuffer not completely sent")); } #endif // HASP_USE_SPIFFS > 0 || HASP_USE_LITTLEFS > 0 || HASP_USE_HTTP > 0 #if HASP_USE_SPIFFS > 0 || HASP_USE_LITTLEFS > 0 /* Flush VDB bytes to a file */ static void gui_screenshot_to_file(lv_disp_drv_t* disp, const lv_area_t* area, lv_color_t* color_p) { size_t len = (area->x2 - area->x1 + 1) * (area->y2 - area->y1 + 1); /* Number of pixels */ len *= sizeof(lv_color_t); /* Number of bytes */ size_t res = pFileOut.write((uint8_t*)color_p, len); if(res != len) gui_flush_not_complete(); // indirect callback to flush screenshot data to the screen // drv_display_flush_cb(disp, area, color_p); haspTft.flush_pixels(disp, area, color_p); } /** Take Screenshot. * * Flush buffer into a binary file. * * @note: data pixel should be formated to uint16_t RGB. Set by Bitmap header. * * @param[in] pFileName Output binary file name. * **/ void guiTakeScreenshot(const char* pFileName) { uint8_t buffer[128]; gui_get_bitmap_header(buffer, sizeof(buffer)); pFileOut = HASP_FS.open(pFileName, "w"); if(pFileOut) { size_t len = pFileOut.write(buffer, 66); if(len == 66) { LOG_VERBOSE(TAG_GUI, F("Bitmap header written")); /* Refresh screen to screenshot callback */ lv_disp_t* disp = lv_disp_get_default(); void (*flush_cb)(struct _disp_drv_t * disp_drv, const lv_area_t* area, lv_color_t* color_p); flush_cb = disp->driver.flush_cb; /* store callback */ disp->driver.flush_cb = gui_screenshot_to_file; lv_obj_invalidate(lv_scr_act()); lv_refr_now(NULL); /* Will call our disp_drv.disp_flush function */ disp->driver.flush_cb = flush_cb; /* restore callback */ LOG_VERBOSE(TAG_GUI, F("Bitmap data flushed to %s"), pFileName); } else { LOG_ERROR(TAG_GUI, F("Data written does not match header size")); } pFileOut.close(); } else { LOG_WARNING(TAG_GUI, F(D_FILE_SAVE_FAILED), pFileName); } } #endif #if HASP_USE_HTTP > 0 /* Flush VDB bytes to a webclient */ static void gui_screenshot_to_http(lv_disp_drv_t* disp, const lv_area_t* area, lv_color_t* color_p) { size_t len = (area->x2 - area->x1 + 1) * (area->y2 - area->y1 + 1); /* Number of pixels */ len *= sizeof(lv_color_t); /* Number of bytes */ size_t res = httpClientWrite((uint8_t*)color_p, len); if(res != len) gui_flush_not_complete(); // indirect callback to flush screenshot data to the screen // drv_display_flush_cb(disp, area, color_p); haspTft.flush_pixels(disp, area, color_p); } /** Take Screenshot. * * Flush buffer into a http client. * * @note: data pixel should be formated to uint16_t RGB. Set by Bitmap header. * **/ void guiTakeScreenshot() { uint8_t buffer[128]; gui_get_bitmap_header(buffer, sizeof(buffer)); if(httpClientWrite(buffer, 66) == 66) { // 122 LOG_VERBOSE(TAG_GUI, F("Bitmap header sent")); /* Refresh screen to screenshot callback */ lv_disp_t* disp = lv_disp_get_default(); void (*flush_cb)(struct _disp_drv_t * disp_drv, const lv_area_t* area, lv_color_t* color_p); flush_cb = disp->driver.flush_cb; /* store callback */ disp->driver.flush_cb = gui_screenshot_to_http; lv_obj_invalidate(lv_scr_act()); lv_refr_now(NULL); /* Will call our disp_drv.disp_flush function */ disp->driver.flush_cb = flush_cb; /* restore callback */ LOG_VERBOSE(TAG_GUI, F("Bitmap data flushed to webclient")); } else { LOG_ERROR(TAG_GUI, F("Data sent does not match header size")); } } #endif
33.935185
116
0.666069
[ "object" ]
4f3e158c6e7071ddcc89c9e12c5c0a127d1163a0
9,165
cpp
C++
mp/src/game/client/toolframework_client.cpp
ozxybox/source-sdk-2013
17dbb5ca5c2aa0e9cfc5360b098833d8b009e79c
[ "Unlicense" ]
4
2022-03-08T04:03:06.000Z
2022-03-09T06:51:54.000Z
mp/src/game/client/toolframework_client.cpp
ozxybox/source-sdk-2013
17dbb5ca5c2aa0e9cfc5360b098833d8b009e79c
[ "Unlicense" ]
null
null
null
mp/src/game/client/toolframework_client.cpp
ozxybox/source-sdk-2013
17dbb5ca5c2aa0e9cfc5360b098833d8b009e79c
[ "Unlicense" ]
1
2022-03-17T12:22:45.000Z
2022-03-17T12:22:45.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //===========================================================================// #include "cbase.h" #include "toolframework_client.h" #include "igamesystem.h" #include "tier1/KeyValues.h" #include "toolframework/iclientenginetools.h" #include "client_factorylist.h" #include "iviewrender.h" #include "materialsystem/imaterialvar.h" extern IViewRender *g_pView; class CToolFrameworkClient : public CBaseGameSystemPerFrame { public: // Methods of IGameSystem virtual bool Init(); virtual void LevelInitPreEntity(); virtual void LevelInitPostEntity(); virtual void LevelShutdownPreEntity(); virtual void LevelShutdownPostEntity(); virtual void PreRender(); virtual void PostRender(); public: // Other public methods void PostToolMessage( HTOOLHANDLE hEntity, KeyValues *msg ); void AdjustEngineViewport( int& x, int& y, int& width, int& height ); bool SetupEngineView( Vector &origin, QAngle &angles, float &fov ); bool SetupAudioState( AudioState_t &audioState ); bool IsThirdPersonCamera(); IClientEngineTools *m_pTools; }; //----------------------------------------------------------------------------- // Singleton //----------------------------------------------------------------------------- static CToolFrameworkClient g_ToolFrameworkClient; #ifndef NO_TOOLFRAMEWORK bool ToolsEnabled() { return g_ToolFrameworkClient.m_pTools && g_ToolFrameworkClient.m_pTools->InToolMode(); } #endif IGameSystem *ToolFrameworkClientSystem() { return &g_ToolFrameworkClient; } bool CToolFrameworkClient::Init() { factorylist_t list; FactoryList_Retrieve( list ); m_pTools = ( IClientEngineTools * )list.appSystemFactory( VCLIENTENGINETOOLS_INTERFACE_VERSION, NULL ); return ( m_pTools != NULL ); } void CToolFrameworkClient::LevelInitPreEntity() { if ( m_pTools ) { m_pTools->LevelInitPreEntityAllTools(); } } void CToolFrameworkClient::LevelInitPostEntity() { if ( m_pTools ) { m_pTools->LevelInitPostEntityAllTools(); } } void CToolFrameworkClient::LevelShutdownPreEntity() { if ( m_pTools ) { m_pTools->LevelShutdownPreEntityAllTools(); } } void CToolFrameworkClient::LevelShutdownPostEntity() { if ( m_pTools ) { m_pTools->LevelShutdownPostEntityAllTools(); } } void CToolFrameworkClient::PreRender() { if ( m_pTools ) { m_pTools->PreRenderAllTools(); } } void CToolFrameworkClient::PostRender() { if ( m_pTools ) { m_pTools->PostRenderAllTools(); } } //----------------------------------------------------------------------------- // Should we render with a 3rd person camera? //----------------------------------------------------------------------------- bool CToolFrameworkClient::IsThirdPersonCamera() { if ( !m_pTools ) return false; return m_pTools->IsThirdPersonCamera( ); } bool ToolFramework_IsThirdPersonCamera( ) { return g_ToolFrameworkClient.IsThirdPersonCamera( ); } //----------------------------------------------------------------------------- // Posts a message to all tools //----------------------------------------------------------------------------- void CToolFrameworkClient::PostToolMessage( HTOOLHANDLE hEntity, KeyValues *msg ) { if ( m_pTools ) { m_pTools->PostToolMessage( hEntity, msg ); } } void ToolFramework_PostToolMessage( HTOOLHANDLE hEntity, KeyValues *msg ) { g_ToolFrameworkClient.PostToolMessage( hEntity, msg ); } //----------------------------------------------------------------------------- // View manipulation //----------------------------------------------------------------------------- void CToolFrameworkClient::AdjustEngineViewport( int& x, int& y, int& width, int& height ) { if ( m_pTools ) { m_pTools->AdjustEngineViewport( x, y, width, height ); } } void ToolFramework_AdjustEngineViewport( int& x, int& y, int& width, int& height ) { g_ToolFrameworkClient.AdjustEngineViewport( x, y, width, height ); } //----------------------------------------------------------------------------- // View manipulation //----------------------------------------------------------------------------- bool CToolFrameworkClient::SetupEngineView( Vector &origin, QAngle &angles, float &fov ) { if ( !m_pTools ) return false; return m_pTools->SetupEngineView( origin, angles, fov ); } bool ToolFramework_SetupEngineView( Vector &origin, QAngle &angles, float &fov ) { return g_ToolFrameworkClient.SetupEngineView( origin, angles, fov ); } //----------------------------------------------------------------------------- // microphone manipulation //----------------------------------------------------------------------------- bool CToolFrameworkClient::SetupAudioState( AudioState_t &audioState ) { if ( !m_pTools ) return false; return m_pTools->SetupAudioState( audioState ); } bool ToolFramework_SetupAudioState( AudioState_t &audioState ) { return g_ToolFrameworkClient.SetupAudioState( audioState ); } //----------------------------------------------------------------------------- // Helper class to indicate ownership of effects //----------------------------------------------------------------------------- CRecordEffectOwner::CRecordEffectOwner( C_BaseEntity *pEntity, bool bIsViewModel ) { m_bToolsEnabled = ToolsEnabled() && clienttools->IsInRecordingMode(); if ( m_bToolsEnabled ) { KeyValues *msg = new KeyValues( "EffectsOwner" ); msg->SetInt( "viewModel", bIsViewModel ); ToolFramework_PostToolMessage( pEntity ? pEntity->GetToolHandle() : HTOOLHANDLE_INVALID, msg ); msg->deleteThis(); } } CRecordEffectOwner::~CRecordEffectOwner() { if ( m_bToolsEnabled ) { KeyValues *msg = new KeyValues( "EffectsOwner" ); ToolFramework_PostToolMessage( HTOOLHANDLE_INVALID, msg ); msg->deleteThis(); } } //----------------------------------------------------------------------------- // material recording - primarily for proxy materials //----------------------------------------------------------------------------- void WriteFloat( char *&buf, float f) { *( float* )buf = f; buf += sizeof( float ); } void WriteInt( char *&buf, int i ) { *( int* )buf = i; buf += sizeof( int ); } void WritePtr( char *&buf, void *p ) { *( void** )buf = p; buf += sizeof( void* ); } void ToolFramework_RecordMaterialParams( IMaterial *pMaterial ) { Assert( pMaterial ); if ( !pMaterial ) return; if ( !clienttools->IsInRecordingMode() ) return; C_BaseEntity *pEnt = g_pView->GetCurrentlyDrawingEntity(); if ( !pEnt || !pEnt->IsToolRecording() ) return; KeyValues *msg = new KeyValues( "material_proxy_state" ); msg->SetString( "mtlName", pMaterial->GetName() ); msg->SetString( "groupName", pMaterial->GetTextureGroupName() ); int nParams = pMaterial->ShaderParamCount(); IMaterialVar **pParams = pMaterial->GetShaderParams(); char str[ 256 ]; for ( int i = 0; i < nParams; ++i ) { IMaterialVar *pVar = pParams[ i ]; const char *pVarName = pVar->GetName(); MaterialVarType_t vartype = pVar->GetType(); switch ( vartype ) { case MATERIAL_VAR_TYPE_FLOAT: msg->SetFloat( pVarName, pVar->GetFloatValue() ); break; case MATERIAL_VAR_TYPE_INT: msg->SetInt( pVarName, pVar->GetIntValue() ); break; case MATERIAL_VAR_TYPE_STRING: msg->SetString( pVarName, pVar->GetStringValue() ); break; case MATERIAL_VAR_TYPE_FOURCC: Assert( 0 ); // JDTODO break; case MATERIAL_VAR_TYPE_VECTOR: { const float *pVal = pVar->GetVecValue(); int dim = pVar->VectorSize(); switch ( dim ) { case 2: V_snprintf( str, sizeof( str ), "vector2d: %f %f", pVal[ 0 ], pVal[ 1 ] ); break; case 3: V_snprintf( str, sizeof( str ), "vector3d: %f %f %f", pVal[ 0 ], pVal[ 1 ], pVal[ 2 ] ); break; case 4: V_snprintf( str, sizeof( str ), "vector4d: %f %f %f %f", pVal[ 0 ], pVal[ 1 ], pVal[ 2 ], pVal[ 3 ] ); break; default: Assert( 0 ); *str = 0; } msg->SetString( pVarName, str ); } break; case MATERIAL_VAR_TYPE_MATRIX: { const VMatrix &matrix = pVar->GetMatrixValue(); const float *pVal = matrix.Base(); V_snprintf( str, sizeof( str ), "matrix: %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f", pVal[ 0 ], pVal[ 1 ], pVal[ 2 ], pVal[ 3 ], pVal[ 4 ], pVal[ 5 ], pVal[ 6 ], pVal[ 7 ], pVal[ 8 ], pVal[ 9 ], pVal[ 10 ], pVal[ 11 ], pVal[ 12 ], pVal[ 13 ], pVal[ 14 ], pVal[ 15 ] ); msg->SetString( pVarName, str ); } break; case MATERIAL_VAR_TYPE_TEXTURE: // V_snprintf( str, sizeof( str ), "texture: %x", pVar->GetTextureValue() ); // msg->SetString( pVarName, str ); break; case MATERIAL_VAR_TYPE_MATERIAL: // V_snprintf( str, sizeof( str ), "material: %x", pVar->GetMaterialValue() ); // msg->SetString( pVarName, str ); break; case MATERIAL_VAR_TYPE_UNDEFINED: // Assert( 0 ); // these appear to be (mostly? all?) textures, although I don't know why they're not caught by the texture case above... break; // JDTODO default: Assert( 0 ); } } Assert( pEnt->GetToolHandle() ); ToolFramework_PostToolMessage( pEnt->GetToolHandle(), msg ); msg->deleteThis(); }
25.672269
141
0.589416
[ "render", "vector" ]
4f42c4f6b31b35375eca2983e5662a1d88122f48
1,287
cc
C++
PhysicsTools/PatAlgos/plugins/GenMETExtractor.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
PhysicsTools/PatAlgos/plugins/GenMETExtractor.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
PhysicsTools/PatAlgos/plugins/GenMETExtractor.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "PhysicsTools/PatAlgos/plugins/GenMETExtractor.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h" #include "FWCore/ParameterSet/interface/ParameterSetDescription.h" #include <memory> using namespace pat; GenMETExtractor::GenMETExtractor(const edm::ParameterSet& iConfig) { edm::InputTag metIT = iConfig.getParameter<edm::InputTag>("metSource"); metSrcToken_ = consumes<pat::METCollection>(metIT); // produces vector of genMet produces<std::vector<reco::GenMET> >(); } GenMETExtractor::~GenMETExtractor() { } void GenMETExtractor::produce(edm::StreamID streamID, edm::Event & iEvent, const edm::EventSetup & iSetup) const { edm::Handle<std::vector<pat::MET> > src; iEvent.getByToken(metSrcToken_, src); if(src->empty()) edm::LogError("GenMETExtractor::produce") << "input genMET collection is empty" ; const reco::GenMET *genMet = src->front().genMET(); std::vector<reco::GenMET> *genMetCol = new std::vector<reco::GenMET>(); genMetCol->push_back( (*genMet) ); std::unique_ptr<std::vector<reco::GenMET> > genMETs(genMetCol); iEvent.put(std::move(genMETs)); } #include "FWCore/Framework/interface/MakerMacros.h" DEFINE_FWK_MODULE(GenMETExtractor);
28.6
100
0.738928
[ "vector" ]
4f446dfbb6992056f78e122ccc8224bbc4cc25e8
16,748
cc
C++
ui/events/ozone/evdev/touch_filter/neural_stylus_palm_detection_filter_unittest.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-10-18T02:33:40.000Z
2020-10-18T02:33:40.000Z
ui/events/ozone/evdev/touch_filter/neural_stylus_palm_detection_filter_unittest.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2021-05-17T16:28:52.000Z
2021-05-21T22:42:22.000Z
ui/events/ozone/evdev/touch_filter/neural_stylus_palm_detection_filter_unittest.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2019 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 "ui/events/ozone/evdev/touch_filter/neural_stylus_palm_detection_filter.h" #include <memory> #include <utility> #include <vector> #include "base/test/gtest_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/events/ozone/evdev/event_device_test_util.h" #include "ui/events/ozone/evdev/touch_filter/neural_stylus_palm_detection_filter_model.h" #include "ui/events/ozone/evdev/touch_filter/palm_detection_filter.h" #include "ui/events/ozone/evdev/touch_filter/shared_palm_detection_filter_state.h" namespace ui { class MockNeuralModel : public NeuralStylusPalmDetectionFilterModel { public: MOCK_CONST_METHOD1(Inference, float(const std::vector<float>& features)); MOCK_CONST_METHOD0(config, const NeuralStylusPalmDetectionFilterModelConfig&()); }; class NeuralStylusPalmDetectionFilterTest : public testing::Test { public: NeuralStylusPalmDetectionFilterTest() = default; void SetUp() override { shared_palm_state = std::make_unique<SharedPalmDetectionFilterState>(); model_ = new testing::StrictMock<MockNeuralModel>; model_config_.biggest_near_neighbor_count = 2; model_config_.min_sample_count = 2; model_config_.max_sample_count = 5; model_config_.max_neighbor_distance_in_mm = 20; model_config_.heuristic_palm_touch_limit = 40; model_config_.heuristic_palm_area_limit = 1000; model_config_.max_dead_neighbor_time = base::TimeDelta::FromMillisecondsD(100); EXPECT_CALL(*model_, config()) .Times(testing::AnyNumber()) .WillRepeatedly(testing::ReturnRef(model_config_)); EXPECT_TRUE( CapabilitiesToDeviceInfo(kNocturneTouchScreen, &nocturne_touchscreen_)); palm_detection_filter_ = std::make_unique<NeuralStylusPalmDetectionFilter>( nocturne_touchscreen_, std::unique_ptr<NeuralStylusPalmDetectionFilterModel>(model_), shared_palm_state.get()); touch_.resize(kNumTouchEvdevSlots); for (size_t i = 0; i < touch_.size(); ++i) { touch_[i].slot = i; } } protected: std::vector<InProgressTouchEvdev> touch_; std::unique_ptr<SharedPalmDetectionFilterState> shared_palm_state; EventDeviceInfo nocturne_touchscreen_; // Owned by the filter. MockNeuralModel* model_; NeuralStylusPalmDetectionFilterModelConfig model_config_; std::unique_ptr<PalmDetectionFilter> palm_detection_filter_; DISALLOW_COPY_AND_ASSIGN(NeuralStylusPalmDetectionFilterTest); }; class NeuralStylusPalmDetectionFilterDeathTest : public NeuralStylusPalmDetectionFilterTest {}; TEST_F(NeuralStylusPalmDetectionFilterTest, EventDeviceSimpleTest) { EventDeviceInfo devinfo; std::vector<std::pair<DeviceCapabilities, bool>> devices = { {kNocturneTouchScreen, true}, {kEveTouchScreen, true}, {kLinkTouchscreen, true}, // No ABS_MT_TOOL_TYPE {kNocturneStylus, false}, {kKohakuTouchscreen, true}, // The Wacom Intuos is external. {kWacomIntuosPtS_Finger, false}}; for (const auto& it : devices) { EXPECT_TRUE(CapabilitiesToDeviceInfo(it.first, &devinfo)); EXPECT_EQ(it.second, NeuralStylusPalmDetectionFilter:: CompatibleWithNeuralStylusPalmDetectionFilter(devinfo)) << "Failed on " << it.first.name; EXPECT_EQ(false, NeuralStylusPalmDetectionFilter:: CompatibleWithNeuralStylusPalmDetectionFilter( devinfo, "{\"touch-compatible\": \"false\"}")); EXPECT_EQ(false, NeuralStylusPalmDetectionFilter:: CompatibleWithNeuralStylusPalmDetectionFilter(devinfo, "{}")); if (it.second) { EXPECT_EQ(true, NeuralStylusPalmDetectionFilter:: CompatibleWithNeuralStylusPalmDetectionFilter( devinfo, "{\"touch-compatible\": \"true\"}")); } } } TEST_F(NeuralStylusPalmDetectionFilterDeathTest, EventDeviceConstructionDeath) { EventDeviceInfo bad_devinfo; EXPECT_TRUE(CapabilitiesToDeviceInfo(kNocturneStylus, &bad_devinfo)); EXPECT_DCHECK_DEATH({ NeuralStylusPalmDetectionFilter f( bad_devinfo, std::unique_ptr<NeuralStylusPalmDetectionFilterModel>(model_), shared_palm_state.get()); }); } TEST_F(NeuralStylusPalmDetectionFilterTest, NameTest) { EXPECT_EQ("NeuralStylusPalmDetectionFilter", palm_detection_filter_->FilterNameForTesting()); } TEST_F(NeuralStylusPalmDetectionFilterTest, ShortTouchPalmAreaTest) { std::bitset<kNumTouchEvdevSlots> actual_held, actual_cancelled, expected_cancelled; touch_[0].touching = true; touch_[0].tracking_id = 600; touch_[0].x = 50; touch_[0].y = 55; touch_[0].major = 34; // 34 * 32 = 1088 touch_[0].minor = 32; base::TimeTicks touch_time = base::TimeTicks::UnixEpoch() + base::TimeDelta::FromMillisecondsD(10.0); palm_detection_filter_->Filter(touch_, touch_time, &actual_held, &actual_cancelled); EXPECT_TRUE(actual_held.none()); EXPECT_TRUE(actual_cancelled.none()); // end it touch_[0].was_touching = true; touch_[0].touching = false; touch_[0].tracking_id = -1; touch_time += base::TimeDelta::FromMillisecondsD(8.0f); palm_detection_filter_->Filter(touch_, touch_time, &actual_held, &actual_cancelled); EXPECT_TRUE(actual_held.none()); expected_cancelled.set(0, true); EXPECT_EQ(expected_cancelled, actual_cancelled); } TEST_F(NeuralStylusPalmDetectionFilterTest, ShortTouchPalmSizeTest) { std::bitset<kNumTouchEvdevSlots> actual_held, actual_cancelled; touch_[0].touching = true; touch_[0].tracking_id = 600; touch_[0].x = 50; touch_[0].y = 55; touch_[0].major = 25; touch_[0].minor = 17; base::TimeTicks touch_time = base::TimeTicks::UnixEpoch() + base::TimeDelta::FromMillisecondsD(10.0); palm_detection_filter_->Filter(touch_, touch_time, &actual_held, &actual_cancelled); EXPECT_TRUE(actual_held.none()); EXPECT_TRUE(actual_cancelled.none()); // end it touch_[0].was_touching = true; touch_[0].touching = false; touch_[0].tracking_id = -1; touch_time += base::TimeDelta::FromMillisecondsD(8.0f); palm_detection_filter_->Filter(touch_, touch_time, &actual_held, &actual_cancelled); EXPECT_TRUE(actual_held.none()); EXPECT_TRUE(actual_cancelled.none()); touch_time += base::TimeDelta::FromSecondsD(3600); touch_[0].touching = true; touch_[0].major = 57; touch_[0].tracking_id = 601; touch_[0].was_touching = false; palm_detection_filter_->Filter(touch_, touch_time, &actual_held, &actual_cancelled); EXPECT_TRUE(actual_held.none()); EXPECT_TRUE(actual_cancelled.none()); touch_[0].was_touching = true; touch_[0].touching = false; touch_[0].tracking_id = -1; touch_time += base::TimeDelta::FromMillisecondsD(8.0f); palm_detection_filter_->Filter(touch_, touch_time, &actual_held, &actual_cancelled); EXPECT_TRUE(actual_held.none()); EXPECT_TRUE(actual_cancelled.test(0)); actual_cancelled.set(0, false); EXPECT_TRUE(actual_cancelled.none()); } TEST_F(NeuralStylusPalmDetectionFilterTest, CallFilterTest) { // Set up 3 touches as touching: // Touch 0 starts off and is sent twice // Touch 1 and 2 are then added on: 2 is far away, 1 is nearby. We expect a // single call to filter, with only 1 neighbor! std::bitset<kNumTouchEvdevSlots> actual_held, actual_cancelled; std::bitset<kNumTouchEvdevSlots> expected_cancelled; model_config_.max_blank_time = base::TimeDelta::FromMillisecondsD(100); model_config_.use_tracking_id_count = true; model_config_.use_active_tracking_id_count = true; touch_[0].touching = true; touch_[0].tracking_id = 500; touch_[0].major = 15; touch_[0].minor = 10; touch_[0].x = 15; touch_[0].y = 10; touch_[0].slot = 0; base::TimeTicks touch_time = base::TimeTicks::UnixEpoch() + base::TimeDelta::FromMillisecondsD(10.0); palm_detection_filter_->Filter(touch_, touch_time, &actual_held, &actual_cancelled); EXPECT_TRUE(actual_held.none()); EXPECT_TRUE(actual_cancelled.none()); // And now, let's add touches 1 and 2. touch_[0].x = 17; touch_[0].major = 14; touch_[0].was_touching = true; touch_[1].touching = true; touch_[1].major = 11; touch_[1].minor = 9; touch_[1].x = 30; touch_[1].y = 25; touch_[1].tracking_id = 501; touch_[1].slot = 1; touch_[2].touching = true; touch_[2].major = 10; touch_[2].minor = 8; touch_[2].x = 5500; touch_[2].y = 2942; touch_[2].tracking_id = 502; touch_[2].slot = 2; touch_time += base::TimeDelta::FromMillisecondsD(8.0f); palm_detection_filter_->Filter(touch_, touch_time, &actual_held, &actual_cancelled); EXPECT_TRUE(actual_held.none()); EXPECT_TRUE(actual_cancelled.none()); touch_[3] = touch_[2]; touch_[3].slot = 3; touch_[3].x = 8000; touch_[3].tracking_id = 504; touch_[1].was_touching = true; touch_[2].was_touching = true; touch_[0].touching = false; touch_[0].tracking_id = -1; std::vector<float> features = { 15, 10, 0, 0.25, 1, 14, 10, 0.05, 0.25, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.4, 0.05, 0, 1, 0.512957, 11, 9, 0, 0.625, 1, 11, 9, 0, 0.625, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4}; EXPECT_CALL(*model_, Inference(testing::Pointwise(testing::FloatEq(), features))) .Times(1) .WillOnce(testing::Return(0.5)); touch_time += base::TimeDelta::FromMillisecondsD(8.0f); palm_detection_filter_->Filter(touch_, touch_time, &actual_held, &actual_cancelled); EXPECT_TRUE(actual_held.none()); expected_cancelled.set(0, true); EXPECT_EQ(actual_cancelled, expected_cancelled); // Touch 0 already ended in last report, now we mark touch 2 ended, its last // two features should be 4 and 3 (tracking_id_count and // active_tracking_id_count). touch_[0].was_touching = false; touch_[2].tracking_id = -1; touch_[3].was_touching = true; features = {10, 8, 0, 73.55, 1, 10, 8, 0, 73.55, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3}; EXPECT_CALL(*model_, Inference(testing::Pointwise(testing::FloatEq(), features))) .Times(1) .WillOnce(testing::Return(0.5)); touch_time += base::TimeDelta::FromMillisecondsD(8.0f); palm_detection_filter_->Filter(touch_, touch_time, &actual_held, &actual_cancelled); EXPECT_TRUE(actual_held.none()); expected_cancelled.set(2, true); EXPECT_EQ(actual_cancelled, expected_cancelled); } TEST_F(NeuralStylusPalmDetectionFilterTest, InferenceOnceNotPalm) { std::bitset<kNumTouchEvdevSlots> actual_held, actual_cancelled; base::TimeTicks touch_time = base::TimeTicks::UnixEpoch() + base::TimeDelta::FromMillisecondsD(10.0); touch_[0].touching = true; touch_[0].tracking_id = 600; touch_[0].x = 50; touch_[0].y = 55; touch_[0].major = 25; touch_[0].minor = 17; EXPECT_CALL(*model_, Inference(testing::_)) .Times(1) .WillOnce(testing::Return(-0.5)); for (int i = 0; i < 5000; ++i) { if (i != 0) { touch_[0].was_touching = true; } touch_time += base::TimeDelta::FromMillisecondsD(8.0f); palm_detection_filter_->Filter(touch_, touch_time, &actual_held, &actual_cancelled); ASSERT_TRUE(actual_held.none()) << " Failed at " << i; ASSERT_TRUE(actual_cancelled.none()) << " Failed at " << i; } } TEST_F(NeuralStylusPalmDetectionFilterTest, InferenceOncePalm) { std::bitset<kNumTouchEvdevSlots> actual_held, actual_cancelled; std::bitset<kNumTouchEvdevSlots> expected_cancelled; base::TimeTicks touch_time = base::TimeTicks::UnixEpoch() + base::TimeDelta::FromMillisecondsD(10.0); expected_cancelled.set(0, true); touch_[0].touching = true; touch_[0].tracking_id = 600; touch_[0].x = 50; touch_[0].y = 55; touch_[0].major = 25; touch_[0].minor = 17; EXPECT_CALL(*model_, Inference(testing::_)) .Times(1) .WillOnce(testing::Return(0.5)); base::TimeTicks original_finger_time = touch_time + base::TimeDelta::FromMillisecondsD(8.0f); base::TimeTicks original_palm_time = touch_time + model_config_.max_sample_count * base::TimeDelta::FromMillisecondsD(8.0f); for (size_t i = 0; i < 5000; ++i) { if (i != 0) { touch_[0].was_touching = true; } touch_time += base::TimeDelta::FromMillisecondsD(8.0f); palm_detection_filter_->Filter(touch_, touch_time, &actual_held, &actual_cancelled); ASSERT_EQ(original_finger_time, shared_palm_state->latest_finger_touch_time); ASSERT_TRUE(actual_held.none()) << " Failed at " << i; if (i >= (model_config_.max_sample_count - 1)) { ASSERT_EQ(expected_cancelled, actual_cancelled) << " Failed at " << i; ASSERT_EQ(1u, shared_palm_state->active_palm_touches) << " Failed at " << i; ASSERT_EQ(original_palm_time, shared_palm_state->latest_palm_touch_time) << " Failed at " << i; } else { ASSERT_EQ(1u, shared_palm_state->active_finger_touches) << "Failed at " << i; } } } TEST_F(NeuralStylusPalmDetectionFilterTest, DelayShortFingerTouch) { std::bitset<kNumTouchEvdevSlots> actual_held, actual_cancelled; std::bitset<kNumTouchEvdevSlots> expected_held, expected_cancelled; model_config_.heuristic_delay_start_if_palm = true; touch_[0].touching = true; touch_[0].tracking_id = 605; touch_[0].x = 50; touch_[0].y = 55; // small touch! 39*21 = 819, which is < 1000. touch_[0].major = 39; touch_[0].minor = 21; base::TimeTicks touch_time = base::TimeTicks::UnixEpoch() + base::TimeDelta::FromMillisecondsD(10.0); palm_detection_filter_->Filter(touch_, touch_time, &actual_held, &actual_cancelled); EXPECT_EQ(expected_held, actual_held); EXPECT_EQ(expected_cancelled, actual_cancelled); } TEST_F(NeuralStylusPalmDetectionFilterTest, DelayShortPalmTouch) { std::bitset<kNumTouchEvdevSlots> actual_held, actual_cancelled; std::bitset<kNumTouchEvdevSlots> expected_held, expected_cancelled; model_config_.heuristic_delay_start_if_palm = true; touch_[0].touching = true; touch_[0].tracking_id = 605; touch_[0].x = 50; touch_[0].y = 55; // big touch! 39*30 = 1170, which is > 1000. touch_[0].major = 39; touch_[0].minor = 30; base::TimeTicks touch_time = base::TimeTicks::UnixEpoch() + base::TimeDelta::FromMillisecondsD(10.0); palm_detection_filter_->Filter(touch_, touch_time, &actual_held, &actual_cancelled); expected_held.set(0, true); EXPECT_EQ(expected_held, actual_held); EXPECT_EQ(expected_cancelled, actual_cancelled); // Delay continues even afterwards, until inference time: then it's off. for (uint32_t i = 1; i < model_config_.max_sample_count - 1; ++i) { touch_[0].was_touching = true; touch_time += base::TimeDelta::FromMillisecondsD(10.0); touch_[0].major = 15; touch_[0].minor = 15; touch_[0].x += 1; touch_[0].y += 1; palm_detection_filter_->Filter(touch_, touch_time, &actual_held, &actual_cancelled); EXPECT_EQ(expected_held, actual_held) << " failed at " << i; EXPECT_EQ(expected_cancelled, actual_cancelled) << " failed at " << i; } // When running inference, turn delay to false. EXPECT_CALL(*model_, Inference(testing::_)) .Times(1) .WillOnce(testing::Return(-0.1)); touch_time = base::TimeTicks::UnixEpoch() + base::TimeDelta::FromMillisecondsD(10.0); palm_detection_filter_->Filter(touch_, touch_time, &actual_held, &actual_cancelled); expected_held.set(0, false); EXPECT_EQ(expected_held, actual_held); EXPECT_EQ(expected_cancelled, actual_cancelled); } } // namespace ui
38.948837
89
0.672021
[ "vector" ]
4f447468e407a22b7e4409607e6ba04f3bb1146c
5,081
hpp
C++
ios/Pods/boost-for-react-native/boost/interprocess/smart_ptr/detail/sp_counted_impl.hpp
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
8,805
2015-11-03T00:52:29.000Z
2022-03-29T22:30:03.000Z
ios/Pods/boost-for-react-native/boost/interprocess/smart_ptr/detail/sp_counted_impl.hpp
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
14,694
2015-02-24T15:13:42.000Z
2022-03-31T13:16:45.000Z
ios/Pods/boost-for-react-native/boost/interprocess/smart_ptr/detail/sp_counted_impl.hpp
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
1,329
2015-11-03T20:25:51.000Z
2022-03-31T18:10:38.000Z
#ifndef BOOST_INTERPROCESS_DETAIL_SP_COUNTED_IMPL_HPP_INCLUDED #define BOOST_INTERPROCESS_DETAIL_SP_COUNTED_IMPL_HPP_INCLUDED #ifndef BOOST_CONFIG_HPP # include <boost/config.hpp> #endif # #if defined(BOOST_HAS_PRAGMA_ONCE) # pragma once #endif // // This file is the adaptation for shared memory memory mapped // files of boost/detail/sp_counted_impl.hpp // // Copyright (c) 2001, 2002, 2003 Peter Dimov and Multi Media Ltd. // Copyright 2004-2005 Peter Dimov // Copyright 2006 Ion Gaztanaga // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #include <boost/interprocess/detail/config_begin.hpp> #include <boost/interprocess/detail/workaround.hpp> #include <boost/interprocess/containers/version_type.hpp> #include <boost/interprocess/smart_ptr/detail/sp_counted_base.hpp> #include <boost/interprocess/smart_ptr/scoped_ptr.hpp> #include <boost/interprocess/detail/utilities.hpp> #include <boost/container/allocator_traits.hpp> #include <boost/intrusive/pointer_traits.hpp> namespace boost { namespace interprocess { namespace ipcdetail { //!A deleter for scoped_ptr that deallocates the memory //!allocated for an object using a STL allocator. template <class Allocator> struct scoped_ptr_dealloc_functor { typedef typename Allocator::pointer pointer; typedef ipcdetail::integral_constant<unsigned, boost::interprocess::version<Allocator>::value> alloc_version; typedef ipcdetail::integral_constant<unsigned, 1> allocator_v1; typedef ipcdetail::integral_constant<unsigned, 2> allocator_v2; private: void priv_deallocate(const typename Allocator::pointer &p, allocator_v1) { m_alloc.deallocate(p, 1); } void priv_deallocate(const typename Allocator::pointer &p, allocator_v2) { m_alloc.deallocate_one(p); } public: Allocator& m_alloc; scoped_ptr_dealloc_functor(Allocator& a) : m_alloc(a) {} void operator()(pointer ptr) { if (ptr) priv_deallocate(ptr, alloc_version()); } }; template<class A, class D> class sp_counted_impl_pd : public sp_counted_base , boost::container::allocator_traits<A>::template portable_rebind_alloc< sp_counted_impl_pd<A, D> >::type , D // copy constructor must not throw { private: typedef sp_counted_impl_pd<A, D> this_type; typedef typename boost::container:: allocator_traits<A>::template portable_rebind_alloc < this_type >::type this_allocator; typedef typename boost::container:: allocator_traits<A>::template portable_rebind_alloc < const this_type >::type const_this_allocator; typedef typename this_allocator::pointer this_pointer; typedef typename boost::intrusive:: pointer_traits<this_pointer> this_pointer_traits; sp_counted_impl_pd( sp_counted_impl_pd const & ); sp_counted_impl_pd & operator= ( sp_counted_impl_pd const & ); typedef typename boost::intrusive:: pointer_traits<typename A::pointer>::template rebind_pointer<const D>::type const_deleter_pointer; typedef typename boost::intrusive:: pointer_traits<typename A::pointer>::template rebind_pointer<const A>::type const_allocator_pointer; typedef typename D::pointer pointer; pointer m_ptr; public: // pre: d(p) must not throw template<class Ptr> sp_counted_impl_pd(const Ptr & p, const A &a, const D &d ) : this_allocator(a), D(d), m_ptr(p) {} const_deleter_pointer get_deleter() const { return const_deleter_pointer(&static_cast<const D&>(*this)); } const_allocator_pointer get_allocator() const { return const_allocator_pointer(&static_cast<const A&>(*this)); } void dispose() // nothrow { static_cast<D&>(*this)(m_ptr); } void destroy() // nothrow { //Self destruction, so move the allocator this_allocator a_copy(::boost::move(static_cast<this_allocator&>(*this))); BOOST_ASSERT(a_copy == *this); this_pointer this_ptr(this_pointer_traits::pointer_to(*this)); //Do it now! scoped_ptr< this_type, scoped_ptr_dealloc_functor<this_allocator> > deleter_ptr(this_ptr, a_copy); typedef typename this_allocator::value_type value_type; ipcdetail::to_raw_pointer(this_ptr)->~value_type(); } void release() // nothrow { if(this->ref_release()){ this->dispose(); this->weak_release(); } } void weak_release() // nothrow { if(sp_counted_base::weak_release()){ this->destroy(); } } }; } // namespace ipcdetail } // namespace interprocess } // namespace boost #include <boost/interprocess/detail/config_end.hpp> #endif // #ifndef BOOST_INTERPROCESS_DETAIL_SP_COUNTED_IMPL_HPP_INCLUDED
31.75625
87
0.685298
[ "object" ]
4f449c6af09424d09add79fb69c662d751b9489c
1,713
hpp
C++
src/net/crossbar.hpp
rikygege/Hornet
8b8ebe70fbc6391f361d98b8960dfdeeca0b8ebd
[ "MIT" ]
null
null
null
src/net/crossbar.hpp
rikygege/Hornet
8b8ebe70fbc6391f361d98b8960dfdeeca0b8ebd
[ "MIT" ]
null
null
null
src/net/crossbar.hpp
rikygege/Hornet
8b8ebe70fbc6391f361d98b8960dfdeeca0b8ebd
[ "MIT" ]
null
null
null
// -*- mode:c++; c-style:k&r; c-basic-offset:4; indent-tabs-mode: nil; -*- // vi:set et cin sw=4 cino=>se0n0f0{0}0^0\:0=sl1g0hspst0+sc3C0/0(0u0U0w0m0: #ifndef __CROSSBAR_HPP__ #define __CROSSBAR_HPP__ #include <vector> #include "node_id.hpp" #include "virtual_queue.hpp" #include "ingress.hpp" #include "egress.hpp" #include "statistics.hpp" #include "vcd.hpp" #include "logger.hpp" #include "random.hpp" class crossbar { public: crossbar(node_id parent, boost::shared_ptr<tile_statistics> stats, boost::shared_ptr<vcd_writer> vcd, logger &log, boost::shared_ptr<random_gen> ran) throw(); void add_ingress(node_id src, boost::shared_ptr<ingress> ingress) throw(err); void add_egress(node_id dst, boost::shared_ptr<egress> egress) throw(err); void tick_positive_edge() throw(err); void tick_negative_edge() throw(err); private: const node_id &get_id() throw(); void rebuild_queues() throw(); private: const node_id id; typedef map<node_id, boost::shared_ptr<ingress> > ingresses_t; typedef map<node_id, boost::shared_ptr<egress> > egresses_t; ingresses_t ingresses; egresses_t egresses; typedef vector<boost::tuple<node_id, boost::shared_ptr<virtual_queue> > > nvqs_t; nvqs_t ingress_qs; typedef vector<boost::shared_ptr<virtual_queue> > vqs_t; vqs_t egress_qs; boost::shared_ptr<tile_statistics> stats; boost::shared_ptr<vcd_writer> vcd; logger &log; boost::shared_ptr<random_gen> ran; typedef struct { char v_xbar_demand; char v_xbar_use; } vcd_hooks_t; vcd_hooks_t vcd_hooks; }; inline const node_id &crossbar::get_id() throw() { return id; } #endif // __CROSSBAR_HPP__
31.145455
85
0.705779
[ "vector" ]
4f45683d278719a3cdb819fcd3cc072c0b9a6353
2,359
hpp
C++
c++/include/connect/ncbi_pipe_connector.hpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
31
2016-12-09T04:56:59.000Z
2021-12-31T17:19:10.000Z
c++/include/connect/ncbi_pipe_connector.hpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
6
2017-03-10T17:25:13.000Z
2021-09-22T15:49:49.000Z
c++/include/connect/ncbi_pipe_connector.hpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
20
2015-01-04T02:15:17.000Z
2021-12-03T02:31:43.000Z
#ifndef CONNECT___NCBI_PIPE_CONNECTOR__HPP #define CONNECT___NCBI_PIPE_CONNECTOR__HPP /* $Id: ncbi_pipe_connector.hpp 337342 2011-09-11 01:13:46Z lavr $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Vladimir Ivanov * * */ /// @file ncbi_pipe_connector.hpp /// Implement CONNECTOR for a pipe interprocess communication /// (based on the NCBI CPipe). /// /// See in "connectr.h" for the detailed specification of the underlying /// connector("CONNECTOR", "SConnectorTag") methods and structures. #include <connect/ncbi_pipe.hpp> #include <connect/ncbi_connector.h> /** @addtogroup Connectors * * @{ */ BEGIN_NCBI_SCOPE /// Create CPipe-based CONNECTOR. /// /// Create new CONNECTOR structure to handle data transfer between /// two processes over interprocess pipe. Return NULL on error. extern NCBI_XCONNECT_EXPORT CONNECTOR PIPE_CreateConnector (const string& cmd, const vector<string>& args, CPipe::TCreateFlags create_flags = 0, CPipe* pipe = 0, EOwnership own_pipe = eTakeOwnership ); END_NCBI_SCOPE /* @} */ #endif /* CONNECT___NCBI_PIPE_CONNECTOR__HPP */
31.878378
78
0.673167
[ "vector" ]
4f4645211f2ae84af63bc17a41d54d566e37a1ce
12,394
cpp
C++
libs/geometry/test/algorithms/overlay/traverse_multi.cpp
zsims/boost
40e6df4e47fc98cf6833d34cc3ea9570b3dfeeaa
[ "BSL-1.0" ]
9
2016-03-01T02:19:06.000Z
2020-05-07T08:48:51.000Z
libs/geometry/test/algorithms/overlay/traverse_multi.cpp
zsims/boost
40e6df4e47fc98cf6833d34cc3ea9570b3dfeeaa
[ "BSL-1.0" ]
2
2016-01-05T06:36:48.000Z
2017-07-13T16:16:30.000Z
libs/geometry/test/algorithms/overlay/traverse_multi.cpp
zsims/boost
40e6df4e47fc98cf6833d34cc3ea9570b3dfeeaa
[ "BSL-1.0" ]
4
2016-06-14T02:31:01.000Z
2019-06-27T00:41:46.000Z
// Boost.Geometry (aka GGL, Generic Geometry Library) // Unit Test // Copyright (c) 2007-2015 Barend Gehrels, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //#define BOOST_GEOMETRY_DEBUG_ENRICH //#define BOOST_GEOMETRY_DEBUG_RELATIVE_ORDER // Include the single-geometry version #define BOOST_GEOMETRY_TEST_MULTI #include <algorithms/overlay/traverse.cpp> #include <boost/geometry/core/closure.hpp> #include <boost/geometry/core/geometry_id.hpp> #include <boost/geometry/core/point_order.hpp> #include <boost/geometry/core/ring_type.hpp> #include <boost/geometry/algorithms/envelope.hpp> #include <boost/geometry/algorithms/num_points.hpp> #include <boost/geometry/algorithms/detail/overlay/copy_segments.hpp> #include <boost/geometry/algorithms/detail/overlay/copy_segment_point.hpp> #include <boost/geometry/algorithms/detail/sections/range_by_section.hpp> #include <boost/geometry/algorithms/detail/sections/sectionalize.hpp> #include <boost/geometry/views/detail/range_type.hpp> #include "multi_overlay_cases.hpp" template <typename MultiPolygon, bool Reverse> void test_geometries() { typedef test_traverse < MultiPolygon, MultiPolygon, bg::overlay_intersection, Reverse, Reverse > test_traverse_intersection; typedef test_traverse < MultiPolygon, MultiPolygon, bg::overlay_union, Reverse, Reverse > test_traverse_union; // Intersections: test_traverse_intersection::apply ( "simplex", 2, 6.42, case_multi_simplex[0], case_multi_simplex[1] ); test_traverse_intersection::apply ( "case_58_multi_b4", 1, 12.666666667, case_58_multi[4], case_58_multi[2] ); #ifdef BOOST_GEOMETRY_TEST_INCLUDE_FAILING_TESTS test_traverse_intersection::apply ( "case_58_multi_b5", 1, 1, case_58_multi[5], case_58_multi[2] ); #endif test_traverse_intersection::apply ( "case_58_multi_b6", 1, 13.25, case_58_multi[6], case_58_multi[2] ); test_traverse_intersection::apply ( "case_65_multi", 1, 1, case_65_multi[0], case_65_multi[1] ); test_traverse_intersection::apply ( "case_66_multi", 1, 1, case_66_multi[0], case_66_multi[1] ); test_traverse_intersection::apply ( "case_67_multi", 1, 1, case_67_multi[0], case_67_multi[1] ); test_traverse_intersection::apply ( "case_69_multi", 1, 1, case_69_multi[0], case_69_multi[1] ); test_traverse_intersection::apply ( "case_71_multi", 2, 2, case_71_multi[0], case_71_multi[1] ); // #72, note that it intersects into 2 shapes, // the third one is done by assemble (see intersection #72) test_traverse_intersection::apply ( "case_72_multi", 2, 1.35, case_72_multi[0], case_72_multi[1] ); test_traverse_intersection::apply ( "case_73_multi", 2, 2, case_73_multi[0], case_73_multi[1] ); test_traverse_intersection::apply ( "case_74_multi", 2, 3, case_74_multi[0], case_74_multi[1] ); test_traverse_intersection::apply ( "case_75_multi", 1, 1, case_75_multi[0], case_75_multi[1] ); test_traverse_intersection::apply ( "case_77_multi", 5, 9, case_77_multi[0], case_77_multi[1] ); test_traverse_intersection::apply ( "case_78_multi", 2, 22, // Went from 3 to 2 by get_turns / partition case_78_multi[0], case_78_multi[1] ); test_traverse_intersection::apply ( "case_80_multi", 1, 0.5, case_80_multi[0], case_80_multi[1] ); test_traverse_intersection::apply ( "case_81_multi", 1, 0.25, case_81_multi[0], case_81_multi[1] ); test_traverse_intersection::apply ( "case_83_multi", 3, 1.25, case_83_multi[0], case_83_multi[1] ); test_traverse_intersection::apply ( "case_91_multi", 2, 1.0, case_91_multi[0], case_91_multi[1] ); test_traverse_intersection::apply ( "case_92_multi", 3, 1.5, case_92_multi[0], case_92_multi[1] ); test_traverse_intersection::apply ( "case_93_multi", 2, 1.25, case_93_multi[0], case_93_multi[1] ); test_traverse_intersection::apply ( "case_96_multi", 1, 0.5, case_96_multi[0], case_96_multi[1] ); test_traverse_intersection::apply ( "case_98_multi", 4, 3.0, case_98_multi[0], case_98_multi[1] ); test_traverse_intersection::apply ( "case_99_multi", 3, 1.75, case_99_multi[0], case_99_multi[1] ); test_traverse_intersection::apply ( "case_100_multi", 2, 1.5, case_100_multi[0], case_100_multi[1] ); test_traverse_intersection::apply ( "case_recursive_boxes_2", 1, 91, case_recursive_boxes_2[0], case_recursive_boxes_2[1] ); test_traverse_intersection::apply ( "case_107_multi", 2, 1.5, case_107_multi[0], case_107_multi[1] ); test_traverse_intersection::apply ( "case_recursive_boxes_3", 19, 12.5, case_recursive_boxes_3[0], case_recursive_boxes_3[1] ); // Unions test_traverse_union::apply ( "simplex", 1, 14.58, case_multi_simplex[0], case_multi_simplex[1] ); test_traverse_union::apply ( "case_61_multi", 1, 4, case_61_multi[0], case_61_multi[1] ); test_traverse_union::apply ( "case_62_multi", 1, 1 /*UU 2, 2 */, case_62_multi[0], case_62_multi[1] ); test_traverse_union::apply ( "case_63_multi", 1, 1 /*UU 2, 2 */, case_63_multi[0], case_63_multi[1] ); test_traverse_union::apply ( "case_64_multi", 1, 3, case_64_multi[0], case_64_multi[1] ); test_traverse_union::apply ( "case_66_multi", 1, 4 /*UU 3, 7 */, case_66_multi[0], case_66_multi[1] ); test_traverse_union::apply ( "case_68_multi", 1, 4 /*UU 2, 5 */, case_68_multi[0], case_68_multi[1] ); // 71: single-polygon generates 2 shapes, multi-polygon // generates 1 shape, both are self-tangent and OK test_traverse_union::apply ( "case_71_multi", 1, 9, case_71_multi[0], case_71_multi[1] ); test_traverse_union::apply ( "case_72_multi", 1, 10.65, case_72_multi[0], case_72_multi[1] ); test_traverse_union::apply ( "case_73_multi", 1, 3, case_73_multi[0], case_73_multi[1] ); test_traverse_union::apply ( "case_74_multi", 2, 17, case_74_multi[0], case_74_multi[1] ); test_traverse_union::apply ( "case_75_multi", 1, 1 /*UU 5, 5 */, case_75_multi[0], case_75_multi[1] ); test_traverse_union::apply ( "case_76_multi", 2, 5 /*UU 6, 6 */, case_76_multi[0], case_76_multi[1] ); test_traverse_union::apply ( "case_80_multi", 1, 9.25, case_80_multi[0], case_80_multi[1] ); test_traverse_union::apply ( "case_81_multi", 1, 3.25, case_81_multi[0], case_81_multi[1] ); test_traverse_union::apply ( "case_82_multi", 3, 4, case_82_multi[0], case_82_multi[1] ); test_traverse_union::apply ( "case_84_multi", 1, 4, case_84_multi[0], case_84_multi[1] ); test_traverse_union::apply ( "case_85_multi", 1, 3.5, case_85_multi[0], case_85_multi[1] ); test_traverse_union::apply ( "case_86_multi", 1, 4, case_86_multi[0], case_86_multi[1] ); test_traverse_union::apply ( "case_87_multi", 1, 6, case_87_multi[0], case_87_multi[1] ); test_traverse_union::apply ( "case_88_multi", 2, 4, case_88_multi[0], case_88_multi[1] ); test_traverse_union::apply ( "case_89_multi", 1, 6, case_89_multi[0], case_89_multi[1] ); test_traverse_union::apply ( "case_90_multi", 1, 7.5, case_90_multi[0], case_90_multi[1] ); test_traverse_union::apply ( "case_92_multi", 2, 6.25, case_92_multi[0], case_92_multi[1] ); test_traverse_union::apply ( "case_94_multi", 1, 10.0, case_94_multi[0], case_94_multi[1] ); test_traverse_union::apply ( "case_95_multi", 2, 6.5, case_95_multi[0], case_95_multi[1] ); test_traverse_union::apply ( "case_96_multi", 1, 3.5, case_96_multi[0], case_96_multi[1] ); test_traverse_union::apply ( "case_97_multi", 1, 3.75, case_97_multi[0], case_97_multi[1] ); test_traverse_union::apply ( "case_101_multi", 1, 22.25, case_101_multi[0], case_101_multi[1] ); test_traverse_union::apply ( "case_102_multi", 3, 24.25, case_102_multi[0], case_102_multi[1] ); test_traverse_union::apply ( "case_103_multi", 1, 25, case_103_multi[0], case_103_multi[1] ); test_traverse_union::apply ( "case_104_multi", 1, 25, case_104_multi[0], case_104_multi[1] ); test_traverse_union::apply ( "case_105_multi", 1, 25, case_105_multi[0], case_105_multi[1] ); test_traverse_union::apply ( "case_106_multi", 1, 25, case_106_multi[0], case_106_multi[1] ); test_traverse_union::apply ( "case_recursive_boxes_1", 2, 97, case_recursive_boxes_1[0], case_recursive_boxes_1[1] ); test_traverse_union::apply ( "case_recursive_boxes_3", 7, 49.5, case_recursive_boxes_3[0], case_recursive_boxes_3[1] ); test_traverse_intersection::apply ( "pie_21_7_21_0_3", 2, 818824.56678, pie_21_7_21_0_3[0], pie_21_7_21_0_3[1] ); test_traverse_intersection::apply ( "pie_23_19_5_0_2", 2, 2948602.3911823, pie_23_19_5_0_2[0], pie_23_19_5_0_2[1] ); test_traverse_intersection::apply ( "pie_7_14_5_0_7", 2, 490804.56678, pie_7_14_5_0_7[0], pie_7_14_5_0_7[1] ); test_traverse_intersection::apply ( "pie_16_16_9_0_2", 2, 1146795, pie_16_16_9_0_2[0], pie_16_16_9_0_2[1] ); test_traverse_intersection::apply ( "pie_7_2_1_0_15", 2, 490585.5, pie_7_2_1_0_15[0], pie_7_2_1_0_15[1] ); } template <typename T> void test_all() { typedef bg::model::point<T, 2, bg::cs::cartesian> point_type; typedef bg::model::multi_polygon < bg::model::polygon<point_type> > multi_polygon; typedef bg::model::multi_polygon < bg::model::polygon<point_type, false> > multi_polygon_ccw; test_geometries<multi_polygon, false>(); test_geometries<multi_polygon_ccw, true>(); } int test_main(int, char* []) { test_all<double>(); return 0; }
27.061135
80
0.562127
[ "geometry", "shape", "model" ]
4f4704871b39f21cddb52d0b4da2a37c20a50bbb
27,451
cpp
C++
editor/editor_help_search.cpp
ZopharShinta/SegsEngine
86d52c5b805e05e107594efd3358cabd694365f0
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
editor/editor_help_search.cpp
ZopharShinta/SegsEngine
86d52c5b805e05e107594efd3358cabd694365f0
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
editor/editor_help_search.cpp
ZopharShinta/SegsEngine
86d52c5b805e05e107594efd3358cabd694365f0
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
/*************************************************************************/ /* editor_help_search.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "editor_feature_profile.h" #include "editor_help_search.h" #include "core/callable_method_pointer.h" #include "core/doc_support/doc_data.h" #include "core/method_bind.h" #include "core/os/keyboard.h" #include "editor/editor_scale.h" #include "editor_node.h" IMPL_GDCLASS(EditorHelpSearch) class EditorHelpSearch::Runner : public RefCounted { enum Phase { PHASE_MATCH_CLASSES_INIT, PHASE_MATCH_CLASSES, PHASE_CLASS_ITEMS_INIT, PHASE_CLASS_ITEMS, PHASE_MEMBER_ITEMS_INIT, PHASE_MEMBER_ITEMS, PHASE_SELECT_MATCH, PHASE_MAX }; struct ClassMatch { DocContents::ClassDoc *doc; bool name; Vector<DocContents::MethodDoc *> methods; Vector<DocContents::MethodDoc *> defined_signals; Vector<DocContents::ConstantDoc *> constants; Vector<DocContents::PropertyDoc *> properties; Vector<DocContents::PropertyDoc *> theme_properties; bool required() { return name || !methods.empty() || !defined_signals.empty() || !constants.empty() || !properties.empty() || !theme_properties.empty(); } }; HashMap<String, ClassMatch> matches; HashMap<String, TreeItem *> class_items; Control *ui_service; Tree *results_tree; String term; Ref<Texture> empty_icon; int search_flags; int phase; Color disabled_color; HashMap<String, DocContents::ClassDoc>::iterator iterator_doc; //HashMap<StringName, DocContents::ClassDoc>::iterator iterator_doc; HashMap<String, ClassMatch>::iterator iterator_match; TreeItem *root_item; TreeItem *matched_item; bool _is_class_disabled_by_feature_profile(const String &p_class); bool _slice(); bool _phase_match_classes_init(); bool _phase_match_classes(); bool _phase_class_items_init(); bool _phase_class_items(); bool _phase_member_items_init(); bool _phase_member_items(); bool _phase_select_match(); bool _match_string(const String &p_term, const String &p_string) const; void _match_item(TreeItem *p_item, StringView p_text); TreeItem *_create_class_hierarchy(const ClassMatch &p_match); TreeItem *_create_class_item(TreeItem *p_parent, const DocContents::ClassDoc *p_doc, bool p_gray); TreeItem *_create_method_item(TreeItem *p_parent, const DocContents::ClassDoc *p_class_doc, const DocContents::MethodDoc *p_doc); TreeItem *_create_signal_item(TreeItem *p_parent, const DocContents::ClassDoc *p_class_doc, const DocContents::MethodDoc *p_doc); TreeItem *_create_constant_item(TreeItem *p_parent, const DocContents::ClassDoc *p_class_doc, const DocContents::ConstantDoc *p_doc); TreeItem *_create_property_item(TreeItem *p_parent, const DocContents::ClassDoc *p_class_doc, const DocContents::PropertyDoc *p_doc); TreeItem *_create_theme_property_item(TreeItem *p_parent, const DocContents::ClassDoc *p_class_doc, const DocContents::PropertyDoc *p_doc); TreeItem *_create_member_item(TreeItem *p_parent, const StringName &p_class_name, StringView p_icon, const String &p_name, StringView p_type, StringView p_metatype, StringView p_tooltip); public: bool work(uint64_t slot = 100000); Runner(Control *p_icon_service, Tree *p_results_tree, StringView p_term, int p_search_flags); }; void EditorHelpSearch::_update_icons() { search_box->set_right_icon(get_icon("Search", "EditorIcons")); search_box->set_clear_button_enabled(true); search_box->add_icon_override("right_icon", get_icon("Search", "EditorIcons")); case_sensitive_button->set_button_icon(get_icon("MatchCase", "EditorIcons")); hierarchy_button->set_button_icon(get_icon("ClassList", "EditorIcons")); if (is_visible_in_tree()) _update_results(); } void EditorHelpSearch::_update_results() { String term = search_box->get_text(); int search_flags = filter_combo->get_selected_id(); if (case_sensitive_button->is_pressed()) search_flags |= SEARCH_CASE_SENSITIVE; if (hierarchy_button->is_pressed()) search_flags |= SEARCH_SHOW_HIERARCHY; search = make_ref_counted<Runner>(this, results_tree, term, search_flags); set_process(true); } void EditorHelpSearch::_search_box_gui_input(const Ref<InputEvent> &p_event) { // Redirect up and down navigational key events to the results list. Ref<InputEventKey> key = dynamic_ref_cast<InputEventKey>(p_event); if (key) { switch (key->get_keycode()) { case KEY_UP: case KEY_DOWN: case KEY_PAGEUP: case KEY_PAGEDOWN: { results_tree->call_va("_gui_input", key); search_box->accept_event(); } break; } } } void EditorHelpSearch::_search_box_text_changed(StringView p_text) { _update_results(); } void EditorHelpSearch::_filter_combo_item_selected(int p_option) { _update_results(); } void EditorHelpSearch::_confirmed() { TreeItem *item = results_tree->get_selected(); if (!item) return; // Activate the script editor and emit the signal with the documentation link to display. EditorNode::get_singleton()->set_visible_editor(EditorNode::EDITOR_SCRIPT); emit_signal("go_to_help", item->get_metadata(0)); hide(); } void EditorHelpSearch::_notification(int p_what) { switch (p_what) { case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { _update_icons(); } break; case NOTIFICATION_ENTER_TREE: { connect("confirmed",callable_mp(this, &ClassName::_confirmed)); _update_icons(); } break; case NOTIFICATION_POPUP_HIDE: { results_tree->call_deferred("clear"); // Wait for the Tree's mouse event propagation. get_ok()->set_disabled(true); EditorSettings::get_singleton()->set_project_metadata("dialog_bounds", "search_help", get_rect()); } break; case NOTIFICATION_PROCESS: { // Update background search. if (search) { if (search->work()) { // Search done. // Only point to the perfect match if it's a new search, and not just reopening a old one. if (!old_search) results_tree->ensure_cursor_is_visible(); else old_search = false; get_ok()->set_disabled(!results_tree->get_selected()); search = Ref<Runner>(); set_process(false); } } else { set_process(false); } } break; } } void EditorHelpSearch::_bind_methods() { MethodBinder::bind_method(D_METHOD("_update_results"), &EditorHelpSearch::_update_results); MethodBinder::bind_method(D_METHOD("_search_box_gui_input"), &EditorHelpSearch::_search_box_gui_input); MethodBinder::bind_method(D_METHOD("_search_box_text_changed"), &EditorHelpSearch::_search_box_text_changed); MethodBinder::bind_method(D_METHOD("_filter_combo_item_selected"), &EditorHelpSearch::_filter_combo_item_selected); MethodBinder::bind_method(D_METHOD("_confirmed"), &EditorHelpSearch::_confirmed); ADD_SIGNAL(MethodInfo("go_to_help")); } void EditorHelpSearch::popup_dialog() { popup_dialog(search_box->get_text()); } void EditorHelpSearch::popup_dialog(StringView p_term) { // Restore valid window bounds or pop up at default size. Rect2 saved_size = EditorSettings::get_singleton()->get_project_metadataT("dialog_bounds", "search_help", Rect2()); if (saved_size != Rect2()) popup(saved_size); else popup_centered_ratio(0.5F); if (p_term.empty()) { search_box->clear(); } else { if (old_term == p_term) old_search = true; else old_term = p_term; search_box->set_text(p_term); search_box->select_all(); } search_box->grab_focus(); _update_results(); } EditorHelpSearch::EditorHelpSearch() { old_search = false; set_hide_on_ok(false); set_resizable(true); set_title(TTR("Search Help")); get_ok()->set_disabled(true); get_ok()->set_text(TTR("Open")); // Split search and results area. VBoxContainer *vbox = memnew(VBoxContainer); add_child(vbox); // Create the search box and filter controls (at the top). HBoxContainer *hbox = memnew(HBoxContainer); vbox->add_child(hbox); search_box = memnew(LineEdit); search_box->set_custom_minimum_size(Size2(200, 0) * EDSCALE); search_box->set_h_size_flags(SIZE_EXPAND_FILL); search_box->connect("gui_input",callable_mp(this, &ClassName::_search_box_gui_input)); search_box->connect("text_changed",callable_mp(this, &ClassName::_search_box_text_changed)); register_text_enter(search_box); hbox->add_child(search_box); case_sensitive_button = memnew(ToolButton); case_sensitive_button->set_tooltip("Case Sensitive"); case_sensitive_button->connect("pressed",callable_mp(this, &ClassName::_update_results)); case_sensitive_button->set_toggle_mode(true); case_sensitive_button->set_focus_mode(FOCUS_NONE); hbox->add_child(case_sensitive_button); hierarchy_button = memnew(ToolButton); hierarchy_button->set_tooltip("Show Hierarchy"); hierarchy_button->connect("pressed",callable_mp(this, &ClassName::_update_results)); hierarchy_button->set_toggle_mode(true); hierarchy_button->set_pressed(true); hierarchy_button->set_focus_mode(FOCUS_NONE); hbox->add_child(hierarchy_button); filter_combo = memnew(OptionButton); filter_combo->set_custom_minimum_size(Size2(200, 0) * EDSCALE); filter_combo->set_stretch_ratio(0); // Fixed width. filter_combo->add_item(TTR("Display All"), SEARCH_FLAG_ALL); filter_combo->add_separator(); filter_combo->add_item(TTR("Classes Only"), SEARCH_CLASSES); filter_combo->add_item(TTR("Methods Only"), SEARCH_METHODS); filter_combo->add_item(TTR("Signals Only"), SEARCH_SIGNALS); filter_combo->add_item(TTR("Constants Only"), SEARCH_CONSTANTS); filter_combo->add_item(TTR("Properties Only"), SEARCH_PROPERTIES); filter_combo->add_item(TTR("Theme Properties Only"), SEARCH_THEME_ITEMS); filter_combo->connect("item_selected",callable_mp(this, &ClassName::_filter_combo_item_selected)); hbox->add_child(filter_combo); // Create the results tree. results_tree = memnew(Tree); results_tree->set_v_size_flags(SIZE_EXPAND_FILL); results_tree->set_columns(2); results_tree->set_column_title(0, TTR("Name")); results_tree->set_column_title(1, TTR("Member Type")); results_tree->set_column_expand(1, false); results_tree->set_column_min_width(1, 150 * EDSCALE); results_tree->set_custom_minimum_size(Size2(0, 100) * EDSCALE); results_tree->set_hide_root(true); results_tree->set_select_mode(Tree::SELECT_ROW); results_tree->connect("item_activated",callable_mp(this, &ClassName::_confirmed)); results_tree->connect("item_selected", callable_mp((BaseButton *)get_ok(), &BaseButton::set_disabled), varray(false)); vbox->add_child(results_tree, true); } bool EditorHelpSearch::Runner::_is_class_disabled_by_feature_profile(const String &p_class) { Ref<EditorFeatureProfile> profile = EditorFeatureProfileManager::get_singleton()->get_current_profile(); if (not profile) { return false; } StringName class_name((p_class)); while (class_name != StringName()) { if (!ClassDB::class_exists(class_name)) { return false; } if (profile->is_class_disabled(class_name)) { return true; } class_name = ClassDB::get_parent_class(class_name); } return false; } bool EditorHelpSearch::Runner::_slice() { bool phase_done = false; switch (phase) { case PHASE_MATCH_CLASSES_INIT: phase_done = _phase_match_classes_init(); break; case PHASE_MATCH_CLASSES: phase_done = _phase_match_classes(); break; case PHASE_CLASS_ITEMS_INIT: phase_done = _phase_class_items_init(); break; case PHASE_CLASS_ITEMS: phase_done = _phase_class_items(); break; case PHASE_MEMBER_ITEMS_INIT: phase_done = _phase_member_items_init(); break; case PHASE_MEMBER_ITEMS: phase_done = _phase_member_items(); break; case PHASE_SELECT_MATCH: phase_done = _phase_select_match(); break; case PHASE_MAX: return true; default: WARN_PRINT("Invalid or unhandled phase in EditorHelpSearch::Runner, aborting search."); return true; } if (phase_done) phase++; return false; } bool EditorHelpSearch::Runner::_phase_match_classes_init() { iterator_doc = EditorHelp::get_doc_data()->class_list.begin(); matches.clear(); matched_item = nullptr; return true; } bool EditorHelpSearch::Runner::_phase_match_classes() { using namespace StringUtils; DocContents::ClassDoc &class_doc = iterator_doc->second; if (!_is_class_disabled_by_feature_profile(class_doc.name)) { matches[class_doc.name] = ClassMatch(); ClassMatch &match = matches[class_doc.name]; match.doc = &class_doc; // Match class name. if (search_flags & SEARCH_CLASSES) match.name = term.empty() || _match_string(term, class_doc.name); // Match members if the term is long enough. if (term.length() > 1) { if (search_flags & SEARCH_METHODS) { for (int i = 0; i < class_doc.methods.size(); i++) { String method_name = (search_flags & SEARCH_CASE_SENSITIVE) ? class_doc.methods[i].name : class_doc.methods[i].name.to_lower(); if (method_name.contains(term) || (term.starts_with(".") && method_name.starts_with(term.right(1))) || (term.ends_with("(") && method_name.ends_with(strip_edges(term.left(term.length() - 1)))) || (term.starts_with(".") && term.ends_with("(") && method_name == strip_edges(term.substr(1, term.length() - 2)))) { match.methods.push_back(const_cast<DocContents::MethodDoc *>(&class_doc.methods[i])); } } } if (search_flags & SEARCH_SIGNALS) for (int i = 0; i < class_doc.defined_signals.size(); i++) if (_match_string(term, class_doc.defined_signals[i].name)) match.defined_signals.push_back(const_cast<DocContents::MethodDoc *>(&class_doc.defined_signals[i])); if (search_flags & SEARCH_CONSTANTS) for (int i = 0; i < class_doc.constants.size(); i++) if (_match_string(term, class_doc.constants[i].name)) match.constants.push_back(const_cast<DocContents::ConstantDoc *>(&class_doc.constants[i])); if (search_flags & SEARCH_PROPERTIES) for (int i = 0; i < class_doc.properties.size(); i++) if (_match_string(term, class_doc.properties[i].name) || _match_string(term, class_doc.properties[i].getter) || _match_string(term, class_doc.properties[i].setter)) match.properties.push_back(const_cast<DocContents::PropertyDoc *>(&class_doc.properties[i])); if (search_flags & SEARCH_THEME_ITEMS) for (int i = 0; i < class_doc.theme_properties.size(); i++) if (_match_string(term, class_doc.theme_properties[i].name)) match.theme_properties.push_back(const_cast<DocContents::PropertyDoc *>(&class_doc.theme_properties[i])); } } ++iterator_doc; return iterator_doc==EditorHelp::get_doc_data()->class_list.end(); } bool EditorHelpSearch::Runner::_phase_class_items_init() { iterator_match = matches.begin(); results_tree->clear(); root_item = results_tree->create_item(); class_items.clear(); return true; } bool EditorHelpSearch::Runner::_phase_class_items() { ClassMatch &match = iterator_match->second; if (search_flags & SEARCH_SHOW_HIERARCHY) { if (match.required()) _create_class_hierarchy(match); } else { if (match.name) _create_class_item(root_item, match.doc, false); } ++iterator_match; return iterator_match==matches.end(); } bool EditorHelpSearch::Runner::_phase_member_items_init() { iterator_match = matches.begin(); return true; } bool EditorHelpSearch::Runner::_phase_member_items() { ClassMatch &match = iterator_match->second; TreeItem *parent = search_flags & SEARCH_SHOW_HIERARCHY ? class_items[match.doc->name] : root_item; for (int i = 0; i < match.methods.size(); i++) _create_method_item(parent, match.doc, match.methods[i]); for (int i = 0; i < match.defined_signals.size(); i++) _create_signal_item(parent, match.doc, match.defined_signals[i]); for (int i = 0; i < match.constants.size(); i++) _create_constant_item(parent, match.doc, match.constants[i]); for (int i = 0; i < match.properties.size(); i++) _create_property_item(parent, match.doc, match.properties[i]); for (int i = 0; i < match.theme_properties.size(); i++) _create_theme_property_item(parent, match.doc, match.theme_properties[i]); ++iterator_match; return iterator_match==matches.end(); } bool EditorHelpSearch::Runner::_phase_select_match() { if (matched_item) matched_item->select(0); return true; } bool EditorHelpSearch::Runner::_match_string(const String &p_term, const String &p_string) const { return p_string.contains(p_term,search_flags & SEARCH_CASE_SENSITIVE); } void EditorHelpSearch::Runner::_match_item(TreeItem *p_item, StringView p_text) { if (!matched_item) { if (search_flags & SEARCH_CASE_SENSITIVE) { if ((term)==p_text) matched_item = p_item; } else { if (StringUtils::compare(term,p_text,StringUtils::CaseInsensitive) == 0) matched_item = p_item; } } } TreeItem *EditorHelpSearch::Runner::_create_class_hierarchy(const ClassMatch &p_match) { if (class_items.contains(p_match.doc->name)) return class_items[p_match.doc->name]; // Ensure parent nodes are created first. TreeItem *parent = root_item; if (!p_match.doc->inherits.empty()) { if (class_items.contains(p_match.doc->inherits)) { parent = class_items[p_match.doc->inherits]; } else { ClassMatch &base_match = matches[p_match.doc->inherits]; parent = _create_class_hierarchy(base_match); } } TreeItem *class_item = _create_class_item(parent, p_match.doc, !p_match.name); class_items[p_match.doc->name] = class_item; return class_item; } TreeItem *EditorHelpSearch::Runner::_create_class_item(TreeItem *p_parent, const DocContents::ClassDoc *p_doc, bool p_gray) { StringName snn((p_doc->name)); Ref<Texture> icon = empty_icon; if (ui_service->has_icon(snn, "EditorIcons")) icon = ui_service->get_icon(snn, "EditorIcons"); else if (ClassDB::class_exists(snn) && ClassDB::is_parent_class(snn, "Object")) icon = ui_service->get_icon("Object", "EditorIcons"); StringName tooltip(StringUtils::strip_edges(StringView((p_doc->brief_description)))); TreeItem *item = results_tree->create_item(p_parent); item->set_icon(0, icon); item->set_text(0, snn); item->set_text(1, TTR("Class")); item->set_tooltip(0, tooltip); item->set_tooltip(1, tooltip); item->set_metadata(0, String("class_name:") + snn.asCString()); if (p_gray) { item->set_custom_color(0, disabled_color); item->set_custom_color(1, disabled_color); } _match_item(item, snn); return item; } TreeItem *EditorHelpSearch::Runner::_create_method_item(TreeItem *p_parent, const DocContents::ClassDoc *p_class_doc, const DocContents::MethodDoc *p_doc) { String tooltip = p_doc->return_type + " " + p_class_doc->name + "." + p_doc->name + "("; for (int i = 0; i < p_doc->arguments.size(); i++) { const DocContents::ArgumentDoc &arg = p_doc->arguments[i]; tooltip += arg.type + " " + arg.name; if (!arg.default_value.empty()) tooltip += " = " + arg.default_value; if (i < p_doc->arguments.size() - 1) tooltip += ", "; } tooltip += ')'; return _create_member_item(p_parent, StringName(p_class_doc->name), "MemberMethod", p_doc->name, "Method", "method", tooltip); } TreeItem *EditorHelpSearch::Runner::_create_signal_item(TreeItem *p_parent, const DocContents::ClassDoc *p_class_doc, const DocContents::MethodDoc *p_doc) { String tooltip = p_doc->return_type + " " + p_class_doc->name + "." + p_doc->name + "("; for (int i = 0; i < p_doc->arguments.size(); i++) { const DocContents::ArgumentDoc &arg = p_doc->arguments[i]; tooltip += arg.type + " " + arg.name; if (!arg.default_value.empty()) tooltip += " = " + arg.default_value; if (i < p_doc->arguments.size() - 1) tooltip += ", "; } tooltip += ')'; return _create_member_item(p_parent, StringName((p_class_doc->name)), "MemberSignal", (p_doc->name), "Signal", "signal", (tooltip)); } TreeItem *EditorHelpSearch::Runner::_create_constant_item(TreeItem *p_parent, const DocContents::ClassDoc *p_class_doc, const DocContents::ConstantDoc *p_doc) { String tooltip = p_class_doc->name + "." + p_doc->name; return _create_member_item(p_parent, StringName((p_class_doc->name)), "MemberConstant", (p_doc->name), "Constant", "constant", (tooltip)); } TreeItem *EditorHelpSearch::Runner::_create_property_item(TreeItem *p_parent, const DocContents::ClassDoc *p_class_doc, const DocContents::PropertyDoc *p_doc) { String tooltip = p_doc->type+ " " + p_class_doc->name + "." + p_doc->name; tooltip += "\n " + p_class_doc->name + "." + p_doc->setter + "(value) setter"; tooltip += "\n " + p_class_doc->name + "." + p_doc->getter + "() getter"; return _create_member_item(p_parent, StringName((p_class_doc->name)), "MemberProperty", (p_doc->name), "Property", "property", (tooltip)); } TreeItem *EditorHelpSearch::Runner::_create_theme_property_item(TreeItem *p_parent, const DocContents::ClassDoc *p_class_doc, const DocContents::PropertyDoc *p_doc) { String tooltip = p_doc->type + " " + p_class_doc->name + "." + p_doc->name; return _create_member_item(p_parent, StringName((p_class_doc->name)), "MemberTheme", (p_doc->name), "Theme Property", "theme_item", (tooltip)); } TreeItem *EditorHelpSearch::Runner::_create_member_item(TreeItem *p_parent, const StringName &p_class_name, StringView p_icon, const String &p_name, StringView p_type, StringView p_metatype, StringView p_tooltip) { Ref<Texture> icon; String text; if (search_flags & SEARCH_SHOW_HIERARCHY) { icon = ui_service->get_icon(StringName(p_icon), "EditorIcons"); text = p_name; } else { icon = ui_service->get_icon(StringName(p_icon), "EditorIcons"); /*// In flat mode, show the class icon. if (ui_service->has_icon(p_class_name, "EditorIcons")) icon = ui_service->get_icon(p_class_name, "EditorIcons"); else if (ClassDB::is_parent_class(p_class_name, "Object")) icon = ui_service->get_icon("Object", "EditorIcons");*/ text = String(p_class_name) + "." + p_name; } TreeItem *item = results_tree->create_item(p_parent); item->set_icon(0, icon); item->set_text_utf8(0, text); item->set_text(1, TTR(p_type)); item->set_tooltip(0, StringName(p_tooltip)); item->set_tooltip(1, StringName(p_tooltip)); item->set_metadata(0, String("class_") + p_metatype + ":" + p_class_name + ":" + p_name); _match_item(item, p_name); return item; } bool EditorHelpSearch::Runner::work(uint64_t slot) { // Return true when the search has been completed, otherwise false. const uint64_t until = OS::get_singleton()->get_ticks_usec() + slot; while (!_slice()) if (OS::get_singleton()->get_ticks_usec() > until) return false; return true; } EditorHelpSearch::Runner::Runner(Control *p_icon_service, Tree *p_results_tree, StringView p_term, int p_search_flags) : ui_service(p_icon_service), results_tree(p_results_tree), empty_icon(ui_service->get_icon("ArrowRight", "EditorIcons")), search_flags(p_search_flags), phase(0), disabled_color(ui_service->get_color("disabled_font_color", "Editor")) { term = (p_search_flags & SEARCH_CASE_SENSITIVE) == 0 ? StringUtils::to_lower(String(p_term).trimmed()) : String(p_term).trimmed(); }
39.726483
191
0.647663
[ "object", "vector" ]
4f4883baf960924352bf4e8e7d3e748c5e785b0b
26,619
cpp
C++
pxr/imaging/lib/hdSt/vboMemoryManager.cpp
navefx/YuksUSD
56c2e1def36ee07121f4ecb349c1626472b3c338
[ "AML" ]
6
2018-08-26T13:27:22.000Z
2021-08-14T23:57:38.000Z
pxr/imaging/lib/hdSt/vboMemoryManager.cpp
navefx/YuksUSD
56c2e1def36ee07121f4ecb349c1626472b3c338
[ "AML" ]
1
2021-08-14T23:57:51.000Z
2021-08-14T23:57:51.000Z
pxr/imaging/lib/hdSt/vboMemoryManager.cpp
navefx/YuksUSD
56c2e1def36ee07121f4ecb349c1626472b3c338
[ "AML" ]
4
2018-06-14T18:14:59.000Z
2021-09-13T22:20:50.000Z
// // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "pxr/imaging/glf/glew.h" #include "pxr/imaging/glf/contextCaps.h" #include "pxr/imaging/glf/diagnostic.h" #include <boost/make_shared.hpp> #include <vector> #include "pxr/base/arch/hash.h" #include "pxr/base/tf/diagnostic.h" #include "pxr/base/tf/envSetting.h" #include "pxr/base/tf/iterator.h" #include "pxr/base/tf/enum.h" #include "pxr/imaging/hdSt/bufferResourceGL.h" #include "pxr/imaging/hdSt/glUtils.h" #include "pxr/imaging/hdSt/vboMemoryManager.h" #include "pxr/imaging/hdSt/glConversions.h" #include "pxr/imaging/hd/perfLog.h" #include "pxr/imaging/hd/tokens.h" #include "pxr/imaging/hf/perfLog.h" PXR_NAMESPACE_OPEN_SCOPE TF_DEFINE_ENV_SETTING(HD_MAX_VBO_SIZE, (1*1024*1024*1024), "Maximum aggregated VBO size"); // --------------------------------------------------------------------------- // HdStVBOMemoryManager // --------------------------------------------------------------------------- HdBufferArraySharedPtr HdStVBOMemoryManager::CreateBufferArray( TfToken const &role, HdBufferSpecVector const &bufferSpecs) { return boost::make_shared<HdStVBOMemoryManager::_StripedBufferArray>( role, bufferSpecs, _isImmutable); } HdBufferArrayRangeSharedPtr HdStVBOMemoryManager::CreateBufferArrayRange() { return boost::make_shared<_StripedBufferArrayRange>(); } HdAggregationStrategy::AggregationId HdStVBOMemoryManager::ComputeAggregationId(HdBufferSpecVector const &bufferSpecs) const { static size_t salt = ArchHash(__FUNCTION__, sizeof(__FUNCTION__)); size_t result = salt; for (HdBufferSpec const &spec : bufferSpecs) { size_t const params[] = { spec.name.Hash(), (size_t) spec.tupleType.type, spec.tupleType.count }; boost::hash_combine(result, ArchHash((char const*)params, sizeof(size_t) * 3)); } // promote to size_t return (AggregationId)result; } /// Returns the buffer specs from a given buffer array HdBufferSpecVector HdStVBOMemoryManager::GetBufferSpecs( HdBufferArraySharedPtr const &bufferArray) const { _StripedBufferArraySharedPtr bufferArray_ = boost::static_pointer_cast<_StripedBufferArray> (bufferArray); return bufferArray_->GetBufferSpecs(); } /// Returns the size of the GPU memory used by the passed buffer array size_t HdStVBOMemoryManager::GetResourceAllocation( HdBufferArraySharedPtr const &bufferArray, VtDictionary &result) const { std::set<GLuint> idSet; size_t gpuMemoryUsed = 0; _StripedBufferArraySharedPtr bufferArray_ = boost::static_pointer_cast<_StripedBufferArray> (bufferArray); TF_FOR_ALL(resIt, bufferArray_->GetResources()) { HdStBufferResourceGLSharedPtr const & resource = resIt->second; // XXX avoid double counting of resources shared within a buffer GLuint id = resource->GetId(); if (idSet.count(id) == 0) { idSet.insert(id); std::string const & role = resource->GetRole().GetString(); size_t size = size_t(resource->GetSize()); if (result.count(role)) { size_t currentSize = result[role].Get<size_t>(); result[role] = VtValue(currentSize + size); } else { result[role] = VtValue(size); } gpuMemoryUsed += size; } } return gpuMemoryUsed; } // --------------------------------------------------------------------------- // _StripedBufferArray // --------------------------------------------------------------------------- HdStVBOMemoryManager::_StripedBufferArray::_StripedBufferArray( TfToken const &role, HdBufferSpecVector const &bufferSpecs, bool isImmutable) : HdBufferArray(role, HdPerfTokens->garbageCollectedVbo, isImmutable), _needsCompaction(false), _totalCapacity(0), _maxBytesPerElement(0) { HD_TRACE_FUNCTION(); HF_MALLOC_TAG_FUNCTION(); /* non-interleaved non-uniform buffer array (for example) .------------------------------------------------------. vec3 | pos.x (prim0) || pos.x (prim1) || ... | | y || y || | | z || z || | '------------------------------------------------------' .------------------------------------------------------. vec4 | color.r (prim0) || color.r (prim1) || ... | | g || g || | | b || b || | | a || a || | '------------------------------------------------------' ^--range0.numElements--^^--range1.numElements--^ | ^-^ ^--range1.offset stride */ // populate BufferResources TF_FOR_ALL(it, bufferSpecs) { int stride = HdDataSizeOfTupleType(it->tupleType); _AddResource(it->name, it->tupleType, /*offset*/0, stride); } // VBO Memory Manage supports an effectivly limitless set of ranges _SetMaxNumRanges(std::numeric_limits<size_t>::max()); // compute max bytes / elements TF_FOR_ALL (it, GetResources()) { _maxBytesPerElement = std::max( _maxBytesPerElement, HdDataSizeOfTupleType(it->second->GetTupleType())); } // GetMaxNumElements() will crash with a divide by 0 // error if _maxBytesPerElement is 0. // // This can happen if bufferSpecs was empty and thus // no resources were added. If means something went // wrong earlier and we are just trying to survive. if (!TF_VERIFY(_maxBytesPerElement != 0)) { _maxBytesPerElement = 1; } } HdStBufferResourceGLSharedPtr HdStVBOMemoryManager::_StripedBufferArray::_AddResource(TfToken const& name, HdTupleType tupleType, int offset, int stride) { HD_TRACE_FUNCTION(); if (TfDebug::IsEnabled(HD_SAFE_MODE)) { // duplication check HdStBufferResourceGLSharedPtr bufferRes = GetResource(name); if (!TF_VERIFY(!bufferRes)) { return bufferRes; } } HdStBufferResourceGLSharedPtr bufferRes = HdStBufferResourceGLSharedPtr( new HdStBufferResourceGL(GetRole(), tupleType, offset, stride)); _resourceList.emplace_back(name, bufferRes); return bufferRes; } HdStVBOMemoryManager::_StripedBufferArray::~_StripedBufferArray() { HD_TRACE_FUNCTION(); HF_MALLOC_TAG_FUNCTION(); // invalidate buffer array ranges in range list // (these ranges may still be held by drawItems) size_t rangeCount = GetRangeCount(); for (size_t rangeIdx = 0; rangeIdx < rangeCount; ++rangeIdx) { _StripedBufferArrayRangeSharedPtr range = _GetRangeSharedPtr(rangeIdx); if (range) { range->Invalidate(); } } } bool HdStVBOMemoryManager::_StripedBufferArray::GarbageCollect() { HD_TRACE_FUNCTION(); HF_MALLOC_TAG_FUNCTION(); if (_needsCompaction) { RemoveUnusedRanges(); std::vector<HdBufferArrayRangeSharedPtr> ranges; size_t rangeCount = GetRangeCount(); ranges.reserve(rangeCount); for (size_t i = 0; i < rangeCount; ++i) { HdBufferArrayRangeSharedPtr range = GetRange(i).lock(); if (range) ranges.push_back(range); } Reallocate(ranges, shared_from_this()); } if (GetRangeCount() == 0) { _DeallocateResources(); return true; } return false; } void HdStVBOMemoryManager::_StripedBufferArray::Reallocate( std::vector<HdBufferArrayRangeSharedPtr> const &ranges, HdBufferArraySharedPtr const &curRangeOwner) { HD_TRACE_FUNCTION(); HF_MALLOC_TAG_FUNCTION(); // XXX: make sure glcontext GlfContextCaps const &caps = GlfContextCaps::GetInstance(); HD_PERF_COUNTER_INCR(HdPerfTokens->vboRelocated); _StripedBufferArraySharedPtr curRangeOwner_ = boost::static_pointer_cast<_StripedBufferArray> (curRangeOwner); if (!TF_VERIFY(GetResources().size() == curRangeOwner_->GetResources().size())) { TF_CODING_ERROR("Resource mismatch when reallocating buffer array"); return; } if (TfDebug::IsEnabled(HD_SAFE_MODE)) { HdStBufferResourceGLNamedList::size_type bresIdx = 0; TF_FOR_ALL(bresIt, GetResources()) { TF_VERIFY(curRangeOwner_->GetResources()[bresIdx++].second == curRangeOwner_->GetResource(bresIt->first)); } } GLF_GROUP_FUNCTION(); // count up total elements and update new offsets size_t totalNumElements = 0; std::vector<size_t> newOffsets; newOffsets.reserve(ranges.size()); TF_FOR_ALL (it, ranges) { HdBufferArrayRangeSharedPtr const &range = *it; if (!range) { TF_CODING_ERROR("Expired range found in the reallocation list"); continue; } // save new offset newOffsets.push_back(totalNumElements); // XXX: always tightly pack for now. totalNumElements += range->GetNumElements(); } // update range list (should be done before early exit) _SetRangeList(ranges); // If there is no data to reallocate, it is the caller's responsibility to // deallocate the underlying resource. // // XXX: There is an issue here if the caller does not deallocate // after this return, we will hold onto unused GPU resources until the next // reallocation. Perhaps we should free the buffer here to avoid that // situation. if (totalNumElements == 0) return; _totalCapacity = totalNumElements; // resize each BufferResource HdStBufferResourceGLNamedList const& resources = GetResources(); for (size_t bresIdx=0; bresIdx<resources.size(); ++bresIdx) { HdStBufferResourceGLSharedPtr const &bres = resources[bresIdx].second; HdStBufferResourceGLSharedPtr const &curRes = curRangeOwner_->GetResources()[bresIdx].second; int bytesPerElement = HdDataSizeOfTupleType(bres->GetTupleType()); TF_VERIFY(bytesPerElement > 0); GLsizeiptr bufferSize = bytesPerElement * _totalCapacity; // allocate new one // curId and oldId will be different when we are adopting ranges // from another buffer array. GLuint newId = 0; GLuint oldId = bres->GetId(); GLuint curId = curRes->GetId(); if (glGenBuffers) { glGenBuffers(1, &newId); if (ARCH_LIKELY(caps.directStateAccessEnabled)) { glNamedBufferDataEXT(newId, bufferSize, /*data=*/NULL, GL_STATIC_DRAW); } else { glBindBuffer(GL_ARRAY_BUFFER, newId); glBufferData(GL_ARRAY_BUFFER, bufferSize, /*data=*/NULL, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); } // if old buffer exists, copy unchanged data if (curId) { std::vector<size_t>::iterator newOffsetIt = newOffsets.begin(); // pre-pass to combine consecutive buffer range relocation HdStGLBufferRelocator relocator(curId, newId); TF_FOR_ALL (it, ranges) { _StripedBufferArrayRangeSharedPtr range = boost::static_pointer_cast<_StripedBufferArrayRange>(*it); if (!range) { TF_CODING_ERROR("_StripedBufferArrayRange " "expired unexpectedly."); continue; } // copy the range. There are three cases: // // 1. src length (capacity) == dst length (numElements) // Copy the entire range // // 2. src length < dst length // Enlarging the range. This typically happens when // applying quadrangulation/subdivision to populate // additional data at the end of source data. // // 3. src length > dst length // Shrinking the range. When the garbage collection // truncates ranges. // int oldSize = range->GetCapacity(); int newSize = range->GetNumElements(); GLsizeiptr copySize = std::min(oldSize, newSize) * bytesPerElement; int oldOffset = range->GetOffset(); if (copySize > 0) { GLintptr readOffset = oldOffset * bytesPerElement; GLintptr writeOffset = *newOffsetIt * bytesPerElement; relocator.AddRange(readOffset, writeOffset, copySize); } ++newOffsetIt; } // buffer copy relocator.Commit(); } if (oldId) { // delete old buffer glDeleteBuffers(1, &oldId); } } else { // for unit test static int id = 1; newId = id++; } // update id of buffer resource bres->SetAllocation(newId, bufferSize); } // update ranges for (size_t idx = 0; idx < ranges.size(); ++idx) { _StripedBufferArrayRangeSharedPtr range = boost::static_pointer_cast<_StripedBufferArrayRange>(ranges[idx]); if (!range) { TF_CODING_ERROR("_StripedBufferArrayRange expired unexpectedly."); continue; } range->SetOffset(newOffsets[idx]); range->SetCapacity(range->GetNumElements()); } _needsReallocation = false; _needsCompaction = false; // increment version to rebuild dispatch buffers. IncrementVersion(); } void HdStVBOMemoryManager::_StripedBufferArray::_DeallocateResources() { TF_FOR_ALL (it, GetResources()) { GLuint id = it->second->GetId(); if (id) { if (glDeleteBuffers) { glDeleteBuffers(1, &id); } it->second->SetAllocation(0, 0); } } } /*virtual*/ size_t HdStVBOMemoryManager::_StripedBufferArray::GetMaxNumElements() const { static size_t vboMaxSize = TfGetEnvSetting(HD_MAX_VBO_SIZE); return vboMaxSize / _maxBytesPerElement; } void HdStVBOMemoryManager::_StripedBufferArray::DebugDump(std::ostream &out) const { out << " HdStVBOMemoryManager\n"; out << " total capacity = " << _totalCapacity << "\n"; out << " Range entries " << GetRangeCount() << ":\n"; size_t rangeCount = GetRangeCount(); for (size_t rangeIdx = 0; rangeIdx < rangeCount; ++rangeIdx) { _StripedBufferArrayRangeSharedPtr range = _GetRangeSharedPtr(rangeIdx); if (range) { out << " " << rangeIdx << *range; } } } HdStBufferResourceGLSharedPtr HdStVBOMemoryManager::_StripedBufferArray::GetResource() const { HD_TRACE_FUNCTION(); if (_resourceList.empty()) return HdStBufferResourceGLSharedPtr(); if (TfDebug::IsEnabled(HD_SAFE_MODE)) { // make sure this buffer array has only one resource. GLuint id = _resourceList.begin()->second->GetId(); TF_FOR_ALL (it, _resourceList) { if (it->second->GetId() != id) { TF_CODING_ERROR("GetResource(void) called on" "HdBufferArray having multiple GL resources"); } } } // returns the first item return _resourceList.begin()->second; } HdStBufferResourceGLSharedPtr HdStVBOMemoryManager::_StripedBufferArray::GetResource(TfToken const& name) { HD_TRACE_FUNCTION(); // linear search. // The number of buffer resources should be small (<10 or so). for (HdStBufferResourceGLNamedList::iterator it = _resourceList.begin(); it != _resourceList.end(); ++it) { if (it->first == name) return it->second; } return HdStBufferResourceGLSharedPtr(); } HdBufferSpecVector HdStVBOMemoryManager::_StripedBufferArray::GetBufferSpecs() const { HdBufferSpecVector result; result.reserve(_resourceList.size()); TF_FOR_ALL (it, _resourceList) { result.emplace_back(it->first, it->second->GetTupleType()); } return result; } // --------------------------------------------------------------------------- // _StripedBufferArrayRange // --------------------------------------------------------------------------- HdStVBOMemoryManager::_StripedBufferArrayRange::~_StripedBufferArrayRange() { // Notify that hosting buffer array needs to be garbage collected. // // Don't do any substantial work here. // if (_stripedBufferArray) { _stripedBufferArray->SetNeedsCompaction(); // notify source bufferArray to bump the version so that // drawbatches to be rebuilt. // Also note that the buffer migration takes place only in // this StripedBufferArray, not in other InterleavedVBO/SimpleVBO. _stripedBufferArray->IncrementVersion(); } } bool HdStVBOMemoryManager::_StripedBufferArrayRange::IsAssigned() const { return (_stripedBufferArray != nullptr); } bool HdStVBOMemoryManager::_StripedBufferArrayRange::IsImmutable() const { return (_stripedBufferArray != nullptr) && _stripedBufferArray->IsImmutable(); } bool HdStVBOMemoryManager::_StripedBufferArrayRange::Resize(int numElements) { HD_TRACE_FUNCTION(); HF_MALLOC_TAG_FUNCTION(); if (!TF_VERIFY(_stripedBufferArray)) return false; bool needsReallocation = false; // XXX: varying topology points fix (bug 114080) // // MDI draw uses a dispatch buffer, and it includes numElements to be // drawn. When a topology is varying, numElements will change so the // dispatch buffer has to be rebuilt. Currently we depend on entire // buffer reallocation for index-drawing prims (e.g. meshes and curves) // with varying topology. We always allocate new BARs for them, // which is inefficient, and will be addressed later (bug 103767) // // However varying points have another problem: When it reduces its // number of points, it doesn't cause the reallocation in the below code // (disabled by #if 0) since points don't have an index buffer. // // These two problems have to be solved together by introducing more // robust mechanism which updates dispatch buffer partially to // reflect numElements correctly without having reallocation. // It needs more works, until then, we invoke reallocation whenever // numElements changes in an aggregated buffer, for the correctness // problem of points drawing (this is bug 114080). // // The varying mesh batch may suffer a performance regression // from this treatment, but it should be relatively small. Because the // topology buffer has already been reallocated on every changes as // described above and the primvar buffer is also reallocated in // GarbageCollect() before drawing (see HdEngine::Draw()). // // We need to revisit to clean this up soon. // #if 0 if (_capacity < numElements) { // mark entire buffer array to be relocated _stripedBufferArray->SetNeedsReallocation(); needsReallocation = true; } else if (_capacity > numElements) { // mark the buffer array can be compacted _stripedBufferArray->SetNeedsCompaction(); } #else if (_capacity != numElements) { const size_t numMaxElements = GetMaxNumElements(); if (static_cast<size_t>(numElements) > numMaxElements) { TF_WARN("Attempting to resize the BAR with 0x%x elements when the " "max number of elements in the buffer array is 0x%lx. " "Clamping BAR size to the latter.", numElements, numMaxElements); numElements = numMaxElements; } _stripedBufferArray->SetNeedsReallocation(); needsReallocation = true; } #endif _numElements = numElements; return needsReallocation; } void HdStVBOMemoryManager::_StripedBufferArrayRange::CopyData( HdBufferSourceSharedPtr const &bufferSource) { HD_TRACE_FUNCTION(); HF_MALLOC_TAG_FUNCTION(); if (!TF_VERIFY(_stripedBufferArray)) return; HdStBufferResourceGLSharedPtr VBO = _stripedBufferArray->GetResource(bufferSource->GetName()); if (!TF_VERIFY((VBO && VBO->GetId()), "VBO doesn't exist for %s", bufferSource->GetName().GetText())) { return; } // datatype of bufferSource has to match with bufferResource if (!TF_VERIFY(bufferSource->GetTupleType() == VBO->GetTupleType(), "'%s': (%s (%i) x %zu) != (%s (%i) x %zu)\n", bufferSource->GetName().GetText(), TfEnum::GetName(bufferSource->GetTupleType().type).c_str(), bufferSource->GetTupleType().type, bufferSource->GetTupleType().count, TfEnum::GetName(VBO->GetTupleType().type).c_str(), VBO->GetTupleType().type, VBO->GetTupleType().count)) { return; } GLF_GROUP_FUNCTION(); GlfContextCaps const &caps = GlfContextCaps::GetInstance(); if (glBufferSubData) { int bytesPerElement = HdDataSizeOfTupleType(VBO->GetTupleType()); // overrun check. for graceful handling of erroneous assets, // issue warning here and continue to copy for the valid range. size_t dstSize = _numElements * bytesPerElement; size_t srcSize = bufferSource->GetNumElements() * HdDataSizeOfTupleType(bufferSource->GetTupleType()); if (srcSize > dstSize) { TF_WARN("%s: size %ld is larger than the range (%ld)", bufferSource->GetName().GetText(), srcSize, dstSize); srcSize = dstSize; } GLintptr vboOffset = bytesPerElement * _offset; HD_PERF_COUNTER_INCR(HdPerfTokens->glBufferSubData); if (ARCH_LIKELY(caps.directStateAccessEnabled)) { glNamedBufferSubDataEXT(VBO->GetId(), vboOffset, srcSize, bufferSource->GetData()); } else { glBindBuffer(GL_ARRAY_BUFFER, VBO->GetId()); glBufferSubData(GL_ARRAY_BUFFER, vboOffset, srcSize, bufferSource->GetData()); glBindBuffer(GL_ARRAY_BUFFER, 0); } } } VtValue HdStVBOMemoryManager::_StripedBufferArrayRange::ReadData(TfToken const &name) const { HD_TRACE_FUNCTION(); HF_MALLOC_TAG_FUNCTION(); VtValue result; if (!TF_VERIFY(_stripedBufferArray)) return result; HdStBufferResourceGLSharedPtr VBO = _stripedBufferArray->GetResource(name); if (!VBO || (VBO->GetId() == 0 && _numElements > 0)) { TF_CODING_ERROR("VBO doesn't exist for %s", name.GetText()); return result; } GLintptr vboOffset = HdDataSizeOfTupleType(VBO->GetTupleType()) * _offset; result = HdStGLUtils::ReadBuffer(VBO->GetId(), VBO->GetTupleType(), vboOffset, /*stride=*/0, // not interleaved. _numElements); return result; } size_t HdStVBOMemoryManager::_StripedBufferArrayRange::GetMaxNumElements() const { return _stripedBufferArray->GetMaxNumElements(); } HdStBufferResourceGLSharedPtr HdStVBOMemoryManager::_StripedBufferArrayRange::GetResource() const { if (!TF_VERIFY(_stripedBufferArray)) return HdStBufferResourceGLSharedPtr(); return _stripedBufferArray->GetResource(); } HdStBufferResourceGLSharedPtr HdStVBOMemoryManager::_StripedBufferArrayRange::GetResource(TfToken const& name) { if (!TF_VERIFY(_stripedBufferArray)) return HdStBufferResourceGLSharedPtr(); return _stripedBufferArray->GetResource(name); } HdStBufferResourceGLNamedList const& HdStVBOMemoryManager::_StripedBufferArrayRange::GetResources() const { if (!TF_VERIFY(_stripedBufferArray)) { static HdStBufferResourceGLNamedList empty; return empty; } return _stripedBufferArray->GetResources(); } void HdStVBOMemoryManager::_StripedBufferArrayRange::SetBufferArray(HdBufferArray *bufferArray) { _stripedBufferArray = static_cast<_StripedBufferArray *>(bufferArray); } void HdStVBOMemoryManager::_StripedBufferArrayRange::DebugDump(std::ostream &out) const { out << "[StripedBAR] offset = " << _offset << ", numElements = " << _numElements << ", capacity = " << _capacity << "\n"; } const void * HdStVBOMemoryManager::_StripedBufferArrayRange::_GetAggregation() const { return _stripedBufferArray; } PXR_NAMESPACE_CLOSE_SCOPE
34.214653
90
0.608362
[ "mesh", "vector" ]
4f4a2fa4afe6cdc4d2a760b77e7ae00ca4942357
2,329
hpp
C++
include/ieompp/models/hubbard/dispersion.hpp
qftphys/Simulate-the-non-equilibrium-dynamics-of-Fermionic-systems
48d36fecbe4bc12af90f104cdf1f9f68352c508c
[ "MIT" ]
2
2021-01-18T14:35:43.000Z
2022-03-22T15:12:49.000Z
include/ieompp/models/hubbard/dispersion.hpp
f-koehler/ieompp
48d36fecbe4bc12af90f104cdf1f9f68352c508c
[ "MIT" ]
null
null
null
include/ieompp/models/hubbard/dispersion.hpp
f-koehler/ieompp
48d36fecbe4bc12af90f104cdf1f9f68352c508c
[ "MIT" ]
null
null
null
#ifndef IEOMPP_MODELS_HUBBARD_DISPERSION_HPP_ #define IEOMPP_MODELS_HUBBARD_DISPERSION_HPP_ #include "ieompp/constants.hpp" #include "ieompp/types/dot_product.hpp" #include "ieompp/types/matrix.hpp" #include <cmath> #include <vector> namespace ieompp { namespace models { namespace hubbard { template <typename Float> Float calculate_fermi_momentum_1d(const Float& filling_factor) { return filling_factor * Pi<Float>::value; } template <typename FloatT> class Dispersion { public: using Float = FloatT; private: std::vector<Float> _values; public: template <typename MomentumSpace, typename Lattice> Dispersion(const MomentumSpace& momentum_space, const Lattice& lattice, const Float& J = 1.) : _values(momentum_space.size(), Float(0.)) { const auto N = momentum_space.size(); const auto lattice_vectors = lattice.lattice_vectors(); #pragma omp parallel for for(typename MomentumSpace::SiteIndex i = 0; i < N; ++i) { const auto& momentum = momentum_space[i]; Float val = 0.; for(const auto& vec : lattice_vectors) { val += std::cos(types::dot_product(momentum, vec)); } _values[i] = -2. * J * val; } } const Float& operator()(typename std::vector<Float>::size_type idx) const { return _values[idx]; } }; template <typename MomentumSpace, typename Lattice> Dispersion<typename MomentumSpace::Float> make_dispersion(const MomentumSpace& momentum_space, const Lattice& lattice, const typename MomentumSpace::Float& J = 1.) { return Dispersion<typename MomentumSpace::Float>(momentum_space, lattice, J); } } // namespace hubbard } // namespace models } // namespace ieompp #endif
32.802817
93
0.519536
[ "vector" ]
4f4e664dc72a44dfb97ad39ae9b7b0763d7b0b4f
4,177
cpp
C++
easy/cpp/c0157_653_two-sum-iv-input-is-a-bst/00_leetcode_0157.cpp
drunkwater/leetcode
8cc4a07763e71efbaedb523015f0c1eff2927f60
[ "Ruby" ]
null
null
null
easy/cpp/c0157_653_two-sum-iv-input-is-a-bst/00_leetcode_0157.cpp
drunkwater/leetcode
8cc4a07763e71efbaedb523015f0c1eff2927f60
[ "Ruby" ]
null
null
null
easy/cpp/c0157_653_two-sum-iv-input-is-a-bst/00_leetcode_0157.cpp
drunkwater/leetcode
8cc4a07763e71efbaedb523015f0c1eff2927f60
[ "Ruby" ]
3
2018-02-09T02:46:48.000Z
2021-02-20T08:32:03.000Z
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //653. Two Sum IV - Input is a BST //Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target. //Example 1: //Input: // 5 // / \ // 3 6 // / \ \ //2 4 7 //Target = 9 //Output: True //Example 2: //Input: // 5 // / \ // 3 6 // / \ \ //2 4 7 //Target = 28 //Output: False ///** // * Definition for a binary tree node. // * struct TreeNode { // * int val; // * TreeNode *left; // * TreeNode *right; // * TreeNode(int x) : val(x), left(NULL), right(NULL) {} // * }; // */ //class Solution { //public: // bool findTarget(TreeNode* root, int k) { // } //}; #include<iostream> #include<iomanip> #include<stdint.h> #include<time.h> #include<limits.h> #include"solution.hpp" /*using namespace std;*/ /** * Note: The returned array must be malloced, assume caller calls free(). */ std::vector<int> Solution::twoSum(std::vector<int>& nums, int target) { /* sanity check */ std::map<int, int> hashTbl;/* index -> data */ for ( int i = 0; i < (int)nums.size(); i++ ) { int n = nums[i]; if ( hashTbl.find(target - n) == hashTbl.end() ) { hashTbl[n] = i; } else { std::vector<int> ret(2); ret[0] = hashTbl[target - n]; ret[1] = i; return ret; } } return std::vector<int>(0); } void printTime(void) { /* sanity check */ time_t rawtime; struct tm *timeinfo; time ( &rawtime ); timeinfo = localtime ( &rawtime ); std::cout << " Current date and time is: " << asctime (timeinfo) << std::endl; } static union { char c[4]; unsigned long l; } endian_test = {{'l', '?', '?', 'b'}}; #define ENDIANNESS ((char)endian_test.l) void dprint_platform(void) { /* sanity check */ std::cout << " int8_t = " << sizeof(int8_t) << std::endl; std::cout << " uint8_t = " << sizeof(uint8_t) << std::endl; std::cout << " int16_t = " << sizeof(int16_t) << std::endl; std::cout << "uint16_t = " << sizeof(uint16_t) << std::endl; std::cout << " int32_t = " << sizeof(int32_t) << std::endl; std::cout << "uint32_t = " << sizeof(uint32_t) << std::endl; std::cout << " int64_t = " << sizeof(int64_t) << std::endl; std::cout << "uint64_t = " << sizeof(uint64_t) << std::endl; std::cout << "ENDIANNESS=" << ENDIANNESS << std::endl; int n = 0x04030201; if (*(char *)&n == 0x01) { std::cout << "little endian" << std::endl; } else { std::cout << " big endian" << std::endl; } std::cout << std::endl << std::endl; } int main( int argc, char *argv[] ) { /* sanity check */ std::cout << "[" << __TIME__" "__DATE__ << "]" << __FILE__ << ":" << __LINE__ << std::endl; printTime(); struct timespec start,end; /* seconds and nanoseconds */ clock_gettime(CLOCK_MONOTONIC, &start); std::cout << "[start]" << start.tv_sec << ", " << start.tv_nsec << std::endl; time_t s,e; s=time(NULL); /* add your codes here */ //dprint_platform(); int array[]={1,2,3,4,5,6}; int target = 7; int size = sizeof(array)/sizeof(array[0]); //std::vector<int> vec(begin(array), end(array)); std::vector<int> vec(array, (array+size)); Solution obj; std::vector<int> result = obj.twoSum(vec, target); for (std::vector<int>::iterator it = result.begin(); it != result.end(); it++) { std::cout << *it << " -> " << array[*it] << std::endl; } #if 0/* disable 'no operation' */ unsigned int z = 0; #define MAX_NOOP 0xCFFFFFFFUL for(z = 0; z < MAX_NOOP; z++) { asm("nop ; nop ; nop ; nop"); asm("nop ; nop ; nop ; nop"); } #endif e=time(NULL); std::cout.setf(std::ios::fixed); std::cout << "Worked time : " << std::fixed << std::setprecision(8) << difftime(e, s) << std::endl;/*6.00000000*/ std::cout.unsetf(std::ios::fixed); clock_gettime(CLOCK_MONOTONIC, &end); std::cout << "[ end]" << end.tv_sec << ", " << end.tv_nsec << std::endl; printTime(); std::cout << "[" << __TIME__" "__DATE__ << "]" << __FILE__ << ":" << __LINE__ << std::endl; return 0; }
19.248848
150
0.575772
[ "vector" ]
4f4f5edcf3cc3227703651c26863f544a1218f92
2,676
cpp
C++
source/sampler.cpp
gonnavis/voxelizer
701b4d282c51bebca370fe2497085dfaa9bb6ba9
[ "Apache-2.0" ]
21
2021-12-03T16:23:47.000Z
2022-02-03T07:50:47.000Z
source/sampler.cpp
gonnavis/voxelizer
701b4d282c51bebca370fe2497085dfaa9bb6ba9
[ "Apache-2.0" ]
1
2022-03-04T16:24:28.000Z
2022-03-04T16:24:28.000Z
source/sampler.cpp
gonnavis/voxelizer
701b4d282c51bebca370fe2497085dfaa9bb6ba9
[ "Apache-2.0" ]
2
2021-12-04T15:41:28.000Z
2021-12-04T17:37:11.000Z
#include <voxelizer/sampler.hpp> #include <voxelizer/sequence.hpp> #include <voxelizer/index.hpp> #include <voxelizer/color.hpp> #include <chrono> #include <thread> #include <atomic> namespace voxelizer { static bool inside(glm::vec3 const & p, index const & i) { int intersections = 0; i.intersects_ray(p, {1.f, 0.f, 0.f}, [&](auto){ ++intersections; }); return (intersections % 2) == 1; } float sample(scene const & input_scene, texture_3d & output_texture, int nsamples, box bbox, progress_callback callback) { std::vector<index> indices; for (auto const & o : input_scene.objects) indices.emplace_back(o.mesh); auto dim = output_texture.dimensions(); using clock = std::chrono::high_resolution_clock; auto start = clock::now(); auto last_report_time = start; int total_work = dim.x * dim.y * dim.z; std::atomic<int> work_done(0); int thread_count = std::thread::hardware_concurrency(); if (thread_count == 0) thread_count = 1; int work_per_thread = total_work / thread_count; std::vector<std::thread> threads; for (int th = 0; th < thread_count; ++th) { threads.emplace_back([&, th]{ int work_start = th * work_per_thread; int work_end = (th + 1 == thread_count) ? total_work : (th + 1) * work_per_thread; for (int work_id = work_start; work_id < work_end; ++work_id) { int x = work_id % dim.x; int y = (work_id / dim.x) % dim.y; int z = work_id / dim.x / dim.y; glm::vec4 color(0.f); sequence seq({0.5f, 0.5f, 0.5f}); for (int s = 0; s < nsamples; ++s) { glm::vec3 p = (glm::vec3(x, y, z) + seq()) / glm::vec3(dim); p = p * (bbox.max - bbox.min) + bbox.min; for (int o = 0; o < input_scene.objects.size(); ++o) { if (inside(p, indices[o])) color += premult(input_scene.objects[o].material.color) / float(nsamples); } } color = unpremult(color); output_texture.at(x, y, z) = to_uint(color); ++work_done; } }); } std::this_thread::sleep_for(std::chrono::milliseconds{100}); while (true) { if (work_done >= total_work) break; auto now = clock::now(); float done = work_done * 1.f / (dim.x * dim.y * dim.z); float time_spent = std::chrono::duration_cast<std::chrono::duration<float>>(now - start).count(); float speed = done / time_spent; float left = 1.f - done; float time_left = left / speed; if (callback) callback(done, time_left); std::this_thread::sleep_for(std::chrono::seconds{1}); } for (auto & th : threads) th.join(); return std::chrono::duration_cast<std::chrono::duration<float>>(clock::now() - start).count(); } }
23.681416
100
0.624066
[ "mesh", "vector" ]
4f4f665d4ee2ebd02d72b6256463e0718f2fca43
12,672
cc
C++
tensorflow/compiler/mlir/tools/kernel_gen/tf_framework_c_interface.cc
brinkqiang/tensorflow
a9643a6a04dbc29e79f2026ec5fc501259b8c53c
[ "Apache-2.0" ]
2
2021-11-25T09:39:10.000Z
2022-03-19T07:14:10.000Z
tensorflow/compiler/mlir/tools/kernel_gen/tf_framework_c_interface.cc
brinkqiang/tensorflow
a9643a6a04dbc29e79f2026ec5fc501259b8c53c
[ "Apache-2.0" ]
null
null
null
tensorflow/compiler/mlir/tools/kernel_gen/tf_framework_c_interface.cc
brinkqiang/tensorflow
a9643a6a04dbc29e79f2026ec5fc501259b8c53c
[ "Apache-2.0" ]
1
2022-03-19T07:14:17.000Z
2022-03-19T07:14:17.000Z
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/mlir/tools/kernel_gen/tf_framework_c_interface.h" #include <cstddef> #include <string> #include <utility> #include "llvm/ADT/SmallVector.h" #include "llvm/Support/TargetSelect.h" #include "mlir/ExecutionEngine/ExecutionEngine.h" // from @llvm-project #include "mlir/ExecutionEngine/OptUtils.h" // from @llvm-project #include "mlir/Parser.h" // from @llvm-project #include "tensorflow/compiler/mlir/tools/kernel_gen/compile_cache_item.pb.h" #include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h" #include "tensorflow/compiler/mlir/tools/kernel_gen/kernel_creator.h" #include "tensorflow/compiler/mlir/tools/kernel_gen/tf_jit_cache.h" #include "tensorflow/core/framework/allocator.h" #include "tensorflow/core/framework/resource_mgr.h" #include "tensorflow/core/lib/io/path.h" #include "tensorflow/core/platform/status.h" #include "tensorflow/core/platform/statusor.h" #include "tensorflow/stream_executor/stream.h" #if defined(GOOGLE_CUDA) || defined(TENSORFLOW_USE_ROCM) #include "tensorflow/compiler/mlir/tools/kernel_gen/tf_gpu_runtime_wrappers.h" #endif static constexpr absl::string_view kTFJitCacheDirEnvVar = "TF_JIT_CACHE_DIR"; namespace mlir { namespace kernel_gen { namespace tf_framework { namespace { using tensorflow::Allocator; using tensorflow::AllocatorAttributes; Allocator* GetAllocator(void* op_kernel_ctx) { auto* ctx = static_cast<tensorflow::OpKernelContext*>(op_kernel_ctx); // TODO(pifon): Figure out how to set AllocatorAttributes correctly. AllocatorAttributes attrs; return ctx->get_allocator(attrs); } } // namespace extern "C" void* _mlir_ciface_tf_alloc(void* op_kernel_ctx, size_t num_elements, size_t element_size, int32_t output_index, int32_t num_candidates, int32_t* candidate_input_indices) { static constexpr int kAmbiguousOutputIndex = -1; auto* ctx = static_cast<tensorflow::OpKernelContext*>(op_kernel_ctx); if (output_index != kAmbiguousOutputIndex) { // Create a 1D shape, because the shapes don't have to match exactly for // input forwarding. Only the number of elements must be the same. tensorflow::TensorShape output_shape; output_shape.AddDim(num_elements); // Iterate over indices of all inputs that can potentially be used for // forwarding. for (int i = 0; i < num_candidates; ++i) { auto tensor = ctx->forward_input(candidate_input_indices[i], output_index, ctx->expected_output_dtype(output_index), output_shape, ctx->output_memory_type(output_index), ctx->output_alloc_attr(output_index)); if (tensor != nullptr) { return tensor->data(); } } CHECK(!ctx->output_expects_forwarding(output_index)); } // If no forwarding happened, allocate a chunk of memory. return GetAllocator(op_kernel_ctx) ->AllocateRaw(Allocator::kAllocatorAlignment, num_elements * element_size); } extern "C" void _mlir_ciface_tf_dealloc(void* op_kernel_ctx, void* ptr) { GetAllocator(op_kernel_ctx)->DeallocateRaw(ptr); } extern "C" void _mlir_ciface_tf_report_error(void* op_kernel_ctx, int32_t error_code, char* msg) { Optional<ErrorCode> symbol = symbolizeErrorCode(error_code); if (!symbol.hasValue()) { LOG(ERROR) << "No valid conversion from integer value = " << error_code << "to ErrorCode attribute"; return; } auto* ctx = static_cast<tensorflow::OpKernelContext*>(op_kernel_ctx); ctx->CtxFailureWithWarning( tensorflow::Status{ConvertAttrToEnumValue(symbol.getValue()), msg}); } static void ReportError(void* op_kernel_ctx, ErrorCode error_code, const char* msg) { _mlir_ciface_tf_report_error(op_kernel_ctx, static_cast<uint32_t>(error_code), const_cast<char*>(msg)); } namespace { std::string GetFileCachePath(const std::string cache_dir, const std::string& code) { size_t hash = llvm::hash_value(code); return tensorflow::io::JoinPath(cache_dir, std::to_string(hash)); } // A callback to register all externally defined symbols needed by the kernel. llvm::orc::SymbolMap TFFrameworkSymbolMap(llvm::orc::MangleAndInterner mangle) { llvm::orc::SymbolMap symbol_map; auto bind = [&](llvm::StringRef name, auto symbol_ptr) { symbol_map[mangle(name)] = llvm::JITEvaluatedSymbol( llvm::pointerToJITTargetAddress(symbol_ptr), llvm::JITSymbolFlags()); }; // Register all the symbols. bind("_mlir_ciface_tf_alloc", &_mlir_ciface_tf_alloc); bind("_mlir_ciface_tf_dealloc", &_mlir_ciface_tf_dealloc); bind("_mlir_ciface_tf_report_error", &_mlir_ciface_tf_report_error); #if defined(GOOGLE_CUDA) || defined(TENSORFLOW_USE_ROCM) bind("_mlir_ciface_tf_launch_kernel", &_mlir_ciface_tf_launch_kernel); #endif return symbol_map; } llvm::Expected<std::unique_ptr<ExecutionEngine>> Compile( const std::string code, llvm::SmallVectorImpl<std::string>& architectures, llvm::SmallVectorImpl<int64_t>& tile_sizes, llvm::SmallVectorImpl<int64_t>& unroll_factors, int64_t max_supported_rank, bool enable_ftz, bool cpu_codegen) { std::string cache_dir; if (const char* dir = getenv(kTFJitCacheDirEnvVar.data())) { cache_dir = dir; } // Check if we already have a partially compiled module in the filesystem // based cache. CompilationCacheItem item; auto tenv = tensorflow::Env::Default(); if (!cache_dir.empty() && tenv->RecursivelyCreateDir(cache_dir).ok()) { std::string data; if (tensorflow::ReadFileToString(tenv, GetFileCachePath(cache_dir, code), &data) .ok()) { item.ParseFromString(data); if (item.original_module() != code) { item.Clear(); } } } // Create the kernel. mlir::OwningModuleRef module; mlir::MLIRContext context; if (item.result_module().empty()) { // Otherwise, compile the module now. tensorflow::StatusOr<mlir::OwningModuleRef> status_or_module = tensorflow::kernel_gen::GenerateKernelForTfCode( context, code, architectures, tile_sizes, unroll_factors, max_supported_rank, /*embed_memref_prints=*/false, /*print_ptx=*/false, /*print_llvmir=*/false, enable_ftz, cpu_codegen, /*jit_compile=*/false); if (!status_or_module.ok()) return nullptr; module = std::move(status_or_module.ValueOrDie()); if (!cache_dir.empty() && tenv->RecursivelyCreateDir(cache_dir).ok()) { // Save the compilation result here for future processes to use. item.set_original_module(code); llvm::raw_string_ostream stream(*item.mutable_result_module()); module.get().print(stream); stream.flush(); tensorflow::WriteStringToFile(tenv, GetFileCachePath(cache_dir, code), item.SerializeAsString()) .IgnoreError(); } } else { module = tensorflow::kernel_gen::SetupContextAndParseModule( context, item.result_module()) .ValueOrDie(); } // Initialize LLVM targets. llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); // Create execution engine with an inner optimization pipeline. auto opt_pipeline = mlir::makeOptimizingTransformer( /*optLevel=*/2, /*sizeLevel=*/0, /*targetMachine=*/nullptr); llvm::Expected<std::unique_ptr<ExecutionEngine>> engine = mlir::ExecutionEngine::create(module.get(), /*llvmModuleBuilder=*/nullptr, opt_pipeline); if (!engine) return nullptr; // Finally, register the missing symbols. engine.get()->registerSymbols(TFFrameworkSymbolMap); return engine; } template <typename T, typename U = T> llvm::SmallVector<T, 8> SmallVectorFromCArray(int64_t num_elements, U* elements_ptr) { llvm::SmallVector<T, 8> result; result.reserve(num_elements); for (int i = 0; i < num_elements; ++i) result.push_back(elements_ptr[i]); return result; } } // namespace extern "C" void* _mlir_ciface_tf_jit_compile( void* op_kernel_ctx, char* code, int64_t num_tile_sizes, int64_t* tile_sizes_ptr, int64_t num_unroll_factors, int64_t* unroll_factors_ptr, int64_t max_supported_rank, bool enable_ftz, bool cpu_codegen) { // Get the resource manager. auto* ctx = static_cast<tensorflow::OpKernelContext*>(op_kernel_ctx); tensorflow::ResourceMgr* rm = ctx->resource_manager(); if (!rm) { ReportError(op_kernel_ctx, ErrorCode::UNKNOWN, "No resource manager."); return nullptr; } // Get the JIT cache. JITCache* jit_cache = nullptr; auto status = rm->LookupOrCreate<JITCache>(rm->default_container(), JITCache::kDefaultResourceName, &jit_cache, JITCache::Create); tensorflow::core::ScopedUnref jit_cache_ref(jit_cache); if (!status.ok()) { ReportError(op_kernel_ctx, ErrorCode::UNKNOWN, "Failed to find or create JIT cache."); return nullptr; } // Determine the unique architecture for the current GPU, if any. SmallVector<std::string, 1> architectures; stream_executor::CudaComputeCapability cc = ctx->op_device_context()->stream()->GetCudaComputeCapability(); #if defined(GOOGLE_CUDA) architectures.push_back(absl::StrCat("sm_", cc.major, cc.minor)); #elif defined(TENSORFLOW_USE_ROCM) architectures.push_back(absl::StrCat("gfx", cc.major, cc.minor)); #endif // Construct `SmallVector`s from arguments. llvm::SmallVector<int64_t, 8> tile_sizes = SmallVectorFromCArray<int64_t>(num_tile_sizes, tile_sizes_ptr); llvm::SmallVector<int64_t, 8> unroll_factors = SmallVectorFromCArray<int64_t>(num_unroll_factors, unroll_factors_ptr); // Lookup or compile the execution module. ExecutionEngine* engine = jit_cache->LookupOrCompile(code, [&]() { return Compile(code, architectures, tile_sizes, unroll_factors, max_supported_rank, enable_ftz, cpu_codegen); }); if (engine == nullptr) { ReportError(op_kernel_ctx, ErrorCode::UNKNOWN, "JIT compilation failed."); return nullptr; } return engine; } extern "C" void _mlir_ciface_tf_jit_execute(void* op_kernel_ctx, void* callable, void* result, int64_t num_args, void* args_ptr) { // JIT compilation must have failed earlier if there is no callable ptr. // Return some empty memory descriptor to prevent a crash. if (callable == nullptr) { auto* desc = static_cast<::UnrankedMemRefType<void>*>(result); desc->rank = 0; auto* inner_desc = static_cast<StridedMemRefType<int8_t, 0>*>( malloc(sizeof(StridedMemRefType<int8_t, 0>))); inner_desc->basePtr = nullptr; inner_desc->data = nullptr; inner_desc->offset = 0; desc->descriptor = inner_desc; return; } // Build the argument array according to `ExecutionEngine`'s calling // convention. auto* typed_args_ptr = static_cast<::UnrankedMemRefType<void>*>(args_ptr); llvm::SmallVector<void*, 8> args_array = {&op_kernel_ctx}; for (int i = 0; i < num_args; i++) { auto& desc = typed_args_ptr[i]; args_array.push_back(&desc.rank); args_array.push_back(&desc.descriptor); } args_array.push_back(result); llvm::Error invocation_result = static_cast<ExecutionEngine*>(callable)->invokePacked("main", args_array); if (invocation_result) ReportError(op_kernel_ctx, ErrorCode::UNKNOWN, "JIT invocation failed."); } } // namespace tf_framework } // namespace kernel_gen } // namespace mlir
39.232198
80
0.682292
[ "shape" ]
4f51558612095c1ee51efdb7f4411c81084a3f52
9,512
cpp
C++
src/Dictionaries/PolygonDictionaryImplementations.cpp
pdv-ru/ClickHouse
0ff975bcf3008fa6c6373cbdfed16328e3863ec5
[ "Apache-2.0" ]
15,577
2019-09-23T11:57:53.000Z
2022-03-31T18:21:48.000Z
src/Dictionaries/PolygonDictionaryImplementations.cpp
pdv-ru/ClickHouse
0ff975bcf3008fa6c6373cbdfed16328e3863ec5
[ "Apache-2.0" ]
16,476
2019-09-23T11:47:00.000Z
2022-03-31T23:06:01.000Z
src/Dictionaries/PolygonDictionaryImplementations.cpp
pdv-ru/ClickHouse
0ff975bcf3008fa6c6373cbdfed16328e3863ec5
[ "Apache-2.0" ]
3,633
2019-09-23T12:18:28.000Z
2022-03-31T15:55:48.000Z
#include "PolygonDictionaryImplementations.h" #include "DictionaryFactory.h" #include <DataTypes/DataTypeArray.h> #include <DataTypes/DataTypeTuple.h> #include <DataTypes/DataTypesNumber.h> #include <base/logger_useful.h> #include <numeric> namespace DB { namespace ErrorCodes { extern const int BAD_ARGUMENTS; } PolygonDictionarySimple::PolygonDictionarySimple( const StorageID & dict_id_, const DictionaryStructure & dict_struct_, DictionarySourcePtr source_ptr_, const DictionaryLifetime dict_lifetime_, Configuration configuration_) : IPolygonDictionary(dict_id_, dict_struct_, std::move(source_ptr_), dict_lifetime_, configuration_) { } std::shared_ptr<const IExternalLoadable> PolygonDictionarySimple::clone() const { return std::make_shared<PolygonDictionarySimple>( this->getDictionaryID(), this->dict_struct, this->source_ptr->clone(), this->dict_lifetime, this->configuration); } bool PolygonDictionarySimple::find(const Point & point, size_t & polygon_index) const { bool found = false; for (size_t i = 0; i < polygons.size(); ++i) { if (bg::covered_by(point, polygons[i])) { polygon_index = i; found = true; break; } } return found; } PolygonDictionaryIndexEach::PolygonDictionaryIndexEach( const StorageID & dict_id_, const DictionaryStructure & dict_struct_, DictionarySourcePtr source_ptr_, const DictionaryLifetime dict_lifetime_, Configuration configuration_, int min_intersections_, int max_depth_) : IPolygonDictionary(dict_id_, dict_struct_, std::move(source_ptr_), dict_lifetime_, configuration_), grid(min_intersections_, max_depth_, polygons), min_intersections(min_intersections_), max_depth(max_depth_) { buckets.reserve(polygons.size()); for (const auto & polygon : polygons) { std::vector<Polygon> single; single.emplace_back(polygon); buckets.emplace_back(single); } } std::shared_ptr<const IExternalLoadable> PolygonDictionaryIndexEach::clone() const { return std::make_shared<PolygonDictionaryIndexEach>( this->getDictionaryID(), this->dict_struct, this->source_ptr->clone(), this->dict_lifetime, this->configuration, this->min_intersections, this->max_depth); } bool PolygonDictionaryIndexEach::find(const Point & point, size_t & polygon_index) const { const auto * cell = grid.find(point.x(), point.y()); if (cell) { for (const auto & candidate : cell->polygon_ids) { size_t unused; if (buckets[candidate].find(point, unused)) { polygon_index = candidate; return true; } } if (cell->first_covered != FinalCell::kNone) { polygon_index = cell->first_covered; return true; } } return false; } PolygonDictionaryIndexCell::PolygonDictionaryIndexCell( const StorageID & dict_id_, const DictionaryStructure & dict_struct_, DictionarySourcePtr source_ptr_, const DictionaryLifetime dict_lifetime_, Configuration configuration_, size_t min_intersections_, size_t max_depth_) : IPolygonDictionary(dict_id_, dict_struct_, std::move(source_ptr_), dict_lifetime_, configuration_), index(min_intersections_, max_depth_, polygons), min_intersections(min_intersections_), max_depth(max_depth_) { } std::shared_ptr<const IExternalLoadable> PolygonDictionaryIndexCell::clone() const { return std::make_shared<PolygonDictionaryIndexCell>( this->getDictionaryID(), this->dict_struct, this->source_ptr->clone(), this->dict_lifetime, this->configuration, this->min_intersections, this->max_depth); } bool PolygonDictionaryIndexCell::find(const Point & point, size_t & polygon_index) const { const auto * cell = index.find(point.x(), point.y()); if (cell) { if (!(cell->corresponding_ids).empty() && cell->index.find(point, polygon_index)) { polygon_index = cell->corresponding_ids[polygon_index]; return true; } if (cell->first_covered != FinalCellWithSlabs::kNone) { polygon_index = cell->first_covered; return true; } } return false; } template <class PolygonDictionary> DictionaryPtr createLayout(const std::string & , const DictionaryStructure & dict_struct, const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, DictionarySourcePtr source_ptr, ContextPtr /* global_context */, bool /*created_from_ddl*/) { const String database = config.getString(config_prefix + ".database", ""); const String name = config.getString(config_prefix + ".name"); if (!dict_struct.key) throw Exception(ErrorCodes::BAD_ARGUMENTS, "'key' is required for a polygon dictionary"); if (dict_struct.key->size() != 1) throw Exception(ErrorCodes::BAD_ARGUMENTS, "The 'key' should consist of a single attribute for a polygon dictionary"); const auto key_type = (*dict_struct.key)[0].type; const auto f64 = std::make_shared<DataTypeFloat64>(); const auto multi_polygon_array = DataTypeArray(std::make_shared<DataTypeArray>(std::make_shared<DataTypeArray>(std::make_shared<DataTypeArray>(f64)))); const auto multi_polygon_tuple = DataTypeArray(std::make_shared<DataTypeArray>(std::make_shared<DataTypeArray>(std::make_shared<DataTypeTuple>(std::vector<DataTypePtr>{f64, f64})))); const auto simple_polygon_array = DataTypeArray(std::make_shared<DataTypeArray>(f64)); const auto simple_polygon_tuple = DataTypeArray(std::make_shared<DataTypeTuple>(std::vector<DataTypePtr>{f64, f64})); IPolygonDictionary::InputType input_type; IPolygonDictionary::PointType point_type; if (key_type->equals(multi_polygon_array)) { input_type = IPolygonDictionary::InputType::MultiPolygon; point_type = IPolygonDictionary::PointType::Array; } else if (key_type->equals(multi_polygon_tuple)) { input_type = IPolygonDictionary::InputType::MultiPolygon; point_type = IPolygonDictionary::PointType::Tuple; } else if (key_type->equals(simple_polygon_array)) { input_type = IPolygonDictionary::InputType::SimplePolygon; point_type = IPolygonDictionary::PointType::Array; } else if (key_type->equals(simple_polygon_tuple)) { input_type = IPolygonDictionary::InputType::SimplePolygon; point_type = IPolygonDictionary::PointType::Tuple; } else { throw Exception(ErrorCodes::BAD_ARGUMENTS, "The key type {} is not one of the following allowed types for a polygon dictionary: {} {} {} {} ", key_type->getName(), multi_polygon_array.getName(), multi_polygon_tuple.getName(), simple_polygon_array.getName(), simple_polygon_tuple.getName()); } const auto & layout_prefix = config_prefix + ".layout"; Poco::Util::AbstractConfiguration::Keys keys; config.keys(layout_prefix, keys); const auto & dict_prefix = layout_prefix + "." + keys.front(); IPolygonDictionary::Configuration configuration { .input_type = input_type, .point_type = point_type, .store_polygon_key_column = config.getBool(dict_prefix + ".store_polygon_key_column", false) }; if (dict_struct.range_min || dict_struct.range_max) throw Exception(ErrorCodes::BAD_ARGUMENTS, "{}: elements range_min and range_max should be defined only " "for a dictionary of layout 'range_hashed'", name); const DictionaryLifetime dict_lifetime{config, config_prefix + ".lifetime"}; const auto dict_id = StorageID::fromDictionaryConfig(config, config_prefix); if constexpr (std::is_same_v<PolygonDictionary, PolygonDictionaryIndexEach> || std::is_same_v<PolygonDictionary, PolygonDictionaryIndexCell>) { size_t max_depth = config.getUInt(dict_prefix + ".max_depth", PolygonDictionary::kMaxDepthDefault); size_t min_intersections = config.getUInt(dict_prefix + ".min_intersections", PolygonDictionary::kMinIntersectionsDefault); return std::make_unique<PolygonDictionary>(dict_id, dict_struct, std::move(source_ptr), dict_lifetime, configuration, min_intersections, max_depth); } else return std::make_unique<PolygonDictionary>(dict_id, dict_struct, std::move(source_ptr), dict_lifetime, configuration); } void registerDictionaryPolygon(DictionaryFactory & factory) { factory.registerLayout("polygon_simple", createLayout<PolygonDictionarySimple>, true); factory.registerLayout("polygon_index_each", createLayout<PolygonDictionaryIndexEach>, true); factory.registerLayout("polygon_index_cell", createLayout<PolygonDictionaryIndexCell>, true); /// Alias to the most performant dictionary type - polygon_index_cell factory.registerLayout("polygon", createLayout<PolygonDictionaryIndexCell>, true); } }
36.584615
186
0.674411
[ "vector" ]
4f53ed41c4b9434cc688712ff1fa77cc655be1da
20,988
cc
C++
chrome/services/speech/cloud_speech_recognition_client_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
chrome/services/speech/cloud_speech_recognition_client_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
chrome/services/speech/cloud_speech_recognition_client_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.000Z
// Copyright 2020 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/services/speech/cloud_speech_recognition_client.h" #include <memory> #include <string> #include <vector> #include "base/bind.h" #include "base/containers/queue.h" #include "base/containers/span.h" #include "base/numerics/safe_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/sys_byteorder.h" #include "base/test/task_environment.h" #include "base/time/time.h" #include "chrome/services/speech/speech_recognition_service_impl.h" #include "chrome/test/base/testing_browser_process.h" #include "content/public/browser/google_streaming_api.pb.h" #include "content/public/test/browser_task_environment.h" #include "media/base/bind_to_current_loop.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "net/http/http_util.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" #include "services/network/public/mojom/url_response_head.mojom.h" #include "services/network/test/test_url_loader_factory.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/mojom/speech/speech_recognition_error.mojom.h" #include "third_party/blink/public/mojom/speech/speech_recognition_result.mojom.h" using base::checked_cast; using base::HostToNet32; namespace speech { // The number of bytes in the dummy audio. constexpr uint32_t kDummyAudioBytes = 4000; class SpeechRecognitionServiceImplMock : public SpeechRecognitionServiceImpl { public: explicit SpeechRecognitionServiceImplMock( mojo::PendingReceiver<media::mojom::SpeechRecognitionService> receiver); mojo::PendingRemote<network::mojom::URLLoaderFactory> GetUrlLoaderFactory() override; std::vector<network::TestURLLoaderFactory::PendingRequest>* GetPendingRequests(); int GetNumPending(); void ResetNetwork(); // private: // Instantiate a TestURLLoaderFactory which we can use to respond and unpause // network requests. network::TestURLLoaderFactory test_url_loader_factory_; mojo::Receiver<network::mojom::URLLoaderFactory> test_factory_receiver_; }; class CloudSpeechRecognitionClientUnitTest : public testing::Test { public: CloudSpeechRecognitionClientUnitTest(); // testing::Test methods. void SetUp() override; protected: void OnRecognitionEvent(media::SpeechRecognitionResult result); void InjectDummyAudio(); void InitializeUpstreamPipeIfNecessary(); // Reads and returns all pending upload data from |upstream_data_pipe_|, // initializing the pipe from |GetUpstreamRequest()|, if needed. std::string ConsumeChunkedUploadData(uint32_t expected_num_bytes); const network::TestURLLoaderFactory::PendingRequest* GetUpstreamRequest(); const network::TestURLLoaderFactory::PendingRequest* GetDownstreamRequest(); void ProvideMockResponseStartDownstreamIfNeeded(); void ProvideMockStringResponseDownstream(const std::string& response_string); void ProvideMockProtoResultDownstream( const content::proto::SpeechRecognitionEvent& result); void ProvideMockResultDownstream(std::vector<std::string> result_strings, bool is_final); static std::string SerializeProtobufResponse( const content::proto::SpeechRecognitionEvent& msg); void ExpectResultsReceived(const std::vector<std::string>& expected_results, bool is_final); std::unique_ptr<CloudSpeechRecognitionClient> client_under_test_; std::unique_ptr<SpeechRecognitionServiceImplMock> speech_recognition_service_impl_; mojo::Remote<media::mojom::SpeechRecognitionService> remote_; mojo::ScopedDataPipeProducerHandle downstream_data_pipe_; mojo::Remote<network::mojom::ChunkedDataPipeGetter> chunked_data_pipe_getter_; mojo::ScopedDataPipeConsumerHandle upstream_data_pipe_; base::queue<std::string> results_; bool is_final_ = false; content::BrowserTaskEnvironment task_environment_{ base::test::TaskEnvironment::TimeSource::MOCK_TIME}; }; SpeechRecognitionServiceImplMock::SpeechRecognitionServiceImplMock( mojo::PendingReceiver<media::mojom::SpeechRecognitionService> receiver) : SpeechRecognitionServiceImpl(std::move(receiver)), test_factory_receiver_(&test_url_loader_factory_) { TestingBrowserProcess::GetGlobal()->SetSharedURLLoaderFactory( base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>( &test_url_loader_factory_)); } mojo::PendingRemote<network::mojom::URLLoaderFactory> SpeechRecognitionServiceImplMock::GetUrlLoaderFactory() { return test_factory_receiver_.BindNewPipeAndPassRemote(); } std::vector<network::TestURLLoaderFactory::PendingRequest>* SpeechRecognitionServiceImplMock::GetPendingRequests() { return test_url_loader_factory_.pending_requests(); } int SpeechRecognitionServiceImplMock::GetNumPending() { return test_url_loader_factory_.NumPending(); } void SpeechRecognitionServiceImplMock::ResetNetwork() { test_factory_receiver_.reset(); } CloudSpeechRecognitionClientUnitTest::CloudSpeechRecognitionClientUnitTest() = default; void CloudSpeechRecognitionClientUnitTest::SetUp() { client_under_test_ = std::make_unique<CloudSpeechRecognitionClient>( media::BindToCurrentLoop(base::BindRepeating( &CloudSpeechRecognitionClientUnitTest::OnRecognitionEvent, base::Unretained(this))), nullptr); speech_recognition_service_impl_ = std::make_unique<SpeechRecognitionServiceImplMock>( remote_.BindNewPipeAndPassReceiver()); client_under_test_->SetUrlLoaderFactoryForTesting( speech_recognition_service_impl_->GetUrlLoaderFactory()); CloudSpeechConfig config; config.sample_rate = 48000; config.channel_count = 2; config.language_code = "en-US"; client_under_test_->Initialize(config); // Run the loop to guarantee that the upstream and downstream loaders have // started. while (!GetUpstreamRequest() || !GetDownstreamRequest()) { task_environment_.RunUntilIdle(); } } void CloudSpeechRecognitionClientUnitTest::OnRecognitionEvent( media::SpeechRecognitionResult result) { results_.push(result.transcription); is_final_ = result.is_final; } void CloudSpeechRecognitionClientUnitTest::InjectDummyAudio() { DCHECK(client_under_test_.get()); char dummy_audio_buffer_data[kDummyAudioBytes] = {'\0'}; client_under_test_->AddAudio(base::span<char>( &dummy_audio_buffer_data[0], sizeof(dummy_audio_buffer_data))); } void CloudSpeechRecognitionClientUnitTest::InitializeUpstreamPipeIfNecessary() { if (!upstream_data_pipe_.get()) { if (!chunked_data_pipe_getter_) { const network::TestURLLoaderFactory::PendingRequest* upstream_request = GetUpstreamRequest(); EXPECT_TRUE(upstream_request); EXPECT_TRUE(upstream_request->request.request_body); auto& mutable_elements = *upstream_request->request.request_body->elements_mutable(); ASSERT_EQ(1u, mutable_elements.size()); ASSERT_EQ(network::DataElement::Tag::kChunkedDataPipe, mutable_elements[0].type()); chunked_data_pipe_getter_.Bind( mutable_elements[0] .As<network::DataElementChunkedDataPipe>() .ReleaseChunkedDataPipeGetter()); } constexpr size_t kDataPipeCapacity = 256; const MojoCreateDataPipeOptions data_pipe_options{ sizeof(MojoCreateDataPipeOptions), MOJO_CREATE_DATA_PIPE_FLAG_NONE, 1, kDataPipeCapacity}; mojo::ScopedDataPipeProducerHandle producer_end; mojo::ScopedDataPipeConsumerHandle consumer_end; CHECK_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(&data_pipe_options, producer_end, consumer_end)); chunked_data_pipe_getter_->StartReading(std::move(producer_end)); upstream_data_pipe_ = std::move(consumer_end); } } std::string CloudSpeechRecognitionClientUnitTest::ConsumeChunkedUploadData( uint32_t expected_num_bytes) { InitializeUpstreamPipeIfNecessary(); EXPECT_TRUE(upstream_data_pipe_.is_valid()); std::string out; while (true) { task_environment_.RunUntilIdle(); const void* data; uint32_t num_bytes = 0; MojoResult result = upstream_data_pipe_->BeginReadData( &data, &num_bytes, MOJO_READ_DATA_FLAG_NONE); expected_num_bytes -= num_bytes; if (result == MOJO_RESULT_OK) { out.append(static_cast<const char*>(data), num_bytes); upstream_data_pipe_->EndReadData(num_bytes); continue; } if (result == MOJO_RESULT_SHOULD_WAIT) { if (expected_num_bytes > 0) { continue; } else { break; } } LOG(INFO) << "Mojo pipe unexpectedly closed with result:" << result; break; } return out; } // Returns the latest upstream request. const network::TestURLLoaderFactory::PendingRequest* CloudSpeechRecognitionClientUnitTest::GetUpstreamRequest() { auto* pending_requests = speech_recognition_service_impl_->GetPendingRequests(); for (int i = pending_requests->size() - 1; i >= 0; i--) { const auto& pending_request = (*pending_requests)[i]; if (pending_request.request.url.spec().find("/up") != std::string::npos) return &pending_request; } return nullptr; } // Returns the latest downstream request. const network::TestURLLoaderFactory::PendingRequest* CloudSpeechRecognitionClientUnitTest::GetDownstreamRequest() { auto* pending_requests = speech_recognition_service_impl_->GetPendingRequests(); for (int i = pending_requests->size() - 1; i >= 0; i--) { const auto& pending_request = (*pending_requests)[i]; if (pending_request.request.url.spec().find("/down") != std::string::npos) return &pending_request; } return nullptr; } void CloudSpeechRecognitionClientUnitTest:: ProvideMockResponseStartDownstreamIfNeeded() { if (downstream_data_pipe_.get()) return; const network::TestURLLoaderFactory::PendingRequest* downstream_request = GetDownstreamRequest(); ASSERT_TRUE(downstream_request); auto head = network::mojom::URLResponseHead::New(); std::string headers("HTTP/1.1 200 OK\n\n"); head->headers = base::MakeRefCounted<net::HttpResponseHeaders>( net::HttpUtil::AssembleRawHeaders(headers)); downstream_request->client->OnReceiveResponse(std::move(head)); constexpr size_t kDataPipeCapacity = 256; const MojoCreateDataPipeOptions data_pipe_options{ sizeof(MojoCreateDataPipeOptions), MOJO_CREATE_DATA_PIPE_FLAG_NONE, 1, kDataPipeCapacity}; mojo::ScopedDataPipeProducerHandle producer_end; mojo::ScopedDataPipeConsumerHandle consumer_end; CHECK_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(&data_pipe_options, producer_end, consumer_end)); downstream_request->client->OnStartLoadingResponseBody( std::move(consumer_end)); downstream_data_pipe_ = std::move(producer_end); } void CloudSpeechRecognitionClientUnitTest::ProvideMockStringResponseDownstream( const std::string& response_string) { ProvideMockResponseStartDownstreamIfNeeded(); uint32_t written = 0; while (written < response_string.size()) { uint32_t write_bytes = response_string.size() - written; MojoResult result = downstream_data_pipe_->WriteData( response_string.data() + written, &write_bytes, MOJO_WRITE_DATA_FLAG_NONE); if (result == MOJO_RESULT_OK) { written += write_bytes; continue; } if (result == MOJO_RESULT_SHOULD_WAIT) { task_environment_.RunUntilIdle(); continue; } FAIL() << "Mojo write failed unexpectedly with result:" << result; } // Flush the mojo pipe. task_environment_.RunUntilIdle(); } void CloudSpeechRecognitionClientUnitTest::ProvideMockProtoResultDownstream( const content::proto::SpeechRecognitionEvent& result) { ProvideMockResponseStartDownstreamIfNeeded(); ASSERT_TRUE(downstream_data_pipe_.get()); ASSERT_TRUE(downstream_data_pipe_.is_valid()); ProvideMockStringResponseDownstream(SerializeProtobufResponse(result)); } void CloudSpeechRecognitionClientUnitTest::ProvideMockResultDownstream( std::vector<std::string> result_strings, bool is_final) { std::vector<blink::mojom::SpeechRecognitionResultPtr> results; results.push_back(blink::mojom::SpeechRecognitionResult::New()); blink::mojom::SpeechRecognitionResultPtr& result = results.back(); result->is_provisional = false; for (std::string result_string : result_strings) { result->hypotheses.push_back(blink::mojom::SpeechRecognitionHypothesis::New( base::UTF8ToUTF16(result_string), 0.1F)); } content::proto::SpeechRecognitionEvent proto_event; proto_event.set_status( content::proto::SpeechRecognitionEvent::STATUS_SUCCESS); content::proto::SpeechRecognitionResult* proto_result = proto_event.add_result(); proto_result->set_final(is_final); proto_result->set_stability(1.0); for (const auto& hypothesis : result->hypotheses) { content::proto::SpeechRecognitionAlternative* proto_alternative = proto_result->add_alternative(); proto_alternative->set_confidence(hypothesis->confidence); proto_alternative->set_transcript(base::UTF16ToUTF8(hypothesis->utterance)); } ProvideMockProtoResultDownstream(proto_event); } std::string CloudSpeechRecognitionClientUnitTest::SerializeProtobufResponse( const content::proto::SpeechRecognitionEvent& msg) { std::string msg_string; msg.SerializeToString(&msg_string); // Prepend 4 byte prefix length indication to the protobuf message as // envisaged by the google streaming recognition webservice protocol. uint32_t prefix = HostToNet32(checked_cast<uint32_t>(msg_string.size())); msg_string.insert(0, reinterpret_cast<char*>(&prefix), sizeof(prefix)); return msg_string; } void CloudSpeechRecognitionClientUnitTest::ExpectResultsReceived( const std::vector<std::string>& expected_results, bool is_final) { ASSERT_GE(1U, results_.size()); std::string expected_transcription; for (std::string result : expected_results) { expected_transcription += result; } ASSERT_EQ(is_final, is_final_); ASSERT_TRUE(!expected_transcription.empty()); ASSERT_TRUE(expected_transcription == results_.front()); results_.pop(); } TEST_F(CloudSpeechRecognitionClientUnitTest, StreamingRecognition) { ASSERT_TRUE(client_under_test_->IsInitialized()); ASSERT_TRUE(GetUpstreamRequest()); ASSERT_TRUE(GetDownstreamRequest()); ASSERT_EQ("", ConsumeChunkedUploadData(0)); InjectDummyAudio(); ASSERT_FALSE(ConsumeChunkedUploadData(kDummyAudioBytes).empty()); // Simulate a protobuf message streamed from the server containing a single // result with two hypotheses. std::vector<std::string> result_strings; result_strings.push_back("hypothesis 1"); result_strings.push_back("hypothesis 2"); bool is_final = false; ProvideMockResultDownstream(result_strings, is_final); ExpectResultsReceived(result_strings, is_final); } TEST_F(CloudSpeechRecognitionClientUnitTest, DidAudioPropertyChange) { ASSERT_FALSE(client_under_test_->DidAudioPropertyChange(48000, 2)); ASSERT_TRUE(client_under_test_->DidAudioPropertyChange(48000, 1)); ASSERT_TRUE(client_under_test_->DidAudioPropertyChange(44100, 2)); ASSERT_TRUE(client_under_test_->DidAudioPropertyChange(44100, 1)); } // Verifies that invalid response strings are handled appropriately. TEST_F(CloudSpeechRecognitionClientUnitTest, InvalidResponseString) { ASSERT_TRUE(client_under_test_->IsInitialized()); ASSERT_TRUE(GetUpstreamRequest()); ASSERT_TRUE(GetDownstreamRequest()); ASSERT_EQ("", ConsumeChunkedUploadData(0)); InjectDummyAudio(); ASSERT_FALSE(ConsumeChunkedUploadData(kDummyAudioBytes).empty()); ProvideMockStringResponseDownstream("INVALID RESPONSE STRING"); ASSERT_TRUE(results_.empty()); } // Verifies that the client gracefully recovers from network crashes. TEST_F(CloudSpeechRecognitionClientUnitTest, NetworkReset) { ASSERT_TRUE(client_under_test_->IsInitialized()); ASSERT_TRUE(GetUpstreamRequest()); ASSERT_TRUE(GetDownstreamRequest()); ASSERT_EQ("", ConsumeChunkedUploadData(0)); InjectDummyAudio(); ASSERT_FALSE(ConsumeChunkedUploadData(kDummyAudioBytes).empty()); // Simulate a network crash by resetting the URL loader factory receiver. speech_recognition_service_impl_->ResetNetwork(); InjectDummyAudio(); ASSERT_FALSE(ConsumeChunkedUploadData(kDummyAudioBytes).empty()); ASSERT_TRUE(GetUpstreamRequest()); ASSERT_TRUE(GetDownstreamRequest()); // Simulate a protobuf message streamed from the server containing a single // result with one hypothesis. std::vector<std::string> result_strings; result_strings.push_back("hypothesis 1"); bool is_final = false; ProvideMockResultDownstream(result_strings, is_final); ExpectResultsReceived(result_strings, is_final); } // Verifies that the stream is reset after 295 seconds. The Open Speech API // supports a maximum recognition time of 5 minutes, so we must reset the stream // with a new request key before then. TEST_F(CloudSpeechRecognitionClientUnitTest, StreamReset) { ASSERT_TRUE(client_under_test_->IsInitialized()); ASSERT_TRUE(GetUpstreamRequest()); ASSERT_TRUE(GetDownstreamRequest()); ASSERT_EQ("", ConsumeChunkedUploadData(0)); std::string UploadUrlBeforeReset = GetUpstreamRequest()->request.url.spec(); std::string DownloadUrlBeforeReset = GetDownstreamRequest()->request.url.spec(); // Fast forward by 325 total seconds to trigger a reset. for (int i = 0; i < 13; i++) { InjectDummyAudio(); task_environment_.FastForwardBy(base::Seconds(25)); } ASSERT_EQ(2, speech_recognition_service_impl_->GetNumPending()); std::string UploadUrlAfterReset = GetUpstreamRequest()->request.url.spec(); std::string DownloadUrlAfterReset = GetDownstreamRequest()->request.url.spec(); // The URLs after the reset should contain a different request key. ASSERT_NE(UploadUrlBeforeReset, UploadUrlAfterReset); ASSERT_NE(DownloadUrlBeforeReset, DownloadUrlAfterReset); } // Verifies that the stream is reset if the audio is paused for longer than 30 // seconds. TEST_F(CloudSpeechRecognitionClientUnitTest, StreamResetAfterPause) { ASSERT_TRUE(client_under_test_->IsInitialized()); ASSERT_TRUE(GetUpstreamRequest()); ASSERT_TRUE(GetDownstreamRequest()); ASSERT_EQ("", ConsumeChunkedUploadData(0)); InjectDummyAudio(); std::string UploadUrlBeforeReset = GetUpstreamRequest()->request.url.spec(); std::string DownloadUrlBeforeReset = GetDownstreamRequest()->request.url.spec(); // Fast forward by 35 seconds to trigger a reset. task_environment_.FastForwardBy(base::Seconds(35)); InjectDummyAudio(); ASSERT_EQ(2, speech_recognition_service_impl_->GetNumPending()); std::string UploadUrlAfterReset = GetUpstreamRequest()->request.url.spec(); std::string DownloadUrlAfterReset = GetDownstreamRequest()->request.url.spec(); // The URLs after the reset should contain a different request key. ASSERT_NE(UploadUrlBeforeReset, UploadUrlAfterReset); ASSERT_NE(DownloadUrlBeforeReset, DownloadUrlAfterReset); } TEST_F(CloudSpeechRecognitionClientUnitTest, FinalRecognitionResult) { ASSERT_TRUE(client_under_test_->IsInitialized()); ASSERT_TRUE(GetUpstreamRequest()); ASSERT_TRUE(GetDownstreamRequest()); ASSERT_EQ("", ConsumeChunkedUploadData(0)); InjectDummyAudio(); ASSERT_FALSE(ConsumeChunkedUploadData(kDummyAudioBytes).empty()); // Simulate a protobuf message streamed from the server containing a single // result. std::vector<std::string> result_strings; result_strings.push_back("hypothesis 2"); bool is_final = true; ProvideMockResultDownstream(result_strings, is_final); ExpectResultsReceived(result_strings, is_final); } // Verify that the leading whitespace is trimmed. TEST_F(CloudSpeechRecognitionClientUnitTest, TrimLeadingWhitespace) { ASSERT_TRUE(client_under_test_->IsInitialized()); ASSERT_TRUE(GetUpstreamRequest()); ASSERT_TRUE(GetDownstreamRequest()); ASSERT_EQ("", ConsumeChunkedUploadData(0)); InjectDummyAudio(); ASSERT_FALSE(ConsumeChunkedUploadData(kDummyAudioBytes).empty()); // Simulate a protobuf message streamed from the server containing two // results. std::vector<std::string> result_strings; result_strings.push_back(" hypothesis 1"); result_strings.push_back(" hypothesis 2"); std::vector<std::string> expected_result_strings; expected_result_strings.push_back("hypothesis 1"); expected_result_strings.push_back(" hypothesis 2"); bool is_final = false; ProvideMockResultDownstream(result_strings, is_final); ExpectResultsReceived(expected_result_strings, is_final); } } // namespace speech
37.081272
82
0.768296
[ "vector" ]
4f54991daded1c4d837d0ee2dfe3526d4eabb514
11,707
cpp
C++
kratos/sources/connectivity_preserve_modeler.cpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
2
2019-10-25T09:28:10.000Z
2019-11-21T12:51:46.000Z
kratos/sources/connectivity_preserve_modeler.cpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
13
2019-10-07T12:06:51.000Z
2020-02-18T08:48:33.000Z
kratos/sources/connectivity_preserve_modeler.cpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
null
null
null
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Riccardo Rossi // // #include "modeler/connectivity_preserve_modeler.h" #include "utilities/variable_utils.h" namespace Kratos { // Public methods ////////////////////////////////////////////////////////////// void ConnectivityPreserveModeler::GenerateModelPart( ModelPart& rOriginModelPart, ModelPart& rDestinationModelPart, Element const& rReferenceElement, Condition const& rReferenceBoundaryCondition) { KRATOS_TRY; this->CheckVariableLists(rOriginModelPart, rDestinationModelPart); this->ResetModelPart(rDestinationModelPart); this->CopyCommonData(rOriginModelPart, rDestinationModelPart); this->DuplicateElements(rOriginModelPart, rDestinationModelPart, rReferenceElement); this->DuplicateConditions(rOriginModelPart, rDestinationModelPart, rReferenceBoundaryCondition); this->DuplicateCommunicatorData(rOriginModelPart,rDestinationModelPart); this->DuplicateSubModelParts(rOriginModelPart, rDestinationModelPart); KRATOS_CATCH(""); } void ConnectivityPreserveModeler::GenerateModelPart( ModelPart& rOriginModelPart, ModelPart& rDestinationModelPart, Element const& rReferenceElement) { KRATOS_TRY; this->CheckVariableLists(rOriginModelPart, rDestinationModelPart); this->ResetModelPart(rDestinationModelPart); this->CopyCommonData(rOriginModelPart, rDestinationModelPart); this->DuplicateElements(rOriginModelPart, rDestinationModelPart, rReferenceElement); this->DuplicateCommunicatorData(rOriginModelPart,rDestinationModelPart); this->DuplicateSubModelParts(rOriginModelPart, rDestinationModelPart); KRATOS_CATCH(""); } void ConnectivityPreserveModeler::GenerateModelPart( ModelPart& rOriginModelPart, ModelPart& rDestinationModelPart, Condition const& rReferenceCondition) { KRATOS_TRY; this->CheckVariableLists(rOriginModelPart, rDestinationModelPart); this->ResetModelPart(rDestinationModelPart); this->CopyCommonData(rOriginModelPart, rDestinationModelPart); this->DuplicateConditions(rOriginModelPart, rDestinationModelPart, rReferenceCondition); this->DuplicateCommunicatorData(rOriginModelPart,rDestinationModelPart); this->DuplicateSubModelParts(rOriginModelPart, rDestinationModelPart); KRATOS_CATCH(""); } // Private methods ///////////////////////////////////////////////////////////// void ConnectivityPreserveModeler::CheckVariableLists(ModelPart& rOriginModelPart, ModelPart& rDestinationModelPart) const { //check that the variable lists are matching const auto& r_destination_variable_list = rDestinationModelPart.GetNodalSolutionStepVariablesList(); const auto& r_origin_variable_list = rOriginModelPart.GetNodalSolutionStepVariablesList(); for (const auto& var : r_destination_variable_list) { KRATOS_WARNING_IF("VARIABLE LIST MISMATCH - ", !r_origin_variable_list.Has(var)) << "Variable: " << var << " is in rDestinationModelPart variables " << "but not in the rOriginModelPart variables" << std::endl; } for (const auto& var : r_origin_variable_list) { KRATOS_WARNING_IF("VARIABLE LIST MISMATCH - ", !r_destination_variable_list.Has(var)) << "Variable: " << var << " is in rOriginModelPart variables " << "but not in the rDestinationModelPart variables" << std::endl; } } void ConnectivityPreserveModeler::ResetModelPart(ModelPart& rDestinationModelPart) const { VariableUtils().SetFlag(TO_ERASE, true, rDestinationModelPart.Nodes()); VariableUtils().SetFlag(TO_ERASE, true, rDestinationModelPart.Elements()); VariableUtils().SetFlag(TO_ERASE, true, rDestinationModelPart.Conditions()); rDestinationModelPart.RemoveNodesFromAllLevels(TO_ERASE); rDestinationModelPart.RemoveElementsFromAllLevels(TO_ERASE); rDestinationModelPart.RemoveConditionsFromAllLevels(TO_ERASE); } void ConnectivityPreserveModeler::CopyCommonData( ModelPart& rOriginModelPart, ModelPart& rDestinationModelPart) const { // Do not try to change some of the things we need to change if the destination is a SubModelPart if( rDestinationModelPart.IsSubModelPart() ) { KRATOS_ERROR_IF_NOT(rOriginModelPart.GetNodalSolutionStepVariablesList() == rDestinationModelPart.GetNodalSolutionStepVariablesList()) << "Attempting to change the SolutionStepVariablesList of the Destination Model Part, which is a SubModelPart." << std::endl << "Aborting, since this would break its parent ModelPart." << std::endl; KRATOS_ERROR_IF_NOT(rDestinationModelPart.GetBufferSize() == rOriginModelPart.GetBufferSize()) << "Attempting to change the BufferSize of the Destination Model Part, which is a SubModelPart." << std::endl << "Aborting, since this would break its parent ModelPart." << std::endl; } else { rDestinationModelPart.SetNodalSolutionStepVariablesList(rOriginModelPart.pGetNodalSolutionStepVariablesList()); rDestinationModelPart.SetBufferSize( rOriginModelPart.GetBufferSize() ); } // These should be safe for SubModelParts rDestinationModelPart.SetProcessInfo( rOriginModelPart.pGetProcessInfo() ); rDestinationModelPart.SetProperties( rOriginModelPart.pProperties() ); rDestinationModelPart.Tables() = rOriginModelPart.Tables(); // Assign the nodes to the new model part rDestinationModelPart.AddNodes(rOriginModelPart.NodesBegin(), rOriginModelPart.NodesEnd()); } void ConnectivityPreserveModeler::DuplicateElements( ModelPart& rOriginModelPart, ModelPart& rDestinationModelPart, const Element& rReferenceElement) const { // Generate the elements ModelPart::ElementsContainerType temp_elements; temp_elements.reserve(rOriginModelPart.NumberOfElements()); for (auto i_elem = rOriginModelPart.ElementsBegin(); i_elem != rOriginModelPart.ElementsEnd(); ++i_elem) { Properties::Pointer properties = i_elem->pGetProperties(); // Reuse the geometry of the old element (to save memory) Element::Pointer p_element = rReferenceElement.Create(i_elem->Id(), i_elem->pGetGeometry(), properties); temp_elements.push_back(p_element); } rDestinationModelPart.AddElements(temp_elements.begin(), temp_elements.end()); } void ConnectivityPreserveModeler::DuplicateConditions( ModelPart& rOriginModelPart, ModelPart& rDestinationModelPart, const Condition& rReferenceBoundaryCondition) const { // Generate the conditions ModelPart::ConditionsContainerType temp_conditions; temp_conditions.reserve(rOriginModelPart.NumberOfConditions()); for (auto i_cond = rOriginModelPart.ConditionsBegin(); i_cond != rOriginModelPart.ConditionsEnd(); ++i_cond) { Properties::Pointer properties = i_cond->pGetProperties(); // Reuse the geometry of the old element (to save memory) Condition::Pointer p_condition = rReferenceBoundaryCondition.Create(i_cond->Id(), i_cond->pGetGeometry(), properties); temp_conditions.push_back(p_condition); } rDestinationModelPart.AddConditions(temp_conditions.begin(), temp_conditions.end()); } void ConnectivityPreserveModeler::DuplicateCommunicatorData( ModelPart& rOriginModelPart, ModelPart& rDestinationModelPart) const { /* Create a new communicator for rDestinationModelPart and fill it with the information of the original one * Only "general" information and node lists are copied, element and condition lists will be created later * using the new elements. */ Communicator& rReferenceComm = rOriginModelPart.GetCommunicator(); Communicator::Pointer pDestinationComm = rReferenceComm.Create(); pDestinationComm->SetNumberOfColors( rReferenceComm.GetNumberOfColors() ); pDestinationComm->NeighbourIndices() = rReferenceComm.NeighbourIndices(); if (rReferenceComm.IsDistributed()) { pDestinationComm->LocalMesh().SetNodes( rReferenceComm.LocalMesh().pNodes() ); pDestinationComm->InterfaceMesh().SetNodes( rReferenceComm.InterfaceMesh().pNodes() ); pDestinationComm->GhostMesh().SetNodes( rReferenceComm.GhostMesh().pNodes() ); for (unsigned int i = 0; i < rReferenceComm.GetNumberOfColors(); i++) { pDestinationComm->pLocalMesh(i)->SetNodes( rReferenceComm.pLocalMesh(i)->pNodes() ); pDestinationComm->pInterfaceMesh(i)->SetNodes( rReferenceComm.pInterfaceMesh(i)->pNodes() ); pDestinationComm->pGhostMesh(i)->SetNodes( rReferenceComm.pGhostMesh(i)->pNodes() ); } // All elements are passed as local elements to the new communicator ModelPart::ElementsContainerType& rDestinationLocalElements = pDestinationComm->LocalMesh().Elements(); rDestinationLocalElements.clear(); rDestinationLocalElements.reserve(rDestinationModelPart.NumberOfElements()); for (auto i_elem = rDestinationModelPart.Elements().ptr_begin(); i_elem != rDestinationModelPart.Elements().ptr_end(); ++i_elem) { rDestinationLocalElements.push_back(*i_elem); } // Do the same for Conditions ModelPart::ConditionsContainerType& rDestinationLocalConditions = pDestinationComm->LocalMesh().Conditions(); rDestinationLocalConditions.clear(); rDestinationLocalConditions.reserve(rDestinationModelPart.NumberOfConditions()); for (auto i_cond = rDestinationModelPart.Conditions().ptr_begin(); i_cond != rDestinationModelPart.Conditions().ptr_end(); ++i_cond) { rDestinationLocalConditions.push_back(*i_cond); } } else { pDestinationComm->SetLocalMesh(rDestinationModelPart.pGetMesh()); } rDestinationModelPart.SetCommunicator( pDestinationComm ); } void ConnectivityPreserveModeler::DuplicateSubModelParts( ModelPart& rOriginModelPart, ModelPart& rDestinationModelPart) const { for (auto i_part = rOriginModelPart.SubModelPartsBegin(); i_part != rOriginModelPart.SubModelPartsEnd(); ++i_part) { if(!rDestinationModelPart.HasSubModelPart(i_part->Name())) { rDestinationModelPart.CreateSubModelPart(i_part->Name()); } ModelPart& destination_part = rDestinationModelPart.GetSubModelPart(i_part->Name()); destination_part.AddNodes(i_part->NodesBegin(), i_part->NodesEnd()); std::vector<ModelPart::IndexType> ids; ids.reserve(i_part->Elements().size()); // Execute only if we created elements in the destination if (rDestinationModelPart.NumberOfElements() > 0) { //adding by index for(auto it=i_part->ElementsBegin(); it!=i_part->ElementsEnd(); ++it) ids.push_back(it->Id()); destination_part.AddElements(ids, 0); //adding by index } // Execute only if we created conditions in the destination if (rDestinationModelPart.NumberOfConditions() > 0) { ids.clear(); for(auto it=i_part->ConditionsBegin(); it!=i_part->ConditionsEnd(); ++it) ids.push_back(it->Id()); destination_part.AddConditions(ids, 0); } // Duplicate the Communicator for this SubModelPart this->DuplicateCommunicatorData(*i_part, destination_part); // Recursively call this function to duplicate any child SubModelParts this->DuplicateSubModelParts(*i_part, destination_part); } } }
42.263538
142
0.722901
[ "geometry", "vector", "model" ]
4f564f47d7809b7ecd76bdcf56c03047fa49db6c
9,202
cpp
C++
backends/imgui_impl_sdlrenderer.cpp
tcarrel/imgui
306d6e14589cd228103af7d72f08dc2314a4c698
[ "MIT" ]
1
2021-09-23T08:44:23.000Z
2021-09-23T08:44:23.000Z
backends/imgui_impl_sdlrenderer.cpp
tcarrel/imgui
306d6e14589cd228103af7d72f08dc2314a4c698
[ "MIT" ]
1
2021-09-14T19:15:34.000Z
2021-09-14T19:15:34.000Z
backends/imgui_impl_sdlrenderer.cpp
tcarrel/imgui
306d6e14589cd228103af7d72f08dc2314a4c698
[ "MIT" ]
1
2021-09-12T18:24:12.000Z
2021-09-12T18:24:12.000Z
// dear imgui: Renderer Backend for SDL_Renderer // (Requires: SDL 2.0.17+) // Important to understand: SDL_Renderer is an _optional_ component of SDL. We do not recommend you use SDL_Renderer // because it provide a rather limited API to the end-user. We provide this backend for the sake of completeness. // For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. // Implemented features: // [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! // Missing features: // [ ] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Read online: https://github.com/ocornut/imgui/tree/master/docs // CHANGELOG // 2021-09-21: Initial version. #include "imgui.h" #include "imgui_impl_sdlrenderer.h" #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier #include <stddef.h> // intptr_t #else #include <stdint.h> // intptr_t #endif // SDL #include <SDL.h> #if !SDL_VERSION_ATLEAST(2,0,17) #error This backend requires SDL 2.0.17+ because of SDL_RenderGeometry() function #endif // SDL_Renderer data struct ImGui_ImplSDLRenderer_Data { SDL_Renderer* SDLRenderer; SDL_Texture* FontTexture; ImGui_ImplSDLRenderer_Data() { memset(this, 0, sizeof(*this)); } }; // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. static ImGui_ImplSDLRenderer_Data* ImGui_ImplSDLRenderer_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplSDLRenderer_Data*)ImGui::GetIO().BackendRendererUserData : NULL; } // Functions bool ImGui_ImplSDLRenderer_Init(SDL_Renderer* renderer) { ImGuiIO& io = ImGui::GetIO(); IM_ASSERT(io.BackendRendererUserData == NULL && "Already initialized a renderer backend!"); IM_ASSERT(renderer != NULL && "SDL_Renderer not initialized!"); // Setup backend capabilities flags ImGui_ImplSDLRenderer_Data* bd = IM_NEW(ImGui_ImplSDLRenderer_Data)(); io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_sdlrenderer"; bd->SDLRenderer = renderer; return true; } void ImGui_ImplSDLRenderer_Shutdown() { ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData(); IM_ASSERT(bd != NULL && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); ImGui_ImplSDLRenderer_DestroyDeviceObjects(); io.BackendRendererName = NULL; io.BackendRendererUserData = NULL; IM_DELETE(bd); } static void ImGui_ImplSDLRenderer_SetupRenderState() { ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData(); // Clear out any viewports and cliprect set by the user // FIXME: Technically speaking there are lots of other things we could backup/setup/restore during our render process. SDL_RenderSetViewport(bd->SDLRenderer, NULL); SDL_RenderSetClipRect(bd->SDLRenderer, NULL); } void ImGui_ImplSDLRenderer_NewFrame() { ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData(); IM_ASSERT(bd != NULL && "Did you call ImGui_ImplSDLRenderer_Init()?"); if (!bd->FontTexture) ImGui_ImplSDLRenderer_CreateDeviceObjects(); } void ImGui_ImplSDLRenderer_RenderDrawData(ImDrawData* draw_data) { ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData(); // If there's a scale factor set by the user, use that instead // If the user has specified a scale factor to SDL_Renderer already via SDL_RenderSetScale(), SDL will scale whatever we pass // to SDL_RenderGeometryRaw() by that scale factor. In that case we don't want to be also scaling it ourselves here. float rsx = 1.0f; float rsy = 1.0f; SDL_RenderGetScale(bd->SDLRenderer, &rsx, &rsy); ImVec2 render_scale; render_scale.x = (rsx == 1.0f) ? draw_data->FramebufferScale.x : 1.0f; render_scale.y = (rsy == 1.0f) ? draw_data->FramebufferScale.y : 1.0f; // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) int fb_width = (int)(draw_data->DisplaySize.x * render_scale.x); int fb_height = (int)(draw_data->DisplaySize.y * render_scale.y); if (fb_width == 0 || fb_height == 0) return; // Will project scissor/clipping rectangles into framebuffer space ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports ImVec2 clip_scale = render_scale; // Render command lists ImGui_ImplSDLRenderer_SetupRenderState(); for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback) { // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) ImGui_ImplSDLRenderer_SetupRenderState(); else pcmd->UserCallback(cmd_list, pcmd); } else { // Project scissor/clipping rectangles into framebuffer space ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); if (clip_min.x < 0.0f) { clip_min.x = 0.0f; } if (clip_min.y < 0.0f) { clip_min.y = 0.0f; } if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; } if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; } if (clip_max.x < clip_min.x || clip_max.y < clip_min.y) continue; SDL_Rect r = { (int)(clip_min.x), (int)(clip_min.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y) }; SDL_RenderSetClipRect(bd->SDLRenderer, &r); const float* xy = (const float*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, pos)); const float* uv = (const float*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, uv)); const int* color = (const int*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, col)); // Bind texture, Draw SDL_Texture* tex = (SDL_Texture*)pcmd->GetTexID(); SDL_RenderGeometryRaw(bd->SDLRenderer, tex, xy, (int)sizeof(ImDrawVert), color, (int)sizeof(ImDrawVert), uv, (int)sizeof(ImDrawVert), cmd_list->VtxBuffer.Size, idx_buffer + pcmd->IdxOffset, pcmd->ElemCount, sizeof(ImDrawIdx)); } } } } // Called by Init/NewFrame/Shutdown bool ImGui_ImplSDLRenderer_CreateFontsTexture() { ImGuiIO& io = ImGui::GetIO(); ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData(); // Build texture atlas unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. // Upload texture to graphics system bd->FontTexture = SDL_CreateTexture(bd->SDLRenderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STATIC, width, height); if (bd->FontTexture == NULL) { SDL_Log("error creating texture"); return false; } SDL_UpdateTexture(bd->FontTexture, NULL, pixels, 4 * width); SDL_SetTextureBlendMode(bd->FontTexture, SDL_BLENDMODE_BLEND); // Store our identifier io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture); return true; } void ImGui_ImplSDLRenderer_DestroyFontsTexture() { ImGuiIO& io = ImGui::GetIO(); ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData(); if (bd->FontTexture) { io.Fonts->SetTexID(0); SDL_DestroyTexture(bd->FontTexture); bd->FontTexture = NULL; } } bool ImGui_ImplSDLRenderer_CreateDeviceObjects() { return ImGui_ImplSDLRenderer_CreateFontsTexture(); } void ImGui_ImplSDLRenderer_DestroyDeviceObjects() { ImGui_ImplSDLRenderer_DestroyFontsTexture(); }
41.45045
366
0.69148
[ "render" ]
4f56e389de4d187ce82d0408bf99560caa2b59df
8,336
cpp
C++
tests/test_ED.cpp
ruelj2/ED_Lib
b48add475f392dc70aec0098c61a3b0f7c6e2d8f
[ "MIT" ]
null
null
null
tests/test_ED.cpp
ruelj2/ED_Lib
b48add475f392dc70aec0098c61a3b0f7c6e2d8f
[ "MIT" ]
null
null
null
tests/test_ED.cpp
ruelj2/ED_Lib
b48add475f392dc70aec0098c61a3b0f7c6e2d8f
[ "MIT" ]
null
null
null
#include "ED_Lib/EDLib.h" #include <iostream> #include "opencv2/ximgproc.hpp" #include "opencv2/imgcodecs.hpp" using namespace cv; using namespace std; using namespace cv::ximgproc; namespace EDLIB { int main(int argc, char **argv) { char *filename; if (argc > 1) filename = argv[1]; else filename = "billiard.jpg"; Mat testImg = imread(filename, 0); TickMeter tm; for (int i = 1; i < 5; i++) { cout << "\n#################################################"; cout << "\n####### ( " << i << " ) ORIGINAL & OPENCV COMPARISON ######"; cout << "\n#################################################\n"; Ptr<EdgeDrawing> ed = createEdgeDrawing(); ed->params.EdgeDetectionOperator = EdgeDrawing::SOBEL; ed->params.GradientThresholdValue = 36; ed->params.AnchorThresholdValue = 8; vector<Vec6d> ellipses; vector<Vec4f> lines; //Detection of edge segments from an input image tm.start(); //Call ED constructor ED testED = ED(testImg, SOBEL_OPERATOR, 36, 8, 1, 10, 1.0, true); tm.stop(); std::cout << "\ntestED.getEdgeImage() (Original) : " << tm.getTimeMilli() << endl; tm.reset(); tm.start(); ed->detectEdges(testImg); tm.stop(); std::cout << "detectEdges() (OpenCV) : " << tm.getTimeMilli() << endl; Mat edgeImg0 = testED.getEdgeImage(); Mat anchImg0 = testED.getAnchorImage(); Mat gradImg0 = testED.getGradImage(); Mat edgeImg1, diff; ed->getEdgeImage(edgeImg1); absdiff(edgeImg0, edgeImg1, diff); cout << "different pixel count : " << countNonZero(diff) << endl; imwrite("gradImg0.png", gradImg0); imwrite("anchImg0.png", anchImg0); imwrite("edgeImg0.png", edgeImg0); imwrite("edgeImg1.png", edgeImg1); imwrite("diff0.png", diff); //***************************** EDLINES Line Segment Detection ***************************** //Detection of lines segments from edge segments instead of input image //Therefore, redundant detection of edge segmens can be avoided tm.reset(); tm.start(); EDLines testEDLines = EDLines(testED); tm.stop(); cout << "-------------------------------------------------\n"; cout << "testEDLines.getLineImage() : " << tm.getTimeMilli() << endl; Mat lineImg0 = testEDLines.getLineImage(); //draws on an empty image imwrite("lineImg0.png", lineImg0); tm.reset(); tm.start(); ed->detectLines(lines); tm.stop(); cout << "detectLines() (OpenCV) : " << tm.getTimeMilli() << endl; Mat lineImg1 = Mat(lineImg0.rows, lineImg0.cols, CV_8UC1, Scalar(255)); for (int i = 0; i < lines.size(); i++) line(lineImg1, Point2d(lines[i][0], lines[i][1]), Point2d(lines[i][2], lines[i][3]), Scalar(0), 1, LINE_AA); absdiff(lineImg0, lineImg1, diff); cout << "different pixel count : " << countNonZero(diff) << endl; imwrite("lineImg1.png", lineImg1); imwrite("diff1.png", diff); //***************************** EDCIRCLES Circle Segment Detection ***************************** //Detection of circles from already available EDPF or ED image tm.reset(); tm.start(); EDCircles testEDCircles = EDCircles(testEDLines); tm.stop(); cout << "-------------------------------------------------\n"; cout << "EDCircles(testEDLines) : " << tm.getTimeMilli() << endl; tm.reset(); tm.start(); ed->detectEllipses(ellipses); tm.stop(); cout << "detectEllipses() (OpenCV) : " << tm.getTimeMilli() << endl; cout << "-------------------------------------------------\n"; vector<mCircle> found_circles = testEDCircles.getCircles(); vector<mEllipse> found_ellipses = testEDCircles.getEllipses(); Mat ellipsImg0 = Mat(lineImg0.rows, lineImg0.cols, CV_8UC3, Scalar::all(0)); Mat ellipsImg1 = Mat(lineImg0.rows, lineImg0.cols, CV_8UC3, Scalar::all(0)); for (int i = 0; i < found_circles.size(); i++) { Point center((int) found_circles[i].center.x, (int) found_circles[i].center.y); Size axes((int) found_circles[i].r, (int) found_circles[i].r); double angle(0.0); Scalar color = Scalar(0, 255, 0); ellipse(ellipsImg0, center, axes, angle, 0, 360, color, 1, LINE_AA); } for (int i = 0; i < found_ellipses.size(); i++) { Point center((int) found_ellipses[i].center.x, (int) found_ellipses[i].center.y); Size axes((int) found_ellipses[i].axes.width, (int) found_ellipses[i].axes.height); double angle = found_ellipses[i].theta * 180 / CV_PI; Scalar color = Scalar(255, 255, 0); ellipse(ellipsImg0, center, axes, angle, 0, 360, color, 1, LINE_AA); } for (size_t i = 0; i < ellipses.size(); i++) { Point center((int) ellipses[i][0], (int) ellipses[i][1]); Size axes((int) ellipses[i][2] + (int) ellipses[i][3], (int) ellipses[i][2] + (int) ellipses[i][4]); double angle(ellipses[i][5]); Scalar color = ellipses[i][2] == 0 ? Scalar(255, 255, 0) : Scalar(0, 255, 0); ellipse(ellipsImg1, center, axes, angle, 0, 360, color, 1, LINE_AA); } imwrite("ellipsImg0.png", ellipsImg0); imwrite("ellipsImg1.png", ellipsImg1); //************************** EDPF Parameter-free Edge Segment Detection ************************** // Detection of edge segments with parameter free ED (EDPF) tm.reset(); tm.start(); EDPF testEDPF = EDPF(testImg); tm.stop(); cout << "testEDPF.getEdgeImage() : " << tm.getTimeMilli() << endl; Ptr<EdgeDrawing> ed1 = createEdgeDrawing(); ed1->params.EdgeDetectionOperator = EdgeDrawing::PREWITT; ed1->params.GradientThresholdValue = 11; ed1->params.AnchorThresholdValue = 3; ed1->params.PFmode = true; tm.reset(); tm.start(); ed1->detectEdges(testImg); tm.stop(); std::cout << "detectEdges() PF (OpenCV) : " << tm.getTimeMilli() << endl; edgeImg0 = testEDPF.getEdgeImage(); ed->getEdgeImage(edgeImg1); absdiff(edgeImg0, edgeImg1, diff); cout << "different pixel count : " << countNonZero(diff) << endl; imwrite("edgePFImage0.png", edgeImg0); imwrite("edgePFImage1.png", edgeImg1); imwrite("diff2.png", diff); //*********************** EDCOLOR Edge Segment Detection from Color Images ********************** Mat colorImg = imread(filename); tm.reset(); tm.start(); EDColor testEDColor = EDColor(colorImg, 36); tm.stop(); cout << "-------------------------------------------------\n"; cout << "testEDColor : " << tm.getTimeMilli() << endl; tm.reset(); tm.start(); // get lines from color image EDLines colorLine = EDLines(testEDColor); tm.stop(); cout << "get lines from color image : " << tm.getTimeMilli() << endl; tm.reset(); tm.start(); // get circles from color image EDCircles colorCircle = EDCircles(testEDColor); tm.stop(); cout << "get circles from color image : " << tm.getTimeMilli() << endl; } return 0; } }
43.643979
116
0.482006
[ "vector" ]
4f57b981c7710e94cb2d3d20b19f37d654848aa5
2,177
cpp
C++
src/chain.cpp
devo2018/bony
628710c3535c484ea06298ecfe63b935572f7636
[ "MIT" ]
null
null
null
src/chain.cpp
devo2018/bony
628710c3535c484ea06298ecfe63b935572f7636
[ "MIT" ]
null
null
null
src/chain.cpp
devo2018/bony
628710c3535c484ea06298ecfe63b935572f7636
[ "MIT" ]
1
2018-12-15T20:54:22.000Z
2018-12-15T20:54:22.000Z
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2016-2017 The BONY developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chain.h" using namespace std; /** * CChain implementation */ void CChain::SetTip(CBlockIndex* pindex) { if (pindex == NULL) { vChain.clear(); return; } vChain.resize(pindex->nHeight + 1); while (pindex && vChain[pindex->nHeight] != pindex) { vChain[pindex->nHeight] = pindex; pindex = pindex->pprev; } } CBlockLocator CChain::GetLocator(const CBlockIndex* pindex) const { int nStep = 1; std::vector<uint256> vHave; vHave.reserve(32); if (!pindex) pindex = Tip(); while (pindex) { vHave.push_back(pindex->GetBlockHash()); // Stop when we have added the genesis block. if (pindex->nHeight == 0) break; // Exponentially larger steps back, plus the genesis block. int nHeight = std::max(pindex->nHeight - nStep, 0); if (Contains(pindex)) { // Use O(1) CChain index if possible. pindex = (*this)[nHeight]; } else { // Otherwise, use O(log n) skiplist. pindex = pindex->GetAncestor(nHeight); } if (vHave.size() > 10) nStep *= 2; } return CBlockLocator(vHave); } const CBlockIndex* CChain::FindFork(const CBlockIndex* pindex) const { if (pindex->nHeight > Height()) pindex = pindex->GetAncestor(Height()); while (pindex && !Contains(pindex)) pindex = pindex->pprev; return pindex; } uint256 CBlockIndex::GetBlockTrust() const { uint256 bnTarget; bnTarget.SetCompact(nBits); if (bnTarget <= 0) return 0; if (IsProofOfStake()) { // Return trust score as usual return (uint256(1) << 256) / (bnTarget + 1); } else { // Calculate work amount for block uint256 bnPoWTrust = ((~uint256(0) >> 20) / (bnTarget + 1)); return bnPoWTrust > 1 ? bnPoWTrust : 1; } }
27.2125
70
0.598071
[ "vector" ]
4f587cc1ec5288ae2b30034c10b4d81dab3e5ff0
3,142
cc
C++
ns-3-dev/src/mobility/model/constant-velocity-helper.cc
maxvonhippel/snake
0805773dc34e1480dffaae40174aa1f82d1c6ce8
[ "BSD-3-Clause" ]
11
2015-11-24T11:07:28.000Z
2021-12-23T04:10:29.000Z
ns-3-dev/src/mobility/model/constant-velocity-helper.cc
maxvonhippel/snake
0805773dc34e1480dffaae40174aa1f82d1c6ce8
[ "BSD-3-Clause" ]
null
null
null
ns-3-dev/src/mobility/model/constant-velocity-helper.cc
maxvonhippel/snake
0805773dc34e1480dffaae40174aa1f82d1c6ce8
[ "BSD-3-Clause" ]
6
2016-03-01T06:32:21.000Z
2022-03-24T19:31:41.000Z
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2006,2007 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #include "ns3/simulator.h" #include "ns3/rectangle.h" #include "ns3/box.h" #include "constant-velocity-helper.h" namespace ns3 { ConstantVelocityHelper::ConstantVelocityHelper () : m_paused (true) { } ConstantVelocityHelper::ConstantVelocityHelper (const Vector &position) : m_position (position), m_paused (true) { } ConstantVelocityHelper::ConstantVelocityHelper (const Vector &position, const Vector &vel) : m_position (position), m_velocity (vel), m_paused (true) { } void ConstantVelocityHelper::SetPosition (const Vector &position) { m_position = position; m_velocity = Vector (0.0, 0.0, 0.0); m_lastUpdate = Simulator::Now (); } Vector ConstantVelocityHelper::GetCurrentPosition (void) const { return m_position; } Vector ConstantVelocityHelper::GetVelocity (void) const { return m_paused ? Vector (0.0, 0.0, 0.0) : m_velocity; } void ConstantVelocityHelper::SetVelocity (const Vector &vel) { m_velocity = vel; m_lastUpdate = Simulator::Now (); } void ConstantVelocityHelper::Update (void) const { Time now = Simulator::Now (); NS_ASSERT (m_lastUpdate <= now); Time deltaTime = now - m_lastUpdate; m_lastUpdate = now; if (m_paused) { return; } double deltaS = deltaTime.GetSeconds (); m_position.x += m_velocity.x * deltaS; m_position.y += m_velocity.y * deltaS; m_position.z += m_velocity.z * deltaS; } void ConstantVelocityHelper::UpdateWithBounds (const Rectangle &bounds) const { Update (); m_position.x = std::min (bounds.xMax, m_position.x); m_position.x = std::max (bounds.xMin, m_position.x); m_position.y = std::min (bounds.yMax, m_position.y); m_position.y = std::max (bounds.yMin, m_position.y); } void ConstantVelocityHelper::UpdateWithBounds (const Box &bounds) const { Update (); m_position.x = std::min (bounds.xMax, m_position.x); m_position.x = std::max (bounds.xMin, m_position.x); m_position.y = std::min (bounds.yMax, m_position.y); m_position.y = std::max (bounds.yMin, m_position.y); m_position.z = std::min (bounds.zMax, m_position.z); m_position.z = std::max (bounds.zMin, m_position.z); } void ConstantVelocityHelper::Pause (void) { m_paused = true; } void ConstantVelocityHelper::Unpause (void) { m_paused = false; } } // namespace ns3
25.966942
76
0.703055
[ "vector" ]
4f5d7db82ef3ea58a03e0088015da905b0938125
16,540
cpp
C++
src/wcl/graphics/structuredlight/GrayCode.cpp
WearableComputerLab/LibWCL
e1687a8fd2f96bfec3a84221044cfb8b7126a79c
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/wcl/graphics/structuredlight/GrayCode.cpp
WearableComputerLab/LibWCL
e1687a8fd2f96bfec3a84221044cfb8b7126a79c
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/wcl/graphics/structuredlight/GrayCode.cpp
WearableComputerLab/LibWCL
e1687a8fd2f96bfec3a84221044cfb8b7126a79c
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
/*- * Copyright (c) 2010 Benjamin Close <Benjamin.Close@clearchain.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <assert.h> #include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include <iostream> #include "GrayCode.h" #define WHITE 255 #ifndef log2 #define log2(x) (log(x) / M_LN2) #endif namespace wcl { using namespace std; GrayCode::GrayCode(const unsigned ipwidth, const unsigned ipheight, const unsigned icwidth, const unsigned icheight ): pwidth(ipwidth), pheight(ipheight), totalGrayCodes(0), codedImages(NULL),stage(0), decodedColumns(icwidth, icheight), decodedRows(icwidth, icheight), cwidth(icwidth),cheight(icheight),mask(NULL) { // Work out how many patterns are needed for the // specified rows and columns. Since we are trying to // encode a binary sequence, this is: count = log2(x) // where x is the width or the height - depending if we // are encoding columns or rows. We also have to cater // for rounding in c hence we ceil to the next // highest value then cast the value to get count; this->grayCodeColumnCount = (unsigned)ceil(log2(this->pwidth)); this->grayCodeRowCount = (unsigned)ceil(log2(this->pheight)); // When considering the columns and the rows we also have to consider // that the width/height is not an exact factor of 2 (ie 800 pixels). // Hence we may have to shift the phase of a binary image so that // the binary bands line up correctly. this->grayCodeColumnPhase = (unsigned)floor((pow(2.0,this->grayCodeColumnCount)-this->pwidth)/2); this->grayCodeRowPhase = (unsigned)floor((pow(2.0,this->grayCodeRowCount)-this->pheight)/2); // Record the total amount of patterns required for // both the columns and the rows, we also cater for the inverts and the // initial images this->totalGrayCodes = ((this->grayCodeColumnCount + this->grayCodeRowCount) * 2) +4; // Create the data storage for the patterns. this->createStorage(); // Build the various images required for graycode displaying this->buildGrayCodes(); // zero the decode matrixes this->decodedColumns.storeZeros(); this->decodedRows.storeZeros(); // Clear our mask memset(this->mask, 0, this->cwidth * this->cheight); }; GrayCode::~GrayCode() { if( this->codedImages ){ for( unsigned i = 0; i < this->totalGrayCodes; i++ ) delete this->codedImages[i]; delete this->codedImages; } delete this->mask; } bool GrayCode::next() { this->stage++; if( this->stage >= this->totalGrayCodes){ this->stage=0; return false; } return true; } const unsigned char *GrayCode::generate() { return this->codedImages[this->stage]; } void GrayCode::buildGrayCodes() { // // Build the required gray code images. // When building the images we build both the initial image and // the image invert to aid in detection // // The first two images are the most sigificant bit and full black/white // this allows us to work out the region the graycodes are projected onto // We set the initial pattern here we calculate all inverts below unsigned char **codedColumnImages = this->codedImages; memset( *codedColumnImages, WHITE, this->pwidth * this->pheight ); codedColumnImages+=2; // We start by building the graycoded columns. for(unsigned column = 0; column < this->pwidth; column++ ) { for ( unsigned imageCount = 0; imageCount < this->grayCodeColumnCount; imageCount++ ){ unsigned char *data = codedColumnImages[imageCount*2]; // // Work out the value for this column // // Binary encoding. Put basically, a particular column over // grayCodeColumnCount images represents a binary number. What // we do here is work out what bit value that number is for this // particular (imageCount) image. Ie the number for column 0 is // always 0..n where n is grayCodeColumnCount long. Column 1 always // equates to 1 in binary. Hence in image 0 column 1 is black. In // image grayCodeColumnCount column 1 is white. // // To work what colour (white/black) a column should be in this particular image // we need to work out the bit value for this image. Hence if column =10 // which is binary n-4..1010 and we're in the second to last image the // column must be white. To calculate colour we bitshift the column // count (ie the value for the column) by the imagecount we are in. // This shifts the bit we care about down to the least significant // bit. We can simply test it using a bit comparison against 1 to // then see if we need to be white or black. // Now the only issue with this is we work from least significant // bit up to most siginificate bit. This makes decoding the number // harder. Hence instead we shift by grayCodeColumnCount-imageCount. // This then works from most significant bit down to least // significant bit which makes decoding easier. // // Take into account that the width and the height of an // image is not a power of two. Hence we offset each column/row by the // relevant phase shift to align the graycodes correctly. unsigned int realColumn = column + this->grayCodeColumnPhase; unsigned char value = imageCount ? ((realColumn >> (this->grayCodeColumnCount - imageCount -1))&1) ^ ((realColumn >> (this->grayCodeColumnCount - imageCount))&1) : (realColumn >> (this->grayCodeColumnCount - imageCount -1))&1; // We now update the value of the column to be in the range 0 // (black) or 255 (white). As this is what GL expects for a texture value *=WHITE; // Store the value in the image this->setPixel(data,column,0 /* y */, this->pwidth, value); // Copy the value down for all rows of the image. // after this the entire column for this image is set for( unsigned row = 1; row < this->pheight; row++ ) this->setPixel(data,column,row, this->pwidth, value); } } // // We now repeat the above setup but focus on the rows not // the columns // unsigned char **codedRowImages= codedColumnImages+(this->grayCodeColumnCount*2); memset( *codedRowImages, WHITE, this->pwidth * this->pheight ); codedRowImages+=2; for( unsigned row=0; row < this->pheight; row++){ for ( unsigned imageCount = 0; imageCount < this->grayCodeRowCount; imageCount++ ){ unsigned char *data = codedRowImages[imageCount*2]; unsigned int realRow = row + this->grayCodeRowPhase; unsigned char value = imageCount ? ((realRow >> (this->grayCodeRowCount - imageCount - 1 ))&1)^ ((realRow >> (this->grayCodeRowCount - imageCount))&1) : (realRow >> (this->grayCodeRowCount - imageCount -1)) & 1; #if 0 if(row == 0 )printf("row: %d, rowcount %d, imagecount %d, bit %d (%d), Bit Value %d, GC Value %d\n", realRow, this->grayCodeRowCount, imageCount, (this->grayCodeRowCount-imageCount-1),(int)pow(2,(this->grayCodeRowCount-imageCount-1)), (realRow >> (this->grayCodeRowCount - imageCount -1)) & 1, value); #endif value *=WHITE; this->setPixel(data,0 /* X */,row, this->pwidth, value); for( unsigned column = 1; column < this->pwidth; column++ ) this->setPixel(data,column,row, this->pwidth, value); } } // // Now create the invert images for each pattern // for( unsigned count = 0; count < this->totalGrayCodes; count+=2 ){ for( unsigned row = 0; row < this->pheight; row++ ){ for( unsigned column = 0; column < this->pwidth; column++ ){ this->codedImages[count+1][row*this->pwidth+column] = this->codedImages[count][row*this->pwidth+column] ? 0 : WHITE; } } } } /** * Create the memory required for all the required gray code images */ void GrayCode::createStorage() { this->codedImages = new unsigned char *[this->totalGrayCodes]; for( unsigned i = 0; i < this->totalGrayCodes; i++ ) this->codedImages[i] = new unsigned char [this->pwidth * this->pheight]; this->mask = new unsigned char[this->cwidth * this->cheight]; } void GrayCode::setPixel(unsigned char *data, const unsigned x, const unsigned y, const unsigned stride, const unsigned char colour ) { data[(y*stride)+x]= colour; } /** * Given a camera coo */ wcl::Vector GrayCode::getRowCol(const wcl::Vector &input) const { wcl::Vector v(2); int col = input[0]; int row = input[1]; // Search the row/column matrixes for the input pixel values v[0] = this->decodedColumns[col][row]; v[1] = this->decodedRows[col][row]; return v; } /** * Given the correct amount of images, decode the structured light sequence. * Note the images are expected to be in 8 bit grayscale. * * @param capturedImages the images captured for each structured light sequence * @param threshold A threshold value for the amount of change that is required between the black and white images pairs */ void GrayCode::decode(const unsigned char **capturedImages, const unsigned int threshold) { // First we separate the rows from the columns; const unsigned char **columnImages = capturedImages; const unsigned char **rowImages = columnImages+(this->grayCodeColumnCount*2)+2; //TODO: Workout automatic threshold based on column/row first two images. //This can be a per image pixel threshold - benjsc 20101206 memset(mask, 0, this->cwidth * this->cheight ); // We now begin the process of decoding the images back into the relevant // graycodes. The decoding works as follows. When capturing the graycodes // we generated both the gray code image and the image invert. By looking // at the difference between these two images we find what the bit is at // each pixel of the imagepair. For pixels that are not part of the // projected image they get assigned a bit value of zero. Ie all undetected // pixels are 0. Since we are using GrayCodes we also have to undo the // greycode detection. This is done by xoring the detected bit per column // per image. The running bit will automatically decode the graycode columnImages+=2; for( unsigned y = 0; y < this->cheight; y++ ){ for( unsigned x = 0; x < this->cwidth; x++ ){ bool bitvalue = false; for(unsigned columnCount = 0; columnCount < this->grayCodeColumnCount; columnCount++){ // Obtain pointers to the gray code image and the image invert const unsigned char *gray = columnImages[(columnCount*2)]; const unsigned char *invgray = columnImages[(columnCount*2)+1]; // Now decode each pixel of the image pair. unsigned offset = (this->cwidth * y) + x; // Find the bit value for this pixel in the image if(columnCount > 0 ) bitvalue ^= gray[offset]>=invgray[offset]; else bitvalue = gray[offset]>=invgray[offset]; mask[offset] |= ((unsigned)abs(gray[offset]-invgray[offset]))>= threshold; #if 0 printf("G:%d, IV:%d, BV:%d | GREY %d | ABS:%d,TH%d | MASK: %d\n", gray[offset], invgray[offset], gray[offset]>=invgray[offset], bitvalue, abs(gray[offset]-invgray[offset]), threshold, mask[offset]); #endif // Store the value of this bit in decoded matrix at the correct // location. The columnCount indicates the significance of the // bit in the number. int bit = this->grayCodeColumnCount - columnCount - 1; if( bitvalue ){ int value = (int)this->decodedColumns[x][y]; value |= 1 << bit; this->decodedColumns[x][y] = value; } } } } // Repeat for rows rowImages+=2; // Now decode each pixel of the image pair. for( unsigned y = 0; y < this->cheight; y++ ){ for( unsigned x = 0; x < this->cwidth; x++ ){ bool bitvalue=false; for(unsigned rowCount = 0; rowCount < this->grayCodeRowCount; rowCount++){ // Obtain pointers to the gray code image and the image invert const unsigned char *gray = rowImages[rowCount*2]; const unsigned char *invgray = rowImages[(rowCount*2)+1]; unsigned offset = (this->cwidth * y) + x; if( rowCount > 0 ) bitvalue ^= gray[offset]>=invgray[offset]; else bitvalue = gray[offset]>=invgray[offset]; mask[offset] |= ((unsigned)abs(gray[offset]-invgray[offset]))>= threshold; int bit = this->grayCodeRowCount - rowCount - 1; #if 0 printf("G:%d, IV:%d, BV:%d | GREY %d | ABS:%d,TH%d | MASK: %d| Bit %d (%d) | Value B4 %d\n", gray[offset], invgray[offset], gray[offset]>=invgray[offset], bitvalue, abs(gray[offset]-invgray[offset]), threshold, mask[offset], bit, (int)pow(2,bit), (int)this->decodedRows[x][y]); #endif if( bitvalue ){ int value = (int)this->decodedRows[x][y]; value |= 1 << bit; this->decodedRows[x][y] = value; } #if 0 printf("Value After: %d\n", (int)this->decodedRows[x][y]); #endif } } } // Each stored value in the matrixes are gray coded still. We now // convert the values back to binary. At the same time we filter to make // sure the values are within range of what they should be (ie width or // height of the original graycode) for(unsigned y=0; y < this->cheight; y++ ){ for(unsigned x=0; x < this->cwidth; x++){ int offset = y*this->cwidth+x; this->decodedRows[x][y] -= this->grayCodeRowPhase; this->decodedColumns[x][y] -= this->grayCodeColumnPhase; if( this->decodedRows[x][y] > this->cheight ) this->mask[offset]=0; if( this->decodedColumns[x][y] > this->cwidth ) this->mask[offset]=0; if( this->decodedRows[x][y] < 0.0 ) this->mask[offset]=0; if( this->decodedColumns[x][y] < 0.0 ) this->mask[offset]=0; this->mask[offset]*=255; } } } bool GrayCode::isValidRowCol(const Vector &p) const { int offset=p[1]*this->cwidth+p[0]; return !(this->mask[offset] == 0); } unsigned GrayCode::getRequiredImageCount() const { return this->totalGrayCodes; } void GrayCode::reset() { this->decodedColumns.storeZeros(); this->decodedRows.storeZeros(); this->stage=0; memset(this->mask, 0, this->cwidth * this->cheight); } const unsigned char *GrayCode::getDebugImage() { static unsigned char *buffer = new unsigned char[this->cwidth*this->cheight]; // Display the values of the detection in the rgb image for(unsigned y = 0; y < this->cheight; y++ ){ for(unsigned x = 0; x < this->cwidth; x++){ this->setPixel(buffer, x, y, this->cwidth, (int)(((this->decodedColumns[x][y] / (float)this->pwidth)) * 255.0)); } } return buffer; } const unsigned char *GrayCode::getMaskImage() { return this->mask; } const unsigned char **GrayCode::getCodedImages() { return (const unsigned char **)this->codedImages; } const unsigned char *GrayCode::getMaskedDebugImage() { const unsigned char *debug = getDebugImage(); // Walk the image and apply the mask for(unsigned y = 0; y < this->cheight; y++ ){ for(unsigned x = 0; x < this->cwidth; x++){ int offset=y*this->cwidth+x; if( this->mask[offset] == 0) this->setPixel((unsigned char *)debug, x, y, this->cwidth, 0); } } return debug; } }; // namespace wcl
34.894515
138
0.669468
[ "vector" ]
4f5ddab1f96ca6d9381054bd90ba47774e87c60c
43,588
cc
C++
mindspore/ccsrc/plugin/device/gpu/optimizer/trt_pass/trt_op_converter.cc
AK391/mindspore
f5aeaa9172dcd647885774e7f657593c81b79fc6
[ "Apache-2.0" ]
null
null
null
mindspore/ccsrc/plugin/device/gpu/optimizer/trt_pass/trt_op_converter.cc
AK391/mindspore
f5aeaa9172dcd647885774e7f657593c81b79fc6
[ "Apache-2.0" ]
null
null
null
mindspore/ccsrc/plugin/device/gpu/optimizer/trt_pass/trt_op_converter.cc
AK391/mindspore
f5aeaa9172dcd647885774e7f657593c81b79fc6
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2021 Huawei Technologies 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 <vector> #include <string> #include <variant> #include <NvInfer.h> #include "plugin/device/gpu/optimizer/trt_pass/trt_converter_context.h" #include "plugin/device/gpu/optimizer/trt_pass/trt_op_factory.h" #include "plugin/device/gpu/kernel/trt/trt_utils.h" namespace mindspore { namespace opt { namespace { nvinfer1::ITensor *ToShape(LayerInput *input, const std::vector<size_t> &shape, std::shared_ptr<TrtConverterContext> context) { MS_EXCEPTION_IF_NULL(input); MS_EXCEPTION_IF_NULL(context); if (!input->IsTensor()) { MS_LOG(WARNING) << "Expect Tensor but got weight"; return nullptr; } const nvinfer1::Dims &src_dim = input->tensor()->getDimensions(); const nvinfer1::Dims &dst_dim = TrtUtils::MsDimsToTrtDims(shape, false); if (TrtUtils::IsSameShape(src_dim, dst_dim)) { return input->tensor(); } auto *layer = context->network()->addShuffle(*input->tensor()); MS_EXCEPTION_IF_NULL(layer); layer->setReshapeDimensions(dst_dim); return layer->getOutput(0); } nvinfer1::ITensor *ToTensor(LayerInput *input, const std::vector<size_t> &shape, std::shared_ptr<TrtConverterContext> context) { MS_EXCEPTION_IF_NULL(input); MS_EXCEPTION_IF_NULL(context); if (input->IsTensor()) { return ToShape(input, shape, context); } const nvinfer1::Dims &dim = TrtUtils::MsDimsToTrtDims(shape, false); auto *const_layer = context->network()->addConstant(dim, *input->weight()); MS_EXCEPTION_IF_NULL(const_layer); return const_layer->getOutput(0); } ConvertResult AddReshapeLayer(AnfNodePtr node, std::shared_ptr<TrtConverterContext> context) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret || inputs.size() != 1 || !inputs[0].IsTensor()) { MS_LOG(WARNING) << "Input num not match: " << inputs.size() << ", with 1 expected."; return {false, {}}; } auto *layer = context->network()->addShuffle(*inputs[0].tensor()); MS_EXCEPTION_IF_NULL(layer); const auto &output_shape = AnfAlgo::GetOutputInferShape(node, 0); const nvinfer1::Dims &dims = TrtUtils::MsDimsToTrtDims(output_shape, false); layer->setReshapeDimensions(dims); return {true, {layer->getOutput(0)}}; } ConvertResult AddElementLayer(AnfNodePtr node, std::shared_ptr<TrtConverterContext> context, nvinfer1::ElementWiseOperation op_type) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret || inputs.size() != 2) { MS_LOG(WARNING) << "Input num not match: " << inputs.size() << ", with 2 expected."; return {false, {}}; } const std::vector<size_t> &x1_shape = AnfAlgo::GetPrevNodeOutputInferShape(node, 0); const std::vector<size_t> &x2_shape = AnfAlgo::GetPrevNodeOutputInferShape(node, 1); const std::vector<size_t> &y_shape = AnfAlgo::GetOutputInferShape(node, 0); auto Broadcast = [&context, &y_shape](nvinfer1::ITensor *tensor, const std::vector<size_t> &x_shape) { if (x_shape.size() == y_shape.size()) { return tensor; } // Copy x_shape to dim with tail align, and fill left axis with 1. // For example: // x: [C, H, W] // y: [N, C, H, W] // dim: [1, C, H, W] nvinfer1::Dims dim; dim.nbDims = SizeToInt(y_shape.size()); std::fill(dim.d, dim.d + dim.nbDims, 1); size_t offset = y_shape.size() - x_shape.size(); for (size_t i = 0; i < x_shape.size(); i++) { dim.d[i + offset] = SizeToInt(x_shape[i]); } auto *layer = context->network()->addShuffle(*tensor); MS_EXCEPTION_IF_NULL(layer); layer->setReshapeDimensions(dim); return layer->getOutput(0); }; auto *x1 = Broadcast(ToTensor(&inputs[0], x1_shape, context), x1_shape); auto *x2 = Broadcast(ToTensor(&inputs[1], x2_shape, context), x2_shape); auto *layer = context->network()->addElementWise(*x1, *x2, op_type); MS_EXCEPTION_IF_NULL(layer); return {true, {layer->getOutput(0)}}; } ConvertResult AddPoolingLayer(AnfNodePtr node, std::shared_ptr<TrtConverterContext> context, nvinfer1::PoolingType pooling_type) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret || inputs.size() != 1 || !inputs[0].IsTensor()) { MS_LOG(WARNING) << "Input num not match: " << inputs.size() << ", with 1 expected."; return {false, {}}; } const auto &format = AnfAlgo::GetNodeAttr<std::string>(node, "format"); if (format != "NCHW") { MS_LOG(WARNING) << "The format: " << format << " not supported."; return {false, {}}; } const auto &kernel_size = AnfAlgo::GetNodeAttr<std::vector<int64_t>>(node, "kernel_size"); auto *layer = context->network()->addPoolingNd( *(inputs[0].tensor()), pooling_type, nvinfer1::DimsHW{LongToInt(kernel_size[2]), LongToInt(kernel_size[3])}); MS_EXCEPTION_IF_NULL(layer); const auto &strides = AnfAlgo::GetNodeAttr<std::vector<int64_t>>(node, "strides"); layer->setStride(nvinfer1::DimsHW{LongToInt(strides[2]), LongToInt(strides[3])}); auto pad_mode = AnfAlgo::GetNodeAttr<std::string>(node, "pad_mode"); std::transform(pad_mode.begin(), pad_mode.end(), pad_mode.begin(), toupper); if (pad_mode == "SAME") { layer->setPaddingMode(nvinfer1::PaddingMode::kSAME_UPPER); } return {true, {layer->getOutput(0)}}; } ConvertResult AddActivationLayer(AnfNodePtr node, std::shared_ptr<TrtConverterContext> context, nvinfer1::ActivationType act_type) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret || inputs.size() != 1 || !inputs[0].IsTensor()) { MS_LOG(WARNING) << "Input num not match: " << inputs.size() << ", with 1 expected."; return {false, {}}; } auto *layer = context->network()->addActivation(*inputs[0].tensor(), act_type); MS_EXCEPTION_IF_NULL(layer); return {true, {layer->getOutput(0)}}; } ConvertResult AddUnaryLayer(AnfNodePtr node, std::shared_ptr<TrtConverterContext> context, nvinfer1::UnaryOperation op_type) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret || inputs.size() != 1) { MS_LOG(WARNING) << "Input num not match: " << inputs.size() << ", with 2 expected."; return {false, {}}; } auto *layer = context->network()->addUnary(*inputs[0].tensor(), op_type); MS_EXCEPTION_IF_NULL(layer); return {true, {layer->getOutput(0)}}; } ConvertResult AddReduceLayer(AnfNodePtr node, std::shared_ptr<TrtConverterContext> context, nvinfer1::ReduceOperation op_type) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret || inputs.size() != 1) { MS_LOG(WARNING) << "Input num not match: " << inputs.size() << ", with 2 expected."; return {false, {}}; } // Calculate reduce axes bitmask const std::vector<size_t> &input_shape = AnfAlgo::GetPrevNodeOutputInferShape(node, 0); const ValuePtr &value = AnfAlgo::GetCNodePrimitive(node)->GetAttr("axis"); uint32_t reduce_axes = 0; if (value->isa<ValueTuple>() || value->isa<ValueList>()) { const auto &axis = AnfAlgo::GetNodeAttr<std::vector<int64_t>>(node, "axis"); for (size_t i = 0; i < axis.size(); i++) { int offset = axis[i] >= 0 ? LongToInt(axis[i]) : LongToInt(axis[i] + input_shape.size()); reduce_axes |= 1UL << offset; } } else { const auto &axis = AnfAlgo::GetNodeAttr<int64_t>(node, "axis"); int offset = axis >= 0 ? LongToInt(axis) : LongToInt(axis + input_shape.size()); reduce_axes = 1UL << offset; } // Tensor-RT do not support reduce with no dimensions. // Skip reduce operator if reduce_axes == 0 if (reduce_axes == 0) { MS_LOG(WARNING) << "No dimension be be reduced. " << node->DebugString(); return {true, {inputs[0].tensor()}}; } bool keep_dims = AnfAlgo::GetNodeAttr<bool>(node, "keep_dims"); // Tensor-RT do not support reduce all dimensions with keep_dims == false. // Reduce with keep_dims = true, add apply reshape latter. bool post_reshape = false; if (keep_dims == false && (reduce_axes == (1UL << input_shape.size()) - 1)) { keep_dims = true; post_reshape = true; } nvinfer1::IReduceLayer *layer = context->network()->addReduce(*inputs[0].tensor(), op_type, reduce_axes, keep_dims); MS_EXCEPTION_IF_NULL(layer); if (post_reshape) { nvinfer1::IShuffleLayer *reshape_layer = context->network()->addShuffle(*layer->getOutput(0)); MS_EXCEPTION_IF_NULL(reshape_layer); nvinfer1::Dims dim; dim.nbDims = 1; dim.d[0] = 1; reshape_layer->setReshapeDimensions(dim); return {true, {reshape_layer->getOutput(0)}}; } return {true, {layer->getOutput(0)}}; } } // namespace // Register operator converter from AnfNode to trt layer: `OPNAME` should keep the same as primitive definition. #define MS_TRT_CONVERTER_FUNC_REG(OPNAME) \ ConvertResult Gpu##OPNAME##TrtConverter(AnfNodePtr node, std::shared_ptr<TrtConverterContext> context); \ static const TrtOpRegister(Gpu##OPNAME##ConverterRegister)(#OPNAME, Gpu##OPNAME##TrtConverter); \ ConvertResult Gpu##OPNAME##TrtConverter(AnfNodePtr node, std::shared_ptr<TrtConverterContext> context) MS_TRT_CONVERTER_FUNC_REG(Conv2D) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret || inputs.size() != 2 || !inputs[0].IsTensor() || !inputs[1].IsWeight()) { MS_LOG(WARNING) << "Input num not match: " << inputs.size() << ", with 2 expected."; return {false, {}}; } const auto &data_format = AnfAlgo::GetNodeAttr<std::string>(node, "format"); if (data_format != "NCHW") { MS_LOG(WARNING) << "The format: " << data_format << " not supported."; return {false, {}}; } const auto &kernel_size = AnfAlgo::GetNodeAttr<std::vector<int64_t>>(node, "kernel_size"); const auto &out_channel = AnfAlgo::GetNodeAttr<int64_t>(node, "out_channel"); nvinfer1::Weights bias{nvinfer1::DataType::kFLOAT, nullptr, 0}; auto *layer = context->network()->addConvolutionNd( *(inputs[0].tensor()), LongToInt(out_channel), nvinfer1::DimsHW{LongToInt(kernel_size[0]), LongToInt(kernel_size[1])}, *(inputs[1].weight()), bias); MS_EXCEPTION_IF_NULL(layer); const auto &strides = AnfAlgo::GetNodeAttr<std::vector<int64_t>>(node, "stride"); layer->setStride(nvinfer1::DimsHW{LongToInt(strides[2]), LongToInt(strides[3])}); auto pad_mode = AnfAlgo::GetNodeAttr<std::string>(node, "pad_mode"); std::transform(pad_mode.begin(), pad_mode.end(), pad_mode.begin(), toupper); if (pad_mode == "SAME") { layer->setPaddingMode(nvinfer1::PaddingMode::kSAME_UPPER); } if (pad_mode == "PAD") { const auto &pad_list = AnfAlgo::GetNodeAttr<std::vector<int64_t>>(node, "pad_list"); layer->setPrePadding(nvinfer1::DimsHW{LongToInt(pad_list[0]), LongToInt(pad_list[2])}); layer->setPostPadding(nvinfer1::DimsHW{LongToInt(pad_list[1]), LongToInt(pad_list[3])}); } const auto &group = AnfAlgo::GetNodeAttr<int64_t>(node, "group"); layer->setNbGroups(SizeToInt(group)); return {true, {layer->getOutput(0)}}; } // Binary broadcast operators. MS_TRT_CONVERTER_FUNC_REG(Add) { return AddElementLayer(node, context, nvinfer1::ElementWiseOperation::kSUM); } MS_TRT_CONVERTER_FUNC_REG(Sub) { return AddElementLayer(node, context, nvinfer1::ElementWiseOperation::kSUB); } MS_TRT_CONVERTER_FUNC_REG(Mul) { return AddElementLayer(node, context, nvinfer1::ElementWiseOperation::kPROD); } MS_TRT_CONVERTER_FUNC_REG(Div) { return AddElementLayer(node, context, nvinfer1::ElementWiseOperation::kDIV); } MS_TRT_CONVERTER_FUNC_REG(RealDiv) { return AddElementLayer(node, context, nvinfer1::ElementWiseOperation::kDIV); } MS_TRT_CONVERTER_FUNC_REG(Pow) { return AddElementLayer(node, context, nvinfer1::ElementWiseOperation::kPOW); } MS_TRT_CONVERTER_FUNC_REG(Maximum) { return AddElementLayer(node, context, nvinfer1::ElementWiseOperation::kMAX); } MS_TRT_CONVERTER_FUNC_REG(Minimum) { return AddElementLayer(node, context, nvinfer1::ElementWiseOperation::kMIN); } MS_TRT_CONVERTER_FUNC_REG(FloorDiv) { return AddElementLayer(node, context, nvinfer1::ElementWiseOperation::kFLOOR_DIV); } // Unary operators MS_TRT_CONVERTER_FUNC_REG(Exp) { return AddUnaryLayer(node, context, nvinfer1::UnaryOperation::kEXP); } MS_TRT_CONVERTER_FUNC_REG(Log) { return AddUnaryLayer(node, context, nvinfer1::UnaryOperation::kLOG); } MS_TRT_CONVERTER_FUNC_REG(Sqrt) { return AddUnaryLayer(node, context, nvinfer1::UnaryOperation::kSQRT); } MS_TRT_CONVERTER_FUNC_REG(Reciprocal) { return AddUnaryLayer(node, context, nvinfer1::UnaryOperation::kRECIP); } MS_TRT_CONVERTER_FUNC_REG(Abs) { return AddUnaryLayer(node, context, nvinfer1::UnaryOperation::kABS); } MS_TRT_CONVERTER_FUNC_REG(Neg) { return AddUnaryLayer(node, context, nvinfer1::UnaryOperation::kNEG); } MS_TRT_CONVERTER_FUNC_REG(Sin) { return AddUnaryLayer(node, context, nvinfer1::UnaryOperation::kSIN); } MS_TRT_CONVERTER_FUNC_REG(Cos) { return AddUnaryLayer(node, context, nvinfer1::UnaryOperation::kCOS); } MS_TRT_CONVERTER_FUNC_REG(Tan) { return AddUnaryLayer(node, context, nvinfer1::UnaryOperation::kTAN); } MS_TRT_CONVERTER_FUNC_REG(Sinh) { return AddUnaryLayer(node, context, nvinfer1::UnaryOperation::kSINH); } MS_TRT_CONVERTER_FUNC_REG(Cosh) { return AddUnaryLayer(node, context, nvinfer1::UnaryOperation::kCOSH); } MS_TRT_CONVERTER_FUNC_REG(Asin) { return AddUnaryLayer(node, context, nvinfer1::UnaryOperation::kASIN); } MS_TRT_CONVERTER_FUNC_REG(Acos) { return AddUnaryLayer(node, context, nvinfer1::UnaryOperation::kACOS); } MS_TRT_CONVERTER_FUNC_REG(Atan) { return AddUnaryLayer(node, context, nvinfer1::UnaryOperation::kATAN); } MS_TRT_CONVERTER_FUNC_REG(Asinh) { return AddUnaryLayer(node, context, nvinfer1::UnaryOperation::kASINH); } MS_TRT_CONVERTER_FUNC_REG(Acosh) { return AddUnaryLayer(node, context, nvinfer1::UnaryOperation::kACOSH); } MS_TRT_CONVERTER_FUNC_REG(Ceil) { return AddUnaryLayer(node, context, nvinfer1::UnaryOperation::kCEIL); } MS_TRT_CONVERTER_FUNC_REG(Floor) { return AddUnaryLayer(node, context, nvinfer1::UnaryOperation::kFLOOR); } // Reduce operators MS_TRT_CONVERTER_FUNC_REG(ReduceSum) { return AddReduceLayer(node, context, nvinfer1::ReduceOperation::kSUM); } MS_TRT_CONVERTER_FUNC_REG(ReduceMean) { return AddReduceLayer(node, context, nvinfer1::ReduceOperation::kAVG); } MS_TRT_CONVERTER_FUNC_REG(ReduceMax) { return AddReduceLayer(node, context, nvinfer1::ReduceOperation::kMAX); } MS_TRT_CONVERTER_FUNC_REG(ReduceMin) { return AddReduceLayer(node, context, nvinfer1::ReduceOperation::kMIN); } MS_TRT_CONVERTER_FUNC_REG(ReduceProd) { return AddReduceLayer(node, context, nvinfer1::ReduceOperation::kPROD); } // Pooling operators. MS_TRT_CONVERTER_FUNC_REG(AvgPool) { return AddPoolingLayer(node, context, nvinfer1::PoolingType::kAVERAGE); } MS_TRT_CONVERTER_FUNC_REG(MaxPool) { return AddPoolingLayer(node, context, nvinfer1::PoolingType::kMAX); } // Activation operators. MS_TRT_CONVERTER_FUNC_REG(ReLU) { return AddActivationLayer(node, context, nvinfer1::ActivationType::kRELU); } MS_TRT_CONVERTER_FUNC_REG(Sigmoid) { return AddActivationLayer(node, context, nvinfer1::ActivationType::kSIGMOID); } MS_TRT_CONVERTER_FUNC_REG(Tanh) { return AddActivationLayer(node, context, nvinfer1::ActivationType::kTANH); } MS_TRT_CONVERTER_FUNC_REG(Elu) { return AddActivationLayer(node, context, nvinfer1::ActivationType::kELU); } MS_TRT_CONVERTER_FUNC_REG(Softsign) { return AddActivationLayer(node, context, nvinfer1::ActivationType::kSOFTSIGN); } MS_TRT_CONVERTER_FUNC_REG(ReLU6) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret || inputs.size() != 1) { MS_LOG(WARNING) << "Input num not match: " << inputs.size() << ", with 1 expected."; return {false, {}}; } const std::vector<size_t> &x_shape = AnfAlgo::GetPrevNodeOutputInferShape(node, 0); nvinfer1::Dims dim; dim.nbDims = SizeToInt(x_shape.size()); std::fill(dim.d, dim.d + dim.nbDims, 1); auto AddConst = [&context, &dim](const float &coeff) { std::shared_ptr<tensor::Tensor> weight = context->CreateTempWeight(kNumberTypeFloat32, {1}); auto value = static_cast<float *>(weight->data_c()); value[0] = coeff; auto *layer = context->network()->addConstant(dim, nvinfer1::Weights{nvinfer1::DataType::kFLOAT, value, 1}); MS_EXCEPTION_IF_NULL(layer); return layer->getOutput(0); }; // y = max(0.0, min(6.0, x) auto *c0 = AddConst(0.0f); auto *c1 = AddConst(6.0f); auto *x = inputs[0].tensor(); nvinfer1::ILayer *layer = context->network()->addElementWise(*x, *c1, nvinfer1::ElementWiseOperation::kMIN); MS_EXCEPTION_IF_NULL(layer); layer = context->network()->addElementWise(*layer->getOutput(0), *c0, nvinfer1::ElementWiseOperation::kMAX); MS_EXCEPTION_IF_NULL(layer); return {true, {layer->getOutput(0)}}; } MS_TRT_CONVERTER_FUNC_REG(GeLU) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret || inputs.size() != 1) { MS_LOG(WARNING) << "Input num not match: " << inputs.size() << ", with 1 expected."; return {false, {}}; } const std::vector<size_t> &x_shape = AnfAlgo::GetPrevNodeOutputInferShape(node, 0); nvinfer1::Dims dim; dim.nbDims = SizeToInt(x_shape.size()); std::fill(dim.d, dim.d + dim.nbDims, 1); auto AddConst = [&context, &dim](const float &coeff) { std::shared_ptr<tensor::Tensor> weight = context->CreateTempWeight(kNumberTypeFloat32, {1}); auto value = static_cast<float *>(weight->data_c()); value[0] = coeff; auto *layer = context->network()->addConstant(dim, nvinfer1::Weights{nvinfer1::DataType::kFLOAT, value, 1}); MS_EXCEPTION_IF_NULL(layer); return layer->getOutput(0); }; // y = 0.5 * x * (1 + tanh(0.7978846 * (x + 0.044715 * x^3))) auto *c1 = AddConst(0.5f); auto *c2 = AddConst(1.0f); auto *c3 = AddConst(0.7978846f); auto *c4 = AddConst(0.044715f); auto *c5 = AddConst(3.0f); auto *x = inputs[0].tensor(); nvinfer1::ILayer *layer = context->network()->addElementWise(*x, *c5, nvinfer1::ElementWiseOperation::kPOW); MS_EXCEPTION_IF_NULL(layer); layer = context->network()->addElementWise(*c4, *layer->getOutput(0), nvinfer1::ElementWiseOperation::kPROD); MS_EXCEPTION_IF_NULL(layer); layer = context->network()->addElementWise(*x, *layer->getOutput(0), nvinfer1::ElementWiseOperation::kSUM); MS_EXCEPTION_IF_NULL(layer); layer = context->network()->addElementWise(*c3, *layer->getOutput(0), nvinfer1::ElementWiseOperation::kPROD); MS_EXCEPTION_IF_NULL(layer); layer = context->network()->addActivation(*layer->getOutput(0), nvinfer1::ActivationType::kTANH); MS_EXCEPTION_IF_NULL(layer); layer = context->network()->addElementWise(*c2, *layer->getOutput(0), nvinfer1::ElementWiseOperation::kSUM); MS_EXCEPTION_IF_NULL(layer); layer = context->network()->addElementWise(*x, *layer->getOutput(0), nvinfer1::ElementWiseOperation::kPROD); MS_EXCEPTION_IF_NULL(layer); layer = context->network()->addElementWise(*c1, *layer->getOutput(0), nvinfer1::ElementWiseOperation::kPROD); MS_EXCEPTION_IF_NULL(layer); return {true, {layer->getOutput(0)}}; } MS_TRT_CONVERTER_FUNC_REG(HSigmoid) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret || inputs.size() != 1) { MS_LOG(WARNING) << "Input num not match: " << inputs.size() << ", with 1 expected."; return {false, {}}; } const std::vector<size_t> &x_shape = AnfAlgo::GetPrevNodeOutputInferShape(node, 0); nvinfer1::Dims dim; dim.nbDims = SizeToInt(x_shape.size()); std::fill(dim.d, dim.d + dim.nbDims, 1); auto AddConst = [&context, &dim](const float &coeff) { std::shared_ptr<tensor::Tensor> weight = context->CreateTempWeight(kNumberTypeFloat32, {1}); auto value = static_cast<float *>(weight->data_c()); value[0] = coeff; auto *layer = context->network()->addConstant(dim, nvinfer1::Weights{nvinfer1::DataType::kFLOAT, value, 1}); MS_EXCEPTION_IF_NULL(layer); return layer->getOutput(0); }; // y = max(0, min(1.0, (x + 3.0)/6.0)) auto *c0 = AddConst(0.0f); auto *c1 = AddConst(1.0f); auto *c2 = AddConst(3.0f); auto *c3 = AddConst(6.0f); auto *x = inputs[0].tensor(); nvinfer1::ILayer *layer = context->network()->addElementWise(*x, *c2, nvinfer1::ElementWiseOperation::kSUM); MS_EXCEPTION_IF_NULL(layer); layer = context->network()->addElementWise(*layer->getOutput(0), *c3, nvinfer1::ElementWiseOperation::kDIV); MS_EXCEPTION_IF_NULL(layer); layer = context->network()->addElementWise(*layer->getOutput(0), *c1, nvinfer1::ElementWiseOperation::kMIN); MS_EXCEPTION_IF_NULL(layer); layer = context->network()->addElementWise(*layer->getOutput(0), *c0, nvinfer1::ElementWiseOperation::kMAX); MS_EXCEPTION_IF_NULL(layer); return {true, {layer->getOutput(0)}}; } MS_TRT_CONVERTER_FUNC_REG(HSwish) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret || inputs.size() != 1) { MS_LOG(WARNING) << "Input num not match: " << inputs.size() << ", with 1 expected."; return {false, {}}; } const std::vector<size_t> &x_shape = AnfAlgo::GetPrevNodeOutputInferShape(node, 0); nvinfer1::Dims dim; dim.nbDims = SizeToInt(x_shape.size()); std::fill(dim.d, dim.d + dim.nbDims, 1); auto AddConst = [&context, &dim](const float &coeff) { std::shared_ptr<tensor::Tensor> weight = context->CreateTempWeight(kNumberTypeFloat32, {1}); auto value = static_cast<float *>(weight->data_c()); value[0] = coeff; auto *layer = context->network()->addConstant(dim, nvinfer1::Weights{nvinfer1::DataType::kFLOAT, value, 1}); MS_EXCEPTION_IF_NULL(layer); return layer->getOutput(0); }; // y = x * Relu6(x + 3.0) / 6.0 // Relu6(x) = min(max(x, 0.0), 6.0) auto *c0 = AddConst(0.0f); auto *c1 = AddConst(3.0f); auto *c2 = AddConst(6.0f); auto *x = inputs[0].tensor(); nvinfer1::ILayer *layer = context->network()->addElementWise(*x, *c1, nvinfer1::ElementWiseOperation::kSUM); MS_EXCEPTION_IF_NULL(layer); layer = context->network()->addElementWise(*layer->getOutput(0), *c0, nvinfer1::ElementWiseOperation::kMAX); MS_EXCEPTION_IF_NULL(layer); layer = context->network()->addElementWise(*layer->getOutput(0), *c2, nvinfer1::ElementWiseOperation::kMIN); MS_EXCEPTION_IF_NULL(layer); layer = context->network()->addElementWise(*layer->getOutput(0), *c2, nvinfer1::ElementWiseOperation::kDIV); MS_EXCEPTION_IF_NULL(layer); layer = context->network()->addElementWise(*x, *layer->getOutput(0), nvinfer1::ElementWiseOperation::kPROD); MS_EXCEPTION_IF_NULL(layer); return {true, {layer->getOutput(0)}}; } MS_TRT_CONVERTER_FUNC_REG(MatMul) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret || inputs.size() != 2) { MS_LOG(WARNING) << "Input num not match: " << inputs.size() << ", with 2 expected."; return {false, {}}; } const auto &transpose_a = AnfAlgo::GetNodeAttr<bool>(node, "transpose_a"); const auto &transpose_b = AnfAlgo::GetNodeAttr<bool>(node, "transpose_b"); if (inputs[0].IsTensor() && inputs[1].IsWeight() && transpose_a == false && transpose_b == true) { // Reshape x from (M, K) to (M, K, 1, 1) nvinfer1::Dims unsqueeze_dims = inputs[0].tensor()->getDimensions(); for (size_t i = 0; i < 2; i++) { unsqueeze_dims.d[unsqueeze_dims.nbDims++] = 1; } auto x_reshape = context->network()->addShuffle(*inputs[0].tensor()); x_reshape->setReshapeDimensions(unsqueeze_dims); // Apply addFullyConnected: y = x * w^T + b nvinfer1::Weights bias{nvinfer1::DataType::kFLOAT, nullptr, 0}; const auto &w_shape = AnfAlgo::GetPrevNodeOutputInferShape(node, 1); auto *layer = context->network()->addFullyConnected(*x_reshape->getOutput(0), w_shape[0], *inputs[1].weight(), bias); MS_EXCEPTION_IF_NULL(layer); // Reshape x from (M, N, 1, 1) to (M, N) const auto &y_shape = AnfAlgo::GetOutputInferShape(node, 0); const nvinfer1::Dims &y_dims = TrtUtils::MsDimsToTrtDims(y_shape, false); auto *squeeze_y = context->network()->addShuffle(*layer->getOutput(0)); squeeze_y->setReshapeDimensions(y_dims); return {true, {squeeze_y->getOutput(0)}}; } else { auto op1 = transpose_a ? nvinfer1::MatrixOperation::kTRANSPOSE : nvinfer1::MatrixOperation::kNONE; auto op2 = transpose_b ? nvinfer1::MatrixOperation::kTRANSPOSE : nvinfer1::MatrixOperation::kNONE; const std::vector<size_t> &x1_shape = AnfAlgo::GetPrevNodeOutputInferShape(node, 0); const std::vector<size_t> &x2_shape = AnfAlgo::GetPrevNodeOutputInferShape(node, 1); nvinfer1::ITensor *x1 = ToTensor(&inputs[0], x1_shape, context); nvinfer1::ITensor *x2 = ToTensor(&inputs[1], x2_shape, context); auto *layer = context->network()->addMatrixMultiply(*x1, op1, *x2, op2); MS_EXCEPTION_IF_NULL(layer); return {true, {layer->getOutput(0)}}; } } MS_TRT_CONVERTER_FUNC_REG(BatchMatMul) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret || inputs.size() != 2) { MS_LOG(WARNING) << "Input num not match: " << inputs.size() << ", with 2 expected."; return {false, {}}; } const auto &transpose_a = AnfAlgo::GetNodeAttr<bool>(node, "transpose_a"); const auto &transpose_b = AnfAlgo::GetNodeAttr<bool>(node, "transpose_b"); const auto &trt_transpose1 = transpose_a ? nvinfer1::MatrixOperation::kTRANSPOSE : nvinfer1::MatrixOperation::kNONE; const auto &trt_transpose2 = transpose_b ? nvinfer1::MatrixOperation::kTRANSPOSE : nvinfer1::MatrixOperation::kNONE; std::vector<size_t> shape1 = AnfAlgo::GetPrevNodeOutputInferShape(node, 0); std::vector<size_t> shape2 = AnfAlgo::GetPrevNodeOutputInferShape(node, 1); nvinfer1::ITensor *tensor1 = ToTensor(&inputs[0], shape1, context); nvinfer1::ITensor *tensor2 = ToTensor(&inputs[1], shape2, context); auto *layer = context->network()->addMatrixMultiply(*tensor1, trt_transpose1, *tensor2, trt_transpose2); MS_EXCEPTION_IF_NULL(layer); return {true, {layer->getOutput(0)}}; } MS_TRT_CONVERTER_FUNC_REG(BiasAdd) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret || inputs.size() != 2) { MS_LOG(WARNING) << "Input num not match: " << inputs.size() << ", with 1 expected."; return {false, {}}; } const auto &x_shape = AnfAlgo::GetPrevNodeOutputInferShape(node, 0); const auto &bias_shape = AnfAlgo::GetPrevNodeOutputInferShape(node, 1); const auto &format = AnfAlgo::GetNodeAttr<std::string>(node, "format"); const string::size_type &pos = format.find("C"); if (pos == std::string::npos || pos >= x_shape.size()) { MS_LOG(WARNING) << "The format " << format << "' invalid"; return {false, {}}; } // Convert bias to ITensor same dims as x. std::vector<size_t> unsqueeze_bias_dims(x_shape.size(), 1); unsqueeze_bias_dims[pos] = SizeToInt(bias_shape[0]); nvinfer1::ITensor *bias = ToTensor(&inputs[1], unsqueeze_bias_dims, context); // Create Broadcast Add layer. auto *layer = context->network()->addElementWise(*inputs[0].tensor(), *bias, nvinfer1::ElementWiseOperation::kSUM); MS_EXCEPTION_IF_NULL(layer); return {true, {layer->getOutput(0)}}; } // NoOp MS_TRT_CONVERTER_FUNC_REG(Reshape) { return AddReshapeLayer(node, context); } MS_TRT_CONVERTER_FUNC_REG(ExpandDims) { return AddReshapeLayer(node, context); } MS_TRT_CONVERTER_FUNC_REG(Squeeze) { return AddReshapeLayer(node, context); } MS_TRT_CONVERTER_FUNC_REG(Flatten) { return AddReshapeLayer(node, context); } MS_TRT_CONVERTER_FUNC_REG(BatchNorm) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret || inputs.size() != 5 || !inputs[0].IsTensor() || !inputs[1].IsWeight() || !inputs[2].IsWeight() || !inputs[3].IsWeight() || !inputs[4].IsWeight()) { MS_LOG(WARNING) << "Input num not match: " << inputs.size() << ", with 1 expected."; return {false, {}}; } auto primitive = GetCNodePrimitive(node); MS_EXCEPTION_IF_NULL(primitive); auto is_training = AnfAlgo::GetNodeAttr<bool>(node, "is_training"); if (is_training != false) { MS_LOG(WARNING) << "Operation not support, is_training: " << is_training; return {false, {}}; } const auto &format = AnfAlgo::GetNodeAttr<std::string>(node, "format"); if (format != "NCHW") { MS_LOG(WARNING) << "The format " << format << "' invalid"; return {false, {}}; } // scale = gamma / sqrt(var + epsilon) // y = (x - mean) * scale + beta // = x * scale - mean * scale + beta // = x * coeff + bias auto gamma = static_cast<const float *>(inputs[1].weight()->values); auto beta = static_cast<const float *>(inputs[2].weight()->values); auto mean = static_cast<const float *>(inputs[3].weight()->values); auto var = static_cast<const float *>(inputs[4].weight()->values); auto epsilon = AnfAlgo::GetNodeAttr<float>(node, "epsilon"); const TypeId &type = AnfAlgo::GetPrevNodeOutputInferDataType(node, 1); const std::vector<size_t> &shape = AnfAlgo::GetPrevNodeOutputInferShape(node, 1); int64_t channel_num = SizeToLong(shape[0]); auto coeff = context->CreateTempWeight(type, shape); auto bias = context->CreateTempWeight(type, shape); auto coeff_value = static_cast<float *>(coeff->data_c()); auto bias_value = static_cast<float *>(bias->data_c()); for (int64_t i = 0; i < channel_num; i++) { float scale = gamma[i] / sqrtf(var[i] + epsilon); coeff_value[i] = scale; bias_value[i] = beta[i] - mean[i] * scale; } const nvinfer1::Weights &scale{nvinfer1::DataType::kFLOAT, coeff_value, channel_num}; const nvinfer1::Weights &shift{nvinfer1::DataType::kFLOAT, bias_value, channel_num}; const nvinfer1::Weights &pow{nvinfer1::DataType::kFLOAT, nullptr, 0}; auto *layer = context->network()->addScale(*inputs[0].tensor(), nvinfer1::ScaleMode::kCHANNEL, shift, scale, pow); MS_EXCEPTION_IF_NULL(layer); return {true, {layer->getOutput(0)}}; } MS_TRT_CONVERTER_FUNC_REG(Concat) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret || inputs.size() == 0) { MS_LOG(WARNING) << "Get inputs failed. Input num: " << inputs.size(); return {false, {}}; } std::vector<nvinfer1::ITensor *> tensors; for (const auto &input : inputs) { if (input.IsWeight()) { MS_LOG(WARNING) << "Concat input do not support weight."; return {false, {}}; } tensors.push_back(input.tensor()); } auto *layer = context->network()->addConcatenation(tensors.data(), tensors.size()); MS_EXCEPTION_IF_NULL(layer); auto axis = static_cast<int>(AnfAlgo::GetNodeAttr<int64_t>(node, "axis")); if (axis < 0) { auto input_shape = AnfAlgo::GetPrevNodeOutputInferShape(node, 0); axis += SizeToInt(input_shape.size()); } layer->setAxis(axis); return {true, {layer->getOutput(0)}}; } MS_TRT_CONVERTER_FUNC_REG(Conv2DBackpropInput) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret || inputs.size() != 2 || !inputs[0].IsTensor() || !inputs[1].IsWeight()) { MS_LOG(WARNING) << "Input num not match: " << inputs.size() << ", with 2 expected."; return {false, {}}; } const auto &format = AnfAlgo::GetNodeAttr<std::string>(node, "format"); if (format != "NCHW") { MS_LOG(WARNING) << "The format: " << format << " not supported."; return {false, {}}; } const auto &kernel_size = AnfAlgo::GetNodeAttr<std::vector<int64_t>>(node, "kernel_size"); const auto &output_shape = AnfAlgo::GetOutputInferShape(node, 0); const nvinfer1::Weights &bias{nvinfer1::DataType::kFLOAT, nullptr, 0}; auto *layer = context->network()->addDeconvolutionNd( *(inputs[0].tensor()), SizeToInt(output_shape[1]), nvinfer1::DimsHW{LongToInt(kernel_size[0]), LongToInt(kernel_size[1])}, *(inputs[1].weight()), bias); MS_EXCEPTION_IF_NULL(layer); const auto &strides = AnfAlgo::GetNodeAttr<std::vector<int64_t>>(node, "stride"); layer->setStride(nvinfer1::DimsHW{LongToInt(strides[2]), LongToInt(strides[3])}); auto pad_mode = AnfAlgo::GetNodeAttr<std::string>(node, "pad_mode"); std::transform(pad_mode.begin(), pad_mode.end(), pad_mode.begin(), toupper); if (pad_mode == "SAME") { layer->setPaddingMode(nvinfer1::PaddingMode::kSAME_UPPER); } if (pad_mode == "PAD") { const auto &pad_list = AnfAlgo::GetNodeAttr<std::vector<int64_t>>(node, "pad_list"); layer->setPaddingMode(nvinfer1::PaddingMode::kEXPLICIT_ROUND_DOWN); layer->setPrePadding(nvinfer1::DimsHW{LongToInt(pad_list[0]), LongToInt(pad_list[2])}); layer->setPostPadding(nvinfer1::DimsHW{LongToInt(pad_list[1]), LongToInt(pad_list[3])}); } return {true, {layer->getOutput(0)}}; } MS_TRT_CONVERTER_FUNC_REG(Slice) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret || inputs.size() != 1 || !inputs[0].IsTensor()) { MS_LOG(WARNING) << "Input num not match: " << inputs.size() << ", with 1 expected."; return {false, {}}; } const auto &begin = AnfAlgo::GetNodeAttr<std::vector<int64_t>>(node, "begin"); const auto &size = AnfAlgo::GetNodeAttr<std::vector<int64_t>>(node, "size"); nvinfer1::Dims trt_start = TrtUtils::MsDimsToTrtDims(begin, false); nvinfer1::Dims trt_size = TrtUtils::MsDimsToTrtDims(size, false); nvinfer1::Dims trt_stride; for (int32_t i = 0; i < trt_start.nbDims; i++) { trt_stride.d[trt_stride.nbDims++] = 1; } auto *layer = context->network()->addSlice(*inputs[0].tensor(), trt_start, trt_size, trt_stride); MS_EXCEPTION_IF_NULL(layer); return {true, {layer->getOutput(0)}}; } MS_TRT_CONVERTER_FUNC_REG(Transpose) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret || inputs.size() != 1 || !inputs[0].IsTensor()) { MS_LOG(WARNING) << "Input num not match: " << inputs.size() << ", with 1 expected."; return {false, {}}; } const auto &perm = AnfAlgo::GetNodeAttr<std::vector<int64_t>>(node, "perm"); nvinfer1::Permutation trt_perm; for (size_t i = 0; i < perm.size(); i++) { trt_perm.order[i] = LongToInt(perm[i]); } auto *layer = context->network()->addShuffle(*inputs[0].tensor()); MS_EXCEPTION_IF_NULL(layer); layer->setFirstTranspose(trt_perm); return {true, {layer->getOutput(0)}}; } MS_TRT_CONVERTER_FUNC_REG(Softmax) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret || inputs.size() != 1 || !inputs[0].IsTensor()) { MS_LOG(WARNING) << "Input num not match: " << inputs.size() << ", with 1 expected."; return {false, {}}; } const std::vector<size_t> &input_shape = AnfAlgo::GetPrevNodeOutputInferShape(node, 0); const ValuePtr &value = AnfAlgo::GetCNodePrimitive(node)->GetAttr("axis"); uint32_t reduce_axes = 0; if (value->isa<ValueTuple>() || value->isa<ValueList>()) { const auto &axis = AnfAlgo::GetNodeAttr<std::vector<int64_t>>(node, "axis"); if (axis.size() != 1) { MS_LOG(WARNING) << "Only one axis can be set. Axis size" << axis.size(); return {false, {}}; } int offset = axis[0] >= 0 ? LongToInt(axis[0]) : LongToInt(axis[0] + input_shape.size()); reduce_axes = 1U << offset; } else { const auto &axis = AnfAlgo::GetNodeAttr<int64_t>(node, "axis"); int offset = axis >= 0 ? LongToInt(axis) : LongToInt(axis + input_shape.size()); reduce_axes = 1UL << offset; } auto *layer = context->network()->addSoftMax(*inputs[0].tensor()); MS_EXCEPTION_IF_NULL(layer); layer->setAxes(reduce_axes); return {true, {layer->getOutput(0)}}; } MS_TRT_CONVERTER_FUNC_REG(LogSoftmax) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret || inputs.size() != 1 || !inputs[0].IsTensor()) { MS_LOG(WARNING) << "Input num not match: " << inputs.size() << ", with 1 expected."; return {false, {}}; } const std::vector<size_t> &input_shape = AnfAlgo::GetPrevNodeOutputInferShape(node, 0); const auto &axis = AnfAlgo::GetNodeAttr<int64_t>(node, "axis"); int offset = axis >= 0 ? LongToInt(axis) : LongToInt(axis + input_shape.size()); uint32_t reduce_axes = 1UL << offset; auto *softmax_layer = context->network()->addSoftMax(*inputs[0].tensor()); MS_EXCEPTION_IF_NULL(softmax_layer); softmax_layer->setAxes(reduce_axes); auto *log_layer = context->network()->addUnary(*softmax_layer->getOutput(0), nvinfer1::UnaryOperation::kLOG); MS_EXCEPTION_IF_NULL(log_layer); return {true, {log_layer->getOutput(0)}}; } MS_TRT_CONVERTER_FUNC_REG(Gather) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret || inputs.size() != 2) { MS_LOG(WARNING) << "Input num not match: " << inputs.size() << ", with 2 expected."; return {false, {}}; } const std::vector<size_t> &input_shape = AnfAlgo::GetPrevNodeOutputInferShape(node, 0); auto axis = AnfAlgo::GetNodeAttr<int64_t>(node, "axis"); axis = axis >= 0 ? axis : axis + input_shape.size(); nvinfer1::ITensor *input = ToTensor(&inputs[0], input_shape, context); const std::vector<size_t> &indices_shape = AnfAlgo::GetPrevNodeOutputInferShape(node, 1); nvinfer1::ITensor *indices = ToTensor(&inputs[1], indices_shape, context); auto *layer = context->network()->addGather(*input, *indices, LongToInt(axis)); MS_EXCEPTION_IF_NULL(layer); return {true, {layer->getOutput(0)}}; } MS_TRT_CONVERTER_FUNC_REG(Cast) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret || inputs.size() != 1) { MS_LOG(WARNING) << "Get inputs failed. Input num: " << inputs.size(); return {false, {}}; } const std::vector<size_t> &input_shape = AnfAlgo::GetPrevNodeOutputInferShape(node, 0); nvinfer1::ITensor *input = ToTensor(&inputs[0], input_shape, context); const TypeId &dst_type = AnfAlgo::GetOutputInferDataType(node, 0); std::variant<bool, nvinfer1::DataType> type = TrtUtils::MsDtypeToTrtDtype(dst_type); if (type.index() != 1) { return {false, {}}; } auto trt_type = std::get<nvinfer1::DataType>(type); auto *layer = context->network()->addIdentity(*input); layer->setOutputType(0, trt_type); if (trt_type == nvinfer1::DataType::kHALF) { MS_LOG(WARNING) << "The model is exported with auto-mixed-precsion or manual precision mode. " << "Retreat inference with native backend. It is recommended that export FP32 model " << "and then inference with FP16 precision mode configuration."; return {false, {}}; } return {true, {layer->getOutput(0)}}; } MS_TRT_CONVERTER_FUNC_REG(LayerNorm) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret || inputs.size() != 3 || !inputs[0].IsTensor()) { MS_LOG(WARNING) << "Get inputs failed. Input num: " << inputs.size(); return {false, {}}; } // Calculate reduce axes const std::vector<size_t> &input_shape = AnfAlgo::GetOutputInferShape(node, 0); auto begin_norm_axis = AnfAlgo::GetNodeAttr<int64_t>(node, "begin_norm_axis"); begin_norm_axis = begin_norm_axis >= 0 ? begin_norm_axis : begin_norm_axis + input_shape.size(); uint32_t reduce_axes = 0; for (size_t i = LongToSize(begin_norm_axis); i < input_shape.size(); i++) { reduce_axes |= 1UL << i; } // Reshape gamma and beta for broadcast auto begin_params_axis = AnfAlgo::GetNodeAttr<int64_t>(node, "begin_params_axis"); begin_params_axis = begin_params_axis >= 0 ? begin_params_axis : begin_params_axis + input_shape.size(); std::vector<size_t> param_shape = input_shape; for (size_t j = 0; j < LongToSize(begin_params_axis); j++) { param_shape[j] = 1; } auto epsilon = AnfAlgo::GetNodeAttr<float>(node, "epsilon"); std::shared_ptr<tensor::Tensor> weight = context->CreateTempWeight(kNumberTypeFloat32, {1}); auto value = static_cast<float *>(weight->data_c()); value[0] = epsilon; nvinfer1::Dims dim; dim.nbDims = SizeToInt(input_shape.size()); for (size_t i = 0; i < input_shape.size(); i++) { dim.d[i] = 1; } auto *epsilon_layer = context->network()->addConstant(dim, nvinfer1::Weights{nvinfer1::DataType::kFLOAT, value, 1}); MS_EXCEPTION_IF_NULL(epsilon_layer); // y = (x - mean) / sqrt(var) * gamma + beta auto *mean = context->network()->addReduce(*inputs[0].tensor(), nvinfer1::ReduceOperation::kAVG, reduce_axes, true); MS_EXCEPTION_IF_NULL(mean); auto *sub = context->network()->addElementWise(*inputs[0].tensor(), *mean->getOutput(0), nvinfer1::ElementWiseOperation::kSUB); MS_EXCEPTION_IF_NULL(sub); auto *pow = context->network()->addElementWise(*sub->getOutput(0), *sub->getOutput(0), nvinfer1::ElementWiseOperation::kPROD); MS_EXCEPTION_IF_NULL(pow); auto *var = context->network()->addReduce(*pow->getOutput(0), nvinfer1::ReduceOperation::kAVG, reduce_axes, true); MS_EXCEPTION_IF_NULL(var); auto *var_epsilon = context->network()->addElementWise(*var->getOutput(0), *epsilon_layer->getOutput(0), nvinfer1::ElementWiseOperation::kSUM); MS_EXCEPTION_IF_NULL(var_epsilon); auto *std = context->network()->addUnary(*var_epsilon->getOutput(0), nvinfer1::UnaryOperation::kSQRT); MS_EXCEPTION_IF_NULL(std); auto *div = context->network()->addElementWise(*sub->getOutput(0), *std->getOutput(0), nvinfer1::ElementWiseOperation::kDIV); MS_EXCEPTION_IF_NULL(div); auto *mul = context->network()->addElementWise(*div->getOutput(0), *ToTensor(&inputs[1], param_shape, context), nvinfer1::ElementWiseOperation::kPROD); MS_EXCEPTION_IF_NULL(mul); auto *add = context->network()->addElementWise(*mul->getOutput(0), *ToTensor(&inputs[2], param_shape, context), nvinfer1::ElementWiseOperation::kSUM); MS_EXCEPTION_IF_NULL(add); return {true, {add->getOutput(0)}}; } MS_TRT_CONVERTER_FUNC_REG(Return) { std::vector<LayerInput> inputs; bool ret = context->LoadLayerInput(node, &inputs); if (!ret) { return {false, {}}; } for (size_t i = 0; i < inputs.size(); ++i) { nvinfer1::ITensor *input = nullptr; if (inputs[i].IsTensor()) { input = inputs[i].tensor(); } else { std::vector<size_t> shape; std::transform(inputs[i].shape().begin(), inputs[i].shape().end(), std::back_inserter(shape), [](int64_t d) { return LongToSize(d); }); input = ToTensor(&inputs[i], shape, context); } const std::string &name = "return_output_" + std::to_string(i); input->setName(name.c_str()); context->network()->markOutput(*input); } return {true, {}}; } } // namespace opt } // namespace mindspore
43.895267
119
0.688309
[ "shape", "vector", "model", "transform" ]
4f62e78ed2116f14c9bfb7b11a3ec1ed0d4656cb
111,629
cpp
C++
pywinrt/winsdk/src/py.Windows.UI.WindowManagement.cpp
pywinrt/python-winsdk
1e2958a712949579f5e84d38220062b2cec12511
[ "MIT" ]
3
2022-02-14T14:53:08.000Z
2022-03-29T20:48:54.000Z
pywinrt/winsdk/src/py.Windows.UI.WindowManagement.cpp
pywinrt/python-winsdk
1e2958a712949579f5e84d38220062b2cec12511
[ "MIT" ]
4
2022-01-28T02:53:52.000Z
2022-02-26T18:10:05.000Z
pywinrt/winsdk/src/py.Windows.UI.WindowManagement.cpp
pywinrt/python-winsdk
1e2958a712949579f5e84d38220062b2cec12511
[ "MIT" ]
null
null
null
// WARNING: Please don't edit this file. It was generated by Python/WinRT v1.0.0-beta.4 #include "pybase.h" #include "py.Windows.UI.WindowManagement.h" PyTypeObject* py::winrt_type<winrt::Windows::UI::WindowManagement::AppWindow>::python_type; PyTypeObject* py::winrt_type<winrt::Windows::UI::WindowManagement::AppWindowChangedEventArgs>::python_type; PyTypeObject* py::winrt_type<winrt::Windows::UI::WindowManagement::AppWindowCloseRequestedEventArgs>::python_type; PyTypeObject* py::winrt_type<winrt::Windows::UI::WindowManagement::AppWindowClosedEventArgs>::python_type; PyTypeObject* py::winrt_type<winrt::Windows::UI::WindowManagement::AppWindowFrame>::python_type; PyTypeObject* py::winrt_type<winrt::Windows::UI::WindowManagement::AppWindowPlacement>::python_type; PyTypeObject* py::winrt_type<winrt::Windows::UI::WindowManagement::AppWindowPresentationConfiguration>::python_type; PyTypeObject* py::winrt_type<winrt::Windows::UI::WindowManagement::AppWindowPresenter>::python_type; PyTypeObject* py::winrt_type<winrt::Windows::UI::WindowManagement::AppWindowTitleBar>::python_type; PyTypeObject* py::winrt_type<winrt::Windows::UI::WindowManagement::AppWindowTitleBarOcclusion>::python_type; PyTypeObject* py::winrt_type<winrt::Windows::UI::WindowManagement::CompactOverlayPresentationConfiguration>::python_type; PyTypeObject* py::winrt_type<winrt::Windows::UI::WindowManagement::DefaultPresentationConfiguration>::python_type; PyTypeObject* py::winrt_type<winrt::Windows::UI::WindowManagement::DisplayRegion>::python_type; PyTypeObject* py::winrt_type<winrt::Windows::UI::WindowManagement::FullScreenPresentationConfiguration>::python_type; PyTypeObject* py::winrt_type<winrt::Windows::UI::WindowManagement::WindowServices>::python_type; PyTypeObject* py::winrt_type<winrt::Windows::UI::WindowManagement::WindowingEnvironment>::python_type; PyTypeObject* py::winrt_type<winrt::Windows::UI::WindowManagement::WindowingEnvironmentAddedEventArgs>::python_type; PyTypeObject* py::winrt_type<winrt::Windows::UI::WindowManagement::WindowingEnvironmentChangedEventArgs>::python_type; PyTypeObject* py::winrt_type<winrt::Windows::UI::WindowManagement::WindowingEnvironmentRemovedEventArgs>::python_type; namespace py::cpp::Windows::UI::WindowManagement { // ----- AppWindow class -------------------- constexpr const char* const _type_name_AppWindow = "AppWindow"; static PyObject* _new_AppWindow(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { py::set_invalid_activation_error(_type_name_AppWindow); return nullptr; } static void _dealloc_AppWindow(py::wrapper::Windows::UI::WindowManagement::AppWindow* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* AppWindow_ClearAllPersistedState(PyObject* /*unused*/, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { winrt::Windows::UI::WindowManagement::AppWindow::ClearAllPersistedState(); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* AppWindow_ClearPersistedState(PyObject* /*unused*/, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 1) { try { auto param0 = py::convert_to<winrt::hstring>(args, 0); winrt::Windows::UI::WindowManagement::AppWindow::ClearPersistedState(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* AppWindow_CloseAsync(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { return py::convert(self->obj.CloseAsync()); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* AppWindow_GetDisplayRegions(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { return py::convert(self->obj.GetDisplayRegions()); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* AppWindow_GetPlacement(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { return py::convert(self->obj.GetPlacement()); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* AppWindow_RequestMoveAdjacentToCurrentView(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { self->obj.RequestMoveAdjacentToCurrentView(); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* AppWindow_RequestMoveAdjacentToWindow(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 1) { try { auto param0 = py::convert_to<winrt::Windows::UI::WindowManagement::AppWindow>(args, 0); self->obj.RequestMoveAdjacentToWindow(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* AppWindow_RequestMoveRelativeToCurrentViewContent(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 1) { try { auto param0 = py::convert_to<winrt::Windows::Foundation::Point>(args, 0); self->obj.RequestMoveRelativeToCurrentViewContent(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* AppWindow_RequestMoveRelativeToDisplayRegion(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 2) { try { auto param0 = py::convert_to<winrt::Windows::UI::WindowManagement::DisplayRegion>(args, 0); auto param1 = py::convert_to<winrt::Windows::Foundation::Point>(args, 1); self->obj.RequestMoveRelativeToDisplayRegion(param0, param1); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* AppWindow_RequestMoveRelativeToWindowContent(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 2) { try { auto param0 = py::convert_to<winrt::Windows::UI::WindowManagement::AppWindow>(args, 0); auto param1 = py::convert_to<winrt::Windows::Foundation::Point>(args, 1); self->obj.RequestMoveRelativeToWindowContent(param0, param1); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* AppWindow_RequestMoveToDisplayRegion(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 1) { try { auto param0 = py::convert_to<winrt::Windows::UI::WindowManagement::DisplayRegion>(args, 0); self->obj.RequestMoveToDisplayRegion(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* AppWindow_RequestSize(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 1) { try { auto param0 = py::convert_to<winrt::Windows::Foundation::Size>(args, 0); self->obj.RequestSize(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* AppWindow_TryCreateAsync(PyObject* /*unused*/, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { return py::convert(winrt::Windows::UI::WindowManagement::AppWindow::TryCreateAsync()); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* AppWindow_TryShowAsync(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { return py::convert(self->obj.TryShowAsync()); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* AppWindow_get_Title(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.Title()); } catch (...) { py::to_PyErr(); return nullptr; } } static int AppWindow_put_Title(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, PyObject* arg, void* /*unused*/) noexcept { if (arg == nullptr) { PyErr_SetString(PyExc_TypeError, "property delete not supported"); return -1; } try { auto param0 = py::convert_to<winrt::hstring>(arg); self->obj.Title(param0); return 0; } catch (...) { py::to_PyErr(); return -1; } } static PyObject* AppWindow_get_PersistedStateId(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.PersistedStateId()); } catch (...) { py::to_PyErr(); return nullptr; } } static int AppWindow_put_PersistedStateId(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, PyObject* arg, void* /*unused*/) noexcept { if (arg == nullptr) { PyErr_SetString(PyExc_TypeError, "property delete not supported"); return -1; } try { auto param0 = py::convert_to<winrt::hstring>(arg); self->obj.PersistedStateId(param0); return 0; } catch (...) { py::to_PyErr(); return -1; } } static PyObject* AppWindow_get_Content(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.Content()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* AppWindow_get_DispatcherQueue(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.DispatcherQueue()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* AppWindow_get_Frame(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.Frame()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* AppWindow_get_IsVisible(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.IsVisible()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* AppWindow_get_Presenter(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.Presenter()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* AppWindow_get_TitleBar(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.TitleBar()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* AppWindow_get_UIContext(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.UIContext()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* AppWindow_get_WindowingEnvironment(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.WindowingEnvironment()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* AppWindow_add_Changed(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::UI::WindowManagement::AppWindow, winrt::Windows::UI::WindowManagement::AppWindowChangedEventArgs>>(arg); return py::convert(self->obj.Changed(param0)); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* AppWindow_remove_Changed(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::event_token>(arg); self->obj.Changed(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* AppWindow_add_CloseRequested(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::UI::WindowManagement::AppWindow, winrt::Windows::UI::WindowManagement::AppWindowCloseRequestedEventArgs>>(arg); return py::convert(self->obj.CloseRequested(param0)); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* AppWindow_remove_CloseRequested(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::event_token>(arg); self->obj.CloseRequested(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* AppWindow_add_Closed(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::UI::WindowManagement::AppWindow, winrt::Windows::UI::WindowManagement::AppWindowClosedEventArgs>>(arg); return py::convert(self->obj.Closed(param0)); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* AppWindow_remove_Closed(py::wrapper::Windows::UI::WindowManagement::AppWindow* self, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::event_token>(arg); self->obj.Closed(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* _from_AppWindow(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::UI::WindowManagement::AppWindow>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_AppWindow[] = { { "clear_all_persisted_state", reinterpret_cast<PyCFunction>(AppWindow_ClearAllPersistedState), METH_VARARGS | METH_STATIC, nullptr }, { "clear_persisted_state", reinterpret_cast<PyCFunction>(AppWindow_ClearPersistedState), METH_VARARGS | METH_STATIC, nullptr }, { "close_async", reinterpret_cast<PyCFunction>(AppWindow_CloseAsync), METH_VARARGS, nullptr }, { "get_display_regions", reinterpret_cast<PyCFunction>(AppWindow_GetDisplayRegions), METH_VARARGS, nullptr }, { "get_placement", reinterpret_cast<PyCFunction>(AppWindow_GetPlacement), METH_VARARGS, nullptr }, { "request_move_adjacent_to_current_view", reinterpret_cast<PyCFunction>(AppWindow_RequestMoveAdjacentToCurrentView), METH_VARARGS, nullptr }, { "request_move_adjacent_to_window", reinterpret_cast<PyCFunction>(AppWindow_RequestMoveAdjacentToWindow), METH_VARARGS, nullptr }, { "request_move_relative_to_current_view_content", reinterpret_cast<PyCFunction>(AppWindow_RequestMoveRelativeToCurrentViewContent), METH_VARARGS, nullptr }, { "request_move_relative_to_display_region", reinterpret_cast<PyCFunction>(AppWindow_RequestMoveRelativeToDisplayRegion), METH_VARARGS, nullptr }, { "request_move_relative_to_window_content", reinterpret_cast<PyCFunction>(AppWindow_RequestMoveRelativeToWindowContent), METH_VARARGS, nullptr }, { "request_move_to_display_region", reinterpret_cast<PyCFunction>(AppWindow_RequestMoveToDisplayRegion), METH_VARARGS, nullptr }, { "request_size", reinterpret_cast<PyCFunction>(AppWindow_RequestSize), METH_VARARGS, nullptr }, { "try_create_async", reinterpret_cast<PyCFunction>(AppWindow_TryCreateAsync), METH_VARARGS | METH_STATIC, nullptr }, { "try_show_async", reinterpret_cast<PyCFunction>(AppWindow_TryShowAsync), METH_VARARGS, nullptr }, { "add_changed", reinterpret_cast<PyCFunction>(AppWindow_add_Changed), METH_O, nullptr }, { "remove_changed", reinterpret_cast<PyCFunction>(AppWindow_remove_Changed), METH_O, nullptr }, { "add_close_requested", reinterpret_cast<PyCFunction>(AppWindow_add_CloseRequested), METH_O, nullptr }, { "remove_close_requested", reinterpret_cast<PyCFunction>(AppWindow_remove_CloseRequested), METH_O, nullptr }, { "add_closed", reinterpret_cast<PyCFunction>(AppWindow_add_Closed), METH_O, nullptr }, { "remove_closed", reinterpret_cast<PyCFunction>(AppWindow_remove_Closed), METH_O, nullptr }, { "_from", reinterpret_cast<PyCFunction>(_from_AppWindow), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_AppWindow[] = { { "title", reinterpret_cast<getter>(AppWindow_get_Title), reinterpret_cast<setter>(AppWindow_put_Title), nullptr, nullptr }, { "persisted_state_id", reinterpret_cast<getter>(AppWindow_get_PersistedStateId), reinterpret_cast<setter>(AppWindow_put_PersistedStateId), nullptr, nullptr }, { "content", reinterpret_cast<getter>(AppWindow_get_Content), nullptr, nullptr, nullptr }, { "dispatcher_queue", reinterpret_cast<getter>(AppWindow_get_DispatcherQueue), nullptr, nullptr, nullptr }, { "frame", reinterpret_cast<getter>(AppWindow_get_Frame), nullptr, nullptr, nullptr }, { "is_visible", reinterpret_cast<getter>(AppWindow_get_IsVisible), nullptr, nullptr, nullptr }, { "presenter", reinterpret_cast<getter>(AppWindow_get_Presenter), nullptr, nullptr, nullptr }, { "title_bar", reinterpret_cast<getter>(AppWindow_get_TitleBar), nullptr, nullptr, nullptr }, { "u_i_context", reinterpret_cast<getter>(AppWindow_get_UIContext), nullptr, nullptr, nullptr }, { "windowing_environment", reinterpret_cast<getter>(AppWindow_get_WindowingEnvironment), nullptr, nullptr, nullptr }, { } }; static PyType_Slot _type_slots_AppWindow[] = { { Py_tp_new, _new_AppWindow }, { Py_tp_dealloc, _dealloc_AppWindow }, { Py_tp_methods, _methods_AppWindow }, { Py_tp_getset, _getset_AppWindow }, { }, }; static PyType_Spec _type_spec_AppWindow = { "_winsdk_Windows_UI_WindowManagement.AppWindow", sizeof(py::wrapper::Windows::UI::WindowManagement::AppWindow), 0, Py_TPFLAGS_DEFAULT, _type_slots_AppWindow }; // ----- AppWindowChangedEventArgs class -------------------- constexpr const char* const _type_name_AppWindowChangedEventArgs = "AppWindowChangedEventArgs"; static PyObject* _new_AppWindowChangedEventArgs(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { py::set_invalid_activation_error(_type_name_AppWindowChangedEventArgs); return nullptr; } static void _dealloc_AppWindowChangedEventArgs(py::wrapper::Windows::UI::WindowManagement::AppWindowChangedEventArgs* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* AppWindowChangedEventArgs_get_DidAvailableWindowPresentationsChange(py::wrapper::Windows::UI::WindowManagement::AppWindowChangedEventArgs* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.DidAvailableWindowPresentationsChange()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* AppWindowChangedEventArgs_get_DidDisplayRegionsChange(py::wrapper::Windows::UI::WindowManagement::AppWindowChangedEventArgs* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.DidDisplayRegionsChange()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* AppWindowChangedEventArgs_get_DidFrameChange(py::wrapper::Windows::UI::WindowManagement::AppWindowChangedEventArgs* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.DidFrameChange()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* AppWindowChangedEventArgs_get_DidSizeChange(py::wrapper::Windows::UI::WindowManagement::AppWindowChangedEventArgs* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.DidSizeChange()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* AppWindowChangedEventArgs_get_DidTitleBarChange(py::wrapper::Windows::UI::WindowManagement::AppWindowChangedEventArgs* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.DidTitleBarChange()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* AppWindowChangedEventArgs_get_DidVisibilityChange(py::wrapper::Windows::UI::WindowManagement::AppWindowChangedEventArgs* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.DidVisibilityChange()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* AppWindowChangedEventArgs_get_DidWindowPresentationChange(py::wrapper::Windows::UI::WindowManagement::AppWindowChangedEventArgs* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.DidWindowPresentationChange()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* AppWindowChangedEventArgs_get_DidWindowingEnvironmentChange(py::wrapper::Windows::UI::WindowManagement::AppWindowChangedEventArgs* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.DidWindowingEnvironmentChange()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* _from_AppWindowChangedEventArgs(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::UI::WindowManagement::AppWindowChangedEventArgs>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_AppWindowChangedEventArgs[] = { { "_from", reinterpret_cast<PyCFunction>(_from_AppWindowChangedEventArgs), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_AppWindowChangedEventArgs[] = { { "did_available_window_presentations_change", reinterpret_cast<getter>(AppWindowChangedEventArgs_get_DidAvailableWindowPresentationsChange), nullptr, nullptr, nullptr }, { "did_display_regions_change", reinterpret_cast<getter>(AppWindowChangedEventArgs_get_DidDisplayRegionsChange), nullptr, nullptr, nullptr }, { "did_frame_change", reinterpret_cast<getter>(AppWindowChangedEventArgs_get_DidFrameChange), nullptr, nullptr, nullptr }, { "did_size_change", reinterpret_cast<getter>(AppWindowChangedEventArgs_get_DidSizeChange), nullptr, nullptr, nullptr }, { "did_title_bar_change", reinterpret_cast<getter>(AppWindowChangedEventArgs_get_DidTitleBarChange), nullptr, nullptr, nullptr }, { "did_visibility_change", reinterpret_cast<getter>(AppWindowChangedEventArgs_get_DidVisibilityChange), nullptr, nullptr, nullptr }, { "did_window_presentation_change", reinterpret_cast<getter>(AppWindowChangedEventArgs_get_DidWindowPresentationChange), nullptr, nullptr, nullptr }, { "did_windowing_environment_change", reinterpret_cast<getter>(AppWindowChangedEventArgs_get_DidWindowingEnvironmentChange), nullptr, nullptr, nullptr }, { } }; static PyType_Slot _type_slots_AppWindowChangedEventArgs[] = { { Py_tp_new, _new_AppWindowChangedEventArgs }, { Py_tp_dealloc, _dealloc_AppWindowChangedEventArgs }, { Py_tp_methods, _methods_AppWindowChangedEventArgs }, { Py_tp_getset, _getset_AppWindowChangedEventArgs }, { }, }; static PyType_Spec _type_spec_AppWindowChangedEventArgs = { "_winsdk_Windows_UI_WindowManagement.AppWindowChangedEventArgs", sizeof(py::wrapper::Windows::UI::WindowManagement::AppWindowChangedEventArgs), 0, Py_TPFLAGS_DEFAULT, _type_slots_AppWindowChangedEventArgs }; // ----- AppWindowCloseRequestedEventArgs class -------------------- constexpr const char* const _type_name_AppWindowCloseRequestedEventArgs = "AppWindowCloseRequestedEventArgs"; static PyObject* _new_AppWindowCloseRequestedEventArgs(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { py::set_invalid_activation_error(_type_name_AppWindowCloseRequestedEventArgs); return nullptr; } static void _dealloc_AppWindowCloseRequestedEventArgs(py::wrapper::Windows::UI::WindowManagement::AppWindowCloseRequestedEventArgs* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* AppWindowCloseRequestedEventArgs_GetDeferral(py::wrapper::Windows::UI::WindowManagement::AppWindowCloseRequestedEventArgs* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { return py::convert(self->obj.GetDeferral()); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* AppWindowCloseRequestedEventArgs_get_Cancel(py::wrapper::Windows::UI::WindowManagement::AppWindowCloseRequestedEventArgs* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.Cancel()); } catch (...) { py::to_PyErr(); return nullptr; } } static int AppWindowCloseRequestedEventArgs_put_Cancel(py::wrapper::Windows::UI::WindowManagement::AppWindowCloseRequestedEventArgs* self, PyObject* arg, void* /*unused*/) noexcept { if (arg == nullptr) { PyErr_SetString(PyExc_TypeError, "property delete not supported"); return -1; } try { auto param0 = py::convert_to<bool>(arg); self->obj.Cancel(param0); return 0; } catch (...) { py::to_PyErr(); return -1; } } static PyObject* _from_AppWindowCloseRequestedEventArgs(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::UI::WindowManagement::AppWindowCloseRequestedEventArgs>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_AppWindowCloseRequestedEventArgs[] = { { "get_deferral", reinterpret_cast<PyCFunction>(AppWindowCloseRequestedEventArgs_GetDeferral), METH_VARARGS, nullptr }, { "_from", reinterpret_cast<PyCFunction>(_from_AppWindowCloseRequestedEventArgs), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_AppWindowCloseRequestedEventArgs[] = { { "cancel", reinterpret_cast<getter>(AppWindowCloseRequestedEventArgs_get_Cancel), reinterpret_cast<setter>(AppWindowCloseRequestedEventArgs_put_Cancel), nullptr, nullptr }, { } }; static PyType_Slot _type_slots_AppWindowCloseRequestedEventArgs[] = { { Py_tp_new, _new_AppWindowCloseRequestedEventArgs }, { Py_tp_dealloc, _dealloc_AppWindowCloseRequestedEventArgs }, { Py_tp_methods, _methods_AppWindowCloseRequestedEventArgs }, { Py_tp_getset, _getset_AppWindowCloseRequestedEventArgs }, { }, }; static PyType_Spec _type_spec_AppWindowCloseRequestedEventArgs = { "_winsdk_Windows_UI_WindowManagement.AppWindowCloseRequestedEventArgs", sizeof(py::wrapper::Windows::UI::WindowManagement::AppWindowCloseRequestedEventArgs), 0, Py_TPFLAGS_DEFAULT, _type_slots_AppWindowCloseRequestedEventArgs }; // ----- AppWindowClosedEventArgs class -------------------- constexpr const char* const _type_name_AppWindowClosedEventArgs = "AppWindowClosedEventArgs"; static PyObject* _new_AppWindowClosedEventArgs(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { py::set_invalid_activation_error(_type_name_AppWindowClosedEventArgs); return nullptr; } static void _dealloc_AppWindowClosedEventArgs(py::wrapper::Windows::UI::WindowManagement::AppWindowClosedEventArgs* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* AppWindowClosedEventArgs_get_Reason(py::wrapper::Windows::UI::WindowManagement::AppWindowClosedEventArgs* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.Reason()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* _from_AppWindowClosedEventArgs(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::UI::WindowManagement::AppWindowClosedEventArgs>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_AppWindowClosedEventArgs[] = { { "_from", reinterpret_cast<PyCFunction>(_from_AppWindowClosedEventArgs), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_AppWindowClosedEventArgs[] = { { "reason", reinterpret_cast<getter>(AppWindowClosedEventArgs_get_Reason), nullptr, nullptr, nullptr }, { } }; static PyType_Slot _type_slots_AppWindowClosedEventArgs[] = { { Py_tp_new, _new_AppWindowClosedEventArgs }, { Py_tp_dealloc, _dealloc_AppWindowClosedEventArgs }, { Py_tp_methods, _methods_AppWindowClosedEventArgs }, { Py_tp_getset, _getset_AppWindowClosedEventArgs }, { }, }; static PyType_Spec _type_spec_AppWindowClosedEventArgs = { "_winsdk_Windows_UI_WindowManagement.AppWindowClosedEventArgs", sizeof(py::wrapper::Windows::UI::WindowManagement::AppWindowClosedEventArgs), 0, Py_TPFLAGS_DEFAULT, _type_slots_AppWindowClosedEventArgs }; // ----- AppWindowFrame class -------------------- constexpr const char* const _type_name_AppWindowFrame = "AppWindowFrame"; static PyObject* _new_AppWindowFrame(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { py::set_invalid_activation_error(_type_name_AppWindowFrame); return nullptr; } static void _dealloc_AppWindowFrame(py::wrapper::Windows::UI::WindowManagement::AppWindowFrame* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* AppWindowFrame_GetFrameStyle(py::wrapper::Windows::UI::WindowManagement::AppWindowFrame* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { return py::convert(self->obj.GetFrameStyle()); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* AppWindowFrame_SetFrameStyle(py::wrapper::Windows::UI::WindowManagement::AppWindowFrame* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 1) { try { auto param0 = py::convert_to<winrt::Windows::UI::WindowManagement::AppWindowFrameStyle>(args, 0); self->obj.SetFrameStyle(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* AppWindowFrame_get_DragRegionVisuals(py::wrapper::Windows::UI::WindowManagement::AppWindowFrame* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.DragRegionVisuals()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* _from_AppWindowFrame(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::UI::WindowManagement::AppWindowFrame>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_AppWindowFrame[] = { { "get_frame_style", reinterpret_cast<PyCFunction>(AppWindowFrame_GetFrameStyle), METH_VARARGS, nullptr }, { "set_frame_style", reinterpret_cast<PyCFunction>(AppWindowFrame_SetFrameStyle), METH_VARARGS, nullptr }, { "_from", reinterpret_cast<PyCFunction>(_from_AppWindowFrame), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_AppWindowFrame[] = { { "drag_region_visuals", reinterpret_cast<getter>(AppWindowFrame_get_DragRegionVisuals), nullptr, nullptr, nullptr }, { } }; static PyType_Slot _type_slots_AppWindowFrame[] = { { Py_tp_new, _new_AppWindowFrame }, { Py_tp_dealloc, _dealloc_AppWindowFrame }, { Py_tp_methods, _methods_AppWindowFrame }, { Py_tp_getset, _getset_AppWindowFrame }, { }, }; static PyType_Spec _type_spec_AppWindowFrame = { "_winsdk_Windows_UI_WindowManagement.AppWindowFrame", sizeof(py::wrapper::Windows::UI::WindowManagement::AppWindowFrame), 0, Py_TPFLAGS_DEFAULT, _type_slots_AppWindowFrame }; // ----- AppWindowPlacement class -------------------- constexpr const char* const _type_name_AppWindowPlacement = "AppWindowPlacement"; static PyObject* _new_AppWindowPlacement(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { py::set_invalid_activation_error(_type_name_AppWindowPlacement); return nullptr; } static void _dealloc_AppWindowPlacement(py::wrapper::Windows::UI::WindowManagement::AppWindowPlacement* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* AppWindowPlacement_get_DisplayRegion(py::wrapper::Windows::UI::WindowManagement::AppWindowPlacement* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.DisplayRegion()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* AppWindowPlacement_get_Offset(py::wrapper::Windows::UI::WindowManagement::AppWindowPlacement* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.Offset()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* AppWindowPlacement_get_Size(py::wrapper::Windows::UI::WindowManagement::AppWindowPlacement* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.Size()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* _from_AppWindowPlacement(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::UI::WindowManagement::AppWindowPlacement>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_AppWindowPlacement[] = { { "_from", reinterpret_cast<PyCFunction>(_from_AppWindowPlacement), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_AppWindowPlacement[] = { { "display_region", reinterpret_cast<getter>(AppWindowPlacement_get_DisplayRegion), nullptr, nullptr, nullptr }, { "offset", reinterpret_cast<getter>(AppWindowPlacement_get_Offset), nullptr, nullptr, nullptr }, { "size", reinterpret_cast<getter>(AppWindowPlacement_get_Size), nullptr, nullptr, nullptr }, { } }; static PyType_Slot _type_slots_AppWindowPlacement[] = { { Py_tp_new, _new_AppWindowPlacement }, { Py_tp_dealloc, _dealloc_AppWindowPlacement }, { Py_tp_methods, _methods_AppWindowPlacement }, { Py_tp_getset, _getset_AppWindowPlacement }, { }, }; static PyType_Spec _type_spec_AppWindowPlacement = { "_winsdk_Windows_UI_WindowManagement.AppWindowPlacement", sizeof(py::wrapper::Windows::UI::WindowManagement::AppWindowPlacement), 0, Py_TPFLAGS_DEFAULT, _type_slots_AppWindowPlacement }; // ----- AppWindowPresentationConfiguration class -------------------- constexpr const char* const _type_name_AppWindowPresentationConfiguration = "AppWindowPresentationConfiguration"; static PyObject* _new_AppWindowPresentationConfiguration(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { py::set_invalid_activation_error(_type_name_AppWindowPresentationConfiguration); return nullptr; } static void _dealloc_AppWindowPresentationConfiguration(py::wrapper::Windows::UI::WindowManagement::AppWindowPresentationConfiguration* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* AppWindowPresentationConfiguration_get_Kind(py::wrapper::Windows::UI::WindowManagement::AppWindowPresentationConfiguration* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.Kind()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* _from_AppWindowPresentationConfiguration(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::UI::WindowManagement::AppWindowPresentationConfiguration>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_AppWindowPresentationConfiguration[] = { { "_from", reinterpret_cast<PyCFunction>(_from_AppWindowPresentationConfiguration), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_AppWindowPresentationConfiguration[] = { { "kind", reinterpret_cast<getter>(AppWindowPresentationConfiguration_get_Kind), nullptr, nullptr, nullptr }, { } }; static PyType_Slot _type_slots_AppWindowPresentationConfiguration[] = { { Py_tp_new, _new_AppWindowPresentationConfiguration }, { Py_tp_dealloc, _dealloc_AppWindowPresentationConfiguration }, { Py_tp_methods, _methods_AppWindowPresentationConfiguration }, { Py_tp_getset, _getset_AppWindowPresentationConfiguration }, { }, }; static PyType_Spec _type_spec_AppWindowPresentationConfiguration = { "_winsdk_Windows_UI_WindowManagement.AppWindowPresentationConfiguration", sizeof(py::wrapper::Windows::UI::WindowManagement::AppWindowPresentationConfiguration), 0, Py_TPFLAGS_DEFAULT, _type_slots_AppWindowPresentationConfiguration }; // ----- AppWindowPresenter class -------------------- constexpr const char* const _type_name_AppWindowPresenter = "AppWindowPresenter"; static PyObject* _new_AppWindowPresenter(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { py::set_invalid_activation_error(_type_name_AppWindowPresenter); return nullptr; } static void _dealloc_AppWindowPresenter(py::wrapper::Windows::UI::WindowManagement::AppWindowPresenter* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* AppWindowPresenter_GetConfiguration(py::wrapper::Windows::UI::WindowManagement::AppWindowPresenter* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { return py::convert(self->obj.GetConfiguration()); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* AppWindowPresenter_IsPresentationSupported(py::wrapper::Windows::UI::WindowManagement::AppWindowPresenter* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 1) { try { auto param0 = py::convert_to<winrt::Windows::UI::WindowManagement::AppWindowPresentationKind>(args, 0); return py::convert(self->obj.IsPresentationSupported(param0)); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* AppWindowPresenter_RequestPresentation(py::wrapper::Windows::UI::WindowManagement::AppWindowPresenter* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 1) { try { auto param0 = py::convert_to<winrt::Windows::UI::WindowManagement::AppWindowPresentationKind>(args, 0); return py::convert(self->obj.RequestPresentation(param0)); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* _from_AppWindowPresenter(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::UI::WindowManagement::AppWindowPresenter>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_AppWindowPresenter[] = { { "get_configuration", reinterpret_cast<PyCFunction>(AppWindowPresenter_GetConfiguration), METH_VARARGS, nullptr }, { "is_presentation_supported", reinterpret_cast<PyCFunction>(AppWindowPresenter_IsPresentationSupported), METH_VARARGS, nullptr }, { "request_presentation", reinterpret_cast<PyCFunction>(AppWindowPresenter_RequestPresentation), METH_VARARGS, nullptr }, { "_from", reinterpret_cast<PyCFunction>(_from_AppWindowPresenter), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_AppWindowPresenter[] = { { } }; static PyType_Slot _type_slots_AppWindowPresenter[] = { { Py_tp_new, _new_AppWindowPresenter }, { Py_tp_dealloc, _dealloc_AppWindowPresenter }, { Py_tp_methods, _methods_AppWindowPresenter }, { Py_tp_getset, _getset_AppWindowPresenter }, { }, }; static PyType_Spec _type_spec_AppWindowPresenter = { "_winsdk_Windows_UI_WindowManagement.AppWindowPresenter", sizeof(py::wrapper::Windows::UI::WindowManagement::AppWindowPresenter), 0, Py_TPFLAGS_DEFAULT, _type_slots_AppWindowPresenter }; // ----- AppWindowTitleBar class -------------------- constexpr const char* const _type_name_AppWindowTitleBar = "AppWindowTitleBar"; static PyObject* _new_AppWindowTitleBar(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { py::set_invalid_activation_error(_type_name_AppWindowTitleBar); return nullptr; } static void _dealloc_AppWindowTitleBar(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* AppWindowTitleBar_GetPreferredVisibility(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { return py::convert(self->obj.GetPreferredVisibility()); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* AppWindowTitleBar_GetTitleBarOcclusions(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { return py::convert(self->obj.GetTitleBarOcclusions()); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* AppWindowTitleBar_SetPreferredVisibility(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 1) { try { auto param0 = py::convert_to<winrt::Windows::UI::WindowManagement::AppWindowTitleBarVisibility>(args, 0); self->obj.SetPreferredVisibility(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* AppWindowTitleBar_get_InactiveForegroundColor(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.InactiveForegroundColor()); } catch (...) { py::to_PyErr(); return nullptr; } } static int AppWindowTitleBar_put_InactiveForegroundColor(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, PyObject* arg, void* /*unused*/) noexcept { if (arg == nullptr) { PyErr_SetString(PyExc_TypeError, "property delete not supported"); return -1; } try { auto param0 = py::convert_to<winrt::Windows::Foundation::IReference<winrt::Windows::UI::Color>>(arg); self->obj.InactiveForegroundColor(param0); return 0; } catch (...) { py::to_PyErr(); return -1; } } static PyObject* AppWindowTitleBar_get_InactiveBackgroundColor(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.InactiveBackgroundColor()); } catch (...) { py::to_PyErr(); return nullptr; } } static int AppWindowTitleBar_put_InactiveBackgroundColor(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, PyObject* arg, void* /*unused*/) noexcept { if (arg == nullptr) { PyErr_SetString(PyExc_TypeError, "property delete not supported"); return -1; } try { auto param0 = py::convert_to<winrt::Windows::Foundation::IReference<winrt::Windows::UI::Color>>(arg); self->obj.InactiveBackgroundColor(param0); return 0; } catch (...) { py::to_PyErr(); return -1; } } static PyObject* AppWindowTitleBar_get_ForegroundColor(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.ForegroundColor()); } catch (...) { py::to_PyErr(); return nullptr; } } static int AppWindowTitleBar_put_ForegroundColor(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, PyObject* arg, void* /*unused*/) noexcept { if (arg == nullptr) { PyErr_SetString(PyExc_TypeError, "property delete not supported"); return -1; } try { auto param0 = py::convert_to<winrt::Windows::Foundation::IReference<winrt::Windows::UI::Color>>(arg); self->obj.ForegroundColor(param0); return 0; } catch (...) { py::to_PyErr(); return -1; } } static PyObject* AppWindowTitleBar_get_ExtendsContentIntoTitleBar(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.ExtendsContentIntoTitleBar()); } catch (...) { py::to_PyErr(); return nullptr; } } static int AppWindowTitleBar_put_ExtendsContentIntoTitleBar(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, PyObject* arg, void* /*unused*/) noexcept { if (arg == nullptr) { PyErr_SetString(PyExc_TypeError, "property delete not supported"); return -1; } try { auto param0 = py::convert_to<bool>(arg); self->obj.ExtendsContentIntoTitleBar(param0); return 0; } catch (...) { py::to_PyErr(); return -1; } } static PyObject* AppWindowTitleBar_get_ButtonPressedForegroundColor(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.ButtonPressedForegroundColor()); } catch (...) { py::to_PyErr(); return nullptr; } } static int AppWindowTitleBar_put_ButtonPressedForegroundColor(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, PyObject* arg, void* /*unused*/) noexcept { if (arg == nullptr) { PyErr_SetString(PyExc_TypeError, "property delete not supported"); return -1; } try { auto param0 = py::convert_to<winrt::Windows::Foundation::IReference<winrt::Windows::UI::Color>>(arg); self->obj.ButtonPressedForegroundColor(param0); return 0; } catch (...) { py::to_PyErr(); return -1; } } static PyObject* AppWindowTitleBar_get_ButtonPressedBackgroundColor(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.ButtonPressedBackgroundColor()); } catch (...) { py::to_PyErr(); return nullptr; } } static int AppWindowTitleBar_put_ButtonPressedBackgroundColor(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, PyObject* arg, void* /*unused*/) noexcept { if (arg == nullptr) { PyErr_SetString(PyExc_TypeError, "property delete not supported"); return -1; } try { auto param0 = py::convert_to<winrt::Windows::Foundation::IReference<winrt::Windows::UI::Color>>(arg); self->obj.ButtonPressedBackgroundColor(param0); return 0; } catch (...) { py::to_PyErr(); return -1; } } static PyObject* AppWindowTitleBar_get_ButtonInactiveForegroundColor(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.ButtonInactiveForegroundColor()); } catch (...) { py::to_PyErr(); return nullptr; } } static int AppWindowTitleBar_put_ButtonInactiveForegroundColor(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, PyObject* arg, void* /*unused*/) noexcept { if (arg == nullptr) { PyErr_SetString(PyExc_TypeError, "property delete not supported"); return -1; } try { auto param0 = py::convert_to<winrt::Windows::Foundation::IReference<winrt::Windows::UI::Color>>(arg); self->obj.ButtonInactiveForegroundColor(param0); return 0; } catch (...) { py::to_PyErr(); return -1; } } static PyObject* AppWindowTitleBar_get_ButtonInactiveBackgroundColor(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.ButtonInactiveBackgroundColor()); } catch (...) { py::to_PyErr(); return nullptr; } } static int AppWindowTitleBar_put_ButtonInactiveBackgroundColor(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, PyObject* arg, void* /*unused*/) noexcept { if (arg == nullptr) { PyErr_SetString(PyExc_TypeError, "property delete not supported"); return -1; } try { auto param0 = py::convert_to<winrt::Windows::Foundation::IReference<winrt::Windows::UI::Color>>(arg); self->obj.ButtonInactiveBackgroundColor(param0); return 0; } catch (...) { py::to_PyErr(); return -1; } } static PyObject* AppWindowTitleBar_get_ButtonHoverForegroundColor(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.ButtonHoverForegroundColor()); } catch (...) { py::to_PyErr(); return nullptr; } } static int AppWindowTitleBar_put_ButtonHoverForegroundColor(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, PyObject* arg, void* /*unused*/) noexcept { if (arg == nullptr) { PyErr_SetString(PyExc_TypeError, "property delete not supported"); return -1; } try { auto param0 = py::convert_to<winrt::Windows::Foundation::IReference<winrt::Windows::UI::Color>>(arg); self->obj.ButtonHoverForegroundColor(param0); return 0; } catch (...) { py::to_PyErr(); return -1; } } static PyObject* AppWindowTitleBar_get_ButtonHoverBackgroundColor(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.ButtonHoverBackgroundColor()); } catch (...) { py::to_PyErr(); return nullptr; } } static int AppWindowTitleBar_put_ButtonHoverBackgroundColor(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, PyObject* arg, void* /*unused*/) noexcept { if (arg == nullptr) { PyErr_SetString(PyExc_TypeError, "property delete not supported"); return -1; } try { auto param0 = py::convert_to<winrt::Windows::Foundation::IReference<winrt::Windows::UI::Color>>(arg); self->obj.ButtonHoverBackgroundColor(param0); return 0; } catch (...) { py::to_PyErr(); return -1; } } static PyObject* AppWindowTitleBar_get_ButtonForegroundColor(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.ButtonForegroundColor()); } catch (...) { py::to_PyErr(); return nullptr; } } static int AppWindowTitleBar_put_ButtonForegroundColor(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, PyObject* arg, void* /*unused*/) noexcept { if (arg == nullptr) { PyErr_SetString(PyExc_TypeError, "property delete not supported"); return -1; } try { auto param0 = py::convert_to<winrt::Windows::Foundation::IReference<winrt::Windows::UI::Color>>(arg); self->obj.ButtonForegroundColor(param0); return 0; } catch (...) { py::to_PyErr(); return -1; } } static PyObject* AppWindowTitleBar_get_ButtonBackgroundColor(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.ButtonBackgroundColor()); } catch (...) { py::to_PyErr(); return nullptr; } } static int AppWindowTitleBar_put_ButtonBackgroundColor(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, PyObject* arg, void* /*unused*/) noexcept { if (arg == nullptr) { PyErr_SetString(PyExc_TypeError, "property delete not supported"); return -1; } try { auto param0 = py::convert_to<winrt::Windows::Foundation::IReference<winrt::Windows::UI::Color>>(arg); self->obj.ButtonBackgroundColor(param0); return 0; } catch (...) { py::to_PyErr(); return -1; } } static PyObject* AppWindowTitleBar_get_BackgroundColor(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.BackgroundColor()); } catch (...) { py::to_PyErr(); return nullptr; } } static int AppWindowTitleBar_put_BackgroundColor(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, PyObject* arg, void* /*unused*/) noexcept { if (arg == nullptr) { PyErr_SetString(PyExc_TypeError, "property delete not supported"); return -1; } try { auto param0 = py::convert_to<winrt::Windows::Foundation::IReference<winrt::Windows::UI::Color>>(arg); self->obj.BackgroundColor(param0); return 0; } catch (...) { py::to_PyErr(); return -1; } } static PyObject* AppWindowTitleBar_get_IsVisible(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.IsVisible()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* _from_AppWindowTitleBar(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::UI::WindowManagement::AppWindowTitleBar>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_AppWindowTitleBar[] = { { "get_preferred_visibility", reinterpret_cast<PyCFunction>(AppWindowTitleBar_GetPreferredVisibility), METH_VARARGS, nullptr }, { "get_title_bar_occlusions", reinterpret_cast<PyCFunction>(AppWindowTitleBar_GetTitleBarOcclusions), METH_VARARGS, nullptr }, { "set_preferred_visibility", reinterpret_cast<PyCFunction>(AppWindowTitleBar_SetPreferredVisibility), METH_VARARGS, nullptr }, { "_from", reinterpret_cast<PyCFunction>(_from_AppWindowTitleBar), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_AppWindowTitleBar[] = { { "inactive_foreground_color", reinterpret_cast<getter>(AppWindowTitleBar_get_InactiveForegroundColor), reinterpret_cast<setter>(AppWindowTitleBar_put_InactiveForegroundColor), nullptr, nullptr }, { "inactive_background_color", reinterpret_cast<getter>(AppWindowTitleBar_get_InactiveBackgroundColor), reinterpret_cast<setter>(AppWindowTitleBar_put_InactiveBackgroundColor), nullptr, nullptr }, { "foreground_color", reinterpret_cast<getter>(AppWindowTitleBar_get_ForegroundColor), reinterpret_cast<setter>(AppWindowTitleBar_put_ForegroundColor), nullptr, nullptr }, { "extends_content_into_title_bar", reinterpret_cast<getter>(AppWindowTitleBar_get_ExtendsContentIntoTitleBar), reinterpret_cast<setter>(AppWindowTitleBar_put_ExtendsContentIntoTitleBar), nullptr, nullptr }, { "button_pressed_foreground_color", reinterpret_cast<getter>(AppWindowTitleBar_get_ButtonPressedForegroundColor), reinterpret_cast<setter>(AppWindowTitleBar_put_ButtonPressedForegroundColor), nullptr, nullptr }, { "button_pressed_background_color", reinterpret_cast<getter>(AppWindowTitleBar_get_ButtonPressedBackgroundColor), reinterpret_cast<setter>(AppWindowTitleBar_put_ButtonPressedBackgroundColor), nullptr, nullptr }, { "button_inactive_foreground_color", reinterpret_cast<getter>(AppWindowTitleBar_get_ButtonInactiveForegroundColor), reinterpret_cast<setter>(AppWindowTitleBar_put_ButtonInactiveForegroundColor), nullptr, nullptr }, { "button_inactive_background_color", reinterpret_cast<getter>(AppWindowTitleBar_get_ButtonInactiveBackgroundColor), reinterpret_cast<setter>(AppWindowTitleBar_put_ButtonInactiveBackgroundColor), nullptr, nullptr }, { "button_hover_foreground_color", reinterpret_cast<getter>(AppWindowTitleBar_get_ButtonHoverForegroundColor), reinterpret_cast<setter>(AppWindowTitleBar_put_ButtonHoverForegroundColor), nullptr, nullptr }, { "button_hover_background_color", reinterpret_cast<getter>(AppWindowTitleBar_get_ButtonHoverBackgroundColor), reinterpret_cast<setter>(AppWindowTitleBar_put_ButtonHoverBackgroundColor), nullptr, nullptr }, { "button_foreground_color", reinterpret_cast<getter>(AppWindowTitleBar_get_ButtonForegroundColor), reinterpret_cast<setter>(AppWindowTitleBar_put_ButtonForegroundColor), nullptr, nullptr }, { "button_background_color", reinterpret_cast<getter>(AppWindowTitleBar_get_ButtonBackgroundColor), reinterpret_cast<setter>(AppWindowTitleBar_put_ButtonBackgroundColor), nullptr, nullptr }, { "background_color", reinterpret_cast<getter>(AppWindowTitleBar_get_BackgroundColor), reinterpret_cast<setter>(AppWindowTitleBar_put_BackgroundColor), nullptr, nullptr }, { "is_visible", reinterpret_cast<getter>(AppWindowTitleBar_get_IsVisible), nullptr, nullptr, nullptr }, { } }; static PyType_Slot _type_slots_AppWindowTitleBar[] = { { Py_tp_new, _new_AppWindowTitleBar }, { Py_tp_dealloc, _dealloc_AppWindowTitleBar }, { Py_tp_methods, _methods_AppWindowTitleBar }, { Py_tp_getset, _getset_AppWindowTitleBar }, { }, }; static PyType_Spec _type_spec_AppWindowTitleBar = { "_winsdk_Windows_UI_WindowManagement.AppWindowTitleBar", sizeof(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBar), 0, Py_TPFLAGS_DEFAULT, _type_slots_AppWindowTitleBar }; // ----- AppWindowTitleBarOcclusion class -------------------- constexpr const char* const _type_name_AppWindowTitleBarOcclusion = "AppWindowTitleBarOcclusion"; static PyObject* _new_AppWindowTitleBarOcclusion(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { py::set_invalid_activation_error(_type_name_AppWindowTitleBarOcclusion); return nullptr; } static void _dealloc_AppWindowTitleBarOcclusion(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBarOcclusion* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* AppWindowTitleBarOcclusion_get_OccludingRect(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBarOcclusion* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.OccludingRect()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* _from_AppWindowTitleBarOcclusion(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::UI::WindowManagement::AppWindowTitleBarOcclusion>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_AppWindowTitleBarOcclusion[] = { { "_from", reinterpret_cast<PyCFunction>(_from_AppWindowTitleBarOcclusion), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_AppWindowTitleBarOcclusion[] = { { "occluding_rect", reinterpret_cast<getter>(AppWindowTitleBarOcclusion_get_OccludingRect), nullptr, nullptr, nullptr }, { } }; static PyType_Slot _type_slots_AppWindowTitleBarOcclusion[] = { { Py_tp_new, _new_AppWindowTitleBarOcclusion }, { Py_tp_dealloc, _dealloc_AppWindowTitleBarOcclusion }, { Py_tp_methods, _methods_AppWindowTitleBarOcclusion }, { Py_tp_getset, _getset_AppWindowTitleBarOcclusion }, { }, }; static PyType_Spec _type_spec_AppWindowTitleBarOcclusion = { "_winsdk_Windows_UI_WindowManagement.AppWindowTitleBarOcclusion", sizeof(py::wrapper::Windows::UI::WindowManagement::AppWindowTitleBarOcclusion), 0, Py_TPFLAGS_DEFAULT, _type_slots_AppWindowTitleBarOcclusion }; // ----- CompactOverlayPresentationConfiguration class -------------------- constexpr const char* const _type_name_CompactOverlayPresentationConfiguration = "CompactOverlayPresentationConfiguration"; static PyObject* _new_CompactOverlayPresentationConfiguration(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { if (kwds != nullptr) { py::set_invalid_kwd_args_error(); return nullptr; } Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { winrt::Windows::UI::WindowManagement::CompactOverlayPresentationConfiguration instance{ }; return py::wrap(instance, type); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static void _dealloc_CompactOverlayPresentationConfiguration(py::wrapper::Windows::UI::WindowManagement::CompactOverlayPresentationConfiguration* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* _from_CompactOverlayPresentationConfiguration(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::UI::WindowManagement::CompactOverlayPresentationConfiguration>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_CompactOverlayPresentationConfiguration[] = { { "_from", reinterpret_cast<PyCFunction>(_from_CompactOverlayPresentationConfiguration), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_CompactOverlayPresentationConfiguration[] = { { } }; static PyType_Slot _type_slots_CompactOverlayPresentationConfiguration[] = { { Py_tp_new, _new_CompactOverlayPresentationConfiguration }, { Py_tp_dealloc, _dealloc_CompactOverlayPresentationConfiguration }, { Py_tp_methods, _methods_CompactOverlayPresentationConfiguration }, { Py_tp_getset, _getset_CompactOverlayPresentationConfiguration }, { }, }; static PyType_Spec _type_spec_CompactOverlayPresentationConfiguration = { "_winsdk_Windows_UI_WindowManagement.CompactOverlayPresentationConfiguration", sizeof(py::wrapper::Windows::UI::WindowManagement::CompactOverlayPresentationConfiguration), 0, Py_TPFLAGS_DEFAULT, _type_slots_CompactOverlayPresentationConfiguration }; // ----- DefaultPresentationConfiguration class -------------------- constexpr const char* const _type_name_DefaultPresentationConfiguration = "DefaultPresentationConfiguration"; static PyObject* _new_DefaultPresentationConfiguration(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { if (kwds != nullptr) { py::set_invalid_kwd_args_error(); return nullptr; } Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { winrt::Windows::UI::WindowManagement::DefaultPresentationConfiguration instance{ }; return py::wrap(instance, type); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static void _dealloc_DefaultPresentationConfiguration(py::wrapper::Windows::UI::WindowManagement::DefaultPresentationConfiguration* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* _from_DefaultPresentationConfiguration(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::UI::WindowManagement::DefaultPresentationConfiguration>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_DefaultPresentationConfiguration[] = { { "_from", reinterpret_cast<PyCFunction>(_from_DefaultPresentationConfiguration), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_DefaultPresentationConfiguration[] = { { } }; static PyType_Slot _type_slots_DefaultPresentationConfiguration[] = { { Py_tp_new, _new_DefaultPresentationConfiguration }, { Py_tp_dealloc, _dealloc_DefaultPresentationConfiguration }, { Py_tp_methods, _methods_DefaultPresentationConfiguration }, { Py_tp_getset, _getset_DefaultPresentationConfiguration }, { }, }; static PyType_Spec _type_spec_DefaultPresentationConfiguration = { "_winsdk_Windows_UI_WindowManagement.DefaultPresentationConfiguration", sizeof(py::wrapper::Windows::UI::WindowManagement::DefaultPresentationConfiguration), 0, Py_TPFLAGS_DEFAULT, _type_slots_DefaultPresentationConfiguration }; // ----- DisplayRegion class -------------------- constexpr const char* const _type_name_DisplayRegion = "DisplayRegion"; static PyObject* _new_DisplayRegion(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { py::set_invalid_activation_error(_type_name_DisplayRegion); return nullptr; } static void _dealloc_DisplayRegion(py::wrapper::Windows::UI::WindowManagement::DisplayRegion* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* DisplayRegion_get_DisplayMonitorDeviceId(py::wrapper::Windows::UI::WindowManagement::DisplayRegion* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.DisplayMonitorDeviceId()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* DisplayRegion_get_IsVisible(py::wrapper::Windows::UI::WindowManagement::DisplayRegion* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.IsVisible()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* DisplayRegion_get_WindowingEnvironment(py::wrapper::Windows::UI::WindowManagement::DisplayRegion* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.WindowingEnvironment()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* DisplayRegion_get_WorkAreaOffset(py::wrapper::Windows::UI::WindowManagement::DisplayRegion* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.WorkAreaOffset()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* DisplayRegion_get_WorkAreaSize(py::wrapper::Windows::UI::WindowManagement::DisplayRegion* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.WorkAreaSize()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* DisplayRegion_add_Changed(py::wrapper::Windows::UI::WindowManagement::DisplayRegion* self, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::UI::WindowManagement::DisplayRegion, winrt::Windows::Foundation::IInspectable>>(arg); return py::convert(self->obj.Changed(param0)); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* DisplayRegion_remove_Changed(py::wrapper::Windows::UI::WindowManagement::DisplayRegion* self, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::event_token>(arg); self->obj.Changed(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* _from_DisplayRegion(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::UI::WindowManagement::DisplayRegion>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_DisplayRegion[] = { { "add_changed", reinterpret_cast<PyCFunction>(DisplayRegion_add_Changed), METH_O, nullptr }, { "remove_changed", reinterpret_cast<PyCFunction>(DisplayRegion_remove_Changed), METH_O, nullptr }, { "_from", reinterpret_cast<PyCFunction>(_from_DisplayRegion), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_DisplayRegion[] = { { "display_monitor_device_id", reinterpret_cast<getter>(DisplayRegion_get_DisplayMonitorDeviceId), nullptr, nullptr, nullptr }, { "is_visible", reinterpret_cast<getter>(DisplayRegion_get_IsVisible), nullptr, nullptr, nullptr }, { "windowing_environment", reinterpret_cast<getter>(DisplayRegion_get_WindowingEnvironment), nullptr, nullptr, nullptr }, { "work_area_offset", reinterpret_cast<getter>(DisplayRegion_get_WorkAreaOffset), nullptr, nullptr, nullptr }, { "work_area_size", reinterpret_cast<getter>(DisplayRegion_get_WorkAreaSize), nullptr, nullptr, nullptr }, { } }; static PyType_Slot _type_slots_DisplayRegion[] = { { Py_tp_new, _new_DisplayRegion }, { Py_tp_dealloc, _dealloc_DisplayRegion }, { Py_tp_methods, _methods_DisplayRegion }, { Py_tp_getset, _getset_DisplayRegion }, { }, }; static PyType_Spec _type_spec_DisplayRegion = { "_winsdk_Windows_UI_WindowManagement.DisplayRegion", sizeof(py::wrapper::Windows::UI::WindowManagement::DisplayRegion), 0, Py_TPFLAGS_DEFAULT, _type_slots_DisplayRegion }; // ----- FullScreenPresentationConfiguration class -------------------- constexpr const char* const _type_name_FullScreenPresentationConfiguration = "FullScreenPresentationConfiguration"; static PyObject* _new_FullScreenPresentationConfiguration(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { if (kwds != nullptr) { py::set_invalid_kwd_args_error(); return nullptr; } Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { winrt::Windows::UI::WindowManagement::FullScreenPresentationConfiguration instance{ }; return py::wrap(instance, type); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static void _dealloc_FullScreenPresentationConfiguration(py::wrapper::Windows::UI::WindowManagement::FullScreenPresentationConfiguration* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* FullScreenPresentationConfiguration_get_IsExclusive(py::wrapper::Windows::UI::WindowManagement::FullScreenPresentationConfiguration* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.IsExclusive()); } catch (...) { py::to_PyErr(); return nullptr; } } static int FullScreenPresentationConfiguration_put_IsExclusive(py::wrapper::Windows::UI::WindowManagement::FullScreenPresentationConfiguration* self, PyObject* arg, void* /*unused*/) noexcept { if (arg == nullptr) { PyErr_SetString(PyExc_TypeError, "property delete not supported"); return -1; } try { auto param0 = py::convert_to<bool>(arg); self->obj.IsExclusive(param0); return 0; } catch (...) { py::to_PyErr(); return -1; } } static PyObject* _from_FullScreenPresentationConfiguration(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::UI::WindowManagement::FullScreenPresentationConfiguration>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_FullScreenPresentationConfiguration[] = { { "_from", reinterpret_cast<PyCFunction>(_from_FullScreenPresentationConfiguration), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_FullScreenPresentationConfiguration[] = { { "is_exclusive", reinterpret_cast<getter>(FullScreenPresentationConfiguration_get_IsExclusive), reinterpret_cast<setter>(FullScreenPresentationConfiguration_put_IsExclusive), nullptr, nullptr }, { } }; static PyType_Slot _type_slots_FullScreenPresentationConfiguration[] = { { Py_tp_new, _new_FullScreenPresentationConfiguration }, { Py_tp_dealloc, _dealloc_FullScreenPresentationConfiguration }, { Py_tp_methods, _methods_FullScreenPresentationConfiguration }, { Py_tp_getset, _getset_FullScreenPresentationConfiguration }, { }, }; static PyType_Spec _type_spec_FullScreenPresentationConfiguration = { "_winsdk_Windows_UI_WindowManagement.FullScreenPresentationConfiguration", sizeof(py::wrapper::Windows::UI::WindowManagement::FullScreenPresentationConfiguration), 0, Py_TPFLAGS_DEFAULT, _type_slots_FullScreenPresentationConfiguration }; // ----- WindowServices class -------------------- constexpr const char* const _type_name_WindowServices = "WindowServices"; static PyObject* _new_WindowServices(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { py::set_invalid_activation_error(_type_name_WindowServices); return nullptr; } static PyObject* WindowServices_FindAllTopLevelWindowIds(PyObject* /*unused*/, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { return py::convert(winrt::Windows::UI::WindowManagement::WindowServices::FindAllTopLevelWindowIds()); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyMethodDef _methods_WindowServices[] = { { "find_all_top_level_window_ids", reinterpret_cast<PyCFunction>(WindowServices_FindAllTopLevelWindowIds), METH_VARARGS | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_WindowServices[] = { { } }; static PyType_Slot _type_slots_WindowServices[] = { { Py_tp_new, _new_WindowServices }, { Py_tp_methods, _methods_WindowServices }, { Py_tp_getset, _getset_WindowServices }, { }, }; static PyType_Spec _type_spec_WindowServices = { "_winsdk_Windows_UI_WindowManagement.WindowServices", 0, 0, Py_TPFLAGS_DEFAULT, _type_slots_WindowServices }; // ----- WindowingEnvironment class -------------------- constexpr const char* const _type_name_WindowingEnvironment = "WindowingEnvironment"; static PyObject* _new_WindowingEnvironment(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { py::set_invalid_activation_error(_type_name_WindowingEnvironment); return nullptr; } static void _dealloc_WindowingEnvironment(py::wrapper::Windows::UI::WindowManagement::WindowingEnvironment* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* WindowingEnvironment_FindAll(PyObject* /*unused*/, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { return py::convert(winrt::Windows::UI::WindowManagement::WindowingEnvironment::FindAll()); } catch (...) { py::to_PyErr(); return nullptr; } } else if (arg_count == 1) { try { auto param0 = py::convert_to<winrt::Windows::UI::WindowManagement::WindowingEnvironmentKind>(args, 0); return py::convert(winrt::Windows::UI::WindowManagement::WindowingEnvironment::FindAll(param0)); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* WindowingEnvironment_GetDisplayRegions(py::wrapper::Windows::UI::WindowManagement::WindowingEnvironment* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { return py::convert(self->obj.GetDisplayRegions()); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* WindowingEnvironment_get_IsEnabled(py::wrapper::Windows::UI::WindowManagement::WindowingEnvironment* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.IsEnabled()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* WindowingEnvironment_get_Kind(py::wrapper::Windows::UI::WindowManagement::WindowingEnvironment* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.Kind()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* WindowingEnvironment_add_Changed(py::wrapper::Windows::UI::WindowManagement::WindowingEnvironment* self, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::UI::WindowManagement::WindowingEnvironment, winrt::Windows::UI::WindowManagement::WindowingEnvironmentChangedEventArgs>>(arg); return py::convert(self->obj.Changed(param0)); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* WindowingEnvironment_remove_Changed(py::wrapper::Windows::UI::WindowManagement::WindowingEnvironment* self, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::event_token>(arg); self->obj.Changed(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* _from_WindowingEnvironment(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::UI::WindowManagement::WindowingEnvironment>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_WindowingEnvironment[] = { { "find_all", reinterpret_cast<PyCFunction>(WindowingEnvironment_FindAll), METH_VARARGS | METH_STATIC, nullptr }, { "get_display_regions", reinterpret_cast<PyCFunction>(WindowingEnvironment_GetDisplayRegions), METH_VARARGS, nullptr }, { "add_changed", reinterpret_cast<PyCFunction>(WindowingEnvironment_add_Changed), METH_O, nullptr }, { "remove_changed", reinterpret_cast<PyCFunction>(WindowingEnvironment_remove_Changed), METH_O, nullptr }, { "_from", reinterpret_cast<PyCFunction>(_from_WindowingEnvironment), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_WindowingEnvironment[] = { { "is_enabled", reinterpret_cast<getter>(WindowingEnvironment_get_IsEnabled), nullptr, nullptr, nullptr }, { "kind", reinterpret_cast<getter>(WindowingEnvironment_get_Kind), nullptr, nullptr, nullptr }, { } }; static PyType_Slot _type_slots_WindowingEnvironment[] = { { Py_tp_new, _new_WindowingEnvironment }, { Py_tp_dealloc, _dealloc_WindowingEnvironment }, { Py_tp_methods, _methods_WindowingEnvironment }, { Py_tp_getset, _getset_WindowingEnvironment }, { }, }; static PyType_Spec _type_spec_WindowingEnvironment = { "_winsdk_Windows_UI_WindowManagement.WindowingEnvironment", sizeof(py::wrapper::Windows::UI::WindowManagement::WindowingEnvironment), 0, Py_TPFLAGS_DEFAULT, _type_slots_WindowingEnvironment }; // ----- WindowingEnvironmentAddedEventArgs class -------------------- constexpr const char* const _type_name_WindowingEnvironmentAddedEventArgs = "WindowingEnvironmentAddedEventArgs"; static PyObject* _new_WindowingEnvironmentAddedEventArgs(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { py::set_invalid_activation_error(_type_name_WindowingEnvironmentAddedEventArgs); return nullptr; } static void _dealloc_WindowingEnvironmentAddedEventArgs(py::wrapper::Windows::UI::WindowManagement::WindowingEnvironmentAddedEventArgs* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* WindowingEnvironmentAddedEventArgs_get_WindowingEnvironment(py::wrapper::Windows::UI::WindowManagement::WindowingEnvironmentAddedEventArgs* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.WindowingEnvironment()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* _from_WindowingEnvironmentAddedEventArgs(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::UI::WindowManagement::WindowingEnvironmentAddedEventArgs>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_WindowingEnvironmentAddedEventArgs[] = { { "_from", reinterpret_cast<PyCFunction>(_from_WindowingEnvironmentAddedEventArgs), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_WindowingEnvironmentAddedEventArgs[] = { { "windowing_environment", reinterpret_cast<getter>(WindowingEnvironmentAddedEventArgs_get_WindowingEnvironment), nullptr, nullptr, nullptr }, { } }; static PyType_Slot _type_slots_WindowingEnvironmentAddedEventArgs[] = { { Py_tp_new, _new_WindowingEnvironmentAddedEventArgs }, { Py_tp_dealloc, _dealloc_WindowingEnvironmentAddedEventArgs }, { Py_tp_methods, _methods_WindowingEnvironmentAddedEventArgs }, { Py_tp_getset, _getset_WindowingEnvironmentAddedEventArgs }, { }, }; static PyType_Spec _type_spec_WindowingEnvironmentAddedEventArgs = { "_winsdk_Windows_UI_WindowManagement.WindowingEnvironmentAddedEventArgs", sizeof(py::wrapper::Windows::UI::WindowManagement::WindowingEnvironmentAddedEventArgs), 0, Py_TPFLAGS_DEFAULT, _type_slots_WindowingEnvironmentAddedEventArgs }; // ----- WindowingEnvironmentChangedEventArgs class -------------------- constexpr const char* const _type_name_WindowingEnvironmentChangedEventArgs = "WindowingEnvironmentChangedEventArgs"; static PyObject* _new_WindowingEnvironmentChangedEventArgs(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { py::set_invalid_activation_error(_type_name_WindowingEnvironmentChangedEventArgs); return nullptr; } static void _dealloc_WindowingEnvironmentChangedEventArgs(py::wrapper::Windows::UI::WindowManagement::WindowingEnvironmentChangedEventArgs* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* _from_WindowingEnvironmentChangedEventArgs(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::UI::WindowManagement::WindowingEnvironmentChangedEventArgs>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_WindowingEnvironmentChangedEventArgs[] = { { "_from", reinterpret_cast<PyCFunction>(_from_WindowingEnvironmentChangedEventArgs), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_WindowingEnvironmentChangedEventArgs[] = { { } }; static PyType_Slot _type_slots_WindowingEnvironmentChangedEventArgs[] = { { Py_tp_new, _new_WindowingEnvironmentChangedEventArgs }, { Py_tp_dealloc, _dealloc_WindowingEnvironmentChangedEventArgs }, { Py_tp_methods, _methods_WindowingEnvironmentChangedEventArgs }, { Py_tp_getset, _getset_WindowingEnvironmentChangedEventArgs }, { }, }; static PyType_Spec _type_spec_WindowingEnvironmentChangedEventArgs = { "_winsdk_Windows_UI_WindowManagement.WindowingEnvironmentChangedEventArgs", sizeof(py::wrapper::Windows::UI::WindowManagement::WindowingEnvironmentChangedEventArgs), 0, Py_TPFLAGS_DEFAULT, _type_slots_WindowingEnvironmentChangedEventArgs }; // ----- WindowingEnvironmentRemovedEventArgs class -------------------- constexpr const char* const _type_name_WindowingEnvironmentRemovedEventArgs = "WindowingEnvironmentRemovedEventArgs"; static PyObject* _new_WindowingEnvironmentRemovedEventArgs(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { py::set_invalid_activation_error(_type_name_WindowingEnvironmentRemovedEventArgs); return nullptr; } static void _dealloc_WindowingEnvironmentRemovedEventArgs(py::wrapper::Windows::UI::WindowManagement::WindowingEnvironmentRemovedEventArgs* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* WindowingEnvironmentRemovedEventArgs_get_WindowingEnvironment(py::wrapper::Windows::UI::WindowManagement::WindowingEnvironmentRemovedEventArgs* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.WindowingEnvironment()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* _from_WindowingEnvironmentRemovedEventArgs(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::UI::WindowManagement::WindowingEnvironmentRemovedEventArgs>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_WindowingEnvironmentRemovedEventArgs[] = { { "_from", reinterpret_cast<PyCFunction>(_from_WindowingEnvironmentRemovedEventArgs), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_WindowingEnvironmentRemovedEventArgs[] = { { "windowing_environment", reinterpret_cast<getter>(WindowingEnvironmentRemovedEventArgs_get_WindowingEnvironment), nullptr, nullptr, nullptr }, { } }; static PyType_Slot _type_slots_WindowingEnvironmentRemovedEventArgs[] = { { Py_tp_new, _new_WindowingEnvironmentRemovedEventArgs }, { Py_tp_dealloc, _dealloc_WindowingEnvironmentRemovedEventArgs }, { Py_tp_methods, _methods_WindowingEnvironmentRemovedEventArgs }, { Py_tp_getset, _getset_WindowingEnvironmentRemovedEventArgs }, { }, }; static PyType_Spec _type_spec_WindowingEnvironmentRemovedEventArgs = { "_winsdk_Windows_UI_WindowManagement.WindowingEnvironmentRemovedEventArgs", sizeof(py::wrapper::Windows::UI::WindowManagement::WindowingEnvironmentRemovedEventArgs), 0, Py_TPFLAGS_DEFAULT, _type_slots_WindowingEnvironmentRemovedEventArgs }; // ----- Windows.UI.WindowManagement Initialization -------------------- static int module_exec(PyObject* module) noexcept { try { py::pyobj_handle bases { PyTuple_Pack(1, py::winrt_type<py::Object>::python_type) }; py::winrt_type<winrt::Windows::UI::WindowManagement::AppWindow>::python_type = py::register_python_type(module, _type_name_AppWindow, &_type_spec_AppWindow, bases.get()); py::winrt_type<winrt::Windows::UI::WindowManagement::AppWindowChangedEventArgs>::python_type = py::register_python_type(module, _type_name_AppWindowChangedEventArgs, &_type_spec_AppWindowChangedEventArgs, bases.get()); py::winrt_type<winrt::Windows::UI::WindowManagement::AppWindowCloseRequestedEventArgs>::python_type = py::register_python_type(module, _type_name_AppWindowCloseRequestedEventArgs, &_type_spec_AppWindowCloseRequestedEventArgs, bases.get()); py::winrt_type<winrt::Windows::UI::WindowManagement::AppWindowClosedEventArgs>::python_type = py::register_python_type(module, _type_name_AppWindowClosedEventArgs, &_type_spec_AppWindowClosedEventArgs, bases.get()); py::winrt_type<winrt::Windows::UI::WindowManagement::AppWindowFrame>::python_type = py::register_python_type(module, _type_name_AppWindowFrame, &_type_spec_AppWindowFrame, bases.get()); py::winrt_type<winrt::Windows::UI::WindowManagement::AppWindowPlacement>::python_type = py::register_python_type(module, _type_name_AppWindowPlacement, &_type_spec_AppWindowPlacement, bases.get()); py::winrt_type<winrt::Windows::UI::WindowManagement::AppWindowPresentationConfiguration>::python_type = py::register_python_type(module, _type_name_AppWindowPresentationConfiguration, &_type_spec_AppWindowPresentationConfiguration, bases.get()); py::winrt_type<winrt::Windows::UI::WindowManagement::AppWindowPresenter>::python_type = py::register_python_type(module, _type_name_AppWindowPresenter, &_type_spec_AppWindowPresenter, bases.get()); py::winrt_type<winrt::Windows::UI::WindowManagement::AppWindowTitleBar>::python_type = py::register_python_type(module, _type_name_AppWindowTitleBar, &_type_spec_AppWindowTitleBar, bases.get()); py::winrt_type<winrt::Windows::UI::WindowManagement::AppWindowTitleBarOcclusion>::python_type = py::register_python_type(module, _type_name_AppWindowTitleBarOcclusion, &_type_spec_AppWindowTitleBarOcclusion, bases.get()); py::winrt_type<winrt::Windows::UI::WindowManagement::CompactOverlayPresentationConfiguration>::python_type = py::register_python_type(module, _type_name_CompactOverlayPresentationConfiguration, &_type_spec_CompactOverlayPresentationConfiguration, bases.get()); py::winrt_type<winrt::Windows::UI::WindowManagement::DefaultPresentationConfiguration>::python_type = py::register_python_type(module, _type_name_DefaultPresentationConfiguration, &_type_spec_DefaultPresentationConfiguration, bases.get()); py::winrt_type<winrt::Windows::UI::WindowManagement::DisplayRegion>::python_type = py::register_python_type(module, _type_name_DisplayRegion, &_type_spec_DisplayRegion, bases.get()); py::winrt_type<winrt::Windows::UI::WindowManagement::FullScreenPresentationConfiguration>::python_type = py::register_python_type(module, _type_name_FullScreenPresentationConfiguration, &_type_spec_FullScreenPresentationConfiguration, bases.get()); py::winrt_type<winrt::Windows::UI::WindowManagement::WindowServices>::python_type = py::register_python_type(module, _type_name_WindowServices, &_type_spec_WindowServices, nullptr); py::winrt_type<winrt::Windows::UI::WindowManagement::WindowingEnvironment>::python_type = py::register_python_type(module, _type_name_WindowingEnvironment, &_type_spec_WindowingEnvironment, bases.get()); py::winrt_type<winrt::Windows::UI::WindowManagement::WindowingEnvironmentAddedEventArgs>::python_type = py::register_python_type(module, _type_name_WindowingEnvironmentAddedEventArgs, &_type_spec_WindowingEnvironmentAddedEventArgs, bases.get()); py::winrt_type<winrt::Windows::UI::WindowManagement::WindowingEnvironmentChangedEventArgs>::python_type = py::register_python_type(module, _type_name_WindowingEnvironmentChangedEventArgs, &_type_spec_WindowingEnvironmentChangedEventArgs, bases.get()); py::winrt_type<winrt::Windows::UI::WindowManagement::WindowingEnvironmentRemovedEventArgs>::python_type = py::register_python_type(module, _type_name_WindowingEnvironmentRemovedEventArgs, &_type_spec_WindowingEnvironmentRemovedEventArgs, bases.get()); return 0; } catch (...) { py::to_PyErr(); return -1; } } static PyModuleDef_Slot module_slots[] = {{Py_mod_exec, module_exec}, {}}; PyDoc_STRVAR(module_doc, "Windows.UI.WindowManagement"); static PyModuleDef module_def = {PyModuleDef_HEAD_INIT, "_winsdk_Windows_UI_WindowManagement", module_doc, 0, nullptr, module_slots, nullptr, nullptr, nullptr}; } // py::cpp::Windows::UI::WindowManagement PyMODINIT_FUNC PyInit__winsdk_Windows_UI_WindowManagement (void) noexcept { return PyModuleDef_Init(&py::cpp::Windows::UI::WindowManagement::module_def); }
35.709853
272
0.623655
[ "object" ]
4f6325cd39dd8bc59822714778f2f5aad6218bb9
3,386
cpp
C++
WholesomeEngine/WholesomeEngine/VulkanInstance.cpp
HeladodePistacho/WholesomeEngine
e85b512f749d2f506cf5eb5603d2791e3221ccd5
[ "MIT" ]
null
null
null
WholesomeEngine/WholesomeEngine/VulkanInstance.cpp
HeladodePistacho/WholesomeEngine
e85b512f749d2f506cf5eb5603d2791e3221ccd5
[ "MIT" ]
null
null
null
WholesomeEngine/WholesomeEngine/VulkanInstance.cpp
HeladodePistacho/WholesomeEngine
e85b512f749d2f506cf5eb5603d2791e3221ccd5
[ "MIT" ]
null
null
null
#include "VulkanInstance.h" #include "SDL2/SDL_vulkan.h" VulkanInstance::VulkanInstance() : instance(std::make_unique<VkInstance>()), current_gpu(VK_NULL_HANDLE) { } VkResult VulkanInstance::CreateInstance(const SDL_Window* window) { VkApplicationInfo application_info{ VkStructureType::VK_STRUCTURE_TYPE_APPLICATION_INFO, //StructureType nullptr, //Next pointer "Wholesome Engine", //Application Name VK_MAKE_VERSION(0, 0, 1), //Application Version "Wholesome Engine", //Engine Name VK_MAKE_VERSION(0, 0, 1), //Engine Version VK_API_VERSION_1_2 //Vulkan Api Version }; const char* extensions[1] = { "VK_KHR_win32_surface" }; uint32 num_extensions; SDL_Vulkan_GetInstanceExtensions(const_cast<SDL_Window*>(window), &num_extensions, nullptr); std::vector<const char*> sdl_extensions{ num_extensions }; SDL_Vulkan_GetInstanceExtensions(const_cast<SDL_Window*>(window), &num_extensions, sdl_extensions.data()); VkInstanceCreateInfo instance_info{ VkStructureType::VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, //StructureType nullptr, //Next pointer 0, //Flags &application_info, //Application info pointer 0, //Layer Count ] nullptr, //Layer Names ]---->Not using Layers nor extensions de momento num_extensions, //Extension Count ] sdl_extensions.data() //Extension Names ] }; auto result = vkCreateInstance(&instance_info, nullptr, instance.get()); return result; } void VulkanInstance::DestroyInstance() { if (instance != nullptr) { DEBUG::LOG("DESTROYING Instance ", nullptr); vkDestroyInstance(*instance, nullptr); instance.reset(nullptr); } else DEBUG::LOG("[ERROR] Instance was Nullptr ", nullptr); } VkInstance VulkanInstance::GetInstance() const { return (*instance); } VkResult VulkanInstance::SelectPhysicalDevice(VkSurfaceKHR surface) { VkResult ret{ VkResult::VK_SUCCESS }; for (auto& device : gpus) { device.InitDevice(surface); if (device.IsValid()) { current_gpu = device; DEBUG::LOG("Using GPU: ", nullptr); current_gpu.PrintInformation(); break; } } return ret; } VkResult VulkanInstance::GetPhysicalDevices() { uint32 device_count = 0; VkResult ret = VkResult::VK_SUCCESS; //Get Num of Devices ret = vkEnumeratePhysicalDevices(*instance, &device_count, nullptr); if (device_count == 0) { DEBUG::LOG("[ERROR] NO DEVICE FOUNDED", nullptr); ret = VkResult::VK_ERROR_UNKNOWN; return ret; } if (ret != VkResult::VK_SUCCESS) { DEBUG::LOG("[ERROR] ENUMERATE PHYSICAL DEVICES ERROR", nullptr); return ret; } std::vector<VkPhysicalDevice> devices(device_count); //Fill the Vector with all the devices ret = vkEnumeratePhysicalDevices(*instance, &device_count, devices.data()); DEBUG::LOG("Num Devices: %", device_count); //Look for the most apropiate device //By now It Will be the first one finded for (const auto& device : devices) { gpus.push_back(device); } return ret; } void VulkanInstance::PrintDeviceInformation(uint8 index) const { if (index >= gpus.size()) { DEBUG::LOG("[ERROR] Device index out of range", nullptr); return; } gpus[index].PrintInformation(); } const VulkanPhysicalDevice& VulkanInstance::GetPhysicalDevice() const { return current_gpu; }
25.458647
108
0.697874
[ "vector" ]
4f65f8f95bd09c440ea8e11aeedcf5fce339a878
7,031
cpp
C++
Table.cpp
PengaloGit/connect-four-cpp
ba6324ef349ef0ea5a7b0a689ec4975e6f899ced
[ "MIT" ]
3
2020-01-24T01:48:50.000Z
2020-04-06T23:57:16.000Z
Table.cpp
PengaloGit/connect-four-cpp
ba6324ef349ef0ea5a7b0a689ec4975e6f899ced
[ "MIT" ]
null
null
null
Table.cpp
PengaloGit/connect-four-cpp
ba6324ef349ef0ea5a7b0a689ec4975e6f899ced
[ "MIT" ]
null
null
null
/* * Connect Four * MIT License, Copyright 2018 Loukmane Maada, Soukaina Moumou & Anas Limouri */ #include "Table.h" Table::Table() { for (int i = 0; i < 6; i++) { for (int j = 0; j < 7; j++) { t[i][j] = 0; } } poids = 0; } void Table::placerPion(int pion, int colonne) { int ligne = 0; while (t[ligne+1][colonne] == 0 && ligne < 5) { ligne += 1; } t[ligne][colonne] = pion; } bool Table::colonneVide(int colonne) { return t[0][colonne] == 0; } void Table::setPoids(int pds) { poids = pds; } int Table::getPoids() { return poids; } bool Table::verifierGagnant(int& gagnant) { for (int i = 0; i < 6; i++) { for (int j = 0; j < 4; j++) { if (t[i][j] == t[i][j+1] && t[i][j] == t[i][j+2] && t[i][j] == t[i][j+3] && t[i][j] != 0) { gagnant = t[i][j]; return true; } } } for (int i = 3; i < 6; i++) { for (int j = 0; j < 7; j++) { if (t[i][j] == t[i-1][j] && t[i][j] == t[i-2][j] && t[i][j] == t[i-3][j] && t[i][j] != 0) { gagnant = t[i][j]; return true; } } } for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { if (t[i][j] == t[i+1][j+1] && t[i][j] == t[i+2][j+2] && t[i][j] == t[i+3][j+3] && t[i][j] != 0) { gagnant = t[i][j]; return true; } } } for (int i = 0; i < 6; i++) { for (int j = 0; j < 7; j++) { if (i-3 >= 0 && j+3 < 7) { if (t[i][j] == t[i-1][j+1] && t[i][j] == t[i-2][j+2] && t[i][j] == t[i-3][j+3] && t[i][j] != 0) { gagnant = t[i][j]; return true; } } } } return false; } int Table::getT(int x, int y) { return t[x][y]; } void Table::setT(int x, int y, int val) { t[x][y] = val; } vector <Table> Table::genereSuccesseurs(int pion) { vector <Table> successeurs; Table temp=*this; for(int i = 0; i < 7; i++) { if(colonneVide(i)) { temp.placerPion(pion, i); successeurs.push_back(temp); } temp=*this; } return successeurs; } void Table::colorierGagnant() { for (int i = 0; i < 6; i++) { for ( int j = 0; j < 4; j++) { if (t[i][j] == t[i][j+1] && t[i][j] == t[i][j+2] && t[i][j] == t[i][j+3] && t[i][j] != 0) { t[i][j] = t[i][j+1] = t[i][j+2] = t[i][j+3] = 3; } } } for (int i = 3; i < 6; i++) { for (int j = 0; j < 7; j++) { if (t[i][j] == t[i-1][j] && t[i][j] == t[i-2][j] && t[i][j] == t[i-3][j] && t[i][j] != 0) { t[i][j] = t[i-1][j] = t[i-2][j] = t[i-3][j] = 3; } } } for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { if (t[i][j] == t[i+1][j+1] && t[i][j] == t[i+2][j+2] && t[i][j] == t[i+3][j+3] && t[i][j] != 0) { t[i][j] = t[i+1][j+1] = t[i+2][j+2] = t[i+3][j+3] = 3; } } } for (int i = 0; i < 6; i++) { for (int j = 0; j < 7; j++) { if (i-3 >= 0 && j+3 < 7) { if (t[i][j] == t[i-1][j+1] && t[i][j] == t[i-2][j+2] && t[i][j] == t[i-3][j+3] && t[i][j] != 0) { t[i][j] = t[i-1][j+1] = t[i-2][j+2] = t[i-3][j+3] = 3; } } } } } int Table::nbrDe3DeSuite(int pion) { int repeated = 0; for (int i = 0; i < 6; i++) { for ( int j = 0; j < 5; j++) { if (t[i][j] == t[i][j+1] && t[i][j] == t[i][j+2] && t[i][j] == pion) { repeated++; } } } for (int i = 2; i < 6; i++) { for (int j = 0; j < 7; j++) { if (t[i][j] == t[i-1][j] && t[i][j] == t[i-2][j] && t[i][j] == pion) { repeated++; } } } for (int i = 0; i < 4; i++) { for (int j = 0; j < 5; j++) { if (t[i][j] == t[i+1][j+1] && t[i][j] == t[i+2][j+2] && t[i][j] == pion) { repeated++; } } } for (int i = 0; i < 6; i++) { for (int j = 0; j < 7; j++) { if (i-2 >= 0 && j+2 < 7) { if (t[i][j] == t[i-1][j+1] && t[i][j] == t[i-2][j+2] && t[i][j] == pion) { repeated++; } } } } return repeated; } int Table::nbrDe2DeSuite(int pion) { int repeated = 0; for (int i = 0; i < 6; i++) { for ( int j = 0; j < 6; j++) { if (t[i][j] == t[i][j+1] && t[i][j] == pion) { repeated++; } } } for (int i = 1; i < 6; i++) { for (int j = 0; j < 7; j++) { if (t[i][j] == t[i-1][j] && t[i][j] == pion) { repeated++; } } } for (int i = 0; i < 5; i++) { for (int j = 0; j < 6; j++) { if (t[i][j] == t[i+1][j+1] && t[i][j] == pion) { repeated++; } } } for (int i=0; i<6; i++) { for (int j=0; j<7; j++) { if (i-1 >= 0 && j+1 < 7) { if (t[i][j] == t[i-1][j+1] && t[i][j] == pion) { repeated++; } } } } return repeated; } int Table::fonctionHeuristique() { int joueur1 = 0, joueur2 = 0; joueur1 = joueur1 + nbrDe3DeSuite(1)*30 + nbrDe2DeSuite(1)*2; joueur2 = joueur2 + nbrDe3DeSuite(2)*30 + nbrDe2DeSuite(2)*2; return joueur2 - joueur1; } int Table::utilite() { int gagnant; if(verifierGagnant(gagnant)) { if(gagnant == 1) { return -400; } if(gagnant == 2) { return +400; } } return 0; } Table Table::minTable(Table tab) { if(poids < tab.poids) { return *this; } else return tab; } Table Table::maxTable(Table tab) { if(poids > tab.poids) return *this; else return tab; } bool Table::tablePleine() { for(int i = 0; i < 7; i++) { if(colonneVide(i)) return false; } return true; }
20.679412
112
0.30778
[ "vector" ]
4f65ff15173cf995fd2b3cefe88687e336808df7
2,139
cpp
C++
POI/difference/kd_ac.cpp
syedakainat3/youtube
9e6860786b3f7b57add7cb4a0d44c551f88b8248
[ "MIT" ]
2,605
2019-02-05T16:03:10.000Z
2022-03-31T15:17:10.000Z
POI/difference/kd_ac.cpp
MohaiminulEraj/youtube
9e6860786b3f7b57add7cb4a0d44c551f88b8248
[ "MIT" ]
11
2019-10-21T14:40:15.000Z
2021-11-07T21:57:26.000Z
POI/difference/kd_ac.cpp
MohaiminulEraj/youtube
9e6860786b3f7b57add7cb4a0d44c551f88b8248
[ "MIT" ]
586
2019-03-24T18:39:57.000Z
2022-03-26T12:22:17.000Z
// POI 18-2, Difference // O(N * A + A^2) where A is the alphabet size #include <bits/stdc++.h> using namespace std; const int NAX = 1e6 + 5; char s[NAX]; vector<int> occurrences[26]; // occurrences[x] - indices where letter 'x' occurs int consider(const vector<int>& A, const vector<int>& B) { if(A.empty() || B.empty()) { return 0; } // merge the two lists/vectors into one with -1, +1 vector<int> seq; int pointer2 = 0; for(int i : A) { while(pointer2 < (int) B.size() && B[pointer2] < i) { seq.push_back(-1); // indices from B are changed to -1 ++pointer2; } seq.push_back(1); // indices from A are changed to +1 } while(pointer2 < (int) B.size()) { seq.push_back(-1); ++pointer2; } //~ for(int x : seq) { //~ printf("%d ", x); //~ } //~ puts(""); // find the maximum sum of a subarray that contains at least one -1 const int n = seq.size(); vector<int> pref{0}; for(int x : seq) { pref.push_back(pref.back() + x); // prefix sums } vector<int> pref_min(n + 1); for(int i = 1; i <= n; ++i) { pref_min[i] = min(pref_min[i-1], pref[i]); // minima of prefix sums } //~ for(int x : pref) { //~ printf("%d ", x); //~ } //~ puts(""); int answer = 0; int last_negative = -1; // fake value, meaning there were no negative values so far for(int i = 0; i < n; ++i) { if(seq[i] == -1) { last_negative = i; } if(last_negative != -1) { answer = max(answer, pref[i+1] - pref_min[last_negative]); } } return answer; } int main() { int n; scanf("%d", &n); scanf("%s", s); assert(n == (int) strlen(s)); for(int i = 0; i < n; ++i) { occurrences[s[i]-'a'].push_back(i); } int answer = 0; for(int a = 0; a < 26; ++a) { for(int b = 0; b < 26; ++b) { if(a != b) { answer = max(answer, consider(occurrences[a], occurrences[b])); } } } printf("%d\n", answer); }
26.7375
87
0.486209
[ "vector" ]
4f689ee89787af5d9e0e14ec33a2efbea9496270
25,363
cc
C++
rewriter/Prop.cc
qaisjp/sorbet
971ed17fd768ea1aca2dbed940fefa91f8cd76db
[ "Apache-2.0" ]
null
null
null
rewriter/Prop.cc
qaisjp/sorbet
971ed17fd768ea1aca2dbed940fefa91f8cd76db
[ "Apache-2.0" ]
null
null
null
rewriter/Prop.cc
qaisjp/sorbet
971ed17fd768ea1aca2dbed940fefa91f8cd76db
[ "Apache-2.0" ]
null
null
null
#include "rewriter/Prop.h" #include "ast/Helpers.h" #include "ast/ast.h" #include "core/Context.h" #include "core/Names.h" #include "core/core.h" #include "core/errors/rewriter.h" #include "rewriter/Util.h" using namespace std; namespace sorbet::rewriter { namespace { // these helpers work on a purely syntactic level. for instance, this function determines if an expression is `T`, // either with no scope or with the root scope (i.e. `::T`). this might not actually refer to the `T` that we define for // users, but we don't know that information in the Rewriter passes. bool isT(ast::ExpressionPtr &expr) { auto *t = ast::cast_tree<ast::UnresolvedConstantLit>(expr); return t != nullptr && t->cnst == core::Names::Constants::T() && ast::MK::isRootScope(t->scope); } bool isTNilable(ast::ExpressionPtr &expr) { auto *nilable = ast::cast_tree<ast::Send>(expr); return nilable != nullptr && nilable->fun == core::Names::nilable() && isT(nilable->recv); } bool isTStruct(ast::ExpressionPtr &expr) { auto *struct_ = ast::cast_tree<ast::UnresolvedConstantLit>(expr); return struct_ != nullptr && struct_->cnst == core::Names::Constants::Struct() && isT(struct_->scope); } bool isTInexactStruct(ast::ExpressionPtr &expr) { auto *struct_ = ast::cast_tree<ast::UnresolvedConstantLit>(expr); return struct_ != nullptr && struct_->cnst == core::Names::Constants::InexactStruct() && isT(struct_->scope); } bool isChalkODMDocument(ast::ExpressionPtr &expr) { auto *document = ast::cast_tree<ast::UnresolvedConstantLit>(expr); if (document == nullptr || document->cnst != core::Names::Constants::Document()) { return false; } auto *odm = ast::cast_tree<ast::UnresolvedConstantLit>(document->scope); if (odm == nullptr || odm->cnst != core::Names::Constants::ODM()) { return false; } auto *chalk = ast::cast_tree<ast::UnresolvedConstantLit>(odm->scope); return chalk != nullptr && chalk->cnst == core::Names::Constants::Chalk() && ast::MK::isRootScope(chalk->scope); } enum class SyntacticSuperClass { Unknown, TStruct, TInexactStruct, ChalkODMDocument, }; bool knownNonModel(SyntacticSuperClass syntacticSuperClass) { switch (syntacticSuperClass) { case SyntacticSuperClass::TStruct: case SyntacticSuperClass::TInexactStruct: case SyntacticSuperClass::ChalkODMDocument: return true; case SyntacticSuperClass::Unknown: return false; } } bool knownNonDocument(SyntacticSuperClass syntacticSuperClass) { switch (syntacticSuperClass) { case SyntacticSuperClass::TStruct: case SyntacticSuperClass::TInexactStruct: return true; case SyntacticSuperClass::ChalkODMDocument: case SyntacticSuperClass::Unknown: return false; } } bool wantTypedInitialize(SyntacticSuperClass syntacticSuperClass) { switch (syntacticSuperClass) { case SyntacticSuperClass::TStruct: return true; case SyntacticSuperClass::TInexactStruct: case SyntacticSuperClass::ChalkODMDocument: case SyntacticSuperClass::Unknown: return false; } } struct PropContext { SyntacticSuperClass syntacticSuperClass = SyntacticSuperClass::Unknown; ast::ClassDef::Kind classDefKind; }; struct PropInfo { core::LocOffsets loc; bool isImmutable = false; bool hasWithoutAccessors = false; core::NameRef name; core::LocOffsets nameLoc; ast::ExpressionPtr type; ast::ExpressionPtr default_; core::NameRef computedByMethodName; core::LocOffsets computedByMethodNameLoc; ast::ExpressionPtr foreign; ast::ExpressionPtr enum_; ast::ExpressionPtr ifunset; }; struct NodesAndPropInfo { vector<ast::ExpressionPtr> nodes; PropInfo propInfo; }; optional<PropInfo> parseProp(core::MutableContext ctx, const ast::Send *send) { PropInfo ret; ret.loc = send->loc; // ----- Is this a send we care about? ----- switch (send->fun.rawId()) { case core::Names::prop().rawId(): // Nothing special break; case core::Names::const_().rawId(): ret.isImmutable = true; break; case core::Names::tokenProp().rawId(): case core::Names::timestampedTokenProp().rawId(): ret.name = core::Names::token(); ret.nameLoc = core::LocOffsets{send->loc.beginPos() + (send->fun == core::Names::timestampedTokenProp() ? 12 : 0), send->loc.endPos() - 5}; // get the 'token' part of it ret.type = ast::MK::Constant(send->loc, core::Symbols::String()); break; case core::Names::createdProp().rawId(): ret.name = core::Names::created(); ret.nameLoc = core::LocOffsets{send->loc.beginPos(), send->loc.endPos() - 5}; // 5 is the difference between `created_prop` and `created` ret.type = ast::MK::Constant(send->loc, core::Symbols::Float()); break; case core::Names::merchantProp().rawId(): ret.isImmutable = true; ret.name = core::Names::merchant(); ret.nameLoc = core::LocOffsets{send->loc.beginPos(), send->loc.endPos() - 5}; // 5 is the difference between `merchant_prop` and `merchant` ret.type = ast::MK::Constant(send->loc, core::Symbols::String()); break; default: return std::nullopt; } auto expectedPosArgs = 3; if (send->hasKwArgs()) { expectedPosArgs = 2; } if (send->numPosArgs > expectedPosArgs) { // Too many args, even if all optional args were provided. return nullopt; } // ----- What's the prop's name? ----- if (!ret.name.exists()) { if (send->args.empty()) { return nullopt; } auto *sym = ast::cast_tree<ast::Literal>(send->args[0]); if (!sym || !sym->isSymbol(ctx)) { return nullopt; } ret.name = sym->asSymbol(ctx); ENFORCE(!core::Loc(ctx.file, sym->loc).source(ctx).empty() && core::Loc(ctx.file, sym->loc).source(ctx)[0] == ':'); ret.nameLoc = core::LocOffsets{sym->loc.beginPos() + 1, sym->loc.endPos()}; } // ----- What's the prop's type? ----- if (ret.type == nullptr) { if (send->numPosArgs == 1) { // Type must have been inferred from prop method (like created_prop) or // been given in second argument. return nullopt; } ret.type = ASTUtil::dupType(send->args[1]); if (ret.type == nullptr) { return nullopt; } } ENFORCE(ASTUtil::dupType(ret.type) != nullptr, "No obvious type AST for this prop"); // ----- Does the prop have any extra options? ----- // Deep copy the rules hash so that we can destruct it at will to parse things, // without having to worry about whether we stole things from the tree. ast::ExpressionPtr rulesTree = ASTUtil::mkKwArgsHash(send); if (rulesTree == nullptr && send->numPosArgs >= expectedPosArgs) { // No rules, but 3 args including name and type. Also not a T::Props return std::nullopt; } // ----- Parse any extra options ----- if (rulesTree) { auto *rules = ast::cast_tree<ast::Hash>(rulesTree); if (ASTUtil::hasTruthyHashValue(ctx, *rules, core::Names::immutable())) { ret.isImmutable = true; } if (ASTUtil::hasHashValue(ctx, *rules, core::Names::withoutAccessors())) { ret.hasWithoutAccessors = true; } if (ASTUtil::hasTruthyHashValue(ctx, *rules, core::Names::factory())) { ret.default_ = ast::MK::RaiseUnimplemented(ret.loc); } else if (ASTUtil::hasHashValue(ctx, *rules, core::Names::default_())) { auto [key, val] = ASTUtil::extractHashValue(ctx, *rules, core::Names::default_()); ret.default_ = std::move(val); } // e.g. `const :foo, type, computed_by: :method_name` if (ASTUtil::hasTruthyHashValue(ctx, *rules, core::Names::computedBy())) { auto [key, val] = ASTUtil::extractHashValue(ctx, *rules, core::Names::computedBy()); auto lit = ast::cast_tree<ast::Literal>(val); if (lit != nullptr && lit->isSymbol(ctx)) { ret.computedByMethodNameLoc = lit->loc; ret.computedByMethodName = lit->asSymbol(ctx); } else { if (auto e = ctx.beginError(val.loc(), core::errors::Rewriter::ComputedBySymbol)) { e.setHeader("Value for `{}` must be a symbol literal", "computed_by"); } } } auto [fk, foreignTree] = ASTUtil::extractHashValue(ctx, *rules, core::Names::foreign()); if (foreignTree != nullptr) { ret.foreign = move(foreignTree); if (auto body = ASTUtil::thunkBody(ctx, ret.foreign)) { ret.foreign = std::move(body); } else { if (auto e = ctx.beginError(ret.foreign.loc(), core::errors::Rewriter::PropForeignStrict)) { e.setHeader("The argument to `{}` must be a lambda", "foreign:"); e.replaceWith("Convert to lambda", core::Loc(ctx.file, ret.foreign.loc()), "-> {{{}}}", core::Loc(ctx.file, ret.foreign.loc()).source(ctx)); } } } auto [enumKey, enum_] = ASTUtil::extractHashValue(ctx, *rules, core::Names::enum_()); if (enum_ != nullptr) { ret.enum_ = std::move(enum_); } auto [ifunsetKey, ifunset] = ASTUtil::extractHashValue(ctx, *rules, core::Names::ifunset()); if (ifunset != nullptr) { ret.ifunset = std::move(ifunset); } } if (ret.default_ == nullptr && isTNilable(ret.type)) { ret.default_ = ast::MK::Nil(ret.loc); } return ret; } vector<ast::ExpressionPtr> processProp(core::MutableContext ctx, PropInfo &ret, PropContext propContext) { vector<ast::ExpressionPtr> nodes; const auto loc = ret.loc; const auto name = ret.name; const auto nameLoc = ret.nameLoc; const auto getType = ASTUtil::dupType(ret.type); const auto computedByMethodName = ret.computedByMethodName; const auto computedByMethodNameLoc = ret.computedByMethodNameLoc; auto ivarName = name.addAt(ctx); nodes.emplace_back(ast::MK::Sig0(loc, ASTUtil::dupType(getType))); if (computedByMethodName.exists()) { // Given `const :foo, type, computed_by: <name>`, where <name> is a Symbol pointing to a class method, // assert that the method takes 1 argument (of any type), and returns the same type as the prop, // via `T.assert_type!(self.class.compute_foo(T.unsafe(nil)), type)` in the getter. auto selfSendClass = ast::MK::Send0(computedByMethodNameLoc, ast::MK::Self(loc), core::Names::class_()); auto raiseUnimplemented = ast::MK::RaiseUnimplemented(computedByMethodNameLoc); auto sendComputedMethod = ast::MK::Send1(computedByMethodNameLoc, std::move(selfSendClass), computedByMethodName, std::move(raiseUnimplemented)); auto assertTypeMatches = ast::MK::AssertType(computedByMethodNameLoc, std::move(sendComputedMethod), ASTUtil::dupType(getType)); auto insSeq = ast::MK::InsSeq1(loc, std::move(assertTypeMatches), ast::MK::RaiseUnimplemented(loc)); nodes.emplace_back(ASTUtil::mkGet(ctx, loc, name, std::move(insSeq))); } else if (propContext.classDefKind == ast::ClassDef::Kind::Module) { // Not all modules include Kernel, can't make an initialize, etc. so we're punting on props in modules rn. nodes.emplace_back(ASTUtil::mkGet(ctx, loc, name, ast::MK::RaiseUnimplemented(loc))); } else if (ret.ifunset == nullptr) { if (knownNonModel(propContext.syntacticSuperClass)) { auto isAttrReader = true; if (wantTypedInitialize(propContext.syntacticSuperClass)) { nodes.emplace_back(ASTUtil::mkGet(ctx, loc, name, ast::MK::Instance(nameLoc, ivarName), isAttrReader)); } else { // Need to hide the instance variable access, because there wasn't a typed constructor to declare it auto ivarGet = ast::MK::Send1(loc, ast::MK::Self(loc), core::Names::instanceVariableGet(), ast::MK::Symbol(nameLoc, ivarName)); nodes.emplace_back(ASTUtil::mkGet(ctx, loc, name, std::move(ivarGet), isAttrReader)); } } else { // Models have a custom decorator, which means we have to forward the prop get to it. // If this is actually a T::InexactStruct or Chalk::ODM::Document sub-sub-class, this implementation is // correct but does extra work. auto arg2 = ast::MK::Local(loc, core::Names::arg2()); auto ivarGet = ast::MK::Send1(loc, ast::MK::Self(loc), core::Names::instanceVariableGet(), ast::MK::Symbol(nameLoc, ivarName)); auto assign = ast::MK::Assign(loc, arg2.deepCopy(), std::move(ivarGet)); auto class_ = ast::MK::Send0(loc, ast::MK::Self(loc), core::Names::class_()); auto decorator = ast::MK::Send0(loc, std::move(class_), core::Names::decorator()); auto propGetLogic = ast::MK::Send3(loc, std::move(decorator), core::Names::propGetLogic(), ast::MK::Self(loc), ast::MK::Symbol(nameLoc, name), std::move(arg2)); auto insSeq = ast::MK::InsSeq1(loc, std::move(assign), std::move(propGetLogic)); nodes.emplace_back(ASTUtil::mkGet(ctx, loc, name, std::move(insSeq))); } } else { nodes.emplace_back(ASTUtil::mkGet(ctx, loc, name, ast::MK::RaiseUnimplemented(loc))); } core::NameRef setName = name.addEq(ctx); // Compute the setter if (!ret.isImmutable) { auto setType = ASTUtil::dupType(ret.type); ast::Send::ARGS_store sigArgs; sigArgs.emplace_back(ast::MK::Symbol(nameLoc, core::Names::arg0())); sigArgs.emplace_back(ASTUtil::dupType(setType)); nodes.emplace_back(ast::MK::Sig(loc, std::move(sigArgs), ASTUtil::dupType(setType))); if (propContext.classDefKind == ast::ClassDef::Kind::Module) { // Not all modules include Kernel, can't make an initialize, etc. so we're punting on props in modules rn. nodes.emplace_back(ASTUtil::mkSet(ctx, loc, setName, nameLoc, ast::MK::RaiseUnimplemented(loc))); } else if (ret.enum_ == nullptr) { if (knownNonDocument(propContext.syntacticSuperClass)) { if (wantTypedInitialize(propContext.syntacticSuperClass)) { auto ivarSet = ast::MK::Assign(loc, ast::MK::Instance(nameLoc, ivarName), ast::MK::Local(nameLoc, core::Names::arg0())); nodes.emplace_back(ASTUtil::mkSet(ctx, loc, setName, nameLoc, std::move(ivarSet))); } else { // need to hide the instance variable access, because there wasn't a typed constructor to declare it auto ivarSet = ast::MK::Send2(loc, ast::MK::Self(loc), core::Names::instanceVariableSet(), ast::MK::Symbol(nameLoc, ivarName), ast::MK::Local(nameLoc, core::Names::arg0())); nodes.emplace_back(ASTUtil::mkSet(ctx, loc, setName, nameLoc, std::move(ivarSet))); } } else { // Chalk::ODM::Document classes have special handling for soft freeze auto doc = ast::MK::String(loc, core::Names::Chalk_ODM_Document()); auto nonForcingCnst = ast::MK::Constant(loc, core::Symbols::T_NonForcingConstants()); auto nonForcingIsA = ast::MK::Send2(loc, std::move(nonForcingCnst), core::Names::nonForcingIsA_p(), ast::MK::Self(loc), std::move(doc)); auto docDecoHelper = ast::MK::Constant(loc, core::Symbols::Chalk_ODM_DocumentDecoratorHelper()); auto softFreezeLogic = ast::MK::Send2(loc, std::move(docDecoHelper), core::Names::softFreezeLogic(), ast::MK::Self(loc), ast::MK::Symbol(loc, name)); auto softFreezeIf = ast::MK::If(loc, std::move(nonForcingIsA), std::move(softFreezeLogic), ast::MK::EmptyTree()); // need to hide the instance variable access, because there wasn't a typed constructor to declare it auto ivarSet = ast::MK::Send2(loc, ast::MK::Self(loc), core::Names::instanceVariableSet(), ast::MK::Symbol(nameLoc, ivarName), ast::MK::Local(nameLoc, core::Names::arg0())); auto insSeq = ast::MK::InsSeq1(loc, std::move(softFreezeIf), std::move(ivarSet)); nodes.emplace_back(ASTUtil::mkSet(ctx, loc, setName, nameLoc, std::move(insSeq))); } } else { nodes.emplace_back(ASTUtil::mkSet(ctx, loc, setName, nameLoc, ast::MK::RaiseUnimplemented(loc))); } } // Compute the `_` foreign accessor if (ret.foreign) { ast::ExpressionPtr type; ast::ExpressionPtr nonNilType; if (ASTUtil::dupType(ret.foreign) == nullptr) { // If it's not a valid type, just use untyped type = ast::MK::Untyped(loc); nonNilType = ast::MK::Untyped(loc); } else { type = ast::MK::Nilable(loc, ASTUtil::dupType(ret.foreign)); nonNilType = ASTUtil::dupType(ret.foreign); } // sig {params(opts: T.untyped).returns(T.nilable($foreign))} nodes.emplace_back( ast::MK::Sig1(loc, ast::MK::Symbol(nameLoc, core::Names::opts()), ast::MK::Untyped(loc), std::move(type))); // def $fk_method(**opts) // T.unsafe(nil) // end auto fkMethod = ctx.state.enterNameUTF8(name.show(ctx) + "_"); auto arg = ast::MK::RestArg(nameLoc, ast::MK::KeywordArg(nameLoc, core::Names::opts())); ast::MethodDef::Flags fkFlags; fkFlags.discardDef = true; auto fkMethodDef = ast::MK::SyntheticMethod1(loc, loc, fkMethod, std::move(arg), ast::MK::RaiseUnimplemented(loc), fkFlags); nodes.emplace_back(std::move(fkMethodDef)); // sig {params(opts: T.untyped).returns($foreign)} nodes.emplace_back(ast::MK::Sig1(loc, ast::MK::Symbol(nameLoc, core::Names::opts()), ast::MK::Untyped(loc), std::move(nonNilType))); // def $fk_method_!(**opts) // T.unsafe(nil) // end auto fkMethodBang = ctx.state.enterNameUTF8(name.show(ctx) + "_!"); auto arg2 = ast::MK::RestArg(nameLoc, ast::MK::KeywordArg(nameLoc, core::Names::opts())); ast::MethodDef::Flags fkBangFlags; fkBangFlags.discardDef = true; auto fkMethodDefBang = ast::MK::SyntheticMethod1(loc, loc, fkMethodBang, std::move(arg2), ast::MK::RaiseUnimplemented(loc), fkBangFlags); nodes.emplace_back(std::move(fkMethodDefBang)); } return nodes; } ast::ExpressionPtr ensureWithoutAccessors(const PropInfo &prop, const ast::Send *send) { ast::ExpressionPtr result = send->deepCopy(); if (prop.hasWithoutAccessors) { return result; } auto withoutAccessors = ast::MK::Symbol(send->loc, core::Names::withoutAccessors()); auto true_ = ast::MK::True(send->loc); auto *copy = ast::cast_tree<ast::Send>(result); if (copy->hasKwArgs() || copy->args.empty()) { // append to the inline keyword arguments of the send auto pos = copy->args.end(); if (copy->hasKwSplat()) { pos--; } pos = copy->args.insert(pos, move(withoutAccessors)); pos++; copy->args.insert(pos, move(true_)); } else { if (auto *hash = ast::cast_tree<ast::Hash>(copy->args.back())) { hash->keys.emplace_back(move(withoutAccessors)); hash->values.emplace_back(move(true_)); } else { auto pos = copy->args.end(); pos = copy->args.insert(pos, move(withoutAccessors)); pos++; copy->args.insert(pos, move(true_)); } } return result; } vector<ast::ExpressionPtr> mkTypedInitialize(core::MutableContext ctx, core::LocOffsets klassLoc, core::LocOffsets klassDeclLoc, const vector<PropInfo> &props) { ast::MethodDef::ARGS_store args; ast::Send::ARGS_store sigArgs; args.reserve(props.size()); sigArgs.reserve(props.size() * 2); // add all the required props first. for (const auto &prop : props) { if (prop.default_ != nullptr) { continue; } auto loc = prop.loc; args.emplace_back(ast::MK::KeywordArg(loc, prop.name)); sigArgs.emplace_back(ast::MK::Symbol(loc, prop.name)); sigArgs.emplace_back(prop.type.deepCopy()); } // then, add all the optional props. for (const auto &prop : props) { if (prop.default_ == nullptr) { continue; } auto loc = prop.loc; args.emplace_back(ast::MK::OptionalArg(loc, ast::MK::KeywordArg(loc, prop.name), prop.default_.deepCopy())); sigArgs.emplace_back(ast::MK::Symbol(loc, prop.name)); sigArgs.emplace_back(prop.type.deepCopy()); } // then initialize all the instance variables in the body ast::InsSeq::STATS_store stats; for (const auto &prop : props) { auto ivarName = prop.name.addAt(ctx); stats.emplace_back(ast::MK::Assign(prop.loc, ast::MK::Instance(prop.nameLoc, ivarName), ast::MK::Local(prop.nameLoc, prop.name))); } auto body = ast::MK::InsSeq(klassLoc, std::move(stats), ast::MK::ZSuper(klassDeclLoc)); vector<ast::ExpressionPtr> result; result.emplace_back(ast::MK::SigVoid(klassDeclLoc, std::move(sigArgs))); result.emplace_back( ast::MK::SyntheticMethod(klassLoc, klassDeclLoc, core::Names::initialize(), std::move(args), std::move(body))); return result; } } // namespace void Prop::run(core::MutableContext ctx, ast::ClassDef *klass) { if (ctx.state.runningUnderAutogen) { return; } auto syntacticSuperClass = SyntacticSuperClass::Unknown; if (!klass->ancestors.empty()) { auto &superClass = klass->ancestors[0]; if (isTStruct(superClass)) { syntacticSuperClass = SyntacticSuperClass::TStruct; } else if (isTInexactStruct(superClass)) { syntacticSuperClass = SyntacticSuperClass::TInexactStruct; } else if (isChalkODMDocument(superClass)) { syntacticSuperClass = SyntacticSuperClass::ChalkODMDocument; } } auto propContext = PropContext{syntacticSuperClass, klass->kind}; UnorderedMap<void *, vector<ast::ExpressionPtr>> replaceNodes; replaceNodes.reserve(klass->rhs.size()); vector<PropInfo> props; for (auto &stat : klass->rhs) { auto *send = ast::cast_tree<ast::Send>(stat); if (send == nullptr) { continue; } auto propInfo = parseProp(ctx, send); if (!propInfo.has_value()) { continue; } auto processed = processProp(ctx, propInfo.value(), propContext); ENFORCE(!processed.empty(), "if parseProp completed successfully, processProp must complete too"); vector<ast::ExpressionPtr> nodes; nodes.emplace_back(ensureWithoutAccessors(propInfo.value(), send)); nodes.insert(nodes.end(), make_move_iterator(processed.begin()), make_move_iterator(processed.end())); replaceNodes[stat.get()] = std::move(nodes); props.emplace_back(std::move(propInfo.value())); } auto oldRHS = std::move(klass->rhs); klass->rhs.clear(); klass->rhs.reserve(oldRHS.size()); // we define our synthesized initialize first so that if the user wrote one themselves, it overrides ours. if (wantTypedInitialize(syntacticSuperClass)) { // For direct T::Struct subclasses, we know that seeing no props means the constructor should be zero-arity. for (auto &stat : mkTypedInitialize(ctx, klass->loc, klass->declLoc, props)) { klass->rhs.emplace_back(std::move(stat)); } } // this is cargo-culted from rewriter.cc. for (auto &stat : oldRHS) { auto replacement = replaceNodes.find(stat.get()); if (replacement == replaceNodes.end()) { klass->rhs.emplace_back(std::move(stat)); } else { for (auto &newNode : replacement->second) { klass->rhs.emplace_back(std::move(newNode)); } } } } }; // namespace sorbet::rewriter
43.72931
120
0.597445
[ "vector" ]
4f699d38a0fe396e698eedf7252e0b2483d06d59
6,365
cpp
C++
Source/Falcor/Scene/Transform.cpp
gonsolo/Falcor
db27e6fa0efb1c04a51333c14ddfeac309995145
[ "BSD-3-Clause" ]
1,615
2017-07-28T05:41:39.000Z
2022-03-31T16:31:57.000Z
Source/Falcor/Scene/Transform.cpp
gonsolo/Falcor
db27e6fa0efb1c04a51333c14ddfeac309995145
[ "BSD-3-Clause" ]
232
2017-08-03T10:58:41.000Z
2022-03-31T16:17:46.000Z
Source/Falcor/Scene/Transform.cpp
gonsolo/Falcor
db27e6fa0efb1c04a51333c14ddfeac309995145
[ "BSD-3-Clause" ]
383
2017-07-30T04:28:34.000Z
2022-03-30T05:12:13.000Z
/*************************************************************************** # Copyright (c) 2015-21, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 "AS IS" AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY # OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **************************************************************************/ #pragma once #include "stdafx.h" #include "Transform.h" #include "glm/gtc/quaternion.hpp" #include "glm/gtx/transform.hpp" namespace Falcor { Transform::Transform() {} void Transform::setTranslation(const float3& translation) { mTranslation = translation; mDirty = true; } void Transform::setScaling(const float3& scaling) { mScaling = scaling; mDirty = true; } void Transform::setRotation(const glm::quat& rotation) { mRotation = rotation; mDirty = true; } float3 Transform::getRotationEuler() const { return glm::eulerAngles(mRotation); } void Transform::setRotationEuler(const float3& angles) { setRotation(glm::quat(angles)); } float3 Transform::getRotationEulerDeg() const { return glm::degrees(getRotationEuler()); } void Transform::setRotationEulerDeg(const float3& angles) { setRotationEuler(glm::radians(angles)); } void Transform::lookAt(const float3& position, const float3& target, const float3& up) { mTranslation = position; float3 dir = normalize(target - position); mRotation = glm::quatLookAt(dir, up); } const glm::float4x4& Transform::getMatrix() const { if (mDirty) { glm::mat4 T = translate(mTranslation); glm::mat4 R = mat4_cast(mRotation); glm::mat4 S = scale(mScaling); mMatrix = T * R * S; mDirty = false; } return mMatrix; } bool Transform::operator==(const Transform& other) const { if (mTranslation != other.mTranslation) return false; if (mScaling != other.mScaling) return false; if (mRotation != other.mRotation) return false; return true; } FALCOR_SCRIPT_BINDING(Transform) { auto init = [](const pybind11::kwargs& args) { Transform transform; std::optional<float3> position; std::optional<float3> target; std::optional<float3> up; for (auto a : args) { auto key = a.first.cast<std::string>(); const auto& value = a.second; float3 float3Value; float floatValue; bool isFloat3 = pybind11::isinstance<float3>(value); bool isNumber = pybind11::isinstance<pybind11::int_>(value) || pybind11::isinstance<pybind11::float_>(value); if (isFloat3) float3Value = pybind11::cast<float3>(value); if (isNumber) floatValue = pybind11::cast<float>(value); if (key == "translation") { if (isFloat3) transform.setTranslation(float3Value); } else if (key == "scaling") { if (isFloat3) transform.setScaling(float3Value); if (isNumber) transform.setScaling(float3(floatValue)); } else if (key == "rotationEuler") { if (isFloat3) transform.setRotationEuler(float3Value); } else if (key == "rotationEulerDeg") { if (isFloat3) transform.setRotationEulerDeg(float3Value); } else if (key == "position") { if (isFloat3) position = float3Value; } else if (key == "target") { if (isFloat3) target = float3Value; } else if (key == "up") { if (isFloat3) up = float3Value; } } if (position && target && up) { transform.lookAt(*position, *target, *up); } return transform; }; pybind11::class_<Transform> transform(m, "Transform"); transform.def(pybind11::init(init)); transform.def_property("translation", &Transform::getTranslation, &Transform::setTranslation); transform.def_property("rotationEuler", &Transform::getRotationEuler, &Transform::setRotationEuler); transform.def_property("rotationEulerDeg", &Transform::getRotationEulerDeg, &Transform::setRotationEulerDeg); transform.def_property("scaling", &Transform::getScaling, &Transform::setScaling); transform.def_property_readonly("matrix", &Transform::getMatrix); transform.def("lookAt", &Transform::lookAt, "position"_a, "target"_a, "up"_a); } }
35.758427
125
0.587431
[ "transform" ]
4f6bca07fc85245d2b5616c295b3210c9a01a6a0
1,766
cpp
C++
perf_test/double/axpby_double.cpp
lql341/ChipSum
75611fecdd0c5577dd0f1eed5e5a0046bd934122
[ "MIT" ]
12
2021-06-25T01:49:05.000Z
2022-01-20T16:49:51.000Z
perf_test/double/axpby_double.cpp
lql341/ChipSum
75611fecdd0c5577dd0f1eed5e5a0046bd934122
[ "MIT" ]
4
2021-06-25T05:56:43.000Z
2021-08-30T02:46:52.000Z
perf_test/double/axpby_double.cpp
lql341/ChipSum
75611fecdd0c5577dd0f1eed5e5a0046bd934122
[ "MIT" ]
4
2021-08-19T01:12:47.000Z
2022-01-14T11:59:40.000Z
/* * * * * * * * * * * * * * * * * * * * * * File: test.cpp * Author: Li Kunyun * group: CDCS-HPC * Time: 2021-07-28 * * * * * * * * * * * * * * * * * * * * * */ #include <iostream> using namespace std; #include <type_traits> #include <vector> #include "ChipSum.hpp" #include <KokkosKernels_IOUtils.hpp> int main(int argc, char *argv[]) { ChipSum::Common::Init(argc, argv); { int N=100; for(int j=0; j<200; ++j){ double *v1 = static_cast<double *>(std::malloc(N * sizeof(double))); double *v2 = static_cast<double *>(std::malloc(N * sizeof(double))); for (int i = 0; i < N; ++i) { v1[i] = double(i); v2[i] = double(i); } Vector a(N,v1); // a = {0,1,2,3,4...} Vector b(N,v2); // b = {0,1,2,3,4...} int repeat = 100; /// \brief 暂时用Kokkos的Timer Kokkos::Timer timer; for(int i=0;i<repeat;++i){ a.AXPBY(b,3.0,2.0); // a=3.0*a+2.0*b } Kokkos::fence(); double time = timer.seconds(); /// \brief 带宽计算公式 double Gbytes = repeat*1.0e-9*(3.0*N-1)/time; if(j==0){ Kokkos::DefaultExecutionSpace::print_configuration(cout,true); cout<<"---------------------ChipSum AXPBY Perf Test " "---------------------"<<endl <<"Vector size,GFlops :"<<endl; } cout<<setiosflags(ios::left)<<setw(12)<<N<<Gbytes<<endl; N*=1.1; std::free(v1); std::free(v2); } } ChipSum::Common::Finalize(); }
28.031746
80
0.411665
[ "vector" ]
4f6fd14fe29bad4f1b9ef69bee41ff5d9b31a861
5,362
cpp
C++
abstractionalgorithms/AStar3.cpp
AaronTrip/hog2
96616b40f4173959b127011c76f3e649688e1a99
[ "MIT" ]
5
2020-08-03T09:43:26.000Z
2022-01-11T08:28:30.000Z
abstractionalgorithms/AStar3.cpp
AaronTrip/hog2
96616b40f4173959b127011c76f3e649688e1a99
[ "MIT" ]
null
null
null
abstractionalgorithms/AStar3.cpp
AaronTrip/hog2
96616b40f4173959b127011c76f3e649688e1a99
[ "MIT" ]
7
2017-07-31T13:01:28.000Z
2021-05-16T10:15:49.000Z
/* * $Id: aStar3.cpp,v 1.2 2006/09/18 06:19:31 nathanst Exp $ * * Hierarchical Open Graph File * * Created by Nathan Sturtevant on 9/29/04. * Copyright 2004 Nathan Sturtevant. All rights reserved. * * This file is part of HOG. * * HOG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * HOG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HOG; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #include "FPUtil.h" #include "AStar3.h" #include "Heap.h" #include <string.h> using namespace GraphAbstractionConstants; static const int verbose = 0; // The constructor aStarOld::aStarOld(double _weight, bool _doPathDraw) :SearchAlgorithm() { wh = _weight; doPathDraw = _doPathDraw; // Generate algorithm's name if (fequal(wh,1.0)) strcpy(aStarName,"aStarOld"); else sprintf(aStarName,"aStarOld(%1.1f)",wh); } // The same A*, but counts the number of states expanded path *aStarOld::GetPath(GraphAbstraction *aMap, node *from, node *to, reservationProvider *rp) { // Reset the number of states expanded nodesExpanded = 0; nodesTouched = 0; if ((from == 0) || (to == 0) || (!aMap->Pathable(from, to)) || (from == to)) return 0; map = aMap; Graph *g = map->GetAbstractGraph(from->GetLabelL(kAbstractionLevel)); Heap *openList = new Heap(30); std::vector<node *> closedList; node *n; // label start node cost 0 n = from; n->SetLabelF(kTemporaryLabel, wh*map->h(n, to)); n->markEdge(0); while (1) { nodesExpanded++; edge_iterator ei; // move current node onto closed list // mark node with its location in the closed list closedList.push_back(n); n->key = closedList.size()-1; if (verbose) printf("Working on %d with cost %1.2f\n", n->GetNum(), n->GetLabelF(kTemporaryLabel)); ei = n->getEdgeIter(); // iterate over all the children for (edge *e = n->edgeIterNext(ei); e; e = n->edgeIterNext(ei)) { nodesTouched++; unsigned int which; if ((which = e->getFrom()) == n->GetNum()) which = e->getTo(); node *nextChild = g->GetNode(which); // if it's on the open list, we can still update the weight if (openList->IsIn(nextChild)) { //nodesExpanded++; relaxEdge(openList, g, e, n->GetNum(), which, to); } else if (rp && (from->GetLabelL(kAbstractionLevel)==0) && (nextChild != to) && rp->nodeOccupied(nextChild)) { //printf("Can't path to %d, %d\n", (unsigned int)nextChild->GetLabelL(kFirstData), (unsigned int)nextChild->GetLabelL(kFirstData+1)); closedList.push_back(nextChild); nextChild->key = closedList.size()-1; // ignore this tile if occupied. } // if it's not on the open list, then add it to the open list else if ((nextChild->key >= closedList.size()) || (closedList[nextChild->key] != nextChild)) { nextChild->SetLabelF(kTemporaryLabel, MAXINT); nextChild->SetKeyLabel(kTemporaryLabel); nextChild->markEdge(0); openList->Add(nextChild); if (verbose) printf("Adding neighbor/child %d\n", which); //nodesExpanded++; relaxEdge(openList, g, e, n->GetNum(), which, to); } } // get the next (the best) node off the open list n = (node*)openList->Remove(); // this means we have expanded all reachable nodes and there is no path if (n == 0) { delete openList; return 0; } if (verbose) printf("Expanding %d\n", n->GetNum()); if (n == to) break; // we found the goal } delete openList; return extractBestPath(g, n->GetNum()); } // this is the standard definition of relaxation as in Introduction to Algorithms (cormen, leiserson and rivest) void aStarOld::relaxEdge(Heap *nodeHeap, Graph *g, edge *e, int source, int nextNode, node *d) { double weight; node *from = g->GetNode(source); node *to = g->GetNode(nextNode); weight = from->GetLabelF(kTemporaryLabel)-wh*map->h(from, d)+wh*map->h(to, d)+e->GetWeight(); if (fless(weight, to->GetLabelF(kTemporaryLabel))) { if (verbose) printf("Updating %d to %1.2f from %1.2f\n", nextNode, weight, to->GetLabelF(kTemporaryLabel)); to->SetLabelF(kTemporaryLabel, weight); nodeHeap->DecreaseKey(to); // this is the edge used to get to this node in the min. path tree to->markEdge(e); } } path *aStarOld::extractBestPath(Graph *g, unsigned int current) { path *p = 0; edge *e; // extract best path from Graph -- each node has a single parent in the Graph which is the marked edge // for visuallization purposes, an edge can be marked meaning it will be drawn in white while ((e = g->GetNode(current)->getMarkedEdge())) { if (verbose) printf("%d <- ", current); p = new path(g->GetNode(current), p); if (doPathDraw) e->setMarked(true); if (e->getFrom() == current) current = e->getTo(); else current = e->getFrom(); } p = new path(g->GetNode(current), p); if (verbose) printf("%d\n", current); return p; }
30.465909
137
0.668034
[ "vector" ]