hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1bdc71c2b1af4f9a4743741f85a126d6acc92bea | 2,983 | cpp | C++ | external/text/example/editor/curses_interface.cpp | geenen124/iresearch | f89902a156619429f9e8df94bd7eea5a78579dbc | [
"Apache-2.0"
] | 12,278 | 2015-01-29T17:11:33.000Z | 2022-03-31T21:12:00.000Z | external/text/example/editor/curses_interface.cpp | geenen124/iresearch | f89902a156619429f9e8df94bd7eea5a78579dbc | [
"Apache-2.0"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | external/text/example/editor/curses_interface.cpp | geenen124/iresearch | f89902a156619429f9e8df94bd7eea5a78579dbc | [
"Apache-2.0"
] | 892 | 2015-01-29T16:26:19.000Z | 2022-03-20T07:44:30.000Z | // Copyright (C) 2020 T. Zachary Laine
//
// 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 "curses_interface.hpp"
extern "C" {
#include <ncurses.h>
}
curses_interface_t::curses_interface_t() : win_(initscr())
{
if (win_ != stdscr)
throw std::runtime_error("ncurses initscr() failed.");
raw();
noecho();
keypad(stdscr, true);
start_color();
use_default_colors();
mmask_t old_mouse_events;
mousemask(
BUTTON1_CLICKED | BUTTON1_DOUBLE_CLICKED | BUTTON1_TRIPLE_CLICKED |
REPORT_MOUSE_POSITION,
&old_mouse_events);
set_tabsize(1);
}
curses_interface_t::~curses_interface_t() { endwin(); }
screen_pos_t curses_interface_t::screen_size() const
{
return {getmaxy(stdscr), getmaxx(stdscr)};
}
event_t curses_interface_t::next_event() const
{
int const k = wgetch(win_);
// Mouse events.
if (k == KEY_MOUSE) {
MEVENT e;
if (getmouse(&e) == ERR)
return {key_code_t{KEY_MAX}, screen_size()};
return {key_code_t{(int)e.bstate, e.x, e.y}, screen_size()};
}
// Everything else.
return {key_code_t{k}, screen_size()};
}
namespace {
void render_text(snapshot_t const & snapshot, screen_pos_t screen_size)
{
int row = 0;
std::vector<char> buf;
std::ptrdiff_t pos = snapshot.first_char_index_;
auto line_first = snapshot.first_row_;
auto const line_last = std::min<std::ptrdiff_t>(
line_first + screen_size.row_ - 2, snapshot.lines_.size());
for (; line_first != line_last; ++line_first) {
auto const line = snapshot.lines_[line_first];
auto first = snapshot.content_.begin().base().base() + pos;
auto const last = first + line.code_units_;
move(row, 0);
buf.clear();
std::copy(first, last, std::back_inserter(buf));
if (!buf.empty() && buf.back() == '\n')
buf.pop_back();
if (!buf.empty() && buf.back() == '\r')
buf.pop_back();
buf.push_back('\0');
addstr(&buf[0]);
pos += line.code_units_;
++row;
}
}
}
void render(buffer_t const & buffer, screen_pos_t screen_size)
{
erase();
auto const size = screen_pos_t{screen_size.row_ - 2, screen_size.col_};
render_text(buffer.snapshot_, screen_size);
// render the info line
move(size.row_, 0);
attron(A_REVERSE);
printw(
" %s %s (%d, %d)",
dirty(buffer) ? "**" : "--",
buffer.path_.c_str(),
buffer.snapshot_.first_row_ + buffer.snapshot_.cursor_pos_.row_ + 1,
buffer.snapshot_.cursor_pos_.col_);
attroff(A_REVERSE);
hline(' ', size.col_);
move(buffer.snapshot_.cursor_pos_.row_, buffer.snapshot_.cursor_pos_.col_);
curs_set(true);
refresh();
}
| 27.878505 | 79 | 0.602749 | geenen124 |
1be01f08d164fc69baeb7682f3aab33360199da3 | 2,887 | cpp | C++ | src/Http/HttpContext.cpp | MisakiOfScut/SingHttpServer | 039636d7cee16ccc46c281456d71a410f3f16e23 | [
"Apache-2.0"
] | 1 | 2021-03-05T09:27:35.000Z | 2021-03-05T09:27:35.000Z | src/Http/HttpContext.cpp | MisakiOfScut/SingHttpServer | 039636d7cee16ccc46c281456d71a410f3f16e23 | [
"Apache-2.0"
] | null | null | null | src/Http/HttpContext.cpp | MisakiOfScut/SingHttpServer | 039636d7cee16ccc46c281456d71a410f3f16e23 | [
"Apache-2.0"
] | null | null | null | #include "HttpContext.h"
#include <unistd.h>
#include <iostream>
#include <bits/types/struct_iovec.h>
using namespace sing;
HttpContext::HttpContext(int fd)
:state(REQUEST_LINE),fd(fd),working(false){
assert(fd>=0);
}
HttpContext::~HttpContext(){
close(fd);// FIX ME
}
bool HttpContext::parseRequest(){
bool ok = true;
bool hasMore = true;
while (hasMore)
{
if (state == REQUEST_LINE)
{
const char* crlf = input.findCRLF();
if(crlf){
ok = parseRequestLine(input.peek(),crlf);
if(ok){
input.retrieveUntil(crlf + 2);
state = HEADERS;
}else{
hasMore = false;
}
}else{
hasMore = false;
}
}else if (state == HEADERS)
{
const char* crlf = input.findCRLF();
if(crlf){
const char* colon = std::find(input.peek(),crlf,':');
if(colon!=crlf){
request.addHeader(input.peek(),colon,crlf);
}else{
state = BODY;
hasMore = true;
}
input.retrieveUntil(crlf + 2);
}else{
hasMore = false;
}
}else if (state==BODY)
{
//TO ADD: process requestbody
state = FINSH;
hasMore = false;
}
}
return ok;
}
bool HttpContext::parseRequestLine(const char* begin, const char* end){
bool success = false;
const char* start = begin;
const char* space = std::find(start, end, ' ');//find the 1st space in a line
if(space!=end && request.setMethod(start,space)){
start = space + 1;
space = std::find(start, end, ' ');
if(space!=end){
const char* quest = std::find(start, space, '?');
if (quest!=space)
{
request.setPath(start,quest);
request.setQuery(quest, space);
}else{
request.setPath(start, space);
}
//parse http version
start = space + 1;
success = end-start == 8 && std::equal(start, end-1, "HTTP/1.");
if(success){
if(*(end-1)=='1'){
request.setVersion(HttpRequest::HTTP11);
}else if(*(end-1)=='0'){
request.setVersion(HttpRequest::HTTP10);
}else{
success = false;
}
}
}
}
return success;
}
bool HttpContext::parseFinsh(){
return state == FINSH;
}
void HttpContext::reset(){
state = REQUEST_LINE;
input.retrieveAll();
output.retrieveAll();
output.setWriteFile(NULL, 0);
request.reset();
response.reset();
}
| 25.776786 | 81 | 0.472116 | MisakiOfScut |
1be324fe4fb70a4b08022431c19002cb56571040 | 6,046 | cpp | C++ | ASSIGNMENTS_MCA_3RD_SEM/Section B/Q9/q9.cpp | therishh/Data-Structures-and-Algorithms | 4e0daf666b94615268478bec8be1ca1b55f2a807 | [
"MIT"
] | null | null | null | ASSIGNMENTS_MCA_3RD_SEM/Section B/Q9/q9.cpp | therishh/Data-Structures-and-Algorithms | 4e0daf666b94615268478bec8be1ca1b55f2a807 | [
"MIT"
] | null | null | null | ASSIGNMENTS_MCA_3RD_SEM/Section B/Q9/q9.cpp | therishh/Data-Structures-and-Algorithms | 4e0daf666b94615268478bec8be1ca1b55f2a807 | [
"MIT"
] | null | null | null | //
// q9.cpp
// Algorithm
//
// Created by Mohd Shoaib Rayeen on 13/11/18.
// Copyright © 2018 Shoaib Rayeen. All rights reserved.
//
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class triathlon {
/*
------------------------------------------------------------------------------------------------
objective : class to decide the order to minimize completion time
------------------------------------------------------------------------------------------------
input parameter : none
------------------------------------------------------------------------------------------------
output parameter : none
------------------------------------------------------------------------------------------------
approach : declaring member functions which can ve accessed publicly -
mainFunction() -> to decide order
display() -> print user's data
helper() -> to insert dara and call member functions
------------------------------------------------------------------------------------------------
*/
public:
int n;
void mainFunction(vector<vector<int>> &data);
void display(vector<vector<int>> data);
void helper();
};
bool selectColumn(const vector<int>& v1, const vector<int>& v2) {
/*
------------------------------------------------------------------------------------------------
objective : select column by which sorting can be applied -> increasing order
------------------------------------------------------------------------------------------------
input parameter : none
------------------------------------------------------------------------------------------------
output parameter : false -> decreasing order
true -> increasing order
------------------------------------------------------------------------------------------------
approach : return bool value which detmines which column has to sorted
------------------------------------------------------------------------------------------------
*/
return v1[1] < v2[1];
}
void triathlon::mainFunction(vector<vector<int>> &data) {
/*
------------------------------------------------------------------------------------------------
objective : main function to decide the order
------------------------------------------------------------------------------------------------
input parameter : none
------------------------------------------------------------------------------------------------
output parameter : none
------------------------------------------------------------------------------------------------
approach : sorting according to swim time and displaying order
------------------------------------------------------------------------------------------------
*/
sort(data.begin() , data.end() , selectColumn );
cout << "\nFollowings are the order of contestants for small completion time\n\n";
for (int i = 0; i < data.size(); i++) {
cout << data[i][0] << "\t";
}
cout << endl;
}
void triathlon::display(vector<vector<int>> data) {
/*
------------------------------------------------------------------------------------------------
objective : print the data
------------------------------------------------------------------------------------------------
input parameter : none
------------------------------------------------------------------------------------------------
output parameter : none
------------------------------------------------------------------------------------------------
approach : displaying using loop
------------------------------------------------------------------------------------------------
*/
cout << "\n-----------------------------------------------------------------";
cout << "\nContestant Number\t|\tSwim Time\t|\tBike Time\t|\tRun Time\n";
cout << "-----------------------------------------------------------------\n";
for ( int i = 0; i < data.size(); i++ ) {
cout << "\t\t" << data[i][0] << "\t\t\t|\t\t" << data[i][1] << "\t\t|\t\t" << data[i][2] << "\t\t|\t" << data[i][3];
cout << endl;
}
}
void triathlon::helper() {
/*
------------------------------------------------------------------------------------------------
objective : insert the data and call member functions
------------------------------------------------------------------------------------------------
input parameter : none
------------------------------------------------------------------------------------------------
output parameter : none
------------------------------------------------------------------------------------------------
approach : insertion using loop and then calling member functions
------------------------------------------------------------------------------------------------
*/
/*
vector<vector<int>> data{
{ 1 , 52 , 13 , 15} ,
{ 2 , 19 , 17 , 13} ,
{ 3 , 99 , 13 , 10 } ,
{ 4 , 79 , 18 , 17 } ,
{ 5 , 37 , 13 , 14 } ,
{ 6 , 67 , 10 , 14 } ,
{ 7 , 89 , 13 , 19}
};
*/
cout << "\nEnter Number of contestants\t:\t";
cin >> n;
vector<vector<int>> data(n);
cout << "\nEnter Value in this form\n";
cout << "\nSwim Time , Bike Time and then Run Time\n";
for ( int i = 0; i < n; i++) {
data[i] = vector<int>(4);
data[i][0] = i + 1;
cin >> data[i][1];
cin >> data[i][2];
cin >> data[i][3];
}
display(data);
mainFunction(data);
data.clear();
}
int main() {
triathlon obj;
obj.helper();
return 0;
}
| 35.775148 | 124 | 0.291598 | therishh |
1be5a97bef7d8c1cabb90ce9e64eb1168d42bcac | 8,234 | cc | C++ | src/core/events.cc | tcoppex/barbu | 02be5b3179a460560191818d9ee1c3ba4ee858c9 | [
"MIT"
] | 2 | 2021-04-15T04:58:01.000Z | 2021-10-11T05:17:34.000Z | src/core/events.cc | tcoppex/barbu | 02be5b3179a460560191818d9ee1c3ba4ee858c9 | [
"MIT"
] | null | null | null | src/core/events.cc | tcoppex/barbu | 02be5b3179a460560191818d9ee1c3ba4ee858c9 | [
"MIT"
] | null | null | null | #include "core/events.h"
#include <algorithm>
#include "core/logger.h"
#include "ui/imgui_wrapper.h" //<! used for UI events preemption.
// ----------------------------------------------------------------------------
void Events::prepareNextFrame() {
// Reset per-frame values.
mouse_moved_ = false;
mouse_hover_ui_ = false;
has_resized_ = false;
last_input_char_ = 0;
mouse_wheel_delta_ = 0.0f;
dropped_filenames_.clear();
// Detect if any mouse buttons are still "Pressed" or "Down".
mouse_button_down_ = std::any_of(buttons_.cbegin(), buttons_.cend(), [](auto const& btn) {
auto const state(btn.second);
return (state == KeyState::Down) || (state == KeyState::Pressed);
});
// Update "Pressed" states to "Down", "Released" states to "Up".
auto const update_state{ [](auto& btn) {
auto const state(btn.second);
btn.second = (state == KeyState::Pressed) ? KeyState::Down :
(state == KeyState::Released) ? KeyState::Up : state;
}};
std::for_each(buttons_.begin(), buttons_.end(), update_state);
std::for_each(keys_.begin(), keys_.end(), update_state);
}
// ----------------------------------------------------------------------------
/* Bypass events capture when pointer hovers UI. */
#define EVENTS_IMGUI_BYPASS_( code, bMouse, bKeyboard ) \
{ \
auto &io{ImGui::GetIO()}; \
mouse_hover_ui_ = io.WantCaptureMouse; \
{ code ;} \
if ((bMouse) && (bKeyboard)) { return; } \
}
/* Bypass if the UI want the mouse */
#define EVENTS_IMGUI_BYPASS_MOUSE( code ) \
EVENTS_IMGUI_BYPASS_(code, io.WantCaptureMouse, true)
/* Bypass if the UI want the pointer or the keyboard. */
#define EVENTS_IMGUI_BYPASS_MOUSE_KB( code ) \
EVENTS_IMGUI_BYPASS_(code, io.WantCaptureMouse, io.WantCaptureKeyboard)
/* Do not bypass. */
#define EVENTS_IMGUI_CONTINUE( code ) \
EVENTS_IMGUI_BYPASS_(code, false, false)
/* Dispatch event signal to sub callbacks handlers. */
#define EVENTS_DISPATCH_SIGNAL( funcName, ... ) \
static_assert( std::string_view(#funcName)==__func__, "Incorrect dispatch signal used."); \
std::for_each(event_callbacks_.begin(), event_callbacks_.end(), [__VA_ARGS__](auto &e){ e->funcName(__VA_ARGS__); })
// ----------------------------------------------------------------------------
void Events::onKeyPressed(KeyCode_t key) {
EVENTS_IMGUI_CONTINUE(
if (io.WantCaptureKeyboard || io.WantCaptureMouse) {
io.KeysDown[key] = true;
}
);
keys_[key] = KeyState::Pressed;
key_pressed_.push( key );
EVENTS_DISPATCH_SIGNAL(onKeyPressed, key);
}
void Events::onKeyReleased(KeyCode_t key) {
EVENTS_IMGUI_CONTINUE(
if (io.WantCaptureKeyboard || io.WantCaptureMouse) {
io.KeysDown[key] = false;
}
);
keys_[key] = KeyState::Released;
EVENTS_DISPATCH_SIGNAL(onKeyReleased, key);
}
void Events::onInputChar(uint16_t c) {
EVENTS_IMGUI_BYPASS_MOUSE_KB(
if (io.WantCaptureKeyboard) { io.AddInputCharacter(c); }
);
last_input_char_ = c;
EVENTS_DISPATCH_SIGNAL(onInputChar, c);
}
void Events::onMousePressed(int x, int y, KeyCode_t button) {
EVENTS_IMGUI_BYPASS_MOUSE(
io.MouseDown[button] = true;
io.MousePos = ImVec2((float)x, (float)y);
);
buttons_[button] = KeyState::Pressed;
EVENTS_DISPATCH_SIGNAL(onMousePressed, x, y, button);
}
void Events::onMouseReleased(int x, int y, KeyCode_t button) {
EVENTS_IMGUI_BYPASS_MOUSE(
io.MouseDown[button] = false;
io.MousePos = ImVec2((float)x, (float)y);
);
buttons_[button] = KeyState::Released;
EVENTS_DISPATCH_SIGNAL(onMouseReleased, x, y, button);
}
void Events::onMouseEntered(int x, int y) {
EVENTS_DISPATCH_SIGNAL(onMouseEntered, x, y);
}
void Events::onMouseExited(int x, int y) {
EVENTS_DISPATCH_SIGNAL(onMouseExited, x, y);
}
void Events::onMouseMoved(int x, int y) {
EVENTS_IMGUI_BYPASS_MOUSE();
mouse_x_ = x;
mouse_y_ = y;
mouse_moved_ = true;
EVENTS_DISPATCH_SIGNAL(onMouseMoved, x, y);
}
void Events::onMouseDragged(int x, int y, KeyCode_t button) {
EVENTS_IMGUI_BYPASS_MOUSE(
io.MouseDown[button] = true;
io.MousePos = ImVec2((float)x, (float)y);
);
mouse_x_ = x;
mouse_y_ = y;
mouse_moved_ = true;
// (note : the button should already be registered as pressed / down)
EVENTS_DISPATCH_SIGNAL(onMouseDragged, x, y, button);
}
void Events::onMouseWheel(float dx, float dy) {
EVENTS_IMGUI_BYPASS_MOUSE(
io.MouseWheelH += dx;
io.MouseWheel += dy;
);
mouse_wheel_delta_ = dy;
mouse_wheel_ += dy;
EVENTS_DISPATCH_SIGNAL(onMouseWheel, dx, dy);
}
void Events::onResize(int w, int h) {
// EVENTS_IMGUI_CONTINUE(
// io.DisplaySize = ImVec2(static_cast<float>(w), static_cast<float>(h));
// io.DisplayFramebufferScale = ImVec2( 1.0f, 1.0f); //
// );
// [beware : downcast from int32 to int16]
surface_w_ = static_cast<SurfaceSize>(w);
surface_h_ = static_cast<SurfaceSize>(h);
has_resized_ = true;
EVENTS_DISPATCH_SIGNAL(onResize, w, h);
}
void Events::onFilesDropped(int count, char const** paths) {
for (int i=0; i<count; ++i) {
dropped_filenames_.push_back(std::string(paths[i]));
}
EVENTS_DISPATCH_SIGNAL(onFilesDropped, count, paths);
}
#undef EVENTS_IMGUI_BYPASS
#undef EVENTS_DISPATCH_SIGNAL
// ----------------------------------------------------------------------------
bool Events::buttonDown(KeyCode_t button) const noexcept {
return checkButtonState( button, [](KeyState state) {
return (state == KeyState::Pressed) || (state == KeyState::Down);
});
}
bool Events::buttonPressed(KeyCode_t button) const noexcept {
return checkButtonState( button, [](KeyState state) {
return (state == KeyState::Pressed);
});
}
bool Events::buttonReleased(KeyCode_t button) const noexcept {
return checkButtonState( button, [](KeyState state) {
return (state == KeyState::Released);
});
}
// ----------------------------------------------------------------------------
bool Events::keyDown(KeyCode_t key) const noexcept {
return checkKeyState( key, [](KeyState state) {
return (state == KeyState::Pressed) || (state == KeyState::Down);
});
}
bool Events::keyPressed(KeyCode_t key) const noexcept {
return checkKeyState( key, [](KeyState state) {
return (state == KeyState::Pressed);
});
}
bool Events::keyReleased(KeyCode_t key) const noexcept {
return checkKeyState( key, [](KeyState state) {
return (state == KeyState::Released);
});
}
// ----------------------------------------------------------------------------
bool Events::checkButtonState(KeyCode_t button, StatePredicate_t predicate) const noexcept {
if (auto search = buttons_.find(button); search != buttons_.end()) {
return predicate(search->second);
}
return false;
}
bool Events::checkKeyState(KeyCode_t key, StatePredicate_t predicate) const noexcept {
if (auto search = keys_.find(key); search != keys_.end()) {
return predicate(search->second);
}
return false;
}
// ----------------------------------------------------------------------------
#if 0
namespace {
void keyboard_cb(GLFWwindow *window, int key, int, int action, int) {
// [temporary]
if ((key >= GLFW_KEY_KP_0) && (key <= GLFW_KEY_KP_9)) {
s_Global.bKeypad |= (action == GLFW_PRESS);
s_Global.bKeypad &= (action != GLFW_RELEASE);
}
// When the UI capture keyboard, don't process it.
ImGuiIO& io = ImGui::GetIO();
if (io.WantCaptureKeyboard || io.WantCaptureMouse) {
io.KeysDown[key] = (action == GLFW_PRESS);
io.KeyCtrl = io.KeysDown[GLFW_KEY_LEFT_CONTROL] || io.KeysDown[GLFW_KEY_RIGHT_CONTROL];
io.KeyShift = io.KeysDown[GLFW_KEY_LEFT_SHIFT] || io.KeysDown[GLFW_KEY_RIGHT_SHIFT];
io.KeyAlt = io.KeysDown[GLFW_KEY_LEFT_ALT] || io.KeysDown[GLFW_KEY_RIGHT_ALT];
io.KeySuper = io.KeysDown[GLFW_KEY_LEFT_SUPER] || io.KeysDown[GLFW_KEY_RIGHT_SUPER];
//return;
}
UpdateButton(key, action, GLFW_KEY_LEFT_CONTROL, s_Global.bLeftCtrl);
UpdateButton(key, action, GLFW_KEY_LEFT_ALT, s_Global.bLeftAlt);
UpdateButton(key, action, GLFW_KEY_LEFT_SHIFT, s_Global.bLeftShift);
}
} // namespace
// ----------------------------------------------------------------------------
#endif
| 28.992958 | 118 | 0.63845 | tcoppex |
1bea047d1eaa1f89b50ad105e7e550ee6f5e9005 | 5,063 | cpp | C++ | obvclip/tests/test_convex_polytope.cpp | javierdelapuente/tfm_ode_bullet | cc0d40b9a91e43b5045c10903b5244e680d909ef | [
"Zlib"
] | 1 | 2021-04-08T11:22:13.000Z | 2021-04-08T11:22:13.000Z | obvclip/tests/test_convex_polytope.cpp | javierdelapuente/tfm_ode_bullet | cc0d40b9a91e43b5045c10903b5244e680d909ef | [
"Zlib"
] | null | null | null | obvclip/tests/test_convex_polytope.cpp | javierdelapuente/tfm_ode_bullet | cc0d40b9a91e43b5045c10903b5244e680d909ef | [
"Zlib"
] | null | null | null | #include "gtest/gtest.h"
#include <fstream>
#include "polytope.hpp"
#include "polytope_examples.hpp"
using namespace OB;
TEST(TESTConvexPolytope, basicTest) {
std::vector<Point> points;
points.push_back(Point(-1, -1, -1));
points.push_back(Point(-1, -1, 1));
points.push_back(Point(-1, 1, -1));
points.push_back(Point(-1, 1, 1));
points.push_back(Point(1, -1, -1));
points.push_back(Point(1, -1, 1));
points.push_back(Point(1, 1, -1));
points.push_back(Point(1, 1, 1));
ConvexPolytope poly;
poly.generate_from_vertices(points);
ASSERT_EQ(poly.euler_number_correct(), true);
//TODO ASSERT, 8 VERTICES, 6 FACES
//TODO CHECK ONE FACE CCW.
//TODO ASSERT EULER NUMBER
std::vector<std::pair<Feature, Plane>> allfacesplanes = poly.get_faces_with_planes();
ASSERT_EQ(allfacesplanes.size(), 6);
Feature f0 = allfacesplanes[0].first;
ASSERT_EQ(poly.get_face_edgepoints(f0).size(), 4);
ASSERT_EQ(poly.get_scan_face(f0).size(), 8);
std::cout << poly << std::endl;
}
TEST(TESTConvexPolytope, testPrismPolytope) {
std::shared_ptr<OB::ConvexPolytope> prism = std::make_shared<OB::ConvexPolytope>(create_prism_polytope (3));
//std::cout << "PRISM: " << *prism << std::endl;
}
TEST(TESTConvexPolytope, shortestBetweenPointEdge) {
// distance equal segment and line
Point point{1,1,1};
Point tail{7, 7, 7};
Point head{1, 0, -1};
Vector director = head - tail;
EdgePoints edge {tail, head};
std::cout << "distance from point " << point.transpose()
<< " to segment: " << edge << std::endl;
ASSERT_FLOAT_EQ(dist_point_edge(point, edge), 1.2040201117631721);
// now one in which the distance is smaller in the head
head = head + (tail - director*0.3);
edge = EdgePoints{tail, head};
std::cout << "distance from point " << point.transpose()
<< " to segment: " << edge << std::endl;
ASSERT_FLOAT_EQ(dist_point_edge(point, edge), 10.392304);
// now one in which the distance is smaller in the tail
head = Point{1, 0, -1} + (tail + director*10);
tail = tail + (tail + director*10);
edge = EdgePoints{tail, head};
std::cout << "distance from point " << point.transpose()
<< " to segment: " << edge << std::endl;
ASSERT_FLOAT_EQ(dist_point_edge(point, edge), 99.73465);
// one with the point in the line
point = Point {1,1,1};
edge = EdgePoints{{0,1,1}, {2,1,1}};
ASSERT_FLOAT_EQ(dist_point_edge(point, edge), 0.0);
// one with the point in the line not in segment
point = Point {0,1,1};
edge = EdgePoints{{1,1,1}, {2,1,1}};
ASSERT_FLOAT_EQ(dist_point_edge(point, edge), 1.0);
}
TEST(TESTConvexPolytope, shortestBetweenEdgeEdge) {
// for line - line, we can use https://keisan.casio.com/exec/system/1223531414#
// caso degenerado, segmentos paralelos
EdgePoints edge1{Point{0, 0, 1}, Point{0, 2, 1}};
EdgePoints edge2{Point{1, 1, 0}, Point{1, -1, 0}};
std::cout << "distance from segment: " << edge1
<< " to segment: " << edge2 << std::endl;
ASSERT_FLOAT_EQ(dist_edge_edge(edge1, edge2), 1.4142135);
// otro caso degenerado, pero el punto mas cercano
// no pertenece a los segmentos.
edge1 = EdgePoints{Point{0, 0, 1}, Point{0, 2, 1}};
edge2 = EdgePoints{Point{1, -1, 0}, Point{1, -2, 0}};
std::cout << "distance from segment: " << edge1
<< " to segment: " << edge2 << std::endl;
ASSERT_FLOAT_EQ(dist_edge_edge(edge1, edge2), 1.7320508);
// mismo segmento
edge1 = EdgePoints{Point{0, 0, 1}, Point{0, 2, 1}};
edge2 = EdgePoints{Point{0, 0, 1}, Point{0, 2, 1}};
std::cout << "distance from segment: " << edge1
<< " to segment: " << edge2 << std::endl;
ASSERT_FLOAT_EQ(dist_edge_edge(edge1, edge2), 0.0);
// minimum points inside both segments
edge1 = EdgePoints{Point{0,4,2}, Point{0,0,2}};
edge2 = EdgePoints{Point{-1,3,0}, Point{2,0,0}};
std::cout << "distance from segment: " << edge1
<< " to segment: " << edge2 << std::endl;
ASSERT_FLOAT_EQ(dist_edge_edge(edge1, edge2), 2.0);
// minimum points in only one segment and one of the edges
edge1 = EdgePoints{Point{0,1.5,2}, Point{0,0,2}};
edge2 = EdgePoints{Point{-1,3,0}, Point{2,0,0}};
std::cout << "distance from segment: " << edge1
<< " to segment: " << edge2 << std::endl;
ASSERT_FLOAT_EQ(dist_edge_edge(edge1, edge2), 2.0310097);
// minimum points in two edge points
edge1 = EdgePoints{Point{0,0,1}, Point{0,0,0}};
edge2 = EdgePoints{Point{1,1,-1}, Point{1,2,-1}};
std::cout << "distance from segment: " << edge1
<< " to segment: " << edge2 << std::endl;
ASSERT_FLOAT_EQ(dist_edge_edge(edge1, edge2), 1.7320508);
}
TEST(TESTConvexPolytope, readwritefromfile) {
std::ostringstream oss;
OB::ConvexPolytope tetrahedron = create_tetrahedron_polytope(1.0);
tetrahedron.write(oss);
std::string first = oss.str();
std::istringstream iss{first};
OB::ConvexPolytope leido = OB::ConvexPolytope::create(iss);
std::ostringstream oss2;
leido.write(oss2);
std::string second = oss2.str();
ASSERT_EQ(first, second);
}
| 32.455128 | 110 | 0.6508 | javierdelapuente |
1bea19058f4b17ba0b19109b788f5a10cc5e9a62 | 1,269 | cc | C++ | Mu2eUtilities/src/RandomUnitSphere.cc | resnegfk/Offline | 4ba81dad54486188fa83fea8c085438d104afbbc | [
"Apache-2.0"
] | 9 | 2020-03-28T00:21:41.000Z | 2021-12-09T20:53:26.000Z | Mu2eUtilities/src/RandomUnitSphere.cc | resnegfk/Offline | 4ba81dad54486188fa83fea8c085438d104afbbc | [
"Apache-2.0"
] | 684 | 2019-08-28T23:37:43.000Z | 2022-03-31T22:47:45.000Z | Mu2eUtilities/src/RandomUnitSphere.cc | resnegfk/Offline | 4ba81dad54486188fa83fea8c085438d104afbbc | [
"Apache-2.0"
] | 61 | 2019-08-16T23:28:08.000Z | 2021-12-20T08:29:48.000Z | //
// Return CLHEP::Hep3Vector objects that are unit vectors uniformly
// distributed over the unit sphere.
//
//
// Original author Rob Kutschke
//
#include "Offline/Mu2eUtilities/inc/RandomUnitSphere.hh"
#include "Offline/Mu2eUtilities/inc/ThreeVectorUtil.hh"
namespace CLHEP { class HepRandomEngine; }
using CLHEP::Hep3Vector;
using CLHEP::RandFlat;
namespace mu2e{
RandomUnitSphere::RandomUnitSphere( CLHEP::HepRandomEngine& engine,
double czmin,
double czmax,
double phimin,
double phimax):
_czmin(czmin),
_czmax(czmax),
_phimin(phimin),
_phimax(phimax),
_randFlat( engine ){
}
RandomUnitSphere::RandomUnitSphere( CLHEP::HepRandomEngine& engine,
const RandomUnitSphereParams& pars):
_czmin(pars.czmin),
_czmax(pars.czmax),
_phimin(pars.phimin),
_phimax(pars.phimax),
_randFlat( engine ){
}
CLHEP::Hep3Vector RandomUnitSphere::fire(){
double cz = _czmin + ( _czmax - _czmin )*_randFlat.fire();
double phi = _phimin + ( _phimax - _phimin )*_randFlat.fire();
return polar3Vector ( 1., cz, phi);
}
}
| 25.897959 | 74 | 0.602049 | resnegfk |
1bec1a22f7bc14d6dffd47b2898b401dc7ba0a90 | 1,818 | cpp | C++ | BFLib/src/BFFileHelper.cpp | McGill-DMaS/Privacy-ITSA | ff1fc65d01660f38530256e8661831b0d3020e6e | [
"CC0-1.0"
] | null | null | null | BFLib/src/BFFileHelper.cpp | McGill-DMaS/Privacy-ITSA | ff1fc65d01660f38530256e8661831b0d3020e6e | [
"CC0-1.0"
] | null | null | null | BFLib/src/BFFileHelper.cpp | McGill-DMaS/Privacy-ITSA | ff1fc65d01660f38530256e8661831b0d3020e6e | [
"CC0-1.0"
] | 1 | 2020-09-15T01:45:28.000Z | 2020-09-15T01:45:28.000Z | //---------------------------------------------------------------------------
// File:
// BFFileHelper.cpp BFFileHelper.hpp
//
// Module:
// CBFFileHelper
//
// History:
// May. 7, 2002 Created by Benjamin Fung
//---------------------------------------------------------------------------
#include "BFPch.h"
#if !defined(BFFILEHELPER_H)
#include "BFFileHelper.h"
#endif
//--------------------------------------------------------------------
//--------------------------------------------------------------------
CBFFileHelper::CBFFileHelper()
{
}
CBFFileHelper::~CBFFileHelper()
{
}
//--------------------------------------------------------------------
//--------------------------------------------------------------------
bool CBFFileHelper::removeFile(LPCTSTR filename)
{
return _tremove(filename) == 0;
}
//--------------------------------------------------------------------
//--------------------------------------------------------------------
void CBFFileHelper::splitPath(LPCTSTR fullPath, CString& drive, CString& dir, CString& fname, CString& ext)
{
TCHAR tDrive[_MAX_DRIVE];
TCHAR tDir[_MAX_DIR];
TCHAR tFname[_MAX_FNAME];
TCHAR tExt[_MAX_EXT];
_tsplitpath_s(fullPath, tDrive, tDir, tFname, tExt);
drive = tDrive;
dir = tDir;
fname = tFname;
ext = tExt;
}
//--------------------------------------------------------------------
//--------------------------------------------------------------------
bool CBFFileHelper::replaceExtension(LPCTSTR fname, LPCTSTR ext, CString& res)
{
res = fname;
int dotPos = res.ReverseFind(TCHAR('.'));
if (dotPos == -1) {
res.Empty();
return false;
}
res = res.Left(dotPos + 1);
res += ext;
return true;
} | 28.40625 | 108 | 0.366887 | McGill-DMaS |
1bf3169b42d205aefeeb0ccad8c4a13d4c1f0bb7 | 2,742 | hpp | C++ | wsi/surface_properties.hpp | xytovl/vulkan-wsi-layer | 4030ab0c70d301695c2aaf42ac98e97184ad79d3 | [
"MIT"
] | 2 | 2021-03-27T15:18:26.000Z | 2021-03-27T15:18:27.000Z | wsi/surface_properties.hpp | xytovl/vulkan-wsi-layer | 4030ab0c70d301695c2aaf42ac98e97184ad79d3 | [
"MIT"
] | null | null | null | wsi/surface_properties.hpp | xytovl/vulkan-wsi-layer | 4030ab0c70d301695c2aaf42ac98e97184ad79d3 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2017-2019, 2021 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @file surface_properties.hpp
*
* @brief Vulkan WSI surface query interfaces.
*/
#pragma once
#include <vulkan/vulkan.h>
#include <util/extension_list.hpp>
namespace wsi
{
/**
* @brief The base surface property query interface.
*/
class surface_properties
{
public:
/**
* @brief Implementation of vkGetPhysicalDeviceSurfaceCapabilitiesKHR for the specific VkSurface type.
*/
virtual VkResult get_surface_capabilities(VkPhysicalDevice physical_device, VkSurfaceKHR surface,
VkSurfaceCapabilitiesKHR *surface_capabilities) = 0;
/**
* @brief Implementation of vkGetPhysicalDeviceSurfaceFormatsKHR for the specific VkSurface type.
*/
virtual VkResult get_surface_formats(VkPhysicalDevice physical_device, VkSurfaceKHR surface,
uint32_t *surface_format_count, VkSurfaceFormatKHR *surface_formats) = 0;
/**
* @brief Implementation of vkGetPhysicalDeviceSurfacePresentModesKHR for the specific VkSurface type.
*/
virtual VkResult get_surface_present_modes(VkPhysicalDevice physical_device, VkSurfaceKHR surface,
uint32_t *present_mode_count, VkPresentModeKHR *present_modes) = 0;
/**
* @brief Return the device extensions that this surface_properties implementation needs.
*/
virtual const util::extension_list &get_required_device_extensions()
{
static const util::extension_list empty{util::allocator::get_generic()};
return empty;
}
};
} /* namespace wsi */
| 37.054054 | 113 | 0.724654 | xytovl |
1bf47543d28e2addda492c2fa7444505064439ae | 8,601 | ipp | C++ | rice/Data_Type.ipp | keyme/rice | 4b5e4ad3e2294a1b58886fb946eb26e3512599d9 | [
"BSD-2-Clause"
] | 11 | 2015-02-09T12:13:45.000Z | 2019-11-25T01:14:31.000Z | rice/Data_Type.ipp | jsomers/rice | 6bbcc2dd85d010a1108a4d7ac7ece39b1c1210f5 | [
"BSD-2-Clause"
] | null | null | null | rice/Data_Type.ipp | jsomers/rice | 6bbcc2dd85d010a1108a4d7ac7ece39b1c1210f5 | [
"BSD-2-Clause"
] | 2 | 2019-11-25T01:14:35.000Z | 2021-09-29T04:57:36.000Z | #ifndef Rice__Data_Type__ipp_
#define Rice__Data_Type__ipp_
#include "Class.hpp"
#include "String.hpp"
#include "Data_Object.hpp"
#include "detail/default_allocation_func.hpp"
#include "detail/creation_funcs.hpp"
#include "detail/method_data.hpp"
#include "detail/Caster.hpp"
#include "detail/demangle.hpp"
#include <stdexcept>
#include <typeinfo>
template<typename T>
VALUE Rice::Data_Type<T>::klass_ = Qnil;
template<typename T>
std::auto_ptr<Rice::detail::Abstract_Caster> Rice::Data_Type<T>::caster_;
template<typename T>
template<typename Base_T>
inline Rice::Data_Type<T> Rice::Data_Type<T>::
bind(Module const & klass)
{
if(klass.value() == klass_)
{
return Data_Type<T>();
}
if(is_bound())
{
std::string s;
s = "Data type ";
s += detail::demangle(typeid(T).name());
s += " is already bound to a different type";
throw std::runtime_error(s.c_str());
}
// TODO: Make sure base type is bound; throw an exception otherwise.
// We can't do this just yet, because we don't have a specialization
// for binding to void.
klass_ = klass;
// TODO: do we need to unregister when the program exits? we have to
// be careful if we do, because the ruby interpreter might have
// already shut down. The correct behavior is probably to register an
// exit proc with the interpreter, so the proc gets called before the
// GC shuts down.
rb_gc_register_address(&klass_);
for(typename Instances::iterator it = unbound_instances().begin(),
end = unbound_instances().end();
it != end;
unbound_instances().erase(it++))
{
(*it)->set_value(klass);
}
detail::Abstract_Caster * base_caster = Data_Type<Base_T>().caster();
caster_.reset(new detail::Caster<T, Base_T>(base_caster, klass));
Data_Type_Base::casters().insert(std::make_pair(klass, caster_.get()));
return Data_Type<T>();
}
template<typename T>
inline Rice::Data_Type<T>::
Data_Type()
: Module_impl<Data_Type_Base, Data_Type<T> >(
klass_ == Qnil ? rb_cObject : klass_)
{
if(!is_bound())
{
unbound_instances().insert(this);
}
}
template<typename T>
inline Rice::Data_Type<T>::
Data_Type(Module const & klass)
: Module_impl<Data_Type_Base, Data_Type<T> >(
klass)
{
this->bind<void>(klass);
}
template<typename T>
inline Rice::Data_Type<T>::
~Data_Type()
{
unbound_instances().erase(this);
}
template<typename T>
Rice::Module
Rice::Data_Type<T>::
klass() {
if(is_bound())
{
return klass_;
}
else
{
std::string s;
s += detail::demangle(typeid(T *).name());
s += " is unbound";
throw std::runtime_error(s.c_str());
}
}
template<typename T>
Rice::Data_Type<T> & Rice::Data_Type<T>::
operator=(Module const & klass)
{
this->bind<void>(klass);
return *this;
}
template<typename T>
template<typename Constructor_T>
inline Rice::Data_Type<T> & Rice::Data_Type<T>::
define_constructor(
Constructor_T /* constructor */,
Arguments* arguments)
{
check_is_bound();
// Normal constructor pattern with new/initialize
rb_define_alloc_func(
static_cast<VALUE>(*this),
detail::default_allocation_func<T>);
this->define_method(
"initialize",
&Constructor_T::construct,
arguments
);
return *this;
}
template<typename T>
template<typename Constructor_T>
inline Rice::Data_Type<T> & Rice::Data_Type<T>::
define_constructor(
Constructor_T constructor,
Arg const& arg)
{
Arguments* args = new Arguments();
args->add(arg);
return define_constructor(constructor, args);
}
template<typename T>
template<typename Director_T>
inline Rice::Data_Type<T>& Rice::Data_Type<T>::
define_director()
{
Rice::Data_Type<Director_T>::template bind<T>(*this);
return *this;
}
template<typename T>
inline T * Rice::Data_Type<T>::
from_ruby(Object x)
{
check_is_bound();
void * v = DATA_PTR(x.value());
Class klass = x.class_of();
if(klass.value() == klass_)
{
// Great, not converting to a base/derived type
Data_Type<T> data_klass;
Data_Object<T> obj(x, data_klass);
return obj.get();
}
Data_Type_Base::Casters::const_iterator it = Data_Type_Base::casters().begin();
Data_Type_Base::Casters::const_iterator end = Data_Type_Base::casters().end();
// Finding the bound type that relates to the given klass is
// a two step process. We iterate over the list of known type casters,
// looking for:
//
// 1) casters that handle this direct type
// 2) casters that handle types that are ancestors of klass
//
// Step 2 allows us to handle the case where a Rice-wrapped class
// is subclassed in Ruby but then an instance of that class is passed
// back into C++ (say, in a Listener / callback construction)
//
VALUE ancestors = rb_mod_ancestors(klass.value());
long earliest = RARRAY_LEN(ancestors) + 1;
int index;
VALUE indexFound;
Data_Type_Base::Casters::const_iterator toUse = end;
for(; it != end; it++) {
// Do we match directly?
if(klass.value() == it->first) {
toUse = it;
break;
}
// Check for ancestors. Trick is, we need to find the lowest
// ancestor that does have a Caster to make sure that we're casting
// to the closest C++ type that the Ruby class is subclassing.
// There might be multiple ancestors that are also wrapped in
// the extension, so find the earliest in the list and use that one.
indexFound = rb_funcall(ancestors, rb_intern("index"), 1, it->first);
if(indexFound != Qnil) {
index = NUM2INT(indexFound);
if(index < earliest) {
earliest = index;
toUse = it;
}
}
}
if(toUse == end)
{
std::string s = "Class ";
s += klass.name().str();
s += " is not registered/bound in Rice";
throw std::runtime_error(s);
}
detail::Abstract_Caster * caster = toUse->second;
if(caster)
{
T * result = static_cast<T *>(caster->cast_to_base(v, klass_));
return result;
}
else
{
return static_cast<T *>(v);
}
}
template<typename T>
inline bool Rice::Data_Type<T>::
is_bound()
{
return klass_ != Qnil;
}
template<typename T>
inline Rice::detail::Abstract_Caster * Rice::Data_Type<T>::
caster() const
{
check_is_bound();
return caster_.get();
}
namespace Rice
{
template<>
inline detail::Abstract_Caster * Data_Type<void>::
caster() const
{
return 0;
}
template<typename T>
void Data_Type<T>::
check_is_bound()
{
if(!is_bound())
{
std::string s;
s = "Data type ";
s += detail::demangle(typeid(T).name());
s += " is not bound";
throw std::runtime_error(s.c_str());
}
}
} // Rice
template<typename T>
inline Rice::Data_Type<T> Rice::
define_class_under(
Object module,
char const * name)
{
Class c(define_class_under(module, name, rb_cObject));
c.undef_creation_funcs();
return Data_Type<T>::template bind<void>(c);
}
template<typename T, typename Base_T>
inline Rice::Data_Type<T> Rice::
define_class_under(
Object module,
char const * name)
{
Data_Type<Base_T> base_dt;
Class c(define_class_under(module, name, base_dt));
c.undef_creation_funcs();
return Data_Type<T>::template bind<Base_T>(c);
}
template<typename T>
inline Rice::Data_Type<T> Rice::
define_class(
char const * name)
{
Class c(define_class(name, rb_cObject));
c.undef_creation_funcs();
return Data_Type<T>::template bind<void>(c);
}
template<typename T, typename Base_T>
inline Rice::Data_Type<T> Rice::
define_class(
char const * name)
{
Data_Type<Base_T> base_dt;
Class c(define_class(name, base_dt));
c.undef_creation_funcs();
return Data_Type<T>::template bind<Base_T>(c);
}
template<typename From_T, typename To_T>
inline void
Rice::define_implicit_cast()
{
// As Rice currently expects only one entry into
// this list for a given klass VALUE, we need to get
// the current caster for From_T and insert in our
// new caster as the head of the caster list
Class from_class = Data_Type<From_T>::klass().value();
Class to_class = Data_Type<To_T>::klass().value();
detail::Abstract_Caster* from_caster =
Data_Type<From_T>::caster_.release();
detail::Abstract_Caster* new_caster =
new detail::Implicit_Caster<To_T, From_T>(from_caster, to_class);
// Insert our new caster into the list for the from class
Data_Type_Base::casters().erase(from_class);
Data_Type_Base::casters().insert(
std::make_pair(
from_class,
new_caster
)
);
// And make sure the from_class has direct access to the
// updated caster list
Data_Type<From_T>::caster_.reset(new_caster);
}
#endif // Rice__Data_Type__ipp_
| 23.5 | 81 | 0.679921 | keyme |
1bf68601f4d5e4898fad071812db64978e2b0f4f | 597 | hpp | C++ | QQDemo/color_skin.hpp | auxs2015/DuiDesign | fb98c38dacae7d77a603a325f635135b54f3f898 | [
"BSD-2-Clause"
] | 11 | 2017-05-26T06:52:32.000Z | 2021-07-01T00:39:27.000Z | QQDemo/color_skin.hpp | auxs2015/DuiDesign | fb98c38dacae7d77a603a325f635135b54f3f898 | [
"BSD-2-Clause"
] | null | null | null | QQDemo/color_skin.hpp | auxs2015/DuiDesign | fb98c38dacae7d77a603a325f635135b54f3f898 | [
"BSD-2-Clause"
] | 24 | 2016-12-12T02:56:31.000Z | 2021-12-06T01:23:52.000Z | #ifndef COLORSKIN_HPP
#define COLORSKIN_HPP
class MainFrame;
using namespace DuiLib;
class ColorSkinWindow : public WindowImplBase
{
public:
ColorSkinWindow(MainFrame* main_frame, RECT rcParentWindow);
LPCTSTR GetWindowClassName() const;
virtual void OnFinalMessage(HWND hWnd);
void Notify(TNotifyUI& msg);
virtual void InitWindow();
virtual CDuiString GetSkinFile();
virtual CDuiString GetSkinFolder();
virtual LRESULT OnKillFocus(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
private:
RECT parent_window_rect_;
MainFrame* main_frame_;
};
#endif // COLORSKIN_HPP | 18.65625 | 86 | 0.788945 | auxs2015 |
1bfb951530f712545adc5d4d58f1d520c9b5314d | 11,690 | hpp | C++ | heart/test/extended_bidomain/TestExtendedBidomainProblem.hpp | mdp19pn/Chaste | f7b6bafa64287d567125b587b29af6d8bd7aeb90 | [
"Apache-2.0",
"BSD-3-Clause"
] | 100 | 2015-02-23T08:32:23.000Z | 2022-02-25T11:39:26.000Z | heart/test/extended_bidomain/TestExtendedBidomainProblem.hpp | mdp19pn/Chaste | f7b6bafa64287d567125b587b29af6d8bd7aeb90 | [
"Apache-2.0",
"BSD-3-Clause"
] | 11 | 2017-06-14T13:48:43.000Z | 2022-03-10T10:42:07.000Z | heart/test/extended_bidomain/TestExtendedBidomainProblem.hpp | mdp19pn/Chaste | f7b6bafa64287d567125b587b29af6d8bd7aeb90 | [
"Apache-2.0",
"BSD-3-Clause"
] | 53 | 2015-02-23T13:52:44.000Z | 2022-02-28T18:57:35.000Z | /*
Copyright (c) 2005-2021, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
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 University of Oxford 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.
*/
#ifndef _TESTEXTENDEDBIDOMAINPROBLEM_HPP_
#define _TESTEXTENDEDBIDOMAINPROBLEM_HPP_
#include "UblasIncludes.hpp"
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include "PetscSetupAndFinalize.hpp"
#include "HeartConfig.hpp"
#include "SimpleStimulus.hpp"
#include "CorriasBuistSMCModified.hpp"
#include "CorriasBuistICCModified.hpp"
#include "CompareHdf5ResultsFiles.hpp"
#include "ExtendedBidomainProblem.hpp"
#include "PlaneStimulusCellFactory.hpp"
#include "LuoRudy1991.hpp"
#include "FaberRudy2000.hpp"
#include "OutputFileHandler.hpp"
#include "Hdf5DataReader.hpp"
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
class ICC_Cell_factory : public AbstractCardiacCellFactory<1>
{
public:
ICC_Cell_factory() : AbstractCardiacCellFactory<1>()
{
}
AbstractCardiacCell* CreateCardiacCellForTissueNode(Node<1>* pNode)
{
CorriasBuistICCModified *cell;
cell = new CorriasBuistICCModified(mpSolver, mpZeroStimulus);
double x = pNode->rGetLocation()[0];
double IP3_initial = 0.00067;
double IP3_final = 0.00065;
double cable_length = 10.0;
//calculate the concentration gradient...
double IP3_conc = IP3_initial + x*(IP3_final - IP3_initial)/cable_length;
//..and set it
cell->SetIP3Concentration(IP3_conc);
cell->SetFractionOfVDDRInPU(0.04);
return cell;
}
};
class SMC_Cell_factory : public AbstractCardiacCellFactory<1>
{
public:
SMC_Cell_factory() : AbstractCardiacCellFactory<1>()
{
}
AbstractCardiacCell* CreateCardiacCellForTissueNode(Node<1>* pNode)
{
CorriasBuistSMCModified *cell;
cell = new CorriasBuistSMCModified(mpSolver, mpZeroStimulus);
cell->SetFakeIccStimulusPresent(false);//it will get it from the real ICC, via gap junction
return cell;
}
};
class TestExtendedBidomainProblem: public CxxTest::TestSuite
{
public:
void SetupParameters()
{
HeartConfig::Instance()->Reset();
HeartConfig::Instance()->SetIntracellularConductivities(Create_c_vector(5.0));
HeartConfig::Instance()->SetExtracellularConductivities(Create_c_vector(1.0));
HeartConfig::Instance()->SetOdePdeAndPrintingTimeSteps(0.1,0.1,10.0);
//HeartConfig::Instance()->SetKSPSolver("gmres");
HeartConfig::Instance()->SetUseAbsoluteTolerance(1e-5);
HeartConfig::Instance()->SetKSPPreconditioner("bjacobi");
}
/**
* This test is aimed at comparing the extended bidomain implementation in Chaste with
* the original Finite Difference code developed by Martin Buist.
*
* All the parameters are chosen to replicate the same conditions as in his code.
*/
void TestExtendedProblemVsMartincCode()
{
SetupParameters();
TetrahedralMesh<1,1> mesh;
unsigned number_of_elements = 100;//this is nGrid in Martin's code
double length = 10.0;//100mm as in Martin's code
mesh.ConstructRegularSlabMesh(length/number_of_elements, length);
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), number_of_elements + 1);
double Am_icc = 1000.0;
double Am_smc = 1000.0;
double Am_gap = 1.0;
double Cm_icc = 1.0;
double Cm_smc = 1.0;
double G_gap = 20.0;//mS/cm^2
HeartConfig::Instance()->SetSimulationDuration(1000.0); //ms.
ICC_Cell_factory icc_factory;
SMC_Cell_factory smc_factory;
std::string dir = "ICCandSMC";
std::string filename = "extended1d";
HeartConfig::Instance()->SetOutputDirectory(dir);
HeartConfig::Instance()->SetOutputFilenamePrefix(filename);
ExtendedBidomainProblem<1> extended_problem( &icc_factory , &smc_factory);
extended_problem.SetMesh(&mesh);
extended_problem.SetExtendedBidomainParameters(Am_icc,Am_smc, Am_gap, Cm_icc, Cm_smc, G_gap);
extended_problem.SetIntracellularConductivitiesForSecondCell(Create_c_vector(1.0));
std::vector<unsigned> outputnodes;
outputnodes.push_back(50u);
HeartConfig::Instance()->SetRequestedNodalTimeTraces(outputnodes);
extended_problem.Initialise();
extended_problem.Solve();
HeartEventHandler::Headings();
HeartEventHandler::Report();
/**
* Compare with valid data.
* As Martin's code is an FD code, results will never match exactly.
* The comparison below is done against a 'valid' h5 file.
*
* The h5 file (1DValid.h5) is a Chaste (old phi_i formulation) file with is valid because, when extrapolating results from it, they look very similar
* (except for a few points at the end of the upstroke) to the results taken
* directly from Martin's code.
* A plot of Chaste results versus Martin's result (at node 50) is stored
* in the file 1DChasteVsMartin.eps for reference.
*
* A second plot comparing the old formulation (with phi_i) to the new formulation with V_m is contained in
*.1DChasteNewFormulation.png
*
*/
TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/extendedbidomain", "1DValid", false,
dir, filename, true,
0.2));
/*
* Here we compare the new formulation (V_m1, V_m2, phi_e)
* with the previous formulation (phi_i1, phi_i2, phi_e) running with GMRES and an absolute KSP tolerance of 1e-8.
*/
TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/extendedbidomain", "extended1d_previous_chaste_formulation_abs_tol_1e-8", false,
dir, filename, true,
1e-2));
}
// Test the functionality for outputting the values of requested cell state variables
void TestExtendedBidomainProblemPrintsMultipleVariables()
{
// Get the singleton in a clean state
HeartConfig::Instance()->Reset();
// Set configuration file
std::string dir = "ExtBidoMultiVars";
std::string filename = "extended";
HeartConfig::Instance()->SetOutputDirectory(dir);
HeartConfig::Instance()->SetOutputFilenamePrefix(filename);
HeartConfig::Instance()->SetSimulationDuration(0.1);
// HeartConfig::Instance()->SetKSPSolver("gmres");
HeartConfig::Instance()->SetUseAbsoluteTolerance(2e-4);
HeartConfig::Instance()->SetKSPPreconditioner("jacobi");
/** Check that also the converters handle multiple variables**/
HeartConfig::Instance()->SetVisualizeWithCmgui(true);
HeartConfig::Instance()->SetVisualizeWithMeshalyzer(true);
TetrahedralMesh<1,1> mesh;
unsigned number_of_elements = 100;
double length = 10.0;
mesh.ConstructRegularSlabMesh(length/number_of_elements, length);
// Override the variables we are interested in writing.
std::vector<std::string> output_variables;
output_variables.push_back("calcium_dynamics__Ca_NSR");
output_variables.push_back("ionic_concentrations__Nai");
output_variables.push_back("fast_sodium_current_j_gate__j");
output_variables.push_back("ionic_concentrations__Ki");
HeartConfig::Instance()->SetOutputVariables( output_variables );
// Set up problem
PlaneStimulusCellFactory<CellFaberRudy2000FromCellML, 1> cell_factory_1(-60, 0.5);
PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 1> cell_factory_2(0.0,0.5);
ExtendedBidomainProblem<1> ext_problem( &cell_factory_1, &cell_factory_2 );
ext_problem.SetMesh(&mesh);
// Solve
ext_problem.Initialise();
ext_problem.Solve();
// Get a reference to a reader object for the simulation results
Hdf5DataReader data_reader1 = ext_problem.GetDataReader();
std::vector<double> times = data_reader1.GetUnlimitedDimensionValues();
// Check there is information about 11 timesteps (0, 0.01, 0.02, ...)
unsigned num_steps = 11u;
TS_ASSERT_EQUALS( times.size(), num_steps);
TS_ASSERT_DELTA( times[0], 0.0, 1e-12);
TS_ASSERT_DELTA( times[1], 0.01, 1e-12);
TS_ASSERT_DELTA( times[2], 0.02, 1e-12);
TS_ASSERT_DELTA( times[3], 0.03, 1e-12);
// There should be 11 values per variable and node.
std::vector<double> node_5_v = data_reader1.GetVariableOverTime("V", 5);
TS_ASSERT_EQUALS( node_5_v.size(), num_steps);
std::vector<double> node_5_v_2 = data_reader1.GetVariableOverTime("V_2", 5);
TS_ASSERT_EQUALS( node_5_v_2.size(), num_steps);
std::vector<double> node_5_phi = data_reader1.GetVariableOverTime("Phi_e", 5);
TS_ASSERT_EQUALS( node_5_phi.size(), num_steps);
for (unsigned i=0; i<output_variables.size(); i++)
{
unsigned global_index = 2+i*2;
std::vector<double> values = data_reader1.GetVariableOverTime(output_variables[i], global_index);
TS_ASSERT_EQUALS( values.size(), num_steps);
// Check the last values match the cells' state
if (ext_problem.rGetMesh().GetDistributedVectorFactory()->IsGlobalIndexLocal(global_index))
{
AbstractCardiacCellInterface* p_cell = ext_problem.GetTissue()->GetCardiacCell(global_index);
TS_ASSERT_DELTA(values.back(), p_cell->GetAnyVariable(output_variables[i],0), 1e-12);
}
//check the extra files for extra variables are there (the content is tested in the converter's tests)
FileFinder file(dir + "/output/"+ filename +"_"+ output_variables[i] + ".dat", RelativeTo::ChasteTestOutput);
TS_ASSERT(file.Exists());
}
}
};
#endif /*_TESTEXTENDEDBIDOMAINPROBLEM_HPP_*/
| 40.731707 | 158 | 0.688452 | mdp19pn |
4005dae3af059be1fc2fcef53024776fd0e2429a | 6,436 | cpp | C++ | src/engine/toppane.cpp | FreeAllegiance/AllegianceDX7 | 3955756dffea8e7e31d3a55fcf6184232b792195 | [
"MIT"
] | 76 | 2015-08-18T19:18:40.000Z | 2022-01-08T12:47:22.000Z | src/engine/toppane.cpp | StudentAlleg/Allegiance | e91660a471eb4e57e9cea4c743ad43a82f8c7b18 | [
"MIT"
] | 37 | 2015-08-14T22:44:12.000Z | 2020-01-21T01:03:06.000Z | src/engine/toppane.cpp | StudentAlleg/Allegiance | e91660a471eb4e57e9cea4c743ad43a82f8c7b18 | [
"MIT"
] | 42 | 2015-08-13T23:31:35.000Z | 2022-03-17T02:20:26.000Z | #include "toppane.h"
#include "engine.h"
#include "enginep.h"
#include "surface.h"
/////////////////////////////////////////////////////////////////////////////
//
// TopPane
//
/////////////////////////////////////////////////////////////////////////////
class TopPaneSurfaceSite : public SurfaceSite {
private:
TopPane* m_ptopPane;
public:
TopPaneSurfaceSite(TopPane* ptopPane) :
m_ptopPane(ptopPane)
{
}
void UpdateSurface(Surface* psurface)
{
m_ptopPane->RepaintSurface();
}
};
/////////////////////////////////////////////////////////////////////////////
//
// TopPane
//
/////////////////////////////////////////////////////////////////////////////
TopPane::TopPane(Engine* pengine, bool bColorKey, TopPaneSite* psite, Pane* pchild) :
Pane(pchild),
m_pengine(pengine),
// m_psurface(pengine->CreateSurface(WinPoint(1, 1), stype, new TopPaneSurfaceSite(this))),
m_psurface(NULL),
m_psite(psite),
m_bColorKey(bColorKey),
m_bNeedLayout(true)
{ //Fix memory leak -Imago 8/2/09
SetSize(WinPoint(0, 0));
}
void TopPane::RepaintSurface()
{
m_bNeedPaint = true;
m_bPaintAll = true;
}
void TopPane::NeedLayout()
{
if (!m_bNeedLayout) {
m_bNeedLayout = true;
m_psite->SizeChanged();
}
}
void TopPane::NeedPaintInternal()
{
if (!m_bNeedPaint) {
m_bNeedPaint = true;
m_psite->SurfaceChanged();
}
}
void TopPane::Paint(Surface* psurface)
{
// psurface->FillSurface(Color(0.8f, 0.5f, 1.0f));
}
void TopPane::Evaluate()
{
if (m_bNeedLayout) {
m_bNeedLayout = false;
WinPoint sizeOld = GetSize();
UpdateLayout();
WinPoint sizeNew = GetSize();
// This creates the top level surface. Create a new render target for now.
if ( ( sizeNew != sizeOld ) && ( sizeNew != WinPoint(0,0) ) )
{
m_bNeedPaint = true;
m_bPaintAll = true;
/* if( sizeNew == CD3DDevice9::GetCurrentResolution() )
{
m_psurface = m_pengine->CreateDummySurface(
sizeNew,
new TopPaneSurfaceSite( this ) );
}
else*/
{
m_psurface = m_pengine->CreateRenderTargetSurface(
sizeNew,
new TopPaneSurfaceSite( this ) );
}
}
}
}
void TopPane::UpdateLayout()
{
DefaultUpdateLayout();
}
bool g_bPaintAll = false;
bool g_bUpdateOffset = false;
void TopPane::UpdateBits()
{
/* ORIGINAL ALLEGIANCE VERSION.
ZEnter("TopPane::UpdateBits()");
if (m_bNeedPaint) {
ZTrace("m_bNeedPaint == true");
if (CalcPaint()) {
m_bNeedPaint = true;
m_bPaintAll = true;
}
ZTrace("after CalcPaint() m_bNeedPaint ==" + ZString(m_bNeedPaint));
ZTrace("after CalcPaint() m_bPaintAll ==" + ZString(m_bPaintAll ));
m_bPaintAll |= g_bPaintAll;
InternalPaint(m_psurface);
m_bNeedPaint = false;
}
ZExit("TopPane::UpdateBits()");*/
ZEnter("TopPane::UpdateBits()");
{
HRESULT hr;
bool bRenderTargetRequired;
ZAssert(m_psurface != NULL);
PrivateSurface* pprivateSurface; CastTo(pprivateSurface, m_psurface);
bRenderTargetRequired = pprivateSurface->GetSurfaceType().Test(SurfaceTypeRenderTarget() ) == true;
if( bRenderTargetRequired == true )
{
TEXHANDLE hTexture = pprivateSurface->GetTexHandle( );
ZAssert( hTexture != INVALID_TEX_HANDLE );
hr = CVRAMManager::Get()->PushRenderTarget( hTexture );
}
ZTrace("m_bNeedPaint == true");
CalcPaint();
m_bNeedPaint = true;
m_bPaintAll = true;
ZTrace("after CalcPaint() m_bPaintAll ==" + ZString(m_bPaintAll ));
WinPoint offset( 0, 0 );
// Call InternalPaint() with the child offset and parent size as params and create initial clipping rect.
WinRect rectClip( 0,
0,
(int) m_psurface->GetSize().X(),
(int) m_psurface->GetSize().Y() );
m_bPaintAll |= g_bPaintAll;
InternalPaint( m_psurface );
m_bNeedPaint = false;
if( bRenderTargetRequired == true )
{
CVRAMManager::Get()->PopRenderTarget( );
}
}
ZExit("TopPane::UpdateBits()");
/* {
ZTrace("m_bNeedPaint == true");
CalcPaint();
m_bNeedPaint = true;
m_bPaintAll = true;
ZTrace("after CalcPaint() m_bNeedPaint ==" + ZString(m_bNeedPaint));
ZTrace("after CalcPaint() m_bPaintAll ==" + ZString(m_bPaintAll ));
m_bPaintAll |= g_bPaintAll;
// localOffset.SetY( localOffset.Y() - (int)m_psurface->GetSize().Y() );
// localOffset += globalOffset;
WinPoint offset( localOffset );
// Remove offset now.
offset.SetY( offset.Y() - (int)m_psurface->GetSize().Y() );
// Call InternalPaint() with the child offset and parent size as params and create initial clipping rect.
WinRect rectClip( offset.X(),
offset.Y(),
offset.X() + (int) m_psurface->GetSize().X(),
offset.Y() + (int) m_psurface->GetSize().Y() );
// m_psurface is a dummy surface. Store the context.
InternalPaint( m_psurface, offset, rectClip );
m_bNeedPaint = false;
}
ZExit("TopPane::UpdateBits()");*/
}
const WinPoint& TopPane::GetSurfaceSize()
{
Evaluate();
return GetSize();
}
Surface* TopPane::GetSurface()
{
Evaluate();
//when the size is zero, the surface is not initialized
if (m_size.X() == 0 || m_size.Y() == 0) {
return NULL;
}
UpdateBits();
return m_psurface;
}
Point TopPane::TransformLocalToImage(const WinPoint& point)
{
return
m_psite->TransformLocalToImage(
GetPanePoint(
Point::Cast(point)
)
);
}
Point TopPane::GetPanePoint(const Point& point)
{
return
Point(
point.X(),
(float)GetSize().Y() - 1.0f - point.Y()
);
}
void TopPane::MouseEnter(IInputProvider* pprovider, const Point& point)
{
// m_bInside = true;
/* if( m_psurface->GetSurfaceType().Test( SurfaceTypeDummy() ) == false )
{
OutputDebugString("MouseEnter\n");
}*/
}
MouseResult TopPane::HitTest(IInputProvider* pprovider, const Point& point, bool bCaptured)
{
return Pane::HitTest(pprovider, GetPanePoint(point), bCaptured);
}
MouseResult TopPane::Button(
IInputProvider* pprovider,
const Point& point,
int button,
bool bCaptured,
bool bInside,
bool bDown
) {
return Pane::Button(pprovider, GetPanePoint(point), button, bCaptured, bInside, bDown);
}
| 23.837037 | 107 | 0.596178 | FreeAllegiance |
40080cb4299d2abfbf73f362827597e3353b56cc | 2,091 | cpp | C++ | src/entities/splatmap.cpp | h4k1m0u/video | 4739f8b1b6c837c41fdb53fc7dea97a47b285d0b | [
"MIT"
] | 5 | 2021-11-11T23:59:38.000Z | 2022-03-24T02:10:40.000Z | src/entities/splatmap.cpp | h4k1m0u/video | 4739f8b1b6c837c41fdb53fc7dea97a47b285d0b | [
"MIT"
] | null | null | null | src/entities/splatmap.cpp | h4k1m0u/video | 4739f8b1b6c837c41fdb53fc7dea97a47b285d0b | [
"MIT"
] | 1 | 2022-01-15T13:31:10.000Z | 2022-01-15T13:31:10.000Z | #include <glm/gtc/matrix_transform.hpp>
#include "entities/splatmap.hpp"
#include "shader_exception.hpp"
#include "geometries/terrain.hpp"
Splatmap::Splatmap():
// terrain textures (used by same shader) need to be attached to different texture units
m_texture_terrain_water(Image("assets/images/terrain/water.jpg"), GL_TEXTURE0),
m_texture_terrain_grass(Image("assets/images/terrain/grass.jpg"), GL_TEXTURE1),
m_texture_terrain_rock(Image("assets/images/terrain/rock.jpg"), GL_TEXTURE2),
m_texture_terrain_splatmap(Image("assets/images/terrain/splatmap.png"), GL_TEXTURE3),
m_program("assets/shaders/light_terrain.vert", "assets/shaders/light_terrain.frag"),
m_image("assets/images/terrain/heightmap.png"),
m_vbo(Terrain(m_image)),
m_renderer(m_program, m_vbo, {{0, "position", 3, 8, 0}, {1, "normal", 3, 8, 3}, {2, "texture_coord", 2, 8, 6}})
{
// vertex or fragment shaders failed to compile
if (m_program.has_failed()) {
throw ShaderException();
}
}
/* delegate drawing with OpenGL (buffers & shaders) to renderer */
void Splatmap::draw(const Uniforms& uniforms) {
// draw terrain using triangle strips
glm::vec3 color_light(1.0f, 1.0f, 1.0f);
glm::vec3 position_light(10.0f, 6.0f, 6.0f);
m_renderer.draw(
{
{"texture2d_water", m_texture_terrain_water},
{"texture2d_grass", m_texture_terrain_grass},
{"texture2d_rock", m_texture_terrain_rock},
{"texture2d_splatmap", m_texture_terrain_splatmap},
{"light.position", position_light},
{"light.ambiant", 0.2f * color_light},
{"light.diffuse", 0.5f * color_light},
{"light.specular", color_light},
}, GL_TRIANGLE_STRIP
);
}
/* delegate transform to renderer */
void Splatmap::set_transform(const Transformation& t) {
m_renderer.set_transform(t);
}
/* Free textures, renderer (vao/vbo buffers), and shader program */
void Splatmap::free() {
m_image.free();
m_texture_terrain_water.free();
m_texture_terrain_grass.free();
m_texture_terrain_rock.free();
m_texture_terrain_splatmap.free();
m_program.free();
m_renderer.free();
}
| 34.278689 | 113 | 0.72023 | h4k1m0u |
400da1c8f4866d0d34f601c3de2a2f567e600191 | 498 | hpp | C++ | src/avif/Box.hpp | link-u/libavifparser | 17984420ff8806a6a852306b839219605ccc1628 | [
"MIT"
] | null | null | null | src/avif/Box.hpp | link-u/libavifparser | 17984420ff8806a6a852306b839219605ccc1628 | [
"MIT"
] | null | null | null | src/avif/Box.hpp | link-u/libavifparser | 17984420ff8806a6a852306b839219605ccc1628 | [
"MIT"
] | null | null | null | //
// Created by psi on 2019/11/24.
//
#pragma once
#include <optional>
#include <string>
namespace avif {
struct Box {
struct Header {
uint32_t offset = {};
uint32_t size = {};
uint32_t type = {};
[[ nodiscard ]] uint32_t end() const {
return this->offset + this->size;
}
};
public:
Header hdr = {};
public:
Box() = default;
Box(Box&&) = default;
Box(Box const&) = default;
Box& operator=(Box&&) = default;
Box& operator=(Box const&) = default;
};
}
| 15.5625 | 42 | 0.582329 | link-u |
400f04332708cf1d422cb448d5c0930846c4b1d4 | 14,333 | cpp | C++ | src/widgets/XMRigWidget.cpp | Midar/feather | ac9693077c338527a4b31ca6b2d85514f8fe739a | [
"BSD-3-Clause"
] | null | null | null | src/widgets/XMRigWidget.cpp | Midar/feather | ac9693077c338527a4b31ca6b2d85514f8fe739a | [
"BSD-3-Clause"
] | null | null | null | src/widgets/XMRigWidget.cpp | Midar/feather | ac9693077c338527a4b31ca6b2d85514f8fe739a | [
"BSD-3-Clause"
] | null | null | null | // SPDX-License-Identifier: BSD-3-Clause
// SPDX-FileCopyrightText: 2020-2022 The Monero Project
#include "XMRigWidget.h"
#include "ui_XMRigWidget.h"
#include <QDesktopServices>
#include <QFileDialog>
#include <QInputDialog>
#include <QMessageBox>
#include <QScrollBar>
#include <QStandardItemModel>
#include <QTableWidget>
#include "utils/Icons.h"
XMRigWidget::XMRigWidget(QSharedPointer<AppContext> ctx, QWidget *parent)
: QWidget(parent)
, ui(new Ui::XMRigWidget)
, m_ctx(std::move(ctx))
, m_XMRig(new XmRig(Config::defaultConfigDir().path()))
, m_model(new QStandardItemModel(this))
, m_contextMenu(new QMenu(this))
{
ui->setupUi(this);
connect(m_XMRig, &XmRig::stateChanged, this, &XMRigWidget::onXMRigStateChanged);
connect(m_XMRig, &XmRig::output, this, &XMRigWidget::onProcessOutput);
connect(m_XMRig, &XmRig::error, this, &XMRigWidget::onProcessError);
connect(m_XMRig, &XmRig::hashrate, this, &XMRigWidget::onHashrate);
// [Downloads] tab
ui->tableView->setModel(m_model);
m_contextMenu->addAction(icons()->icon("network.png"), "Download file", this, &XMRigWidget::linkClicked);
connect(ui->tableView, &QHeaderView::customContextMenuRequested, this, &XMRigWidget::showContextMenu);
connect(ui->tableView, &QTableView::doubleClicked, this, &XMRigWidget::linkClicked);
// [Settings] tab
ui->poolFrame->show();
ui->soloFrame->hide();
// XMRig executable
connect(ui->btn_browse, &QPushButton::clicked, this, &XMRigWidget::onBrowseClicked);
ui->lineEdit_path->setText(config()->get(Config::xmrigPath).toString());
// Run as admin/root
bool elevated = config()->get(Config::xmrigElevated).toBool();
if (elevated) {
ui->radio_elevateYes->setChecked(true);
} else {
ui->radio_elevateNo->setChecked(true);
}
connect(ui->radio_elevateYes, &QRadioButton::toggled, this, &XMRigWidget::onXMRigElevationChanged);
#if defined(Q_OS_WIN)
ui->radio_elevateYes->setToolTip("Not supported on Windows, yet.");
ui->radio_elevateYes->setEnabled(false);
ui->radio_elevateNo->setChecked(true);
#endif
// CPU threads
ui->threadSlider->setMinimum(1);
ui->threadSlider->setMaximum(QThread::idealThreadCount());
int threads = config()->get(Config::xmrigThreads).toInt();
ui->threadSlider->setValue(threads);
ui->label_threads->setText(QString("CPU threads: %1").arg(threads));
connect(ui->threadSlider, &QSlider::valueChanged, this, &XMRigWidget::onThreadsValueChanged);
// Mining mode
connect(ui->combo_miningMode, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &XMRigWidget::onMiningModeChanged);
ui->combo_miningMode->setCurrentIndex(config()->get(Config::miningMode).toInt());
// Pool/node address
this->updatePools();
connect(ui->combo_pools, &QComboBox::currentTextChanged, this, &XMRigWidget::onPoolChanged);
connect(ui->btn_poolConfig, &QPushButton::clicked, [this]{
QStringList pools = config()->get(Config::pools).toStringList();
bool ok;
QString poolStr = QInputDialog::getMultiLineText(this, "Pool addresses", "Set pool addresses (one per line):", pools.join("\n"), &ok);
if (!ok) {
return;
}
QStringList newPools = poolStr.split("\n");
newPools.removeAll("");
newPools.removeDuplicates();
config()->set(Config::pools, newPools);
this->updatePools();
});
// Network settings
connect(ui->check_tls, &QCheckBox::toggled, this, &XMRigWidget::onNetworkTLSToggled);
connect(ui->relayTor, &QCheckBox::toggled, this, &XMRigWidget::onNetworkTorToggled);
ui->check_tls->setChecked(config()->get(Config::xmrigNetworkTLS).toBool());
ui->relayTor->setChecked(config()->get(Config::xmrigNetworkTor).toBool());
// Receiving address
auto username = m_ctx->wallet->getCacheAttribute("feather.xmrig_username");
if (!username.isEmpty()) {
ui->lineEdit_address->setText(username);
}
connect(ui->lineEdit_address, &QLineEdit::textChanged, [=]() {
m_ctx->wallet->setCacheAttribute("feather.xmrig_username", ui->lineEdit_address->text());
});
connect(ui->btn_fillPrimaryAddress, &QPushButton::clicked, this, &XMRigWidget::onUsePrimaryAddressClicked);
// Password
auto password = m_ctx->wallet->getCacheAttribute("feather.xmrig_password");
if (!password.isEmpty()) {
ui->lineEdit_password->setText(password);
} else {
ui->lineEdit_password->setText("featherwallet");
m_ctx->wallet->setCacheAttribute("feather.xmrig_password", ui->lineEdit_password->text());
}
connect(ui->lineEdit_password, &QLineEdit::textChanged, [=]() {
m_ctx->wallet->setCacheAttribute("feather.xmrig_password", ui->lineEdit_password->text());
});
// [Status] tab
connect(ui->btn_start, &QPushButton::clicked, this, &XMRigWidget::onStartClicked);
connect(ui->btn_stop, &QPushButton::clicked, this, &XMRigWidget::onStopClicked);
connect(ui->btn_clear, &QPushButton::clicked, this, &XMRigWidget::onClearClicked);
ui->btn_stop->setEnabled(false);
ui->check_autoscroll->setChecked(true);
ui->label_status->setTextInteractionFlags(Qt::TextSelectableByMouse);
ui->label_status->hide();
this->printConsoleInfo();
}
bool XMRigWidget::isMining() {
return m_isMining;
}
void XMRigWidget::onWalletClosed() {
this->onStopClicked();
}
void XMRigWidget::onThreadsValueChanged(int threads) {
config()->set(Config::xmrigThreads, threads);
ui->label_threads->setText(QString("CPU threads: %1").arg(threads));
}
void XMRigWidget::onPoolChanged(const QString &pool) {
if (!pool.isEmpty()) {
config()->set(Config::xmrigPool, pool);
}
}
void XMRigWidget::onXMRigElevationChanged(bool elevated) {
config()->set(Config::xmrigElevated, elevated);
}
void XMRigWidget::onBrowseClicked() {
QString fileName = QFileDialog::getOpenFileName(this, "Path to XMRig executable", QDir::homePath());
if (fileName.isEmpty()) {
return;
}
config()->set(Config::xmrigPath, fileName);
ui->lineEdit_path->setText(fileName);
}
void XMRigWidget::onClearClicked() {
ui->console->clear();
}
void XMRigWidget::onUsePrimaryAddressClicked() {
ui->lineEdit_address->setText(m_ctx->wallet->address(0, 0));
}
void XMRigWidget::onStartClicked() {
QString xmrigPath = config()->get(Config::xmrigPath).toString();
if (!this->checkXMRigPath()) {
return;
}
QString address = [this](){
if (ui->combo_miningMode->currentIndex() == Config::MiningMode::Pool) {
return config()->get(Config::xmrigPool).toString();
} else {
return ui->lineEdit_solo->text().trimmed();
}
}();
if (address.isEmpty()) {
ui->console->appendPlainText("No pool or node address set. Please configure on the Settings tab.");
return;
}
// username is receiving address usually
auto username = m_ctx->wallet->getCacheAttribute("feather.xmrig_username");
auto password = m_ctx->wallet->getCacheAttribute("feather.xmrig_password");
if (username.isEmpty()) {
ui->console->appendPlainText("Please specify a receiving address on the Settings screen.");
return;
}
if (address.contains("cryptonote.social") && !username.contains(".")) {
// cryptonote social requires <addr>.<username>, we'll just grab a few chars from primary addy
username = QString("%1.%2").arg(username, m_ctx->wallet->address(0, 0).mid(0, 6));
}
int threads = ui->threadSlider->value();
m_XMRig->start(xmrigPath, threads, address, username, password, ui->relayTor->isChecked(), ui->check_tls->isChecked(),
ui->radio_elevateYes->isChecked());
}
void XMRigWidget::onStopClicked() {
m_XMRig->stop();
}
void XMRigWidget::onProcessOutput(const QByteArray &data) {
auto output = Utils::barrayToString(data);
if(output.endsWith("\n"))
output = output.trimmed();
ui->console->appendPlainText(output);
if(ui->check_autoscroll->isChecked())
ui->console->verticalScrollBar()->setValue(ui->console->verticalScrollBar()->maximum());
}
void XMRigWidget::onProcessError(const QString &msg) {
ui->console->appendPlainText("\n" + msg);
ui->btn_start->setEnabled(true);
ui->btn_stop->setEnabled(false);
this->setMiningStopped();
}
void XMRigWidget::onHashrate(const QString &hashrate) {
ui->label_status->show();
ui->label_status->setText(QString("Mining at %1").arg(hashrate));
}
void XMRigWidget::onDownloads(const QJsonObject &data) {
// For the downloads table we'll manually update the table
// with items once, as opposed to creating a class in
// src/models/. Saves effort; full-blown model
// is unnecessary in this case.
m_model->clear();
m_urls.clear();
auto version = data.value("version").toString();
ui->label_latest_version->setText(QString("Latest version: %1").arg(version));
QJsonObject assets = data.value("assets").toObject();
const auto _linux = assets.value("linux").toArray();
const auto macos = assets.value("macos").toArray();
const auto windows = assets.value("windows").toArray();
auto info = QSysInfo::productType();
QJsonArray *os_assets;
if(info == "osx") {
os_assets = const_cast<QJsonArray *>(&macos);
} else if (info == "windows") {
os_assets = const_cast<QJsonArray *>(&windows);
} else {
// assume linux
os_assets = const_cast<QJsonArray *>(&_linux);
}
int i = 0;
for(const auto &entry: *os_assets) {
auto _obj = entry.toObject();
auto _name = _obj.value("name").toString();
auto _url = _obj.value("url").toString();
auto _created_at = _obj.value("created_at").toString();
m_urls.append(_url);
auto download_count = _obj.value("download_count").toInt();
m_model->setItem(i, 0, Utils::qStandardItem(_name));
m_model->setItem(i, 1, Utils::qStandardItem(_created_at));
m_model->setItem(i, 2, Utils::qStandardItem(QString::number(download_count)));
i++;
}
m_model->setHeaderData(0, Qt::Horizontal, tr("Filename"), Qt::DisplayRole);
m_model->setHeaderData(1, Qt::Horizontal, tr("Date"), Qt::DisplayRole);
m_model->setHeaderData(2, Qt::Horizontal, tr("Downloads"), Qt::DisplayRole);
ui->tableView->verticalHeader()->setVisible(false);
ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
ui->tableView->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
ui->tableView->setColumnWidth(2, 100);
}
void XMRigWidget::showContextMenu(const QPoint &pos) {
QModelIndex index = ui->tableView->indexAt(pos);
if (!index.isValid()) {
return;
}
m_contextMenu->exec(ui->tableView->viewport()->mapToGlobal(pos));
}
void XMRigWidget::updatePools() {
QStringList pools = config()->get(Config::pools).toStringList();
if (pools.isEmpty()) {
pools = m_defaultPools;
config()->set(Config::pools, pools);
}
ui->combo_pools->clear();
ui->combo_pools->insertItems(0, pools);
QString preferredPool = config()->get(Config::xmrigPool).toString();
if (pools.contains(preferredPool)) {
ui->combo_pools->setCurrentIndex(pools.indexOf(preferredPool));
} else {
preferredPool = pools.at(0);
config()->set(Config::xmrigPool, preferredPool);
}
}
void XMRigWidget::printConsoleInfo() {
ui->console->appendPlainText(QString("Detected %1 CPU threads.").arg(QThread::idealThreadCount()));
if (this->checkXMRigPath()) {
QString path = config()->get(Config::xmrigPath).toString();
ui->console->appendPlainText(QString("XMRig path set to %1").arg(path));
}
}
void XMRigWidget::onMiningModeChanged(int mode) {
config()->set(Config::miningMode, mode);
if (mode == Config::MiningMode::Pool) {
ui->poolFrame->show();
ui->soloFrame->hide();
ui->label_poolNodeAddress->setText("Pool address:");
ui->check_tls->setChecked(true);
} else { // Solo mining
ui->poolFrame->hide();
ui->soloFrame->show();
ui->label_poolNodeAddress->setText("Node address:");
ui->check_tls->setChecked(false);
}
}
void XMRigWidget::onNetworkTLSToggled(bool checked) {
config()->set(Config::xmrigNetworkTLS, checked);
}
void XMRigWidget::onNetworkTorToggled(bool checked) {
config()->set(Config::xmrigNetworkTor, checked);
}
void XMRigWidget::onXMRigStateChanged(QProcess::ProcessState state) {
if (state == QProcess::ProcessState::Starting) {
ui->btn_start->setEnabled(false);
ui->btn_stop->setEnabled(false);
this->setMiningStarted();
}
else if (state == QProcess::ProcessState::Running) {
ui->btn_start->setEnabled(false);
ui->btn_stop->setEnabled(true);
this->setMiningStarted();
}
else if (state == QProcess::ProcessState::NotRunning) {
ui->btn_start->setEnabled(true); // todo
ui->btn_stop->setEnabled(false);
ui->label_status->hide();
this->setMiningStopped();
}
}
void XMRigWidget::setMiningStopped() {
m_isMining = false;
emit miningEnded();
}
void XMRigWidget::setMiningStarted() {
m_isMining = true;
emit miningStarted();
}
bool XMRigWidget::checkXMRigPath() {
QString path = config()->get(Config::xmrigPath).toString();
if (path.isEmpty()) {
ui->console->appendPlainText("No XMRig executable is set. Please configure on the Settings tab.");
return false;
} else if (!Utils::fileExists(path)) {
ui->console->appendPlainText("Invalid path to XMRig executable detected. Please reconfigure on the Settings tab.");
return false;
} else {
return true;
}
}
void XMRigWidget::linkClicked() {
QModelIndex index = ui->tableView->currentIndex();
auto download_link = m_urls.at(index.row());
Utils::externalLinkWarning(this, download_link);
}
QStandardItemModel *XMRigWidget::model() {
return m_model;
}
XMRigWidget::~XMRigWidget() = default; | 35.477723 | 142 | 0.669155 | Midar |
400f3ad1b8bbd7ff2e3e1015d72397aca32a6e11 | 8,490 | cpp | C++ | src/core/application.cpp | dream-overflow/o3d | 087ab870cc0fd9091974bb826e25c23903a1dde0 | [
"FSFAP"
] | 2 | 2019-06-22T23:29:44.000Z | 2019-07-07T18:34:04.000Z | src/core/application.cpp | dream-overflow/o3d | 087ab870cc0fd9091974bb826e25c23903a1dde0 | [
"FSFAP"
] | null | null | null | src/core/application.cpp | dream-overflow/o3d | 087ab870cc0fd9091974bb826e25c23903a1dde0 | [
"FSFAP"
] | null | null | null | /**
* @file application.cpp
* @brief
* @author Frederic SCHERMA ([email protected])
* @date 2001-12-25
* @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved.
* @details
*/
#include "o3d/core/precompiled.h"
#include "o3d/core/application.h"
#include "o3d/core/classfactory.h"
#include "o3d/core/taskmanager.h"
#include "o3d/core/display.h"
#include "o3d/core/filemanager.h"
#include "o3d/core/thread.h"
#include "o3d/core/timer.h"
#include "o3d/core/uuid.h"
#include "o3d/core/date.h"
#include "o3d/core/datetime.h"
#include "o3d/core/math.h"
#include "o3d/core/stringmap.h"
#include "o3d/core/appwindow.h"
#include "o3d/core/debug.h"
#include "o3d/core/gl.h"
#include <algorithm>
using namespace o3d;
String *Application::ms_appsName = nullptr;
String *Application::ms_appsPath = nullptr;
Application::T_AppWindowMap Application::ms_appWindowMap;
_DISP Application::ms_display = NULL_DISP;
Activity *Application::ms_activity = nullptr;
void* Application::ms_app = nullptr;
Int32 Application::ms_appState = 0;
AppWindow* Application::ms_currAppWindow = nullptr;
CommandLine *Application::ms_appsCommandLine = nullptr;
Bool Application::ms_init = False;
Bool Application::ms_displayInit = False;
StringMap<BaseObject*> *ms_mappedObject = nullptr;
Bool Application::ms_displayError = False;
Activity::~Activity()
{
}
// Objective-3D initialization
void Application::init(AppSettings settings, Int32 argc, Char **argv, void *app)
{
if (ms_init) {
return;
}
ms_appState = 0;
ms_app = app;
ms_mappedObject = new StringMap<BaseObject*>;
// get the main thread id
ThreadManager::init();
System::initTime();
Date::init();
DateTime::init();
Uuid::init();
// Get the application name and path
getBaseNamePrivate(argc, argv);
if (settings.clearLog) {
Debug::instance()->getDefaultLog().clearLog();
}
// Log start time
DateTime current(True);
O3D_MESSAGE(String("Starting of application on ") + current.buildString("%Y-%m-%d %H:%M:%S.%f"));
// Initialize fast memory allocator
MemoryManager::instance()->initFastAllocator(
settings.sizeOfFastAlloc16,
settings.sizeOfFastAlloc32,
settings.sizeOfFastAlloc64);
// Registration of the main thread to activate events
EvtManager::instance()->registerThread(nullptr);
#ifdef O3D_ANDROID
// @todo
ms_appsCommandLine = new CommandLine("");
#elif defined(O3D_WINDOWS)
String commandLine(GetCommandLineW());
ms_appsCommandLine = new CommandLine(commandLine);
#else
ms_appsCommandLine = new CommandLine(argc, argv);
#endif
// Math initialization
Math::init();
// only if display
if (settings.useDisplay) {
apiInitPrivate();
ms_displayInit = True;
GL::init();
String typeString = "Undefined";
if (GL::getType() == GL::API_GL) {
typeString = "GL3+";
} else if (GL::getType() == GL::API_GLES_3) {
typeString = "GLES3+";
}
O3D_MESSAGE(String("Choose {0} implementation with a {1} API").arg(GL::getImplementationName()).arg(typeString));
Display::instance();
}
// Active the PostMessage
EvtManager::instance()->enableAutoWakeUp();
ms_init = True;
}
// Objective-3D terminate
void Application::quit()
{
deletePtr(ms_activity);
if (!ms_init) {
return;
}
// Log quit time
DateTime current(True);
O3D_MESSAGE(String("Terminating of application on ") + current.buildString("%Y-%m-%d at %H:%M:%S.%f"));
ms_init = False;
// Disable the PostMessage
EvtManager::instance()->disableAutoWakeUp();
if (!ms_appWindowMap.empty()) {
O3D_WARNING("Still always exists application windows");
}
if (!ms_mappedObject->empty()) {
O3D_WARNING("Still always exists mapped object");
}
// terminate the task manager if running
TaskManager::destroy();
// timer manager before thread
TimerManager::destroy();
// wait all threads terminate
ThreadManager::waitEndThreads();
// delete class factory
ClassFactory::destroy();
// display manager
Display::destroy();
// Specific quit
if (ms_displayInit) {
apiQuitPrivate();
GL::quit();
ms_displayInit = False;
}
// deletion of the main thread
EvtManager::instance()->unRegisterThread(nullptr);
// debug manager
Debug::destroy();
// file manager
FileManager::destroy();
// event manager
EvtManager::destroy();
// math release
Math::quit();
// date quit
Date::quit();
DateTime::quit();
Uuid::quit();
// object mapping
deletePtr(ms_mappedObject);
// release memory manager allocators
MemoryManager::instance()->releaseFastAllocator();
// common members
deletePtr(ms_appsCommandLine);
deletePtr(ms_appsName);
deletePtr(ms_appsPath);
ms_app = nullptr;
}
Bool Application::isInit()
{
return ms_init;
}
// Return the command line
CommandLine* Application::getCommandLine()
{
return ms_appsCommandLine;
}
// Get the application name
const String& Application::getAppName()
{
if (ms_appsName) {
return *ms_appsName;
} else {
return String::getNull();
}
}
const String &Application::getAppPath()
{
if (ms_appsPath) {
return *ms_appsPath;
} else {
return String::getNull();
}
}
void Application::addAppWindow(AppWindow *appWindow)
{
if (appWindow && appWindow->getHWND()) {
if (ms_appWindowMap.find(appWindow->getHWND()) != ms_appWindowMap.end()) {
O3D_ERROR(E_InvalidParameter("Cannot add an application window with a similar handle"));
}
ms_appWindowMap[appWindow->getHWND()] = appWindow;
} else {
O3D_ERROR(E_InvalidParameter("Cannot add an invalid application window"));
}
}
void Application::removeAppWindow(_HWND hWnd)
{
IT_AppWindowMap it = ms_appWindowMap.find(hWnd);
if (it != ms_appWindowMap.end()) {
AppWindow *appWindow = it->second;
ms_appWindowMap.erase(it);
// and delete it
deletePtr(appWindow);
} else {
O3D_ERROR(E_InvalidParameter("Unable to find the window handle"));
}
}
Activity *Application::getActivity()
{
return ms_activity;
}
AppWindow* Application::getAppWindow(_HWND window)
{
IT_AppWindowMap it = ms_appWindowMap.find(window);
if (it != ms_appWindowMap.end()) {
return it->second;
} else {
return nullptr;
}
}
void Application::throwDisplayError(void *generic_data)
{
ms_displayError = True;
}
// Get the default primary display.
_DISP Application::getDisplay()
{
return ms_display;
}
void *Application::getApp()
{
return ms_app;
}
Bool Application::isDisplayError()
{
return ms_displayError;
}
void Application::registerObject(const String &name, BaseObject *object)
{
if (ms_mappedObject) {
if (ms_mappedObject->find(name) != ms_mappedObject->end()) {
O3D_ERROR(E_InvalidOperation(name + " is a registred object"));
}
ms_mappedObject->insert(std::make_pair(name, object));
}
}
void Application::unregisterObject(const String &name)
{
if (ms_mappedObject) {
auto it = ms_mappedObject->find(name);
if (it != ms_mappedObject->end()) {
ms_mappedObject->erase(it);
}
}
}
BaseObject *Application::getObject(const String &name)
{
if (ms_mappedObject) {
auto it = ms_mappedObject->find(name);
if (it != ms_mappedObject->end()) {
return it->second;
}
}
return nullptr;
}
void Application::setState(Int32 state)
{
ms_appState = state;
}
Int32 Application::getState()
{
return ms_appState;
}
#ifndef O3D_ANDROID
Int32 Application::startPrivate()
{
if (ms_activity) {
return ms_activity->onStart();
} else {
return 0;
}
}
Int32 Application::stopPrivate()
{
if (ms_activity) {
return ms_activity->onStop();
} else {
return 0;
}
}
#endif
void Application::setActivity(Activity *activity)
{
if (ms_activity) {
delete ms_activity;
}
ms_activity = activity;
}
void Application::start()
{
if (startPrivate() != 0) {
// @todo need exit now
}
}
void Application::run(Bool runOnce)
{
runPrivate(runOnce);
}
void Application::stop()
{
if (stopPrivate() != 0) {
// @todo need exit now
}
}
void Application::pushEvent(Application::EventType type, _HWND hWnd, void *data)
{
pushEventPrivate(type, hWnd, data);
}
| 21.225 | 121 | 0.66384 | dream-overflow |
4014349595174704789f2de878af3e95cfa028cc | 440 | cpp | C++ | 9/9.45.cpp | kousikpramanik/C-_Primer_5th | e21fb665f04b26193fc13f9c2c263b782aea3f3c | [
"MIT"
] | null | null | null | 9/9.45.cpp | kousikpramanik/C-_Primer_5th | e21fb665f04b26193fc13f9c2c263b782aea3f3c | [
"MIT"
] | 2 | 2020-08-15T17:33:00.000Z | 2021-07-05T14:18:26.000Z | 9/9.45.cpp | kousikpramanik/C-_Primer_5th | e21fb665f04b26193fc13f9c2c263b782aea3f3c | [
"MIT"
] | 1 | 2020-08-15T17:24:54.000Z | 2020-08-15T17:24:54.000Z | #include <iostream>
#include <string>
void prefix_name_suffix(std::string &name, const std::string &prefix, const std::string &suffix) {
name.insert(name.begin(), 1, ' ');
name.insert(name.begin(), prefix.cbegin(), prefix.cend());
name.append(1, ' ');
name.append(suffix);
}
int main() {
std::string test("Stephen Inverter");
prefix_name_suffix(test, "Mr.", "III");
std::cout << test << '\n';
return 0;
}
| 24.444444 | 98 | 0.618182 | kousikpramanik |
4017a39b14c250e5467b575075367f6cde6a683b | 15,723 | cpp | C++ | win32-OpenGL/MotionPlanning_Project/Graph.cpp | Peanoquio/fuzzy-logic-demo | 100a64094adb2d5274c32761ed4ede15b912dd90 | [
"MIT"
] | null | null | null | win32-OpenGL/MotionPlanning_Project/Graph.cpp | Peanoquio/fuzzy-logic-demo | 100a64094adb2d5274c32761ed4ede15b912dd90 | [
"MIT"
] | null | null | null | win32-OpenGL/MotionPlanning_Project/Graph.cpp | Peanoquio/fuzzy-logic-demo | 100a64094adb2d5274c32761ed4ede15b912dd90 | [
"MIT"
] | null | null | null | /******************************************************************************/
/*!
\file Graph.cpp
\author Oliver Ryan Chong
\par email: oliver.chong\@digipen.edu
\par oliver.chong 900863
\par Course: CS1150
\par Project #02
\date 01/03/2012
\brief
This is the graph class that will be used to generate the graph to be used by the algorithm to find the shortest path
Copyright (C) 2011 DigiPen Institute of Technology Singapore
*/
/******************************************************************************/
#include "Graph.h"
#include "MathUtility.h"
//Edge class
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The constructor for the Edge class
\param
\return
*/
/******************************************************************************/
Edge::Edge()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The destructor for the Edge class
\param
\return
*/
/******************************************************************************/
Edge::~Edge()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The copy constructor for the Edge class
\param ed
the Edge class to be assigned
\return
*/
/******************************************************************************/
Edge::Edge(const Edge & ed)
{
from = ed.from;
to = ed.to;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The assignment operator overload for the Edge class
\param ed
the Edge class to be assigned
\return Edge
the Edge
*/
/******************************************************************************/
Edge & Edge::operator=(const Edge & ed)
{
if(this != &ed)
{
from = ed.from;
to = ed.to;
}
return *this;
}
//State class
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The constructor for the State class
\param
\return
*/
/******************************************************************************/
State::State()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The destructor for the State class
\param
\return
*/
/******************************************************************************/
State::~State()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The copy constructor for the State class
\param st
the State class to be assigned
\return
*/
/******************************************************************************/
State::State(const State & st)
{
worldPositionX = st.worldPositionX;
worldPositionY = st.worldPositionY;
edges = st.edges;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The assignment operator overload for the State class
\param st
the State class to be assigned
\return State
the State
*/
/******************************************************************************/
State & State::operator=(const State & st)
{
if(this != &st)
{
worldPositionX = st.worldPositionX;
worldPositionY = st.worldPositionY;
edges = st.edges;
}
return *this;
}
//Path class
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The constructor for the Path class
\param
\return
*/
/******************************************************************************/
Path::Path()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The destructor for the Path class
\param
\return
*/
/******************************************************************************/
Path::~Path()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The assignment operator overload for the Path class
\param pa1
the Path class to be assigned
\return Path
the Path
*/
/******************************************************************************/
Path & Path::operator=(Path & pa1)
{
if(this != &pa1)
{
}
return *this;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
Initializes the distance and path matrices based on the number of states in the path
\param
\return
*/
/******************************************************************************/
void Path::InitMatrix( void )
{
unsigned noOfStates = this->states.size();
//initialize the distance matrix based on the number of states in the path
std::vector< float > floatVec;
floatVec.reserve( noOfStates );
std::vector< int > intVec;
intVec.reserve( noOfStates );
for ( unsigned int y = 0; y < noOfStates; ++y )
{
floatVec.push_back( MAX_DISTANCE );
intVec.push_back( NO_LINK );
}//end for loop
this->m_distanceMtx.reserve( noOfStates );
this->m_pathMtx.reserve( noOfStates );
for ( unsigned int x = 0; x < noOfStates; ++x )
{
this->m_distanceMtx.push_back( floatVec );
this->m_pathMtx.push_back( intVec );
}//end for loop
//set to identity
for ( unsigned int x = 0; x < noOfStates; ++x )
{
for ( unsigned int y = 0; y < noOfStates; ++y )
{
if ( x == y )
{
this->m_distanceMtx.at( x ).at( y ) = 0;
this->m_pathMtx.at( x ).at( y ) = DIRECT_LINK;
break;
}
}//end for loop
}//end for loop
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
Populates the distance and path matrices based on the edges of each state in the path
\param
\return
*/
/******************************************************************************/
void Path::PopulateMatrix( void )
{
unsigned noOfStates = this->states.size();
//populate the distance matrix based on the edges of each state in the path
//loop through the states
for ( unsigned stateIndex = 0; stateIndex < noOfStates; ++stateIndex )
{
//get the current state
const State & currState = this->states.at( stateIndex );
//loop through the edges
for ( unsigned edgeIndex = 0; edgeIndex < currState.edges.size(); ++edgeIndex )
{
//get the current edge
const Edge & currEdge = currState.edges.at( edgeIndex );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//traverse the row
for ( unsigned x = 0; x < this->m_distanceMtx.size(); ++x )
{
//if row found ( from )
if ( currEdge.from == static_cast<int>( x ) )
{
std::vector< float > & colVecDM = this->m_distanceMtx.at( x );
std::vector< int> & colVecPath = this->m_pathMtx.at( x );
//traverse the column
for ( unsigned y = 0; colVecDM.size(); ++y )
{
//if column found ( to )
if ( currEdge.to == static_cast<int>( y ) )
{
//get the x and y positions of the from and to states
const State & fromState = this->states.at( currEdge.from );
const State & toState = this->states.at( currEdge.to );
//compute the distance between from and to states
float xDiff = toState.worldPositionX - fromState.worldPositionX;
float yDiff = toState.worldPositionY - fromState.worldPositionY;
float distanceSquared = ( xDiff * xDiff ) + ( yDiff * yDiff );
//store the distance ( cost ) between the states
colVecDM.at( y ) = distanceSquared;
//to identify a direct path between states
colVecPath.at( y ) = DIRECT_LINK;
break;
}
}//end for loop
break;
}
}//end for loop
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
}//end for loop
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
Generate the distance and path matrices to be used by Floyd's algorithm
\param
\return
*/
/******************************************************************************/
void Path::GenerateMatrix( void )
{
this->InitMatrix();
this->PopulateMatrix();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
Floyd (or Floyd-Warshall) algorithm is a dynamic algorithm that finds the shortest paths between all pairs in a graph.
\param
\return
*/
/******************************************************************************/
void Path::FloydAlgorithm( void )
{
unsigned noOfStates = this->states.size();
//loop through the intermediate nodes that could possible provide the shortest path
for ( unsigned interIndex = 0; interIndex < noOfStates; ++interIndex )
{
for ( unsigned fromIndex = 0; fromIndex < noOfStates; ++fromIndex )
{
for ( unsigned toIndex = 0; toIndex < noOfStates; ++toIndex )
{
float distFromTo = this->m_distanceMtx.at( fromIndex).at( toIndex );
float distFromInter = this->m_distanceMtx.at( fromIndex ).at( interIndex );
float distInterTo = this->m_distanceMtx.at( interIndex ).at( toIndex );
//validate if the intermediate state node will give a shorter path to the destination
if ( distFromTo > distFromInter + distInterTo )
{
//update the distance cost based on the new shorter path
distFromTo = distFromInter + distInterTo;
this->m_distanceMtx.at( fromIndex).at( toIndex ) = distFromTo;
//update the path
this->m_pathMtx.at( fromIndex ).at( toIndex ) = interIndex;
}
}//end for loop
}//end for loop
}//end for loop
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
Finds the shortest path based on the start and end indices.
This uses the path matrix generated by Floyd's algorithm
\param startIndex
the start index of the path
\param endIndex
the end index of the path
\return
*/
/******************************************************************************/
void Path::ComputeShortestPath( const int startIndex, const int endIndex )
{
//get the path node index based on the start and end index
int pathNodeIndex = this->m_pathMtx.at( startIndex ).at( endIndex );
//if there is no path
if ( pathNodeIndex == NO_LINK )
{
//do nothing
}
//if there is a direct path from start to end
else if ( pathNodeIndex == DIRECT_LINK )
{
//add the starting state
this->shortestPathIndices.push_back( startIndex );
//add the ending state
this->shortestPathIndices.push_back( endIndex );
}
//if there is an intermediate node
else
{
//find the intermediate nodes between the start and the middle state
this->FindIntermediateNodes( startIndex, pathNodeIndex, true );
//find the intermediate nodes between the middle and end state
this->FindIntermediateNodes( pathNodeIndex, endIndex, false );
//add the starting state
//this->shortestPathIndices.push_back( startIndex );
//add the intermediate nodes
for ( unsigned index = 0; index < this->intermediateNodes.size(); ++index )
{
this->shortestPathIndices.push_back( this->intermediateNodes.at( index ) );
}//end for loop
//clear the intermediate nodes
this->intermediateNodes.clear();
//add the ending state
//this->shortestPathIndices.push_back( endIndex );
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
Finds the intermediate nodes between a specified start and end state
\param startIndex
the start index of the path
\param endIndex
the end index of the path
\param leftToRight
if true, traverse nodes from left to right.
if false, traverse from right to left
\return
*/
/******************************************************************************/
void Path::FindIntermediateNodes( const int startIndex, const int endIndex, bool leftToRight )
{
//get the path node index based on the start and end index
int pathNodeIndex = this->m_pathMtx.at( startIndex ).at( endIndex );
//if there is no path
if ( pathNodeIndex == NO_LINK )
{
//do nothing
}
//if there is a direct path from start to end
else if ( pathNodeIndex == DIRECT_LINK )
{
int firstStateIndex = 0;
int secondStateIndex = 0;
if ( leftToRight == true )
{
firstStateIndex = startIndex;
secondStateIndex = endIndex;
}
else
{
firstStateIndex = endIndex;
secondStateIndex = startIndex;
}
this->AddNodeIndex( firstStateIndex );
this->AddNodeIndex( secondStateIndex );
}
//if there is an intermediate node
else
{
//invoke function recursively to check for possible succeeding intermediate nodes
this->FindIntermediateNodes( startIndex, pathNodeIndex, true );
this->FindIntermediateNodes( pathNodeIndex, endIndex, false );
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
Adds the state node index to the list
\param stateIndex
the state node index of the path
\return
*/
/******************************************************************************/
void Path::AddNodeIndex( const int stateIndex )
{
bool isExisting = false;
//validate if the node to be is already existing
for ( unsigned index = 0; index < this->intermediateNodes.size(); ++index )
{
if ( stateIndex == this->intermediateNodes.at( index ) )
{
isExisting = true;
break;
}
}//end for loop
if ( isExisting == false )
{
this->intermediateNodes.push_back( stateIndex );
}
} | 26.694397 | 143 | 0.423011 | Peanoquio |
4018a792a0a6347c5f884fceecd845d56585bc05 | 11,424 | hpp | C++ | src/framework/gui/CommonControls.hpp | yslking/GPURayTraversal | cfcc825aef473318fc7eb4975c13fe40cda5c915 | [
"BSD-3-Clause"
] | 39 | 2016-07-19T15:25:16.000Z | 2021-07-15T16:06:15.000Z | src/framework/gui/CommonControls.hpp | ItsHoff/BDPT | 4a5ae6559764799c77182a965a674cae127e2b0e | [
"MIT"
] | null | null | null | src/framework/gui/CommonControls.hpp | ItsHoff/BDPT | 4a5ae6559764799c77182a965a674cae127e2b0e | [
"MIT"
] | 14 | 2017-12-19T03:14:50.000Z | 2021-06-24T16:53:10.000Z | /*
* Copyright (c) 2009-2011, 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 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 <COPYRIGHT HOLDER> 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 "gui/Window.hpp"
#include "base/Timer.hpp"
#include "base/Array.hpp"
#include "base/Hash.hpp"
namespace FW
{
//------------------------------------------------------------------------
class StateDump;
//------------------------------------------------------------------------
class CommonControls : public Window::Listener
{
public:
//------------------------------------------------------------------------
enum Feature
{
Feature_CloseOnEsc = 1 << 0,
Feature_CloseOnAltF4 = 1 << 1,
Feature_RepaintOnF5 = 1 << 2,
Feature_ShowFPSOnF9 = 1 << 3,
Feature_HideControlsOnF10 = 1 << 4,
Feature_FullScreenOnF11 = 1 << 5,
Feature_ScreenshotOnPrtScn = 1 << 6,
Feature_LoadStateOnNum = 1 << 7,
Feature_SaveStateOnAltNum = 1 << 8,
Feature_None = 0,
Feature_All = (1 << 9) - 1,
Feature_Default = Feature_All
};
//------------------------------------------------------------------------
class StateObject
{
public:
StateObject (void) {}
virtual ~StateObject (void) {}
virtual void readState (StateDump& d) = 0;
virtual void writeState (StateDump& d) const = 0;
};
private:
struct Key;
//------------------------------------------------------------------------
struct Message
{
String string;
String volatileID;
F32 highlightTime;
U32 abgr;
};
//------------------------------------------------------------------------
struct Toggle
{
bool* boolTarget;
S32* enumTarget;
S32 enumValue;
bool* dirtyNotify;
bool isButton;
bool isSeparator;
Key* key;
String title;
F32 highlightTime;
bool visible;
Vec2f pos;
Vec2f size;
};
//------------------------------------------------------------------------
struct Slider
{
F32* floatTarget;
S32* intTarget;
bool* dirtyNotify;
F32 slack;
F32 minValue;
F32 maxValue;
bool isExponential;
Key* increaseKey;
Key* decreaseKey;
String format;
F32 speed;
F32 highlightTime;
bool visible;
bool stackWithPrevious;
Vec2f pos;
Vec2f size;
Vec2f blockPos;
Vec2f blockSize;
};
//------------------------------------------------------------------------
struct Key
{
String id;
Array<Toggle*> toggles;
Array<Slider*> sliderIncrease;
Array<Slider*> sliderDecrease;
};
//------------------------------------------------------------------------
public:
CommonControls (U32 features = Feature_Default);
virtual ~CommonControls (void);
virtual bool handleEvent (const Window::Event& ev);
void message (const String& str, const String& volatileID = "", U32 abgr = 0xffffffffu);
void addToggle (bool* target, const String& key, const String& title, bool* dirtyNotify = NULL) { FW_ASSERT(target); addToggle(target, NULL, 0, false, key, title, dirtyNotify); }
void addToggle (S32* target, S32 value, const String& key, const String& title, bool* dirtyNotify = NULL) { FW_ASSERT(target); addToggle(NULL, target, value, false, key, title, dirtyNotify); }
void addButton (bool* target, const String& key, const String& title, bool* dirtyNotify = NULL) { FW_ASSERT(target); addToggle(target, NULL, 0, true, key, title, dirtyNotify); }
void addButton (S32* target, S32 value, const String& key, const String& title, bool* dirtyNotify = NULL) { FW_ASSERT(target); addToggle(NULL, target, value, true, key, title, dirtyNotify); }
void addSeparator (void) { addToggle(NULL, NULL, 0, false, "", "", NULL); }
void setControlVisibility(bool visible) { m_controlVisibility = visible; } // applies to next addXxx()
void addSlider (F32* target, F32 minValue, F32 maxValue, bool isExponential, const String& increaseKey, const String& decreaseKey, const String& format, F32 speed = 0.25f, bool* dirtyNotify = NULL) { addSlider(target, NULL, minValue, maxValue, isExponential, increaseKey, decreaseKey, format, speed, dirtyNotify); }
void addSlider (S32* target, S32 minValue, S32 maxValue, bool isExponential, const String& increaseKey, const String& decreaseKey, const String& format, F32 speed = 0.0f, bool* dirtyNotify = NULL) { addSlider(NULL, target, (F32)minValue, (F32)maxValue, isExponential, increaseKey, decreaseKey, format, speed, dirtyNotify); }
void beginSliderStack (void) { m_sliderStackBegun = true; m_sliderStackEmpty = true; }
void endSliderStack (void) { m_sliderStackBegun = false; }
void removeControl (const void* target);
void resetControls (void);
void setStateFilePrefix (const String& prefix) { m_stateFilePrefix = prefix; }
void setScreenshotFilePrefix(const String& prefix) { m_screenshotFilePrefix = prefix; }
String getStateFileName (int idx) const { return sprintf("%s%03d.dat", m_stateFilePrefix.getPtr(), idx); }
String getScreenshotFileName(void) const;
void addStateObject (StateObject* obj) { if (obj && !m_stateObjs.contains(obj)) m_stateObjs.add(obj); }
void removeStateObject (StateObject* obj) { m_stateObjs.removeItem(obj); }
bool loadState (const String& fileName);
bool saveState (const String& fileName);
bool loadStateDialog (void);
bool saveStateDialog (void);
void showControls (bool show) { m_showControls = show; }
void showFPS (bool show) { m_showFPS = show; }
bool getShowControls (void) const { return m_showControls; }
bool getShowFPS (void) const { return m_showFPS; }
F32 getKeyBoost (void) const;
void flashButtonTitles (void);
private:
bool hasFeature (Feature feature) { return ((m_features & feature) != 0); }
void render (GLContext* gl);
void addToggle (bool* boolTarget, S32* enumTarget, S32 enumValue, bool isButton, const String& key, const String& title, bool* dirtyNotify);
void addSlider (F32* floatTarget, S32* intTarget, F32 minValue, F32 maxValue, bool isExponential, const String& increaseKey, const String& decreaseKey, const String& format, F32 speed, bool* dirtyNotify);
Key* getKey (const String& id);
void layout (const Vec2f& viewSize, F32 fontHeight);
void clearActive (void);
void updateActive (const Vec2f& mousePos);
F32 updateHighlightFade (F32* highlightTime);
U32 fadeABGR (U32 abgr, F32 fade);
static void selectToggle (Toggle* t);
F32 getSliderY (const Slider* s, bool applySlack) const;
void setSliderY (Slider* s, F32 y);
static F32 getSliderValue (const Slider* s, bool applySlack);
static void setSliderValue (Slider* s, F32 v);
static String getSliderLabel (const Slider* s);
static void sliderKeyDown (Slider* s, int dir);
void enterSliderValue (Slider* s);
static void drawPanel (GLContext* gl, const Vec2f& pos, const Vec2f& size, U32 interiorABGR, U32 topLeftABGR, U32 bottomRightABGR);
private:
CommonControls (const CommonControls&); // forbidden
CommonControls& operator= (const CommonControls&); // forbidden
private:
const U32 m_features;
Window* m_window;
Timer m_timer;
bool m_showControls;
bool m_showFPS;
String m_stateFilePrefix;
String m_screenshotFilePrefix;
Array<Message> m_messages;
Array<Toggle*> m_toggles;
Array<Slider*> m_sliders;
Array<StateObject*> m_stateObjs;
Hash<String, Key*> m_keyHash;
bool m_sliderStackBegun;
bool m_sliderStackEmpty;
bool m_controlVisibility;
Vec2f m_viewSize;
F32 m_fontHeight;
F32 m_rightX;
S32 m_activeSlider;
S32 m_activeToggle;
bool m_dragging;
F32 m_avgFrameTime;
bool m_screenshot;
};
//------------------------------------------------------------------------
}
| 44.976378 | 349 | 0.523372 | yslking |
40198441b55144c425d6a51c11f979b7e34474ca | 1,595 | cpp | C++ | ogsr_engine/xrGame/GraviArtifact.cpp | stepa2/OGSR-Engine | 32a23aa30506684be1267d9c4fc272350cd167c5 | [
"Apache-2.0"
] | 247 | 2018-11-02T18:50:55.000Z | 2022-03-15T09:11:43.000Z | ogsr_engine/xrGame/GraviArtifact.cpp | stepa2/OGSR-Engine | 32a23aa30506684be1267d9c4fc272350cd167c5 | [
"Apache-2.0"
] | 193 | 2018-11-02T20:12:44.000Z | 2022-03-07T13:35:17.000Z | ogsr_engine/xrGame/GraviArtifact.cpp | stepa2/OGSR-Engine | 32a23aa30506684be1267d9c4fc272350cd167c5 | [
"Apache-2.0"
] | 106 | 2018-10-26T11:33:01.000Z | 2022-03-19T12:34:20.000Z | ///////////////////////////////////////////////////////////////
// GraviArtifact.cpp
// GraviArtefact - гравитационный артефакт, прыгает на месте
// и неустойчиво парит над землей
///////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "GraviArtifact.h"
#include "PhysicsShell.h"
#include "level.h"
#include "xrmessages.h"
#include "game_cl_base.h"
#include "../Include/xrRender/Kinematics.h"
#include "phworld.h"
extern CPHWorld* ph_world;
#define CHOOSE_MAX(x,inst_x,y,inst_y,z,inst_z)\
if(x>y)\
if(x>z){inst_x;}\
else{inst_z;}\
else\
if(y>z){inst_y;}\
else{inst_z;}
CGraviArtefact::CGraviArtefact(void)
{
shedule.t_min = 20;
shedule.t_max = 50;
m_fJumpHeight = 0;
m_fEnergy = 1.f;
}
CGraviArtefact::~CGraviArtefact(void)
{
}
void CGraviArtefact::Load(LPCSTR section)
{
inherited::Load(section);
if(pSettings->line_exist(section, "jump_height")) m_fJumpHeight = pSettings->r_float(section,"jump_height");
// m_fEnergy = pSettings->r_float(section,"energy");
}
void CGraviArtefact::UpdateCLChild()
{
VERIFY(!ph_world->Processing());
if (getVisible() && m_pPhysicsShell) {
if (m_fJumpHeight) {
Fvector dir;
dir.set(0, -1.f, 0);
collide::rq_result RQ;
//проверить высоту артифакта
if(Level().ObjectSpace.RayPick(Position(), dir, m_fJumpHeight, collide::rqtBoth, RQ, this))
{
dir.y = 1.f;
m_pPhysicsShell->applyImpulse(dir,
30.f * Device.fTimeDelta *
m_pPhysicsShell->getMass());
}
}
} else
if(H_Parent())
{
XFORM().set(H_Parent()->XFORM());
};
} | 22.152778 | 109 | 0.619436 | stepa2 |
401a1a934270716c9dee2332135d5c7416f85b84 | 9,387 | cpp | C++ | MIDI Test/console_io_handler.cpp | MiguelGuthridge/HDSQs-MIDI-Editor | a5d6a2ea84b5123fb8f1aa0921da0b04e6e6cc27 | [
"MIT"
] | null | null | null | MIDI Test/console_io_handler.cpp | MiguelGuthridge/HDSQs-MIDI-Editor | a5d6a2ea84b5123fb8f1aa0921da0b04e6e6cc27 | [
"MIT"
] | 1 | 2018-07-01T08:51:05.000Z | 2018-08-18T10:40:53.000Z | MIDI Test/console_io_handler.cpp | HDSQmid/HDSQs-MIDI-Editor | a5d6a2ea84b5123fb8f1aa0921da0b04e6e6cc27 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "console_io_handler.h"
#include "messageSend.h"
#include "multiLingual.h"
#include "settings.h"
ConsoleQuit quit;
ConsoleHelp help;
ConsoleFileNew newFile;
ConsoleFileOpen openFile;
ConsoleFileClose closeFile;
ConsoleFileSave saveFile;
ConsoleFileSaveAs saveFileAs;
ConsoleMidiMakeEdit makeEdit;
ConsoleCrash crash;
ConsoleInfo info;
ConsoleSettingsAddLanguage addLanguage;
ConsolePrintTranslation printTranslation;
ConsoleMidiPattern pattern;
ConsoleInputHandler* input_handlers[NUM_HANDLERS] =
{
&help,
&quit,
&openFile,
&newFile,
&closeFile,
&saveFile,
&saveFileAs,
&crash, &info,
&makeEdit,
&addLanguage,
&printTranslation,
&pattern
};
void handleConsoleInput(std::string input, ConsoleInputHandler ** handlerList, int numHandlers)
{
std::string test;
std::istringstream iss{ input };
iss >> test;
std::ostringstream oss;
oss << iss.rdbuf();
std::string args = oss.str();
if (test == "") {
sendMessage(MESSAGE_NO_COMMAND_PROVIDED, "", MESSAGE_TYPE_ERROR);
return;
}
if(args != "") args = args.substr(1); // remove space from start of string
//remove command from rest of arguments for easier processing
bool foundCall = false; // bool for whether a handler was found
for (int i = 0; i <numHandlers; i++) {
if (handlerList[i]->getIdentifier() == test) {
handlerList[i]->call(args);
foundCall = 1;
break;
}
}
if (!foundCall) sendMessage(MESSAGE_NO_MATCHING_COMMAND, "", MESSAGE_TYPE_ERROR);
}
/***************************************/
//implement multi-layered console input handler
ConsoleInputHandler::ConsoleInputHandler()
{
identifier = "NULL";
description = CONSOLE_INPUT_HANDLER_DEFAULT_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_DEFAULT_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_DEFAULT_EXAMPLE_USAGE;
}
void ConsoleInputHandler::call(std::string args)
{
std::cout << "Test" << std::endl;
}
std::string ConsoleInputHandler::getIdentifier()
{
return identifier;
}
std::string ConsoleInputHandler::getDescription()
{
return translate(description);
}
std::string ConsoleInputHandler::getArguments()
{
return translate(arguments);
}
std::string ConsoleInputHandler::getExampleUsage()
{
std::string str = identifier + " " + translate(exampleUsage);
return str;
}
/***************************************/
// files
ConsoleFileOpen::ConsoleFileOpen()
{
identifier = "open";
description = CONSOLE_INPUT_HANDLER_FILE_OPEN_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_FILE_OPEN_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_FILE_OPEN_EXAMPLE_USAGE;
}
void ConsoleFileOpen::call(std::string args)
{
if (args == "") {
sendMessage(MESSAGE_NOT_VALID_FILENAME, "", MESSAGE_TYPE_ERROR);
return;
}
fileOpen(args);
return;
}
ConsoleFileClose::ConsoleFileClose()
{
identifier = "close";
description = CONSOLE_INPUT_HANDLER_FILE_CLOSE_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_FILE_CLOSE_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_FILE_CLOSE_EXAMPLE_USAGE;
}
void ConsoleFileClose::call(std::string args)
{
if (currentFile == NULL) // if file is not open
{
sendMessage(MESSAGE_NO_FILE_OPEN, "",MESSAGE_TYPE_ERROR);
return;
}
fileClose();
}
ConsoleFileSave::ConsoleFileSave()
{
identifier = "save";
description = CONSOLE_INPUT_HANDLER_FILE_SAVE_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_FILE_SAVE_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_FILE_SAVE_EXAMPLE_USAGE;
}
void ConsoleFileSave::call(std::string args)
{
if (currentFile == NULL) // if file is not open
{
sendMessage(MESSAGE_NO_FILE_OPEN, "", MESSAGE_TYPE_ERROR);
return;
}
if (args != "") currentFile->saveAs(args);
else currentFile->save();
}
ConsoleFileSaveAs::ConsoleFileSaveAs()
{
identifier = "saveAs";
description = CONSOLE_INPUT_HANDLER_FILE_SAVE_AS_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_FILE_SAVE_AS_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_FILE_SAVE_AS_EXAMPLE_USAGE;
}
void ConsoleFileSaveAs::call(std::string args)
{
if (currentFile == NULL) // if file is not open
{
sendMessage(MESSAGE_NO_FILE_OPEN, "",MESSAGE_TYPE_ERROR);
return;
}
if (args == "") { // if no file name provided
sendMessage(MESSAGE_NOT_VALID_FILENAME, "", MESSAGE_TYPE_ERROR);
return;
}
currentFile->saveAs(args);
}
ConsoleFileNew::ConsoleFileNew()
{
identifier = "new";
description = CONSOLE_INPUT_HANDLER_FILE_NEW_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_FILE_NEW_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_FILE_NEW_EXAMPLE_USAGE;
}
void ConsoleFileNew::call(std::string args)
{
fileNew();
}
// program functions
ConsoleQuit::ConsoleQuit()
{
identifier = "quit";
description = CONSOLE_INPUT_HANDLER_QUIT_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_QUIT_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_QUIT_EXAMPLE_USAGE;
}
void ConsoleQuit::call(std::string args)
{
quit();
}
ConsoleHelp::ConsoleHelp()
{
identifier = "help";
description = CONSOLE_INPUT_HANDLER_HELP_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_HELP_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_HELP_EXAMPLE_USAGE;
}
void ConsoleHelp::call(std::string args)
{
//set colour to green
HANDLE hConsole;
int colour = 2;
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, colour);
//if no argument
if (args == "") {
std::cout << "Help:" << std::endl;
for (int i = 0; i < NUM_HANDLERS; i++) {
std::cout << input_handlers[i]->getIdentifier() << ": "
<< input_handlers[i]->getDescription() << std::endl;
}
}
//if argument provided
else {
bool foundCall = false; // bool for whether a handler was found
for (int i = 0; i < NUM_HANDLERS; i++) {
if (input_handlers[i]->getIdentifier() == args) {
std::cout << translate(STRING_HELP_FOR) << " " << input_handlers[i]->getIdentifier() << "\n"
<< input_handlers[i]->getDescription() << "\n"
<< input_handlers[i]->getArguments() << "\n" << input_handlers[i]->getExampleUsage() << std::endl;
foundCall = 1;
break;
}
}
if (!foundCall) sendMessage(MESSAGE_NO_MATCHING_COMMAND, "", MESSAGE_TYPE_ERROR);
}
SetConsoleTextAttribute(hConsole, 15);
}
ConsoleCrash::ConsoleCrash()
{
identifier = "crash";
description = CONSOLE_INPUT_HANDLER_CRASH_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_CRASH_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_CRASH_EXAMPLE_USAGE;
}
void ConsoleCrash::call(std::string args)
{
throw std::exception("Manually initiated crash", ERROR_CODE_MANUAL_CRASH);
}
ConsoleInfo::ConsoleInfo()
{
identifier = "info";
description = CONSOLE_INPUT_HANDLER_INFO_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_INFO_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_INFO_EXAMPLE_USAGE;
}
void ConsoleInfo::call(std::string args)
{
printAppInfo();
}
// midi functions
ConsoleMidiMakeEdit::ConsoleMidiMakeEdit()
{
identifier = "makeEdit";
description = CONSOLE_INPUT_HANDLER_MAKE_EDIT_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_MAKE_EDIT_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_MAKE_EDIT_EXAMPLE_USAGE;
}
void ConsoleMidiMakeEdit::call(std::string args)
{
currentFile->makeEdit();
}
ConsoleMidiTrack::ConsoleMidiTrack()
{
identifier = "track";
description = CONSOLE_INPUT_HANDLER_MIDI_TRACK_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_MIDI_TRACK_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_MIDI_TRACK_EXAMPLE_USAGE;
}
void ConsoleMidiTrack::call(std::string args)
{
// determine request type
// based on request type, perform action
}
ConsoleMidiSelect::ConsoleMidiSelect()
{
identifier = "select";
description = CONSOLE_INPUT_HANDLER_MIDI_SELECT_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_MIDI_SELECT_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_MIDI_SELECT_EXAMPLE_USAGE;
}
void ConsoleMidiSelect::call(std::string args)
{
// use arguments to determine what to select, then select it
}
ConsoleMidiSelection::ConsoleMidiSelection()
{
identifier = "selection";
description = CONSOLE_INPUT_HANDLER_MIDI_SELECTION_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_MIDI_SELECTION_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_MIDI_SELECTION_EXAMPLE_USAGE;
}
void ConsoleMidiSelection::call(std::string args)
{
// determine action to perform based on arguments
}
ConsoleSettingsAddLanguage::ConsoleSettingsAddLanguage()
{
identifier = "addLanguage";
description = CONSOLE_INPUT_HANDLER_SETTINGS_ADD_LANGUAGE_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_SETTINGS_ADD_LANGUAGE_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_SETTINGS_ADD_LANGUAGE_EXAMPLE_USAGE;
}
void ConsoleSettingsAddLanguage::call(std::string args)
{
settings->addLanguage(args);
}
ConsolePrintTranslation::ConsolePrintTranslation()
{
identifier = "printTranslation";
description = CONSOLE_INPUT_HANDLER_PRINT_TRANSLATION_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_PRINT_TRANSLATION_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_PRINT_TRANSLATION_EXAMPLE_USAGE;
}
void ConsolePrintTranslation::call(std::string args)
{
std::stringstream ss(args);
int i;
ss >> i;
sendMessage(STRING_TRANSLATION, translate(i));
}
ConsoleRunScript::ConsoleRunScript()
{
identifier = "run";
description = CONSOLE_INPUT_HANDLER_RUN_SCRIPT_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_RUN_SCRIPT_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_RUN_SCRIPT_EXAMPLE_USAGE;
}
void ConsoleRunScript::call(std::string args) {
}
| 23.12069 | 103 | 0.764994 | MiguelGuthridge |
401cf996e5148b7507fd95cdc9a84ddbc9ae99b8 | 1,469 | hpp | C++ | brainfucppk/include/implementations/StandardImplementation.hpp | Milo46/brainfuck-interpreter | 55065f4ff80df229f29a35e1875fc195eb092cb8 | [
"MIT"
] | null | null | null | brainfucppk/include/implementations/StandardImplementation.hpp | Milo46/brainfuck-interpreter | 55065f4ff80df229f29a35e1875fc195eb092cb8 | [
"MIT"
] | 1 | 2022-02-04T14:16:44.000Z | 2022-02-04T14:16:44.000Z | brainfucppk/include/implementations/StandardImplementation.hpp | Milo46/brainfuck-interpreter | 55065f4ff80df229f29a35e1875fc195eb092cb8 | [
"MIT"
] | 1 | 2022-02-04T14:07:51.000Z | 2022-02-04T14:07:51.000Z | #pragma once
#include "core/Implementation.hpp"
#include <map>
BRAINFUCPPK_BEGIN
enum class StandardToken : char
{
IncrementPointer = '>',
DecrementPointer = '<',
IncrementValue = '+',
DecrementValue = '-',
Write = '.',
Read = ',',
BeginLoop = '[',
EndLoop = ']',
End,
};
class StandardImplementation : public Implementation
{
public:
StandardImplementation(const WarpableIterator<unsigned char>& pointer, std::ostream& output, std::istream& input);
protected:
virtual bool ResolveToken(const std::string& source, std::size_t& index) noexcept(false) override;
private:
void IncrementPointer(const std::string& source, std::size_t& index);
void DecrementPointer(const std::string& source, std::size_t& index);
void IncrementValue(const std::string& source, std::size_t& index);
void DecrementValue(const std::string& source, std::size_t& index);
void Write(const std::string& source, std::size_t& index);
void Read(const std::string& source, std::size_t& index);
void BeginLoop(const std::string& source, std::size_t& index);
void EndLoop(const std::string& source, std::size_t& index);
private:
/* The code isn't ready for that kind of thing yet. */
// bool IsThisLoopInfinite(const std::string& source, const std::size_t bracketPosition) const;
private:
std::map<std::size_t, std::size_t> m_LoopsPositions;
};
BRAINFUCPPK_END
| 29.38 | 118 | 0.673928 | Milo46 |
401e1cd2bde42a05fa8a0953fa5731908a00eb85 | 3,078 | cpp | C++ | source/sirtthread.cpp | drminix/ctsimulator | b6ef3feed5310ff43b60ddd039a6a187c6e60718 | [
"MIT"
] | 7 | 2017-02-10T10:12:48.000Z | 2022-03-06T06:43:57.000Z | source/sirtthread.cpp | drminix/ctsimulator | b6ef3feed5310ff43b60ddd039a6a187c6e60718 | [
"MIT"
] | null | null | null | source/sirtthread.cpp | drminix/ctsimulator | b6ef3feed5310ff43b60ddd039a6a187c6e60718 | [
"MIT"
] | 4 | 2017-02-21T07:31:15.000Z | 2022-03-10T02:54:49.000Z | /****************************
* Author: Sanghyeb(Sam) Lee
* Date: Jan/2013
* email: [email protected]
* Copyright 2013 Sang hyeb(Sam) Lee MIT License
*
* X-ray CT simulation & reconstruction
*****************************/
#include "SirtThread.h"
SirtThread::SirtThread(QObject *parent) :
QThread(parent)
{
}
SirtThread::SirtThread(drawingarea* tarea,int tsweeps,double trelaxation, int twhentoshow) :
maindrawingarea(tarea), sweeps(tsweeps), relaxation(trelaxation), whentoshow(twhentoshow) {
A = maindrawingarea->A; //A
x = new double[maindrawingarea->A_size.width()];
b = new double[maindrawingarea->sinogram_size.width()*maindrawingarea->sinogram_size.height()];
//setup it to running
running = true;
}
inline void swap(double** x1,double** x2) {
double* x_temp;
x_temp = *x1;
*x1 = *x2;
*x2 = x_temp;
}
void SirtThread::setupReturnBuffer(double **pBuffer) {
pX = pBuffer;
}
//perform art.
void SirtThread::run() {
//Ax = b
int a_row = this->maindrawingarea->A_size.height();
int a_column = this->maindrawingarea->A_size.width();
int x_row = a_column;
int b_row = a_row;
std::cout<<"SirtThread: started."<<std::endl;
int sino_width = maindrawingarea->sinogram_size.width();
int sino_height = maindrawingarea->sinogram_size.height();
//initialize x(estimate image) to zero
memset(x,0,sizeof(double)*x_row);
for(int i=0;i<sino_width;i++) {
//memcpy(dest,src, number of bytes)*/
memcpy(b+(sino_height*i),this->maindrawingarea->sinogram[i],sizeof(double)*sino_height);
}
//now perform ART
//main iteration.
double rs; //residual
double* diff = new double[a_row];
double Ax;
double* x_prev = new double[a_column];
for(int main_iterator=0;main_iterator<sweeps&&running==true;main_iterator++) {
//after this command, x_prev points to x, x point to new area
swap(&x_prev,&x);
for(int i=0;i<a_row;i++) {
//calculate Ax
Ax=0; //Ax
for(int j=0;j<a_column;j++) {
Ax+=A[i][j] * x_prev[j]; //Ax = Row(M) *1
}
diff[i]=b[i]-Ax; //Ax-b = Row(M)*1
}
for(int i=0;i<a_column;i++) {
double AtAx_B=0;
for(int j=0;j<a_row;j++) {
AtAx_B += A[j][i] * diff[j];
}
x[i]=x_prev[i]+(relaxation * AtAx_B);
}
//inform main window for availability
if(((main_iterator+1)%this->whentoshow)==0) {
if(*pX==NULL) { //if it is empty create it first
*pX = new double[a_column];
}
//copy the image value
memcpy(*pX,x,sizeof(double)*x_row);
//notify the main window
emit updateReady(main_iterator+1);
}
//work out residual.
rs=0;
for(int z=0;z<x_row;z++) {
rs +=fabs(this->maindrawingarea->matrix[z] -
x[z]);
}
emit singleiteration(main_iterator+1,rs);
}
}
| 26.084746 | 99 | 0.565627 | drminix |
40203db47ac7f7ebe9ed5b73ddf8f75e00a5176e | 3,743 | cc | C++ | DreamDaq/dream_to_offline/DreamDaqEventUnpacker.cc | ivivarel/DREMTubes | ac768990b4c5e2c23d986284ed10189f31796b38 | [
"MIT"
] | 3 | 2021-07-22T12:17:48.000Z | 2021-07-27T07:22:54.000Z | DreamDaq/dream_to_offline/DreamDaqEventUnpacker.cc | ivivarel/DREMTubes | ac768990b4c5e2c23d986284ed10189f31796b38 | [
"MIT"
] | 38 | 2021-07-14T15:41:04.000Z | 2022-03-29T14:18:20.000Z | DreamDaq/dream_to_offline/DreamDaqEventUnpacker.cc | ivivarel/DREMTubes | ac768990b4c5e2c23d986284ed10189f31796b38 | [
"MIT"
] | 7 | 2021-07-21T12:00:33.000Z | 2021-11-13T10:45:30.000Z | #include <cassert>
#include <cstdio>
#include "DreamDaqEventUnpacker.hh"
#include "DreamDaqEvent.h"
#include "DaqModuleUnpackers.hh"
#include "myFIFO-IOp.h"
#include "myRawFile.h"
DreamDaqEventUnpacker::DreamDaqEventUnpacker() :
event_(0)
{
}
DreamDaqEventUnpacker::DreamDaqEventUnpacker(DreamDaqEvent* event) :
event_(0)
{
setDreamDaqEvent(event);
}
DreamDaqEventUnpacker::~DreamDaqEventUnpacker()
{
}
void DreamDaqEventUnpacker::setDreamDaqEvent(DreamDaqEvent* event)
{
packSeq_.clear();
if (event)
{
// The sequence of unpackers does not matter.
// The sequence of packers can be made correct
// by calling the "setPackingSequence" method.
packSeq_.push_back(std::make_pair(&event->TDC_0, &LeCroy1176_));
packSeq_.push_back(std::make_pair(&event->ADC_C1, &CaenV792_));
packSeq_.push_back(std::make_pair(&event->ADC_C2, &CaenV792_));
packSeq_.push_back(std::make_pair(&event->ADC_L, &LeCroy1182_));
packSeq_.push_back(std::make_pair(&event->SCA_0, &CaenV260_));
packSeq_.push_back(std::make_pair(&event->SCOPE_0, &TDS7254B_));
packSeq_.push_back(std::make_pair(&event->TSENS, &TemperatureSensors_));
}
event_ = event;
}
int DreamDaqEventUnpacker::setPackingSequence(
const unsigned *subEventIds, unsigned nIds)
{
UnpakerSequence ordered;
const unsigned n_packers = packSeq_.size();
int missing_packer = 0;
for (unsigned i=0; i<nIds; ++i)
{
const unsigned id = subEventIds[i];
unsigned packer_found = 0;
for (unsigned j=0; j<n_packers; ++j)
{
DreamDaqModule *module = packSeq_[j].first;
if (module->subEventId() == id)
{
packer_found = 1;
ordered.push_back(packSeq_[j]);
break;
}
}
if (!packer_found)
{
fprintf(stderr, "Failed to find unpacker for sub event id 0x%08x\n", id);
fflush(stderr);
missing_packer++;
}
}
packSeq_ = ordered;
return missing_packer;
}
int DreamDaqEventUnpacker::unpack(unsigned *eventData) const
{
int status = 0;
for (unsigned i=0; i<packSeq_.size(); ++i)
{
DreamDaqModule *module = packSeq_[i].first;
const int ustat = packSeq_[i].second->unpack(
event_->formatVersion, module, eventData);
if (ustat == NODATA)
module->setEnabled(false);
else
{
module->setEnabled(true);
if (ustat)
status = 1;
}
}
return status;
}
int DreamDaqEventUnpacker::pack(unsigned *buf, unsigned buflen) const
{
// Create the event header
EventHeader evh;
evh.evmark = EVENTMARKER;
evh.evhsiz = sizeof(EventHeader);
evh.evnum = event_->eventNumber;
evh.spill = event_->spillNumber;
evh.tsec = event_->timeSec;
evh.tusec = event_->timeUSec;
// Pack the event header
int wordcount = sizeof(EventHeader)/sizeof(unsigned);
assert(buflen > (unsigned)wordcount);
memcpy(buf, &evh, sizeof(EventHeader));
// Pack the modules
for (unsigned i=0; i<packSeq_.size(); ++i)
{
DreamDaqModule *module = packSeq_[i].first;
if (module->enabled())
{
int sz = packSeq_[i].second->pack(
event_->formatVersion, module,
buf+wordcount, buflen-wordcount);
if (sz < 0)
return sz;
else
wordcount += sz;
}
}
// Set the correct event size (in bytes)
buf[offsetof(EventHeader, evsiz)/sizeof(unsigned)] =
wordcount*sizeof(unsigned);
return wordcount;
}
| 27.522059 | 85 | 0.604862 | ivivarel |
4021b6e5c0aafd3d6d9ab3325cc50dec47e6877b | 4,904 | hpp | C++ | inc/core/setst.hpp | frang75/nappgui | fffa48d0f93f0b7db4e547838b33b625d19c2430 | [
"MIT"
] | 25 | 2020-01-31T09:23:45.000Z | 2022-02-01T04:46:32.000Z | inc/core/setst.hpp | frang75/nappgui | fffa48d0f93f0b7db4e547838b33b625d19c2430 | [
"MIT"
] | 2 | 2021-10-20T13:05:18.000Z | 2021-11-26T08:24:31.000Z | inc/core/setst.hpp | frang75/nappgui | fffa48d0f93f0b7db4e547838b33b625d19c2430 | [
"MIT"
] | 1 | 2020-01-31T09:22:16.000Z | 2020-01-31T09:22:16.000Z | /*
* NAppGUI Cross-platform C SDK
* 2015-2021 Francisco Garcia Collado
* MIT Licence
* https://nappgui.com/en/legal/license.html
*
* File: setst.hpp
*
*/
/* Set of structures */
#ifndef __SETST_HPP__
#define __SETST_HPP__
#include "bstd.h"
#include "nowarn.hxx"
#include <typeinfo>
#include "warn.hxx"
template<class type>
struct SetSt
{
static SetSt<type>* create(int(func_compare)(const type*, const type*));
static void destroy(SetSt<type> **set, void(*func_remove)(type*));
static uint32_t size(const SetSt<type> *set);
static type* get(SetSt<type> *set, const type *key);
static const type* get(const SetSt<type> *set, const type *key);
static bool_t ddelete(SetSt<type> *set, const type *key, void(*func_remove)(type*));
static type* first(SetSt<type> *set);
static const type* first(const SetSt<type> *set);
static type* last(SetSt<type> *set);
static const type* last(const SetSt<type> *set);
static type* next(SetSt<type> *set);
static const type* next(const SetSt<type> *set);
static type* prev(SetSt<type> *set);
static const type* prev(const SetSt<type> *set);
#if defined __ASSERTS__
// Only for debuggers inspector (non used)
template<class ttype>
struct TypeNode
{
uint32_t rb;
struct TypeNode<ttype> *left;
struct TypeNode<ttype> *right;
ttype data;
};
uint32_t elems;
uint16_t esize;
uint16_t ksize;
TypeNode<type> *root;
FPtr_compare func_compare;
#endif
};
/*---------------------------------------------------------------------------*/
template<typename type>
static const char_t* i_settype(void)
{
static char_t dtype[64];
bstd_sprintf(dtype, sizeof(dtype), "SetSt<%s>", typeid(type).name());
return dtype;
}
/*---------------------------------------------------------------------------*/
template<typename type>
SetSt<type>* SetSt<type>::create(int(func_compare)(const type*, const type*))
{
return (SetSt<type>*)rbtree_create((FPtr_compare)func_compare, (uint16_t)sizeof(type), 0, i_settype<type>());
}
/*---------------------------------------------------------------------------*/
template<typename type>
void SetSt<type>::destroy(SetSt<type> **set, void(*func_remove)(type*))
{
rbtree_destroy((RBTree**)set, (FPtr_remove)func_remove, NULL, i_settype<type>());
}
/*---------------------------------------------------------------------------*/
template<typename type>
uint32_t SetSt<type>::size(const SetSt<type> *set)
{
return rbtree_size((const RBTree*)set);
}
/*---------------------------------------------------------------------------*/
template<typename type>
type* SetSt<type>::get(SetSt<type> *set, const type *key)
{
return (type*)rbtree_get((RBTree*)set, (const void*)key, FALSE);
}
/*---------------------------------------------------------------------------*/
template<typename type>
const type* SetSt<type>::get(const SetSt<type> *set, const type *key)
{
return (const type*)rbtree_get((RBTree*)set, (const void*)key, FALSE);
}
/*---------------------------------------------------------------------------*/
template<typename type>
bool_t SetSt<type>::ddelete(SetSt<type> *set, const type *key, void(*func_remove)(type*))
{
return rbtree_delete((RBTree*)set, (const void*)key, (FPtr_remove)func_remove, NULL);
}
/*---------------------------------------------------------------------------*/
template<typename type>
type* SetSt<type>::first(SetSt<type> *set)
{
return (type*)rbtree_first((RBTree*)set);
}
/*---------------------------------------------------------------------------*/
template<typename type>
const type* SetSt<type>::first(const SetSt<type> *set)
{
return (const type*)rbtree_first((RBTree*)set);
}
/*---------------------------------------------------------------------------*/
template<typename type>
type* SetSt<type>::last(SetSt<type> *set)
{
return (type*)rbtree_last((RBTree*)set);
}
/*---------------------------------------------------------------------------*/
template<typename type>
const type* SetSt<type>::last(const SetSt<type> *set)
{
return (const type*)rbtree_last((RBTree*)set);
}
/*---------------------------------------------------------------------------*/
template<typename type>
type* SetSt<type>::next(SetSt<type> *set)
{
return (type*)rbtree_next((RBTree*)set);
}
/*---------------------------------------------------------------------------*/
template<typename type>
const type* SetSt<type>::next(const SetSt<type> *set)
{
return (const type*)rbtree_next((RBTree*)set);
}
/*---------------------------------------------------------------------------*/
template<typename type>
type* SetSt<type>::prev(SetSt<type> *set)
{
return (type*)rbtree_prev((RBTree*)set);
}
/*---------------------------------------------------------------------------*/
template<typename type>
const type* SetSt<type>::prev(const SetSt<type> *set)
{
return (const type*)rbtree_prev((RBTree*)set);
}
#endif
| 25.278351 | 113 | 0.530995 | frang75 |
40257420d09a9d8802142b66e2fde1874bb642c4 | 59,307 | cpp | C++ | OgreMain/src/OgreRenderSystem.cpp | FreeNightKnight/ogre-next | f2d1a31887a87c492b4225e063325c48693fec19 | [
"MIT"
] | null | null | null | OgreMain/src/OgreRenderSystem.cpp | FreeNightKnight/ogre-next | f2d1a31887a87c492b4225e063325c48693fec19 | [
"MIT"
] | null | null | null | OgreMain/src/OgreRenderSystem.cpp | FreeNightKnight/ogre-next | f2d1a31887a87c492b4225e063325c48693fec19 | [
"MIT"
] | null | null | null | /*
-----------------------------------------------------------------------------
This source file is part of OGRE-Next
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 "OgreStableHeaders.h"
// RenderSystem implementation
// Note that most of this class is abstract since
// we cannot know how to implement the behaviour without
// being aware of the 3D API. However there are a few
// simple functions which can have a base implementation
#include "OgreRenderSystem.h"
#include "Compositor/OgreCompositorManager2.h"
#include "Compositor/OgreCompositorWorkspace.h"
#include "OgreDepthBuffer.h"
#include "OgreDescriptorSetUav.h"
#include "OgreException.h"
#include "OgreHardwareOcclusionQuery.h"
#include "OgreHlmsPso.h"
#include "OgreIteratorWrappers.h"
#include "OgreLogManager.h"
#include "OgreLwString.h"
#include "OgreMaterialManager.h"
#include "OgreProfiler.h"
#include "OgreRoot.h"
#include "OgreTextureGpuManager.h"
#include "OgreViewport.h"
#include "OgreWindow.h"
#include "Vao/OgreUavBufferPacked.h"
#include "Vao/OgreVaoManager.h"
#include "Vao/OgreVertexArrayObject.h"
#if OGRE_NO_RENDERDOC_INTEGRATION == 0
# include "renderdoc/renderdoc_app.h"
# if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
# define WIN32_LEAN_AND_MEAN
# define VC_EXTRALEAN
# define NOMINMAX
# include <windows.h>
# endif
#endif
namespace Ogre
{
RenderSystem::ListenerList RenderSystem::msSharedEventListeners;
//-----------------------------------------------------------------------
RenderSystem::RenderSystem() :
mCurrentRenderPassDescriptor( 0 ),
mMaxBoundViewports( 16u ),
mVaoManager( 0 ),
mTextureGpuManager( 0 )
#if OGRE_DEBUG_MODE >= OGRE_DEBUG_HIGH
,
mDebugShaders( true )
#else
,
mDebugShaders( false )
#endif
,
mWBuffer( false ),
mInvertVertexWinding( false ),
mDisabledTexUnitsFrom( 0 ),
mCurrentPassIterationCount( 0 ),
mCurrentPassIterationNum( 0 ),
mDerivedDepthBias( false ),
mDerivedDepthBiasBase( 0.0f ),
mDerivedDepthBiasMultiplier( 0.0f ),
mDerivedDepthBiasSlopeScale( 0.0f ),
mUavRenderingDirty( false ),
mUavStartingSlot( 1 ),
mUavRenderingDescSet( 0 ),
mGlobalInstanceVertexBufferVertexDeclaration( NULL ),
mGlobalNumberOfInstances( 1 ),
mRenderDocApi( 0 ),
mVertexProgramBound( false ),
mGeometryProgramBound( false ),
mFragmentProgramBound( false ),
mTessellationHullProgramBound( false ),
mTessellationDomainProgramBound( false ),
mComputeProgramBound( false ),
mClipPlanesDirty( true ),
mRealCapabilities( 0 ),
mCurrentCapabilities( 0 ),
mUseCustomCapabilities( false ),
mNativeShadingLanguageVersion( 0 ),
mTexProjRelative( false ),
mTexProjRelativeOrigin( Vector3::ZERO ),
mReverseDepth( true ),
mInvertedClipSpaceY( false )
{
mEventNames.push_back( "RenderSystemCapabilitiesCreated" );
}
//-----------------------------------------------------------------------
RenderSystem::~RenderSystem()
{
shutdown();
OGRE_DELETE mRealCapabilities;
mRealCapabilities = 0;
// Current capabilities managed externally
mCurrentCapabilities = 0;
}
//-----------------------------------------------------------------------
Window *RenderSystem::_initialise( bool autoCreateWindow, const String &windowTitle )
{
// Have I been registered by call to Root::setRenderSystem?
/** Don't do this anymore, just allow via Root
RenderSystem* regPtr = Root::getSingleton().getRenderSystem();
if (!regPtr || regPtr != this)
// Register self - library user has come to me direct
Root::getSingleton().setRenderSystem(this);
*/
// Subclasses should take it from here
// They should ALL call this superclass method from
// their own initialise() implementations.
mVertexProgramBound = false;
mGeometryProgramBound = false;
mFragmentProgramBound = false;
mTessellationHullProgramBound = false;
mTessellationDomainProgramBound = false;
mComputeProgramBound = false;
return 0;
}
//---------------------------------------------------------------------------------------------
void RenderSystem::useCustomRenderSystemCapabilities( RenderSystemCapabilities *capabilities )
{
if( mRealCapabilities != 0 )
{
OGRE_EXCEPT(
Exception::ERR_INTERNAL_ERROR,
"Custom render capabilities must be set before the RenderSystem is initialised.",
"RenderSystem::useCustomRenderSystemCapabilities" );
}
mCurrentCapabilities = capabilities;
mUseCustomCapabilities = true;
}
//---------------------------------------------------------------------------------------------
bool RenderSystem::_createRenderWindows( const RenderWindowDescriptionList &renderWindowDescriptions,
WindowList &createdWindows )
{
unsigned int fullscreenWindowsCount = 0;
// Grab some information and avoid duplicate render windows.
for( unsigned int nWindow = 0; nWindow < renderWindowDescriptions.size(); ++nWindow )
{
const RenderWindowDescription *curDesc = &renderWindowDescriptions[nWindow];
// Count full screen windows.
if( curDesc->useFullScreen )
fullscreenWindowsCount++;
bool renderWindowFound = false;
for( unsigned int nSecWindow = nWindow + 1; nSecWindow < renderWindowDescriptions.size();
++nSecWindow )
{
if( curDesc->name == renderWindowDescriptions[nSecWindow].name )
{
renderWindowFound = true;
break;
}
}
// Make sure we don't already have a render target of the
// same name as the one supplied
if( renderWindowFound )
{
String msg;
msg = "A render target of the same name '" + String( curDesc->name ) +
"' already "
"exists. You cannot create a new window with this name.";
OGRE_EXCEPT( Exception::ERR_INTERNAL_ERROR, msg, "RenderSystem::createRenderWindow" );
}
}
// Case we have to create some full screen rendering windows.
if( fullscreenWindowsCount > 0 )
{
// Can not mix full screen and windowed rendering windows.
if( fullscreenWindowsCount != renderWindowDescriptions.size() )
{
OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS,
"Can not create mix of full screen and windowed rendering windows",
"RenderSystem::createRenderWindows" );
}
}
return true;
}
//---------------------------------------------------------------------------------------------
void RenderSystem::destroyRenderWindow( Window *window )
{
WindowSet::iterator itor = mWindows.find( window );
if( itor == mWindows.end() )
{
OGRE_EXCEPT( Exception::ERR_ITEM_NOT_FOUND,
"Window does not belong to us or is already deleted!",
"RenderSystem::destroyRenderWindow" );
}
mWindows.erase( window );
OGRE_DELETE window;
}
//-----------------------------------------------------------------------
void RenderSystem::_setPipelineStateObject( const HlmsPso *pso )
{
assert( ( !pso || pso->rsData ) &&
"The PipelineStateObject must have been created via "
"RenderSystem::_hlmsPipelineStateObjectCreated!" );
// Disable previous state
mActiveVertexGpuProgramParameters.reset();
mActiveGeometryGpuProgramParameters.reset();
mActiveTessellationHullGpuProgramParameters.reset();
mActiveTessellationDomainGpuProgramParameters.reset();
mActiveFragmentGpuProgramParameters.reset();
mActiveComputeGpuProgramParameters.reset();
if( mVertexProgramBound && !mClipPlanes.empty() )
mClipPlanesDirty = true;
mVertexProgramBound = false;
mGeometryProgramBound = false;
mFragmentProgramBound = false;
mTessellationHullProgramBound = false;
mTessellationDomainProgramBound = false;
mComputeProgramBound = false;
// Derived class must set new state
}
//-----------------------------------------------------------------------
void RenderSystem::_setTextureUnitSettings( size_t texUnit, TextureUnitState &tl )
{
// This method is only ever called to set a texture unit to valid details
// The method _disableTextureUnit is called to turn a unit off
TextureGpu *tex = tl._getTexturePtr();
bool isValidBinding = false;
if( mCurrentCapabilities->hasCapability( RSC_COMPLETE_TEXTURE_BINDING ) )
_setBindingType( tl.getBindingType() );
// Vertex texture binding?
if( mCurrentCapabilities->hasCapability( RSC_VERTEX_TEXTURE_FETCH ) &&
!mCurrentCapabilities->getVertexTextureUnitsShared() )
{
isValidBinding = true;
if( tl.getBindingType() == TextureUnitState::BT_VERTEX )
{
// Bind vertex texture
_setVertexTexture( texUnit, tex );
// bind nothing to fragment unit (hardware isn't shared but fragment
// unit can't be using the same index
_setTexture( texUnit, 0, false );
}
else
{
// vice versa
_setVertexTexture( texUnit, 0 );
_setTexture( texUnit, tex,
mCurrentRenderPassDescriptor->mDepth.texture &&
mCurrentRenderPassDescriptor->mDepth.texture == tex );
}
}
if( mCurrentCapabilities->hasCapability( RSC_GEOMETRY_PROGRAM ) )
{
isValidBinding = true;
if( tl.getBindingType() == TextureUnitState::BT_GEOMETRY )
{
// Bind vertex texture
_setGeometryTexture( texUnit, tex );
// bind nothing to fragment unit (hardware isn't shared but fragment
// unit can't be using the same index
_setTexture( texUnit, 0, false );
}
else
{
// vice versa
_setGeometryTexture( texUnit, 0 );
_setTexture( texUnit, tex,
mCurrentRenderPassDescriptor->mDepth.texture &&
mCurrentRenderPassDescriptor->mDepth.texture == tex );
}
}
if( mCurrentCapabilities->hasCapability( RSC_TESSELLATION_DOMAIN_PROGRAM ) )
{
isValidBinding = true;
if( tl.getBindingType() == TextureUnitState::BT_TESSELLATION_DOMAIN )
{
// Bind vertex texture
_setTessellationDomainTexture( texUnit, tex );
// bind nothing to fragment unit (hardware isn't shared but fragment
// unit can't be using the same index
_setTexture( texUnit, 0, false );
}
else
{
// vice versa
_setTessellationDomainTexture( texUnit, 0 );
_setTexture( texUnit, tex,
mCurrentRenderPassDescriptor->mDepth.texture &&
mCurrentRenderPassDescriptor->mDepth.texture == tex );
}
}
if( mCurrentCapabilities->hasCapability( RSC_TESSELLATION_HULL_PROGRAM ) )
{
isValidBinding = true;
if( tl.getBindingType() == TextureUnitState::BT_TESSELLATION_HULL )
{
// Bind vertex texture
_setTessellationHullTexture( texUnit, tex );
// bind nothing to fragment unit (hardware isn't shared but fragment
// unit can't be using the same index
_setTexture( texUnit, 0, false );
}
else
{
// vice versa
_setTessellationHullTexture( texUnit, 0 );
_setTexture( texUnit, tex,
mCurrentRenderPassDescriptor->mDepth.texture &&
mCurrentRenderPassDescriptor->mDepth.texture == tex );
}
}
if( !isValidBinding )
{
// Shared vertex / fragment textures or no vertex texture support
// Bind texture (may be blank)
_setTexture( texUnit, tex,
mCurrentRenderPassDescriptor->mDepth.texture &&
mCurrentRenderPassDescriptor->mDepth.texture == tex );
}
_setHlmsSamplerblock( (uint8)texUnit, tl.getSamplerblock() );
// Set blend modes
// Note, colour before alpha is important
_setTextureBlendMode( texUnit, tl.getColourBlendMode() );
_setTextureBlendMode( texUnit, tl.getAlphaBlendMode() );
// Set texture effects
TextureUnitState::EffectMap::iterator effi;
// Iterate over new effects
bool anyCalcs = false;
for( effi = tl.mEffects.begin(); effi != tl.mEffects.end(); ++effi )
{
switch( effi->second.type )
{
case TextureUnitState::ET_ENVIRONMENT_MAP:
if( effi->second.subtype == TextureUnitState::ENV_CURVED )
{
_setTextureCoordCalculation( texUnit, TEXCALC_ENVIRONMENT_MAP );
anyCalcs = true;
}
else if( effi->second.subtype == TextureUnitState::ENV_PLANAR )
{
_setTextureCoordCalculation( texUnit, TEXCALC_ENVIRONMENT_MAP_PLANAR );
anyCalcs = true;
}
else if( effi->second.subtype == TextureUnitState::ENV_REFLECTION )
{
_setTextureCoordCalculation( texUnit, TEXCALC_ENVIRONMENT_MAP_REFLECTION );
anyCalcs = true;
}
else if( effi->second.subtype == TextureUnitState::ENV_NORMAL )
{
_setTextureCoordCalculation( texUnit, TEXCALC_ENVIRONMENT_MAP_NORMAL );
anyCalcs = true;
}
break;
case TextureUnitState::ET_UVSCROLL:
case TextureUnitState::ET_USCROLL:
case TextureUnitState::ET_VSCROLL:
case TextureUnitState::ET_ROTATE:
case TextureUnitState::ET_TRANSFORM:
break;
case TextureUnitState::ET_PROJECTIVE_TEXTURE:
_setTextureCoordCalculation( texUnit, TEXCALC_PROJECTIVE_TEXTURE, effi->second.frustum );
anyCalcs = true;
break;
}
}
// Ensure any previous texcoord calc settings are reset if there are now none
if( !anyCalcs )
{
_setTextureCoordCalculation( texUnit, TEXCALC_NONE );
}
// Change tetxure matrix
_setTextureMatrix( texUnit, tl.getTextureTransform() );
}
//-----------------------------------------------------------------------
void RenderSystem::_setBindingType( TextureUnitState::BindingType bindingType )
{
OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED,
"This rendersystem does not support binding texture to other shaders then fragment",
"RenderSystem::_setBindingType" );
}
//-----------------------------------------------------------------------
void RenderSystem::_setVertexTexture( size_t unit, TextureGpu *tex )
{
OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED,
"This rendersystem does not support separate vertex texture samplers, "
"you should use the regular texture samplers which are shared between "
"the vertex and fragment units.",
"RenderSystem::_setVertexTexture" );
}
//-----------------------------------------------------------------------
void RenderSystem::_setGeometryTexture( size_t unit, TextureGpu *tex )
{
OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED,
"This rendersystem does not support separate geometry texture samplers, "
"you should use the regular texture samplers which are shared between "
"the vertex and fragment units.",
"RenderSystem::_setGeometryTexture" );
}
//-----------------------------------------------------------------------
void RenderSystem::_setTessellationHullTexture( size_t unit, TextureGpu *tex )
{
OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED,
"This rendersystem does not support separate tessellation hull texture samplers, "
"you should use the regular texture samplers which are shared between "
"the vertex and fragment units.",
"RenderSystem::_setTessellationHullTexture" );
}
//-----------------------------------------------------------------------
void RenderSystem::_setTessellationDomainTexture( size_t unit, TextureGpu *tex )
{
OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED,
"This rendersystem does not support separate tessellation domain texture samplers, "
"you should use the regular texture samplers which are shared between "
"the vertex and fragment units.",
"RenderSystem::_setTessellationDomainTexture" );
}
//-----------------------------------------------------------------------
void RenderSystem::destroyRenderPassDescriptor( RenderPassDescriptor *renderPassDesc )
{
RenderPassDescriptorSet::iterator itor = mRenderPassDescs.find( renderPassDesc );
assert( itor != mRenderPassDescs.end() && "Already destroyed?" );
if( itor != mRenderPassDescs.end() )
mRenderPassDescs.erase( itor );
if( renderPassDesc->mDepth.texture )
{
_dereferenceSharedDepthBuffer( renderPassDesc->mDepth.texture );
if( renderPassDesc->mStencil.texture &&
renderPassDesc->mStencil.texture == renderPassDesc->mDepth.texture )
{
_dereferenceSharedDepthBuffer( renderPassDesc->mStencil.texture );
renderPassDesc->mStencil.texture = 0;
}
}
if( renderPassDesc->mStencil.texture )
{
_dereferenceSharedDepthBuffer( renderPassDesc->mStencil.texture );
renderPassDesc->mStencil.texture = 0;
}
delete renderPassDesc;
}
//---------------------------------------------------------------------
void RenderSystem::destroyAllRenderPassDescriptors()
{
RenderPassDescriptorSet::const_iterator itor = mRenderPassDescs.begin();
RenderPassDescriptorSet::const_iterator endt = mRenderPassDescs.end();
while( itor != endt )
delete *itor++;
mRenderPassDescs.clear();
}
//---------------------------------------------------------------------
void RenderSystem::beginRenderPassDescriptor( RenderPassDescriptor *desc, TextureGpu *anyTarget,
uint8 mipLevel, const Vector4 *viewportSizes,
const Vector4 *scissors, uint32 numViewports,
bool overlaysEnabled, bool warnIfRtvWasFlushed )
{
assert( anyTarget );
mCurrentRenderPassDescriptor = desc;
for( size_t i = 0; i < numViewports; ++i )
{
mCurrentRenderViewport[i].setDimensions( anyTarget, viewportSizes[i], scissors[i],
mipLevel );
mCurrentRenderViewport[i].setOverlaysEnabled( overlaysEnabled );
}
mMaxBoundViewports = numViewports;
}
//---------------------------------------------------------------------
void RenderSystem::executeRenderPassDescriptorDelayedActions() {}
//---------------------------------------------------------------------
void RenderSystem::endRenderPassDescriptor()
{
mCurrentRenderPassDescriptor = 0;
const size_t maxBoundViewports = mMaxBoundViewports;
for( size_t i = 0; i < maxBoundViewports; ++i )
mCurrentRenderViewport[i].setDimensions( 0, Vector4::ZERO, Vector4::ZERO, 0u );
mMaxBoundViewports = 1u;
// Where graphics ends, compute may start, or a new frame.
// Very likely we'll have to flush the UAVs again, so assume we need.
mUavRenderingDirty = true;
}
//---------------------------------------------------------------------
void RenderSystem::destroySharedDepthBuffer( TextureGpu *depthBuffer )
{
TextureGpuVec &bufferVec = mDepthBufferPool2[depthBuffer->getDepthBufferPoolId()];
TextureGpuVec::iterator itor = std::find( bufferVec.begin(), bufferVec.end(), depthBuffer );
if( itor != bufferVec.end() )
{
efficientVectorRemove( bufferVec, itor );
mTextureGpuManager->destroyTexture( depthBuffer );
}
}
//---------------------------------------------------------------------
void RenderSystem::_cleanupDepthBuffers()
{
TextureGpuSet::const_iterator itor = mSharedDepthBufferZeroRefCandidates.begin();
TextureGpuSet::const_iterator endt = mSharedDepthBufferZeroRefCandidates.end();
while( itor != endt )
{
// When a shared depth buffer ends up in mSharedDepthBufferZeroRefCandidates,
// it's because its ref. count reached 0. However it may have been reacquired.
// We need to check its reference count is still 0 before deleting it.
DepthBufferRefMap::iterator itMap = mSharedDepthBufferRefs.find( *itor );
if( itMap != mSharedDepthBufferRefs.end() && itMap->second == 0u )
{
destroySharedDepthBuffer( *itor );
mSharedDepthBufferRefs.erase( itMap );
}
++itor;
}
mSharedDepthBufferZeroRefCandidates.clear();
}
//---------------------------------------------------------------------
void RenderSystem::referenceSharedDepthBuffer( TextureGpu *depthBuffer )
{
OGRE_ASSERT_MEDIUM( depthBuffer->getSourceType() == TextureSourceType::SharedDepthBuffer );
OGRE_ASSERT_MEDIUM( mSharedDepthBufferRefs.find( depthBuffer ) != mSharedDepthBufferRefs.end() );
++mSharedDepthBufferRefs[depthBuffer];
}
//---------------------------------------------------------------------
void RenderSystem::_dereferenceSharedDepthBuffer( TextureGpu *depthBuffer )
{
if( !depthBuffer )
return;
DepthBufferRefMap::iterator itor = mSharedDepthBufferRefs.find( depthBuffer );
if( itor != mSharedDepthBufferRefs.end() )
{
OGRE_ASSERT_MEDIUM( depthBuffer->getSourceType() == TextureSourceType::SharedDepthBuffer );
OGRE_ASSERT_LOW( itor->second > 0u && "Releasing a shared depth buffer too much" );
--itor->second;
if( itor->second == 0u )
mSharedDepthBufferZeroRefCandidates.insert( depthBuffer );
}
else
{
// This is not a shared depth buffer (e.g. one created by the user)
OGRE_ASSERT_MEDIUM( depthBuffer->getSourceType() != TextureSourceType::SharedDepthBuffer );
}
}
//---------------------------------------------------------------------
void RenderSystem::selectDepthBufferFormat( const uint8 supportedFormats )
{
if( ( DepthBuffer::AvailableDepthFormats & DepthBuffer::DFM_D32 ) &&
( supportedFormats & DepthBuffer::DFM_D32 ) )
{
if( DepthBuffer::AvailableDepthFormats & DepthBuffer::DFM_S8 )
DepthBuffer::DefaultDepthBufferFormat = PFG_D32_FLOAT_S8X24_UINT;
else
DepthBuffer::DefaultDepthBufferFormat = PFG_D32_FLOAT;
}
else if( DepthBuffer::AvailableDepthFormats & ( DepthBuffer::DFM_D32 | DepthBuffer::DFM_D24 ) &&
( supportedFormats & DepthBuffer::DFM_D24 ) )
{
if( DepthBuffer::AvailableDepthFormats & DepthBuffer::DFM_S8 )
DepthBuffer::DefaultDepthBufferFormat = PFG_D24_UNORM_S8_UINT;
else
DepthBuffer::DefaultDepthBufferFormat = PFG_D24_UNORM;
}
else if( DepthBuffer::AvailableDepthFormats &
( DepthBuffer::DFM_D32 | DepthBuffer::DFM_D24 | DepthBuffer::DFM_D16 ) &&
( supportedFormats & DepthBuffer::DFM_D16 ) )
{
DepthBuffer::DefaultDepthBufferFormat = PFG_D16_UNORM;
}
else
DepthBuffer::DefaultDepthBufferFormat = PFG_NULL;
}
//---------------------------------------------------------------------
TextureGpu *RenderSystem::createDepthBufferFor( TextureGpu *colourTexture, bool preferDepthTexture,
PixelFormatGpu depthBufferFormat, uint16 poolId )
{
uint32 textureFlags = TextureFlags::RenderToTexture;
if( !preferDepthTexture )
textureFlags |= TextureFlags::NotTexture | TextureFlags::DiscardableContent;
char tmpBuffer[64];
LwString depthBufferName( LwString::FromEmptyPointer( tmpBuffer, sizeof( tmpBuffer ) ) );
depthBufferName.a( "DepthBuffer_", Id::generateNewId<TextureGpu>() );
TextureGpu *retVal = mTextureGpuManager->createTexture(
depthBufferName.c_str(), GpuPageOutStrategy::Discard, textureFlags, TextureTypes::Type2D );
retVal->setResolution( colourTexture->getInternalWidth(), colourTexture->getInternalHeight() );
retVal->setPixelFormat( depthBufferFormat );
retVal->_setDepthBufferDefaults( poolId, preferDepthTexture, depthBufferFormat );
retVal->_setSourceType( TextureSourceType::SharedDepthBuffer );
retVal->setSampleDescription( colourTexture->getRequestedSampleDescription() );
retVal->_transitionTo( GpuResidency::Resident, (uint8 *)0 );
// Start reference count on the depth buffer here
mSharedDepthBufferRefs[retVal] = 1u;
return retVal;
}
//---------------------------------------------------------------------
TextureGpu *RenderSystem::getDepthBufferFor( TextureGpu *colourTexture, uint16 poolId,
bool preferDepthTexture,
PixelFormatGpu depthBufferFormat )
{
if( poolId == DepthBuffer::POOL_NO_DEPTH || depthBufferFormat == PFG_NULL )
return 0; // RenderTarget explicitly requested no depth buffer
if( colourTexture->isRenderWindowSpecific() )
{
Window *window;
colourTexture->getCustomAttribute( "Window", &window );
return window->getDepthBuffer();
}
if( poolId == DepthBuffer::POOL_NON_SHAREABLE )
{
TextureGpu *retVal =
createDepthBufferFor( colourTexture, preferDepthTexture, depthBufferFormat, poolId );
return retVal;
}
// Find a depth buffer in the pool
TextureGpuVec::const_iterator itor = mDepthBufferPool2[poolId].begin();
TextureGpuVec::const_iterator endt = mDepthBufferPool2[poolId].end();
TextureGpu *retVal = 0;
while( itor != endt && !retVal )
{
if( preferDepthTexture == ( *itor )->isTexture() &&
( depthBufferFormat == PFG_UNKNOWN ||
depthBufferFormat == ( *itor )->getPixelFormat() ) &&
( *itor )->supportsAsDepthBufferFor( colourTexture ) )
{
retVal = *itor;
referenceSharedDepthBuffer( retVal );
}
else
{
retVal = 0;
}
++itor;
}
// Not found yet? Create a new one!
if( !retVal )
{
retVal =
createDepthBufferFor( colourTexture, preferDepthTexture, depthBufferFormat, poolId );
mDepthBufferPool2[poolId].push_back( retVal );
if( !retVal )
{
LogManager::getSingleton().logMessage(
"WARNING: Couldn't create a suited "
"DepthBuffer for RTT: " +
colourTexture->getNameStr(),
LML_CRITICAL );
}
}
return retVal;
}
//---------------------------------------------------------------------
void RenderSystem::setUavStartingSlot( uint32 startingSlot )
{
mUavStartingSlot = startingSlot;
mUavRenderingDirty = true;
}
//---------------------------------------------------------------------
void RenderSystem::queueBindUAVs( const DescriptorSetUav *descSetUav )
{
if( mUavRenderingDescSet != descSetUav )
{
mUavRenderingDescSet = descSetUav;
mUavRenderingDirty = true;
}
}
//-----------------------------------------------------------------------
BoundUav RenderSystem::getBoundUav( size_t slot ) const
{
BoundUav retVal;
memset( &retVal, 0, sizeof( retVal ) );
if( mUavRenderingDescSet )
{
if( slot < mUavRenderingDescSet->mUavs.size() )
{
if( mUavRenderingDescSet->mUavs[slot].isTexture() )
{
retVal.rttOrBuffer = mUavRenderingDescSet->mUavs[slot].getTexture().texture;
retVal.boundAccess = mUavRenderingDescSet->mUavs[slot].getTexture().access;
}
else
{
retVal.rttOrBuffer = mUavRenderingDescSet->mUavs[slot].getBuffer().buffer;
retVal.boundAccess = mUavRenderingDescSet->mUavs[slot].getBuffer().access;
}
}
}
return retVal;
}
//-----------------------------------------------------------------------
void RenderSystem::_beginFrameOnce() { mVaoManager->_beginFrame(); }
//-----------------------------------------------------------------------
void RenderSystem::_endFrameOnce() { queueBindUAVs( 0 ); }
//-----------------------------------------------------------------------
bool RenderSystem::getWBufferEnabled() const { return mWBuffer; }
//-----------------------------------------------------------------------
void RenderSystem::setWBufferEnabled( bool enabled ) { mWBuffer = enabled; }
//-----------------------------------------------------------------------
SampleDescription RenderSystem::validateSampleDescription( const SampleDescription &sampleDesc,
PixelFormatGpu format )
{
SampleDescription retVal( sampleDesc.getMaxSamples(), sampleDesc.getMsaaPattern() );
return retVal;
}
//-----------------------------------------------------------------------
void RenderSystem::shutdown()
{
// Remove occlusion queries
for( HardwareOcclusionQueryList::iterator i = mHwOcclusionQueries.begin();
i != mHwOcclusionQueries.end(); ++i )
{
OGRE_DELETE *i;
}
mHwOcclusionQueries.clear();
destroyAllRenderPassDescriptors();
_cleanupDepthBuffers();
OGRE_ASSERT_LOW( mSharedDepthBufferRefs.empty() &&
"destroyAllRenderPassDescriptors followed by _cleanupDepthBuffers should've "
"emptied mSharedDepthBufferRefs. Please report this bug to "
"https://github.com/OGRECave/ogre-next/issues/" );
OGRE_DELETE mTextureGpuManager;
mTextureGpuManager = 0;
OGRE_DELETE mVaoManager;
mVaoManager = 0;
{
// Remove all windows.
// (destroy primary window last since others may depend on it)
Window *primary = 0;
WindowSet::const_iterator itor = mWindows.begin();
WindowSet::const_iterator endt = mWindows.end();
while( itor != endt )
{
// Set mTextureManager to 0 as it is no longer valid on shutdown
if( ( *itor )->getTexture() )
( *itor )->getTexture()->_resetTextureManager();
if( ( *itor )->getDepthBuffer() )
( *itor )->getDepthBuffer()->_resetTextureManager();
if( ( *itor )->getStencilBuffer() )
( *itor )->getStencilBuffer()->_resetTextureManager();
if( !primary && ( *itor )->isPrimary() )
primary = *itor;
else
OGRE_DELETE *itor;
++itor;
}
OGRE_DELETE primary;
mWindows.clear();
}
}
//-----------------------------------------------------------------------
void RenderSystem::_resetMetrics()
{
const bool oldValue = mMetrics.mIsRecordingMetrics;
mMetrics = RenderingMetrics();
mMetrics.mIsRecordingMetrics = oldValue;
}
//-----------------------------------------------------------------------
void RenderSystem::_addMetrics( const RenderingMetrics &newMetrics )
{
if( mMetrics.mIsRecordingMetrics )
{
mMetrics.mBatchCount += newMetrics.mBatchCount;
mMetrics.mFaceCount += newMetrics.mFaceCount;
mMetrics.mVertexCount += newMetrics.mVertexCount;
mMetrics.mDrawCount += newMetrics.mDrawCount;
mMetrics.mInstanceCount += newMetrics.mInstanceCount;
}
}
//-----------------------------------------------------------------------
void RenderSystem::setMetricsRecordingEnabled( bool bEnable )
{
mMetrics.mIsRecordingMetrics = bEnable;
}
//-----------------------------------------------------------------------
const RenderingMetrics &RenderSystem::getMetrics() const { return mMetrics; }
//-----------------------------------------------------------------------
void RenderSystem::convertColourValue( const ColourValue &colour, uint32 *pDest )
{
*pDest = v1::VertexElement::convertColourValue( colour, getColourVertexElementType() );
}
//-----------------------------------------------------------------------
CompareFunction RenderSystem::reverseCompareFunction( CompareFunction depthFunc )
{
switch( depthFunc )
{
case CMPF_LESS:
return CMPF_GREATER;
case CMPF_LESS_EQUAL:
return CMPF_GREATER_EQUAL;
case CMPF_GREATER_EQUAL:
return CMPF_LESS_EQUAL;
case CMPF_GREATER:
return CMPF_LESS;
default:
return depthFunc;
}
return depthFunc;
}
//-----------------------------------------------------------------------
void RenderSystem::_makeRsProjectionMatrix( const Matrix4 &matrix, Matrix4 &dest, Real nearPlane,
Real farPlane, ProjectionType projectionType )
{
dest = matrix;
Real inv_d = 1 / ( farPlane - nearPlane );
Real q, qn;
if( mReverseDepth )
{
if( projectionType == PT_PERSPECTIVE )
{
if( farPlane == 0 )
{
// Infinite far plane
// q = limit( near / (far - near), far, inf );
// qn = limit( (far * near) / (far - near), far, inf );
q = 0;
qn = nearPlane;
}
else
{
// Standard Z for range [-1; 1]
// q = - (far + near) / (far - near)
// qn = - 2 * (far * near) / (far - near)
//
// Standard Z for range [0; 1]
// q = - far / (far - near)
// qn = - (far * near) / (far - near)
//
// Reverse Z for range [1; 0]:
// [ 1 0 0 0 ] [ A 0 C 0 ]
// [ 0 1 0 0 ] X [ 0 B D 0 ]
// [ 0 0 -1 1 ] [ 0 0 q qn ]
// [ 0 0 0 1 ] [ 0 0 -1 0 ]
//
// [ A 0 C 0 ]
// [ 0 B D 0 ]
// [ 0 0 -q-1 -qn ]
// [ 0 0 -1 0 ]
//
// q' = -q - 1
// = far / (far - near) - 1
// = ( far - (far - near) ) / (far - near)
// q' = near / (far - near)
// qn'= -qn
q = nearPlane * inv_d;
qn = ( farPlane * nearPlane ) * inv_d;
}
}
else
{
if( farPlane == 0 )
{
// Can not do infinite far plane here, avoid divided zero only
q = Frustum::INFINITE_FAR_PLANE_ADJUST / nearPlane;
qn = Frustum::INFINITE_FAR_PLANE_ADJUST + 1;
}
else
{
// Standard Z for range [-1; 1]
// q = - 2 / (far - near)
// qn = -(far + near) / (far - near)
//
// Standard Z for range [0; 1]
// q = - 1 / (far - near)
// qn = - near / (far - near)
//
// Reverse Z for range [1; 0]:
// q' = 1 / (far - near)
// qn'= far / (far - near)
q = inv_d;
qn = farPlane * inv_d;
}
}
}
else
{
if( projectionType == PT_PERSPECTIVE )
{
if( farPlane == 0 )
{
// Infinite far plane
q = Frustum::INFINITE_FAR_PLANE_ADJUST - 1;
qn = nearPlane * ( Frustum::INFINITE_FAR_PLANE_ADJUST - 1 );
}
else
{
q = -farPlane * inv_d;
qn = -( farPlane * nearPlane ) * inv_d;
}
}
else
{
if( farPlane == 0 )
{
// Can not do infinite far plane here, avoid divided zero only
q = -Frustum::INFINITE_FAR_PLANE_ADJUST / nearPlane;
qn = -Frustum::INFINITE_FAR_PLANE_ADJUST;
}
else
{
q = -inv_d;
qn = -nearPlane * inv_d;
}
}
}
dest[2][2] = q;
dest[2][3] = qn;
}
//-----------------------------------------------------------------------
void RenderSystem::_convertProjectionMatrix( const Matrix4 &matrix, Matrix4 &dest )
{
dest = matrix;
if( !mReverseDepth )
{
// Convert depth range from [-1,+1] to [0,1]
dest[2][0] = ( dest[2][0] + dest[3][0] ) / 2;
dest[2][1] = ( dest[2][1] + dest[3][1] ) / 2;
dest[2][2] = ( dest[2][2] + dest[3][2] ) / 2;
dest[2][3] = ( dest[2][3] + dest[3][3] ) / 2;
}
else
{
// Convert depth range from [-1,+1] to [1,0]
dest[2][0] = ( -dest[2][0] + dest[3][0] ) / 2;
dest[2][1] = ( -dest[2][1] + dest[3][1] ) / 2;
dest[2][2] = ( -dest[2][2] + dest[3][2] ) / 2;
dest[2][3] = ( -dest[2][3] + dest[3][3] ) / 2;
}
}
//-----------------------------------------------------------------------
void RenderSystem::_convertOpenVrProjectionMatrix( const Matrix4 &matrix, Matrix4 &dest )
{
dest = matrix;
if( mReverseDepth )
{
// Convert depth range from [0,1] to [1,0]
dest[2][0] = ( -dest[2][0] + dest[3][0] );
dest[2][1] = ( -dest[2][1] + dest[3][1] );
dest[2][2] = ( -dest[2][2] + dest[3][2] );
dest[2][3] = ( -dest[2][3] + dest[3][3] );
}
}
//-----------------------------------------------------------------------
void RenderSystem::_setWorldMatrices( const Matrix4 *m, unsigned short count )
{
// Do nothing with these matrices here, it never used for now,
// derived class should take care with them if required.
// Set hardware matrix to nothing
_setWorldMatrix( Matrix4::IDENTITY );
}
//-----------------------------------------------------------------------
void RenderSystem::setStencilBufferParams( uint32 refValue, const StencilParams &stencilParams )
{
mStencilParams = stencilParams;
// NB: We should always treat CCW as front face for consistent with default
// culling mode.
const bool mustFlip =
( ( mInvertVertexWinding && !mCurrentRenderPassDescriptor->requiresTextureFlipping() ) ||
( !mInvertVertexWinding && mCurrentRenderPassDescriptor->requiresTextureFlipping() ) );
if( mustFlip )
{
mStencilParams.stencilBack = stencilParams.stencilFront;
mStencilParams.stencilFront = stencilParams.stencilBack;
}
}
//-----------------------------------------------------------------------
void RenderSystem::_render( const v1::RenderOperation &op )
{
// Update stats
size_t primCount = op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount;
size_t trueInstanceNum = std::max<size_t>( op.numberOfInstances, 1 );
primCount *= trueInstanceNum;
// account for a pass having multiple iterations
if( mCurrentPassIterationCount > 1 )
primCount *= mCurrentPassIterationCount;
mCurrentPassIterationNum = 0;
switch( op.operationType )
{
case OT_TRIANGLE_LIST:
mMetrics.mFaceCount += ( primCount / 3u );
break;
case OT_TRIANGLE_STRIP:
case OT_TRIANGLE_FAN:
mMetrics.mFaceCount += ( primCount - 2u );
break;
default:
break;
}
mMetrics.mVertexCount += op.vertexData->vertexCount * trueInstanceNum;
mMetrics.mBatchCount += mCurrentPassIterationCount;
// sort out clip planes
// have to do it here in case of matrix issues
if( mClipPlanesDirty )
{
setClipPlanesImpl( mClipPlanes );
mClipPlanesDirty = false;
}
}
//-----------------------------------------------------------------------
/*void RenderSystem::_render( const VertexArrayObject *vao )
{
// Update stats
mFaceCount += vao->mFaceCount;
mVertexCount += vao->mVertexBuffers[0]->getNumElements();
++mBatchCount;
}*/
//-----------------------------------------------------------------------
void RenderSystem::setInvertVertexWinding( bool invert ) { mInvertVertexWinding = invert; }
//-----------------------------------------------------------------------
bool RenderSystem::getInvertVertexWinding() const { return mInvertVertexWinding; }
//---------------------------------------------------------------------
void RenderSystem::addClipPlane( const Plane &p )
{
mClipPlanes.push_back( p );
mClipPlanesDirty = true;
}
//---------------------------------------------------------------------
void RenderSystem::addClipPlane( Real A, Real B, Real C, Real D )
{
addClipPlane( Plane( A, B, C, D ) );
}
//---------------------------------------------------------------------
void RenderSystem::setClipPlanes( const PlaneList &clipPlanes )
{
if( clipPlanes != mClipPlanes )
{
mClipPlanes = clipPlanes;
mClipPlanesDirty = true;
}
}
//---------------------------------------------------------------------
void RenderSystem::resetClipPlanes()
{
if( !mClipPlanes.empty() )
{
mClipPlanes.clear();
mClipPlanesDirty = true;
}
}
//---------------------------------------------------------------------
bool RenderSystem::updatePassIterationRenderState()
{
if( mCurrentPassIterationCount <= 1 )
return false;
--mCurrentPassIterationCount;
++mCurrentPassIterationNum;
if( mActiveVertexGpuProgramParameters )
{
mActiveVertexGpuProgramParameters->incPassIterationNumber();
bindGpuProgramPassIterationParameters( GPT_VERTEX_PROGRAM );
}
if( mActiveGeometryGpuProgramParameters )
{
mActiveGeometryGpuProgramParameters->incPassIterationNumber();
bindGpuProgramPassIterationParameters( GPT_GEOMETRY_PROGRAM );
}
if( mActiveFragmentGpuProgramParameters )
{
mActiveFragmentGpuProgramParameters->incPassIterationNumber();
bindGpuProgramPassIterationParameters( GPT_FRAGMENT_PROGRAM );
}
if( mActiveTessellationHullGpuProgramParameters )
{
mActiveTessellationHullGpuProgramParameters->incPassIterationNumber();
bindGpuProgramPassIterationParameters( GPT_HULL_PROGRAM );
}
if( mActiveTessellationDomainGpuProgramParameters )
{
mActiveTessellationDomainGpuProgramParameters->incPassIterationNumber();
bindGpuProgramPassIterationParameters( GPT_DOMAIN_PROGRAM );
}
if( mActiveComputeGpuProgramParameters )
{
mActiveComputeGpuProgramParameters->incPassIterationNumber();
bindGpuProgramPassIterationParameters( GPT_COMPUTE_PROGRAM );
}
return true;
}
//-----------------------------------------------------------------------
void RenderSystem::addSharedListener( Listener *l ) { msSharedEventListeners.push_back( l ); }
//-----------------------------------------------------------------------
void RenderSystem::removeSharedListener( Listener *l ) { msSharedEventListeners.remove( l ); }
//-----------------------------------------------------------------------
void RenderSystem::addListener( Listener *l ) { mEventListeners.push_back( l ); }
//-----------------------------------------------------------------------
void RenderSystem::removeListener( Listener *l ) { mEventListeners.remove( l ); }
//-----------------------------------------------------------------------
void RenderSystem::fireEvent( const String &name, const NameValuePairList *params )
{
for( ListenerList::iterator i = mEventListeners.begin(); i != mEventListeners.end(); ++i )
{
( *i )->eventOccurred( name, params );
}
fireSharedEvent( name, params );
}
//-----------------------------------------------------------------------
void RenderSystem::fireSharedEvent( const String &name, const NameValuePairList *params )
{
for( ListenerList::iterator i = msSharedEventListeners.begin();
i != msSharedEventListeners.end(); ++i )
{
( *i )->eventOccurred( name, params );
}
}
//-----------------------------------------------------------------------
const char *RenderSystem::getPriorityConfigOption( size_t ) const
{
OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "idx must be < getNumPriorityConfigOptions()",
"RenderSystem::getPriorityConfigOption" );
}
//-----------------------------------------------------------------------
size_t RenderSystem::getNumPriorityConfigOptions() const { return 0u; }
//-----------------------------------------------------------------------
void RenderSystem::destroyHardwareOcclusionQuery( HardwareOcclusionQuery *hq )
{
HardwareOcclusionQueryList::iterator i =
std::find( mHwOcclusionQueries.begin(), mHwOcclusionQueries.end(), hq );
if( i != mHwOcclusionQueries.end() )
{
mHwOcclusionQueries.erase( i );
OGRE_DELETE hq;
}
}
//-----------------------------------------------------------------------
bool RenderSystem::isGpuProgramBound( GpuProgramType gptype )
{
switch( gptype )
{
case GPT_VERTEX_PROGRAM:
return mVertexProgramBound;
case GPT_GEOMETRY_PROGRAM:
return mGeometryProgramBound;
case GPT_FRAGMENT_PROGRAM:
return mFragmentProgramBound;
case GPT_HULL_PROGRAM:
return mTessellationHullProgramBound;
case GPT_DOMAIN_PROGRAM:
return mTessellationDomainProgramBound;
case GPT_COMPUTE_PROGRAM:
return mComputeProgramBound;
}
// Make compiler happy
return false;
}
//---------------------------------------------------------------------
void RenderSystem::_setTextureProjectionRelativeTo( bool enabled, const Vector3 &pos )
{
mTexProjRelative = enabled;
mTexProjRelativeOrigin = pos;
}
//---------------------------------------------------------------------
RenderSystem::RenderSystemContext *RenderSystem::_pauseFrame()
{
_endFrame();
return new RenderSystem::RenderSystemContext;
}
//---------------------------------------------------------------------
void RenderSystem::_resumeFrame( RenderSystemContext *context )
{
_beginFrame();
delete context;
}
//---------------------------------------------------------------------
void RenderSystem::_update()
{
OgreProfile( "RenderSystem::_update" );
mBarrierSolver.reset();
mTextureGpuManager->_update( false );
mVaoManager->_update();
}
//---------------------------------------------------------------------
void RenderSystem::updateCompositorManager( CompositorManager2 *compositorManager )
{
compositorManager->_updateImplementation();
}
//---------------------------------------------------------------------
void RenderSystem::compositorWorkspaceBegin( CompositorWorkspace *workspace,
const bool forceBeginFrame )
{
workspace->_beginUpdate( forceBeginFrame, true );
}
//---------------------------------------------------------------------
void RenderSystem::compositorWorkspaceUpdate( CompositorWorkspace *workspace )
{
workspace->_update( true );
}
//---------------------------------------------------------------------
void RenderSystem::compositorWorkspaceEnd( CompositorWorkspace *workspace, const bool forceEndFrame )
{
workspace->_endUpdate( forceEndFrame, true );
}
//---------------------------------------------------------------------
const String &RenderSystem::_getDefaultViewportMaterialScheme() const
{
#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS
if( !( getCapabilities()->hasCapability( Ogre::RSC_FIXED_FUNCTION ) ) )
{
// I am returning the exact value for now - I don't want to add dependency for the RTSS just
// for one string
static const String ShaderGeneratorDefaultScheme = "ShaderGeneratorDefaultScheme";
return ShaderGeneratorDefaultScheme;
}
else
#endif
{
return MaterialManager::DEFAULT_SCHEME_NAME;
}
}
//---------------------------------------------------------------------
Ogre::v1::HardwareVertexBufferSharedPtr RenderSystem::getGlobalInstanceVertexBuffer() const
{
return mGlobalInstanceVertexBuffer;
}
//---------------------------------------------------------------------
void RenderSystem::setGlobalInstanceVertexBuffer( const v1::HardwareVertexBufferSharedPtr &val )
{
if( val && !val->getIsInstanceData() )
{
OGRE_EXCEPT(
Exception::ERR_INVALIDPARAMS,
"A none instance data vertex buffer was set to be the global instance vertex buffer.",
"RenderSystem::setGlobalInstanceVertexBuffer" );
}
mGlobalInstanceVertexBuffer = val;
}
//---------------------------------------------------------------------
size_t RenderSystem::getGlobalNumberOfInstances() const { return mGlobalNumberOfInstances; }
//---------------------------------------------------------------------
void RenderSystem::setGlobalNumberOfInstances( const size_t val ) { mGlobalNumberOfInstances = val; }
v1::VertexDeclaration *RenderSystem::getGlobalInstanceVertexBufferVertexDeclaration() const
{
return mGlobalInstanceVertexBufferVertexDeclaration;
}
//---------------------------------------------------------------------
void RenderSystem::setGlobalInstanceVertexBufferVertexDeclaration( v1::VertexDeclaration *val )
{
mGlobalInstanceVertexBufferVertexDeclaration = val;
}
//---------------------------------------------------------------------
bool RenderSystem::startGpuDebuggerFrameCapture( Window *window )
{
if( !mRenderDocApi )
{
loadRenderDocApi();
if( !mRenderDocApi )
return false;
}
#if OGRE_NO_RENDERDOC_INTEGRATION == 0
RENDERDOC_DevicePointer device = 0;
RENDERDOC_WindowHandle windowHandle = 0;
if( window )
{
window->getCustomAttribute( "RENDERDOC_DEVICE", device );
window->getCustomAttribute( "RENDERDOC_WINDOW", windowHandle );
}
mRenderDocApi->StartFrameCapture( device, windowHandle );
#endif
return true;
}
//---------------------------------------------------------------------
void RenderSystem::endGpuDebuggerFrameCapture( Window *window )
{
if( !mRenderDocApi )
return;
#if OGRE_NO_RENDERDOC_INTEGRATION == 0
RENDERDOC_DevicePointer device = 0;
RENDERDOC_WindowHandle windowHandle = 0;
if( window )
{
window->getCustomAttribute( "RENDERDOC_DEVICE", device );
window->getCustomAttribute( "RENDERDOC_WINDOW", windowHandle );
}
mRenderDocApi->EndFrameCapture( device, windowHandle );
#endif
}
//---------------------------------------------------------------------
bool RenderSystem::loadRenderDocApi()
{
#if OGRE_NO_RENDERDOC_INTEGRATION == 0
if( mRenderDocApi )
return true; // Already loaded
# if OGRE_PLATFORM == OGRE_PLATFORM_LINUX || OGRE_PLATFORM == OGRE_PLATFORM_ANDROID
# if OGRE_PLATFORM != OGRE_PLATFORM_ANDROID
void *mod = dlopen( "librenderdoc.so", RTLD_NOW | RTLD_NOLOAD );
# else
void *mod = dlopen( "libVkLayer_GLES_RenderDoc.so", RTLD_NOW | RTLD_NOLOAD );
# endif
if( mod )
{
pRENDERDOC_GetAPI RENDERDOC_GetAPI = (pRENDERDOC_GetAPI)dlsym( mod, "RENDERDOC_GetAPI" );
const int ret = RENDERDOC_GetAPI( eRENDERDOC_API_Version_1_4_1, (void **)&mRenderDocApi );
return ret == 1;
}
# elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32
HMODULE mod = GetModuleHandleA( "renderdoc.dll" );
if( mod )
{
pRENDERDOC_GetAPI RENDERDOC_GetAPI =
(pRENDERDOC_GetAPI)GetProcAddress( mod, "RENDERDOC_GetAPI" );
const int ret = RENDERDOC_GetAPI( eRENDERDOC_API_Version_1_4_1, (void **)&mRenderDocApi );
return ret == 1;
}
# endif
#endif
return false;
}
//---------------------------------------------------------------------
void RenderSystem::getCustomAttribute( const String &name, void *pData )
{
OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Attribute not found.",
"RenderSystem::getCustomAttribute" );
}
//---------------------------------------------------------------------
void RenderSystem::setDebugShaders( bool bDebugShaders ) { mDebugShaders = bDebugShaders; }
//---------------------------------------------------------------------
bool RenderSystem::isSameLayout( ResourceLayout::Layout a, ResourceLayout::Layout b,
const TextureGpu *texture, bool bIsDebugCheck ) const
{
if( ( a != ResourceLayout::Uav && b != ResourceLayout::Uav ) || bIsDebugCheck )
return true;
return a == b;
}
//---------------------------------------------------------------------
void RenderSystem::_clearStateAndFlushCommandBuffer() {}
//---------------------------------------------------------------------
RenderSystem::Listener::~Listener() {}
} // namespace Ogre
| 41.589762 | 105 | 0.51633 | FreeNightKnight |
4027453f9518a17a754721bc386f6e52a00cf360 | 409 | cpp | C++ | hdu/1000/1412.cpp | TheBadZhang/OJ | b5407f2483aa630068343b412ecaf3a9e3303f7e | [
"Apache-2.0"
] | 1 | 2020-07-22T16:54:07.000Z | 2020-07-22T16:54:07.000Z | hdu/1000/1412.cpp | TheBadZhang/OJ | b5407f2483aa630068343b412ecaf3a9e3303f7e | [
"Apache-2.0"
] | 1 | 2018-05-12T12:53:06.000Z | 2018-05-12T12:53:06.000Z | hdu/1000/1412.cpp | TheBadZhang/OJ | b5407f2483aa630068343b412ecaf3a9e3303f7e | [
"Apache-2.0"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<set>
using namespace std;
int main() {
int temp,n1,n2;
while(scanf("%d %d",&n1,&n2)!=EOF) {
set<int> s;
n1=n1+n2;
while(n1--) {
scanf("%d",&temp);
s.insert(temp);
}
set<int>::const_iterator itor;
itor=s.begin();
while(itor!=s.end()) {
printf("%d",*itor);
itor++;
if(itor!=s.end())
printf(" ");
}
printf("\n");
}
return 0;
} | 15.730769 | 37 | 0.550122 | TheBadZhang |
4029fe61bd9aaa38e13a6aacea0750c6aa697b2c | 2,685 | cpp | C++ | src/CL_DataBuffer_stub.cpp | fccm/ocaml-clanlib | 1929f1c11d4cc9fc19e7da22826238b4cce7a07d | [
"Zlib",
"OLDAP-2.2.1"
] | 1 | 2020-10-24T14:48:04.000Z | 2020-10-24T14:48:04.000Z | src/CL_DataBuffer_stub.cpp | fccm/ocaml-clanlib | 1929f1c11d4cc9fc19e7da22826238b4cce7a07d | [
"Zlib",
"OLDAP-2.2.1"
] | null | null | null | src/CL_DataBuffer_stub.cpp | fccm/ocaml-clanlib | 1929f1c11d4cc9fc19e7da22826238b4cce7a07d | [
"Zlib",
"OLDAP-2.2.1"
] | null | null | null | /* ocaml-clanlib: OCaml bindings to the ClanLib SDK
Copyright (C) 2013 Florent Monnier
This software is provided "AS-IS", without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely. */
#include <ClanLib/Core/System/databuffer.h>
#include "cl_caml_incs.hpp"
#include "cl_caml_conv.hpp"
#include "CL_DataBuffer_stub.hpp"
CAMLextern_C value
caml_CL_DataBuffer_init(value unit)
{
CL_DataBuffer *buf = new CL_DataBuffer();
return Val_CL_DataBuffer(buf);
}
CAMLextern_C value
caml_CL_DataBuffer_copy(value orig)
{
CL_DataBuffer *buf = new CL_DataBuffer(*CL_DataBuffer_val(orig));
return Val_CL_DataBuffer(buf);
}
CAMLextern_C value
caml_CL_DataBuffer_of_string(value str)
{
CL_DataBuffer *buf = new CL_DataBuffer(
String_val(str),
caml_string_length(str));
return Val_CL_DataBuffer(buf);
}
/* TODO:
CL_DataBuffer(int size, CL_MemoryPool *pool = 0);
CL_DataBuffer(const void *data, int size, CL_MemoryPool *pool = 0);
CL_DataBuffer(const CL_DataBuffer &data, int pos, int size = -1, CL_MemoryPool *pool = 0);
*/
CAMLextern_C value
caml_CL_DataBuffer_delete(value buf)
{
delete CL_DataBuffer_val(buf);
nullify_ptr(buf);
return Val_unit;
}
CAMLextern_C value
caml_CL_DataBuffer_get_size(value buf)
{
int size = CL_DataBuffer_val(buf)->get_size();
return Val_long(size);
}
CAMLextern_C value
caml_CL_DataBuffer_get_capacity(value buf)
{
int cap = CL_DataBuffer_val(buf)->get_capacity();
return Val_long(cap);
}
CAMLextern_C value
caml_CL_DataBuffer_set_size(value buf, value size)
{
CL_DataBuffer_val(buf)->set_size(Int_val(size));
return Val_unit;
}
CAMLextern_C value
caml_CL_DataBuffer_set_capacity(value buf, value cap)
{
CL_DataBuffer_val(buf)->set_capacity(Int_val(cap));
return Val_unit;
}
CAMLextern_C value
caml_CL_DataBuffer_get_i(value buf, value i)
{
const char c =
(*CL_DataBuffer_val(buf))[ Int_val(i) ];
return Val_char(c);
}
CAMLextern_C value
caml_CL_DataBuffer_set_i(value buf, value i, value c)
{
(*CL_DataBuffer_val(buf))[ Int_val(i) ] = Char_val(c);
return Val_unit;
}
/* TODO:
char *get_data();
const char *get_data();
char &operator[](int i);
const char &operator[](int i);
char &operator[](unsigned int i);
const char &operator[](unsigned int i);
bool is_null();
CL_DataBuffer &operator =(const CL_DataBuffer ©);
*/
// vim: sw=4 sts=4 ts=4 et
| 24.189189 | 94 | 0.72365 | fccm |
402e91dbc88528fd74639a15bb0e5689aed78f82 | 3,491 | cpp | C++ | libcaf_core/src/response_promise.cpp | v2nero/actor-framework | c2f811809143d32c598471a20363238b0882a761 | [
"BSL-1.0",
"BSD-3-Clause"
] | 1 | 2021-03-06T19:51:07.000Z | 2021-03-06T19:51:07.000Z | libcaf_core/src/response_promise.cpp | Boubou818/actor-framework | da90ef78b26da5d225f039072e616da415c48494 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | libcaf_core/src/response_promise.cpp | Boubou818/actor-framework | da90ef78b26da5d225f039072e616da415c48494 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | /******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include <utility>
#include <algorithm>
#include "caf/response_promise.hpp"
#include "caf/logger.hpp"
#include "caf/local_actor.hpp"
namespace caf {
response_promise::response_promise() : self_(nullptr) {
// nop
}
response_promise::response_promise(none_t) : response_promise() {
// nop
}
response_promise::response_promise(strong_actor_ptr self,
strong_actor_ptr source,
forwarding_stack stages, message_id mid)
: self_(std::move(self)),
source_(std::move(source)),
stages_(std::move(stages)),
id_(mid) {
// Form an invalid request promise when initialized from a response ID, since
// we always drop messages in this case.
if (mid.is_response()) {
source_ = nullptr;
stages_.clear();
}
}
response_promise::response_promise(strong_actor_ptr self, mailbox_element& src)
: response_promise(std::move(self), std::move(src.sender),
std::move(src.stages), src.mid) {
// nop
}
void response_promise::deliver(error x) {
deliver_impl(make_message(std::move(x)));
}
void response_promise::deliver(unit_t) {
deliver_impl(make_message());
}
bool response_promise::async() const {
return id_.is_async();
}
execution_unit* response_promise::context() {
return self_ == nullptr
? nullptr
: static_cast<local_actor*>(actor_cast<abstract_actor*>(self_))
->context();
}
void response_promise::deliver_impl(message msg) {
CAF_LOG_TRACE(CAF_ARG(msg));
if (!stages_.empty()) {
auto next = std::move(stages_.back());
stages_.pop_back();
next->enqueue(make_mailbox_element(std::move(source_), id_,
std::move(stages_), std::move(msg)),
context());
return;
}
if (source_) {
source_->enqueue(std::move(self_), id_.response_id(),
std::move(msg), context());
source_.reset();
return;
}
CAF_LOG_INFO_IF(self_ != nullptr, "response promise already satisfied");
CAF_LOG_INFO_IF(self_ == nullptr, "invalid response promise");
}
} // namespace caf
| 35.262626 | 80 | 0.493841 | v2nero |
402efd6856e50ca629d5b72ec75b07bbe50e7ac7 | 1,948 | hpp | C++ | system/dummy_diag_publisher/include/dummy_diag_publisher/dummy_diag_publisher_node.hpp | meliketanrikulu/autoware.universe | 04f2b53ae1d7b41846478641ad6ff478c3d5a247 | [
"Apache-2.0"
] | 58 | 2021-11-30T09:03:46.000Z | 2022-03-31T15:25:17.000Z | system/dummy_diag_publisher/include/dummy_diag_publisher/dummy_diag_publisher_node.hpp | meliketanrikulu/autoware.universe | 04f2b53ae1d7b41846478641ad6ff478c3d5a247 | [
"Apache-2.0"
] | 425 | 2021-11-30T02:24:44.000Z | 2022-03-31T10:26:37.000Z | system/dummy_diag_publisher/include/dummy_diag_publisher/dummy_diag_publisher_node.hpp | meliketanrikulu/autoware.universe | 04f2b53ae1d7b41846478641ad6ff478c3d5a247 | [
"Apache-2.0"
] | 69 | 2021-11-30T02:09:18.000Z | 2022-03-31T15:38:29.000Z | // Copyright 2020 Tier IV, 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.
#ifndef DUMMY_DIAG_PUBLISHER__DUMMY_DIAG_PUBLISHER_NODE_HPP_
#define DUMMY_DIAG_PUBLISHER__DUMMY_DIAG_PUBLISHER_NODE_HPP_
#include <diagnostic_updater/diagnostic_updater.hpp>
#include <rclcpp/rclcpp.hpp>
#include <string>
#include <vector>
struct DiagConfig
{
std::string name;
std::string hardware_id;
std::string msg_ok;
std::string msg_warn;
std::string msg_error;
std::string msg_stale;
};
class DummyDiagPublisherNode : public rclcpp::Node
{
public:
explicit DummyDiagPublisherNode(const rclcpp::NodeOptions & node_options);
private:
enum Status {
OK,
WARN,
ERROR,
STALE,
};
struct DummyDiagPublisherConfig
{
Status status;
bool is_active;
};
// Parameter
double update_rate_;
DiagConfig diag_config_;
DummyDiagPublisherConfig config_;
// Dynamic Reconfigure
OnSetParametersCallbackHandle::SharedPtr set_param_res_;
rcl_interfaces::msg::SetParametersResult paramCallback(
const std::vector<rclcpp::Parameter> & parameters);
// Diagnostic Updater
// Set long period to reduce automatic update
diagnostic_updater::Updater updater_{this, 1000.0 /* sec */};
void produceDiagnostics(diagnostic_updater::DiagnosticStatusWrapper & stat);
// Timer
void onTimer();
rclcpp::TimerBase::SharedPtr timer_;
};
#endif // DUMMY_DIAG_PUBLISHER__DUMMY_DIAG_PUBLISHER_NODE_HPP_
| 25.973333 | 78 | 0.755647 | meliketanrikulu |
4037198d8d3c56b935e3d4812801ed4cddd9e74f | 11,493 | cpp | C++ | rilc_test.cpp | cocktail828/rilc | 09d469e26b527cef9b407e7e8d4186ac3726eef7 | [
"MIT"
] | null | null | null | rilc_test.cpp | cocktail828/rilc | 09d469e26b527cef9b407e7e8d4186ac3726eef7 | [
"MIT"
] | null | null | null | rilc_test.cpp | cocktail828/rilc | 09d469e26b527cef9b407e7e8d4186ac3726eef7 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <thread>
#include <chrono>
#include <future>
#include <vector>
#include <getopt.h>
#include <unistd.h>
#include <string.h>
#include "rilc_api.h"
#include "rilc_interface.h"
#include "logger.h"
std::mutex mutexSocilited;
std::condition_variable condSocilited;
void socilited_notify(RILResponse *arg)
{
condSocilited.notify_one();
LOGI << "RILC call user defined socilited_notify function" << ENDL;
}
void unsocilited_notify(RILResponse *arg)
{
LOGI << "RILC call user defined unsocilited_notify function" << ENDL;
}
static int sg_index = 0;
/**
* will call std::abort() if get an timeout
*/
#define RILC_TEST_ABORT_TIMEOUT(func, args...) \
do \
{ \
LOGI << ">>>>>>>> RILC_TEST index: " << ++sg_index << ENDL; \
RILResponse resp; \
memset(&resp, 0, sizeof(RILResponse)); \
resp.responseNotify = socilited_notify; \
std::unique_lock<std::mutex> _lk(mutexSocilited); \
func(&resp, ##args); \
if (condSocilited.wait_for(_lk, std::chrono::seconds(60)) == std::cv_status::timeout) \
{ \
LOGI << ">>>>>>>> RILC_TEST index: " << sg_index << " failed for timeout" << ENDL; \
LOGE << "OOPS!!! request timeout" << ENDL; \
LOGE << "check wether host can get response from device" << ENDL; \
std::abort(); \
} \
else \
{ \
if (resp.responseShow) \
resp.responseShow(&resp); \
if (resp.responseFree) \
resp.responseFree(&resp); \
LOGI << ">>>>>>>> RILC_TEST index: " << sg_index << " pass" << ENDL; \
} \
_lk.unlock(); \
LOGI << ">>>>>>>> RILC_TEST index: " << sg_index << " finished" << ENDL << ENDL << ENDL; \
} while (0);
int main(int argc, char **argv)
{
static const struct option long_options[] = {
{"device", required_argument, NULL, 'd'},
{"mode", required_argument, NULL, 'm'},
{"platform", required_argument, NULL, 'p'},
{"level", required_argument, NULL, 'l'},
{NULL, 0, NULL, 0}};
const char *device = "/dev/ttyUSB4";
Severity s = Severity::DEBUG;
/**
* 0 Linux
* 1 Android
*/
int platform = 0;
/**
* 0 abort if timeout
* 1 abort if response report an error
*/
int test_mode = 0;
int long_index = 0;
int opt;
while ((opt = getopt_long(argc, argv, "d:m:p:l:?h", long_options, &long_index)) != -1)
{
switch (opt)
{
case 'd':
device = optarg;
LOGI << "using device: " << device << ENDL;
break;
case 'm':
test_mode = !!atoi(optarg);
LOGI << "using test mode: " << test_mode << ENDL;
break;
case 'p':
if (optarg && !strncasecmp(optarg, "linux", 4))
platform = 0;
else if (optarg && !strncasecmp(optarg, "android", 4))
platform = 1;
LOGI << "using platform: " << (platform ? "Android" : "Linux") << ENDL;
break;
case 'l':
if (optarg && !strncasecmp(optarg, "debug", 4))
s = Severity::DEBUG;
else if (optarg && !strncasecmp(optarg, "info", 4))
s = Severity::INFO;
else if (optarg && !strncasecmp(optarg, "warn", 4))
s = Severity::WARNING;
else if (optarg && !strncasecmp(optarg, "error", 4))
s = Severity::ERROR;
else
s = Severity::INFO;
break;
default:
LOGI << "help message:" << ENDL;
LOGI << " -d, --device ttydevice or socket" << ENDL;
LOGI << " -m, --mode test mode(0 stop test if meet a timeout, 1 stop test if meet an error)" << ENDL;
LOGI << " -p, --platform os platform(0 for Linux, 1 for Android)" << ENDL;
LOGI << " -l, --level log level(debug, info, warning, error)" << ENDL;
return 0;
}
}
if (access(device, R_OK | W_OK))
{
LOGE << "invalid device: " << device << ENDL;
return 0;
}
/**
* set log level Severity::INFO
* for more detail set Severity::DEBUG
*/
Logger::Init("RILC", s, false);
/** test on Android
* Android only allow user radio connect socket '/dev/socket/rild'
*/
if (platform == 1)
{
setgid(1001);
setuid(1001);
LOGI << "try to switch user to radio: id 1001" << ENDL;
LOGD << "after switch user UID\t= " << getuid() << ENDL;
LOGD << "after switch user EUID\t= " << geteuid() << ENDL;
LOGD << "after switch user GID\t= " << getgid() << ENDL;
LOGD << "after switch user EGID\t= " << getegid() << ENDL;
}
/** test on Linux with RG500U
* Android only allow user radio connect socket '/dev/socket/rild'
*/
if (device)
RILC_init(device);
else
{
if (platform == 1)
RILC_init("/dev/socket/rild");
else
RILC_init("/dev/ttyUSB4");
}
RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_NEW_SMS, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_NEW_SMS_STATUS_REPORT, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_NEW_SMS_ON_SIM, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_ON_USSD, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_ON_USSD_REQUEST, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_NITZ_TIME_RECEIVED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_SIGNAL_STRENGTH, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_DATA_CALL_LIST_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_SUPP_SVC_NOTIFICATION, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_STK_SESSION_END, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_STK_PROACTIVE_COMMAND, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_STK_EVENT_NOTIFY, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_STK_CALL_SETUP, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_SIM_SMS_STORAGE_FULL, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_SIM_REFRESH, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_CALL_RING, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_CDMA_NEW_SMS, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_NEW_BROADCAST_SMS, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_CDMA_RUIM_SMS_STORAGE_FULL, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RESTRICTED_STATE_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_ENTER_EMERGENCY_CALLBACK_MODE, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_CDMA_CALL_WAITING, unsocilited_notify); // TOD;
RILC_unsocilitedRegister(RIL_UNSOL_CDMA_OTA_PROVISION_STATUS, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_CDMA_INFO_REC, unsocilited_notify); // TOD;
RILC_unsocilitedRegister(RIL_UNSOL_OEM_HOOK_RAW, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RINGBACK_TONE, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RESEND_INCALL_MUTE, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_CDMA_PRL_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_EXIT_EMERGENCY_CALLBACK_MODE, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RIL_CONNECTED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_VOICE_RADIO_TECH_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_CELL_INFO_LIST, unsocilited_notify); // TOD;
RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_IMS_NETWORK_STATE_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_UICC_SUBSCRIPTION_STATUS_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_SRVCC_STATE_NOTIFY, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_HARDWARE_CONFIG_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_DC_RT_INFO_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RADIO_CAPABILITY, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_ON_SS, unsocilited_notify); // TOD;
RILC_unsocilitedRegister(RIL_UNSOL_STK_CC_ALPHA_NOTIFY, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_LCEDATA_RECV, unsocilited_notify);
RILC_TEST_ABORT_TIMEOUT(RILC_getIMEI);
RILC_TEST_ABORT_TIMEOUT(RILC_getIMEISV);
RILC_TEST_ABORT_TIMEOUT(RILC_getIMSI);
RILC_TEST_ABORT_TIMEOUT(RILC_getVoiceRegistrationState);
RILC_TEST_ABORT_TIMEOUT(RILC_getDataRegistrationState);
RILC_TEST_ABORT_TIMEOUT(RILC_getOperator);
RILC_TEST_ABORT_TIMEOUT(RILC_getNeighboringCids);
RILC_TEST_ABORT_TIMEOUT(RILC_getSignalStrength);
RILC_TEST_ABORT_TIMEOUT(RILC_getPreferredNetworkType);
RILC_TEST_ABORT_TIMEOUT(RILC_setPreferredNetworkType, RADIO_TECHNOLOGY_LTE);
RILC_TEST_ABORT_TIMEOUT(RILC_setupDataCall, RADIO_TECHNOLOGY_LTE, "0", "3gnet",
"", "", SETUP_DATA_AUTH_NONE, PROTOCOL_IPV4);
RILC_TEST_ABORT_TIMEOUT(RILC_getIccCardStatus);
RILC_TEST_ABORT_TIMEOUT(RILC_getCurrentCalls);
RILC_TEST_ABORT_TIMEOUT(RILC_getNetworkSelectionMode);
RILC_TEST_ABORT_TIMEOUT(RILC_getDataCallList);
RILC_TEST_ABORT_TIMEOUT(RILC_getBasebandVersion);
RILC_TEST_ABORT_TIMEOUT(RILC_queryAvailableBandMode);
RILC_uninit();
return 0;
}
| 45.426877 | 127 | 0.595406 | cocktail828 |
4038654c9fcdc2b790ca19c3b87d229ac0346f20 | 939 | cpp | C++ | sample03/utils.cpp | trumpsilver/Aladin | 283233c0583db120eb2a881cddca20f474dc6a98 | [
"MIT"
] | null | null | null | sample03/utils.cpp | trumpsilver/Aladin | 283233c0583db120eb2a881cddca20f474dc6a98 | [
"MIT"
] | null | null | null | sample03/utils.cpp | trumpsilver/Aladin | 283233c0583db120eb2a881cddca20f474dc6a98 | [
"MIT"
] | null | null | null | #include <d3dx9.h>
#include "utils.h"
#include "trace.h"
LPDIRECT3DSURFACE9 CreateSurfaceFromFile(LPDIRECT3DDEVICE9 d3ddv, LPWSTR FilePath)
{
D3DXIMAGE_INFO info;
HRESULT result = D3DXGetImageInfoFromFile(FilePath,&info);
if (result!=D3D_OK)
{
trace(L"[ERROR] Failed to get image info '%s'",FilePath);
return NULL;
}
LPDIRECT3DSURFACE9 surface;
d3ddv->CreateOffscreenPlainSurface(
info.Width, // width
info.Height, // height
D3DFMT_X8R8G8B8, // format
D3DPOOL_DEFAULT,
&surface,
NULL);
result = D3DXLoadSurfaceFromFile(
surface, // surface
NULL, // destination palette
NULL, // destination rectangle
FilePath,
NULL, // source rectangle
D3DX_DEFAULT, // filter image
D3DCOLOR_XRGB(0,0,0), // transparency (0 = none)
NULL); // reserved
if (result!=D3D_OK)
{
trace(L"[ERROR] D3DXLoadSurfaceFromFile() failed");
return NULL;
}
return surface;
} | 20.866667 | 82 | 0.681576 | trumpsilver |
403ac187da7e7c7c5fc71365257f91d6306c8305 | 356 | cpp | C++ | dataset/test/modification/1467_rename/27/transformation_1.cpp | Karina5005/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | 3 | 2022-02-15T00:29:39.000Z | 2022-03-15T08:36:44.000Z | dataset/test/modification/1467_rename/27/transformation_1.cpp | Kira5005-code/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | null | null | null | dataset/test/modification/1467_rename/27/transformation_1.cpp | Kira5005-code/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | null | null | null | #include <cstdio>
int main() {
int pwg;scanf("%d", &pwg);
while (pwg--) {
int awr;scanf("%d", &awr);
switch (awr) {
case 1: printf("9");break;
case 2: printf("98");break;
default: printf("989");int zqi_ifn = 0;for (int ebe = 4;ebe <= awr;ebe++) {printf("%d", zqi_ifn);zqi_ifn = (zqi_ifn + 1) % 10;}break;
}
printf("\n");
}
return 0;
}
| 23.733333 | 136 | 0.55618 | Karina5005 |
403b76428c6f36b0dfa3723efaa3cd6befc6fdbc | 9,350 | hpp | C++ | vsl/Types.hpp | VegaLib/VSL | c110b1b8ce6aa7a88d2bc97a3e99385e638dfc6d | [
"MS-PL"
] | null | null | null | vsl/Types.hpp | VegaLib/VSL | c110b1b8ce6aa7a88d2bc97a3e99385e638dfc6d | [
"MS-PL"
] | null | null | null | vsl/Types.hpp | VegaLib/VSL | c110b1b8ce6aa7a88d2bc97a3e99385e638dfc6d | [
"MS-PL"
] | null | null | null | /*
* Microsoft Public License (Ms-PL) - Copyright (c) 2020-2021 Sean Moss
* This file is subject to the terms and conditions of the Microsoft Public License, the text of which can be found in
* the 'LICENSE' file at the root of this repository, or online at <https://opensource.org/licenses/MS-PL>.
*/
#pragma once
#include "./Config.hpp"
#include <unordered_map>
#include <vector>
namespace vsl
{
// Enum of the base shader types
enum class BaseType : uint32
{
Void = 0, // Special type for errors and function returns
Boolean = 1, // Boolean scalar/vector
Signed = 2, // Signed integer scalar/vector
Unsigned = 3, // Unsigned integer scalar/vector
Float = 4, // Floating point scalar/vector/matrix
Sampler = 5, // Vk combined image/sampler, glsl 'sampler*D' (no separate image and sampler objects)
Image = 6, // Vk storage image, glsl `image*D` w/ layout
ROBuffer = 7, // Vk readonly storage buffer, glsl `readonly buffer <name> { ... }`
RWBuffer = 8, // Vk read/write storage buffer, glsl `buffer <name> { ... }`
ROTexels = 9, // Vk uniform texel buffer, glsl `textureBuffer`
RWTexels = 10, // Vk storage texel buffer, glsl `imageBuffer` w/ layout
SPInput = 11, // Vk input attachment, glsl `[ ui]subpassInput`
Uniform = 12, // Vk uniform buffer, glsl `uniform <name> { ... }`
Struct = 13, // User-defined POD struct
// Max value
MAX = Struct
}; // enum class BaseType
struct ShaderType;
// Describes a user-defined struct type
struct StructType final
{
public:
struct Member final
{
string name;
uint32 arraySize;
const ShaderType* type;
}; // struct Member
StructType(const string& name, const std::vector<Member>& members);
StructType() : StructType("INVALID", {}) { }
~StructType() { }
/* Fields */
inline const string& name() const { return name_; }
inline const std::vector<Member>& members() const { return members_; }
inline const std::vector<uint32>& offsets() const { return offsets_; }
inline uint32 size() const { return size_; }
inline uint32 alignment() const { return alignment_; }
/* Member Access */
const Member* getMember(const string& name, uint32* offset = nullptr) const;
inline bool hasMember(const string& name) const { return !!getMember(name, nullptr); }
private:
string name_;
std::vector<Member> members_;
std::vector<uint32> offsets_;
uint32 size_;
uint32 alignment_;
}; // struct StructType
// The different ranks (dimension counts) that texel-like objects can have
enum class TexelRank : uint32
{
E1D = 0, // Single 1D texture
E2D = 1, // Single 2D texture
E3D = 2, // Single 3D texture
E1DArray = 3, // Array of 1D textures
E2DArray = 4, // Array of 2D textures
Cube = 5, // Single cubemap texture
Buffer = 6, // The dims specific to a ROTexels object
// Max value
MAX = Buffer
}; // enum class TexelRank
string TexelRankGetSuffix(TexelRank rank);
uint32 TexelRankGetComponentCount(TexelRank rank);
// The base types for texel formats
enum class TexelType : uint32
{
Signed = 0,
Unsigned = 1,
Float = 2,
UNorm = 3,
SNorm = 4,
MAX = SNorm
};
// Describes a texel format
struct TexelFormat final
{
public:
TexelFormat() : type{}, size{ 0 }, count{ 0 } { }
TexelFormat(TexelType type, uint32 size, uint32 count)
: type{ type }, size{ size }, count{ count }
{ }
/* Base Type Checks */
inline bool isSigned() const { return type == TexelType::Signed; }
inline bool isUnsigned() const { return type == TexelType::Unsigned; }
inline bool isFloat() const { return type == TexelType::Float; }
inline bool isUNorm() const { return type == TexelType::UNorm; }
inline bool isSNorm() const { return type == TexelType::SNorm; }
inline bool isIntegerType() const { return isSigned() || isUnsigned(); }
inline bool isFloatingType() const { return isFloat() || isUNorm() || isSNorm(); }
inline bool isNormlizedType() const { return isUNorm() || isSNorm(); }
/* Type Check */
bool isSame(const TexelFormat* format) const;
/* Names */
string getVSLName() const;
string getGLSLName() const;
string getVSLPrefix() const;
string getGLSLPrefix() const;
/* Conversion */
const ShaderType* asDataType() const;
public:
TexelType type;
uint32 size;
uint32 count;
}; // struct TexelFormat
// Contains complete type information (minus array size) about an object, variable, or result
struct ShaderType final
{
public:
ShaderType() : baseType{ BaseType::Void }, texel{} { }
ShaderType(BaseType numericType, uint32 size, uint32 components, uint32 columns)
: baseType{ numericType }, texel{}
{
numeric = { size, { components, columns } };
}
ShaderType(BaseType texelObjectType, TexelRank rank, const TexelFormat* format)
: baseType{ texelObjectType }, texel{ rank, format }
{ }
ShaderType(const BaseType bufferType, const ShaderType* structType)
: baseType{ bufferType }, texel{}
{
buffer.structType = structType;
}
ShaderType(const StructType* structType)
: baseType{ BaseType::Struct }, texel{}
{
userStruct.type = structType;
}
/* Base Type Checks */
inline bool isVoid() const { return baseType == BaseType::Void; }
inline bool isBoolean() const { return baseType == BaseType::Boolean; }
inline bool isSigned() const { return baseType == BaseType::Signed; }
inline bool isUnsigned() const { return baseType == BaseType::Unsigned; }
inline bool isFloat() const { return baseType == BaseType::Float; }
inline bool isSampler() const { return baseType == BaseType::Sampler; }
inline bool isImage() const { return baseType == BaseType::Image; }
inline bool isROBuffer() const { return baseType == BaseType::ROBuffer; }
inline bool isRWBuffer() const { return baseType == BaseType::RWBuffer; }
inline bool isROTexels() const { return baseType == BaseType::ROTexels; }
inline bool isRWTexels() const { return baseType == BaseType::RWTexels; }
inline bool isSPInput() const { return baseType == BaseType::SPInput; }
inline bool isUniform() const { return baseType == BaseType::Uniform; }
inline bool isStruct() const { return baseType == BaseType::Struct; }
/* Composite Type Checks */
inline bool isInteger() const { return isSigned() || isUnsigned(); }
inline bool isNumericType() const { return isInteger() || isFloat(); }
inline bool isScalar() const {
return (isNumericType() || isBoolean()) && (numeric.dims[0] == 1) && (numeric.dims[1] == 1);
}
inline bool isVector() const {
return (isNumericType() || isBoolean()) && (numeric.dims[0] != 1) && (numeric.dims[1] == 1);
}
inline bool isMatrix() const {
return isNumericType() && (numeric.dims[0] != 1) && (numeric.dims[1] != 1);
}
inline bool isTexelType() const { return isSampler() || isImage() || isROTexels() || isRWTexels() || isSPInput(); }
inline bool isBufferType() const { return isROBuffer() || isRWBuffer(); }
inline bool hasStructType() const { return isUniform() || isBufferType() || isStruct(); }
/* Casting */
bool isSame(const ShaderType* otherType) const;
bool hasImplicitCast(const ShaderType* targetType) const;
/* Names */
string getVSLName() const;
string getGLSLName() const;
/* Type-Specific Functions */
uint32 getBindingCount() const;
/* Operators */
inline bool operator == (const ShaderType& r) const { return (this == &r) || isSame(&r); }
inline bool operator != (const ShaderType& r) const { return (this != &r) && !isSame(&r); }
public:
BaseType baseType;
union
{
struct NumericInfo
{
uint32 size;
uint32 dims[2];
} numeric;
struct TexelInfo
{
TexelRank rank;
const TexelFormat* format;
} texel;
struct BufferInfo
{
const ShaderType* structType;
} buffer;
struct StructInfo
{
const StructType* type;
} userStruct;
};
}; // struct ShaderType
// Contains a collection of types for a specific shader
class TypeList final
{
public:
using TypeMap = std::unordered_map<string, ShaderType>;
using StructMap = std::unordered_map<string, StructType>;
using FormatMap = std::unordered_map<string, TexelFormat>;
TypeList() : types_{ }, structs_{ }, error_{ } { Initialize(); }
~TypeList() { }
inline const string& lastError() const { return error_; }
/* Types */
const ShaderType* addType(const string& name, const ShaderType& type);
const ShaderType* getType(const string& name) const;
const StructType* addStructType(const string& name, const StructType& type);
const StructType* getStructType(const string& name) const;
const ShaderType* parseOrGetType(const string& name);
/* Access */
inline static const TypeMap& BuiltinTypes() {
if (BuiltinTypes_.empty()) {
Initialize();
}
return BuiltinTypes_;
}
static const ShaderType* GetBuiltinType(const string& name);
static const TexelFormat* GetTexelFormat(const string& format);
static const ShaderType* GetNumericType(BaseType baseType, uint32 size, uint32 dim0, uint32 dim1);
static const ShaderType* ParseGenericType(const string& baseType);
private:
static void Initialize();
private:
TypeMap types_; // Types added by the shader, does not duplicate BuiltinTypes_
StructMap structs_;
mutable string error_;
static bool Initialized_;
static TypeMap BuiltinTypes_;
static TypeMap GenericTypes_;
static FormatMap Formats_;
VSL_NO_COPY(TypeList)
VSL_NO_MOVE(TypeList)
}; // class TypeList
} // namespace vsl
| 31.694915 | 118 | 0.694118 | VegaLib |
403bf13cd3d727bb040b68c6ed8860e673818d6d | 5,322 | cpp | C++ | VEngine/src/VEngine/scene/Scene.cpp | Parsif/VEngine | a31bdb1479c4dabe6a5eb808008600e736164180 | [
"MIT"
] | null | null | null | VEngine/src/VEngine/scene/Scene.cpp | Parsif/VEngine | a31bdb1479c4dabe6a5eb808008600e736164180 | [
"MIT"
] | null | null | null | VEngine/src/VEngine/scene/Scene.cpp | Parsif/VEngine | a31bdb1479c4dabe6a5eb808008600e736164180 | [
"MIT"
] | null | null | null | #include "precheader.h"
#include "Scene.h"
#include "renderer/ModelLoader.h"
#include "renderer/Renderer.h"
#include "renderer/MaterialLibrary.h"
#include <glm/gtx/string_cast.hpp>
namespace vengine
{
void Scene::init(Ref<Renderer> renderer)
{
m_renderer = renderer;
create_camera();
}
void Scene::on_update()
{
//Try to move setting params out from loop
m_renderer->set_camera_params(m_active_camera);
for (auto&& [view_entity, dir_light_component, transform_component] : m_registry.view<DirLightComponent, TransformComponent>().each())
{
m_renderer->add_dir_light(dir_light_component, transform_component.translation);
}
for (auto&& [view_entity, point_light_component, transform_component] : m_registry.view<PointLightComponent, TransformComponent>().each())
{
m_renderer->add_point_light(point_light_component, transform_component.translation);
}
for (auto&& [view_entity, sphere_area_light_component, transform_component] : m_registry.view<SphereAreaLightComponent, TransformComponent>().each())
{
m_renderer->add_sphere_area_light(sphere_area_light_component, transform_component.translation);
}
for (auto&& [view_entity, tube_area_light_component, transform_component] : m_registry.view<TubeAreaLightComponent, TransformComponent>().each())
{
m_renderer->add_tube_area_light(tube_area_light_component, transform_component.translation);
}
for (auto&& [view_entity, model_component, transform_component, materials_component]
: m_registry.view<ModelComponent, TransformComponent, MaterialsComponent>().each())
{
auto& mesh = ModelLoader::get_mesh(model_component.filepath);
mesh.is_casting_shadow = true;
mesh.transform = transform_component.get_transform();
mesh.materials = materials_component;
m_renderer->add_drawable(mesh);
}
}
void Scene::on_event(const Event& event)
{
m_active_camera.on_event(event);
}
[[nodiscard]] entt::entity Scene::create_empty_entity(const std::string& tag)
{
const auto entity = m_registry.create();
m_registry.emplace<TagComponent>(entity, tag);
return entity;
}
void Scene::create_camera()
{
m_game_camera_entity = m_registry.create();
m_registry.emplace<TagComponent>(m_game_camera_entity, "Camera");
const Camera camera{ 45.0f, 0.1f, 500.f };
m_registry.emplace<CameraComponent>(m_game_camera_entity, camera);
m_registry.emplace<TransformComponent>(m_game_camera_entity);
}
void Scene::create_model(const std::string& model_path)
{
const auto entity = m_registry.create();
m_registry.emplace<TagComponent>(entity, "Model entity");
m_registry.emplace<TransformComponent>(entity);
m_registry.emplace<ModelComponent>(entity, model_path);
m_registry.emplace<MaterialsComponent>(entity);
}
void Scene::destroy_entity(entt::entity entity)
{
m_registry.destroy(entity);
}
void Scene::set_game_camera_entity(entt::entity entity)
{
m_game_camera_entity = entity;
}
void Scene::clear()
{
m_registry.clear();
}
void Scene::create_dir_light()
{
if (m_registry.view<DirLightComponent>().size() == Renderer::get_max_lights())
{
LOG_WARNING("Too many lights")
return;
}
const entt::entity entity = m_registry.create();
m_registry.emplace<TagComponent>(entity, "Directional light");
m_registry.emplace<TransformComponent>(entity);
m_registry.emplace<DirLightComponent>(entity);
}
void Scene::create_point_light()
{
if (m_registry.view<PointLightComponent>().size() == Renderer::get_max_lights())
{
LOG_WARNING("Too many lights")
return;
}
const entt::entity entity = m_registry.create();
m_registry.emplace<TagComponent>(entity, "Point light");
m_registry.emplace<TransformComponent>(entity);
m_registry.emplace<PointLightComponent>(entity);
}
void Scene::create_sphere_area_light()
{
if (m_registry.view<SphereAreaLightComponent>().size() == Renderer::get_max_lights())
{
LOG_WARNING("Too many lights")
return;
}
const entt::entity entity = m_registry.create();
m_registry.emplace<TagComponent>(entity, "Sphere area light");
m_registry.emplace<TransformComponent>(entity);
m_registry.emplace<SphereAreaLightComponent>(entity);
}
void Scene::create_tube_area_light()
{
if(m_registry.view<TubeAreaLightComponent>().size() == Renderer::get_max_lights())
{
LOG_WARNING("Too many lights")
return;
}
const entt::entity entity = m_registry.create();
m_registry.emplace<TagComponent>(entity, "Tube area light");
m_registry.emplace<TransformComponent>(entity);
m_registry.emplace<TubeAreaLightComponent>(entity);
}
void Scene::start_game()
{
if(m_registry.valid(m_game_camera_entity) && m_registry.has<CameraComponent>(m_game_camera_entity))
{
m_is_gamemode_on = true;
m_active_camera = m_registry.get<CameraComponent>(m_game_camera_entity).camera;
m_active_camera.set_position(m_registry.get<TransformComponent>(m_game_camera_entity).translation);
}
else
{
LOG_ERROR("There is no camera in the scene")
}
}
void Scene::stop_game()
{
m_is_gamemode_on = false;
m_active_camera = m_editor_camera;
}
void Scene::set_environment_texture(const TextureGL& texture) const
{
m_renderer->set_scene_environment_map(texture);
}
void Scene::set_exposure(float exposure) const
{
m_renderer->set_exposure(exposure);
}
}
| 28.923913 | 151 | 0.753288 | Parsif |
404140631d8c24907572ed196bb6790b21d7964d | 12,853 | cpp | C++ | src/main.cpp | sthoduka/VOCUS2 | 19da5f334ee59c36853a5989030ff63bc82b9f28 | [
"MIT"
] | 6 | 2018-03-21T03:33:26.000Z | 2021-08-04T07:19:52.000Z | src/main.cpp | sthoduka/VOCUS2 | 19da5f334ee59c36853a5989030ff63bc82b9f28 | [
"MIT"
] | null | null | null | src/main.cpp | sthoduka/VOCUS2 | 19da5f334ee59c36853a5989030ff63bc82b9f28 | [
"MIT"
] | 7 | 2017-12-01T11:01:19.000Z | 2022-01-17T12:03:11.000Z | /*****************************************************************************
*
* main.cpp file for the saliency program VOCUS2.
* A detailed description of the algorithm can be found in the paper: "Traditional Saliency Reloaded: A Good Old Model in New Shape", S. Frintrop, T. Werner, G. Martin Garcia, in Proceedings of the IEEE International Conference on Computer Vision and Pattern Recognition (CVPR), 2015.
* Please cite this paper if you use our method.
*
* Implementation: Thomas Werner ([email protected])
* Design and supervision: Simone Frintrop ([email protected])
*
* Version 1.1
*
* This code is published under the MIT License
* (see file LICENSE.txt for details)
*
******************************************************************************/
#include <iostream>
#include <sstream>
#include <unistd.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <sys/stat.h>
#include "VOCUS2.h"
using namespace std;
using namespace cv;
struct stat sb;
int WEBCAM_MODE = -1;
bool VIDEO_MODE = false;
float MSR_THRESH = 0.75; // most salient region
bool SHOW_OUTPUT = true;
string WRITE_OUT = "";
string WRITE_PATH = "";
string OUTOUT = "";
bool WRITEPATHSET = false;
bool CENTER_BIAS = false;
float SIGMA, K;
int MIN_SIZE, METHOD;
vector<string> split_string(const string &s, char delim) {
vector<string> elems;
stringstream ss(s);
string item;
while (getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
void print_usage(char* argv[]){
cout << "\nUsage: " << argv[0] << " [OPTIONS] <input-file(s)>" << endl << endl;
cout << "===== SALIENCY =====" << endl << endl;
cout << " -x <name>" << "\t\t" << "Config file (is loaded first, additional options have higher priority)" << endl << endl;
cout << " -C <value>" << "\t\t" << "Used colorspace [default: 1]:" << endl;
cout << "\t\t " << "0: LAB" << endl;
cout << "\t\t " << "1: Opponent (CoDi)" << endl;
cout << "\t\t " << "2: Opponent (Equal domains)\n" << endl;
cout << " -f <value>" << "\t\t" << "Fusing operation (Feature maps) [default: 0]:" << endl;
cout << " -F <value>" << "\t\t" << "Fusing operation (Conspicuity/Saliency maps) [default: 0]:" << endl;
cout << "\t\t " << "0: Arithmetic mean" << endl;
cout << "\t\t " << "1: Max" << endl;
cout << "\t\t " << "2: Uniqueness weight\n" << endl;
cout << " -p <value>" << "\t\t" << "Pyramidal structure [default: 2]:" << endl;
cout << "\t\t " << "0: Two independant pyramids (Classic)" << endl;
cout << "\t\t " << "1: Two pyramids derived from a base pyramid (CoDi-like)" << endl;
cout << "\t\t " << "2: Surround pyramid derived from center pyramid (New)\n" << endl;
cout << " -l <value>" << "\t\t" << "Start layer (included) [default: 0]" << endl << endl;
cout << " -L <value>" << "\t\t" << "Stop layer (included) [default: 4]" << endl << endl;
cout << " -S <value>" << "\t\t" << "No. of scales [default: 2]" << endl << endl;
cout << " -c <value>" << "\t\t" << "Center sigma [default: 2]" << endl << endl;
cout << " -s <value>" << "\t\t" << "Surround sigma [default: 10]" << endl << endl;
//cout << " -r" << "\t\t" << "Use orientation [default: off] " << endl << endl;
cout << " -e" << "\t\t" << "Use Combined Feature [default: off]" << endl << endl;
cout << "===== MISC (NOT INCLUDED IN A CONFIG FILE) =====" << endl << endl;
cout << " -v <id>" << "\t\t" << "Webcam source" << endl << endl;
cout << " -V" << "\t\t" << "Video files" << endl << endl;
cout << " -t <value>" << "\t\t" << "MSR threshold (percentage of fixation) [default: 0.75]" << endl << endl;
cout << " -N" << "\t\t" << "No visualization" << endl << endl;
cout << " -o <path>" << "\t\t" << "WRITE results to specified path [default: <input_path>/saliency/*]" << endl << endl;
cout << " -w <path>" << "\t\t" << "WRITE all intermediate maps to an existing folder" << endl << endl;
cout << " -b" << "\t\t" << "Add center bias to the saliency map\n" << endl << endl;
}
bool process_arguments(int argc, char* argv[], VOCUS2_Cfg& cfg, vector<char*>& files){
if(argc == 1) return false;
int c;
while((c = getopt(argc, argv, "bnreNhVC:x:f:F:v:l:o:L:S:c:s:t:p:w:G:")) != -1){
switch(c){
case 'h': return false;
case 'C': cfg.c_space = ColorSpace(atoi(optarg)); break;
case 'f': cfg.fuse_feature = FusionOperation(atoi(optarg)); break;
case 'F': cfg.fuse_conspicuity = FusionOperation(atoi(optarg)); break;
case 'v': WEBCAM_MODE = atoi(optarg) ; break;
case 'l': cfg.start_layer = atoi(optarg); break;
case 'L': cfg.stop_layer = atoi(optarg); break;
case 'S': cfg.n_scales = atoi(optarg); break;
case 'c': cfg.center_sigma = atof(optarg); break;
case 's': cfg.surround_sigma = atof(optarg); break;
case 'V': VIDEO_MODE = true; break;
case 't': MSR_THRESH = atof(optarg); break;
case 'N': SHOW_OUTPUT = false; break;
case 'o': WRITEPATHSET = true; WRITE_PATH = string(optarg); break;
case 'n': cfg.normalize = true; break;
case 'r': cfg.orientation = true; break;
case 'e': cfg.combined_features = true; break;
case 'p': cfg.pyr_struct = PyrStructure(atoi(optarg));
case 'w': WRITE_OUT = string(optarg); break;
case 'b': CENTER_BIAS = true; break;
case 'x': break;
default:
return false;
}
}
if(MSR_THRESH < 0 || MSR_THRESH > 1){
cerr << "MSR threshold must be in the range [0,1]" << endl;
return false;
}
if(cfg.start_layer < 0){
cerr << "Start layer must be positive" << endl;
return false;
}
if(cfg.start_layer > cfg.stop_layer){
cerr << "Start layer cannot be larger than stop layer" << endl;
return false;
}
if(cfg.n_scales <= 0){
cerr << "Numbor of scales must be > 0" << endl;
return false;
}
if(cfg.center_sigma <= 0){
cerr << "Center sigma must be positive" << endl;
return false;
}
if(cfg.surround_sigma <= cfg.center_sigma){
cerr << "Surround sigma must be positive and largen than center sigma" << endl;
return false;
}
for (int i = optind; i < argc; i++)
files.push_back(argv[i]);
if (files.size() == 0 && WEBCAM_MODE < 0) {
return false;
}
if(files.size() == 0 && VIDEO_MODE){
return false;
}
if(WEBCAM_MODE >= 0 && VIDEO_MODE){
return false;
}
return true;
}
// if parameter x specified, load config file
VOCUS2_Cfg create_base_config(int argc, char* argv[]){
VOCUS2_Cfg cfg;
int c;
while((c = getopt(argc, argv, "NbnrehVC:x:f:F:v:l:L:S:o:c:s:t:p:w:G:")) != -1){
if(c == 'x') cfg.load(optarg);
}
optind = 1;
return cfg;
}
//get most salient region
vector<Point> get_msr(Mat& salmap){
double ma;
Point p_ma;
minMaxLoc(salmap, nullptr, &ma, nullptr, &p_ma);
vector<Point> msr;
msr.push_back(p_ma);
int pos = 0;
float thresh = MSR_THRESH*ma;
Mat considered = Mat::zeros(salmap.size(), CV_8U);
considered.at<uchar>(p_ma) = 1;
while(pos < (int)msr.size()){
int r = msr[pos].y;
int c = msr[pos].x;
for(int dr = -1; dr <= 1; dr++){
for(int dc = -1; dc <= 1; dc++){
if(dc == 0 && dr == 0) continue;
if(considered.ptr<uchar>(r+dr)[c+dc] != 0) continue;
if(r+dr < 0 || r+dr >= salmap.rows) continue;
if(c+dc < 0 || c+dc >= salmap.cols) continue;
if(salmap.ptr<float>(r+dr)[c+dc] >= thresh){
msr.push_back(Point(c+dc, r+dr));
considered.ptr<uchar>(r+dr)[c+dc] = 1;
}
}
}
pos++;
}
return msr;
}
int main(int argc, char* argv[]) {
VOCUS2_Cfg cfg = create_base_config(argc, argv);
vector<char*> files; // names of input images or video files
bool correct = process_arguments(argc, argv, cfg, files);
if(!correct){
print_usage(argv);
return EXIT_FAILURE;
}
VOCUS2 vocus2(cfg);
if(WEBCAM_MODE <= -1 && !VIDEO_MODE){ // if normal image
double overall_time = 0;
if(stat(WRITE_PATH.c_str(), &sb)!=0){
if(WRITEPATHSET){
std::cout << "Creating directory..." << std::endl;
mkdir(WRITE_PATH.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
}
//test if data is image data
if(files.size()>=1){
Mat img = imread(files[0]);
if( !(img.channels()==3) ){
std::cout << "ABBORT: Inconsistent Image Data"<< img.channels() << std::endl;
exit(-1);
}
}
//compute saliency
for(size_t i = 0; i < files.size(); i++){
cout << "Opening " << files[i] << " (" << i+1 << "/" << files.size() << "), ";
Mat img = imread(files[i], 1);
long long start = getTickCount();
Mat salmap;
vocus2.process(img);
if(CENTER_BIAS)
salmap = vocus2.add_center_bias(0.00005);
else
salmap = vocus2.get_salmap();
long long stop = getTickCount();
double elapsed_time = (stop-start)/getTickFrequency();
cout << elapsed_time << "sec" << endl;
overall_time += elapsed_time;
//WRITE resulting saliency maps to path/directory
string pathStr(files[i]);
int found = 0;
found = pathStr.find_last_of("/\\");
string path = pathStr.substr(0,found);
string filename_plus = pathStr.substr(found+1);
string filename = filename_plus.substr(0,filename_plus.find_last_of("."));
string WRITE_NAME = filename + "_saliency";
string WRITE_result_PATH;
//if no path set, write to /saliency directory
if(!WRITEPATHSET){
//get the folder, if possible
if(found>=0){
string WRITE_DIR = "/saliency/";
if ( !(stat(WRITE_PATH.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode))){
mkdir((path+WRITE_DIR).c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
WRITE_result_PATH = path + WRITE_DIR + WRITE_NAME + ".png";
}
else{ //if images are in the source folder
string WRITE_DIR = "saliency/";
if ( !(stat(WRITE_PATH.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode))){
mkdir((WRITE_DIR).c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
WRITE_result_PATH = WRITE_DIR + WRITE_NAME + ".png";
}
}
else{
WRITE_result_PATH = WRITE_PATH+"/"+WRITE_NAME+".png";
}
std::cout << "WRITE result to " << WRITE_result_PATH << std::endl << std::endl;
imwrite(WRITE_result_PATH.c_str(), salmap*255.f);
if(WRITE_OUT.compare("") != 0) vocus2.write_out(WRITE_OUT);
vector<Point> msr = get_msr(salmap);
Point2f center;
float rad;
minEnclosingCircle(msr, center, rad);
if(rad >= 5 && rad <= max(img.cols, img.rows)){
circle(img, center, (int)rad, Scalar(0,0,255), 3);
}
if(SHOW_OUTPUT){
imshow("input", img);
imshow("saliency normalized", salmap);
waitKey(0);
}
img.release();
}
cout << "Avg. runtime per image: " << overall_time/(double)files.size() << endl;
}
else if(WEBCAM_MODE >= 0 || !VIDEO_MODE){ // data from webcam
double overall_time = 0;
int n_frames = 0;
VideoCapture vc(WEBCAM_MODE);
if(!vc.isOpened()) return EXIT_FAILURE;
Mat img;
while(vc.read(img)){
n_frames++;
long start = getTickCount();
Mat salmap;
vocus2.process(img);
if(CENTER_BIAS)
salmap = vocus2.add_center_bias(0.00005);
else
salmap = vocus2.get_salmap();
long stop = getTickCount();
double elapsed_time = (stop-start)/getTickFrequency();
cout << "frame " << n_frames << ": " << elapsed_time << "sec" << endl;
overall_time += elapsed_time;
vector<Point> msr = get_msr(salmap);
Point2f center;
float rad;
minEnclosingCircle(msr, center, rad);
if(SHOW_OUTPUT){
imshow("input (ESC to exit)", img);
imshow("saliency streched (ESC to exit)", salmap);
int key_code = waitKey(30);
if(key_code == 113 || key_code == 27) break;
}
img.release();
}
vc.release();
cout << "Avg. runtime per frame: " << overall_time/(double)n_frames << endl;
}
else{ // Video data
for(size_t i = 0; i < files.size(); i++){ // loop over video files
double overall_time = 0;
int n_frames = 0;
VideoCapture vc(files[i]);
if(!vc.isOpened()) return EXIT_FAILURE;
Mat img;
while(vc.read(img)){
n_frames++;
long start = getTickCount();
Mat salmap;
vocus2.process(img);
if(!CENTER_BIAS) salmap = vocus2.get_salmap();
else salmap = vocus2.add_center_bias(0.5);
long stop = getTickCount();
double elapsed_time = (stop-start)/getTickFrequency();
cout << "frame " << n_frames << ": " << elapsed_time << "sec" << endl;
overall_time += elapsed_time;
vector<Point> msr = get_msr(salmap);
Point2f center;
float rad;
minEnclosingCircle(msr, center, rad);
if(SHOW_OUTPUT){
imshow("input (ESC to exit)", img);
imshow("saliency streched (ESC to exit)", salmap);
int key_code = waitKey(30);
if(key_code == 113 || key_code == 27) break;
}
img.release();
}
vc.release();
cout << "Avg. runtime per frame: " << overall_time/(double)n_frames << endl;
}
}
return EXIT_SUCCESS;
}
| 27.522484 | 285 | 0.597993 | sthoduka |
40418b3b6842bf314c4fddc9277886581fc06913 | 5,112 | cpp | C++ | msg_re/parse_x3/src/main.cpp | Bram-Wel/routeros | 21d721384c25edbca66a3d52c853edc9faa83cad | [
"BSD-3-Clause"
] | 732 | 2018-10-07T14:51:37.000Z | 2022-03-31T09:25:20.000Z | msg_re/parse_x3/src/main.cpp | Bram-Wel/routeros | 21d721384c25edbca66a3d52c853edc9faa83cad | [
"BSD-3-Clause"
] | 22 | 2018-10-09T06:49:35.000Z | 2020-05-17T07:43:20.000Z | msg_re/parse_x3/src/main.cpp | Bram-Wel/routeros | 21d721384c25edbca66a3d52c853edc9faa83cad | [
"BSD-3-Clause"
] | 401 | 2018-10-07T16:28:58.000Z | 2022-03-30T09:17:47.000Z | #include <fstream>
#include <iostream>
#include <boost/cstdint.hpp>
#include <boost/scoped_array.hpp>
#include <boost/program_options.hpp>
namespace
{
const char s_version[] = "x3 parser version 1.0.0";
// at least need room for the header
const boost::uint32_t s_minFileSize = 12;
// this isn't actually a hard limit, but larger sizes are unexpected
const boost::uint32_t s_maxFileSize = 100000;
struct x3_header
{
// total length is the file size - 4 bytes (ie. itself)
boost::uint32_t m_totalLength;
// unused?
boost::uint32_t m_reserved0;
// unused?
boost::uint32_t m_reserved1;
};
struct x3_entry
{
boost::uint32_t m_length;
boost::uint32_t m_type;
};
bool parseCommandLine(int p_argCount, const char* p_argArray[], std::string& p_file)
{
boost::program_options::options_description description("options");
description.add_options()
("help,h", "A list of command line options")
("version,v", "Display version information")
("file,f", boost::program_options::value<std::string>(), "The file to parse");
boost::program_options::variables_map argv_map;
try
{
boost::program_options::store(
boost::program_options::parse_command_line(
p_argCount, p_argArray, description), argv_map);
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
std::cout << description << std::endl;
return false;
}
boost::program_options::notify(argv_map);
if (argv_map.empty() || argv_map.count("help"))
{
std::cout << description << std::endl;
return false;
}
if (argv_map.count("version"))
{
std::cout << "Version: " << ::s_version << std::endl;
return false;
}
if (argv_map.count("file"))
{
p_file.assign(argv_map["file"].as<std::string>());
return true;
}
return false;
}
}
int main(int p_argc, const char** p_argv)
{
std::string file;
if (!parseCommandLine(p_argc, p_argv, file))
{
return EXIT_FAILURE;
}
std::ifstream fileStream(file, std::ios::in | std::ios::binary | std::ios::ate);
if (!fileStream.is_open())
{
std::cerr << "Failed to open " << file << std::endl;
return EXIT_FAILURE;
}
std::streampos fileSize = fileStream.tellg();
if (fileSize < s_minFileSize || fileSize > s_maxFileSize)
{
std::cerr << "Bad file size: " << fileSize << std::endl;
fileStream.close();
return EXIT_FAILURE;
}
// read the file into an array
boost::scoped_array<char> memblock(new char[fileSize]);
fileStream.seekg(0, std::ios::beg);
fileStream.read(memblock.get(), fileSize);
fileStream.close();
const x3_header* head = reinterpret_cast<const x3_header*>(memblock.get());
if (head->m_totalLength != (static_cast<boost::uint32_t>(fileSize) - 4))
{
std::cerr << "Invalid total size." << std::endl;
return EXIT_FAILURE;
}
const char* memoryEnd = memblock.get() + fileSize;
const char* memoryCurrent = memblock.get() + 12;
for (const x3_entry* entry = reinterpret_cast<const x3_entry*>(memoryCurrent);
(reinterpret_cast<const char*>(entry) + 12) < memoryEnd;
memoryCurrent += entry->m_length + 4, entry = reinterpret_cast<const x3_entry*>(memoryCurrent))
{
// the outter entry should always be of type 0x1e
if (entry->m_type != 0x1e)
{
std::cerr << "Parsing error." << std::endl;
return EXIT_FAILURE;
}
for (const x3_entry* inner_entry = reinterpret_cast<const x3_entry*>(memoryCurrent + 12);
reinterpret_cast<const char*>(inner_entry) < (memoryCurrent + entry->m_length + 4);
inner_entry = reinterpret_cast<const x3_entry*>(reinterpret_cast<const char*>(inner_entry) + inner_entry->m_length + 4))
{
switch (inner_entry->m_type)
{
case 0x04: // the router number
{
const char* route = reinterpret_cast<const char*>(inner_entry) + inner_entry->m_length;
std::cout << ",";
for (boost::uint8_t i = 0; i < 4; i++)
{
if (route[i] != 0)
{
std::cout << route[i];
}
}
std::cout << std::endl;
}
break;
case 0x07: // the binary name
{
std::string path(reinterpret_cast<const char*>(inner_entry) + 20, inner_entry->m_length - 16);
std::cout << path;
}
break;
default:
break;
}
}
}
return EXIT_SUCCESS;
}
| 31.170732 | 133 | 0.544405 | Bram-Wel |
4047ee09ebe17c6fbed2988abb3bf23a30aab4cc | 2,213 | cpp | C++ | Lab 09/lab9.cpp | ndbeals/Operating-System-Labs | a691558b240fd54ce8272ee2b045cd4c4743804c | [
"MIT"
] | null | null | null | Lab 09/lab9.cpp | ndbeals/Operating-System-Labs | a691558b240fd54ce8272ee2b045cd4c4743804c | [
"MIT"
] | null | null | null | Lab 09/lab9.cpp | ndbeals/Operating-System-Labs | a691558b240fd54ce8272ee2b045cd4c4743804c | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdio.h>
#include <string>
#include <numeric>
#include <algorithm>
// supplied values
int blockSize[] = {5,10,50,100};
int numBlocks = sizeof blockSize / sizeof blockSize[0];
int processSize[] = {11,6,34,5,25,60};
int numberOfProcesses = sizeof processSize / sizeof processSize[0];
// process struct
struct Process
{
int pid;
int blockNumberFF;
int blockNumberNF;
int size;
};
int main()
{
// create an array to hold our processes
Process* list[numberOfProcesses];
// populate array
for(int i = 0; i < numberOfProcesses; i++)
{
list[i] = new Process{ i+1 , 0 , 0 , processSize[i] };
}
// First First
for(int pid = 0; pid < numberOfProcesses; pid++)
{
Process* proc = list[pid];
for(int block = 0; block < numBlocks; block++)
{
// if the process size is less than or equal to block size, assign it to this block
if (proc->size <= blockSize[block] ) {
proc->blockNumberFF = block + 1;
// subtract size from remaining
blockSize[block] -= proc->size;
//exit loop
break;
}
}
}
int blockSize[] = {5,10,50,100};
// Best Fit
int lastblock = 0;
for(int pid = 0; pid < numberOfProcesses; pid++)
{
for(int block = lastblock; block < numBlocks; block++)
{
Process* proc = list[pid];
// if the process size is less than or equal to block size, assign it to this block
if (proc->size <= blockSize[block] && proc->blockNumberNF < 1 ) {
proc->blockNumberNF = block + 1;
// subtract size from remaining
blockSize[block] -= proc->size;
lastblock=block;
}
}
}
// print processes
printf("First Fit:\nPID Process Size Block no.\n");
for(int pid = 0; pid < numberOfProcesses; pid++)
{
Process* proc = list[pid];
printf(" %d %2d %d\n",proc->pid,proc->size,proc->blockNumberFF);
}
// print processes
printf("Next Fit:\nPID Process Size Block no.\n");
for(int pid = 0; pid < numberOfProcesses; pid++)
{
Process* proc = list[pid];
if (proc->blockNumberNF==0) {
printf(" %d %2d %s\n",proc->pid,proc->size,"Not Allocated");
}
else
{
printf(" %d %2d %d\n",proc->pid,proc->size,proc->blockNumberNF);
}
}
} | 22.581633 | 86 | 0.617714 | ndbeals |
405834ee034967ffc7ca02159fc0ca568825fcd6 | 93,895 | cpp | C++ | src/systems/CollisionDetectionSystem.cpp | VaderY/reactphysics3d | 6fe67640fbda3f7c0a50dc0fd88f4c940f9d9c7b | [
"Zlib"
] | null | null | null | src/systems/CollisionDetectionSystem.cpp | VaderY/reactphysics3d | 6fe67640fbda3f7c0a50dc0fd88f4c940f9d9c7b | [
"Zlib"
] | null | null | null | src/systems/CollisionDetectionSystem.cpp | VaderY/reactphysics3d | 6fe67640fbda3f7c0a50dc0fd88f4c940f9d9c7b | [
"Zlib"
] | null | null | null | /********************************************************************************
* ReactPhysics3D physics library, http://www.reactphysics3d.com *
* Copyright (c) 2010-2020 Daniel Chappuis *
*********************************************************************************
* *
* This software is provided 'as-is', without any express or implied warranty. *
* In no event will the authors be held liable for any damages arising from the *
* use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not claim *
* that you wrote the original software. If you use this software in a *
* product, an acknowledgment in the product documentation would be *
* appreciated but is not required. *
* *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* *
* 3. This notice may not be removed or altered from any source distribution. *
* *
********************************************************************************/
// Libraries
#include <reactphysics3d/systems/CollisionDetectionSystem.h>
#include <reactphysics3d/engine/PhysicsWorld.h>
#include <reactphysics3d/collision/OverlapCallback.h>
#include <reactphysics3d/collision/shapes/BoxShape.h>
#include <reactphysics3d/collision/shapes/ConcaveShape.h>
#include <reactphysics3d/collision/ContactManifoldInfo.h>
#include <reactphysics3d/constraint/ContactPoint.h>
#include <reactphysics3d/body/RigidBody.h>
#include <reactphysics3d/configuration.h>
#include <reactphysics3d/collision/CollisionCallback.h>
#include <reactphysics3d/collision/OverlapCallback.h>
#include <reactphysics3d/collision/narrowphase/NarrowPhaseInfoBatch.h>
#include <reactphysics3d/collision/ContactManifold.h>
#include <reactphysics3d/utils/Profiler.h>
#include <reactphysics3d/engine/EventListener.h>
#include <reactphysics3d/collision/RaycastInfo.h>
#include <reactphysics3d/containers/Pair.h>
#include <cassert>
#include <iostream>
// We want to use the ReactPhysics3D namespace
using namespace reactphysics3d;
using namespace std;
// Constructor
CollisionDetectionSystem::CollisionDetectionSystem(PhysicsWorld* world, ColliderComponents& collidersComponents, TransformComponents& transformComponents,
CollisionBodyComponents& collisionBodyComponents, RigidBodyComponents& rigidBodyComponents,
MemoryManager& memoryManager, HalfEdgeStructure& triangleHalfEdgeStructure)
: mMemoryManager(memoryManager), mCollidersComponents(collidersComponents), mRigidBodyComponents(rigidBodyComponents),
mCollisionDispatch(mMemoryManager.getPoolAllocator()), mWorld(world),
mNoCollisionPairs(mMemoryManager.getPoolAllocator()),
mOverlappingPairs(mMemoryManager, mCollidersComponents, collisionBodyComponents, rigidBodyComponents,
mNoCollisionPairs, mCollisionDispatch),
mBroadPhaseOverlappingNodes(mMemoryManager.getHeapAllocator(), 32),
mBroadPhaseSystem(*this, mCollidersComponents, transformComponents, rigidBodyComponents),
mMapBroadPhaseIdToColliderEntity(memoryManager.getPoolAllocator()),
mNarrowPhaseInput(mMemoryManager.getSingleFrameAllocator(), mOverlappingPairs), mPotentialContactPoints(mMemoryManager.getSingleFrameAllocator()),
mPotentialContactManifolds(mMemoryManager.getSingleFrameAllocator()), mContactPairs1(mMemoryManager.getPoolAllocator()),
mContactPairs2(mMemoryManager.getPoolAllocator()), mPreviousContactPairs(&mContactPairs1), mCurrentContactPairs(&mContactPairs2),
mLostContactPairs(mMemoryManager.getSingleFrameAllocator()), mPreviousMapPairIdToContactPairIndex(mMemoryManager.getHeapAllocator()),
mContactManifolds1(mMemoryManager.getPoolAllocator()), mContactManifolds2(mMemoryManager.getPoolAllocator()),
mPreviousContactManifolds(&mContactManifolds1), mCurrentContactManifolds(&mContactManifolds2),
mContactPoints1(mMemoryManager.getPoolAllocator()), mContactPoints2(mMemoryManager.getPoolAllocator()),
mPreviousContactPoints(&mContactPoints1), mCurrentContactPoints(&mContactPoints2), mCollisionBodyContactPairsIndices(mMemoryManager.getSingleFrameAllocator()),
mNbPreviousPotentialContactManifolds(0), mNbPreviousPotentialContactPoints(0), mTriangleHalfEdgeStructure(triangleHalfEdgeStructure) {
#ifdef IS_RP3D_PROFILING_ENABLED
mProfiler = nullptr;
mCollisionDispatch.setProfiler(mProfiler);
mOverlappingPairs.setProfiler(mProfiler);
#endif
}
// Compute the collision detection
void CollisionDetectionSystem::computeCollisionDetection() {
RP3D_PROFILE("CollisionDetectionSystem::computeCollisionDetection()", mProfiler);
// Compute the broad-phase collision detection
computeBroadPhase();
// Compute the middle-phase collision detection
computeMiddlePhase(mNarrowPhaseInput, true);
// Compute the narrow-phase collision detection
computeNarrowPhase();
}
// Compute the broad-phase collision detection
void CollisionDetectionSystem::computeBroadPhase() {
RP3D_PROFILE("CollisionDetectionSystem::computeBroadPhase()", mProfiler);
assert(mBroadPhaseOverlappingNodes.size() == 0);
// Ask the broad-phase to compute all the shapes overlapping with the shapes that
// have moved or have been added in the last frame. This call can only add new
// overlapping pairs in the collision detection.
mBroadPhaseSystem.computeOverlappingPairs(mMemoryManager, mBroadPhaseOverlappingNodes);
// Create new overlapping pairs if necessary
updateOverlappingPairs(mBroadPhaseOverlappingNodes);
// Remove non overlapping pairs
removeNonOverlappingPairs();
mBroadPhaseOverlappingNodes.clear();
}
// Remove pairs that are not overlapping anymore
void CollisionDetectionSystem::removeNonOverlappingPairs() {
RP3D_PROFILE("CollisionDetectionSystem::removeNonOverlappingPairs()", mProfiler);
// For each convex pairs
for (uint64 i=0; i < mOverlappingPairs.mConvexPairs.size(); i++) {
OverlappingPairs::ConvexOverlappingPair& overlappingPair = mOverlappingPairs.mConvexPairs[i];
// Check if we need to test overlap. If so, test if the two shapes are still overlapping.
// Otherwise, we destroy the overlapping pair
if (overlappingPair.needToTestOverlap) {
if(mBroadPhaseSystem.testOverlappingShapes(overlappingPair.broadPhaseId1, overlappingPair.broadPhaseId2)) {
overlappingPair.needToTestOverlap = false;
}
else {
// If the two colliders of the pair were colliding in the previous frame
if (overlappingPair.collidingInPreviousFrame) {
// Create a new lost contact pair
addLostContactPair(overlappingPair);
}
mOverlappingPairs.removePair(i, true);
i--;
}
}
}
// For each concave pairs
for (uint64 i=0; i < mOverlappingPairs.mConcavePairs.size(); i++) {
OverlappingPairs::ConcaveOverlappingPair& overlappingPair = mOverlappingPairs.mConcavePairs[i];
// Check if we need to test overlap. If so, test if the two shapes are still overlapping.
// Otherwise, we destroy the overlapping pair
if (overlappingPair.needToTestOverlap) {
if(mBroadPhaseSystem.testOverlappingShapes(overlappingPair.broadPhaseId1, overlappingPair.broadPhaseId2)) {
overlappingPair.needToTestOverlap = false;
}
else {
// If the two colliders of the pair were colliding in the previous frame
if (overlappingPair.collidingInPreviousFrame) {
// Create a new lost contact pair
addLostContactPair(overlappingPair);
}
mOverlappingPairs.removePair(i, false);
i--;
}
}
}
}
// Add a lost contact pair (pair of colliders that are not in contact anymore)
void CollisionDetectionSystem::addLostContactPair(OverlappingPairs::OverlappingPair& overlappingPair) {
const uint32 collider1Index = mCollidersComponents.getEntityIndex(overlappingPair.collider1);
const uint32 collider2Index = mCollidersComponents.getEntityIndex(overlappingPair.collider2);
const Entity body1Entity = mCollidersComponents.mBodiesEntities[collider1Index];
const Entity body2Entity = mCollidersComponents.mBodiesEntities[collider2Index];
const bool isCollider1Trigger = mCollidersComponents.mIsTrigger[collider1Index];
const bool isCollider2Trigger = mCollidersComponents.mIsTrigger[collider2Index];
const bool isTrigger = isCollider1Trigger || isCollider2Trigger;
// Create a lost contact pair
ContactPair lostContactPair(overlappingPair.pairID, body1Entity, body2Entity, overlappingPair.collider1, overlappingPair.collider2, mLostContactPairs.size(),
true, isTrigger, mMemoryManager.getHeapAllocator());
mLostContactPairs.add(lostContactPair);
}
// Take an array of overlapping nodes in the broad-phase and create new overlapping pairs if necessary
void CollisionDetectionSystem::updateOverlappingPairs(const Array<Pair<int32, int32>>& overlappingNodes) {
RP3D_PROFILE("CollisionDetectionSystem::updateOverlappingPairs()", mProfiler);
// For each overlapping pair of nodes
const uint32 nbOverlappingNodes = overlappingNodes.size();
for (uint32 i=0; i < nbOverlappingNodes; i++) {
Pair<int32, int32> nodePair = overlappingNodes[i];
assert(nodePair.first != -1);
assert(nodePair.second != -1);
// Skip pairs with same overlapping nodes
if (nodePair.first != nodePair.second) {
// Get the two colliders
const Entity collider1Entity = mMapBroadPhaseIdToColliderEntity[nodePair.first];
const Entity collider2Entity = mMapBroadPhaseIdToColliderEntity[nodePair.second];
const uint collider1Index = mCollidersComponents.getEntityIndex(collider1Entity);
const uint collider2Index = mCollidersComponents.getEntityIndex(collider2Entity);
// Get the two bodies
const Entity body1Entity = mCollidersComponents.mBodiesEntities[collider1Index];
const Entity body2Entity = mCollidersComponents.mBodiesEntities[collider2Index];
// If the two colliders are from the same body, skip it
if (body1Entity != body2Entity) {
const uint32 nbEnabledColliderComponents = mCollidersComponents.getNbEnabledComponents();
const bool isBody1Enabled = collider1Index < nbEnabledColliderComponents;
const bool isBody2Enabled = collider2Index < nbEnabledColliderComponents;
bool isBody1Static = false;
bool isBody2Static = false;
uint32 rigidBody1Index, rigidBody2Index;
if (mRigidBodyComponents.hasComponentGetIndex(body1Entity, rigidBody1Index)) {
isBody1Static = mRigidBodyComponents.mBodyTypes[rigidBody1Index] == BodyType::STATIC;
}
if (mRigidBodyComponents.hasComponentGetIndex(body2Entity, rigidBody2Index)) {
isBody2Static = mRigidBodyComponents.mBodyTypes[rigidBody2Index] == BodyType::STATIC;
}
const bool isBody1Active = isBody1Enabled && !isBody1Static;
const bool isBody2Active = isBody2Enabled && !isBody2Static;
if (isBody1Active || isBody2Active) {
// Check if the bodies are in the set of bodies that cannot collide between each other
// TODO OPTI : What not use the pairId here ??
const bodypair bodiesIndex = OverlappingPairs::computeBodiesIndexPair(body1Entity, body2Entity);
if (!mNoCollisionPairs.contains(bodiesIndex)) {
// Compute the overlapping pair ID
const uint64 pairId = pairNumbers(std::max(nodePair.first, nodePair.second), std::min(nodePair.first, nodePair.second));
// Check if the overlapping pair already exists
OverlappingPairs::OverlappingPair* overlappingPair = mOverlappingPairs.getOverlappingPair(pairId);
if (overlappingPair == nullptr) {
const unsigned short shape1CollideWithMaskBits = mCollidersComponents.mCollideWithMaskBits[collider1Index];
const unsigned short shape2CollideWithMaskBits = mCollidersComponents.mCollideWithMaskBits[collider2Index];
const unsigned short shape1CollisionCategoryBits = mCollidersComponents.mCollisionCategoryBits[collider1Index];
const unsigned short shape2CollisionCategoryBits = mCollidersComponents.mCollisionCategoryBits[collider2Index];
// Check if the collision filtering allows collision between the two shapes
if ((shape1CollideWithMaskBits & shape2CollisionCategoryBits) != 0 &&
(shape1CollisionCategoryBits & shape2CollideWithMaskBits) != 0) {
Collider* shape1 = mCollidersComponents.mColliders[collider1Index];
Collider* shape2 = mCollidersComponents.mColliders[collider2Index];
// Check that at least one collision shape is convex
const bool isShape1Convex = shape1->getCollisionShape()->isConvex();
const bool isShape2Convex = shape2->getCollisionShape()->isConvex();
if (isShape1Convex || isShape2Convex) {
// Add the new overlapping pair
mOverlappingPairs.addPair(collider1Index, collider2Index, isShape1Convex && isShape2Convex);
}
}
}
else {
// We do not need to test the pair for overlap because it has just been reported that they still overlap
overlappingPair->needToTestOverlap = false;
}
}
}
}
}
}
}
// Compute the middle-phase collision detection
void CollisionDetectionSystem::computeMiddlePhase(NarrowPhaseInput& narrowPhaseInput, bool needToReportContacts) {
RP3D_PROFILE("CollisionDetectionSystem::computeMiddlePhase()", mProfiler);
// Reserve memory for the narrow-phase input using cached capacity from previous frame
narrowPhaseInput.reserveMemory();
// Remove the obsolete last frame collision infos and mark all the others as obsolete
mOverlappingPairs.clearObsoleteLastFrameCollisionInfos();
// For each possible convex vs convex pair of bodies
const uint64 nbConvexVsConvexPairs = mOverlappingPairs.mConvexPairs.size();
for (uint64 i=0; i < nbConvexVsConvexPairs; i++) {
OverlappingPairs::ConvexOverlappingPair& overlappingPair = mOverlappingPairs.mConvexPairs[i];
assert(mCollidersComponents.getBroadPhaseId(overlappingPair.collider1) != -1);
assert(mCollidersComponents.getBroadPhaseId(overlappingPair.collider2) != -1);
assert(mCollidersComponents.getBroadPhaseId(overlappingPair.collider1) != mCollidersComponents.getBroadPhaseId(overlappingPair.collider2));
const Entity collider1Entity = overlappingPair.collider1;
const Entity collider2Entity = overlappingPair.collider2;
const uint collider1Index = mCollidersComponents.getEntityIndex(collider1Entity);
const uint collider2Index = mCollidersComponents.getEntityIndex(collider2Entity);
CollisionShape* collisionShape1 = mCollidersComponents.mCollisionShapes[collider1Index];
CollisionShape* collisionShape2 = mCollidersComponents.mCollisionShapes[collider2Index];
NarrowPhaseAlgorithmType algorithmType = overlappingPair.narrowPhaseAlgorithmType;
const bool isCollider1Trigger = mCollidersComponents.mIsTrigger[collider1Index];
const bool isCollider2Trigger = mCollidersComponents.mIsTrigger[collider2Index];
const bool reportContacts = needToReportContacts && !isCollider1Trigger && !isCollider2Trigger;
// No middle-phase is necessary, simply create a narrow phase info
// for the narrow-phase collision detection
narrowPhaseInput.addNarrowPhaseTest(overlappingPair.pairID, collider1Entity, collider2Entity, collisionShape1, collisionShape2,
mCollidersComponents.mLocalToWorldTransforms[collider1Index],
mCollidersComponents.mLocalToWorldTransforms[collider2Index],
algorithmType, reportContacts, &overlappingPair.lastFrameCollisionInfo,
mMemoryManager.getSingleFrameAllocator());
overlappingPair.collidingInCurrentFrame = false;
}
// For each possible convex vs concave pair of bodies
const uint64 nbConcavePairs = mOverlappingPairs.mConcavePairs.size();
for (uint64 i=0; i < nbConcavePairs; i++) {
OverlappingPairs::ConcaveOverlappingPair& overlappingPair = mOverlappingPairs.mConcavePairs[i];
assert(mCollidersComponents.getBroadPhaseId(overlappingPair.collider1) != -1);
assert(mCollidersComponents.getBroadPhaseId(overlappingPair.collider2) != -1);
assert(mCollidersComponents.getBroadPhaseId(overlappingPair.collider1) != mCollidersComponents.getBroadPhaseId(overlappingPair.collider2));
computeConvexVsConcaveMiddlePhase(overlappingPair, mMemoryManager.getSingleFrameAllocator(), narrowPhaseInput, needToReportContacts);
overlappingPair.collidingInCurrentFrame = false;
}
}
// Compute the middle-phase collision detection
void CollisionDetectionSystem::computeMiddlePhaseCollisionSnapshot(Array<uint64>& convexPairs, Array<uint64>& concavePairs,
NarrowPhaseInput& narrowPhaseInput, bool reportContacts) {
RP3D_PROFILE("CollisionDetectionSystem::computeMiddlePhase()", mProfiler);
// Reserve memory for the narrow-phase input using cached capacity from previous frame
narrowPhaseInput.reserveMemory();
// Remove the obsolete last frame collision infos and mark all the others as obsolete
mOverlappingPairs.clearObsoleteLastFrameCollisionInfos();
// For each possible convex vs convex pair of bodies
const uint64 nbConvexPairs = convexPairs.size();
for (uint64 p=0; p < nbConvexPairs; p++) {
const uint64 pairId = convexPairs[p];
const uint64 pairIndex = mOverlappingPairs.mMapConvexPairIdToPairIndex[pairId];
assert(pairIndex < mOverlappingPairs.mConvexPairs.size());
const Entity collider1Entity = mOverlappingPairs.mConvexPairs[pairIndex].collider1;
const Entity collider2Entity = mOverlappingPairs.mConvexPairs[pairIndex].collider2;
const uint collider1Index = mCollidersComponents.getEntityIndex(collider1Entity);
const uint collider2Index = mCollidersComponents.getEntityIndex(collider2Entity);
assert(mCollidersComponents.getBroadPhaseId(collider1Entity) != -1);
assert(mCollidersComponents.getBroadPhaseId(collider2Entity) != -1);
assert(mCollidersComponents.getBroadPhaseId(collider1Entity) != mCollidersComponents.getBroadPhaseId(collider2Entity));
CollisionShape* collisionShape1 = mCollidersComponents.mCollisionShapes[collider1Index];
CollisionShape* collisionShape2 = mCollidersComponents.mCollisionShapes[collider2Index];
NarrowPhaseAlgorithmType algorithmType = mOverlappingPairs.mConvexPairs[pairIndex].narrowPhaseAlgorithmType;
// No middle-phase is necessary, simply create a narrow phase info
// for the narrow-phase collision detection
narrowPhaseInput.addNarrowPhaseTest(pairId, collider1Entity, collider2Entity, collisionShape1, collisionShape2,
mCollidersComponents.mLocalToWorldTransforms[collider1Index],
mCollidersComponents.mLocalToWorldTransforms[collider2Index],
algorithmType, reportContacts, &mOverlappingPairs.mConvexPairs[pairIndex].lastFrameCollisionInfo, mMemoryManager.getSingleFrameAllocator());
}
// For each possible convex vs concave pair of bodies
const uint nbConcavePairs = concavePairs.size();
for (uint p=0; p < nbConcavePairs; p++) {
const uint64 pairId = concavePairs[p];
const uint64 pairIndex = mOverlappingPairs.mMapConcavePairIdToPairIndex[pairId];
assert(mCollidersComponents.getBroadPhaseId(mOverlappingPairs.mConcavePairs[pairIndex].collider1) != -1);
assert(mCollidersComponents.getBroadPhaseId(mOverlappingPairs.mConcavePairs[pairIndex].collider2) != -1);
assert(mCollidersComponents.getBroadPhaseId(mOverlappingPairs.mConcavePairs[pairIndex].collider1) != mCollidersComponents.getBroadPhaseId(mOverlappingPairs.mConcavePairs[pairIndex].collider2));
computeConvexVsConcaveMiddlePhase(mOverlappingPairs.mConcavePairs[pairIndex], mMemoryManager.getSingleFrameAllocator(), narrowPhaseInput, reportContacts);
}
}
// Compute the concave vs convex middle-phase algorithm for a given pair of bodies
void CollisionDetectionSystem::computeConvexVsConcaveMiddlePhase(OverlappingPairs::ConcaveOverlappingPair& overlappingPair, MemoryAllocator& allocator, NarrowPhaseInput& narrowPhaseInput, bool reportContacts) {
RP3D_PROFILE("CollisionDetectionSystem::computeConvexVsConcaveMiddlePhase()", mProfiler);
const Entity collider1 = overlappingPair.collider1;
const Entity collider2 = overlappingPair.collider2;
const uint collider1Index = mCollidersComponents.getEntityIndex(collider1);
const uint collider2Index = mCollidersComponents.getEntityIndex(collider2);
Transform& shape1LocalToWorldTransform = mCollidersComponents.mLocalToWorldTransforms[collider1Index];
Transform& shape2LocalToWorldTransform = mCollidersComponents.mLocalToWorldTransforms[collider2Index];
Transform convexToConcaveTransform;
// Collision shape 1 is convex, collision shape 2 is concave
ConvexShape* convexShape;
ConcaveShape* concaveShape;
if (overlappingPair.isShape1Convex) {
convexShape = static_cast<ConvexShape*>(mCollidersComponents.mCollisionShapes[collider1Index]);
concaveShape = static_cast<ConcaveShape*>(mCollidersComponents.mCollisionShapes[collider2Index]);
convexToConcaveTransform = shape2LocalToWorldTransform.getInverse() * shape1LocalToWorldTransform;
}
else { // Collision shape 2 is convex, collision shape 1 is concave
convexShape = static_cast<ConvexShape*>(mCollidersComponents.mCollisionShapes[collider2Index]);
concaveShape = static_cast<ConcaveShape*>(mCollidersComponents.mCollisionShapes[collider1Index]);
convexToConcaveTransform = shape1LocalToWorldTransform.getInverse() * shape2LocalToWorldTransform;
}
assert(convexShape->isConvex());
assert(!concaveShape->isConvex());
assert(overlappingPair.narrowPhaseAlgorithmType != NarrowPhaseAlgorithmType::None);
// Compute the convex shape AABB in the local-space of the convex shape
AABB aabb;
convexShape->computeAABB(aabb, convexToConcaveTransform);
// Compute the concave shape triangles that are overlapping with the convex mesh AABB
Array<Vector3> triangleVertices(allocator, 64);
Array<Vector3> triangleVerticesNormals(allocator, 64);
Array<uint> shapeIds(allocator, 64);
concaveShape->computeOverlappingTriangles(aabb, triangleVertices, triangleVerticesNormals, shapeIds, allocator);
assert(triangleVertices.size() == triangleVerticesNormals.size());
assert(shapeIds.size() == triangleVertices.size() / 3);
assert(triangleVertices.size() % 3 == 0);
assert(triangleVerticesNormals.size() % 3 == 0);
const bool isCollider1Trigger = mCollidersComponents.mIsTrigger[collider1Index];
const bool isCollider2Trigger = mCollidersComponents.mIsTrigger[collider2Index];
reportContacts = reportContacts && !isCollider1Trigger && !isCollider2Trigger;
CollisionShape* shape1;
CollisionShape* shape2;
if (overlappingPair.isShape1Convex) {
shape1 = convexShape;
}
else {
shape2 = convexShape;
}
// For each overlapping triangle
const uint32 nbShapeIds = shapeIds.size();
for (uint32 i=0; i < nbShapeIds; i++) {
// Create a triangle collision shape (the allocated memory for the TriangleShape will be released in the
// destructor of the corresponding NarrowPhaseInfo.
TriangleShape* triangleShape = new (allocator.allocate(sizeof(TriangleShape)))
TriangleShape(&(triangleVertices[i * 3]), &(triangleVerticesNormals[i * 3]), shapeIds[i], mTriangleHalfEdgeStructure, allocator);
#ifdef IS_RP3D_PROFILING_ENABLED
// Set the profiler to the triangle shape
triangleShape->setProfiler(mProfiler);
#endif
if (overlappingPair.isShape1Convex) {
shape2 = triangleShape;
}
else {
shape1 = triangleShape;
}
// Add a collision info for the two collision shapes into the overlapping pair (if not present yet)
LastFrameCollisionInfo* lastFrameInfo = overlappingPair.addLastFrameInfoIfNecessary(shape1->getId(), shape2->getId());
// Create a narrow phase info for the narrow-phase collision detection
narrowPhaseInput.addNarrowPhaseTest(overlappingPair.pairID, collider1, collider2, shape1, shape2,
shape1LocalToWorldTransform, shape2LocalToWorldTransform,
overlappingPair.narrowPhaseAlgorithmType, reportContacts, lastFrameInfo, allocator);
}
}
// Execute the narrow-phase collision detection algorithm on batches
bool CollisionDetectionSystem::testNarrowPhaseCollision(NarrowPhaseInput& narrowPhaseInput,
bool clipWithPreviousAxisIfStillColliding, MemoryAllocator& allocator) {
bool contactFound = false;
// Get the narrow-phase collision detection algorithms for each kind of collision shapes
SphereVsSphereAlgorithm* sphereVsSphereAlgo = mCollisionDispatch.getSphereVsSphereAlgorithm();
SphereVsCapsuleAlgorithm* sphereVsCapsuleAlgo = mCollisionDispatch.getSphereVsCapsuleAlgorithm();
CapsuleVsCapsuleAlgorithm* capsuleVsCapsuleAlgo = mCollisionDispatch.getCapsuleVsCapsuleAlgorithm();
SphereVsConvexPolyhedronAlgorithm* sphereVsConvexPolyAlgo = mCollisionDispatch.getSphereVsConvexPolyhedronAlgorithm();
CapsuleVsConvexPolyhedronAlgorithm* capsuleVsConvexPolyAlgo = mCollisionDispatch.getCapsuleVsConvexPolyhedronAlgorithm();
ConvexPolyhedronVsConvexPolyhedronAlgorithm* convexPolyVsConvexPolyAlgo = mCollisionDispatch.getConvexPolyhedronVsConvexPolyhedronAlgorithm();
// get the narrow-phase batches to test for collision for contacts
NarrowPhaseInfoBatch& sphereVsSphereBatchContacts = narrowPhaseInput.getSphereVsSphereBatch();
NarrowPhaseInfoBatch& sphereVsCapsuleBatchContacts = narrowPhaseInput.getSphereVsCapsuleBatch();
NarrowPhaseInfoBatch& capsuleVsCapsuleBatchContacts = narrowPhaseInput.getCapsuleVsCapsuleBatch();
NarrowPhaseInfoBatch& sphereVsConvexPolyhedronBatchContacts = narrowPhaseInput.getSphereVsConvexPolyhedronBatch();
NarrowPhaseInfoBatch& capsuleVsConvexPolyhedronBatchContacts = narrowPhaseInput.getCapsuleVsConvexPolyhedronBatch();
NarrowPhaseInfoBatch& convexPolyhedronVsConvexPolyhedronBatchContacts = narrowPhaseInput.getConvexPolyhedronVsConvexPolyhedronBatch();
// Compute the narrow-phase collision detection for each kind of collision shapes (for contacts)
if (sphereVsSphereBatchContacts.getNbObjects() > 0) {
contactFound |= sphereVsSphereAlgo->testCollision(sphereVsSphereBatchContacts, 0, sphereVsSphereBatchContacts.getNbObjects(), allocator);
}
if (sphereVsCapsuleBatchContacts.getNbObjects() > 0) {
contactFound |= sphereVsCapsuleAlgo->testCollision(sphereVsCapsuleBatchContacts, 0, sphereVsCapsuleBatchContacts.getNbObjects(), allocator);
}
if (capsuleVsCapsuleBatchContacts.getNbObjects() > 0) {
contactFound |= capsuleVsCapsuleAlgo->testCollision(capsuleVsCapsuleBatchContacts, 0, capsuleVsCapsuleBatchContacts.getNbObjects(), allocator);
}
if (sphereVsConvexPolyhedronBatchContacts.getNbObjects() > 0) {
contactFound |= sphereVsConvexPolyAlgo->testCollision(sphereVsConvexPolyhedronBatchContacts, 0, sphereVsConvexPolyhedronBatchContacts.getNbObjects(), clipWithPreviousAxisIfStillColliding, allocator);
}
if (capsuleVsConvexPolyhedronBatchContacts.getNbObjects() > 0) {
contactFound |= capsuleVsConvexPolyAlgo->testCollision(capsuleVsConvexPolyhedronBatchContacts, 0, capsuleVsConvexPolyhedronBatchContacts.getNbObjects(), clipWithPreviousAxisIfStillColliding, allocator);
}
if (convexPolyhedronVsConvexPolyhedronBatchContacts.getNbObjects() > 0) {
contactFound |= convexPolyVsConvexPolyAlgo->testCollision(convexPolyhedronVsConvexPolyhedronBatchContacts, 0, convexPolyhedronVsConvexPolyhedronBatchContacts.getNbObjects(), clipWithPreviousAxisIfStillColliding, allocator);
}
return contactFound;
}
// Process the potential contacts after narrow-phase collision detection
void CollisionDetectionSystem::processAllPotentialContacts(NarrowPhaseInput& narrowPhaseInput, bool updateLastFrameInfo,
Array<ContactPointInfo>& potentialContactPoints,
Array<ContactManifoldInfo>& potentialContactManifolds,
Array<ContactPair>* contactPairs) {
assert(contactPairs->size() == 0);
Map<uint64, uint> mapPairIdToContactPairIndex(mMemoryManager.getHeapAllocator(), mPreviousMapPairIdToContactPairIndex.size());
// get the narrow-phase batches to test for collision
NarrowPhaseInfoBatch& sphereVsSphereBatch = narrowPhaseInput.getSphereVsSphereBatch();
NarrowPhaseInfoBatch& sphereVsCapsuleBatch = narrowPhaseInput.getSphereVsCapsuleBatch();
NarrowPhaseInfoBatch& capsuleVsCapsuleBatch = narrowPhaseInput.getCapsuleVsCapsuleBatch();
NarrowPhaseInfoBatch& sphereVsConvexPolyhedronBatch = narrowPhaseInput.getSphereVsConvexPolyhedronBatch();
NarrowPhaseInfoBatch& capsuleVsConvexPolyhedronBatch = narrowPhaseInput.getCapsuleVsConvexPolyhedronBatch();
NarrowPhaseInfoBatch& convexPolyhedronVsConvexPolyhedronBatch = narrowPhaseInput.getConvexPolyhedronVsConvexPolyhedronBatch();
// Process the potential contacts
processPotentialContacts(sphereVsSphereBatch, updateLastFrameInfo, potentialContactPoints, potentialContactManifolds, mapPairIdToContactPairIndex, contactPairs);
processPotentialContacts(sphereVsCapsuleBatch, updateLastFrameInfo, potentialContactPoints, potentialContactManifolds, mapPairIdToContactPairIndex, contactPairs);
processPotentialContacts(capsuleVsCapsuleBatch, updateLastFrameInfo, potentialContactPoints, potentialContactManifolds, mapPairIdToContactPairIndex, contactPairs);
processPotentialContacts(sphereVsConvexPolyhedronBatch, updateLastFrameInfo, potentialContactPoints, potentialContactManifolds, mapPairIdToContactPairIndex, contactPairs);
processPotentialContacts(capsuleVsConvexPolyhedronBatch, updateLastFrameInfo, potentialContactPoints, potentialContactManifolds, mapPairIdToContactPairIndex, contactPairs);
processPotentialContacts(convexPolyhedronVsConvexPolyhedronBatch, updateLastFrameInfo, potentialContactPoints,
potentialContactManifolds, mapPairIdToContactPairIndex, contactPairs);
}
// Compute the narrow-phase collision detection
void CollisionDetectionSystem::computeNarrowPhase() {
RP3D_PROFILE("CollisionDetectionSystem::computeNarrowPhase()", mProfiler);
MemoryAllocator& allocator = mMemoryManager.getSingleFrameAllocator();
// Swap the previous and current contacts arrays
swapPreviousAndCurrentContacts();
mPotentialContactManifolds.reserve(mNbPreviousPotentialContactManifolds);
mPotentialContactPoints.reserve(mNbPreviousPotentialContactPoints);
// Test the narrow-phase collision detection on the batches to be tested
testNarrowPhaseCollision(mNarrowPhaseInput, true, allocator);
// Process all the potential contacts after narrow-phase collision
processAllPotentialContacts(mNarrowPhaseInput, true, mPotentialContactPoints,
mPotentialContactManifolds, mCurrentContactPairs);
// Reduce the number of contact points in the manifolds
reducePotentialContactManifolds(mCurrentContactPairs, mPotentialContactManifolds, mPotentialContactPoints);
// Add the contact pairs to the bodies
addContactPairsToBodies();
assert(mCurrentContactManifolds->size() == 0);
assert(mCurrentContactPoints->size() == 0);
}
// Add the contact pairs to the corresponding bodies
void CollisionDetectionSystem::addContactPairsToBodies() {
const uint32 nbContactPairs = mCurrentContactPairs->size();
for (uint32 p=0 ; p < nbContactPairs; p++) {
ContactPair& contactPair = (*mCurrentContactPairs)[p];
const bool isBody1Rigid = mRigidBodyComponents.hasComponent(contactPair.body1Entity);
const bool isBody2Rigid = mRigidBodyComponents.hasComponent(contactPair.body2Entity);
// Add the associated contact pair to both bodies of the pair (used to create islands later)
if (isBody1Rigid) {
mRigidBodyComponents.addContacPair(contactPair.body1Entity, p);
}
if (isBody2Rigid) {
mRigidBodyComponents.addContacPair(contactPair.body2Entity, p);
}
// If at least of body is a CollisionBody
if (!isBody1Rigid || !isBody2Rigid) {
// Add the pair index to the array of pairs with CollisionBody
mCollisionBodyContactPairsIndices.add(p);
}
}
}
// Compute the map from contact pairs ids to contact pair for the next frame
void CollisionDetectionSystem::computeMapPreviousContactPairs() {
mPreviousMapPairIdToContactPairIndex.clear();
const uint32 nbCurrentContactPairs = mCurrentContactPairs->size();
for (uint32 i=0; i < nbCurrentContactPairs; i++) {
mPreviousMapPairIdToContactPairIndex.add(Pair<uint64, uint>((*mCurrentContactPairs)[i].pairId, i));
}
}
// Compute the narrow-phase collision detection for the testOverlap() methods.
/// This method returns true if contacts are found.
bool CollisionDetectionSystem::computeNarrowPhaseOverlapSnapshot(NarrowPhaseInput& narrowPhaseInput, OverlapCallback* callback) {
RP3D_PROFILE("CollisionDetectionSystem::computeNarrowPhaseOverlapSnapshot()", mProfiler);
MemoryAllocator& allocator = mMemoryManager.getPoolAllocator();
// Test the narrow-phase collision detection on the batches to be tested
bool collisionFound = testNarrowPhaseCollision(narrowPhaseInput, false, allocator);
if (collisionFound && callback != nullptr) {
// Compute the overlapping colliders
Array<ContactPair> contactPairs(allocator);
Array<ContactPair> lostContactPairs(allocator); // Always empty in this case (snapshot)
computeOverlapSnapshotContactPairs(narrowPhaseInput, contactPairs);
// Report overlapping colliders
OverlapCallback::CallbackData callbackData(contactPairs, lostContactPairs, false, *mWorld);
(*callback).onOverlap(callbackData);
}
return collisionFound;
}
// Process the potential overlapping bodies for the testOverlap() methods
void CollisionDetectionSystem::computeOverlapSnapshotContactPairs(NarrowPhaseInput& narrowPhaseInput, Array<ContactPair>& contactPairs) const {
Set<uint64> setOverlapContactPairId(mMemoryManager.getHeapAllocator());
// get the narrow-phase batches to test for collision
NarrowPhaseInfoBatch& sphereVsSphereBatch = narrowPhaseInput.getSphereVsSphereBatch();
NarrowPhaseInfoBatch& sphereVsCapsuleBatch = narrowPhaseInput.getSphereVsCapsuleBatch();
NarrowPhaseInfoBatch& capsuleVsCapsuleBatch = narrowPhaseInput.getCapsuleVsCapsuleBatch();
NarrowPhaseInfoBatch& sphereVsConvexPolyhedronBatch = narrowPhaseInput.getSphereVsConvexPolyhedronBatch();
NarrowPhaseInfoBatch& capsuleVsConvexPolyhedronBatch = narrowPhaseInput.getCapsuleVsConvexPolyhedronBatch();
NarrowPhaseInfoBatch& convexPolyhedronVsConvexPolyhedronBatch = narrowPhaseInput.getConvexPolyhedronVsConvexPolyhedronBatch();
// Process the potential contacts
computeOverlapSnapshotContactPairs(sphereVsSphereBatch, contactPairs, setOverlapContactPairId);
computeOverlapSnapshotContactPairs(sphereVsCapsuleBatch, contactPairs, setOverlapContactPairId);
computeOverlapSnapshotContactPairs(capsuleVsCapsuleBatch, contactPairs, setOverlapContactPairId);
computeOverlapSnapshotContactPairs(sphereVsConvexPolyhedronBatch, contactPairs, setOverlapContactPairId);
computeOverlapSnapshotContactPairs(capsuleVsConvexPolyhedronBatch, contactPairs, setOverlapContactPairId);
computeOverlapSnapshotContactPairs(convexPolyhedronVsConvexPolyhedronBatch, contactPairs, setOverlapContactPairId);
}
// Notify that the overlapping pairs where a given collider is involved need to be tested for overlap
void CollisionDetectionSystem::notifyOverlappingPairsToTestOverlap(Collider* collider) {
// Get the overlapping pairs involved with this collider
Array<uint64>& overlappingPairs = mCollidersComponents.getOverlappingPairs(collider->getEntity());
const uint32 nbPairs = overlappingPairs.size();
for (uint32 i=0; i < nbPairs; i++) {
// Notify that the overlapping pair needs to be testbed for overlap
mOverlappingPairs.setNeedToTestOverlap(overlappingPairs[i], true);
}
}
// Convert the potential overlapping bodies for the testOverlap() methods
void CollisionDetectionSystem::computeOverlapSnapshotContactPairs(NarrowPhaseInfoBatch& narrowPhaseInfoBatch, Array<ContactPair>& contactPairs,
Set<uint64>& setOverlapContactPairId) const {
RP3D_PROFILE("CollisionDetectionSystem::computeSnapshotContactPairs()", mProfiler);
// For each narrow phase info object
for(uint i=0; i < narrowPhaseInfoBatch.getNbObjects(); i++) {
// If there is a collision
if (narrowPhaseInfoBatch.narrowPhaseInfos[i].isColliding) {
// If the contact pair does not already exist
if (!setOverlapContactPairId.contains(narrowPhaseInfoBatch.narrowPhaseInfos[i].overlappingPairId)) {
const Entity collider1Entity = narrowPhaseInfoBatch.narrowPhaseInfos[i].colliderEntity1;
const Entity collider2Entity = narrowPhaseInfoBatch.narrowPhaseInfos[i].colliderEntity2;
const uint32 collider1Index = mCollidersComponents.getEntityIndex(collider1Entity);
const uint32 collider2Index = mCollidersComponents.getEntityIndex(collider2Entity);
const Entity body1Entity = mCollidersComponents.mBodiesEntities[collider1Index];
const Entity body2Entity = mCollidersComponents.mBodiesEntities[collider2Index];
const bool isTrigger = mCollidersComponents.mIsTrigger[collider1Index] || mCollidersComponents.mIsTrigger[collider2Index];
// Create a new contact pair
ContactPair contactPair(narrowPhaseInfoBatch.narrowPhaseInfos[i].overlappingPairId, body1Entity, body2Entity, collider1Entity, collider2Entity, contactPairs.size(), isTrigger, false, mMemoryManager.getHeapAllocator());
contactPairs.add(contactPair);
setOverlapContactPairId.add(narrowPhaseInfoBatch.narrowPhaseInfos[i].overlappingPairId);
}
}
narrowPhaseInfoBatch.resetContactPoints(i);
}
}
// Compute the narrow-phase collision detection for the testCollision() methods.
// This method returns true if contacts are found.
bool CollisionDetectionSystem::computeNarrowPhaseCollisionSnapshot(NarrowPhaseInput& narrowPhaseInput, CollisionCallback& callback) {
RP3D_PROFILE("CollisionDetectionSystem::computeNarrowPhaseCollisionSnapshot()", mProfiler);
MemoryAllocator& allocator = mMemoryManager.getHeapAllocator();
// Test the narrow-phase collision detection on the batches to be tested
bool collisionFound = testNarrowPhaseCollision(narrowPhaseInput, false, allocator);
// If collision has been found, create contacts
if (collisionFound) {
Array<ContactPointInfo> potentialContactPoints(allocator);
Array<ContactManifoldInfo> potentialContactManifolds(allocator);
Array<ContactPair> contactPairs(allocator);
Array<ContactPair> lostContactPairs(allocator); // Not used during collision snapshots
Array<ContactManifold> contactManifolds(allocator);
Array<ContactPoint> contactPoints(allocator);
// Process all the potential contacts after narrow-phase collision
processAllPotentialContacts(narrowPhaseInput, true, potentialContactPoints, potentialContactManifolds, &contactPairs);
// Reduce the number of contact points in the manifolds
reducePotentialContactManifolds(&contactPairs, potentialContactManifolds, potentialContactPoints);
// Create the actual contact manifolds and contact points
createSnapshotContacts(contactPairs, contactManifolds, contactPoints, potentialContactManifolds, potentialContactPoints);
// Report the contacts to the user
reportContacts(callback, &contactPairs, &contactManifolds, &contactPoints, lostContactPairs);
}
return collisionFound;
}
// Swap the previous and current contacts arrays
void CollisionDetectionSystem::swapPreviousAndCurrentContacts() {
if (mPreviousContactPairs == &mContactPairs1) {
mPreviousContactPairs = &mContactPairs2;
mPreviousContactManifolds = &mContactManifolds2;
mPreviousContactPoints = &mContactPoints2;
mCurrentContactPairs = &mContactPairs1;
mCurrentContactManifolds = &mContactManifolds1;
mCurrentContactPoints = &mContactPoints1;
}
else {
mPreviousContactPairs = &mContactPairs1;
mPreviousContactManifolds = &mContactManifolds1;
mPreviousContactPoints = &mContactPoints1;
mCurrentContactPairs = &mContactPairs2;
mCurrentContactManifolds = &mContactManifolds2;
mCurrentContactPoints = &mContactPoints2;
}
}
// Create the actual contact manifolds and contacts points
void CollisionDetectionSystem::createContacts() {
RP3D_PROFILE("CollisionDetectionSystem::createContacts()", mProfiler);
mCurrentContactManifolds->reserve(mCurrentContactPairs->size());
mCurrentContactPoints->reserve(mCurrentContactManifolds->size());
// We go through all the contact pairs and add the pairs with a least a CollisionBody at the end of the
// mProcessContactPairsOrderIslands array because those pairs have not been added during the islands
// creation (only the pairs with two RigidBodies are added during island creation)
mWorld->mProcessContactPairsOrderIslands.addRange(mCollisionBodyContactPairsIndices);
assert(mWorld->mProcessContactPairsOrderIslands.size() == (*mCurrentContactPairs).size());
// Process the contact pairs in the order defined by the islands such that the contact manifolds and
// contact points of a given island are packed together in the array of manifolds and contact points
const uint32 nbContactPairsToProcess = mWorld->mProcessContactPairsOrderIslands.size();
for (uint p=0; p < nbContactPairsToProcess; p++) {
uint32 contactPairIndex = mWorld->mProcessContactPairsOrderIslands[p];
ContactPair& contactPair = (*mCurrentContactPairs)[contactPairIndex];
contactPair.contactManifoldsIndex = mCurrentContactManifolds->size();
contactPair.nbContactManifolds = contactPair.potentialContactManifoldsIndices.size();
contactPair.contactPointsIndex = mCurrentContactPoints->size();
// For each potential contact manifold of the pair
for (uint32 m=0; m < contactPair.nbContactManifolds; m++) {
ContactManifoldInfo& potentialManifold = mPotentialContactManifolds[contactPair.potentialContactManifoldsIndices[m]];
// Start index and number of contact points for this manifold
const uint32 contactPointsIndex = mCurrentContactPoints->size();
const uint32 nbContactPoints = static_cast<uint32>(potentialManifold.potentialContactPointsIndices.size());
contactPair.nbToTalContactPoints += nbContactPoints;
// Create and add the contact manifold
mCurrentContactManifolds->emplace(contactPair.body1Entity, contactPair.body2Entity, contactPair.collider1Entity,
contactPair.collider2Entity, contactPointsIndex, nbContactPoints);
assert(potentialManifold.potentialContactPointsIndices.size() > 0);
// For each contact point of the manifold
for (uint c=0; c < nbContactPoints; c++) {
ContactPointInfo& potentialContactPoint = mPotentialContactPoints[potentialManifold.potentialContactPointsIndices[c]];
// Create and add the contact point
mCurrentContactPoints->emplace(potentialContactPoint, mWorld->mConfig.persistentContactDistanceThreshold);
}
}
}
// Initialize the current contacts with the contacts from the previous frame (for warmstarting)
initContactsWithPreviousOnes();
// Compute the lost contacts (contact pairs that were colliding in previous frame but not in this one)
computeLostContactPairs();
mPreviousContactPoints->clear();
mPreviousContactManifolds->clear();
mPreviousContactPairs->clear();
mNbPreviousPotentialContactManifolds = mPotentialContactManifolds.capacity();
mNbPreviousPotentialContactPoints = mPotentialContactPoints.capacity();
// Reset the potential contacts
mPotentialContactPoints.clear(true);
mPotentialContactManifolds.clear(true);
// Compute the map from contact pairs ids to contact pair for the next frame
computeMapPreviousContactPairs();
mCollisionBodyContactPairsIndices.clear(true);
mNarrowPhaseInput.clear();
}
// Compute the lost contact pairs (contact pairs in contact in the previous frame but not in the current one)
void CollisionDetectionSystem::computeLostContactPairs() {
// For each convex pair
const uint32 nbConvexPairs = mOverlappingPairs.mConvexPairs.size();
for (uint32 i=0; i < nbConvexPairs; i++) {
// If the two colliders of the pair were colliding in the previous frame but not in the current one
if (mOverlappingPairs.mConvexPairs[i].collidingInPreviousFrame && !mOverlappingPairs.mConvexPairs[i].collidingInCurrentFrame) {
// If both bodies still exist
if (mCollidersComponents.hasComponent(mOverlappingPairs.mConvexPairs[i].collider1) && mCollidersComponents.hasComponent(mOverlappingPairs.mConvexPairs[i].collider2)) {
// Create a lost contact pair
addLostContactPair(mOverlappingPairs.mConvexPairs[i]);
}
}
}
// For each convex pair
const uint32 nbConcavePairs = mOverlappingPairs.mConcavePairs.size();
for (uint32 i=0; i < nbConcavePairs; i++) {
// If the two colliders of the pair were colliding in the previous frame but not in the current one
if (mOverlappingPairs.mConcavePairs[i].collidingInPreviousFrame && !mOverlappingPairs.mConcavePairs[i].collidingInCurrentFrame) {
// If both bodies still exist
if (mCollidersComponents.hasComponent(mOverlappingPairs.mConcavePairs[i].collider1) && mCollidersComponents.hasComponent(mOverlappingPairs.mConcavePairs[i].collider2)) {
// Create a lost contact pair
addLostContactPair(mOverlappingPairs.mConcavePairs[i]);
}
}
}
}
// Create the actual contact manifolds and contacts points for testCollision() methods
void CollisionDetectionSystem::createSnapshotContacts(Array<ContactPair>& contactPairs,
Array<ContactManifold>& contactManifolds,
Array<ContactPoint>& contactPoints,
Array<ContactManifoldInfo>& potentialContactManifolds,
Array<ContactPointInfo>& potentialContactPoints) {
RP3D_PROFILE("CollisionDetectionSystem::createSnapshotContacts()", mProfiler);
contactManifolds.reserve(contactPairs.size());
contactPoints.reserve(contactManifolds.size());
// For each contact pair
const uint32 nbContactPairs = contactPairs.size();
for (uint32 p=0; p < nbContactPairs; p++) {
ContactPair& contactPair = contactPairs[p];
assert(contactPair.potentialContactManifoldsIndices.size() > 0);
contactPair.contactManifoldsIndex = contactManifolds.size();
contactPair.nbContactManifolds = contactPair.potentialContactManifoldsIndices.size();
contactPair.contactPointsIndex = contactPoints.size();
// For each potential contact manifold of the pair
for (uint32 m=0; m < contactPair.nbContactManifolds; m++) {
ContactManifoldInfo& potentialManifold = potentialContactManifolds[contactPair.potentialContactManifoldsIndices[m]];
// Start index and number of contact points for this manifold
const uint32 contactPointsIndex = contactPoints.size();
const uint32 nbContactPoints = static_cast<uint32>(potentialManifold.potentialContactPointsIndices.size());
contactPair.nbToTalContactPoints += nbContactPoints;
// Create and add the contact manifold
contactManifolds.emplace(contactPair.body1Entity, contactPair.body2Entity, contactPair.collider1Entity,
contactPair.collider2Entity, contactPointsIndex, nbContactPoints);
assert(nbContactPoints > 0);
// For each contact point of the manifold
for (uint32 c=0; c < nbContactPoints; c++) {
ContactPointInfo& potentialContactPoint = potentialContactPoints[potentialManifold.potentialContactPointsIndices[c]];
// Create a new contact point
ContactPoint contactPoint(potentialContactPoint, mWorld->mConfig.persistentContactDistanceThreshold);
// Add the contact point
contactPoints.add(contactPoint);
}
}
}
}
// Initialize the current contacts with the contacts from the previous frame (for warmstarting)
void CollisionDetectionSystem::initContactsWithPreviousOnes() {
const decimal persistentContactDistThresholdSqr = mWorld->mConfig.persistentContactDistanceThreshold * mWorld->mConfig.persistentContactDistanceThreshold;
// For each contact pair of the current frame
const uint32 nbCurrentContactPairs = mCurrentContactPairs->size();
for (uint32 i=0; i < nbCurrentContactPairs; i++) {
ContactPair& currentContactPair = (*mCurrentContactPairs)[i];
// Find the corresponding contact pair in the previous frame (if any)
auto itPrevContactPair = mPreviousMapPairIdToContactPairIndex.find(currentContactPair.pairId);
// If we have found a corresponding contact pair in the previous frame
if (itPrevContactPair != mPreviousMapPairIdToContactPairIndex.end()) {
const uint previousContactPairIndex = itPrevContactPair->second;
ContactPair& previousContactPair = (*mPreviousContactPairs)[previousContactPairIndex];
// --------------------- Contact Manifolds --------------------- //
const uint contactManifoldsIndex = currentContactPair.contactManifoldsIndex;
const uint nbContactManifolds = currentContactPair.nbContactManifolds;
// For each current contact manifold of the current contact pair
for (uint m=contactManifoldsIndex; m < contactManifoldsIndex + nbContactManifolds; m++) {
assert(m < mCurrentContactManifolds->size());
ContactManifold& currentContactManifold = (*mCurrentContactManifolds)[m];
assert(currentContactManifold.nbContactPoints > 0);
ContactPoint& currentContactPoint = (*mCurrentContactPoints)[currentContactManifold.contactPointsIndex];
const Vector3& currentContactPointNormal = currentContactPoint.getNormal();
// Find a similar contact manifold among the contact manifolds from the previous frame (for warmstarting)
const uint previousContactManifoldIndex = previousContactPair.contactManifoldsIndex;
const uint previousNbContactManifolds = previousContactPair.nbContactManifolds;
for (uint p=previousContactManifoldIndex; p < previousContactManifoldIndex + previousNbContactManifolds; p++) {
ContactManifold& previousContactManifold = (*mPreviousContactManifolds)[p];
assert(previousContactManifold.nbContactPoints > 0);
ContactPoint& previousContactPoint = (*mPreviousContactPoints)[previousContactManifold.contactPointsIndex];
// If the previous contact manifold has a similar contact normal with the current manifold
if (previousContactPoint.getNormal().dot(currentContactPointNormal) >= mWorld->mConfig.cosAngleSimilarContactManifold) {
// Transfer data from the previous contact manifold to the current one
currentContactManifold.frictionVector1 = previousContactManifold.frictionVector1;
currentContactManifold.frictionVector2 = previousContactManifold.frictionVector2;
currentContactManifold.frictionImpulse1 = previousContactManifold.frictionImpulse1;
currentContactManifold.frictionImpulse2 = previousContactManifold.frictionImpulse2;
currentContactManifold.frictionTwistImpulse = previousContactManifold.frictionTwistImpulse;
break;
}
}
}
// --------------------- Contact Points --------------------- //
const uint contactPointsIndex = currentContactPair.contactPointsIndex;
const uint nbTotalContactPoints = currentContactPair.nbToTalContactPoints;
// For each current contact point of the current contact pair
for (uint c=contactPointsIndex; c < contactPointsIndex + nbTotalContactPoints; c++) {
assert(c < mCurrentContactPoints->size());
ContactPoint& currentContactPoint = (*mCurrentContactPoints)[c];
const Vector3& currentContactPointLocalShape1 = currentContactPoint.getLocalPointOnShape1();
// Find a similar contact point among the contact points from the previous frame (for warmstarting)
const uint previousContactPointsIndex = previousContactPair.contactPointsIndex;
const uint previousNbContactPoints = previousContactPair.nbToTalContactPoints;
for (uint p=previousContactPointsIndex; p < previousContactPointsIndex + previousNbContactPoints; p++) {
const ContactPoint& previousContactPoint = (*mPreviousContactPoints)[p];
// If the previous contact point is very close to th current one
const decimal distSquare = (currentContactPointLocalShape1 - previousContactPoint.getLocalPointOnShape1()).lengthSquare();
if (distSquare <= persistentContactDistThresholdSqr) {
// Transfer data from the previous contact point to the current one
currentContactPoint.setPenetrationImpulse(previousContactPoint.getPenetrationImpulse());
currentContactPoint.setIsRestingContact(previousContactPoint.getIsRestingContact());
break;
}
}
}
}
}
}
// Remove a body from the collision detection
void CollisionDetectionSystem::removeCollider(Collider* collider) {
const int colliderBroadPhaseId = collider->getBroadPhaseId();
assert(colliderBroadPhaseId != -1);
assert(mMapBroadPhaseIdToColliderEntity.containsKey(colliderBroadPhaseId));
// Remove all the overlapping pairs involving this collider
Array<uint64>& overlappingPairs = mCollidersComponents.getOverlappingPairs(collider->getEntity());
while(overlappingPairs.size() > 0) {
// TODO : Remove all the contact manifold of the overlapping pair from the contact manifolds array of the two bodies involved
// Remove the overlapping pair
mOverlappingPairs.removePair(overlappingPairs[0]);
}
mMapBroadPhaseIdToColliderEntity.remove(colliderBroadPhaseId);
// Remove the body from the broad-phase
mBroadPhaseSystem.removeCollider(collider);
}
// Ray casting method
void CollisionDetectionSystem::raycast(RaycastCallback* raycastCallback, const Ray& ray, unsigned short raycastWithCategoryMaskBits) const {
RP3D_PROFILE("CollisionDetectionSystem::raycast()", mProfiler);
RaycastTest rayCastTest(raycastCallback);
// Ask the broad-phase algorithm to call the testRaycastAgainstShape()
// callback method for each collider hit by the ray in the broad-phase
mBroadPhaseSystem.raycast(ray, rayCastTest, raycastWithCategoryMaskBits);
}
// Convert the potential contact into actual contacts
void CollisionDetectionSystem::processPotentialContacts(NarrowPhaseInfoBatch& narrowPhaseInfoBatch, bool updateLastFrameInfo,
Array<ContactPointInfo>& potentialContactPoints,
Array<ContactManifoldInfo>& potentialContactManifolds,
Map<uint64, uint>& mapPairIdToContactPairIndex,
Array<ContactPair>* contactPairs) {
RP3D_PROFILE("CollisionDetectionSystem::processPotentialContacts()", mProfiler);
const uint nbObjects = narrowPhaseInfoBatch.getNbObjects();
if (updateLastFrameInfo) {
// For each narrow phase info object
for(uint i=0; i < nbObjects; i++) {
narrowPhaseInfoBatch.narrowPhaseInfos[i].lastFrameCollisionInfo->wasColliding = narrowPhaseInfoBatch.narrowPhaseInfos[i].isColliding;
// The previous frame collision info is now valid
narrowPhaseInfoBatch.narrowPhaseInfos[i].lastFrameCollisionInfo->isValid = true;
}
}
// For each narrow phase info object
for(uint i=0; i < nbObjects; i++) {
// If the two colliders are colliding
if (narrowPhaseInfoBatch.narrowPhaseInfos[i].isColliding) {
const uint64 pairId = narrowPhaseInfoBatch.narrowPhaseInfos[i].overlappingPairId;
OverlappingPairs::OverlappingPair* overlappingPair = mOverlappingPairs.getOverlappingPair(pairId);
assert(overlappingPair != nullptr);
overlappingPair->collidingInCurrentFrame = true;
const Entity collider1Entity = narrowPhaseInfoBatch.narrowPhaseInfos[i].colliderEntity1;
const Entity collider2Entity = narrowPhaseInfoBatch.narrowPhaseInfos[i].colliderEntity2;
const uint32 collider1Index = mCollidersComponents.getEntityIndex(collider1Entity);
const uint32 collider2Index = mCollidersComponents.getEntityIndex(collider2Entity);
const Entity body1Entity = mCollidersComponents.mBodiesEntities[collider1Index];
const Entity body2Entity = mCollidersComponents.mBodiesEntities[collider2Index];
// If we have a convex vs convex collision (if we consider the base collision shapes of the colliders)
if (mCollidersComponents.mCollisionShapes[collider1Index]->isConvex() && mCollidersComponents.mCollisionShapes[collider2Index]->isConvex()) {
// Create a new ContactPair
const bool isTrigger = mCollidersComponents.mIsTrigger[collider1Index] || mCollidersComponents.mIsTrigger[collider2Index];
assert(!mWorld->mCollisionBodyComponents.getIsEntityDisabled(body1Entity) || !mWorld->mCollisionBodyComponents.getIsEntityDisabled(body2Entity));
const uint32 newContactPairIndex = contactPairs->size();
contactPairs->emplace(pairId, body1Entity, body2Entity, collider1Entity, collider2Entity,
newContactPairIndex, overlappingPair->collidingInPreviousFrame, isTrigger, mMemoryManager.getHeapAllocator());
ContactPair* pairContact = &((*contactPairs)[newContactPairIndex]);
// Create a new potential contact manifold for the overlapping pair
uint32 contactManifoldIndex = static_cast<uint>(potentialContactManifolds.size());
potentialContactManifolds.emplace(pairId, mMemoryManager.getHeapAllocator());
ContactManifoldInfo& contactManifoldInfo = potentialContactManifolds[contactManifoldIndex];
const uint32 contactPointIndexStart = static_cast<uint>(potentialContactPoints.size());
// Add the potential contacts
for (uint j=0; j < narrowPhaseInfoBatch.narrowPhaseInfos[i].nbContactPoints; j++) {
// Add the contact point to the manifold
contactManifoldInfo.potentialContactPointsIndices.add(contactPointIndexStart + j);
// Add the contact point to the array of potential contact points
const ContactPointInfo& contactPoint = narrowPhaseInfoBatch.narrowPhaseInfos[i].contactPoints[j];
potentialContactPoints.add(contactPoint);
}
// Add the contact manifold to the overlapping pair contact
assert(pairId == contactManifoldInfo.pairId);
pairContact->potentialContactManifoldsIndices.add(contactManifoldIndex);
}
else {
// If there is not already a contact pair for this overlapping pair
auto it = mapPairIdToContactPairIndex.find(pairId);
ContactPair* pairContact = nullptr;
if (it == mapPairIdToContactPairIndex.end()) {
// Create a new ContactPair
const bool isTrigger = mCollidersComponents.mIsTrigger[collider1Index] || mCollidersComponents.mIsTrigger[collider2Index];
assert(!mWorld->mCollisionBodyComponents.getIsEntityDisabled(body1Entity) || !mWorld->mCollisionBodyComponents.getIsEntityDisabled(body2Entity));
const uint32 newContactPairIndex = contactPairs->size();
contactPairs->emplace(pairId, body1Entity, body2Entity, collider1Entity, collider2Entity,
newContactPairIndex, overlappingPair->collidingInPreviousFrame, isTrigger, mMemoryManager.getHeapAllocator());
pairContact = &((*contactPairs)[newContactPairIndex]);
mapPairIdToContactPairIndex.add(Pair<uint64, uint>(pairId, newContactPairIndex));
}
else { // If a ContactPair already exists for this overlapping pair, we use this one
assert(it->first == pairId);
const uint pairContactIndex = it->second;
pairContact = &((*contactPairs)[pairContactIndex]);
}
assert(pairContact != nullptr);
// Add the potential contacts
for (uint j=0; j < narrowPhaseInfoBatch.narrowPhaseInfos[i].nbContactPoints; j++) {
const ContactPointInfo& contactPoint = narrowPhaseInfoBatch.narrowPhaseInfos[i].contactPoints[j];
// Add the contact point to the array of potential contact points
const uint32 contactPointIndex = potentialContactPoints.size();
potentialContactPoints.add(contactPoint);
bool similarManifoldFound = false;
// For each contact manifold of the overlapping pair
const uint32 nbPotentialManifolds = pairContact->potentialContactManifoldsIndices.size();
for (uint m=0; m < nbPotentialManifolds; m++) {
uint contactManifoldIndex = pairContact->potentialContactManifoldsIndices[m];
// Get the first contact point of the current manifold
assert(potentialContactManifolds[contactManifoldIndex].potentialContactPointsIndices.size() > 0);
const uint manifoldContactPointIndex = potentialContactManifolds[contactManifoldIndex].potentialContactPointsIndices[0];
const ContactPointInfo& manifoldContactPoint = potentialContactPoints[manifoldContactPointIndex];
// If we have found a corresponding manifold for the new contact point
// (a manifold with a similar contact normal direction)
if (manifoldContactPoint.normal.dot(contactPoint.normal) >= mWorld->mConfig.cosAngleSimilarContactManifold) {
// Add the contact point to the manifold
potentialContactManifolds[contactManifoldIndex].potentialContactPointsIndices.add(contactPointIndex);
similarManifoldFound = true;
break;
}
}
// If we have not found a manifold with a similar contact normal for the contact point
if (!similarManifoldFound) {
// Create a new potential contact manifold for the overlapping pair
uint32 contactManifoldIndex = potentialContactManifolds.size();
potentialContactManifolds.emplace(pairId, mMemoryManager.getHeapAllocator());
ContactManifoldInfo& contactManifoldInfo = potentialContactManifolds[contactManifoldIndex];
// Add the contact point to the manifold
contactManifoldInfo.potentialContactPointsIndices.add(contactPointIndex);
assert(pairContact != nullptr);
// Add the contact manifold to the overlapping pair contact
assert(pairContact->pairId == contactManifoldInfo.pairId);
pairContact->potentialContactManifoldsIndices.add(contactManifoldIndex);
}
assert(pairContact->potentialContactManifoldsIndices.size() > 0);
}
}
narrowPhaseInfoBatch.resetContactPoints(i);
}
}
}
// Clear the obsolete manifolds and contact points and reduce the number of contacts points of the remaining manifolds
void CollisionDetectionSystem::reducePotentialContactManifolds(Array<ContactPair>* contactPairs,
Array<ContactManifoldInfo>& potentialContactManifolds,
const Array<ContactPointInfo>& potentialContactPoints) const {
RP3D_PROFILE("CollisionDetectionSystem::reducePotentialContactManifolds()", mProfiler);
// Reduce the number of potential contact manifolds in a contact pair
const uint32 nbContactPairs = contactPairs->size();
for (uint32 i=0; i < nbContactPairs; i++) {
ContactPair& contactPair = (*contactPairs)[i];
// While there are too many manifolds in the contact pair
while(contactPair.potentialContactManifoldsIndices.size() > NB_MAX_CONTACT_MANIFOLDS) {
// Look for a manifold with the smallest contact penetration depth.
decimal minDepth = DECIMAL_LARGEST;
int minDepthManifoldIndex = -1;
for (uint32 j=0; j < contactPair.potentialContactManifoldsIndices.size(); j++) {
ContactManifoldInfo& manifold = potentialContactManifolds[contactPair.potentialContactManifoldsIndices[j]];
// Get the largest contact point penetration depth of the manifold
const decimal depth = computePotentialManifoldLargestContactDepth(manifold, potentialContactPoints);
if (depth < minDepth) {
minDepth = depth;
minDepthManifoldIndex = static_cast<int>(j);
}
}
// Remove the non optimal manifold
assert(minDepthManifoldIndex >= 0);
contactPair.removePotentialManifoldAtIndex(minDepthManifoldIndex);
}
}
// Reduce the number of potential contact points in the manifolds
for (uint32 i=0; i < nbContactPairs; i++) {
const ContactPair& pairContact = (*contactPairs)[i];
// For each potential contact manifold
for (uint32 j=0; j < pairContact.potentialContactManifoldsIndices.size(); j++) {
ContactManifoldInfo& manifold = potentialContactManifolds[pairContact.potentialContactManifoldsIndices[j]];
// If there are two many contact points in the manifold
if (manifold.potentialContactPointsIndices.size() > MAX_CONTACT_POINTS_IN_MANIFOLD) {
Transform shape1LocalToWorldTransoform = mCollidersComponents.getLocalToWorldTransform(pairContact.collider1Entity);
// Reduce the number of contact points in the manifold
reduceContactPoints(manifold, shape1LocalToWorldTransoform, potentialContactPoints);
}
assert(manifold.potentialContactPointsIndices.size() <= MAX_CONTACT_POINTS_IN_MANIFOLD);
// Remove the duplicated contact points in the manifold (if any)
removeDuplicatedContactPointsInManifold(manifold, potentialContactPoints);
}
}
}
// Return the largest depth of all the contact points of a potential manifold
decimal CollisionDetectionSystem::computePotentialManifoldLargestContactDepth(const ContactManifoldInfo& manifold,
const Array<ContactPointInfo>& potentialContactPoints) const {
decimal largestDepth = 0.0f;
const uint32 nbContactPoints = static_cast<uint32>(manifold.potentialContactPointsIndices.size());
assert(nbContactPoints > 0);
for (uint32 i=0; i < nbContactPoints; i++) {
decimal depth = potentialContactPoints[manifold.potentialContactPointsIndices[i]].penetrationDepth;
if (depth > largestDepth) {
largestDepth = depth;
}
}
return largestDepth;
}
// Reduce the number of contact points of a potential contact manifold
// This is based on the technique described by Dirk Gregorius in his
// "Contacts Creation" GDC presentation. This method will reduce the number of
// contact points to a maximum of 4 points (but it can be less).
void CollisionDetectionSystem::reduceContactPoints(ContactManifoldInfo& manifold, const Transform& shape1ToWorldTransform,
const Array<ContactPointInfo>& potentialContactPoints) const {
assert(manifold.potentialContactPointsIndices.size() > MAX_CONTACT_POINTS_IN_MANIFOLD);
// The following algorithm only works to reduce to a maximum of 4 contact points
assert(MAX_CONTACT_POINTS_IN_MANIFOLD == 4);
// Array of the candidate contact points indices in the manifold. Every time that we have found a
// point we want to keep, we will remove it from this array
Array<uint> candidatePointsIndices(manifold.potentialContactPointsIndices);
assert(manifold.potentialContactPointsIndices.size() == candidatePointsIndices.size());
int8 nbReducedPoints = 0;
uint pointsToKeepIndices[MAX_CONTACT_POINTS_IN_MANIFOLD];
for (int8 i=0; i<MAX_CONTACT_POINTS_IN_MANIFOLD; i++) {
pointsToKeepIndices[i] = 0;
}
// Compute the initial contact point we need to keep.
// The first point we keep is always the point in a given
// constant direction (in order to always have same contact points
// between frames for better stability)
const Transform worldToShape1Transform = shape1ToWorldTransform.getInverse();
// Compute the contact normal of the manifold (we use the first contact point)
// in the local-space of the first collision shape
const Vector3 contactNormalShape1Space = worldToShape1Transform.getOrientation() * potentialContactPoints[candidatePointsIndices[0]].normal;
// Compute a search direction
const Vector3 searchDirection(1, 1, 1);
decimal maxDotProduct = DECIMAL_SMALLEST;
uint elementIndexToKeep = 0;
for (uint i=0; i < candidatePointsIndices.size(); i++) {
const ContactPointInfo& element = potentialContactPoints[candidatePointsIndices[i]];
decimal dotProduct = searchDirection.dot(element.localPoint1);
if (dotProduct > maxDotProduct) {
maxDotProduct = dotProduct;
elementIndexToKeep = i;
nbReducedPoints = 1;
}
}
pointsToKeepIndices[0] = candidatePointsIndices[elementIndexToKeep];
removeItemAtInArray(candidatePointsIndices, elementIndexToKeep);
//candidatePointsIndices.removeAt(elementIndexToKeep);
assert(nbReducedPoints == 1);
// Compute the second contact point we need to keep.
// The second point we keep is the one farthest away from the first point.
decimal maxDistance = decimal(0.0);
elementIndexToKeep = 0;
for (uint i=0; i < candidatePointsIndices.size(); i++) {
const ContactPointInfo& element = potentialContactPoints[candidatePointsIndices[i]];
const ContactPointInfo& pointToKeep0 = potentialContactPoints[pointsToKeepIndices[0]];
assert(candidatePointsIndices[i] != pointsToKeepIndices[0]);
const decimal distance = (pointToKeep0.localPoint1 - element.localPoint1).lengthSquare();
if (distance >= maxDistance) {
maxDistance = distance;
elementIndexToKeep = i;
nbReducedPoints = 2;
}
}
pointsToKeepIndices[1] = candidatePointsIndices[elementIndexToKeep];
removeItemAtInArray(candidatePointsIndices, elementIndexToKeep);
assert(nbReducedPoints == 2);
// Compute the third contact point we need to keep.
// The third point is the one producing the triangle with the larger area
// with first and second point.
// We compute the most positive or most negative triangle area (depending on winding)
uint thirdPointMaxAreaIndex = 0;
uint thirdPointMinAreaIndex = 0;
decimal minArea = decimal(0.0);
decimal maxArea = decimal(0.0);
bool isPreviousAreaPositive = true;
for (uint i=0; i < candidatePointsIndices.size(); i++) {
const ContactPointInfo& element = potentialContactPoints[candidatePointsIndices[i]];
const ContactPointInfo& pointToKeep0 = potentialContactPoints[pointsToKeepIndices[0]];
const ContactPointInfo& pointToKeep1 = potentialContactPoints[pointsToKeepIndices[1]];
assert(candidatePointsIndices[i] != pointsToKeepIndices[0]);
assert(candidatePointsIndices[i] != pointsToKeepIndices[1]);
const Vector3 newToFirst = pointToKeep0.localPoint1 - element.localPoint1;
const Vector3 newToSecond = pointToKeep1.localPoint1 - element.localPoint1;
// Compute the triangle area
decimal area = newToFirst.cross(newToSecond).dot(contactNormalShape1Space);
if (area >= maxArea) {
maxArea = area;
thirdPointMaxAreaIndex = i;
}
if (area <= minArea) {
minArea = area;
thirdPointMinAreaIndex = i;
}
}
assert(minArea <= decimal(0.0));
assert(maxArea >= decimal(0.0));
if (maxArea > (-minArea)) {
isPreviousAreaPositive = true;
pointsToKeepIndices[2] = candidatePointsIndices[thirdPointMaxAreaIndex];
removeItemAtInArray(candidatePointsIndices, thirdPointMaxAreaIndex);
}
else {
isPreviousAreaPositive = false;
pointsToKeepIndices[2] = candidatePointsIndices[thirdPointMinAreaIndex];
removeItemAtInArray(candidatePointsIndices, thirdPointMinAreaIndex);
}
nbReducedPoints = 3;
// Compute the 4th point by choosing the triangle that adds the most
// triangle area to the previous triangle and has opposite sign area (opposite winding)
decimal largestArea = decimal(0.0); // Largest area (positive or negative)
elementIndexToKeep = 0;
nbReducedPoints = 4;
decimal area;
// For each remaining candidate points
for (uint i=0; i < candidatePointsIndices.size(); i++) {
const ContactPointInfo& element = potentialContactPoints[candidatePointsIndices[i]];
assert(candidatePointsIndices[i] != pointsToKeepIndices[0]);
assert(candidatePointsIndices[i] != pointsToKeepIndices[1]);
assert(candidatePointsIndices[i] != pointsToKeepIndices[2]);
// For each edge of the triangle made by the first three points
for (uint j=0; j<3; j++) {
uint edgeVertex1Index = j;
uint edgeVertex2Index = j < 2 ? j + 1 : 0;
const ContactPointInfo& pointToKeepEdgeV1 = potentialContactPoints[pointsToKeepIndices[edgeVertex1Index]];
const ContactPointInfo& pointToKeepEdgeV2 = potentialContactPoints[pointsToKeepIndices[edgeVertex2Index]];
const Vector3 newToFirst = pointToKeepEdgeV1.localPoint1 - element.localPoint1;
const Vector3 newToSecond = pointToKeepEdgeV2.localPoint1 - element.localPoint1;
// Compute the triangle area
area = newToFirst.cross(newToSecond).dot(contactNormalShape1Space);
// We are looking at the triangle with maximal area (positive or negative).
// If the previous area is positive, we are looking at negative area now.
// If the previous area is negative, we are looking at the positive area now.
if (isPreviousAreaPositive && area <= largestArea) {
largestArea = area;
elementIndexToKeep = i;
}
else if (!isPreviousAreaPositive && area >= largestArea) {
largestArea = area;
elementIndexToKeep = i;
}
}
}
pointsToKeepIndices[3] = candidatePointsIndices[elementIndexToKeep];
removeItemAtInArray(candidatePointsIndices, elementIndexToKeep);
// Only keep the four selected contact points in the manifold
manifold.potentialContactPointsIndices.clear();
manifold.potentialContactPointsIndices.add(pointsToKeepIndices[0]);
manifold.potentialContactPointsIndices.add(pointsToKeepIndices[1]);
manifold.potentialContactPointsIndices.add(pointsToKeepIndices[2]);
manifold.potentialContactPointsIndices.add(pointsToKeepIndices[3]);
}
// Remove the duplicated contact points in a given contact manifold
void CollisionDetectionSystem::removeDuplicatedContactPointsInManifold(ContactManifoldInfo& manifold,
const Array<ContactPointInfo>& potentialContactPoints) const {
RP3D_PROFILE("CollisionDetectionSystem::removeDuplicatedContactPointsInManifold()", mProfiler);
const decimal distThresholdSqr = SAME_CONTACT_POINT_DISTANCE_THRESHOLD * SAME_CONTACT_POINT_DISTANCE_THRESHOLD;
// For each contact point of the manifold
for (uint32 i=0; i < manifold.potentialContactPointsIndices.size(); i++) {
for (uint32 j=i+1; j < manifold.potentialContactPointsIndices.size(); j++) {
const ContactPointInfo& point1 = potentialContactPoints[manifold.potentialContactPointsIndices[i]];
const ContactPointInfo& point2 = potentialContactPoints[manifold.potentialContactPointsIndices[j]];
// Compute the distance between the two contact points
const decimal distSqr = (point2.localPoint1 - point1.localPoint1).lengthSquare();
// We have a found a duplicated contact point
if (distSqr < distThresholdSqr) {
// Remove the duplicated contact point
manifold.potentialContactPointsIndices.removeAtAndReplaceByLast(j);
j--;
}
}
}
}
// Remove an element in an array (and replace it by the last one in the array)
void CollisionDetectionSystem::removeItemAtInArray(Array<uint>& array, uint32 index) const {
assert(index < array.size());
assert(array.size() > 0);
array.removeAtAndReplaceByLast(index);
}
// Report contacts and triggers
void CollisionDetectionSystem::reportContactsAndTriggers() {
// Report contacts and triggers to the user
if (mWorld->mEventListener != nullptr) {
reportContacts(*(mWorld->mEventListener), mCurrentContactPairs, mCurrentContactManifolds, mCurrentContactPoints, mLostContactPairs);
reportTriggers(*(mWorld->mEventListener), mCurrentContactPairs, mLostContactPairs);
}
// Report contacts for debug rendering (if enabled)
if (mWorld->mIsDebugRenderingEnabled) {
reportDebugRenderingContacts(mCurrentContactPairs, mCurrentContactManifolds, mCurrentContactPoints, mLostContactPairs);
}
mOverlappingPairs.updateCollidingInPreviousFrame();
mLostContactPairs.clear(true);
}
// Report all contacts to the user
void CollisionDetectionSystem::reportContacts(CollisionCallback& callback, Array<ContactPair>* contactPairs,
Array<ContactManifold>* manifolds, Array<ContactPoint>* contactPoints, Array<ContactPair>& lostContactPairs) {
RP3D_PROFILE("CollisionDetectionSystem::reportContacts()", mProfiler);
// If there are contacts
if (contactPairs->size() + lostContactPairs.size() > 0) {
CollisionCallback::CallbackData callbackData(contactPairs, manifolds, contactPoints, lostContactPairs, *mWorld);
// Call the callback method to report the contacts
callback.onContact(callbackData);
}
}
// Report all triggers to the user
void CollisionDetectionSystem::reportTriggers(EventListener& eventListener, Array<ContactPair>* contactPairs, Array<ContactPair>& lostContactPairs) {
RP3D_PROFILE("CollisionDetectionSystem::reportTriggers()", mProfiler);
// If there are contacts
if (contactPairs->size() + lostContactPairs.size() > 0) {
OverlapCallback::CallbackData callbackData(*contactPairs, lostContactPairs, true, *mWorld);
// Call the callback method to report the overlapping shapes
eventListener.onTrigger(callbackData);
}
}
// Report all contacts for debug rendering
void CollisionDetectionSystem::reportDebugRenderingContacts(Array<ContactPair>* contactPairs, Array<ContactManifold>* manifolds, Array<ContactPoint>* contactPoints, Array<ContactPair>& lostContactPairs) {
RP3D_PROFILE("CollisionDetectionSystem::reportDebugRenderingContacts()", mProfiler);
// If there are contacts
if (contactPairs->size() + lostContactPairs.size() > 0) {
CollisionCallback::CallbackData callbackData(contactPairs, manifolds, contactPoints, lostContactPairs, *mWorld);
// Call the callback method to report the contacts
mWorld->mDebugRenderer.onContact(callbackData);
}
}
// Return true if two bodies overlap (collide)
bool CollisionDetectionSystem::testOverlap(CollisionBody* body1, CollisionBody* body2) {
NarrowPhaseInput narrowPhaseInput(mMemoryManager.getPoolAllocator(), mOverlappingPairs);
// Compute the broad-phase collision detection
computeBroadPhase();
// Filter the overlapping pairs to get only the ones with the selected body involved
Array<uint64> convexPairs(mMemoryManager.getPoolAllocator());
Array<uint64> concavePairs(mMemoryManager.getPoolAllocator());
filterOverlappingPairs(body1->getEntity(), body2->getEntity(), convexPairs, concavePairs);
if (convexPairs.size() > 0 || concavePairs.size() > 0) {
// Compute the middle-phase collision detection
computeMiddlePhaseCollisionSnapshot(convexPairs, concavePairs, narrowPhaseInput, false);
// Compute the narrow-phase collision detection
return computeNarrowPhaseOverlapSnapshot(narrowPhaseInput, nullptr);
}
return false;
}
// Report all the bodies that overlap (collide) in the world
void CollisionDetectionSystem::testOverlap(OverlapCallback& callback) {
NarrowPhaseInput narrowPhaseInput(mMemoryManager.getPoolAllocator(), mOverlappingPairs);
// Compute the broad-phase collision detection
computeBroadPhase();
// Compute the middle-phase collision detection
computeMiddlePhase(narrowPhaseInput, false);
// Compute the narrow-phase collision detection and report overlapping shapes
computeNarrowPhaseOverlapSnapshot(narrowPhaseInput, &callback);
}
// Report all the bodies that overlap (collide) with the body in parameter
void CollisionDetectionSystem::testOverlap(CollisionBody* body, OverlapCallback& callback) {
NarrowPhaseInput narrowPhaseInput(mMemoryManager.getPoolAllocator(), mOverlappingPairs);
// Compute the broad-phase collision detection
computeBroadPhase();
// Filter the overlapping pairs to get only the ones with the selected body involved
Array<uint64> convexPairs(mMemoryManager.getPoolAllocator());
Array<uint64> concavePairs(mMemoryManager.getPoolAllocator());
filterOverlappingPairs(body->getEntity(), convexPairs, concavePairs);
if (convexPairs.size() > 0 || concavePairs.size() > 0) {
// Compute the middle-phase collision detection
computeMiddlePhaseCollisionSnapshot(convexPairs, concavePairs, narrowPhaseInput, false);
// Compute the narrow-phase collision detection
computeNarrowPhaseOverlapSnapshot(narrowPhaseInput, &callback);
}
}
// Test collision and report contacts between two bodies.
void CollisionDetectionSystem::testCollision(CollisionBody* body1, CollisionBody* body2, CollisionCallback& callback) {
NarrowPhaseInput narrowPhaseInput(mMemoryManager.getPoolAllocator(), mOverlappingPairs);
// Compute the broad-phase collision detection
computeBroadPhase();
// Filter the overlapping pairs to get only the ones with the selected body involved
Array<uint64> convexPairs(mMemoryManager.getPoolAllocator());
Array<uint64> concavePairs(mMemoryManager.getPoolAllocator());
filterOverlappingPairs(body1->getEntity(), body2->getEntity(), convexPairs, concavePairs);
if (convexPairs.size() > 0 || concavePairs.size() > 0) {
// Compute the middle-phase collision detection
computeMiddlePhaseCollisionSnapshot(convexPairs, concavePairs, narrowPhaseInput, true);
// Compute the narrow-phase collision detection and report contacts
computeNarrowPhaseCollisionSnapshot(narrowPhaseInput, callback);
}
}
// Test collision and report all the contacts involving the body in parameter
void CollisionDetectionSystem::testCollision(CollisionBody* body, CollisionCallback& callback) {
NarrowPhaseInput narrowPhaseInput(mMemoryManager.getPoolAllocator(), mOverlappingPairs);
// Compute the broad-phase collision detection
computeBroadPhase();
// Filter the overlapping pairs to get only the ones with the selected body involved
Array<uint64> convexPairs(mMemoryManager.getPoolAllocator());
Array<uint64> concavePairs(mMemoryManager.getPoolAllocator());
filterOverlappingPairs(body->getEntity(), convexPairs, concavePairs);
if (convexPairs.size() > 0 || concavePairs.size() > 0) {
// Compute the middle-phase collision detection
computeMiddlePhaseCollisionSnapshot(convexPairs, concavePairs, narrowPhaseInput, true);
// Compute the narrow-phase collision detection and report contacts
computeNarrowPhaseCollisionSnapshot(narrowPhaseInput, callback);
}
}
// Test collision and report contacts between each colliding bodies in the world
void CollisionDetectionSystem::testCollision(CollisionCallback& callback) {
NarrowPhaseInput narrowPhaseInput(mMemoryManager.getPoolAllocator(), mOverlappingPairs);
// Compute the broad-phase collision detection
computeBroadPhase();
// Compute the middle-phase collision detection
computeMiddlePhase(narrowPhaseInput, true);
// Compute the narrow-phase collision detection and report contacts
computeNarrowPhaseCollisionSnapshot(narrowPhaseInput, callback);
}
// Filter the overlapping pairs to keep only the pairs where a given body is involved
void CollisionDetectionSystem::filterOverlappingPairs(Entity bodyEntity, Array<uint64>& convexPairs, Array<uint64>& concavePairs) const {
// For each convex pairs
const uint32 nbConvexPairs = mOverlappingPairs.mConvexPairs.size();
for (uint32 i=0; i < nbConvexPairs; i++) {
if (mCollidersComponents.getBody(mOverlappingPairs.mConvexPairs[i].collider1) == bodyEntity ||
mCollidersComponents.getBody(mOverlappingPairs.mConvexPairs[i].collider2) == bodyEntity) {
convexPairs.add(mOverlappingPairs.mConvexPairs[i].pairID);
}
}
// For each concave pairs
const uint32 nbConcavePairs = mOverlappingPairs.mConcavePairs.size();
for (uint32 i=0; i < nbConcavePairs; i++) {
if (mCollidersComponents.getBody(mOverlappingPairs.mConcavePairs[i].collider1) == bodyEntity ||
mCollidersComponents.getBody(mOverlappingPairs.mConcavePairs[i].collider2) == bodyEntity) {
concavePairs.add(mOverlappingPairs.mConcavePairs[i].pairID);
}
}
}
// Filter the overlapping pairs to keep only the pairs where two given bodies are involved
void CollisionDetectionSystem::filterOverlappingPairs(Entity body1Entity, Entity body2Entity, Array<uint64>& convexPairs, Array<uint64>& concavePairs) const {
// For each convex pair
const uint32 nbConvexPairs = mOverlappingPairs.mConvexPairs.size();
for (uint32 i=0; i < nbConvexPairs; i++) {
const Entity collider1Body = mCollidersComponents.getBody(mOverlappingPairs.mConvexPairs[i].collider1);
const Entity collider2Body = mCollidersComponents.getBody(mOverlappingPairs.mConvexPairs[i].collider2);
if ((collider1Body == body1Entity && collider2Body == body2Entity) ||
(collider1Body == body2Entity && collider2Body == body1Entity)) {
convexPairs.add(mOverlappingPairs.mConvexPairs[i].pairID);
}
}
// For each concave pair
const uint nbConcavePairs = mOverlappingPairs.mConcavePairs.size();
for (uint i=0; i < nbConcavePairs; i++) {
const Entity collider1Body = mCollidersComponents.getBody(mOverlappingPairs.mConcavePairs[i].collider1);
const Entity collider2Body = mCollidersComponents.getBody(mOverlappingPairs.mConcavePairs[i].collider2);
if ((collider1Body == body1Entity && collider2Body == body2Entity) ||
(collider1Body == body2Entity && collider2Body == body1Entity)) {
concavePairs.add(mOverlappingPairs.mConcavePairs[i].pairID);
}
}
}
// Return the world event listener
EventListener* CollisionDetectionSystem::getWorldEventListener() {
return mWorld->mEventListener;
}
// Return the world-space AABB of a given collider
const AABB CollisionDetectionSystem::getWorldAABB(const Collider* collider) const {
assert(collider->getBroadPhaseId() > -1);
return mBroadPhaseSystem.getFatAABB(collider->getBroadPhaseId());
}
| 50.535522 | 234 | 0.70712 | VaderY |
4058914fa3ce8fe6ccb306ca35396bf2dcd5a009 | 253 | cpp | C++ | imposc-service/imposc-cpp/main.cpp | FelixDux/imposccpp | c8c612df87a53ddaca6260816c913ade44adbe6d | [
"MIT"
] | null | null | null | imposc-service/imposc-cpp/main.cpp | FelixDux/imposccpp | c8c612df87a53ddaca6260816c913ade44adbe6d | [
"MIT"
] | 1 | 2021-03-22T17:27:17.000Z | 2021-07-02T07:31:39.000Z | imposc-service/imposc-cpp/main.cpp | FelixDux/imposccpp | c8c612df87a53ddaca6260816c913ade44adbe6d | [
"MIT"
] | null | null | null | #include "imposcpy.hpp"
#include <iostream>
int main(int argc, char** argv)
{
// map_impacts(5.2, 0.8, -0.63, 100, 0.5, 2, 4000, "impact-map.png", "errors.txt");
map_doa(5.2, 0.8, -0.63, 100, 4, 10, 10, 1000, "doa.png", "errors.txt");
return 0;
}
| 21.083333 | 84 | 0.600791 | FelixDux |
40645b9aa78cb739fe57666415c51357c04c2105 | 8,282 | cpp | C++ | src/aadcUser/BirdsEyeTransform/BirdsEyeTransform.cpp | kimsoohwan/Cariosity2018 | 49f935623c41d627b45c47a219358f9d7d207fdf | [
"BSD-4-Clause"
] | null | null | null | src/aadcUser/BirdsEyeTransform/BirdsEyeTransform.cpp | kimsoohwan/Cariosity2018 | 49f935623c41d627b45c47a219358f9d7d207fdf | [
"BSD-4-Clause"
] | null | null | null | src/aadcUser/BirdsEyeTransform/BirdsEyeTransform.cpp | kimsoohwan/Cariosity2018 | 49f935623c41d627b45c47a219358f9d7d207fdf | [
"BSD-4-Clause"
] | 1 | 2019-10-03T12:23:26.000Z | 2019-10-03T12:23:26.000Z | #include "stdafx.h"
#include "BirdsEyeTransform.h"
#include "ADTF3_OpenCV_helper.h"
#include <opencv/cv.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/cudaarithm.hpp>
#include <opencv2/core/cuda.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/cudaimgproc.hpp>
/// This defines a data triggered filter and exposes it via a plugin class factory.
/// The Triggerfunction cSimpleDataStatistics will be embedded to the Filter
/// and called repeatedly (last parameter of this macro)!
ADTF_TRIGGER_FUNCTION_FILTER_PLUGIN(CID_CARIOSITY_DATA_TRIGGERED_FILTER,
"Birds Eye Transform",
fcBirdsEyeTransform,
adtf::filter::pin_trigger({ "in" }));
fcBirdsEyeTransform::fcBirdsEyeTransform() {
//Register Properties
RegisterPropertyVariable("ROIOffsetX [%]", m_ROIOffsetX);
RegisterPropertyVariable("ROIOffsetY [%]", m_ROIOffsetY);
RegisterPropertyVariable("ROIWidth [%]", m_ROIWidth);
RegisterPropertyVariable("ROIHeight [%]", m_ROIHeight);
RegisterPropertyVariable("Output Height [Pixel]", m_OutputHeight);
RegisterPropertyVariable("side inset at top [%]", m_topSideInset);
RegisterPropertyVariable("side inset at bottom [%]", m_bottomSideInset);
RegisterPropertyVariable("Show ROI, no transform", m_showROIDebug);
//create and set inital input format type
m_InPinVideoFormat.m_strFormatName = ADTF_IMAGE_FORMAT(RGB_24);
adtf::ucom::object_ptr<IStreamType> pTypeInput = adtf::ucom::make_object_ptr<cStreamType>(stream_meta_type_image());
set_stream_type_image_format(*pTypeInput, m_InPinVideoFormat);
//Register input pin
Register(m_oReaderVideo, "in", pTypeInput);
//Register output pins
adtf::ucom::object_ptr<IStreamType> pTypeOutput = adtf::ucom::make_object_ptr<cStreamType>(stream_meta_type_image());
set_stream_type_image_format(*pTypeOutput, m_OutPinVideoFormat);
Register(m_oWriterVideo, "out", pTypeOutput);
//register callback for type changes
m_oReaderVideo.SetAcceptTypeCallback([this](const adtf::ucom::ant::iobject_ptr<const adtf::streaming::ant::IStreamType>& pType) -> tResult
{
return ChangeType(m_oReaderVideo, *pType.Get());
});
}
tResult fcBirdsEyeTransform::Configure()
{
//get clock object
RETURN_IF_FAILED(_runtime->GetObject(m_pClock));
RETURN_NOERROR;
}
tResult fcBirdsEyeTransform::ChangeType(adtf::streaming::cDynamicSampleReader& inputPin, const adtf::streaming::ant::IStreamType& oType) {
if (oType == adtf::streaming::stream_meta_type_image())
{
adtf::ucom::object_ptr<const adtf::streaming::IStreamType> pTypeInput;
// get pType from input reader
inputPin >> pTypeInput;
adtf::streaming::get_stream_type_image_format(m_InPinVideoFormat, *pTypeInput);
//set also output format
adtf::streaming::get_stream_type_image_format(m_OutPinVideoFormat, *pTypeInput);
// and set pType also to samplewriter
m_oWriterVideo << pTypeInput;
}
else
{
RETURN_ERROR(ERR_INVALID_TYPE);
}
RETURN_NOERROR;
}
tResult fcBirdsEyeTransform::Process(tTimeStamp tmTimeOfTrigger) {
object_ptr<const ISample> pReadSample;
if (IS_OK(m_oReaderVideo.GetNextSample(pReadSample))) {
object_ptr_shared_locked<const ISampleBuffer> pReadBuffer;
Mat outputImage;
cv::cuda::GpuMat dst, src;
//lock read buffer
if (IS_OK(pReadSample->Lock(pReadBuffer))) {
RETURN_IF_FAILED(checkRoi());
Size inputSize = cv::Size(m_InPinVideoFormat.m_ui32Width, m_InPinVideoFormat.m_ui32Height);
//create a opencv matrix from the media sample buffer
Mat inputImage(inputSize, CV_8UC3, (uchar*)pReadBuffer->GetPtr());
inputImage = inputImage.clone();
Rect roi(
inputSize.width * m_ROIOffsetX,
inputSize.height * m_ROIOffsetY,
inputSize.width * m_ROIWidth,
inputSize.height * m_ROIHeight
);
tInt64 aspectRatio = roi.width / roi.height;
Size outputSize = cv::Size(m_OutputHeight * aspectRatio , m_OutputHeight);
Point2f src_vertices[4];
src_vertices[0] = Point2f(roi.x, roi.y);
src_vertices[1] = Point2f(roi.x + roi.width, roi.y);
src_vertices[2] = Point2f(roi.x + roi.width, roi.y + roi.height);
src_vertices[3] = Point2f(roi.x, roi.y + roi.height);
Point2f dst_vertices[4];
dst_vertices[0] = Point2f(roi.x + roi.width * m_topSideInset, roi.y); // Point2f(inputSize.width * m_topSideInset, 0);
dst_vertices[1] = Point2f(roi.x + roi.width * (1.0f - m_topSideInset), roi.y); // Point2f(inputSize.width * (1.0f - m_topSideInset), 0);
dst_vertices[2] = Point2f(roi.x + (1.0f - m_bottomSideInset) * roi.width, roi.y + roi.height); // Point2f(inputSize.width * (1.0f - m_bottomSideInset), inputSize.height);
dst_vertices[3] = Point2f(roi.x + m_bottomSideInset * roi.width, roi.y + roi.height); // Point2f(inputSize.width * m_bottomSideInset, inputSize.height);
Mat M = getPerspectiveTransform(src_vertices, dst_vertices);
if(m_showROIDebug) {
outputImage = inputImage.clone();
line(outputImage, src_vertices[0], src_vertices[1], Scalar(0,255,255), 2);
line(outputImage, src_vertices[1], src_vertices[2], Scalar(0,255,255), 2);
line(outputImage, src_vertices[2], src_vertices[3], Scalar(0,255,255), 2);
line(outputImage, src_vertices[3], src_vertices[0], Scalar(0,255,255), 2);
line(outputImage, dst_vertices[0], dst_vertices[1], Scalar(255,255,255), 2);
line(outputImage, dst_vertices[1], dst_vertices[2], Scalar(255,255,255), 2);
line(outputImage, dst_vertices[2], dst_vertices[3], Scalar(255,255,255), 2);
line(outputImage, dst_vertices[3], dst_vertices[0], Scalar(255,255,255), 2);
resize(outputImage, outputImage, outputSize);
} else {
src.upload(inputImage);
cv::cuda::warpPerspective(src, dst, M, inputSize, INTER_LINEAR, BORDER_CONSTANT);
// cv::cuda::resize(dst, dst, outputSize);
dst.download(outputImage);
outputImage = outputImage(roi).clone();
}
pReadBuffer->Unlock();
}
//copy to outputimage
//Write processed Image to Output Pin
if (!outputImage.empty())
{
//update output format if matrix size does not fit to
if (outputImage.total() * outputImage.elemSize() != m_OutPinVideoFormat.m_szMaxByteSize)
{
setTypeFromMat(m_oWriterVideo, outputImage);
}
// write to pin
writeMatToPin(m_oWriterVideo, outputImage, m_pClock->GetStreamTime());
}
}
RETURN_NOERROR;
}
tResult fcBirdsEyeTransform::checkRoi(void)
{
// if width or heigt are not set ignore the roi
if (static_cast<tFloat32>(m_ROIWidth) == 0 || static_cast<tFloat32>(m_ROIHeight) == 0)
{
LOG_ERROR("ROI width or height is not set!");
RETURN_ERROR_DESC(ERR_INVALID_ARG, "ROI width or height is not set!");
}
//check if we are within the boundaries of the image
if ((static_cast<tFloat32>(m_ROIOffsetX) + static_cast<tFloat32>(m_ROIWidth)) > m_InPinVideoFormat.m_ui32Width)
{
LOG_ERROR("ROI is outside of image");
RETURN_ERROR_DESC(ERR_INVALID_ARG, "ROI is outside of image");
}
if ((static_cast<tFloat32>(m_ROIOffsetY) + static_cast<tFloat32>(m_ROIHeight)) > m_InPinVideoFormat.m_ui32Height)
{
LOG_ERROR("ROI is outside of image");
RETURN_ERROR_DESC(ERR_INVALID_ARG, "ROI is outside of image");
}
//create the rectangle
m_LaneRoi = cv::Rect2f(static_cast<tFloat32>(m_ROIOffsetX), static_cast<tFloat32>(m_ROIOffsetY), static_cast<tFloat32>(m_ROIWidth), static_cast<tFloat32>(m_ROIHeight));
RETURN_NOERROR;
} | 42.040609 | 182 | 0.655277 | kimsoohwan |
406486fd3719f11df98280a5ba769ea3eef2ae14 | 1,720 | hpp | C++ | include/limitless/fx/modules/custom_material.hpp | Tehsapper/graphics-engine | 5b7cd93c750ccce7b254c6bb4a13948b2b4ec975 | [
"MIT"
] | 9 | 2020-07-23T13:00:12.000Z | 2021-01-07T10:44:24.000Z | include/limitless/fx/modules/custom_material.hpp | Tehsapper/graphics-engine | 5b7cd93c750ccce7b254c6bb4a13948b2b4ec975 | [
"MIT"
] | 7 | 2020-09-11T18:23:45.000Z | 2020-11-01T19:05:47.000Z | include/limitless/fx/modules/custom_material.hpp | Tehsapper/graphics-engine | 5b7cd93c750ccce7b254c6bb4a13948b2b4ec975 | [
"MIT"
] | 3 | 2020-08-24T01:59:48.000Z | 2021-02-18T16:41:27.000Z | #pragma once
#include <limitless/fx/modules/module.hpp>
namespace Limitless::fx {
template<typename Particle>
class CustomMaterial : public Module<Particle> {
private:
std::array<std::unique_ptr<Distribution<float>>, 4> properties;
public:
CustomMaterial(std::unique_ptr<Distribution<float>> prop1,
std::unique_ptr<Distribution<float>> prop2,
std::unique_ptr<Distribution<float>> prop3,
std::unique_ptr<Distribution<float>> prop4 ) noexcept
: Module<Particle>(ModuleType::CustomMaterial)
, properties {std::move(prop1), std::move(prop2), std::move(prop3), std::move(prop4)} {}
~CustomMaterial() override = default;
CustomMaterial(const CustomMaterial& module)
: Module<Particle>(module.type){
for (size_t i = 0; i < module.properties.size(); ++i) {
if (module.properties[i]) {
properties[i] = std::unique_ptr<Distribution<float>>(module.properties[i]->clone());
}
}
}
auto& getProperties() noexcept { return properties; }
const auto& getProperties() const noexcept { return properties; }
void initialize([[maybe_unused]] AbstractEmitter& emitter, Particle& particle, [[maybe_unused]] size_t index) noexcept override {
for (size_t i = 0; i < properties.size(); ++i) {
if (properties[i]) {
particle.properties[i] = properties[i]->get();
}
}
}
[[nodiscard]] CustomMaterial* clone() const override {
return new CustomMaterial(*this);
}
};
} | 39.090909 | 137 | 0.575581 | Tehsapper |
40664a29a8104c19ccfcaf385df93666aa2e4865 | 5,139 | cpp | C++ | native/common/file_descriptor.cpp | kaloianm/rural-pipe | 7bdae362f360da3114282512ef2c0d01e621a4c1 | [
"Unlicense"
] | null | null | null | native/common/file_descriptor.cpp | kaloianm/rural-pipe | 7bdae362f360da3114282512ef2c0d01e621a4c1 | [
"Unlicense"
] | 1 | 2021-02-18T18:35:46.000Z | 2021-02-18T18:35:46.000Z | native/common/file_descriptor.cpp | kaloianm/rural-pipe | 7bdae362f360da3114282512ef2c0d01e621a4c1 | [
"Unlicense"
] | null | null | null | /**
* Copyright 2020 Kaloian Manassiev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
#include "common/base.h"
#include "common/file_descriptor.h"
#include <boost/log/trivial.hpp>
#include <poll.h>
#include <sstream>
#include <sys/ioctl.h>
#include <unistd.h>
#include "common/exception.h"
namespace ruralpi {
FileDescriptor::FileDescriptor(const std::string &desc, int fd) : _desc(desc), _fd(fd) {
SYSCALL_MSG(_fd, boost::format("Could not open file descriptor (%d): %s") % _fd % _desc);
}
FileDescriptor::FileDescriptor(const FileDescriptor &) = default;
FileDescriptor::FileDescriptor(FileDescriptor &&other) { *this = std::move(other); }
FileDescriptor &FileDescriptor::operator=(FileDescriptor &&other) {
_desc = std::move(other._desc);
_fd = other._fd;
other._fd = -1;
return *this;
}
void FileDescriptor::makeNonBlocking() {
int flags = SYSCALL(::fcntl(_fd, F_GETFL));
SYSCALL(::fcntl(_fd, F_SETFL, flags | O_NONBLOCK));
}
int FileDescriptor::availableToRead() {
int nAvailable;
SYSCALL(::ioctl(_fd, FIONREAD, &nAvailable));
return nAvailable;
}
int FileDescriptor::readNonBlocking(void *buf, size_t nbytes) {
int nRead = ::read(_fd, buf, nbytes);
if (nRead < 0 && (errno == EWOULDBLOCK || errno == EAGAIN))
return nRead;
SYSCALL_MSG(nRead, boost::format("Failed to read from file descriptor (%d): %s") % _fd % _desc);
return nRead;
}
int FileDescriptor::read(void *buf, size_t nbytes) {
while (true) {
int nRead = readNonBlocking(buf, nbytes);
if (nRead > 0) {
return nRead;
} else if (nRead == 0) {
throw SystemException(
boost::format("Failed to read from closed file descriptor (%d): %s") % _fd % _desc);
} else if (nRead < 0 && (errno == EWOULDBLOCK || errno == EAGAIN)) {
poll(Milliseconds(-1), POLLIN);
}
}
}
int FileDescriptor::writeNonBlocking(void const *buf, size_t nbytes) {
int nWritten = ::write(_fd, buf, nbytes);
if (nWritten < 0 && (errno == EWOULDBLOCK || errno == EAGAIN))
return nWritten;
SYSCALL_MSG(nWritten,
boost::format("Failed to write to file descriptor (%d): %s") % _fd % _desc);
return nWritten;
}
int FileDescriptor::write(void const *buf, size_t nbytes) {
while (true) {
int nWritten = writeNonBlocking(buf, nbytes);
if (nWritten > 0) {
return nWritten;
} else if (nWritten == 0) {
throw SystemException(
boost::format("Failed to write to closed file descriptor (%d): %s") % _fd % _desc);
} else if (nWritten < 0 && (errno == EWOULDBLOCK || errno == EAGAIN)) {
poll(Milliseconds(-1), POLLOUT);
}
}
}
int FileDescriptor::poll(Milliseconds timeout, short events) {
pollfd fd;
fd.fd = _fd;
fd.events = events;
return SYSCALL(::poll(&fd, 1, timeout.count()));
}
std::string FileDescriptor::toString() const {
std::stringstream ss;
ss << _desc << " (fd " << _fd << ')';
return ss.str();
}
ScopedFileDescriptor::ScopedFileDescriptor(const std::string &desc, int fd)
: FileDescriptor(desc, fd) {
BOOST_LOG_TRIVIAL(debug) << boost::format("File descriptor created (%d): %s") % _fd % _desc;
}
ScopedFileDescriptor::ScopedFileDescriptor(ScopedFileDescriptor &&other) = default;
ScopedFileDescriptor &ScopedFileDescriptor::operator=(ScopedFileDescriptor &&) = default;
ScopedFileDescriptor::~ScopedFileDescriptor() { close(); }
void ScopedFileDescriptor::close() {
if (_fd > 0) {
BOOST_LOG_TRIVIAL(debug) << boost::format("File descriptor closed (%d): %s") % _fd % _desc;
if (::close(_fd) < 0) {
BOOST_LOG_TRIVIAL(debug)
<< (boost::format("File descriptor close failed (%d): %s") % _fd % _desc) << ": "
<< SystemException::getLastError();
}
_fd = -1;
return;
} else if (_fd == -1) {
return;
}
RASSERT_MSG(false, boost::format("Illegal file descriptor (%d): %s") % _fd % _desc.c_str());
}
} // namespace ruralpi
| 33.809211 | 100 | 0.650905 | kaloianm |
4066a29a25316d7395e4cd3fb2a5065ea0b53be4 | 1,554 | cpp | C++ | src/analysis/ismt/cvc_context.cpp | gdslang/summy | bd450278f18859eb94d1f30b7b878bbb1b94c42c | [
"Apache-2.0"
] | null | null | null | src/analysis/ismt/cvc_context.cpp | gdslang/summy | bd450278f18859eb94d1f30b7b878bbb1b94c42c | [
"Apache-2.0"
] | null | null | null | src/analysis/ismt/cvc_context.cpp | gdslang/summy | bd450278f18859eb94d1f30b7b878bbb1b94c42c | [
"Apache-2.0"
] | null | null | null | /*
* cvc_context.cpp
*
* Created on: Nov 7, 2014
* Author: Julian Kranz
*/
#include <summy/analysis/ismt/cvc_context.h>
#include <cvc4/cvc4.h>
#include <string>
#include <sstream>
using namespace std;
using namespace CVC4;
analysis::cvc_context::cvc_context(bool unsat_cores) : smtEngine(&manager) {
smtEngine.setOption("produce-models", SExpr("true"));
smtEngine.setOption("incremental", SExpr("true"));
if(unsat_cores) {
smtEngine.setOption("produce-unsat-cores", SExpr("true"));
// smtEngine.setOption("tear-down-incremental", SExpr("true"));
}
mem_type = manager.mkArrayType(manager.mkBitVectorType(61), manager.mkBitVectorType(64));
}
CVC4::Expr analysis::cvc_context::var(std::string name) {
auto i_it = var_map.find(name);
if(i_it != var_map.end()) return i_it->second;
else {
Expr i_exp = manager.mkVar(name, manager.mkBitVectorType(64));
var_map[name] = i_exp;
return i_exp;
}
}
CVC4::Expr analysis::cvc_context::memory(memory_map_t &m, string base, size_t rev) {
auto rev_it = m.find(rev);
if(rev_it != m.end()) return rev_it->second;
else {
stringstream name;
name << base << rev;
Expr mem = manager.mkVar(name.str(), mem_type);
m[rev] = mem;
return mem;
}
}
//CVC4::Expr analysis::cvc_context::var_def(std::string name) {
// return var(name + "_def");
//}
CVC4::Expr analysis::cvc_context::memory(size_t rev) {
return memory(mem_map, "m_", rev);
}
CVC4::Expr analysis::cvc_context::memory_def(size_t rev) {
return memory(mem_def_map, "m_def_", rev);
}
| 25.9 | 91 | 0.680824 | gdslang |
406def49682fe2b251bb469e529554cb8e02c00c | 5,872 | cpp | C++ | device/built_ins/x64/gen8/aux_translation_Gen8core.cpp | shuangwan01/compute-runtime | efdd870b92c22beb9211f4a4ceaa2f062b84b7d3 | [
"MIT"
] | null | null | null | device/built_ins/x64/gen8/aux_translation_Gen8core.cpp | shuangwan01/compute-runtime | efdd870b92c22beb9211f4a4ceaa2f062b84b7d3 | [
"MIT"
] | 1 | 2019-09-17T08:06:24.000Z | 2019-09-17T08:06:24.000Z | device/built_ins/x64/gen8/aux_translation_Gen8core.cpp | shuangwan01/compute-runtime | efdd870b92c22beb9211f4a4ceaa2f062b84b7d3 | [
"MIT"
] | 2 | 2019-09-12T05:03:02.000Z | 2020-03-12T02:17:34.000Z | #include <cstddef>
#include <cstdint>
size_t AuxTranslationBinarySize_Gen8core = 1692;
uint32_t AuxTranslationBinary_Gen8core[423] = {
0x494e5443, 0x00000420, 0x0000000b, 0x00000008, 0x00000001, 0x00000000, 0x00000000, 0x2f674870,
0xad5c17e9, 0x304ea729, 0x0000000c, 0x000003a0, 0x000001c0, 0x00000000, 0x00000020, 0x000000cc,
0x00000140, 0x6c6c7566, 0x79706f43, 0x00000000, 0x00008006, 0x30000004, 0x16001000, 0x04c004c0,
0x202d8041, 0x00090800, 0x20004d01, 0x00007f07, 0x00800040, 0x20600a28, 0x12000100, 0x00b10020,
0x00802040, 0x20a00a28, 0x12000100, 0x00b10040, 0x20019640, 0x07030307, 0x00802040, 0x20a00a28,
0x0a8d00a0, 0x000000e0, 0x00800009, 0x21400a28, 0x1e8d0060, 0x00040004, 0x00802009, 0x21800a28,
0x1e8d00a0, 0x00040004, 0x0c800031, 0x21c03a68, 0x068d0140, 0x04805000, 0x20005601, 0x000a1e07,
0x0c802031, 0x22c03a68, 0x068d0180, 0x04805000, 0x00802001, 0x25000208, 0x008d0180, 0x00000000,
0x2002d601, 0x000e2007, 0x2002d601, 0x00102207, 0x2002d601, 0x00122407, 0x2002d601, 0x00142607,
0x00802001, 0x25400a28, 0x008d02c0, 0x00000000, 0x00802001, 0x25800a28, 0x008d0300, 0x00000000,
0x00802001, 0x25c00a28, 0x008d0340, 0x00000000, 0x00802001, 0x26000a28, 0x008d0380, 0x00000000,
0x0c800031, 0x20003a60, 0x068d03c0, 0x14025001, 0x0c802031, 0x20003a60, 0x068d0500, 0x14025001,
0x07600031, 0x20003a04, 0x068d0fe0, 0x82000010, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x000000c3, 0x00000000, 0x00000000, 0x00000003, 0x83ffc000, 0x03000000, 0x1fff007f, 0x0fe00000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x83ffc000, 0x03000000, 0x1fff007f, 0x0fe00000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x87ffc000, 0x03000000, 0x1fff007f, 0x0fe00000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000040, 0x00000080, 0x00000013,
0x0000000c, 0x00000000, 0x00000015, 0x00000018, 0x00000000, 0x00000000, 0x00000000, 0x000000c0,
0x00000008, 0x00000014, 0x000000c0, 0x00000003, 0x00000000, 0x00000011, 0x00000028, 0x00000010,
0x00000000, 0x00000000, 0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000011,
0x00000028, 0x00000010, 0x00000000, 0x00000004, 0x00000004, 0x00000004, 0x00000000, 0x00000000,
0x00000000, 0x00000011, 0x00000028, 0x00000010, 0x00000000, 0x00000008, 0x00000004, 0x00000008,
0x00000000, 0x00000000, 0x00000000, 0x00000011, 0x00000028, 0x00000002, 0x00000000, 0x0000000c,
0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000011, 0x00000028, 0x00000002,
0x00000000, 0x00000010, 0x00000004, 0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000011,
0x00000028, 0x00000002, 0x00000000, 0x00000014, 0x00000004, 0x00000008, 0x00000000, 0x00000000,
0x00000000, 0x00000011, 0x00000028, 0x0000002b, 0x00000000, 0x00000020, 0x00000004, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000011, 0x00000028, 0x0000002b, 0x00000001, 0x00000028,
0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000011, 0x00000028, 0x0000001c,
0x00000000, 0x00000040, 0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000011,
0x00000028, 0x0000001c, 0x00000000, 0x00000044, 0x00000004, 0x00000004, 0x00000000, 0x00000000,
0x00000000, 0x00000011, 0x00000028, 0x0000001c, 0x00000000, 0x00000048, 0x00000004, 0x00000008,
0x00000000, 0x00000000, 0x00000000, 0x0000001e, 0x00000024, 0x00000000, 0x00000000, 0x00000020,
0x00000008, 0xffffffff, 0xffffffff, 0x00000000, 0x0000001e, 0x00000024, 0x00000001, 0x00000040,
0x00000028, 0x00000008, 0xffffffff, 0xffffffff, 0x00000000, 0x00000026, 0x00000018, 0x00000080,
0x00000030, 0x00000008, 0x00000000, 0x00000019, 0x0000000c, 0x00000060, 0x00000016, 0x00000040,
0x00000000, 0x00000001, 0x00000001, 0x00000001, 0x00000000, 0x00000001, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000017, 0x00000064,
0x00000000, 0x00000000, 0x00000000, 0x00000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000001, 0x00000000, 0x00000080, 0x00000000, 0x00000000, 0x00000000, 0x0000001b,
0x00000010, 0x00000004, 0x00000000, 0x0000001a, 0x00000048, 0x00000000, 0x0000000c, 0x00000008,
0x00000004, 0x00000008, 0x00000008, 0x6c675f5f, 0x6c61626f, 0x00000000, 0x454e4f4e, 0x00000000,
0x00637273, 0x746e6975, 0x00383b2a, 0x736e6f63, 0x00000074, 0x0000001a, 0x00000048, 0x00000001,
0x0000000c, 0x00000008, 0x00000004, 0x00000008, 0x00000008, 0x6c675f5f, 0x6c61626f, 0x00000000,
0x454e4f4e, 0x00000000, 0x00747364, 0x746e6975, 0x00383b2a, 0x454e4f4e, 0x00000000};
#include "runtime/built_ins/registry/built_ins_registry.h"
namespace NEO {
static RegisterEmbeddedResource registerAuxTranslationBin(
createBuiltinResourceName(
EBuiltInOps::AuxTranslation,
BuiltinCode::getExtension(BuiltinCode::ECodeType::Binary), "Gen8core", 0)
.c_str(),
(const char *)AuxTranslationBinary_Gen8core,
AuxTranslationBinarySize_Gen8core);
}
| 82.704225 | 100 | 0.790531 | shuangwan01 |
40715819e82a2de3e3fc52d3b2159bfe67b89525 | 6,015 | cpp | C++ | MemPool.cpp | mkschleg/MemoryPool | 1c899bc2d4562b27102e2d2b38a75e5030008737 | [
"MIT"
] | null | null | null | MemPool.cpp | mkschleg/MemoryPool | 1c899bc2d4562b27102e2d2b38a75e5030008737 | [
"MIT"
] | null | null | null | MemPool.cpp | mkschleg/MemoryPool | 1c899bc2d4562b27102e2d2b38a75e5030008737 | [
"MIT"
] | null | null | null |
#include <iostream>
#include "MemPool.h"
Pool::Pool(int size){
//create the pool, or char array...
pool = new unsigned char[size];
//create temp which is a temp pointer to the beginning of pool
int* temp=(int*)pool;
//The value of *temp becomes the size of our array
*temp=size;
//Out puts the size and where the char array is!
std::cout<<*temp<<" "<<temp<<std::endl;
//Create a new ptr in our pool which points nowhere but is casted as a int*
long* ptr_b=(long*)temp+1;
*ptr_b=(long)NULL;
//Create a new ptr in our pool which points nowhere but is casted as a int*
long* ptr_f=ptr_b+1;
*ptr_f=(long)NULL;
//Set our firstNode as the beginning of our empty array
firstNode=temp;
}
void* Pool::allocate (unsigned int bytes){
//find where we can start allocating!
int* temp=firstNode;
if(firstNode==NULL){
std::cout<<"You are out of memory!"<<std::endl;
return NULL;
}
//This is the next node where we can store data
long* next=(long*)temp+2;
//We need this loop to be able to loop through to find an appropriate space
//to allocate the variable.
while(true){
//This first if statement finds if the size of empty space is smaller than
//the wanted size. If true we need to check if the next slot is available.
//If so then we loop around and do the check again! If not there is no
//space available for the variable and we just return the NULL pointer.
if(*temp<bytes){
if(*next==(long)NULL){
std::cout<<"No space available for this item!"<<std::endl;
return NULL;
}
else{
temp=(int*) *next;
next=(long*)temp+2;
}
}
//This is when the variable fits perfectly into the slot! If our current
//slot is the only node we need to show that our memory is full and set
//the firstNode to Null returning our memory. If it is not but is the
//firstNode we change the memory area pointed to in next as the new
//firstNode.
else if(*temp==bytes){
std::cout<<"Warning your memory is getting full!!"<<std::endl;
if(temp==firstNode){
if(*next==(long)NULL){
std::cout<<"You're memory is now full!"<<std::endl;
//*temp alread is equivalent to the bytes
//there are no more nodes!
//and we need to send the pointer to the memory slot!
firstNode=NULL;
return temp+1;
}
else{
firstNode==(int*)*next;
return temp+1;
}
}
//Otherwise our node is in the middle and we need to close it and set
//the appropriate pointers to the right places.
else{
long* ptr_b=(long*)temp+1;
long* ptr_f=(long*)temp+2;
int* tempb=(int*)*ptr_b;
long* ptrb_f=(long*)tempb+2;
*ptrb_f=*ptr_f;
int* tempf=(int*)*ptr_f;
long* ptrf_b=(long*)tempf+1;
*ptrf_b=*ptr_b;
}
}
//This is when our space does not exactly equal the space wanted and we
//split the area.
else{
//std::cout<<"Help\n";
void* ptr=temp+1;
long* pb=(long*) temp+1;
long* pf=pb+1;
int* temp2=temp+1+(bytes/sizeof(int));
*temp2=*temp-bytes-sizeof(int);
*temp=bytes;
long* ptr_b=(long*)temp2+1;
*ptr_b=*pb;
long* ptr_f=ptr_b+1;
*ptr_f=*pf;
firstNode=temp2;
std::cout<<*temp<<' '<<ptr<<std::endl
<<*temp2<<' '<<temp2<<' '<<ptr_b<<' '<<ptr_f<<std::endl
<<firstNode<<std::endl;
return ptr;
}
}
}
//Deallocate function
void Pool::deallocate (void* ptr){
int* a=(int*) ptr;
a-=1;
int* b=firstNode;
long* next=(long*) b+2;
//if the firstNode is full we know our vector is full and have to make a
//a node that will become our firstNode
if(firstNode==NULL){
//size remains the same
long* aptr_b=(long*)a+1;
long* aptr_f=aptr_b+1;
*aptr_b=(long)NULL;
*aptr_f=(long)NULL;
firstNode=a;
}
//If the slot comes before our firstNode
else if(a<firstNode){
std::cout<<"1";
// std::cout<<a+(*a/sizeof(int))+1<<std::endl;
//Is the slot connected to the first node?
if(a+*a/sizeof(int)+1==b){
//Node pointers for a
std::cout<<"a"<<std::endl;
int* aptr_b=a+1;
int* aptr_f=aptr_b+1;
//Node pointers for b
int* c=b+1;
int* d=c+1;
*a=*a+*b+sizeof(int);
*aptr_b=*c;
*aptr_f=*d;
firstNode=a;
}
//When it is not connected to the firstNode
else{
std::cout<<"b"<<std::endl;
long* aptr_b=(long*) a+1;
long* aptr_f=aptr_b+1;
//The size stays the same! *a=*a
*aptr_b=(long)NULL;
*aptr_f=(long) b;
firstNode=a;
}
}
//When the deallocation spot comes after our firstNode
else{
//std::cout<<"else"<<std::endl;
//Finding where our slot is in the memory
while((long)a>*next){
std::cout<<"loop"<<std::endl;
if(a>(int*) *next){
b=(int*) *next;
next=(long*) b+2;
}
}
long* bptr_b=(long*) b+1;
long* bptr_f=bptr_b+1;
int* x=(int*) *bptr_f;
long* xptr_b=(long*) x+1;
long* xptr_f=xptr_b+1;
//These are our test cases
std::cout<<"2";
//connected on both sides to free space
if(a==b+*b/sizeof(int)+1 and x==a+*a/sizeof(int)+1){
std::cout<<"a"<<std::endl;
*b=*b+*a+*x+2*sizeof(int);
*bptr_f=*xptr_f;
}
//connected on the front side
else if(a==b+*b/sizeof(int)+1){
std::cout<<"b"<<std::endl;
*b=*b+*a+sizeof(int);
}
//connected on the back side
else if(x==a+*a/sizeof(int)+1){
std::cout<<"c"<<std::endl;
long* aptr_b=(long*)a+1;
long* aptr_f=aptr_b+1;
*a=*a+*x+sizeof(int);
*aptr_b=*xptr_b;
*aptr_f=*xptr_f;
}
//not connected to any free space
else{
std::cout<<"d"<<std::endl;
long* aptr_b=(long*)a+1;
long* aptr_f=aptr_b+1;
//size stays the same! *a=*a
*aptr_b=*xptr_b;
*aptr_f=*bptr_f;
*xptr_b=(long)a;
*bptr_f=(long)a;
}
}
}
void Pool::print_size(){
int* temp=firstNode;
std::cout<<*temp<<" "<<temp<<std::endl;
}
| 24.352227 | 78 | 0.590357 | mkschleg |
4072ce1c8fbf3fd3267fe10c2a504eb15dcdadac | 460 | cpp | C++ | src/ximage_overlay.cpp | jtpio/xleaflet | 67df1c06ef7b8bb753180bfea545e5ad38ac88b3 | [
"BSD-3-Clause"
] | null | null | null | src/ximage_overlay.cpp | jtpio/xleaflet | 67df1c06ef7b8bb753180bfea545e5ad38ac88b3 | [
"BSD-3-Clause"
] | null | null | null | src/ximage_overlay.cpp | jtpio/xleaflet | 67df1c06ef7b8bb753180bfea545e5ad38ac88b3 | [
"BSD-3-Clause"
] | null | null | null | #include "xleaflet/ximage_overlay.hpp"
template class XLEAFLET_API xw::xmaterialize<xlf::ximage_overlay>;
template xw::xmaterialize<xlf::ximage_overlay>::xmaterialize();
template class XLEAFLET_API xw::xtransport<xw::xmaterialize<xlf::ximage_overlay>>;
template class XLEAFLET_API xw::xgenerator<xlf::ximage_overlay>;
template xw::xgenerator<xlf::ximage_overlay>::xgenerator();
template class XLEAFLET_API xw::xtransport<xw::xgenerator<xlf::ximage_overlay>>;
| 51.111111 | 82 | 0.813043 | jtpio |
4073a13dcbdaf83823637a3f17f6030ff05454cc | 59 | cpp | C++ | source/core/ObjLoader.cpp | zhanghao00925/CG-Path_Tracing-Algorithm | 12bd6d7334051aa2bb0544dd26bfe4ad13ec5560 | [
"MIT"
] | 3 | 2020-04-05T13:09:17.000Z | 2021-03-16T10:56:17.000Z | source/core/ObjLoader.cpp | zhanghao00925/CG-Path_Tracing-Algorithm | 12bd6d7334051aa2bb0544dd26bfe4ad13ec5560 | [
"MIT"
] | null | null | null | source/core/ObjLoader.cpp | zhanghao00925/CG-Path_Tracing-Algorithm | 12bd6d7334051aa2bb0544dd26bfe4ad13ec5560 | [
"MIT"
] | 1 | 2020-02-19T02:59:44.000Z | 2020-02-19T02:59:44.000Z | //
// Created by hao on 3/6/19.
//
#include "ObjLoader.h"
| 9.833333 | 28 | 0.59322 | zhanghao00925 |
407917d32becd9a35deb6c6f126c78b4c698fda3 | 553 | cpp | C++ | Session_04/00_FlowerClassVector/src/ofApp.cpp | SAIC-ATS/ARTTECH3135 | 179805d373601ac92dcdbb51ddc4925fc65f7c22 | [
"MIT"
] | 26 | 2015-09-23T12:31:16.000Z | 2020-12-14T03:19:19.000Z | Session_04/00_FlowerClassVector/src/ofApp.cpp | SAIC-ATS/ARTTECH3135 | 179805d373601ac92dcdbb51ddc4925fc65f7c22 | [
"MIT"
] | 2 | 2017-07-05T18:14:52.000Z | 2017-10-31T00:04:13.000Z | Session_04/00_FlowerClassVector/src/ofApp.cpp | SAIC-ATS/ARTTECH3135 | 179805d373601ac92dcdbb51ddc4925fc65f7c22 | [
"MIT"
] | 37 | 2015-09-19T22:10:32.000Z | 2019-12-07T19:35:55.000Z | #include "ofApp.h"
void ofApp::setup()
{
ofBackground(80);
ofSetCircleResolution(64);
// flowers = { Flower(), Flower(), Flower() };
}
void ofApp::update()
{
for (std::size_t i = 0; i < flowers.size(); i++)
{
flowers[i].update();
}
}
void ofApp::draw()
{
for (std::size_t i = 0; i < flowers.size(); i++)
{
flowers[i].draw();
}
}
void ofApp::mousePressed(int x, int y, int button)
{
Flower aFlower;
aFlower.x = x;
aFlower.y = y;
flowers.push_back(aFlower);
}
| 13.487805 | 52 | 0.522604 | SAIC-ATS |
407c72000ab7cfb5d427ccb9cf9a401af39c7f0d | 4,002 | cpp | C++ | src/connection.cpp | tmplt/libircppclient | 99121502564b9085b7ce81367ac73e933213706c | [
"MIT"
] | 1 | 2020-11-12T22:57:20.000Z | 2020-11-12T22:57:20.000Z | src/connection.cpp | tmplt/libircppclient | 99121502564b9085b7ce81367ac73e933213706c | [
"MIT"
] | null | null | null | src/connection.cpp | tmplt/libircppclient | 99121502564b9085b7ce81367ac73e933213706c | [
"MIT"
] | null | null | null | #include "connection.hpp"
#include <boost/bind.hpp>
#include <thread>
#include <string>
#include <iostream>
namespace irc {
connection::connection(const bool use_ssl)
: socket_(io_service_),
use_ssl_(use_ssl), ctx_(ssl::context::sslv23), ssl_socket_(io_service_, ctx_)
{
if (use_ssl_) {
ctx_.set_default_verify_paths(ec_);
if (ec_)
throw ec_;
}
}
boost::system::error_code connection::verify_cert()
{
boost::system::error_code ec;
ssl_socket_.set_verify_mode(ssl::verify_peer | ssl::verify_fail_if_no_peer_cert);
ssl_socket_.set_verify_callback(ssl::rfc2818_verification(addr_), ec);
return ec;
}
boost::system::error_code connection::shake_hands()
{
boost::system::error_code ec;
ssl_socket_.handshake(ssl_socket::client, ec);
return ec;
}
void connection::connect()
{
using boost::asio::ip::tcp;
tcp::resolver r(io_service_);
tcp::resolver::query query(addr_, port_);
/* default error. */
ec_ = boost::asio::error::host_not_found;
if (use_ssl_) {
boost::asio::connect(ssl_socket_.lowest_layer(), r.resolve(query), ec_);
if (!ec_) {
ec_ = verify_cert();
if (!ec_)
ec_ = shake_hands();
}
} else {
boost::asio::connect(socket_.lowest_layer(), r.resolve(query), ec_);
}
if (ec_)
throw ec_;
}
template<class S>
void connection::read_some(S &s)
{
s.async_read_some(boost::asio::buffer(read_buffer_),
boost::bind(&connection::read_handler,
this, boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred()));
}
void connection::read_handler(const boost::system::error_code &ec, std::size_t length)
{
using std::experimental::string_view;
if (ec) {
/* Unable to read from server. */
throw ec;
} else {
const string_view content(read_buffer_.data(), length);
std::stringstream iss(content.data());
std::string command;
iss >> command;
if (command == "PING")
pong();
else
ext_read_handler_(content);
if (use_ssl_)
read_some(ssl_socket_);
else
read_some(socket_);
}
}
void connection::run()
{
std::thread ping_thread(ping_handler_);
if (use_ssl_)
read_some(ssl_socket_);
else
read_some(socket_);
boost::system::error_code ec;
io_service_.run(ec);
/*
* Remain at this point until we
* do not need the connection any more.
*/
ping_thread.join();
if (ec)
throw ec;
}
void connection::ping()
{
using namespace std::literals;
while (do_ping) {
/*
* Interval decided by mimicing WeeChat.
* The standard does not seem to explicitly
* state a ping inverval. Is it the server's
* decision?
*/
std::this_thread::sleep_for(1min + 30s);
write("PING " + addr_);
}
}
void connection::pong()
{
write("PONG :" + addr_);
}
void connection::write(std::string content)
{
/*
* The IRC protocol specifies that all messages sent to the server
* must be terminated with CR-LF (Carriage Return - Line Feed)
*/
content.append("\r\n");
#ifdef DEBUG
std::cout << "[debug] writing: " << content;
#endif
if (use_ssl_)
boost::asio::write(ssl_socket_, boost::asio::buffer(content), ec_);
else
boost::asio::write(socket_.next_layer(), boost::asio::buffer(content), ec_);
if (ec_)
throw ec_;
}
void connection::stop()
{
/*
* For a proper shutdown, we first need to terminate
* the ping thread, which might have to be done while
* it's in nanosleep. After that, we are free to stop
* the io_service.
*/
if (use_ssl_)
ssl_socket_.lowest_layer().close();
else
socket_.lowest_layer().close();
io_service_.stop();
}
/* ns irc */
}
| 21.516129 | 86 | 0.601949 | tmplt |
407c7ad3c3a83f0c135ad2ebe28d5cba02b3015f | 2,667 | cpp | C++ | app/android/jni/tango-gl/camera.cpp | Riotpiaole/rtabmap | 2b8b36db2ed7a08361dcffc9e2da3070b92a3883 | [
"BSD-3-Clause"
] | null | null | null | app/android/jni/tango-gl/camera.cpp | Riotpiaole/rtabmap | 2b8b36db2ed7a08361dcffc9e2da3070b92a3883 | [
"BSD-3-Clause"
] | null | null | null | app/android/jni/tango-gl/camera.cpp | Riotpiaole/rtabmap | 2b8b36db2ed7a08361dcffc9e2da3070b92a3883 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2014 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "tango-gl/camera.h"
#include "tango-gl/util.h"
namespace tango_gl {
Camera::Camera() {
field_of_view_ = 45.0f * DEGREE_2_RADIANS;
aspect_ratio_ = 4.0f / 3.0f;
width_ = 800.0f;
height_ = 600.0f;
near_clip_plane_ = 0.2f;
far_clip_plane_ = 1000.0f;
ortho_ = false;
orthoScale_ = 2.0f;
orthoCropFactor_ = -1.0f;
}
glm::mat4 Camera::GetViewMatrix() {
return glm::inverse(GetTransformationMatrix());
}
glm::mat4 Camera::GetProjectionMatrix() {
if(ortho_)
{
return glm::ortho(-orthoScale_*aspect_ratio_, orthoScale_*aspect_ratio_, -orthoScale_, orthoScale_, orthoScale_ + orthoCropFactor_, far_clip_plane_);
}
return glm::perspective(field_of_view_, aspect_ratio_, near_clip_plane_, far_clip_plane_);
}
void Camera::SetWindowSize(float width, float height) {
width_ = width;
height_ = height;
aspect_ratio_ = width/height;
}
void Camera::SetFieldOfView(float fov) {
field_of_view_ = fov * DEGREE_2_RADIANS;
}
void Camera::SetNearFarClipPlanes(const float near, const float far)
{
near_clip_plane_ = near;
far_clip_plane_ = far;
}
Camera::~Camera() {
}
glm::mat4 Camera::ProjectionMatrixForCameraIntrinsics(float width, float height,
float fx, float fy,
float cx, float cy,
float near, float far) {
const float xscale = near / fx;
const float yscale = near / fy;
const float xoffset = (cx - (width / 2.0)) * xscale;
// Color camera's coordinates has y pointing downwards so we negate this term.
const float yoffset = -(cy - (height / 2.0)) * yscale;
return glm::frustum(xscale * -width / 2.0f - xoffset,
xscale * width / 2.0f - xoffset,
yscale * -height / 2.0f - yoffset,
yscale * height / 2.0f - yoffset,
near, far);
}
} // namespace tango_gl
| 31.75 | 152 | 0.625422 | Riotpiaole |
407cf629fcf94f07c138846cc23266e7741e9941 | 7,987 | cpp | C++ | src/eval.cpp | andrew-pa/bicycle | 03a7bd1a5d08eb43cafcb6cfe4d38b3a6841895c | [
"MIT"
] | 2 | 2020-06-12T20:13:17.000Z | 2020-12-22T05:01:25.000Z | src/eval.cpp | andrew-pa/bicycle | 03a7bd1a5d08eb43cafcb6cfe4d38b3a6841895c | [
"MIT"
] | null | null | null | src/eval.cpp | andrew-pa/bicycle | 03a7bd1a5d08eb43cafcb6cfe4d38b3a6841895c | [
"MIT"
] | null | null | null | #include "eval.h"
void eval::analyzer::visit(ast::seq_stmt* s) {
s->first->visit(this);
if (s->second != nullptr) s->second->visit(this);
}
void eval::analyzer::visit(ast::block_stmt* s) {
if (s->body == nullptr) return;
instrs.push_back(std::make_shared<enter_scope_instr>());
s->body->visit(this);
instrs.push_back(std::make_shared<exit_scope_instr>());
}
void eval::analyzer::visit(ast::let_stmt* s) {
s->value->visit(this);
instrs.push_back(std::make_shared<bind_instr>(ids->at(s->identifer)));
}
void eval::analyzer::visit(ast::expr_stmt* s) {
s->expr->visit(this);
instrs.push_back(std::make_shared<discard_instr>());
}
void eval::analyzer::visit(ast::if_stmt* s) {
// compute condition
// if true
// stuff
// go to end
// if false
// other stuff
// end
s->condition->visit(this);
auto true_b_mark = new_marker();
auto false_b_mark = new_marker();
instrs.push_back(std::make_shared<if_instr>(true_b_mark, false_b_mark));
instrs.push_back(std::make_shared<marker_instr>(true_b_mark));
s->if_true->visit(this);
if (s->if_false != nullptr) {
auto end_mark = new_marker();
instrs.push_back(std::make_shared<jump_to_marker_instr>(end_mark));
instrs.push_back(std::make_shared<marker_instr>(false_b_mark));
s->if_false->visit(this);
instrs.push_back(std::make_shared<marker_instr>(end_mark));
} else {
instrs.push_back(std::make_shared<marker_instr>(false_b_mark));
}
}
void eval::analyzer::visit(ast::continue_stmt* s) {
auto start = 0;
if (s->name.has_value()) {
for (int i = loop_marker_stack.size() - 1; i >= 0; --i) {
auto loop = loop_marker_stack[i];
if (std::get<0>(loop).has_value() && std::get<0>(loop).value() == s->name.value()) {
start = std::get<1>(loop);
break;
}
}
}
else {
auto loop = loop_marker_stack[loop_marker_stack.size() - 1];
start = std::get<1>(loop);
}
instrs.push_back(std::make_shared<jump_instr>(start));
}
void eval::analyzer::visit(ast::break_stmt* s) {
auto end_mark = 0;
if (s->name.has_value()) {
for (int i = loop_marker_stack.size() - 1; i >= 0; --i) {
auto loop = loop_marker_stack[i];
if (std::get<0>(loop).has_value() && std::get<0>(loop).value() == s->name.value()) {
end_mark = std::get<2>(loop);
break;
}
}
}
else {
auto loop = loop_marker_stack[loop_marker_stack.size() - 1];
end_mark = std::get<2>(loop);
}
instrs.push_back(std::make_shared<jump_to_marker_instr>(end_mark));
}
void eval::analyzer::visit(ast::loop_stmt* s) {
auto start = instrs.size();
auto endm = new_marker();
loop_marker_stack.push_back(std::tuple(s->name, start, endm));
s->body->visit(this);
instrs.push_back(std::make_shared<jump_instr>(start));
instrs.push_back(std::make_shared<marker_instr>(endm));
loop_marker_stack.pop_back();
}
void eval::analyzer::visit(ast::return_stmt* s) {
if (s->expr != nullptr) s->expr->visit(this);
instrs.push_back(std::make_shared<ret_instr>());
}
void eval::analyzer::visit(ast::named_value* x) {
instrs.push_back(std::make_shared<get_binding_instr>(ids->at(x->identifier)));
}
void eval::analyzer::visit(ast::qualified_value* x) {
std::vector<std::string> path;
for (auto i : x->path) path.push_back(ids->at(i));
instrs.push_back(std::make_shared<get_qualified_binding_instr>(path));
}
void eval::analyzer::visit(ast::integer_value* x) {
auto v = std::make_shared<int_value>(x->value);
instrs.push_back(std::make_shared<literal_instr>(v));
}
void eval::analyzer::visit(ast::str_value* x) {
auto v = std::make_shared<str_value>(x->value);
instrs.push_back(std::make_shared<literal_instr>(v));
}
void eval::analyzer::visit(ast::bool_value* x) {
auto v = std::make_shared<bool_value>(x->value);
instrs.push_back(std::make_shared<literal_instr>(v));
}
void eval::analyzer::visit(ast::list_value* x) {
auto v = std::make_shared<list_value>();
instrs.push_back(std::make_shared<literal_instr>(v));
for (auto v : x->values) {
v->visit(this);
instrs.push_back(std::make_shared<append_list_instr>());
}
}
void eval::analyzer::visit(ast::map_value* x) {
auto v = std::make_shared<map_value>();
instrs.push_back(std::make_shared<literal_instr>(v));
for (auto v : x->values) {
auto n = std::make_shared<str_value>(ids->at(v.first));
instrs.push_back(std::make_shared<literal_instr>(n));
v.second->visit(this);
instrs.push_back(std::make_shared<set_key_instr>());
}
}
void eval::analyzer::visit(ast::binary_op* x) {
if (x->op == op_type::assign) {
auto path = std::dynamic_pointer_cast<ast::binary_op>(x->left);
if (path != nullptr && path->op == op_type::dot) {
path->left->visit(this);
auto name = ids->at(std::dynamic_pointer_cast<ast::named_value>(path->right)->identifier);
instrs.push_back(std::make_shared<literal_instr>(std::make_shared<str_value>(name)));
x->right->visit(this);
instrs.push_back(std::make_shared<set_key_instr>());
return;
}
auto index = std::dynamic_pointer_cast<ast::index_into>(x->left);
if (index != nullptr) {
index->collection->visit(this);
index->index->visit(this);
x->right->visit(this);
instrs.push_back(std::make_shared<set_index_instr>());
return;
}
auto name = std::dynamic_pointer_cast<ast::named_value>(x->left)->identifier;
x->right->visit(this);
instrs.push_back(std::make_shared<set_binding_instr>(ids->at(name)));
return;
}
else if (x->op == op_type::dot) {
x->left->visit(this);
auto name = ids->at(std::dynamic_pointer_cast<ast::named_value>(x->right)->identifier);
instrs.push_back(std::make_shared<literal_instr>(std::make_shared<str_value>(name)));
instrs.push_back(std::make_shared<get_key_instr>());
return;
}
x->left->visit(this);
x->right->visit(this);
instrs.push_back(std::make_shared<bin_op_instr>(x->op));
}
void eval::analyzer::visit(ast::logical_negation* x) {
x->value->visit(this);
instrs.push_back(std::make_shared<log_not_instr>());
}
void eval::analyzer::visit(ast::index_into* x) {
x->collection->visit(this);
x->index->visit(this);
instrs.push_back(std::make_shared<get_index_instr>());
}
void eval::analyzer::visit(ast::fn_call* x) {
if (x->args.size() > 0) {
for (int i = x->args.size() - 1; i >= 0; --i) {
x->args[i]->visit(this);
}
}
x->fn->visit(this);
instrs.push_back(std::make_shared<call_instr>(x->args.size()));
}
void eval::analyzer::visit(ast::fn_value* x) {
std::vector<std::string> arg_names;
for (auto an : x->args) arg_names.push_back(ids->at(an));
eval::analyzer anl(ids, this->root_path);
instrs.push_back(std::make_shared<make_closure_instr>(arg_names, anl.analyze(x->body), x->name));
}
void eval::analyzer::visit(ast::module_stmt* s) {
if(!s->inner_import) instrs.push_back(std::make_shared<enter_scope_instr>());
if (s->body != nullptr) {
s->body->visit(this);
} else {
auto modcode = eval::load_and_assemble(root_path / (ids->at(s->name)+".bcy"));
instrs.insert(instrs.end(),
std::make_move_iterator(modcode.begin()),
std::make_move_iterator(modcode.end()));
}
if(!s->inner_import) instrs.push_back(std::make_shared<exit_scope_as_new_module_instr>(ids->at(s->name)));
}
#include <fstream>
#include "parse.h"
std::vector<std::shared_ptr<eval::instr>> eval::load_and_assemble(const std::filesystem::path& path) {
std::ifstream input_stream(path);
tokenizer tok(&input_stream);
parser par(&tok);
std::vector<std::shared_ptr<eval::instr>> code;
while (!tok.peek().is_eof()) {
try {
auto stmt = par.next_stmt();
eval::analyzer anl(&tok.identifiers, path.parent_path());
auto part = anl.analyze(stmt);
code.insert(code.end(), std::make_move_iterator(part.begin()), std::make_move_iterator(part.end()));
}
catch (const parse_error& pe) {
std::cout << "parse error: " << pe.what()
<< " [file= " << path << "line= " << tok.line_number
<< " token type=" << pe.irritant.type << " data=" << pe.irritant.data << "]";
}
catch (const std::runtime_error& e) {
std::cout << "error: " << e.what() << " in file " << path << std::endl;
}
}
return code;
}
| 31.444882 | 107 | 0.679354 | andrew-pa |
408115ebbf873df278bc62fdb8834b2e4094ca84 | 5,029 | cpp | C++ | simulator/simulator.cpp | M-ximus/mipt-mips | ea0b131e3b70273a58311c6921998b6be4549b9c | [
"MIT"
] | null | null | null | simulator/simulator.cpp | M-ximus/mipt-mips | ea0b131e3b70273a58311c6921998b6be4549b9c | [
"MIT"
] | null | null | null | simulator/simulator.cpp | M-ximus/mipt-mips | ea0b131e3b70273a58311c6921998b6be4549b9c | [
"MIT"
] | null | null | null | /*
* simulator.cpp - interface for simulator
* Copyright 2018 MIPT-MIPS
*/
// Configurations
#include <infra/config/config.h>
#include <infra/exception.h>
// Simulators
#include <func_sim/func_sim.h>
#include <modules/core/perf_sim.h>
// ISAs
#include <mips/mips.h>
#include <risc_v/risc_v.h>
#include "simulator.h"
#include <algorithm>
namespace config {
static AliasedValue<std::string> isa = { "I", "isa", "mars", "modeled ISA"};
static AliasedSwitch disassembly_on = { "d", "disassembly", "print disassembly"};
static AliasedSwitch functional_only = { "f", "functional-only", "run functional simulation only"};
} // namespace config
void CPUModel::duplicate_all_registers_to( CPUModel* model) const
{
auto max = model->max_cpu_register();
for ( size_t i = 0; i < max; ++i)
model->write_cpu_register( i, read_cpu_register( i));
}
class SimulatorFactory {
struct Builder {
virtual std::unique_ptr<Simulator> get_funcsim( bool log) = 0;
virtual std::unique_ptr<CycleAccurateSimulator> get_perfsim() = 0;
Builder() = default;
virtual ~Builder() = default;
Builder( const Builder&) = delete;
Builder( Builder&&) = delete;
Builder& operator=( const Builder&) = delete;
Builder& operator=( Builder&&) = delete;
};
template<typename T>
struct TBuilder : public Builder {
const std::string isa;
const Endian e;
TBuilder( std::string_view isa, Endian e) : isa( isa), e( e) { }
std::unique_ptr<Simulator> get_funcsim( bool log) final { return std::make_unique<FuncSim<T>>( e, log, isa); }
std::unique_ptr<CycleAccurateSimulator> get_perfsim() final { return std::make_unique<PerfSim<T>>( e, isa); }
};
std::map<std::string, std::unique_ptr<Builder>> map;
template<typename T>
void emplace( std::string_view name, Endian e)
{
map.emplace( name, std::make_unique<TBuilder<T>>( name, e));
}
template<typename T>
void emplace_all_endians( std::string name)
{
emplace<T>( name, Endian::little);
emplace<T>( name + "le", Endian::little);
if constexpr ( std::is_base_of_v<IsMIPS, T>)
emplace<T>( name + "be", Endian::big);
}
std::string get_supported_isa_message() const
{
std::ostringstream oss;
oss << "Supported ISAs:" << std::endl;
for ( const auto& isa : get_supported_isa())
oss << "\t" << isa << std::endl;
return oss.str();
}
auto get_factory( const std::string& name) const try
{
return map.at( name).get();
}
catch ( const std::out_of_range&)
{
throw InvalidISA( name + "\n" + get_supported_isa_message());
}
SimulatorFactory()
{
emplace_all_endians<MIPSI>( "mipsI");
emplace_all_endians<MIPSII>( "mipsII");
emplace_all_endians<MIPSIII>( "mipsIII");
emplace_all_endians<MIPSIV>( "mipsIV");
emplace_all_endians<MIPS32>( "mips32");
emplace_all_endians<MIPS64>( "mips64");
emplace_all_endians<MARS>( "mars");
emplace_all_endians<MARS64>( "mars64");
emplace_all_endians<RISCV32>( "riscv32");
emplace_all_endians<RISCV64>( "riscv64");
emplace_all_endians<RISCV128>( "riscv128");
}
public:
static SimulatorFactory& get_instance()
{
static SimulatorFactory sf;
return sf;
}
std::vector<std::string> get_supported_isa() const
{
std::vector<std::string> result( map.size());
std::transform( map.begin(), map.end(), result.begin(), [](const auto& e) { return e.first; });
return result;
}
auto get_funcsim( const std::string& name, bool log) const
{
return get_factory( name)->get_funcsim( log);
}
auto get_perfsim( const std::string& name) const
{
return get_factory( name)->get_perfsim();
}
};
std::vector<std::string>
Simulator::get_supported_isa()
{
return SimulatorFactory::get_instance().get_supported_isa();
}
std::shared_ptr<Simulator>
Simulator::create_simulator( const std::string& isa, bool functional_only, bool log)
{
if ( functional_only)
return SimulatorFactory::get_instance().get_funcsim( isa, log);
return CycleAccurateSimulator::create_simulator( isa);
}
std::shared_ptr<Simulator>
Simulator::create_simulator( const std::string& isa, bool functional_only)
{
return create_simulator( isa, functional_only, false);
}
std::shared_ptr<Simulator>
Simulator::create_configured_simulator()
{
return create_simulator( config::isa, config::functional_only, config::disassembly_on);
}
std::shared_ptr<Simulator>
Simulator::create_configured_isa_simulator( const std::string& isa)
{
return create_simulator( isa, config::functional_only, config::disassembly_on);
}
std::shared_ptr<CycleAccurateSimulator>
CycleAccurateSimulator::create_simulator( const std::string& isa)
{
return SimulatorFactory::get_instance().get_perfsim( isa);
}
| 29.409357 | 118 | 0.653211 | M-ximus |
408abb005896f1833358fcc4734abc16ee18bd9c | 1,475 | hpp | C++ | lib/Util/CoutBuf.hpp | EnjoMitch/EnjoLib | 321167146657cba1497a9d3b4ffd71430f9b24b3 | [
"BSD-3-Clause"
] | 3 | 2021-06-14T15:36:46.000Z | 2022-02-28T15:16:08.000Z | lib/Util/CoutBuf.hpp | EnjoMitch/EnjoLib | 321167146657cba1497a9d3b4ffd71430f9b24b3 | [
"BSD-3-Clause"
] | 1 | 2021-07-17T07:52:15.000Z | 2021-07-17T07:52:15.000Z | lib/Util/CoutBuf.hpp | EnjoMitch/EnjoLib | 321167146657cba1497a9d3b4ffd71430f9b24b3 | [
"BSD-3-Clause"
] | 3 | 2021-07-12T14:52:38.000Z | 2021-11-28T17:10:33.000Z | #ifndef COUTBUF_H
#define COUTBUF_H
#include <Ios/Osstream.hpp>
#include <Ios/Cout.hpp>
#include <3rdParty/stdfwd.hh>
namespace EnjoLib
{
class LogBuf
{
public:
LogBuf(bool verbose = true);
virtual ~LogBuf();
void Flush();
Ostream & GetLog();
private:
//SafePtrFast<std::ostream> m_cnull;
//std::wostream m_wcnull;
Osstream m_ostr;
bool m_verbose;
};
class Log
{
public:
Log();
virtual ~Log();
Ostream & GetLog();
private:
Cout m_cout;
};
}
extern std::ostream cnull;
//extern std::wostream wcnull;
std::ostream & GetLog(bool verbose);
/// Create a buffered log object "logLocal" with optional disabled logging.
/**
The log will be displayed on the destruction of the object, but may be flushed before.
Usage:
ELOG // or ELOG(verbose)
LOG << "Text" << EnjoLib::Nl;
LOG_FLUSH // optional flushing
*/
#define ELOG(verbose) EnjoLib::LogBuf logLocal(verbose);
/// Create a buffered log object logLocal with enabled logging
#define ELO ELOG(true)
#define LOG logLocal.GetLog()
#define LOG_FLUSH logLocal.Flush()
/// Create a non buffered log object "logLocal".
/**
No need to flush it, but it needs to be wraped in braces, if it's expected to be reused.
Usage:
LOGL << "Text" << EnjoLib::Nl;
or:
{LOGL << "Text1" << EnjoLib::Nl;}
{LOGL << "Text2" << EnjoLib::Nl;}
*/
#define LOGL EnjoLib::Log logLocal; logLocal.GetLog()
#endif // COUTBUF_H
| 19.407895 | 88 | 0.650847 | EnjoMitch |
408d6ce8d45ee870b0c0f2870e5cc65eeca53ec7 | 50,562 | cpp | C++ | source/d3d11/d3d11_runtime.cpp | Kaldaien/reshade | 5dfd2eebce6a00d4c3270f3b9ba628f15c5460fa | [
"BSD-3-Clause"
] | 4 | 2017-03-23T01:52:32.000Z | 2018-10-25T00:37:06.000Z | source/d3d11/d3d11_runtime.cpp | Kaldaien/reshade | 5dfd2eebce6a00d4c3270f3b9ba628f15c5460fa | [
"BSD-3-Clause"
] | null | null | null | source/d3d11/d3d11_runtime.cpp | Kaldaien/reshade | 5dfd2eebce6a00d4c3270f3b9ba628f15c5460fa | [
"BSD-3-Clause"
] | 2 | 2017-02-28T18:10:53.000Z | 2020-08-04T02:55:35.000Z | /**
* Copyright (C) 2014 Patrick Mours. All rights reserved.
* License: https://github.com/crosire/reshade#license
*/
#include "log.hpp"
#include "d3d11_runtime.hpp"
#include "d3d11_effect_compiler.hpp"
#include "lexer.hpp"
#include "input.hpp"
#include "resource_loading.hpp"
#include "..\deps\imgui\imgui.h"
#include <algorithm>
#include <map>
#include <mutex>
#include <atlbase.h>
typedef bool (__stdcall *SK_ReShade_PresentCallback_pfn)(void *user);
typedef void (__stdcall *SK_ReShade_OnCopyResourceD3D11_pfn)(void* user, ID3D11Resource *&dest, ID3D11Resource *&source);
typedef void (__stdcall *SK_ReShade_OnClearDepthStencilViewD3D11_pfn)(void* user, ID3D11DepthStencilView *&depthstencil);
typedef void (__stdcall *SK_ReShade_OnGetDepthStencilViewD3D11_pfn)(void* user, ID3D11DepthStencilView *&depthstencil);
typedef void (__stdcall *SK_ReShade_OnSetDepthStencilViewD3D11_pfn)(void* user, ID3D11DepthStencilView *&depthstencil);
typedef void (__stdcall *SK_ReShade_OnDrawD3D11_pfn)(void* user, ID3D11DeviceContext *context, unsigned int vertices);
__declspec (dllimport)
void
SK_ReShade_InstallPresentCallback (SK_ReShade_PresentCallback_pfn fn, void* user);
__declspec (dllimport)
void
SK_ReShade_InstallDrawCallback (SK_ReShade_OnDrawD3D11_pfn fn, void* user);
__declspec (dllimport)
void
SK_ReShade_InstallSetDepthStencilViewCallback (SK_ReShade_OnSetDepthStencilViewD3D11_pfn fn, void* user);
__declspec (dllimport)
void
SK_ReShade_InstallGetDepthStencilViewCallback (SK_ReShade_OnGetDepthStencilViewD3D11_pfn fn, void* user);
__declspec (dllimport)
void
SK_ReShade_InstallClearDepthStencilViewCallback (SK_ReShade_OnClearDepthStencilViewD3D11_pfn fn, void* user);
__declspec (dllimport)
void
SK_ReShade_InstallCopyResourceCallback (SK_ReShade_OnCopyResourceD3D11_pfn fn, void* user);
struct explict_draw_s
{
void* ptr;
ID3D11RenderTargetView* pRTV;
bool pass = false;
int calls = 0;
} explicit_draw;
bool
__stdcall
SK_ReShade_PresentCallbackD3D11 (void *user)
{
const auto runtime =
(reshade::d3d11::d3d11_runtime *)((explict_draw_s *)user)->ptr;
if (! explicit_draw.pass)
{
//explicit_draw.calls = ((explict_draw_s *)user)->calls;
explicit_draw.pass = true;
runtime->on_present ();
explicit_draw.pass = false;
}
return true;
}
void
__stdcall
SK_ReShade_OnCopyResourceCallbackD3D11 (void* user, ID3D11Resource *&dest, ID3D11Resource *&source)
{
((reshade::d3d11::d3d11_runtime *)user)->on_copy_resource (dest, source);
}
void
__stdcall
SK_ReShade_OnClearDepthStencilViewD3D11 (void* user, ID3D11DepthStencilView *&depthstencil)
{
((reshade::d3d11::d3d11_runtime *)user)->on_clear_depthstencil_view (depthstencil);
}
void
__stdcall
SK_ReShade_OnGetDepthStencilViewD3D11 (void* user, ID3D11DepthStencilView *&depthstencil)
{
((reshade::d3d11::d3d11_runtime *)user)->on_get_depthstencil_view (depthstencil);
}
void
__stdcall
SK_ReShade_OnSetDepthStencilViewD3D11 (void* user, ID3D11DepthStencilView *&depthstencil)
{
((reshade::d3d11::d3d11_runtime *)user)->on_set_depthstencil_view (depthstencil);
}
void
__stdcall
SK_ReShade_OnDrawD3D11 (void* user, ID3D11DeviceContext *context, unsigned int vertices)
{
((reshade::d3d11::d3d11_runtime *)user)->on_draw_call (context, vertices);
}
_Return_type_success_ (nullptr)
IUnknown*
SK_COM_ValidateRelease (IUnknown** ppObj)
{
if ((! ppObj) || (! ReadPointerAcquire ((volatile LPVOID *)ppObj)))
return nullptr;
ULONG refs =
(*ppObj)->Release ();
assert (refs == 0);
if (refs == 0)
{
InterlockedExchangePointer ((void **)ppObj, nullptr);
}
return *ppObj;
}
IMGUI_API
void
ImGui_ImplDX11_RenderDrawLists (ImDrawData* draw_data);
#if 0
struct SK_DisjointTimerQueryD3D11
{
volatile ID3D11Query* async = nullptr;
volatile LONG active = false;
D3D11_QUERY_DATA_TIMESTAMP_DISJOINT last_results = { };
};
struct SK_TimerQueryD3D11
{
volatile ID3D11Query* async = nullptr;
volatile LONG active = FALSE;
UINT64 last_results = { };
};
struct SK_DisjointTimerQueryD3D11
{
ID3D11Query* async = nullptr;
bool active = false;
D3D11_QUERY_DATA_TIMESTAMP_DISJOINT last_results = { };
};
struct SK_TimerQueryD3D11
{
ID3D11Query* async = nullptr;
bool active = false;
UINT64 last_results = { };
};
static SK_DisjointTimerQueryD3D11 disjoint_query;
struct duration_s
{
// Timestamp at beginning
SK_TimerQueryD3D11 start;
// Timestamp at end
SK_TimerQueryD3D11 end;
};
std::vector <duration_s> timers;
// Cumulative runtime of all timers after the disjoint query
// is finished and reading these results would not stall
// the pipeline
UINT64 runtime_ticks = 0ULL;
double runtime_ms = 0.0;
double last_runtime_ms = 0.0;
#endif
namespace reshade::d3d11
{
extern DXGI_FORMAT make_format_srgb (DXGI_FORMAT format);
extern DXGI_FORMAT make_format_normal (DXGI_FORMAT format);
extern DXGI_FORMAT make_format_typeless (DXGI_FORMAT format);
d3d11_runtime::d3d11_runtime (ID3D11Device *device, IDXGISwapChain *swapchain) : runtime (device->GetFeatureLevel ()),
_device (device),
_swapchain (swapchain),
_stateblock (device)
{
assert (device != nullptr);
assert (swapchain != nullptr);
_device->GetImmediateContext (&_immediate_context);
HRESULT hr = E_FAIL;
DXGI_ADAPTER_DESC adapter_desc = { };
com_ptr <IDXGIDevice> dxgidevice = nullptr;
com_ptr <IDXGIAdapter> dxgiadapter = nullptr;
hr =
_device->QueryInterface (&dxgidevice);
assert (SUCCEEDED (hr));
hr =
dxgidevice->GetAdapter (&dxgiadapter);
assert (SUCCEEDED (hr));
hr =
dxgiadapter->GetDesc (&adapter_desc);
assert (SUCCEEDED (hr));
_vendor_id = adapter_desc.VendorId;
_device_id = adapter_desc.DeviceId;
}
bool
d3d11_runtime::init_backbuffer_texture (void)
{
// Get back buffer texture
HRESULT hr =
_swapchain->GetBuffer (0, IID_PPV_ARGS (&_backbuffer));
assert (SUCCEEDED (hr));
D3D11_TEXTURE2D_DESC texdesc = { };
texdesc.Width = _width;
texdesc.Height = _height;
texdesc.ArraySize = texdesc.MipLevels = 1;
texdesc.Format = make_format_typeless (_backbuffer_format);
texdesc.SampleDesc = { 1, 0 };
texdesc.Usage = D3D11_USAGE_DEFAULT;
texdesc.BindFlags = D3D11_BIND_RENDER_TARGET;
OSVERSIONINFOEX verinfo_windows7 = {
sizeof (OSVERSIONINFOEX), 6, 1
};
const bool is_windows7 =
VerifyVersionInfo ( &verinfo_windows7, VER_MAJORVERSION | VER_MINORVERSION,
VerSetConditionMask ( VerSetConditionMask (0, VER_MAJORVERSION, VER_EQUAL),
VER_MINORVERSION, VER_EQUAL )
) != FALSE;
//if ( _is_multisampling_enabled ||
// make_format_normal (_backbuffer_format) != _backbuffer_format ||
// (! is_windows7) )
//{
hr =
_device->CreateTexture2D (&texdesc, nullptr, &_backbuffer_resolved);
if (FAILED (hr))
{
LOG (ERROR) << "Failed to create back buffer resolve texture ("
"Width = " << texdesc.Width << ", "
"Height = " << texdesc.Height << ", "
"Format = " << texdesc.Format << ", "
"SampleCount = " << texdesc.SampleDesc.Count << ", "
"SampleQuality = " << texdesc.SampleDesc.Quality << ")! HRESULT is '" << std::hex << hr << std::dec << "'.";
return false;
}
hr =
_device->CreateRenderTargetView (_backbuffer.get (), nullptr, &_backbuffer_rtv [2]);
assert (SUCCEEDED (hr));
//}
if (! ( _is_multisampling_enabled ||
make_format_normal (_backbuffer_format) != _backbuffer_format ||
(! is_windows7) )
)
{
_backbuffer_resolved = _backbuffer;
}
// Create back buffer shader texture
texdesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
hr =
_device->CreateTexture2D (&texdesc, nullptr, &_backbuffer_texture);
if (SUCCEEDED (hr))
{
D3D11_SHADER_RESOURCE_VIEW_DESC srvdesc = { };
srvdesc.Format = make_format_normal (texdesc.Format);
srvdesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvdesc.Texture2D.MipLevels = texdesc.MipLevels;
if (SUCCEEDED(hr))
{
hr =
_device->CreateShaderResourceView (_backbuffer_texture.get (), &srvdesc, &_backbuffer_texture_srv [0]);
}
else
{
LOG(ERROR) << "Failed to create back buffer texture resource view ("
"Format = " << srvdesc.Format << ")! HRESULT is '" << std::hex << hr << std::dec << "'.";
}
srvdesc.Format = make_format_srgb (texdesc.Format);
if (SUCCEEDED(hr))
{
hr =
_device->CreateShaderResourceView (_backbuffer_texture.get (), &srvdesc, &_backbuffer_texture_srv [1]);
}
else
{
LOG(ERROR) << "Failed to create back buffer SRGB texture resource view ("
"Format = " << srvdesc.Format << ")! HRESULT is '" << std::hex << hr << std::dec << "'.";
}
}
else
{
LOG (ERROR) << "Failed to create back buffer texture ("
"Width = " << texdesc.Width << ", "
"Height = " << texdesc.Height << ", "
"Format = " << texdesc.Format << ", "
"SampleCount = " << texdesc.SampleDesc.Count << ", "
"SampleQuality = " << texdesc.SampleDesc.Quality << ")! HRESULT is '" << std::hex << hr << std::dec << "'.";
}
if (FAILED (hr))
{
return false;
}
D3D11_RENDER_TARGET_VIEW_DESC rtdesc = { };
rtdesc.Format = make_format_normal (texdesc.Format);
rtdesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
hr =
_device->CreateRenderTargetView (_backbuffer_resolved.get (), &rtdesc, &_backbuffer_rtv [0]);
if (FAILED (hr))
{
LOG (ERROR) << "Failed to create back buffer render target ("
"Format = " << rtdesc.Format << ")! HRESULT is '" << std::hex << hr << std::dec << "'.";
return false;
}
rtdesc.Format = make_format_srgb (texdesc.Format);
hr =
_device->CreateRenderTargetView (_backbuffer_resolved.get (), &rtdesc, &_backbuffer_rtv [1]);
if (FAILED (hr))
{
LOG (ERROR) << "Failed to create back buffer SRGB render target ("
"Format = " << rtdesc.Format << ")! HRESULT is '" << std::hex << hr << std::dec << "'.";
return false;
}
{
const resources::data_resource vs =
resources::load_data_resource (IDR_RCDATA1);
hr =
_device->CreateVertexShader (vs.data, vs.data_size, nullptr, &_copy_vertex_shader);
if (FAILED (hr))
{
return false;
}
const resources::data_resource ps =
resources::load_data_resource (IDR_RCDATA2);
hr =
_device->CreatePixelShader (ps.data, ps.data_size, nullptr, &_copy_pixel_shader);
if (FAILED (hr))
{
return false;
}
}
{
const D3D11_SAMPLER_DESC desc = {
D3D11_FILTER_MIN_MAG_MIP_POINT,
D3D11_TEXTURE_ADDRESS_CLAMP,
D3D11_TEXTURE_ADDRESS_CLAMP,
D3D11_TEXTURE_ADDRESS_CLAMP
};
hr =
_device->CreateSamplerState (&desc, &_copy_sampler);
if (FAILED (hr))
{
return false;
}
}
return true;
}
bool
d3d11_runtime::init_default_depth_stencil (void)
{
const D3D11_TEXTURE2D_DESC texdesc = {
_width,
_height,
1, 1,
DXGI_FORMAT_D24_UNORM_S8_UINT,
{ 1, 0 },
D3D11_USAGE_DEFAULT,
D3D11_BIND_DEPTH_STENCIL
};
com_ptr <ID3D11Texture2D> depth_stencil_texture = nullptr;
HRESULT hr =
_device->CreateTexture2D (&texdesc, nullptr, &depth_stencil_texture);
if (FAILED (hr))
{
LOG (ERROR) << "Failed to create depth stencil texture ("
"Width = " << texdesc.Width << ", "
"Height = " << texdesc.Height << ", "
"Format = " << texdesc.Format << ", "
"SampleCount = " << texdesc.SampleDesc.Count << ", "
"SampleQuality = " << texdesc.SampleDesc.Quality << ")! HRESULT is '" << std::hex << hr << std::dec << "'.";
return false;
}
hr =
_device->CreateDepthStencilView (depth_stencil_texture.get (), nullptr, &_default_depthstencil);
return SUCCEEDED (hr);
}
bool
d3d11_runtime::init_fx_resources (void)
{
D3D11_RASTERIZER_DESC desc = { };
desc.FillMode = D3D11_FILL_SOLID;
desc.CullMode = D3D11_CULL_NONE;
desc.DepthClipEnable = TRUE;
desc.SlopeScaledDepthBias = 0.0f;
desc.DepthBiasClamp = 0.0f;
return
SUCCEEDED (_device->CreateRasterizerState (&desc, &_effect_rasterizer_state));
}
bool
d3d11_runtime::on_init (const DXGI_SWAP_CHAIN_DESC &desc)
{
_width = desc.BufferDesc.Width;
_height = desc.BufferDesc.Height;
_backbuffer_format = desc.BufferDesc.Format;
_is_multisampling_enabled = desc.SampleDesc.Count > 1;
if ( (! init_backbuffer_texture ()) ||
(! init_default_depth_stencil ()) ||
(! init_fx_resources ()) )
{
return false;
}
// Clear reference count to make UnrealEngine happy
_backbuffer->Release ();
return runtime::on_init ();
}
void
d3d11_runtime::on_reset (void)
{
if (! is_initialized ())
{
return;
}
runtime::on_reset ();
// Reset reference count to make UnrealEngine happy
_backbuffer->AddRef ();
// Destroy resources
_backbuffer.reset ();
_backbuffer_resolved.reset ();
_backbuffer_texture.reset ();
_backbuffer_texture_srv [0].reset ();
_backbuffer_texture_srv [1].reset ();
_backbuffer_rtv [0].reset ();
_backbuffer_rtv [1].reset ();
_backbuffer_rtv [2].reset ();
_depthstencil.reset ();
_depthstencil_replacement.reset ();
for ( auto it : _depth_source_table ) it.first->Release ();
_depth_source_table.clear ();
_depthstencil_texture.reset ();
_depthstencil_texture_srv.reset ();
_default_depthstencil.reset ();
_copy_vertex_shader.reset ();
_copy_pixel_shader.reset ();
_copy_sampler.reset ();
_effect_rasterizer_state.reset ();
}
void
d3d11_runtime::on_reset_effect (void)
{
runtime::on_reset_effect ();
for (auto it : _effect_sampler_states)
{
it->Release ();
}
_effect_sampler_descs.clear ();
_effect_sampler_states.clear ();
_constant_buffers.clear ();
_effect_shader_resources.resize (3);
_effect_shader_resources [0] = _backbuffer_texture_srv [0].get ();
_effect_shader_resources [1] = _backbuffer_texture_srv [1].get ();
_effect_shader_resources [2] = _depthstencil_texture_srv.get ();
}
void
d3d11_runtime::on_present (void)
{
static int last_calls = 0;
static bool first = true;
if (is_initialized ())
{
SK_ReShade_InstallPresentCallback (SK_ReShade_PresentCallbackD3D11, this);
//SK_ReShade_InstallCopyResourceCallback (SK_ReShade_OnCopyResourceCallbackD3D11, this);
//SK_ReShade_InstallSetDepthStencilViewCallback (SK_ReShade_OnSetDepthStencilViewD3D11, this);
//SK_ReShade_InstallGetDepthStencilViewCallback (SK_ReShade_OnGetDepthStencilViewD3D11, this);
//SK_ReShade_InstallClearDepthStencilViewCallback (SK_ReShade_OnClearDepthStencilViewD3D11, this);
SK_ReShade_InstallDrawCallback (SK_ReShade_OnDrawD3D11, this);
first = false;
}
if ((! is_initialized ()) || _drawcalls.load () == 0)
{
return;
}
#if 0
if (is_effect_loaded ())
{
if (ReadPointerAcquire ((void **)&_techniques [0].timer.disjoint_query.async) == nullptr)
{
D3D11_QUERY_DESC query_desc {
D3D11_QUERY_TIMESTAMP_DISJOINT, 0x00
};
ID3D11Query* pQuery = nullptr;
if (SUCCEEDED (_device->CreateQuery (&query_desc, &pQuery)))
{
InterlockedExchangePointer ((void **)&_techniques [0].timer.disjoint_query.async, pQuery);
_immediate_context->Begin (pQuery);
InterlockedExchange ((volatile unsigned long *)&_techniques [0].timer.disjoint_query.active, TRUE);
}
}
}
#endif
if (explicit_draw.pass)
{
CComPtr <ID3D11Resource> pRTVRes = nullptr;
CComPtr <ID3D11RenderTargetView> pRTV = nullptr;
D3D11_TEXTURE2D_DESC tex_desc = { };
// Apply post processing
if (is_effect_loaded ())
{
CComPtr <ID3D11DepthStencilView> pDSV = nullptr;
CComPtr <ID3D11RenderTargetView> pRTVs [D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT];
_immediate_context->OMGetRenderTargets (D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, &pRTVs [0], &pDSV);
D3D11_TEXTURE2D_DESC bb_desc = { };
_backbuffer_texture.get ()->GetDesc (&bb_desc);
//pRTV = pRTVs [0];
// CComPtr <ID3D11Resource > pRTVRes = nullptr;
// pRTV->GetResource (&pRTVRes);
// CComQIPtr <ID3D11Texture2D> pRTVTex (pRTVRes);
//
// pRTVTex->GetDesc (&tex_desc);
for ( auto it : pRTVs )
{
if (it == nullptr)
continue;
D3D11_RENDER_TARGET_VIEW_DESC rt_desc = { };
it->GetDesc (&rt_desc);
if (/*make_format_typeless (rt_desc.Format) == make_format_typeless (bb_desc.Format) && */rt_desc.Texture2D.MipSlice == 0)
{
CComPtr <ID3D11Resource > pRTVRes = nullptr;
it->GetResource (&pRTVRes);
CComQIPtr <ID3D11Texture2D> pRTVTex (pRTVRes);
pRTVTex->GetDesc (&tex_desc);
if ( tex_desc.SampleDesc.Count == 1 &&
tex_desc.ArraySize == 1 &&
tex_desc.MipLevels <= 1 &&
(tex_desc.BindFlags & ( D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE ) ) )
{
pRTV = it;
break;
}
}
}
if (pRTV != nullptr)
{
// Capture device state
_stateblock.capture (_immediate_context.get ());
// Disable unused pipeline stages
_immediate_context->HSSetShader (nullptr, nullptr, 0);
_immediate_context->DSSetShader (nullptr, nullptr, 0);
_immediate_context->GSSetShader (nullptr, nullptr, 0);
const uintptr_t null = 0;
pRTV->GetResource (&pRTVRes);
D3D11_SHADER_RESOURCE_VIEW_DESC srv_desc = { };
srv_desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srv_desc.Format = tex_desc.Format;
srv_desc.Texture2D.MipLevels = 1;
CComPtr <ID3D11ShaderResourceView> pSRV = nullptr;
bool view = SUCCEEDED (_device->CreateShaderResourceView (pRTVRes, &srv_desc, &pSRV));
const auto rtv = _backbuffer_rtv [0].get ();
_immediate_context->OMSetRenderTargets (1, &rtv, nullptr);
D3D11_DEPTH_STENCIL_DESC stencil_desc = { };
stencil_desc.DepthEnable = FALSE;
stencil_desc.DepthFunc = D3D11_COMPARISON_ALWAYS;
stencil_desc.StencilEnable = FALSE;
CComPtr <ID3D11DepthStencilState> pDepthState = nullptr;
_device->CreateDepthStencilState (&stencil_desc, &pDepthState);
_immediate_context->OMSetDepthStencilState (pDepthState, 0);
_immediate_context->RSSetState (_effect_rasterizer_state.get ());
_immediate_context->IASetPrimitiveTopology (D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
_immediate_context->IASetInputLayout (nullptr);
_immediate_context->IASetVertexBuffers (0, 1, reinterpret_cast<ID3D11Buffer *const *>(&null), reinterpret_cast<const UINT *>(&null), reinterpret_cast<const UINT *>(&null));
_immediate_context->RSSetState (_effect_rasterizer_state.get ());
_immediate_context->VSSetShader (_copy_vertex_shader.get (), nullptr, 0);
_immediate_context->PSSetShader (_copy_pixel_shader.get (), nullptr, 0);
//// Setup samplers
_immediate_context->VSSetSamplers (0, static_cast <UINT> (_effect_sampler_states.size ()), _effect_sampler_states.data ());
_immediate_context->PSSetSamplers (0, static_cast <UINT> (_effect_sampler_states.size ()), _effect_sampler_states.data ());
const auto sst = _copy_sampler.get ();
if (view)
{
_immediate_context->PSSetSamplers (0, 1, &sst);
_immediate_context->PSSetShaderResources (0, 1, &pSRV);
_immediate_context->Draw (3, 0);
}
else
_immediate_context->ResolveSubresource (_backbuffer_resolved.get (), 0, pRTVRes, 0, _backbuffer_format);
_immediate_context->RSSetState (_effect_rasterizer_state.get ());
int techs =
on_present_effect ();
if (techs > 0)
{
_immediate_context->CopyResource (_backbuffer_texture.get (), _backbuffer_resolved.get ());
_immediate_context->OMSetRenderTargets (1, &pRTV, nullptr);
_immediate_context->IASetPrimitiveTopology (D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
_immediate_context->IASetInputLayout (nullptr);
_immediate_context->IASetVertexBuffers (0, 1, reinterpret_cast<ID3D11Buffer *const *>(&null), reinterpret_cast<const UINT *>(&null), reinterpret_cast<const UINT *>(&null));
_immediate_context->RSSetState (_effect_rasterizer_state.get ());
_immediate_context->VSSetShader (_copy_vertex_shader.get (), nullptr, 0);
_immediate_context->PSSetShader (_copy_pixel_shader.get (), nullptr, 0);
const auto srv = _backbuffer_texture_srv [make_format_srgb(_backbuffer_format) == _backbuffer_format].get();
_immediate_context->PSSetSamplers (0, 1, &sst);
_immediate_context->PSSetShaderResources (0, 1, &srv);
_immediate_context->Draw (3, 0);
}
// Apply previous device state
_stateblock.apply_and_release ();
explicit_draw.calls++;
}
}
}
else
{
detect_depth_source ();
// Apply presenting
runtime::on_present ();
if (last_calls == explicit_draw.calls)
{
// Apply post processing
if (is_effect_loaded ())
{
// Capture device state
_stateblock.capture (_immediate_context.get ());
// Disable unused pipeline stages
_immediate_context->HSSetShader (nullptr, nullptr, 0);
_immediate_context->DSSetShader (nullptr, nullptr, 0);
_immediate_context->GSSetShader (nullptr, nullptr, 0);
// Setup real back buffer
const auto rtv = _backbuffer_rtv [0].get ();
_immediate_context->OMSetRenderTargets (1, &rtv, nullptr);
// Resolve back buffer
if (_backbuffer_resolved != _backbuffer)
{
_immediate_context->ResolveSubresource(_backbuffer_resolved.get(), 0, _backbuffer.get(), 0, _backbuffer_format);
}
// Setup vertex input
const uintptr_t null = 0;
_immediate_context->IASetPrimitiveTopology (D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
_immediate_context->IASetInputLayout (nullptr);
_immediate_context->IASetVertexBuffers (0, 1, reinterpret_cast<ID3D11Buffer *const *>(&null), reinterpret_cast<const UINT *>(&null), reinterpret_cast<const UINT *>(&null));
_immediate_context->RSSetState (_effect_rasterizer_state.get ());
D3D11_DEPTH_STENCIL_DESC stencil_desc = { };
stencil_desc.DepthEnable = FALSE;
stencil_desc.DepthFunc = D3D11_COMPARISON_ALWAYS;
stencil_desc.StencilEnable = FALSE;
CComPtr <ID3D11DepthStencilState> pDepthState = nullptr;
_device->CreateDepthStencilState (&stencil_desc, &pDepthState);
// Setup samplers
_immediate_context->VSSetSamplers (0, static_cast <UINT> (_effect_sampler_states.size ()), _effect_sampler_states.data ());
_immediate_context->PSSetSamplers (0, static_cast <UINT> (_effect_sampler_states.size ()), _effect_sampler_states.data ());
int techs = on_present_effect ();
// Copy to back buffer
if (techs > 0 && _backbuffer_resolved != _backbuffer)
{
_immediate_context->CopyResource(_backbuffer_texture.get(), _backbuffer_resolved.get());
const auto rtv = _backbuffer_rtv[2].get();
_immediate_context->OMSetRenderTargets(1, &rtv, nullptr);
const uintptr_t null = 0;
_immediate_context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
_immediate_context->IASetInputLayout(nullptr);
_immediate_context->IASetVertexBuffers(0, 1, reinterpret_cast<ID3D11Buffer *const *>(&null), reinterpret_cast<const UINT *>(&null), reinterpret_cast<const UINT *>(&null));
_immediate_context->RSSetState(_effect_rasterizer_state.get());
_immediate_context->VSSetShader(_copy_vertex_shader.get(), nullptr, 0);
_immediate_context->PSSetShader(_copy_pixel_shader.get(), nullptr, 0);
const auto sst = _copy_sampler.get();
_immediate_context->PSSetSamplers(0, 1, &sst);
const auto srv = _backbuffer_texture_srv[make_format_srgb(_backbuffer_format) == _backbuffer_format].get();
_immediate_context->PSSetShaderResources(0, 1, &srv);
_immediate_context->Draw(3, 0);
}
// Apply previous device state
_stateblock.apply_and_release ();
}
}
#if 0
if (is_effect_loaded ())
{
if ((! _techniques [0].timer.disjoint_done) && ReadPointerAcquire ((volatile PVOID *)_techniques [0].timer.disjoint_query.async))
{
if (ReadAcquire ((volatile const LONG *)&_techniques [0].timer.disjoint_query.active))
{
_immediate_context->End ((ID3D11Asynchronous *)ReadPointerAcquire ((volatile PVOID*)&_techniques [0].timer.disjoint_query.async));
InterlockedExchange ((volatile unsigned long *)&_techniques [0].timer.disjoint_query.active, FALSE);
}
else
{
HRESULT const hr =
_immediate_context->GetData ( (ID3D11Asynchronous *)ReadPointerAcquire ((volatile PVOID*)&_techniques [0].timer.disjoint_query.async),
&_techniques [0].timer.disjoint_query.last_results,
sizeof D3D11_QUERY_DATA_TIMESTAMP_DISJOINT,
0x0 );
if (hr == S_OK)
{
((ID3D11Asynchronous *)ReadPointerAcquire ((volatile PVOID*)&_techniques [0].timer.disjoint_query.async))->Release ();
InterlockedExchangePointer ((void **)&_techniques [0].timer.disjoint_query.async, nullptr);
// Check for failure, if so, toss out the results.
if (! _techniques [0].timer.disjoint_query.last_results.Disjoint)
_techniques [0].timer.disjoint_done = true;
else
{
for (auto& technique : _techniques)
{
technique.timer.timer.start.active = 0;
technique.timer.timer.end.active = 0;
if (technique.timer.timer.start.async != nullptr)
{
SK_COM_ValidateRelease ((IUnknown **)&technique.timer.timer.start.async);
technique.timer.timer.start.async = nullptr;
}
if (technique.timer.timer.end.async != nullptr)
{
SK_COM_ValidateRelease ((IUnknown **)&technique.timer.timer.end.async);
technique.timer.timer.end.async = nullptr;
}
}
_techniques [0].timer.disjoint_done = true;
}
}
}
}
if (_techniques [0].timer.disjoint_done)
{
for (auto& technique : _techniques)
{
auto GetTimerDataStart = [](ID3D11DeviceContext* dev_ctx, duration* pDuration, bool& success) ->
UINT64
{
if (! FAILED (dev_ctx->GetData ( (ID3D11Query *)ReadPointerAcquire ((volatile PVOID *)&pDuration->start.async), &pDuration->start.last_results, sizeof UINT64, 0x00 )))
{
SK_COM_ValidateRelease ((IUnknown **)&pDuration->start.async);
success = true;
return pDuration->start.last_results;
}
success = false;
return 0;
};
auto GetTimerDataEnd = [](ID3D11DeviceContext* dev_ctx, duration* pDuration, bool& success) ->
UINT64
{
if (pDuration->end.async == nullptr)
{
success = true;
return pDuration->start.last_results;
}
if (! FAILED (dev_ctx->GetData ( (ID3D11Query *)ReadPointerAcquire ((volatile PVOID *)&pDuration->end.async), &pDuration->end.last_results, sizeof UINT64, 0x00 )))
{
SK_COM_ValidateRelease ((IUnknown **)&pDuration->end.async);
success = true;
return pDuration->end.last_results;
}
success = false;
return 0;
};
auto CalcRuntimeMS = [&](gpu_interval_timer* timer)
{
if (ReadAcquire64 ((volatile LONG64 *)&timer->runtime_ticks) != 0LL)
{
timer->runtime_ms =
1000.0 * (((double)(ULONG64)ReadAcquire64 ((volatile LONG64 *)&timer->runtime_ticks)) / (double)_techniques [0].timer.disjoint_query.last_results.Frequency);
// Filter out queries that spanned multiple frames
//
if (timer->runtime_ms > 0.0 && timer->last_runtime_ms > 0.0)
{
if (timer->runtime_ms > timer->last_runtime_ms * 100.0 || timer->runtime_ms > 12.0)
timer->runtime_ms = timer->last_runtime_ms;
}
timer->last_runtime_ms = timer->runtime_ms;
}
};
auto AccumulateRuntimeTicks = [&](ID3D11DeviceContext* dev_ctx, gpu_interval_timer* timer) ->
void
{
std::vector <duration> rejects;
InterlockedExchange64 ((volatile LONG64 *)&timer->runtime_ticks, 0LL);
bool success0 = false, success1 = false;
UINT64 time0 = 0ULL, time1 = 0ULL;
time0 = GetTimerDataEnd (dev_ctx, &timer->timer, success0);
time1 = GetTimerDataStart (dev_ctx, &timer->timer, success1);
if (success0 && success1)
InterlockedAdd64 ((volatile LONG64 *)&timer->runtime_ticks, time0 - time1);
else
rejects.push_back (timer->timer);
// If effect was cancelled ...
//{
// InterlockedExchange64 ((volatile LONG64 *)&tracker->runtime_ticks, 0LL);
// timer->runtime_ms = 0.0;
// timer->last_runtime_ms = 0.0;
//}
// Anything that fails goes back on the list and we will try again next frame
//if (! rejects.empty ())
// timer->timer = rejects [0];
};
AccumulateRuntimeTicks (_immediate_context.get (), &technique.timer);
CalcRuntimeMS (&technique.timer);
technique.average_gpu_duration.append (technique.timer.last_runtime_ms);
}
_techniques [0].timer.disjoint_done = false;
}
}
#endif
last_calls = explicit_draw.calls;
}
}
void
d3d11_runtime::on_draw_call (ID3D11DeviceContext *context, unsigned int vertices)
{
_vertices += vertices;
_drawcalls += 1;
com_ptr <ID3D11DepthStencilView> current_depthstencil = nullptr;
context->OMGetRenderTargets ( 0, nullptr,
¤t_depthstencil );
if ( current_depthstencil == nullptr ||
current_depthstencil == _default_depthstencil )
{
return;
}
if (current_depthstencil == _depthstencil_replacement)
{
current_depthstencil = _depthstencil;
}
const auto it =
_depth_source_table.find (current_depthstencil.get ());
if (it != _depth_source_table.cend () && (! it->second.invalidated))
{
it->second.drawcall_count = _drawcalls.load ();
it->second.vertices_count += vertices;
}
}
void
d3d11_runtime::on_set_depthstencil_view (ID3D11DepthStencilView *&depthstencil)
{
if ( (! _depth_source_table.count (depthstencil)) || _depth_source_table [depthstencil].invalidated )
{
D3D11_TEXTURE2D_DESC texture_desc = { };
com_ptr <ID3D11Resource> resource = nullptr;
com_ptr <ID3D11Texture2D> texture = nullptr;
depthstencil->GetResource (&resource);
if (FAILED (resource->QueryInterface (&texture)))
{
return;
}
texture->GetDesc (&texture_desc);
// Early depth stencil rejection
if ( texture_desc.Width != _width ||
texture_desc.Height != _height ||
texture_desc.SampleDesc.Count > 1 )
{
return;
}
depthstencil->AddRef ();
// Begin tracking new depth stencil
const depth_source_info info =
{ texture_desc.Width, texture_desc.Height,
0, 0,
false
};
_depth_source_table [depthstencil] = info;
}
if (_depthstencil_replacement != nullptr && depthstencil == _depthstencil)
{
depthstencil = _depthstencil_replacement.get ();
}
}
void
d3d11_runtime::on_get_depthstencil_view (ID3D11DepthStencilView *&depthstencil)
{
if ( _depthstencil_replacement != nullptr &&
depthstencil == _depthstencil_replacement )
{
depthstencil->Release ();
depthstencil =
_depthstencil.get ();
depthstencil->AddRef ();
}
}
void
d3d11_runtime::on_clear_depthstencil_view (ID3D11DepthStencilView *&depthstencil)
{
if ( _depthstencil_replacement != nullptr &&
depthstencil == _depthstencil )
{
depthstencil =
_depthstencil_replacement.get ();
}
}
void
d3d11_runtime::on_copy_resource (ID3D11Resource *&dest, ID3D11Resource *&source)
{
if (_depthstencil_replacement != nullptr)
{
com_ptr <ID3D11Resource> resource = nullptr;
_depthstencil->GetResource (&resource);
if (dest == resource)
{
dest =
_depthstencil_texture.get ();
}
if (source == resource)
{
source =
_depthstencil_texture.get ();
}
}
}
void
d3d11_runtime::capture_frame(uint8_t *buffer) const
{
if (_backbuffer_format != DXGI_FORMAT_R8G8B8A8_UNORM &&
_backbuffer_format != DXGI_FORMAT_R8G8B8A8_UNORM_SRGB &&
_backbuffer_format != DXGI_FORMAT_B8G8R8A8_UNORM &&
_backbuffer_format != DXGI_FORMAT_B8G8R8A8_UNORM_SRGB)
{
LOG (WARNING) << "Screenshots are not supported for back buffer format " << _backbuffer_format << ".";
return;
}
D3D11_TEXTURE2D_DESC texture_desc = { };
texture_desc.Width = _width;
texture_desc.Height = _height;
texture_desc.ArraySize = 1;
texture_desc.MipLevels = 1;
texture_desc.Format = _backbuffer_format;
texture_desc.SampleDesc.Count = 1;
texture_desc.Usage = D3D11_USAGE_STAGING;
texture_desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
com_ptr<ID3D11Texture2D> texture_staging;
HRESULT hr =
_device->CreateTexture2D (&texture_desc, nullptr, &texture_staging);
if (FAILED (hr))
{
LOG (ERROR) << "Failed to create staging resource for screenshot capture! HRESULT is '" << std::hex << hr << std::dec << "'.";
return;
}
_immediate_context->CopyResource ( texture_staging.get (),
_backbuffer_resolved.get () );
D3D11_MAPPED_SUBRESOURCE mapped = { };
hr =
_immediate_context->Map (texture_staging.get (), 0, D3D11_MAP_READ, 0, &mapped);
if (FAILED (hr))
{
LOG(ERROR) << "Failed to map staging resource with screenshot capture! HRESULT is '" << std::hex << hr << std::dec << "'.";
return;
}
auto mapped_data = static_cast <BYTE *> (mapped.pData);
const UINT pitch = texture_desc.Width * 4;
for (UINT y = 0; y < texture_desc.Height; y++)
{
CopyMemory (buffer, mapped_data, std::min (pitch, static_cast <UINT> (mapped.RowPitch)));
for (UINT x = 0; x < pitch; x += 4)
{
buffer [x + 3] = 0xFF;
if ( texture_desc.Format == DXGI_FORMAT_B8G8R8A8_UNORM ||
texture_desc.Format == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB )
{
std::swap (buffer [x + 0], buffer [x + 2]);
}
}
buffer += pitch;
mapped_data += mapped.RowPitch;
}
_immediate_context->Unmap (texture_staging.get (), 0);
}
bool
d3d11_runtime::load_effect (const reshadefx::syntax_tree &ast, std::string &errors)
{
return d3d11_effect_compiler (this, ast, errors, false).run ();
}
bool
d3d11_runtime::update_texture (texture &texture, const uint8_t *data)
{
if (texture.impl_reference != texture_reference::none)
{
return false;
}
const auto texture_impl =
texture.impl->as <d3d11_tex_data> ();
assert (data != nullptr);
assert (texture_impl != nullptr);
switch (texture.format)
{
case texture_format::r8:
{
std::vector <uint8_t> data2 (texture.width * texture.height);
for (size_t i = 0, k = 0; i < texture.width * texture.height * 4; i += 4, k++)
data2 [k] = data [i];
_immediate_context->UpdateSubresource ( texture_impl->texture.get (),
0, nullptr, data2.data (),
texture.width, texture.width * texture.height );
} break;
case texture_format::rg8:
{
std::vector <uint8_t> data2 (texture.width * texture.height * 2);
for (size_t i = 0, k = 0; i < texture.width * texture.height * 4; i += 4, k += 2)
data2 [k ] = data [i ],
data2 [k + 1] = data [i + 1];
_immediate_context->UpdateSubresource ( texture_impl->texture.get (),
0, nullptr, data2.data (),
texture.width * 2, texture.width * texture.height * 2 );
} break;
default:
{
_immediate_context->UpdateSubresource ( texture_impl->texture.get (),
0, nullptr, data,
texture.width * 4, texture.width * texture.height * 4 );
} break;
}
if (texture.levels > 1)
{
_immediate_context->GenerateMips (texture_impl->srv [0].get ());
}
return true;
}
void
d3d11_runtime::render_technique (const technique &technique)
{
#if 0
if (_techniques [0].timer.disjoint_query.active)
{
// Start a new query
D3D11_QUERY_DESC query_desc {
D3D11_QUERY_TIMESTAMP, 0x00
};
duration duration_;
ID3D11Query* pQuery = nullptr;
if (SUCCEEDED (_device->CreateQuery (&query_desc, &pQuery)))
{
InterlockedExchangePointer ((void **)&technique.timer.timer.start.async, pQuery);
_immediate_context->End (pQuery);
}
}
#endif
bool is_default_depthstencil_cleared = false;
// Setup shader constants
if (technique.uniform_storage_index >= 0)
{
const auto constant_buffer =
_constant_buffers [technique.uniform_storage_index].get ();
D3D11_MAPPED_SUBRESOURCE mapped = { };
const HRESULT hr =
_immediate_context->Map (constant_buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped);
if (SUCCEEDED (hr))
{
CopyMemory (mapped.pData, get_uniform_value_storage().data() + technique.uniform_storage_offset, mapped.RowPitch);
_immediate_context->Unmap (constant_buffer, 0);
}
else
{
LOG(ERROR) << "Failed to map constant buffer! HRESULT is '" << std::hex << hr << std::dec << "'!";
}
_immediate_context->VSSetConstantBuffers (0, 1, &constant_buffer);
_immediate_context->PSSetConstantBuffers (0, 1, &constant_buffer);
}
for (const auto &pass_object : technique.passes)
{
const d3d11_pass_data &pass =
*pass_object->as <d3d11_pass_data> ();
// Setup states
_immediate_context->VSSetShader (pass.vertex_shader.get (), nullptr, 0);
_immediate_context->PSSetShader (pass.pixel_shader.get (), nullptr, 0);
//if (pass.shader_resources.empty ())
// continue;
static const float blendfactor [4] = { 1.0f, 1.0f, 1.0f, 1.0f };
_immediate_context->OMSetBlendState (pass.blend_state.get (), blendfactor, D3D11_DEFAULT_SAMPLE_MASK);
_immediate_context->OMSetDepthStencilState (pass.depth_stencil_state.get (), pass.stencil_reference);
// Save back buffer of previous pass
_immediate_context->CopyResource ( _backbuffer_texture.get (),
_backbuffer_resolved.get () );
// Setup shader resources
_immediate_context->VSSetShaderResources (0, static_cast <UINT> (pass.shader_resources.size ()), pass.shader_resources.data ());
_immediate_context->PSSetShaderResources (0, static_cast <UINT> (pass.shader_resources.size ()), pass.shader_resources.data ());
// Setup render targets
if ( static_cast <UINT> (pass.viewport.Width) == _width &&
static_cast <UINT> (pass.viewport.Height) == _height )
{
_immediate_context->OMSetRenderTargets (D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, pass.render_targets, _default_depthstencil.get());
if (!is_default_depthstencil_cleared)
{
is_default_depthstencil_cleared = true;
_immediate_context->ClearDepthStencilView (_default_depthstencil.get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
}
}
else
{
_immediate_context->OMSetRenderTargets (D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, pass.render_targets, nullptr);
}
_immediate_context->RSSetViewports (1, &pass.viewport);
if (pass.clear_render_targets)
{
for (const auto target : pass.render_targets)
{
if (target != nullptr)
{
constexpr float color [4] = { 0.0f, 0.0f, 0.0f, 0.0f };
_immediate_context->ClearRenderTargetView(target, color);
}
}
}
// Draw triangle
_immediate_context->Draw (3, 0);
_vertices += 3;
_drawcalls += 1;
// Reset render targets
_immediate_context->OMSetRenderTargets ( 0, nullptr, nullptr );
// Reset shader resources
ID3D11ShaderResourceView* null [D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT] = { nullptr };
_immediate_context->VSSetShaderResources (0, static_cast <UINT> (pass.shader_resources.size ()), null);
_immediate_context->PSSetShaderResources (0, static_cast <UINT> (pass.shader_resources.size ()), null);
// Update shader resources
for (const auto resource : pass.render_target_resources)
{
if (resource == nullptr)
{
continue;
}
D3D11_SHADER_RESOURCE_VIEW_DESC resource_desc = { };
resource->GetDesc (&resource_desc);
if (resource_desc.Texture2D.MipLevels > 1)
{
_immediate_context->GenerateMips (resource);
}
}
}
#if 0
if (_techniques [0].timer.disjoint_query.active)
{
D3D11_QUERY_DESC query_desc {
D3D11_QUERY_TIMESTAMP, 0x00
};
ID3D11Query* pQuery = nullptr;
if (SUCCEEDED (_device->CreateQuery (&query_desc, &pQuery)))
{
InterlockedExchangePointer ((void **)&technique.timer.timer.end.async, pQuery);
_immediate_context->End (pQuery);
}
}
#endif
}
void
d3d11_runtime::render_imgui_draw_data (ImDrawData *draw_data)
{
ImGui_ImplDX11_RenderDrawLists (draw_data);
}
void
d3d11_runtime::detect_depth_source (void)
{
if ( _is_multisampling_enabled || _depth_source_table.empty () )
{
return;
}
depth_source_info best_info = { 0 };
ID3D11DepthStencilView *best_match = nullptr;
for (auto it = _depth_source_table.begin (); it != _depth_source_table.end ();)
{
const auto depthstencil = it->first;
auto &depthstencil_info = it->second;
if ((! depthstencil_info.invalidated) && (depthstencil->AddRef (), depthstencil->Release ()) == 1)
{
depthstencil_info.invalidated = TRUE;
depthstencil->Release ();
++it;
continue;
}
else
{
++it;
}
if (depthstencil_info.drawcall_count == 0)
{
continue;
}
if ((depthstencil_info.vertices_count * (1.2f - float(depthstencil_info.drawcall_count) / _drawcalls.load ())) >= (best_info.vertices_count * (1.2f - float(best_info.drawcall_count) / _drawcalls.load ())))
{
best_match = depthstencil;
best_info = depthstencil_info;
}
depthstencil_info.drawcall_count = depthstencil_info.vertices_count = 0;
}
static int overload_iters = 0;
if (_depth_source_table.load_factor () > 0.75f && (! (overload_iters++ % 15)))
{
concurrency::concurrent_unordered_map <ID3D11DepthStencilView *, depth_source_info> live_map;
// Trim the table
for (auto& it : _depth_source_table)
{
if (! it.second.invalidated)
{
live_map.insert (std::make_pair (it.first, it.second));
}
}
_depth_source_table.swap (live_map);
}
if (best_match != nullptr && _depthstencil != best_match)
{
create_depthstencil_replacement (best_match);
}
}
bool
d3d11_runtime::create_depthstencil_replacement (ID3D11DepthStencilView *depthstencil)
{
_depthstencil.reset ();
_depthstencil_replacement.reset ();
_depthstencil_texture.reset ();
_depthstencil_texture_srv.reset ();
if (depthstencil != nullptr)
{
_depthstencil = depthstencil;
depthstencil->GetResource (reinterpret_cast <ID3D11Resource **> (&_depthstencil_texture));
D3D11_TEXTURE2D_DESC texdesc = { };
_depthstencil_texture->GetDesc (&texdesc);
HRESULT hr = S_OK;
if ((texdesc.BindFlags & D3D11_BIND_SHADER_RESOURCE) == 0)
{
_depthstencil_texture.reset ();
switch (texdesc.Format)
{
case DXGI_FORMAT_R16_TYPELESS:
case DXGI_FORMAT_R16_FLOAT:
case DXGI_FORMAT_D16_UNORM:
texdesc.Format = DXGI_FORMAT_R16_TYPELESS;
break;
case DXGI_FORMAT_R8_UNORM:
case DXGI_FORMAT_R32_TYPELESS:
case DXGI_FORMAT_R32_FLOAT:
case DXGI_FORMAT_D32_FLOAT:
texdesc.Format = DXGI_FORMAT_R32_TYPELESS;
break;
default:
case DXGI_FORMAT_R24G8_TYPELESS:
case DXGI_FORMAT_D24_UNORM_S8_UINT:
texdesc.Format = DXGI_FORMAT_R24G8_TYPELESS;
break;
case DXGI_FORMAT_R32G8X24_TYPELESS:
case DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
texdesc.Format = DXGI_FORMAT_R32G8X24_TYPELESS;
break;
}
texdesc.BindFlags = D3D11_BIND_DEPTH_STENCIL |
D3D11_BIND_SHADER_RESOURCE;
hr =
_device->CreateTexture2D (&texdesc, nullptr, &_depthstencil_texture);
if (SUCCEEDED (hr))
{
D3D11_DEPTH_STENCIL_VIEW_DESC dsvdesc = { };
dsvdesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
switch (texdesc.Format)
{
case DXGI_FORMAT_R16_TYPELESS:
dsvdesc.Format = DXGI_FORMAT_D16_UNORM;
break;
case DXGI_FORMAT_R32_TYPELESS:
dsvdesc.Format = DXGI_FORMAT_D32_FLOAT;
break;
case DXGI_FORMAT_R24G8_TYPELESS:
dsvdesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
break;
case DXGI_FORMAT_R32G8X24_TYPELESS:
dsvdesc.Format = DXGI_FORMAT_D32_FLOAT_S8X24_UINT;
break;
}
hr =
_device->CreateDepthStencilView (_depthstencil_texture.get (), &dsvdesc, &_depthstencil_replacement);
}
}
if (FAILED (hr))
{
LOG(ERROR) << "Failed to create depth stencil replacement texture! HRESULT is '" << std::hex << hr << std::dec << "'.";
return false;
}
D3D11_SHADER_RESOURCE_VIEW_DESC srvdesc = { };
srvdesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvdesc.Texture2D.MipLevels = 1;
switch (texdesc.Format)
{
case DXGI_FORMAT_R16_TYPELESS:
srvdesc.Format = DXGI_FORMAT_R16_FLOAT;
break;
case DXGI_FORMAT_R32_TYPELESS:
srvdesc.Format = DXGI_FORMAT_R32_FLOAT;
break;
case DXGI_FORMAT_R24G8_TYPELESS:
srvdesc.Format = DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
break;
case DXGI_FORMAT_R32G8X24_TYPELESS:
srvdesc.Format = DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS;
break;
}
hr =
_device->CreateShaderResourceView (_depthstencil_texture.get (), &srvdesc, &_depthstencil_texture_srv);
if (FAILED (hr))
{
LOG (ERROR) << "Failed to create depth stencil replacement resource view! HRESULT is '" << std::hex << hr << std::dec << "'.";
return false;
}
if (_depthstencil != _depthstencil_replacement)
{
// Update auto depth stencil
com_ptr <ID3D11DepthStencilView> current_depthstencil = nullptr;
ID3D11RenderTargetView *targets [D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT] = { nullptr };
_immediate_context->OMGetRenderTargets (D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, targets, ¤t_depthstencil);
if (current_depthstencil != nullptr && current_depthstencil == _depthstencil)
{
_immediate_context->OMSetRenderTargets (D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, targets, _depthstencil_replacement.get ());
}
for (auto& target : targets)
{
if (target != nullptr)
{
target->Release ();
}
}
}
}
// Update effect textures
_effect_shader_resources [2] = _depthstencil_texture_srv.get ();
for (const auto &technique : _techniques)
for (const auto &pass : technique.passes)
pass->as <d3d11_pass_data> ()->shader_resources [2] = _depthstencil_texture_srv.get ();
return true;
}
} | 31.019632 | 208 | 0.632095 | Kaldaien |
40916bc0026863bc9ac779a5c3456633dc8a3fbf | 715 | hpp | C++ | src/pixelwriter.hpp | intbeam/dos-rpg-game | 7b2ee87d00319da609b61f054ebf4eed34714768 | [
"MIT"
] | 2 | 2021-01-23T19:22:53.000Z | 2021-09-15T10:39:41.000Z | src/pixelwriter.hpp | intbeam/dos-rpg-game | 7b2ee87d00319da609b61f054ebf4eed34714768 | [
"MIT"
] | null | null | null | src/pixelwriter.hpp | intbeam/dos-rpg-game | 7b2ee87d00319da609b61f054ebf4eed34714768 | [
"MIT"
] | null | null | null | #ifndef PIXELWRITER_HPP
#define PIXELWRITER_HPP
#include "displayadapter.hpp"
#define PACKET_SINGLE_COLOR 0
#define PACKET_SOURCE_COPY 1
#define PACKET_SKIP 2
#define PACKET_NEXT_LINE 3
typedef struct pixel_packet
{
int count;
int value;
void *data;
int type;
} pixel_packet;
class PixelWriter
{
protected:
surface_rect dimensions;
int line_length;
public:
PixelWriter(surface_rect dimensions);
void set_line_length(int width);
virtual void write_pixeldata(int x_origin, int y_origin, const pixel_packet *operations, int packet_count) = 0;
virtual void copy_line(int x_origin, int y_origin, void *source, int numpixels) = 0;
};
#endif
| 20.428571 | 119 | 0.718881 | intbeam |
40922616eb2419a55194d539c52fe3ebe134ba23 | 3,974 | cpp | C++ | common/src/ttime.cpp | jangmys/PBBPerm | c13ad1045d0c7a36fd8d8ace728410fee38d70a4 | [
"MIT"
] | null | null | null | common/src/ttime.cpp | jangmys/PBBPerm | c13ad1045d0c7a36fd8d8ace728410fee38d70a4 | [
"MIT"
] | null | null | null | common/src/ttime.cpp | jangmys/PBBPerm | c13ad1045d0c7a36fd8d8ace728410fee38d70a4 | [
"MIT"
] | null | null | null | #include <time.h>
#include <iostream>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include "../include/ttime.h"
#include "../include/arguments.h"
#include "../include/log.h"
// ___________________________________________
ttime::ttime()
{
period_set(CHECKPOINT_TTIME, arguments::checkpointv);
// std::cout<<"lasts 1 "<<arguments::checkpointv<<" "<<lasts[CHECKPOINT_TTIME]<<" "<<periods[CHECKPOINT_TTIME]<<std::endl;
period_set(WORKER_BALANCING, arguments::balancingv);
// std::cout<<"lasts 2 "<<lasts[WORKER_BALANCING]<<" "<<periods[WORKER_BALANCING]<<std::endl;
processRequest = new mytimer();
masterWalltime = new mytimer();
wall = new mytimer();
update = new mytimer();
split = new mytimer();
test = new mytimer();
workerExploretime = new mytimer();
pthread_mutex_init(&mutex_lasttime, NULL);
// printElapsed(wserver,"WSERVER");
}
ttime::~ttime()
{
delete processRequest;
delete masterWalltime;
delete wall;
delete update;
delete split;
}
void ttime::reset()
{
wall->isOn=false;
wall->elapsed.tv_sec=0;
wall->elapsed.tv_nsec=0;
processRequest->isOn=false;
processRequest->elapsed.tv_sec=0;
processRequest->elapsed.tv_nsec=0;
// wall.tv_nsec=0;
masterWalltime->isOn=false;
masterWalltime->elapsed.tv_sec=0;
masterWalltime->elapsed.tv_nsec=0;
// masterWalltime.tv_nsec=0;
// processRequest.tv_sec=0;
// processRequest.tv_nsec=0;
}
time_t
ttime::time_get()
{
time_t tmp;
time(&tmp);
return tmp;
}
void
ttime::wait(int index)
{
srand48(getpid());
double t = (unsigned int) (periods[index] * 1.0) * drand48();
std::cout << (unsigned int) t << std::endl << std::flush;
std::cout << "debut" << std::endl << std::flush;
sleep((unsigned int) t);
std::cout << "fin" << std::endl << std::flush;
}
// ___________________________________________
void
ttime::period_set(int index, time_t t)
{
srand48(getpid());
lasts[index] = (time_t) (time_get() - (t * 1.0) * drand48());
periods[index] = t;
}
bool
ttime::period_passed(int index)
{
time_t tmp = time_get();
// std::cout<<"time? "<<tmp<<"\t"<<lasts[index]<<"\t"<<periods[index]<<std::endl<<std::flush;
if ((tmp - lasts[index]) < periods[index]) return false;
// multi-core worker threads execute this function...
pthread_mutex_lock(&mutex_lasttime);
lasts[index] = tmp;
// std::cout<<"PASSED "<<lasts[index]<<"\n"<<std::flush;
pthread_mutex_unlock(&mutex_lasttime);
return true;
}
// ======================================
void
ttime::on(mytimer * t)
{
t->isOn = true;
clock_gettime(CLOCK_MONOTONIC, &t->start);
}
void
ttime::off(mytimer * t)
{
clock_gettime(CLOCK_MONOTONIC, &t->stop);
struct timespec diff = subtractTime(t->stop, t->start);
if (t->isOn) t->elapsed = addTime(t->elapsed, diff);
t->isOn = false;
}
void
ttime::printElapsed(mytimer * t, const char * name)
{
printf("%s\t:\t %lld.%.9ld\n", name, (long long) t->elapsed.tv_sec, t->elapsed.tv_nsec);
}
void
ttime::logElapsed(mytimer * t, const char * name)
{
FILE_LOG(logINFO) << name << "\t:" << (long long) t->elapsed.tv_sec << "." << t->elapsed.tv_nsec;
}
float
ttime::divide(mytimer * t1, mytimer * t2)
{
return (t1->elapsed.tv_sec + t1->elapsed.tv_nsec / 1e9) / (t2->elapsed.tv_sec + t2->elapsed.tv_nsec / 1e9);
}
float
ttime::masterLoadPerc()
{
return 100.0 * divide(masterWalltime, wall);
}
timespec
ttime::subtractTime(struct timespec t2, struct timespec t1)
{
t2.tv_sec -= t1.tv_sec;
t2.tv_nsec -= t1.tv_nsec;
while (t2.tv_nsec < 0) {
t2.tv_sec--;
t2.tv_nsec += NSECS;
}
return t2;
}
timespec
ttime::addTime(struct timespec t1, struct timespec t2)
{
t1.tv_sec += t2.tv_sec;
t1.tv_nsec += t2.tv_nsec;
while (t1.tv_nsec > NSECS) {
t1.tv_sec++;
t1.tv_nsec -= NSECS;
}
return t1;
}
| 22.451977 | 126 | 0.627831 | jangmys |
4099ed056428ea6cbf70361a8417861140a5bfa9 | 1,001 | cpp | C++ | test/sandbox/hash_map/foldable/foldr.cpp | rbock/hana | 2b76377f91a5ebe037dea444e4eaabba6498d3a8 | [
"BSL-1.0"
] | 2 | 2015-05-07T14:29:13.000Z | 2015-07-04T10:59:46.000Z | test/sandbox/hash_map/foldable/foldr.cpp | rbock/hana | 2b76377f91a5ebe037dea444e4eaabba6498d3a8 | [
"BSL-1.0"
] | null | null | null | test/sandbox/hash_map/foldable/foldr.cpp | rbock/hana | 2b76377f91a5ebe037dea444e4eaabba6498d3a8 | [
"BSL-1.0"
] | null | null | null | /*
@copyright Louis Dionne 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#include <boost/hana/detail/sandbox/hash_map.hpp>
#include <boost/hana/detail/assert.hpp>
#include <boost/hana/detail/constexpr.hpp>
#include <boost/hana/functional.hpp>
#include <boost/hana/integral.hpp>
#include <boost/hana/list/instance.hpp>
#include <boost/hana/pair.hpp>
using namespace boost::hana;
BOOST_HANA_CONSTEXPR_LAMBDA auto check_fold = [](auto ...pairs) {
auto values = fmap(second, list(pairs...));
auto result = foldr(hash_map(pairs...), list(), cons);
BOOST_HANA_CONSTANT_ASSERT(elem(permutations(values), result));
};
template <int k, int v>
BOOST_HANA_CONSTEXPR_LAMBDA auto p = pair(int_<k>, int_<v>);
int main() {
check_fold();
check_fold(p<1, 1>);
check_fold(p<1, 1>, p<2, 2>);
check_fold(p<1, 1>, p<2, 2>, p<3, 3>);
check_fold(p<1, 1>, p<2, 2>, p<3, 3>, p<4, 4>);
}
| 29.441176 | 78 | 0.689311 | rbock |
40a40d6b1d333dcb37f7659c3058c4fb08b7c1f1 | 10,277 | cpp | C++ | test/TestOramReadPathEvictionRW.cpp | young-du/PathORAM | 23d18b23153adf2e4a689e26d4bd05dc7db2497e | [
"MIT"
] | 9 | 2020-08-01T22:00:47.000Z | 2021-11-08T09:44:18.000Z | test/TestOramReadPathEvictionRW.cpp | young-du/PathORAM | 23d18b23153adf2e4a689e26d4bd05dc7db2497e | [
"MIT"
] | null | null | null | test/TestOramReadPathEvictionRW.cpp | young-du/PathORAM | 23d18b23153adf2e4a689e26d4bd05dc7db2497e | [
"MIT"
] | 5 | 2020-06-24T19:23:57.000Z | 2022-01-24T14:52:48.000Z | #include "catch.h"
#include "Bucket.h"
#include "ServerStorage.h"
#include "OramInterface.h"
#include "RandForOramInterface.h"
#include "RandomForOram.h"
#include "UntrustedStorageInterface.h"
#include "OramReadPathEviction.h"
#include "OramReadPathEviction.h"
int* sampleDataReadPathEviction(int i) {
int* newArray = new int[Block::BLOCK_SIZE];
for (int j = 0; j < Block::BLOCK_SIZE; ++j) {
newArray[j] = i;
}
return newArray;
}
TEST_CASE("Test ORAM with read path eviction read very small numBlocks")
{
int bucketSize = 2;
int numBlocks = 1;
Bucket::setMaxSize(bucketSize);
UntrustedStorageInterface* storage = new ServerStorage();
RandForOramInterface* random = new RandomForOram();
OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks);
int bound = numBlocks;
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks));
}
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL);
for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) {
int temp = accessed[j];
REQUIRE(temp == i%numBlocks);
}
}
Bucket::resetState();
ServerStorage::is_initialized = false;
ServerStorage::is_capacity_set = false;
RandomForOram::is_initialized = false;
RandomForOram::bound = -1;
}
TEST_CASE("Test ORAM with read path eviction read small numBlocks")
{
int bucketSize = 2;
int numBlocks = 32;
Bucket::setMaxSize(bucketSize);
UntrustedStorageInterface* storage = new ServerStorage();
RandForOramInterface* random = new RandomForOram();
OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks);
int bound = numBlocks;
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks));
}
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL);
for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) {
int temp = accessed[j];
REQUIRE(temp == i%numBlocks);
}
}
Bucket::resetState();
ServerStorage::is_initialized = false;
ServerStorage::is_capacity_set = false;
RandomForOram::is_initialized = false;
RandomForOram::bound = -1;
}
TEST_CASE("Test ORAM with read path eviction read larger numBlocks")
{
int bucketSize = 2;
int numBlocks = 1024;
Bucket::setMaxSize(bucketSize);
UntrustedStorageInterface* storage = new ServerStorage();
RandForOramInterface* random = new RandomForOram();
OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks);
int bound = numBlocks;
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks));
}
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL);
for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) {
int temp = accessed[j];
REQUIRE(temp == i%numBlocks);
}
}
Bucket::resetState();
ServerStorage::is_initialized = false;
ServerStorage::is_capacity_set = false;
RandomForOram::is_initialized = false;
RandomForOram::bound = -1;
}
TEST_CASE("Test ORAM with read path eviction read numBlocks not power of 2")
{
int bucketSize = 2;
int numBlocks = 30;
Bucket::setMaxSize(bucketSize);
UntrustedStorageInterface* storage = new ServerStorage();
RandForOramInterface* random = new RandomForOram();
OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks);
int bound = numBlocks;
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks));
}
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL);
for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) {
int temp = accessed[j];
REQUIRE(temp == i%numBlocks);
}
}
Bucket::resetState();
ServerStorage::is_initialized = false;
ServerStorage::is_capacity_set = false;
RandomForOram::is_initialized = false;
RandomForOram::bound = -1;
}
TEST_CASE("Test ORAM with read path eviction read very small numBlocks, bucketSize = 4")
{
int bucketSize = 4;
int numBlocks = 1;
Bucket::setMaxSize(bucketSize);
UntrustedStorageInterface* storage = new ServerStorage();
RandForOramInterface* random = new RandomForOram();
OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks);
int bound = numBlocks;
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks));
}
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL);
for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) {
int temp = accessed[j];
REQUIRE(temp == i%numBlocks);
}
}
Bucket::resetState();
ServerStorage::is_initialized = false;
ServerStorage::is_capacity_set = false;
RandomForOram::is_initialized = false;
RandomForOram::bound = -1;
}
TEST_CASE("Test ORAM with read path eviction read small numBlocks, bucketSize = 4")
{
int bucketSize = 4;
int numBlocks = 32;
Bucket::setMaxSize(bucketSize);
UntrustedStorageInterface* storage = new ServerStorage();
RandForOramInterface* random = new RandomForOram();
OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks);
int bound = numBlocks;
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks));
}
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL);
for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) {
int temp = accessed[j];
REQUIRE(temp == i%numBlocks);
}
}
Bucket::resetState();
ServerStorage::is_initialized = false;
ServerStorage::is_capacity_set = false;
RandomForOram::is_initialized = false;
RandomForOram::bound = -1;
}
TEST_CASE("Test ORAM with read path eviction read larger numBlocks, bucketSize = 4")
{
int bucketSize = 4;
int numBlocks = 1024;
Bucket::setMaxSize(bucketSize);
UntrustedStorageInterface* storage = new ServerStorage();
RandForOramInterface* random = new RandomForOram();
OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks);
int bound = numBlocks;
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks));
}
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL);
for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) {
int temp = accessed[j];
REQUIRE(temp == i%numBlocks);
}
}
Bucket::resetState();
ServerStorage::is_initialized = false;
ServerStorage::is_capacity_set = false;
RandomForOram::is_initialized = false;
RandomForOram::bound = -1;
}
TEST_CASE("Test ORAM with read path eviction read numBlocks not power of 2, bucketSize = 4")
{
int bucketSize = 4;
int numBlocks = 30;
Bucket::setMaxSize(bucketSize);
UntrustedStorageInterface* storage = new ServerStorage();
RandForOramInterface* random = new RandomForOram();
OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks);
int bound = numBlocks;
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks));
}
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL);
for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) {
int temp = accessed[j];
REQUIRE(temp == i%numBlocks);
}
}
Bucket::resetState();
ServerStorage::is_initialized = false;
ServerStorage::is_capacity_set = false;
RandomForOram::is_initialized = false;
RandomForOram::bound = -1;
}
// Uncomment the below test case to run for when the number of blocks is very large (=2^20).
/*
TEST_CASE("Test ORAM read path eviction read very large numBlocks", "[setup_det2]")
{
int bucketSize = 2;
int numBlocks = 1048576;
Bucket::setMaxSize(bucketSize);
UntrustedStorageInterface* storage = new ServerStorage();
RandForOramInterface* random = new RandomForOram();
OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks);
int bound = numBlocks;
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks));
}
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL);
for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) {
int temp = accessed[j];
REQUIRE(temp == i%numBlocks);
}
}
Bucket::resetState();
ServerStorage::is_initialized = false;
ServerStorage::is_capacity_set = false;
RandomForOram::is_initialized = false;
RandomForOram::bound = -1;
}
*/
| 29.113314 | 126 | 0.637054 | young-du |
40a6f0044b675d29396de67bc5154e30b823347c | 967 | cpp | C++ | week1/Arrays/Rotate Array without using extraSpace.cpp | rishabhrathore055/gfg-11-weeks-workshop-on-DSA | 052039bfbe3ae261740fc73d50f32528ddd49e6a | [
"MIT"
] | 9 | 2021-08-01T16:17:04.000Z | 2022-01-22T19:51:18.000Z | week1/Arrays/Rotate Array without using extraSpace.cpp | rishabhrathore055/gfg-11-weeks-workshop-on-DSA | 052039bfbe3ae261740fc73d50f32528ddd49e6a | [
"MIT"
] | null | null | null | week1/Arrays/Rotate Array without using extraSpace.cpp | rishabhrathore055/gfg-11-weeks-workshop-on-DSA | 052039bfbe3ae261740fc73d50f32528ddd49e6a | [
"MIT"
] | 1 | 2021-08-30T12:26:11.000Z | 2021-08-30T12:26:11.000Z | #include<bits/stdc++.h>
using namespace std;
class Solution {
public:
void reverseArr(int arr[],int start,int end)
{
while(start<end)
{
swap(arr[start],arr[end]);
start++;
end--;
}
}
void rotateArr(int arr[],int d, int n)
{
d=d%n;
if(d==0) return;
reverseArr(arr,0,n-1);
reverseArr(arr,0,d-1);
reverseArr(arr,d,n-1);
}
};
int main() {
int t;
//taking testcases
cin >> t;
while(t--){
int n, d;
//input n and d
cin >> n >> d;
int arr[n];
//inserting elements in the array
for(int i = 0; i < n; i++){
cin >> arr[i];
}
Solution ob;
//calling rotateArr() function
ob.rotateArr(arr, d,n);
//printing the elements of the array
for(int i =0;i<n;i++){
cout << arr[i] << " ";
}
cout << endl;
}
return 0;
} // } Driver Code Ends
| 16.964912 | 48 | 0.463289 | rishabhrathore055 |
40ab556d22b4cd023760f114b916061bc55a866a | 1,204 | cpp | C++ | src/main/cpp/commands/SetBallHolder.cpp | Team7433/2021InfiniteRecharge | c14d3a06347cdafa22443298fdc12b9406bf6312 | [
"BSD-3-Clause"
] | null | null | null | src/main/cpp/commands/SetBallHolder.cpp | Team7433/2021InfiniteRecharge | c14d3a06347cdafa22443298fdc12b9406bf6312 | [
"BSD-3-Clause"
] | null | null | null | src/main/cpp/commands/SetBallHolder.cpp | Team7433/2021InfiniteRecharge | c14d3a06347cdafa22443298fdc12b9406bf6312 | [
"BSD-3-Clause"
] | null | null | null | /*----------------------------------------------------------------------------*/
/* Copyright (c) 2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "commands/SetBallHolder.h"
SetBallHolder::SetBallHolder(BallHolder * ballholder, double indexer, double magazine) {
AddRequirements({ballholder});
m_indexerTarget = indexer;
m_magazineTarget = magazine;
m_ballholder = ballholder;
}
// Called when the command is initially scheduled.
void SetBallHolder::Initialize() {
m_ballholder->SetIndexer(m_indexerTarget);
m_ballholder->SetMagazine(m_magazineTarget);
}
// Called repeatedly when this Command is scheduled to run
void SetBallHolder::Execute() {}
// Called once the command ends or is interrupted.
void SetBallHolder::End(bool interrupted) {}
// Returns true when the command should end.
bool SetBallHolder::IsFinished() { return true; }
| 38.83871 | 88 | 0.596346 | Team7433 |
40ad55f29ea62bc0faf20b0fdd64a7ce4cc67377 | 3,654 | cpp | C++ | Implementation/Core/amc_parameterhandler.cpp | FabianSpangler/AutodeskMachineControlFramework | da257a4a609edbbdf3d7c5d834d61f8555c68e09 | [
"BSD-3-Clause"
] | null | null | null | Implementation/Core/amc_parameterhandler.cpp | FabianSpangler/AutodeskMachineControlFramework | da257a4a609edbbdf3d7c5d834d61f8555c68e09 | [
"BSD-3-Clause"
] | null | null | null | Implementation/Core/amc_parameterhandler.cpp | FabianSpangler/AutodeskMachineControlFramework | da257a4a609edbbdf3d7c5d834d61f8555c68e09 | [
"BSD-3-Clause"
] | null | null | null | /*++
Copyright (C) 2020 Autodesk Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Autodesk Inc. nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL AUTODESK INC. BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "amc_parameterhandler.hpp"
#include "libmc_interfaceexception.hpp"
#define AMC_MAXPARAMETERGROUPCOUNT (1024 * 1024)
namespace AMC {
CParameterHandler::CParameterHandler()
{
m_DataStore = std::make_shared <CParameterGroup>();
}
CParameterHandler::~CParameterHandler()
{
}
bool CParameterHandler::hasGroup(const std::string& sName)
{
std::lock_guard <std::mutex> lockGuard(m_Mutex);
auto iter = m_Groups.find(sName);
return (iter != m_Groups.end());
}
void CParameterHandler::addGroup(PParameterGroup pGroup)
{
std::lock_guard <std::mutex> lockGuard(m_Mutex);
if (pGroup.get() == nullptr)
throw ELibMCInterfaceException(LIBMC_ERROR_INVALIDPARAM);
auto sName = pGroup->getName();
if (m_Groups.find(sName) != m_Groups.end())
throw ELibMCInterfaceException(LIBMC_ERROR_DUPLICATEPARAMETERGROUPNAME);
if (m_GroupList.size() >= AMC_MAXPARAMETERGROUPCOUNT)
throw ELibMCInterfaceException(LIBMC_ERROR_TOOMANYPARAMETERGROUPS);
m_Groups.insert(std::make_pair(sName, pGroup));
m_GroupList.push_back(pGroup);
}
PParameterGroup CParameterHandler::addGroup(const std::string& sName, const std::string& sDescription)
{
PParameterGroup pGroup = std::make_shared<CParameterGroup>(sName, sDescription);
addGroup(pGroup);
return pGroup;
}
uint32_t CParameterHandler::getGroupCount()
{
std::lock_guard <std::mutex> lockGuard(m_Mutex);
return (uint32_t)m_GroupList.size();
}
CParameterGroup* CParameterHandler::getGroup(const uint32_t nIndex)
{
std::lock_guard <std::mutex> lockGuard(m_Mutex);
if (nIndex >= m_GroupList.size())
throw ELibMCInterfaceException(LIBMC_ERROR_INVALIDINDEX);
return m_GroupList[nIndex].get();
}
CParameterGroup* CParameterHandler::findGroup(const std::string& sName, const bool bFailIfNotExisting)
{
std::lock_guard <std::mutex> lockGuard(m_Mutex);
auto iter = m_Groups.find(sName);
if (iter != m_Groups.end())
return iter->second.get();
if (bFailIfNotExisting)
throw ELibMCInterfaceException(LIBMC_ERROR_PARAMETERGROUPNOTFOUND);
return nullptr;
}
CParameterGroup* CParameterHandler::getDataStore()
{
return m_DataStore.get();
}
}
| 28.771654 | 103 | 0.769294 | FabianSpangler |
40ae7e2ea8c1874ba95f3a3ee5ef419fa784e7a2 | 2,023 | cpp | C++ | ares/ws/cartridge/io.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 153 | 2020-07-25T17:55:29.000Z | 2021-10-01T23:45:01.000Z | ares/ws/cartridge/io.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 245 | 2021-10-08T09:14:46.000Z | 2022-03-31T08:53:13.000Z | ares/ws/cartridge/io.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 44 | 2020-07-25T08:51:55.000Z | 2021-09-25T16:09:01.000Z | auto Cartridge::readIO(n16 address) -> n8 {
n8 data;
switch(address) {
case 0x00c0: //BANK_ROM2
data = io.romBank2;
break;
case 0x00c1: //BANK_SRAM
data = io.sramBank;
break;
case 0x00c2: //BANK_ROM0
data = io.romBank0;
break;
case 0x00c3: //BANK_ROM1
data = io.romBank1;
break;
case 0x00c4: //EEP_DATALO
data = eeprom.read(EEPROM::DataLo);
break;
case 0x00c5: //EEP_DATAHI
data = eeprom.read(EEPROM::DataHi);
break;
case 0x00c6: //EEP_ADDRLO
data = eeprom.read(EEPROM::AddressLo);
break;
case 0x00c7: //EEP_ADDRHI
data = eeprom.read(EEPROM::AddressHi);
break;
case 0x00c8: //EEP_STATUS
data = eeprom.read(EEPROM::Status);
break;
case 0x00ca: //RTC_STATUS
data = rtc.status();
break;
case 0x00cb: //RTC_DATA
data = rtc.read();
break;
case 0x00cc: //GPO_EN
data = io.gpoEnable;
break;
case 0x00cd: //GPO_DATA
data = io.gpoData;
break;
}
return data;
}
auto Cartridge::writeIO(n16 address, n8 data) -> void {
switch(address) {
case 0x00c0: //BANK_ROM2
io.romBank2 = data;
break;
case 0x00c1: //BANK_SRAM
io.sramBank = data;
break;
case 0x00c2: //BANK_ROM0
io.romBank0 = data;
break;
case 0x00c3: //BANK_ROM1
io.romBank1 = data;
break;
case 0x00c4: //EEP_DATALO
eeprom.write(EEPROM::DataLo, data);
break;
case 0x00c5: //EEP_DATAHI
eeprom.write(EEPROM::DataHi, data);
break;
case 0x00c6: //EEP_ADDRLO
eeprom.write(EEPROM::AddressLo, data);
break;
case 0x00c7: //EEP_ADDRHI
eeprom.write(EEPROM::AddressHi, data);
break;
case 0x00c8: //EEP_CMD
eeprom.write(EEPROM::Command, data);
break;
case 0x00ca: //RTC_CMD
rtc.execute(data);
break;
case 0x00cb: //RTC_DATA
rtc.write(data);
break;
case 0x00cc: //GPO_EN
io.gpoEnable = data;
break;
case 0x00cd: //GPO_DATA
io.gpoData = data;
break;
}
return;
}
| 16.581967 | 55 | 0.610479 | CasualPokePlayer |
40b1260ec98ef4fc9580894e01d570ab57783b71 | 19,222 | cpp | C++ | src/vm/assemblynativeresource.cpp | danmosemsft/coreclr | 04a3d11e4eecec2a4b7dcc81ab1575a57e30e3e2 | [
"MIT"
] | 6 | 2017-09-22T06:55:45.000Z | 2021-07-02T07:07:08.000Z | src/vm/assemblynativeresource.cpp | danmosemsft/coreclr | 04a3d11e4eecec2a4b7dcc81ab1575a57e30e3e2 | [
"MIT"
] | 2 | 2018-07-13T00:48:13.000Z | 2019-02-27T16:19:30.000Z | src/vm/assemblynativeresource.cpp | danmosemsft/coreclr | 04a3d11e4eecec2a4b7dcc81ab1575a57e30e3e2 | [
"MIT"
] | 2 | 2020-01-16T10:14:30.000Z | 2020-02-09T08:48:51.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
////////////////////////////////////////////////////////////////////////////////
// ResFile.CPP
#include "common.h"
#include "assemblynativeresource.h"
#include <limits.h>
#ifndef CP_WINUNICODE
#define CP_WINUNICODE 1200
#endif
#ifndef MAKEINTRESOURCE
#define MAKEINTRESOURCE MAKEINTRESOURCEW
#endif
Win32Res::Win32Res()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
}
CONTRACTL_END
m_szFile = NULL;
m_Icon = NULL;
int i;
for (i = 0; i < NUM_VALUES; i++)
m_Values[i] = NULL;
for (i = 0; i < NUM_VALUES; i++)
m_Values[i] = NULL;
m_fDll = false;
m_pData = NULL;
m_pCur = NULL;
m_pEnd = NULL;
}
Win32Res::~Win32Res()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
}
CONTRACTL_END
m_szFile = NULL;
m_Icon = NULL;
int i;
for (i = 0; i < NUM_VALUES; i++)
m_Values[i] = NULL;
for (i = 0; i < NUM_VALUES; i++)
m_Values[i] = NULL;
m_fDll = false;
if (m_pData)
delete [] m_pData;
m_pData = NULL;
m_pCur = NULL;
m_pEnd = NULL;
}
//*****************************************************************************
// Initializes the structures with version information.
//*****************************************************************************
VOID Win32Res::SetInfo(
LPCWSTR szFile,
LPCWSTR szTitle,
LPCWSTR szIconName,
LPCWSTR szDescription,
LPCWSTR szCopyright,
LPCWSTR szTrademark,
LPCWSTR szCompany,
LPCWSTR szProduct,
LPCWSTR szProductVersion,
LPCWSTR szFileVersion,
LCID lcid,
BOOL fDLL)
{
STANDARD_VM_CONTRACT;
_ASSERTE(szFile != NULL);
m_szFile = szFile;
if (szIconName && szIconName[0] != 0)
m_Icon = szIconName; // a non-mepty string
#define NonNull(sz) (sz == NULL || *sz == W('\0') ? W(" ") : sz)
m_Values[v_Description] = NonNull(szDescription);
m_Values[v_Title] = NonNull(szTitle);
m_Values[v_Copyright] = NonNull(szCopyright);
m_Values[v_Trademark] = NonNull(szTrademark);
m_Values[v_Product] = NonNull(szProduct);
m_Values[v_ProductVersion] = NonNull(szProductVersion);
m_Values[v_Company] = NonNull(szCompany);
m_Values[v_FileVersion] = NonNull(szFileVersion);
#undef NonNull
m_fDll = fDLL;
m_lcid = lcid;
}
VOID Win32Res::MakeResFile(const void **pData, DWORD *pcbData)
{
STANDARD_VM_CONTRACT;
static const RESOURCEHEADER magic = { 0x00000000, 0x00000020, 0xFFFF, 0x0000, 0xFFFF, 0x0000,
0x00000000, 0x0000, 0x0000, 0x00000000, 0x00000000 };
_ASSERTE(pData != NULL && pcbData != NULL);
*pData = NULL;
*pcbData = 0;
m_pData = new BYTE[(sizeof(RESOURCEHEADER) * 3 + sizeof(EXEVERRESOURCE))];
m_pCur = m_pData;
m_pEnd = m_pData + sizeof(RESOURCEHEADER) * 3 + sizeof(EXEVERRESOURCE);
// inject the magic empty entry
Write( &magic, sizeof(magic) );
WriteVerResource();
if (m_Icon)
{
WriteIconResource();
}
*pData = m_pData;
*pcbData = (DWORD)(m_pCur - m_pData);
return;
}
/*
* WriteIconResource
* Writes the Icon resource into the RES file.
*
* RETURNS: TRUE on succes, FALSE on failure (errors reported to user)
*/
VOID Win32Res::WriteIconResource()
{
STANDARD_VM_CONTRACT;
HandleHolder hIconFile = INVALID_HANDLE_VALUE;
WORD wTemp, wCount, resID = 2; // Skip 1 for the version ID
DWORD dwRead = 0, dwWritten = 0;
RESOURCEHEADER grpHeader = { 0x00000000, 0x00000020, 0xFFFF, (WORD)(size_t)RT_GROUP_ICON, 0xFFFF, 0x7F00, // 0x7F00 == IDI_APPLICATION
0x00000000, 0x1030, 0x0000, 0x00000000, 0x00000000 };
// Read the icon
hIconFile = WszCreateFile( m_Icon, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
FILE_FLAG_SEQUENTIAL_SCAN, NULL);
if (hIconFile == INVALID_HANDLE_VALUE) {
COMPlusThrowWin32();
}
// Read the magic reserved WORD
if (ReadFile( hIconFile, &wTemp, sizeof(WORD), &dwRead, NULL) == FALSE) {
COMPlusThrowWin32();
} else if (wTemp != 0 || dwRead != sizeof(WORD)) {
COMPlusThrowHR(HRESULT_FROM_WIN32(ERROR_INVALID_DATA));
}
// Verify the Type WORD
if (ReadFile( hIconFile, &wCount, sizeof(WORD), &dwRead, NULL) == FALSE) {
COMPlusThrowWin32();
} else if (wCount != 1 || dwRead != sizeof(WORD)) {
COMPlusThrowHR(HRESULT_FROM_WIN32(ERROR_INVALID_DATA));
}
// Read the Count WORD
if (ReadFile( hIconFile, &wCount, sizeof(WORD), &dwRead, NULL) == FALSE) {
COMPlusThrowWin32();
} else if (wCount == 0 || dwRead != sizeof(WORD)) {
COMPlusThrowHR(HRESULT_FROM_WIN32(ERROR_INVALID_DATA));
}
NewArrayHolder<ICONRESDIR> grp = new ICONRESDIR[wCount];
grpHeader.DataSize = 3 * sizeof(WORD) + wCount * sizeof(ICONRESDIR);
// For each Icon
for (WORD i = 0; i < wCount; i++) {
ICONDIRENTRY ico;
DWORD icoPos, newPos;
RESOURCEHEADER icoHeader = { 0x00000000, 0x00000020, 0xFFFF, (WORD)(size_t)RT_ICON, 0xFFFF, 0x0000,
0x00000000, 0x1010, 0x0000, 0x00000000, 0x00000000 };
icoHeader.Name = resID++;
// Read the Icon header
if (ReadFile( hIconFile, &ico, sizeof(ICONDIRENTRY), &dwRead, NULL) == FALSE) {
COMPlusThrowWin32();
}
else if (dwRead != sizeof(ICONDIRENTRY)) {
COMPlusThrowHR(HRESULT_FROM_WIN32(ERROR_INVALID_DATA));
}
_ASSERTE(sizeof(ICONRESDIR) + sizeof(WORD) == sizeof(ICONDIRENTRY));
memcpy(grp + i, &ico, sizeof(ICONRESDIR));
grp[i].IconId = icoHeader.Name;
icoHeader.DataSize = ico.dwBytesInRes;
NewArrayHolder<BYTE> icoBuffer = new BYTE[icoHeader.DataSize];
// Write the header to the RES file
Write( &icoHeader, sizeof(RESOURCEHEADER) );
// Position to read the Icon data
icoPos = SetFilePointer( hIconFile, 0, NULL, FILE_CURRENT);
if (icoPos == INVALID_SET_FILE_POINTER) {
COMPlusThrowWin32();
}
newPos = SetFilePointer( hIconFile, ico.dwImageOffset, NULL, FILE_BEGIN);
if (newPos == INVALID_SET_FILE_POINTER) {
COMPlusThrowWin32();
}
// Actually read the data
if (ReadFile( hIconFile, icoBuffer, icoHeader.DataSize, &dwRead, NULL) == FALSE) {
COMPlusThrowWin32();
}
else if (dwRead != icoHeader.DataSize) {
COMPlusThrowHR(HRESULT_FROM_WIN32(ERROR_INVALID_DATA));
}
// Because Icon files don't seem to record the actual Planes and BitCount in
// the ICONDIRENTRY, get the info from the BITMAPINFOHEADER at the beginning
// of the data here:
grp[i].Planes = ((BITMAPINFOHEADER*)(BYTE*)icoBuffer)->biPlanes;
grp[i].BitCount = ((BITMAPINFOHEADER*)(BYTE*)icoBuffer)->biBitCount;
// Now write the data to the RES file
Write( (BYTE*)icoBuffer, icoHeader.DataSize );
// Reposition to read the next Icon header
newPos = SetFilePointer( hIconFile, icoPos, NULL, FILE_BEGIN);
if (newPos != icoPos) {
COMPlusThrowWin32();
}
}
// inject the icon group
Write( &grpHeader, sizeof(RESOURCEHEADER) );
// Write the header to the RES file
wTemp = 0; // the reserved WORD
Write( &wTemp, sizeof(WORD) );
wTemp = RES_ICON; // the GROUP type
Write( &wTemp, sizeof(WORD) );
Write( &wCount, sizeof(WORD) );
// now write the entries
Write( grp, sizeof(ICONRESDIR) * wCount );
return;
}
/*
* WriteVerResource
* Writes the version resource into the RES file.
*
* RETURNS: TRUE on succes, FALSE on failure (errors reported to user)
*/
VOID Win32Res::WriteVerResource()
{
STANDARD_VM_CONTRACT;
WCHAR szLangCp[9]; // language/codepage string.
EXEVERRESOURCE VerResource;
WORD cbStringBlocks;
int i;
bool bUseFileVer = false;
WCHAR rcFile[_MAX_PATH] = {0}; // Name of file without path
WCHAR rcFileExtension[_MAX_PATH] = {0}; // file extension
WCHAR rcFileName[_MAX_PATH]; // Name of file with extension but without path
DWORD cbTmp;
SplitPath(m_szFile, 0, 0, 0, 0, rcFile, _MAX_PATH, rcFileExtension, _MAX_PATH);
wcscpy_s(rcFileName, COUNTOF(rcFileName), rcFile);
wcscat_s(rcFileName, COUNTOF(rcFileName), rcFileExtension);
static const EXEVERRESOURCE VerResourceTemplate = {
sizeof(EXEVERRESOURCE), sizeof(VS_FIXEDFILEINFO), 0, W("VS_VERSION_INFO"),
{
VS_FFI_SIGNATURE, // Signature
VS_FFI_STRUCVERSION, // structure version
0, 0, // file version number
0, 0, // product version number
VS_FFI_FILEFLAGSMASK, // file flags mask
0, // file flags
VOS__WINDOWS32,
VFT_APP, // file type
0, // subtype
0, 0 // file date/time
},
sizeof(WORD) * 2 + 2 * HDRSIZE + KEYBYTES("VarFileInfo") + KEYBYTES("Translation"),
0,
1,
W("VarFileInfo"),
sizeof(WORD) * 2 + HDRSIZE + KEYBYTES("Translation"),
sizeof(WORD) * 2,
0,
W("Translation"),
0,
0,
2 * HDRSIZE + KEYBYTES("StringFileInfo") + KEYBYTES("12345678"),
0,
1,
W("StringFileInfo"),
HDRSIZE + KEYBYTES("12345678"),
0,
1,
W("12345678")
};
static const WCHAR szComments[] = W("Comments");
static const WCHAR szCompanyName[] = W("CompanyName");
static const WCHAR szFileDescription[] = W("FileDescription");
static const WCHAR szCopyright[] = W("LegalCopyright");
static const WCHAR szTrademark[] = W("LegalTrademarks");
static const WCHAR szProdName[] = W("ProductName");
static const WCHAR szFileVerResName[] = W("FileVersion");
static const WCHAR szProdVerResName[] = W("ProductVersion");
static const WCHAR szInternalNameResName[] = W("InternalName");
static const WCHAR szOriginalNameResName[] = W("OriginalFilename");
// If there's no product version, use the file version
if (m_Values[v_ProductVersion][0] == 0) {
m_Values[v_ProductVersion] = m_Values[v_FileVersion];
bUseFileVer = true;
}
// Keep the two following arrays in the same order
#define MAX_KEY 10
static const LPCWSTR szKeys [MAX_KEY] = {
szComments,
szCompanyName,
szFileDescription,
szFileVerResName,
szInternalNameResName,
szCopyright,
szTrademark,
szOriginalNameResName,
szProdName,
szProdVerResName,
};
LPCWSTR szValues [MAX_KEY] = { // values for keys
m_Values[v_Description], //compiler->assemblyDescription == NULL ? W("") : compiler->assemblyDescription,
m_Values[v_Company], // Company Name
m_Values[v_Title], // FileDescription //compiler->assemblyTitle == NULL ? W("") : compiler->assemblyTitle,
m_Values[v_FileVersion], // FileVersion
rcFileName, // InternalName
m_Values[v_Copyright], // Copyright
m_Values[v_Trademark], // Trademark
rcFileName, // OriginalName
m_Values[v_Product], // Product Name //compiler->assemblyTitle == NULL ? W("") : compiler->assemblyTitle,
m_Values[v_ProductVersion] // Product Version
};
memcpy(&VerResource, &VerResourceTemplate, sizeof(VerResource));
if (m_fDll)
VerResource.vsFixed.dwFileType = VFT_DLL;
else
VerResource.vsFixed.dwFileType = VFT_APP;
// Extract the numeric version from the string.
m_Version[0] = m_Version[1] = m_Version[2] = m_Version[3] = 0;
int nNumStrings = swscanf_s(m_Values[v_FileVersion], W("%hu.%hu.%hu.%hu"), m_Version, m_Version + 1, m_Version + 2, m_Version + 3);
// Fill in the FIXEDFILEINFO
VerResource.vsFixed.dwFileVersionMS =
((DWORD)m_Version[0] << 16) + m_Version[1];
VerResource.vsFixed.dwFileVersionLS =
((DWORD)m_Version[2] << 16) + m_Version[3];
if (bUseFileVer) {
VerResource.vsFixed.dwProductVersionLS = VerResource.vsFixed.dwFileVersionLS;
VerResource.vsFixed.dwProductVersionMS = VerResource.vsFixed.dwFileVersionMS;
}
else {
WORD v[4];
v[0] = v[1] = v[2] = v[3] = 0;
// Try to get the version numbers, but don't waste time or give any errors
// just default to zeros
nNumStrings = swscanf_s(m_Values[v_ProductVersion], W("%hu.%hu.%hu.%hu"), v, v + 1, v + 2, v + 3);
VerResource.vsFixed.dwProductVersionMS =
((DWORD)v[0] << 16) + v[1];
VerResource.vsFixed.dwProductVersionLS =
((DWORD)v[2] << 16) + v[3];
}
// There is no documentation on what units to use for the date! So we use zero.
// The Windows resource compiler does too.
VerResource.vsFixed.dwFileDateMS = VerResource.vsFixed.dwFileDateLS = 0;
// Fill in codepage/language -- we'll assume the IDE language/codepage
// is the right one.
if (m_lcid != -1)
VerResource.langid = static_cast<WORD>(m_lcid);
else
VerResource.langid = MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL);
VerResource.codepage = CP_WINUNICODE; // Unicode codepage.
swprintf_s(szLangCp, NumItems(szLangCp), W("%04x%04x"), VerResource.langid, VerResource.codepage);
wcscpy_s(VerResource.szLangCpKey, COUNTOF(VerResource.szLangCpKey), szLangCp);
// Determine the size of all the string blocks.
cbStringBlocks = 0;
for (i = 0; i < MAX_KEY; i++) {
if (szValues[i] == NULL || wcslen(szValues[i]) == 0)
continue;
cbTmp = SizeofVerString( szKeys[i], szValues[i]);
if ((cbStringBlocks + cbTmp) > USHRT_MAX / 2)
COMPlusThrow(kArgumentException, W("Argument_VerStringTooLong"));
cbStringBlocks += (WORD) cbTmp;
}
if ((cbStringBlocks + VerResource.cbLangCpBlock) > USHRT_MAX / 2)
COMPlusThrow(kArgumentException, W("Argument_VerStringTooLong"));
VerResource.cbLangCpBlock += cbStringBlocks;
if ((cbStringBlocks + VerResource.cbStringBlock) > USHRT_MAX / 2)
COMPlusThrow(kArgumentException, W("Argument_VerStringTooLong"));
VerResource.cbStringBlock += cbStringBlocks;
if ((cbStringBlocks + VerResource.cbRootBlock) > USHRT_MAX / 2)
COMPlusThrow(kArgumentException, W("Argument_VerStringTooLong"));
VerResource.cbRootBlock += cbStringBlocks;
// Call this VS_VERSION_INFO
RESOURCEHEADER verHeader = { 0x00000000, 0x0000003C, 0xFFFF, (WORD)(size_t)RT_VERSION, 0xFFFF, 0x0001,
0x00000000, 0x0030, 0x0000, 0x00000000, 0x00000000 };
verHeader.DataSize = VerResource.cbRootBlock;
// Write the header
Write( &verHeader, sizeof(RESOURCEHEADER) );
// Write the version resource
Write( &VerResource, sizeof(VerResource) );
// Write each string block.
for (i = 0; i < MAX_KEY; i++) {
if (szValues[i] == NULL || wcslen(szValues[i]) == 0)
continue;
WriteVerString( szKeys[i], szValues[i] );
}
#undef MAX_KEY
return;
}
/*
* SizeofVerString
* Determines the size of a version string to the given stream.
* RETURNS: size of block in bytes.
*/
WORD Win32Res::SizeofVerString(LPCWSTR lpszKey, LPCWSTR lpszValue)
{
STANDARD_VM_CONTRACT;
size_t cbKey, cbValue;
cbKey = (wcslen(lpszKey) + 1) * 2; // Make room for the NULL
cbValue = (wcslen(lpszValue) + 1) * 2;
if (cbValue == 2)
cbValue = 4; // Empty strings need a space and NULL terminator (for Win9x)
if (cbKey + cbValue >= 0xFFF0)
COMPlusThrow(kArgumentException, W("Argument_VerStringTooLong"));
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:6305) // "Potential mismatch between sizeof and countof quantities"
#endif
return (WORD)(PadKeyLen(cbKey) + // key, 0 padded to DWORD boundary
PadValLen(cbValue) + // value, 0 padded to dword boundary
HDRSIZE); // block header.
#ifdef _PREFAST_
#pragma warning(pop)
#endif
}
/*----------------------------------------------------------------------------
* WriteVerString
* Writes a version string to the given file.
*/
VOID Win32Res::WriteVerString( LPCWSTR lpszKey, LPCWSTR lpszValue)
{
STANDARD_VM_CONTRACT;
size_t cbKey, cbValue, cbBlock;
bool bNeedsSpace = false;
cbKey = (wcslen(lpszKey) + 1) * 2; // includes terminating NUL
cbValue = wcslen(lpszValue);
if (cbValue > 0)
cbValue++; // make room for NULL
else {
bNeedsSpace = true;
cbValue = 2; // Make room for space and NULL (for Win9x)
}
cbBlock = SizeofVerString(lpszKey, lpszValue);
NewArrayHolder<BYTE> pbBlock = new BYTE[(DWORD)cbBlock + HDRSIZE];
ZeroMemory(pbBlock, (DWORD)cbBlock + HDRSIZE);
_ASSERTE(cbValue < USHRT_MAX && cbKey < USHRT_MAX && cbBlock < USHRT_MAX);
// Copy header, key and value to block.
*(WORD *)((BYTE *)pbBlock) = (WORD)cbBlock;
*(WORD *)(pbBlock + sizeof(WORD)) = (WORD)cbValue;
*(WORD *)(pbBlock + 2 * sizeof(WORD)) = 1; // 1 = text value
// size = (cbBlock + HDRSIZE - HDRSIZE) / sizeof(WCHAR)
wcscpy_s((WCHAR*)(pbBlock + HDRSIZE), (cbBlock / sizeof(WCHAR)), lpszKey);
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:6305) // "Potential mismatch between sizeof and countof quantities"
#endif
if (bNeedsSpace)
*((WCHAR*)(pbBlock + (HDRSIZE + PadKeyLen(cbKey)))) = W(' ');
else
{
wcscpy_s((WCHAR*)(pbBlock + (HDRSIZE + PadKeyLen(cbKey))),
//size = ((cbBlock + HDRSIZE) - (HDRSIZE + PadKeyLen(cbKey))) / sizeof(WCHAR)
(cbBlock - PadKeyLen(cbKey))/sizeof(WCHAR),
lpszValue);
}
#ifdef _PREFAST_
#pragma warning(pop)
#endif
// Write block
Write( pbBlock, cbBlock);
return;
}
VOID Win32Res::Write(LPCVOID pData, size_t len)
{
STANDARD_VM_CONTRACT;
if (m_pCur + len > m_pEnd) {
// Grow
size_t newSize = (m_pEnd - m_pData);
// double the size unless we need more than that
if (len > newSize)
newSize += len;
else
newSize *= 2;
LPBYTE pNew = new BYTE[newSize];
memcpy(pNew, m_pData, m_pCur - m_pData);
delete [] m_pData;
// Relocate the pointers
m_pCur = pNew + (m_pCur - m_pData);
m_pData = pNew;
m_pEnd = pNew + newSize;
}
// Copy it in
memcpy(m_pCur, pData, len);
m_pCur += len;
return;
}
| 32.802048 | 138 | 0.606128 | danmosemsft |
40b5d8fc2532554b65212e12da18a8c740bd2163 | 6,728 | cpp | C++ | render_delegate/render_param.cpp | krishnancr/arnold-usd | e32b6042cb16a87bdef90c602e2fdc0c921a9d5c | [
"Apache-2.0"
] | 1 | 2019-12-02T13:51:27.000Z | 2019-12-02T13:51:27.000Z | render_delegate/render_param.cpp | krishnancr/arnold-usd | e32b6042cb16a87bdef90c602e2fdc0c921a9d5c | [
"Apache-2.0"
] | 1 | 2020-01-07T20:57:45.000Z | 2020-01-17T10:41:39.000Z | render_delegate/render_param.cpp | krishnancr/arnold-usd | e32b6042cb16a87bdef90c602e2fdc0c921a9d5c | [
"Apache-2.0"
] | 3 | 2019-12-03T07:45:47.000Z | 2022-01-25T08:43:05.000Z | // Copyright 2019 Luma Pictures
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Modifications Copyright 2019 Autodesk, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "render_param.h"
#include "render_delegate.h"
#include <ai.h>
PXR_NAMESPACE_OPEN_SCOPE
#ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS
HdArnoldRenderParam::HdArnoldRenderParam(HdArnoldRenderDelegate* delegate) : _delegate(delegate)
#else
HdArnoldRenderParam::HdArnoldRenderParam()
#endif
{
_needsRestart.store(false, std::memory_order::memory_order_release);
_aborted.store(false, std::memory_order::memory_order_release);
}
HdArnoldRenderParam::Status HdArnoldRenderParam::Render()
{
const auto aborted = _aborted.load(std::memory_order_acquire);
// Checking early if the render was aborted earlier.
if (aborted) {
return Status::Aborted;
}
#ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS
const auto status = AiRenderGetStatus(_delegate->GetRenderSession());
#else
const auto status = AiRenderGetStatus();
#endif
if (status == AI_RENDER_STATUS_FINISHED) {
// If render restart is true, it means the Render Delegate received an update after rendering has finished
// and AiRenderInterrupt does not change the status anymore.
// For the atomic operations we are using a release-acquire model.
const auto needsRestart = _needsRestart.exchange(false, std::memory_order_acq_rel);
if (needsRestart) {
_paused.store(false, std::memory_order_release);
#ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS
AiRenderRestart(_delegate->GetRenderSession());
#else
AiRenderRestart();
#endif
return Status::Converging;
}
return Status::Converged;
}
// Resetting the value.
_needsRestart.store(false, std::memory_order_release);
if (status == AI_RENDER_STATUS_PAUSED) {
const auto needsRestart = _needsRestart.exchange(false, std::memory_order_acq_rel);
if (needsRestart) {
_paused.store(false, std::memory_order_release);
#ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS
AiRenderRestart(_delegate->GetRenderSession());
#else
AiRenderRestart();
#endif
} else if (!_paused.load(std::memory_order_acquire)) {
#ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS
AiRenderResume(_delegate->GetRenderSession());
#else
AiRenderResume();
#endif
}
return Status::Converging;
}
if (status == AI_RENDER_STATUS_RESTARTING) {
_paused.store(false, std::memory_order_release);
return Status::Converging;
}
if (status == AI_RENDER_STATUS_FAILED) {
_aborted.store(true, std::memory_order_release);
_paused.store(false, std::memory_order_release);
#ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS
const auto errorCode = AiRenderEnd(_delegate->GetRenderSession());
#else
const auto errorCode = AiRenderEnd();
#endif
if (errorCode == AI_ABORT) {
TF_WARN("[arnold-usd] Render was aborted.");
} else if (errorCode == AI_ERROR_NO_CAMERA) {
TF_WARN("[arnold-usd] Camera not defined.");
} else if (errorCode == AI_ERROR_BAD_CAMERA) {
TF_WARN("[arnold-usd] Bad camera data.");
} else if (errorCode == AI_ERROR_VALIDATION) {
TF_WARN("[arnold-usd] Usage not validated.");
} else if (errorCode == AI_ERROR_RENDER_REGION) {
TF_WARN("[arnold-usd] Invalid render region.");
} else if (errorCode == AI_INTERRUPT) {
TF_WARN("[arnold-usd] Render interrupted by user.");
} else if (errorCode == AI_ERROR_NO_OUTPUTS) {
TF_WARN("[arnold-usd] No rendering outputs.");
} else if (errorCode == AI_ERROR_UNAVAILABLE_DEVICE) {
TF_WARN("[arnold-usd] Cannot create GPU context.");
} else if (errorCode == AI_ERROR) {
TF_WARN("[arnold-usd] Generic error.");
}
return Status::Aborted;
}
_paused.store(false, std::memory_order_release);
if (status != AI_RENDER_STATUS_RENDERING) {
#ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS
AiRenderBegin(_delegate->GetRenderSession());
#else
AiRenderBegin();
#endif
}
return Status::Converging;
}
void HdArnoldRenderParam::Interrupt(bool needsRestart, bool clearStatus)
{
#ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS
const auto status = AiRenderGetStatus(_delegate->GetRenderSession());
#else
const auto status = AiRenderGetStatus();
#endif
if (status != AI_RENDER_STATUS_NOT_STARTED) {
#ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS
AiRenderInterrupt(_delegate->GetRenderSession(), AI_BLOCKING);
#else
AiRenderInterrupt(AI_BLOCKING);
#endif
}
if (needsRestart) {
_needsRestart.store(true, std::memory_order_release);
}
if (clearStatus) {
_aborted.store(false, std::memory_order_release);
}
}
void HdArnoldRenderParam::Pause()
{
Interrupt(false, false);
_paused.store(true, std::memory_order_release);
}
void HdArnoldRenderParam::Resume() { _paused.store(false, std::memory_order_release); }
void HdArnoldRenderParam::Restart()
{
_paused.store(false, std::memory_order_release);
_needsRestart.store(true, std::memory_order_release);
}
bool HdArnoldRenderParam::UpdateShutter(const GfVec2f& shutter)
{
if (!GfIsClose(_shutter[0], shutter[0], AI_EPSILON) || !GfIsClose(_shutter[1], shutter[1], AI_EPSILON)) {
_shutter = shutter;
return true;
}
return false;
}
bool HdArnoldRenderParam::UpdateFPS(const float FPS)
{
if (!GfIsClose(_fps, FPS, AI_EPSILON)) {
_fps = FPS;
return true;
}
return false;
}
PXR_NAMESPACE_CLOSE_SCOPE
| 34.502564 | 114 | 0.695898 | krishnancr |
40b85203fb671cbf485eee6d339700b7e69245bd | 30,398 | cpp | C++ | libfairygui/Classes/Transition.cpp | zeas2/FairyGUI-cocos2dx | c6ddaafc1b1bf51b0ef6929d6937c0cf111cd06a | [
"MIT"
] | null | null | null | libfairygui/Classes/Transition.cpp | zeas2/FairyGUI-cocos2dx | c6ddaafc1b1bf51b0ef6929d6937c0cf111cd06a | [
"MIT"
] | null | null | null | libfairygui/Classes/Transition.cpp | zeas2/FairyGUI-cocos2dx | c6ddaafc1b1bf51b0ef6929d6937c0cf111cd06a | [
"MIT"
] | null | null | null | #include "Transition.h"
#include "GComponent.h"
#include "utils/ToolSet.h"
NS_FGUI_BEGIN
USING_NS_CC;
using namespace std;
const int FRAME_RATE = 24;
const int OPTION_IGNORE_DISPLAY_CONTROLLER = 1;
const int OPTION_AUTO_STOP_DISABLED = 2;
const int OPTION_AUTO_STOP_AT_END = 4;
class TransitionValue
{
public:
float f1;//x, scalex, pivotx,alpha,shakeAmplitude,rotation
float f2;//y, scaley, pivoty, shakePeriod
float f3;
float f4;
int i;//frame
Color4B c;//color
bool b;//playing
string s;//sound,transName
bool b1;
bool b2;
TransitionValue();
TransitionValue(TransitionValue& source);
TransitionValue& operator= (const TransitionValue& other);
};
TransitionValue::TransitionValue() :
f1(0), f2(0), f3(0), f4(0), i(0), b(false), b1(false), b2(false)
{
}
TransitionValue::TransitionValue(TransitionValue& other)
{
*this = other;
}
TransitionValue& TransitionValue::operator= (const TransitionValue& other)
{
f1 = other.f1;
f2 = other.f2;
f3 = other.f3;
f4 = other.f4;
i = other.i;
c = other.c;
b = other.b;
s = other.s;
b1 = other.b1;
b2 = other.b2;
return *this;
}
class TransitionItem
{
public:
float time;
string targetId;
TransitionActionType type;
float duration;
TransitionValue value;
TransitionValue startValue;
TransitionValue endValue;
tweenfunc::TweenType easeType;
int repeat;
bool yoyo;
bool tween;
string label;
string label2;
//hooks
Transition::TransitionHook hook;
Transition::TransitionHook hook2;
//running properties
bool completed;
GObject* target;
bool filterCreated;
uint32_t displayLockToken;
TransitionItem();
};
TransitionItem::TransitionItem() :
time(0),
type(TransitionActionType::XY),
duration(0),
easeType(tweenfunc::TweenType::Quad_EaseOut),
repeat(0),
yoyo(false),
tween(false),
hook(nullptr),
hook2(nullptr),
completed(false),
target(nullptr),
filterCreated(false),
displayLockToken(0)
{
}
Transition::Transition(GComponent* owner, int index) :
autoPlayRepeat(1),
autoPlayDelay(0),
_owner(owner),
_totalTimes(0),
_totalTasks(0),
_playing(false),
_ownerBaseX(0),
_ownerBaseY(0),
_onComplete(nullptr),
_options(0),
_reversed(false),
_maxTime(0),
_autoPlay(false),
_actionTag(ActionTag::TRANSITION_ACTION + index)
{
}
Transition::~Transition()
{
for (auto &item : _items)
delete item;
}
void Transition::setAutoPlay(bool value)
{
if (_autoPlay != value)
{
_autoPlay = value;
if (_autoPlay)
{
if (_owner->onStage())
play(autoPlayRepeat, autoPlayDelay, nullptr);
}
else
{
if (!_owner->onStage())
stop(false, true);
}
}
}
void Transition::play(PlayCompleteCallback callback)
{
play(1, 0, callback);
}
void Transition::play(int times, float delay, PlayCompleteCallback callback)
{
play(times, delay, callback, false);
}
void Transition::playReverse(PlayCompleteCallback callback)
{
playReverse(1, 0, callback);
}
void Transition::playReverse(int times, float delay, PlayCompleteCallback callback)
{
play(times, delay, callback, true);
}
void Transition::changeRepeat(int value)
{
_totalTimes = value;
}
void Transition::play(int times, float delay, PlayCompleteCallback onComplete, bool reverse)
{
stop(true, true);
_totalTimes = times;
_reversed = reverse;
internalPlay(delay);
_playing = _totalTasks > 0;
if (_playing)
{
_onComplete = onComplete;
if ((_options & OPTION_IGNORE_DISPLAY_CONTROLLER) != 0)
{
for (auto &item : _items)
{
if (item->target != nullptr && item->target != _owner)
item->displayLockToken = item->target->addDisplayLock();
}
}
}
else if (onComplete != nullptr)
onComplete();
}
void Transition::stop()
{
stop(true, false);
}
void Transition::stop(bool setToComplete, bool processCallback)
{
if (_playing)
{
_playing = false;
_totalTasks = 0;
_totalTimes = 0;
PlayCompleteCallback func = _onComplete;
_onComplete = nullptr;
_owner->displayObject()->stopAllActionsByTag(_actionTag);
int cnt = (int)_items.size();
if (_reversed)
{
for (int i = cnt - 1; i >= 0; i--)
{
TransitionItem* item = _items[i];
if (item->target == nullptr)
continue;
stopItem(item, setToComplete);
}
}
else
{
for (int i = 0; i < cnt; i++)
{
TransitionItem *item = _items[i];
if (item->target == nullptr)
continue;
stopItem(item, setToComplete);
}
}
if (processCallback && func != nullptr)
func();
}
}
void Transition::stopItem(TransitionItem * item, bool setToComplete)
{
if (item->displayLockToken != 0)
{
item->target->releaseDisplayLock(item->displayLockToken);
item->displayLockToken = 0;
}
//if (item->type == TransitionActionType::ColorFilter && item->filterCreated)
// item->target->setFilter(nullptr);
if (item->completed)
return;
if (item->type == TransitionActionType::Transition)
{
Transition* trans = item->target->as<GComponent>()->getTransition(item->value.s);
if (trans != nullptr)
trans->stop(setToComplete, false);
}
else if (item->type == TransitionActionType::Shake)
{
Director::getInstance()->getScheduler()->unschedule("-", item);
item->target->_gearLocked = true;
item->target->setPosition(item->target->getX() - item->startValue.f1, item->target->getY() - item->startValue.f2);
item->target->_gearLocked = false;
}
else
{
if (setToComplete)
{
if (item->tween)
{
if (!item->yoyo || item->repeat % 2 == 0)
applyValue(item, _reversed ? item->startValue : item->endValue);
else
applyValue(item, _reversed ? item->endValue : item->startValue);
}
else if (item->type != TransitionActionType::Sound)
applyValue(item, item->value);
}
}
}
void Transition::setValue(const std::string & label, const ValueVector& values)
{
for (auto &item : _items)
{
if (item->label == label)
{
if (item->tween)
setValue(item, item->startValue, values);
else
setValue(item, item->value, values);
}
else if (item->label2 == label)
{
setValue(item, item->endValue, values);
}
}
}
void Transition::setValue(TransitionItem* item, TransitionValue& value, const ValueVector& values)
{
switch (item->type)
{
case TransitionActionType::XY:
case TransitionActionType::Size:
case TransitionActionType::Pivot:
case TransitionActionType::Scale:
case TransitionActionType::Skew:
value.b1 = true;
value.b2 = true;
value.f1 = values[0].asFloat();
value.f2 = values[1].asFloat();
break;
case TransitionActionType::Alpha:
value.f1 = values[0].asFloat();
break;
case TransitionActionType::Rotation:
value.f1 = values[0].asFloat();
break;
case TransitionActionType::Color:
{
uint32_t v = values[0].asUnsignedInt();
value.c = Color4B((v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF, (v >> 24) & 0xFF);
break;
}
case TransitionActionType::Animation:
value.i = values[0].asInt();
if (values.size() > 1)
value.b = values[1].asBool();
break;
case TransitionActionType::Visible:
value.b = values[0].asBool();
break;
case TransitionActionType::Sound:
value.s = values[0].asString();
if (values.size() > 1)
value.f1 = values[1].asFloat();
break;
case TransitionActionType::Transition:
value.s = values[0].asString();
if (values.size() > 1)
value.i = values[1].asInt();
break;
case TransitionActionType::Shake:
value.f1 = values[0].asFloat();
if (values.size() > 1)
value.f2 = values[1].asFloat();
break;
case TransitionActionType::ColorFilter:
value.f1 = values[1].asFloat();
value.f2 = values[2].asFloat();
value.f3 = values[3].asFloat();
value.f4 = values[4].asFloat();
break;
default:
break;
}
}
void Transition::setHook(const std::string & label, TransitionHook callback)
{
for (auto &item : _items)
{
if (item->label == label)
{
item->hook = callback;
break;
}
else if (item->label2 == label)
{
item->hook2 = callback;
break;
}
}
}
void Transition::clearHooks()
{
for (auto &item : _items)
{
item->hook = nullptr;
item->hook2 = nullptr;
}
}
void Transition::setTarget(const std::string & label, GObject * newTarget)
{
for (auto &item : _items)
{
if (item->label == label)
item->targetId = newTarget->id;
}
}
void Transition::setDuration(const std::string & label, float value)
{
for (auto &item : _items)
{
if (item->tween && item->label == label)
item->duration = value;
}
}
void Transition::updateFromRelations(const std::string & targetId, float dx, float dy)
{
int cnt = (int)_items.size();
if (cnt == 0)
return;
for (int i = 0; i < cnt; i++)
{
TransitionItem* item = _items[i];
if (item->type == TransitionActionType::XY && item->targetId == targetId)
{
if (item->tween)
{
item->startValue.f1 += dx;
item->startValue.f2 += dy;
item->endValue.f1 += dx;
item->endValue.f2 += dy;
}
else
{
item->value.f1 += dx;
item->value.f2 += dy;
}
}
}
}
void Transition::OnOwnerRemovedFromStage()
{
if ((_options & OPTION_AUTO_STOP_DISABLED) == 0)
stop((_options & OPTION_AUTO_STOP_AT_END) != 0 ? true : false, false);
}
void Transition::internalPlay(float delay)
{
_ownerBaseX = _owner->getX();
_ownerBaseY = _owner->getY();
_totalTasks = 0;
for (auto &item : _items)
{
if (!item->targetId.empty())
item->target = _owner->getChildById(item->targetId);
else
item->target = _owner;
if (item->target == nullptr)
continue;
if (item->tween)
{
float startTime = delay;
if (_reversed)
startTime += (_maxTime - item->time - item->duration);
else
startTime += item->time;
if (startTime > 0 && (item->type == TransitionActionType::XY || item->type == TransitionActionType::Size))
{
_totalTasks++;
item->completed = false;
ActionInterval* action = Sequence::createWithTwoActions(DelayTime::create(startTime), CallFunc::create([item, this]
{
_totalTasks--;
startTween(item, 0);
}));
action->setTag(ActionTag::TRANSITION_ACTION);
_owner->displayObject()->runAction(action);
}
else
startTween(item, startTime);
}
else
{
float startTime = delay;
if (_reversed)
startTime += (_maxTime - item->time);
else
startTime += item->time;
if (startTime == 0)
{
applyValue(item, item->value);
if (item->hook)
item->hook();
}
else
{
item->completed = false;
_totalTasks++;
ActionInterval* action = Sequence::createWithTwoActions(DelayTime::create(startTime), CallFunc::create([item, this]
{
item->completed = true;
_totalTasks--;
applyValue(item, item->value);
if (item->hook)
item->hook();
checkAllComplete();
}));
action->setTag(ActionTag::TRANSITION_ACTION);
_owner->displayObject()->runAction(action);
}
}
}
}
void Transition::startTween(TransitionItem * item, float delay)
{
if (_reversed)
startTween(item, delay, item->endValue, item->startValue);
else
startTween(item, delay, item->startValue, item->endValue);
}
void Transition::startTween(TransitionItem * item, float delay, TransitionValue& startValue, TransitionValue& endValue)
{
ActionInterval* mainAction = nullptr;
switch (item->type)
{
case TransitionActionType::XY:
case TransitionActionType::Size:
{
if (item->type == TransitionActionType::XY)
{
if (item->target == _owner)
{
if (!startValue.b1)
startValue.f1 = 0;
if (!startValue.b2)
startValue.f2 = 0;
}
else
{
if (!startValue.b1)
startValue.f1 = item->target->getX();
if (!startValue.b2)
startValue.f2 = item->target->getY();
}
}
else
{
if (!startValue.b1)
startValue.f1 = item->target->getWidth();
if (!startValue.b2)
startValue.f2 = item->target->getHeight();
}
item->value.f1 = startValue.f1;
item->value.f2 = startValue.f2;
if (!endValue.b1)
endValue.f1 = item->value.f1;
if (!endValue.b2)
endValue.f2 = item->value.f2;
item->value.b1 = startValue.b1 || endValue.b1;
item->value.b2 = startValue.b2 || endValue.b2;
mainAction = ActionVec2::create(item->duration,
Vec2(startValue.f1, startValue.f2),
Vec2(endValue.f1, endValue.f2),
[this, item](const Vec2& value)
{
item->value.f1 = value.x;
item->value.f2 = value.y;
applyValue(item, item->value);
});
break;
}
case TransitionActionType::Scale:
case TransitionActionType::Skew:
{
item->value.f1 = startValue.f1;
item->value.f2 = startValue.f2;
mainAction = ActionVec2::create(item->duration,
Vec2(startValue.f1, startValue.f2),
Vec2(endValue.f1, endValue.f2),
[this, item](const Vec2& value)
{
item->value.f1 = value.x;
item->value.f2 = value.y;
applyValue(item, item->value);
});
break;
}
case TransitionActionType::Alpha:
case TransitionActionType::Rotation:
{
item->value.f1 = startValue.f1;
mainAction = ActionFloat::create(item->duration,
startValue.f1,
endValue.f1,
[this, item](float value)
{
item->value.f1 = value;
applyValue(item, item->value);
});
break;
}
case TransitionActionType::Color:
{
item->value.c = startValue.c;
mainAction = ActionVec4::create(item->duration,
Vec4(item->value.c.r, item->value.c.g, item->value.c.b, item->value.c.a),
Vec4(endValue.c.r, endValue.c.g, endValue.c.b, endValue.c.a),
[this, item](const Vec4& value)
{
item->value.c.r = value.x;
item->value.c.g = value.y;
item->value.c.b = value.z;
item->value.c.a = value.w;
applyValue(item, item->value);
});
break;
}
case TransitionActionType::ColorFilter:
{
item->value.f1 = startValue.f1;
item->value.f2 = startValue.f2;
item->value.f3 = startValue.f3;
item->value.f4 = startValue.f4;
mainAction = ActionVec4::create(item->duration,
Vec4(startValue.f1, startValue.f2, startValue.f3, startValue.f4),
Vec4(endValue.f1, endValue.f2, endValue.f3, endValue.f4),
[this, item](const Vec4& value)
{
item->value.f1 = value.x;
item->value.f2 = value.y;
item->value.f3 = value.z;
item->value.f4 = value.w;
applyValue(item, item->value);
});
break;
}
default:
break;
}
mainAction = createEaseAction(item->easeType, mainAction);
if (item->repeat != 0)
mainAction = RepeatYoyo::create(mainAction, item->repeat == -1 ? INT_MAX : (item->repeat + 1), item->yoyo);
FiniteTimeAction* completeAction = CallFunc::create([this, item]() { tweenComplete(item); });
if (delay > 0)
{
FiniteTimeAction* delayAction = DelayTime::create(delay);
if (item->hook)
mainAction = Sequence::create({ delayAction, CallFunc::create(item->hook), mainAction, completeAction });
else
mainAction = Sequence::create({ delayAction, mainAction, completeAction });
}
else
{
applyValue(item, item->value);
if (item->hook)
item->hook();
mainAction = Sequence::createWithTwoActions(mainAction, completeAction);
}
mainAction->setTag(ActionTag::TRANSITION_ACTION);
_owner->displayObject()->runAction(mainAction);
_totalTasks++;
item->completed = false;
}
void Transition::tweenComplete(TransitionItem * item)
{
item->completed = true;
_totalTasks--;
if (item->hook2)
item->hook2();
checkAllComplete();
}
void Transition::checkAllComplete()
{
if (_playing && _totalTasks == 0)
{
if (_totalTimes < 0)
{
internalPlay(0);
}
else
{
_totalTimes--;
if (_totalTimes > 0)
internalPlay(0);
else
{
_playing = false;
for (auto &item : _items)
{
if (item->target != nullptr)
{
if (item->displayLockToken != 0)
{
item->target->releaseDisplayLock(item->displayLockToken);
item->displayLockToken = 0;
}
/*if (item->filterCreated)
{
item->filterCreated = false;
item->target->setFilter(nullptr);
}*/
}
}
if (_onComplete)
{
PlayCompleteCallback func = _onComplete;
_onComplete = nullptr;
func();
}
}
}
}
}
void Transition::applyValue(TransitionItem * item, TransitionValue & value)
{
item->target->_gearLocked = true;
switch (item->type)
{
case TransitionActionType::XY:
if (item->target == _owner)
{
float f1, f2;
if (!value.b1)
f1 = item->target->getX();
else
f1 = value.f1 + _ownerBaseX;
if (!value.b2)
f2 = item->target->getY();
else
f2 = value.f2 + _ownerBaseY;
item->target->setPosition(f1, f2);
}
else
{
if (!value.b1)
value.f1 = item->target->getX();
if (!value.b2)
value.f2 = item->target->getY();
item->target->setPosition(value.f1, value.f2);
}
break;
case TransitionActionType::Size:
if (!value.b1)
value.f1 = item->target->getWidth();
if (!value.b2)
value.f2 = item->target->getHeight();
item->target->setSize(value.f1, value.f2);
break;
case TransitionActionType::Pivot:
item->target->setPivot(value.f1, value.f2);
break;
case TransitionActionType::Alpha:
item->target->setAlpha(value.f1);
break;
case TransitionActionType::Rotation:
item->target->setRotation(value.f1);
break;
case TransitionActionType::Scale:
item->target->setScale(value.f1, value.f2);
break;
case TransitionActionType::Skew:
item->target->setSkewX(value.f1);
item->target->setSkewY(value.f2);
break;
case TransitionActionType::Color:
{
IColorGear* cg = dynamic_cast<IColorGear*>(item->target);
if (cg)
cg->cg_setColor(value.c);
break;
}
case TransitionActionType::Animation:
{
IAnimationGear* ag = dynamic_cast<IAnimationGear*>(item->target);
if (ag)
{
if (!value.b1)
value.i = ag->getCurrentFrame();
ag->setCurrentFrame(value.i);
ag->setPlaying(value.b);
}
break;
}
case TransitionActionType::Visible:
item->target->setVisible(value.b);
break;
case TransitionActionType::Transition:
{
Transition* trans = item->target->as<GComponent>()->getTransition(value.s);
if (trans != nullptr)
{
if (value.i == 0)
trans->stop(false, true);
else if (trans->isPlaying())
trans->_totalTimes = value.i;
else
{
item->completed = false;
_totalTasks++;
if (_reversed)
trans->playReverse(value.i, 0, [this, item]() { playTransComplete(item); });
else
trans->play(value.i, 0, [this, item]() { playTransComplete(item); });
}
}
break;
}
case TransitionActionType::Sound:
{
UIRoot->playSound(value.s, value.f1);
break;
}
case TransitionActionType::Shake:
item->startValue.f1 = 0; //offsetX
item->startValue.f2 = 0; //offsetY
item->startValue.f3 = item->value.f2;//shakePeriod
Director::getInstance()->getScheduler()->schedule(CC_CALLBACK_1(Transition::shakeItem, this, item), item, 0, false, "-");
_totalTasks++;
item->completed = false;
break;
case TransitionActionType::ColorFilter:
break;
default:
break;
}
item->target->_gearLocked = false;
}
void Transition::playTransComplete(TransitionItem* item)
{
_totalTasks--;
item->completed = true;
checkAllComplete();
}
void Transition::shakeItem(float dt, TransitionItem * item)
{
float r = ceil(item->value.f1 * item->startValue.f3 / item->value.f2);
float x1 = (1 - rand_0_1() * 2)*r;
float y1 = (1 - rand_0_1() * 2)*r;
x1 = x1 > 0 ? ceil(x1) : floor(x1);
y1 = y1 > 0 ? ceil(y1) : floor(y1);
item->target->_gearLocked = true;
item->target->setPosition(item->target->getX() - item->startValue.f1 + x1, item->target->getY() - item->startValue.f2 + y1);
item->target->_gearLocked = false;
item->startValue.f1 = x1;
item->startValue.f2 = y1;
item->startValue.f3 -= dt;
if (item->startValue.f3 <= 0)
{
item->target->_gearLocked = true;
item->target->setPosition(item->target->getX() - item->startValue.f1, item->target->getY() - item->startValue.f2);
item->target->_gearLocked = false;
item->completed = true;
_totalTasks--;
Director::getInstance()->getScheduler()->unschedule("-", item);
checkAllComplete();
}
}
void Transition::decodeValue(TransitionActionType type, const char* pValue, TransitionValue & value)
{
string str;
if (pValue)
str = pValue;
switch (type)
{
case TransitionActionType::XY:
case TransitionActionType::Size:
case TransitionActionType::Pivot:
case TransitionActionType::Skew:
{
string s1, s2;
ToolSet::splitString(str, ',', s1, s2);
if (s1 == "-")
{
value.b1 = false;
}
else
{
value.f1 = atof(s1.c_str());
value.b1 = true;
}
if (s2 == "-")
{
value.b2 = false;
}
else
{
value.f2 = atof(s2.c_str());
value.b2 = true;
}
break;
}
case TransitionActionType::Alpha:
value.f1 = atof(str.c_str());
break;
case TransitionActionType::Rotation:
value.f1 = atof(str.c_str());
break;
case TransitionActionType::Scale:
{
Vec2 v2;
ToolSet::splitString(str, ',', v2);
value.f1 = v2.x;
value.f2 = v2.y;
break;
}
case TransitionActionType::Color:
value.c = ToolSet::convertFromHtmlColor(str.c_str());
break;
case TransitionActionType::Animation:
{
string s1, s2;
ToolSet::splitString(str, ',', s1, s2);
if (s1 == "-")
{
value.b1 = false;
}
else
{
value.i = atoi(s1.c_str());
value.b1 = true;
}
value.b = s2 == "p";
break;
}
case TransitionActionType::Visible:
value.b = str == "true";
break;
case TransitionActionType::Sound:
{
string s;
ToolSet::splitString(str, ',', value.s, s);
if (!s.empty())
{
int intv = atoi(s.c_str());
if (intv == 100 || intv == 0)
value.f1 = 1;
else
value.f1 = (float)intv / 100;
}
else
value.f1 = 1;
break;
}
case TransitionActionType::Transition:
{
string s;
ToolSet::splitString(str, ',', value.s, s);
if (!s.empty())
value.i = atoi(s.c_str());
else
value.i = 1;
break;
}
case TransitionActionType::Shake:
{
Vec2 v2;
ToolSet::splitString(str, ',', v2);
value.f1 = v2.x;
value.f2 = v2.y;
break;
}
case TransitionActionType::ColorFilter:
{
Vec4 v4;
ToolSet::splitString(str, ',', v4);
value.f1 = v4.x;
value.f2 = v4.y;
value.f3 = v4.z;
value.f4 = v4.w;
break;
}
default:
break;
}
}
void Transition::setup(TXMLElement * xml)
{
const char* p;
name = xml->Attribute("name");
p = xml->Attribute("options");
if (p)
_options = atoi(p);
_autoPlay = xml->BoolAttribute("autoPlay");
if (_autoPlay)
{
p = xml->Attribute("autoPlayRepeat");
if (p)
autoPlayRepeat = atoi(p);
autoPlayDelay = xml->FloatAttribute("autoPlayDelay");
}
TXMLElement* cxml = xml->FirstChildElement("item");
while (cxml)
{
TransitionItem* item = new TransitionItem();
_items.push_back(item);
item->time = (float)cxml->IntAttribute("time") / (float)FRAME_RATE;
p = cxml->Attribute("target");
if (p)
item->targetId = p;
p = cxml->Attribute("type");
if (p)
item->type = ToolSet::parseTransitionActionType(p);
item->tween = cxml->BoolAttribute("tween");
p = cxml->Attribute("label");
if (p)
item->label = p;
if (item->tween)
{
item->duration = (float)cxml->IntAttribute("duration") / FRAME_RATE;
if (item->time + item->duration > _maxTime)
_maxTime = item->time + item->duration;
p = cxml->Attribute("ease");
if (p)
item->easeType = ToolSet::parseEaseType(p);
item->repeat = cxml->IntAttribute("repeat");
item->yoyo = cxml->BoolAttribute("yoyo");
p = cxml->Attribute("label2");
if (p)
item->label2 = p;
p = cxml->Attribute("endValue");
if (p)
{
decodeValue(item->type, cxml->Attribute("startValue"), item->startValue);
decodeValue(item->type, p, item->endValue);
}
else
{
item->tween = false;
decodeValue(item->type, cxml->Attribute("startValue"), item->value);
}
}
else
{
if (item->time > _maxTime)
_maxTime = item->time;
decodeValue(item->type, cxml->Attribute("value"), item->value);
}
cxml = cxml->NextSiblingElement("item");
}
}
NS_FGUI_END
| 27.141071 | 132 | 0.506086 | zeas2 |
40bba22d34acaf7d3cc2f0ec0642006778387ec2 | 941 | cpp | C++ | solutions/edit_distance.cpp | spythrone/gfg-solutions | 7bb5198a1a8c7a06d7f81eea78dfa9451252c6b2 | [
"MIT"
] | null | null | null | solutions/edit_distance.cpp | spythrone/gfg-solutions | 7bb5198a1a8c7a06d7f81eea78dfa9451252c6b2 | [
"MIT"
] | null | null | null | solutions/edit_distance.cpp | spythrone/gfg-solutions | 7bb5198a1a8c7a06d7f81eea78dfa9451252c6b2 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int getsol(string s, string t, int n, int m, vector<vector<int>> &v){
if(n==0)
return m;
if(m==0)
return n;
if(v[n][m] > -1)
return v[n][m];
if(s[n-1] == t[m-1])
return getsol(s, t, n-1, m-1, v);
v[n][m] = 1 + min(getsol(s, t, n, m-1, v), min(getsol(s, t, n-1, m, v), getsol(s, t, n-1, m-1, v)));
return v[n][m];
}
int editDistance(string s, string t) {
int n = s.size();
int m = t.size();
vector<vector<int>> v(n+1, vector<int>(m+1, -1));
int sol = getsol(s, t, n, m, v);
return sol;
}
};
int main() {
int T;
cin >> T;
while (T--) {
string s, t;
cin >> s >> t;
Solution ob;
int ans = ob.editDistance(s, t);
cout << ans << "\n";
}
return 0;
}
| 22.404762 | 108 | 0.428268 | spythrone |
40bc70b2d2bf2ee43f9d3da2ea799c7b4c33856c | 11,248 | cpp | C++ | packages/monte_carlo/collision/electron/src/MonteCarlo_ScreenedRutherfordElasticElectronScatteringDistribution.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 10 | 2019-11-14T19:58:30.000Z | 2021-04-04T17:44:09.000Z | packages/monte_carlo/collision/electron/src/MonteCarlo_ScreenedRutherfordElasticElectronScatteringDistribution.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 43 | 2020-03-03T19:59:20.000Z | 2021-09-08T03:36:08.000Z | packages/monte_carlo/collision/electron/src/MonteCarlo_ScreenedRutherfordElasticElectronScatteringDistribution.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 6 | 2020-02-12T17:37:07.000Z | 2020-09-08T18:59:51.000Z | //---------------------------------------------------------------------------//
//!
//! \file MonteCarlo_ScreenedRutherfordElasticElectronScatteringDistribution.cpp
//! \author Luke Kersting
//! \brief The electron screened Rutherford elastic scattering distribution definition
//!
//---------------------------------------------------------------------------//
// FRENSIE Includes
#include "MonteCarlo_ScreenedRutherfordElasticElectronScatteringDistribution.hpp"
#include "MonteCarlo_KinematicHelpers.hpp"
#include "Utility_RandomNumberGenerator.hpp"
#include "Utility_SearchAlgorithms.hpp"
#include "Utility_3DCartesianVectorHelpers.hpp"
#include "Utility_PhysicalConstants.hpp"
namespace MonteCarlo{
// Constructor
ScreenedRutherfordElasticElectronScatteringDistribution::ScreenedRutherfordElasticElectronScatteringDistribution(
const int atomic_number,
const bool seltzer_modification_on )
{
d_elastic_traits.reset( new ElasticTraits( atomic_number,
seltzer_modification_on ) );
}
// Evaluate the distribution at the given energy and scattering angle cosine
/*! \details The returned value is not normalized to the elastic cutoff
* distribution. The correct normalized value can be calculated by multiplying
* the the returned value by the pdf of the cutoff distribution at mu peak.
* When the scattering angle cosine is very close to one, precision will be lost.
*/
double ScreenedRutherfordElasticElectronScatteringDistribution::evaluate(
const double incoming_energy,
const double scattering_angle_cosine ) const
{
// Make sure the energy and angle are valid
testPrecondition( incoming_energy > 0.0 );
testPrecondition( scattering_angle_cosine >= ElasticTraits::mu_peak );
testPrecondition( scattering_angle_cosine <= 1.0 );
return this->evaluatePDF( incoming_energy, scattering_angle_cosine );
}
// Evaluate the distribution at the given energy and scattering angle cosine
/*! \details The returned value is not normalized to the elastic cutoff
* distribution. The correct normalized value can be calculated by multiplying
* the the returned value by the pdf of the cutoff distribution at mu peak.
* When the scattering angle cosine is very close to one, precision will be lost.
*/
double ScreenedRutherfordElasticElectronScatteringDistribution::evaluate(
const double incoming_energy,
const double scattering_angle_cosine,
const double eta ) const
{
// Make sure the energy, eta and angle are valid
testPrecondition( incoming_energy > 0.0 );
testPrecondition( scattering_angle_cosine >= ElasticTraits::mu_peak );
testPrecondition( scattering_angle_cosine <= 1.0 );
testPrecondition( eta > 0.0 );
return this->evaluatePDF( incoming_energy, scattering_angle_cosine, eta );
}
// Evaluate the PDF at the given energy and scattering angle cosine
/*! \details The returned value is not normalized to the elastic cutoff
* distribution. The correct normalized value can be calculated by multiplying
* the the returned value by the pdf of the cutoff distribution at mu peak.
* When the scattering angle cosine is very close to one, precision will be lost.
*/
double ScreenedRutherfordElasticElectronScatteringDistribution::evaluatePDF(
const double incoming_energy,
const double scattering_angle_cosine ) const
{
// Make sure the energy, eta and angle are valid
testPrecondition( incoming_energy > 0.0 );
testPrecondition( scattering_angle_cosine >= ElasticTraits::mu_peak );
testPrecondition( scattering_angle_cosine <= 1.0 );
double eta = d_elastic_traits->evaluateMoliereScreeningConstant( incoming_energy );
return this->evaluatePDF( incoming_energy, scattering_angle_cosine, eta );
}
// Evaluate the PDF at the given energy and scattering angle cosine
/*! \details The returned value is not normalized to the elastic cutoff
* distribution. The correct normalized value can be calculated by multiplying
* the the returned value by the pdf of the cutoff distribution at mu peak.
* When the scattering angle cosine is very close to one, precision will be lost.
*/
double ScreenedRutherfordElasticElectronScatteringDistribution::evaluatePDF(
const double incoming_energy,
const double scattering_angle_cosine,
const double eta ) const
{
// Make sure the energy, eta and angle are valid
testPrecondition( incoming_energy > 0.0 );
testPrecondition( scattering_angle_cosine >= ElasticTraits::mu_peak );
testPrecondition( scattering_angle_cosine <= 1.0 );
testPrecondition( eta > 0.0 );
double delta_mu = 1.0L - scattering_angle_cosine;
return ( ElasticTraits::delta_mu_peak + eta )*( ElasticTraits::delta_mu_peak + eta )/(
( delta_mu + eta )*( delta_mu + eta ) );
}
// Evaluate the CDF
double ScreenedRutherfordElasticElectronScatteringDistribution::evaluateCDF(
const double incoming_energy,
const double scattering_angle_cosine ) const
{
// Make sure the energy and angle are valid
testPrecondition( incoming_energy > 0.0 );
testPrecondition( scattering_angle_cosine >= ElasticTraits::mu_peak );
testPrecondition( scattering_angle_cosine <= 1.0 );
double eta = d_elastic_traits->evaluateMoliereScreeningConstant( incoming_energy );
return this->evaluateCDF( incoming_energy, scattering_angle_cosine, eta );
}
// Evaluate the CDF
double ScreenedRutherfordElasticElectronScatteringDistribution::evaluateCDF(
const double incoming_energy,
const double scattering_angle_cosine,
const double eta ) const
{
// Make sure the energy, eta and angle cosine are valid
testPrecondition( incoming_energy > 0.0 );
testPrecondition( scattering_angle_cosine >= ElasticTraits::mu_peak );
testPrecondition( scattering_angle_cosine <= 1.0 );
testPrecondition( eta > 0.0 );
double delta_mu = 1.0L - scattering_angle_cosine;
return ( ElasticTraits::delta_mu_peak + eta )/( delta_mu + eta )*
( delta_mu/ElasticTraits::delta_mu_peak );
}
// Sample an outgoing energy and direction from the distribution
void ScreenedRutherfordElasticElectronScatteringDistribution::sample(
const double incoming_energy,
double& outgoing_energy,
double& scattering_angle_cosine ) const
{
// The outgoing energy is always equal to the incoming energy
outgoing_energy = incoming_energy;
Counter trial_dummy;
// Sample an outgoing direction
this->sampleAndRecordTrialsImpl( incoming_energy,
scattering_angle_cosine,
trial_dummy );
}
// Sample an outgoing energy and direction and record the number of trials
void ScreenedRutherfordElasticElectronScatteringDistribution::sampleAndRecordTrials(
const double incoming_energy,
double& outgoing_energy,
double& scattering_angle_cosine,
Counter& trials ) const
{
// The outgoing energy is always equal to the incoming energy
outgoing_energy = incoming_energy;
// Sample an outgoing direction
this->sampleAndRecordTrialsImpl( incoming_energy,
scattering_angle_cosine,
trials );
}
// Randomly scatter the electron
void ScreenedRutherfordElasticElectronScatteringDistribution::scatterElectron(
ElectronState& electron,
ParticleBank& bank,
Data::SubshellType& shell_of_interaction ) const
{
double scattering_angle_cosine;
Counter trial_dummy;
// Sample an outgoing direction
this->sampleAndRecordTrialsImpl( electron.getEnergy(),
scattering_angle_cosine,
trial_dummy );
shell_of_interaction =Data::UNKNOWN_SUBSHELL;
// Set the new direction
electron.rotateDirection( scattering_angle_cosine,
this->sampleAzimuthalAngle() );
}
// Randomly scatter the positron
void ScreenedRutherfordElasticElectronScatteringDistribution::scatterPositron(
PositronState& positron,
ParticleBank& bank,
Data::SubshellType& shell_of_interaction ) const
{
double scattering_angle_cosine;
Counter trial_dummy;
// Sample an outgoing direction
this->sampleAndRecordTrialsImpl( positron.getEnergy(),
scattering_angle_cosine,
trial_dummy );
shell_of_interaction =Data::UNKNOWN_SUBSHELL;
// Set the new direction
positron.rotateDirection( scattering_angle_cosine,
this->sampleAzimuthalAngle() );
}
// Randomly scatter the adjoint electron
void ScreenedRutherfordElasticElectronScatteringDistribution::scatterAdjointElectron(
AdjointElectronState& adjoint_electron,
ParticleBank& bank,
Data::SubshellType& shell_of_interaction ) const
{
double scattering_angle_cosine;
Counter trial_dummy;
// Sample an outgoing direction
this->sampleAndRecordTrialsImpl( adjoint_electron.getEnergy(),
scattering_angle_cosine,
trial_dummy );
shell_of_interaction = Data::UNKNOWN_SUBSHELL;
// Set the new direction
adjoint_electron.rotateDirection( scattering_angle_cosine,
this->sampleAzimuthalAngle() );
}
// Sample an outgoing direction from the distribution
/* \details The CDF is inverted to create the sampling routine.
* mu = ( eta mu_p + ( 1 + eta )( 1 - mu_p )CDF )/
* ( eta + ( 1 - mu_p )CDF )
*/
void ScreenedRutherfordElasticElectronScatteringDistribution::sampleAndRecordTrialsImpl(
const double incoming_energy,
double& scattering_angle_cosine,
Counter& trials ) const
{
// Make sure the incoming energy is valid
testPrecondition( incoming_energy > 0.0 );
// Increment the number of trials
++trials;
double random_number =
Utility::RandomNumberGenerator::getRandomNumber<double>();
double eta = d_elastic_traits->evaluateMoliereScreeningConstant( incoming_energy );
scattering_angle_cosine =
( ElasticTraits::mu_peak * eta +
( 1.0L + eta ) * ElasticTraits::delta_mu_peak * random_number )/
( eta + ElasticTraits::delta_mu_peak * random_number );
// Make sure the scattering angle cosine is valid
testPostcondition( scattering_angle_cosine >= ElasticTraits::mu_peak - 1e-15 );
testPostcondition( scattering_angle_cosine <= 1.0+1e-15 );
// There will sometimes be roundoff error in which case the scattering angle
// cosine should never be greater than 1
scattering_angle_cosine = std::min( scattering_angle_cosine, 1.0 );
}
} // end MonteCarlo namespace
//---------------------------------------------------------------------------//
// end MonteCarlo_ScreenedRutherfordElasticElectronScatteringDistribution.cpp
//---------------------------------------------------------------------------//
| 39.886525 | 113 | 0.69159 | bam241 |
8ad62ce7a35a43ef06ac6339a10e8d5558d65373 | 631 | cpp | C++ | code/Remove_Nth_Node_From_End_of_List.cpp | Shiv-sharma-111/Leetcode_Solution | 52c941f32f0670271360821a8675225d83fa04a6 | [
"MIT"
] | null | null | null | code/Remove_Nth_Node_From_End_of_List.cpp | Shiv-sharma-111/Leetcode_Solution | 52c941f32f0670271360821a8675225d83fa04a6 | [
"MIT"
] | null | null | null | code/Remove_Nth_Node_From_End_of_List.cpp | Shiv-sharma-111/Leetcode_Solution | 52c941f32f0670271360821a8675225d83fa04a6 | [
"MIT"
] | null | null | null | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* pre = new ListNode(0);
pre->next = head;
ListNode* cur = pre;
int L = 0;
while (cur){
L += 1;
cur = cur->next;
}
cur = pre;
int i = 0;
while (i < L-n-1){
cur = cur->next;
i += 1;
}
cur->next = cur->next->next;
return pre->next;
}
};
| 21.033333 | 55 | 0.44374 | Shiv-sharma-111 |
8ad91ca22293db54fcc19764318ec7ebfcd7eea2 | 27,001 | cpp | C++ | src/parser/ifc3_parser.cpp | bostonceltics20/phoebe | b7e6294ee32d7f94299cd027ba2e72c3552ab246 | [
"MIT"
] | null | null | null | src/parser/ifc3_parser.cpp | bostonceltics20/phoebe | b7e6294ee32d7f94299cd027ba2e72c3552ab246 | [
"MIT"
] | null | null | null | src/parser/ifc3_parser.cpp | bostonceltics20/phoebe | b7e6294ee32d7f94299cd027ba2e72c3552ab246 | [
"MIT"
] | null | null | null | #include "ifc3_parser.h"
#include "constants.h"
#include "eigen.h"
#include "mpiHelper.h"
#include <fstream>// it may be used
#include <iostream>
#include <set>
#ifdef HDF5_AVAIL
#include <highfive/H5Easy.hpp>
#endif
// decide which ifc3 parser to use
Interaction3Ph IFC3Parser::parse(Context &context, Crystal &crystal) {
// check if this is a phonopy file is set in input
if (context.getPhFC3FileName().find("hdf5") != std::string::npos) {
if(context.getPhonopyDispFileName().empty()) {
Error("You need both fc3.hdf5 and phonopy_disp.yaml "
"files to run phono3py." );
} else {
if (mpi->mpiHead()) {
std::cout << "Using anharmonic force constants from phono3py."
<< std::endl;
}
}
return parseFromPhono3py(context, crystal);
} else {
if (mpi->mpiHead()) {
std::cout << "Using anharmonic force constants from ShengBTE."
<< std::endl;
}
return parseFromShengBTE(context, crystal);
}
}
/* this function is used by phono3py parser, and
* constructs a list of vectors which are in the first WS
* superCell of the phonon superCell */
Eigen::MatrixXd IFC3Parser::wsInit(Crystal &crystal,
Eigen::Vector3i qCoarseGrid) {
const int nx = 2;
int index = 0;
const int nrwsx = 200;
Eigen::MatrixXd directUnitCell = crystal.getDirectUnitCell();
Eigen::MatrixXd unitCell(3, 3);
unitCell.col(0) = directUnitCell.col(0) * qCoarseGrid(0);
unitCell.col(1) = directUnitCell.col(1) * qCoarseGrid(1);
unitCell.col(2) = directUnitCell.col(2) * qCoarseGrid(2);
Eigen::MatrixXd tmpResult(3, nrwsx);
for (int ir = -nx; ir <= nx; ir++) {
for (int jr = -nx; jr <= nx; jr++) {
for (int kr = -nx; kr <= nx; kr++) {
for (int i : {0, 1, 2}) {
tmpResult(i, index) =
unitCell(i, 0) * ir + unitCell(i, 1) * jr + unitCell(i, 2) * kr;
}
if (tmpResult.col(index).squaredNorm() > 1.0e-6) {
index += 1;
}
if (index > nrwsx) {
Error("WSInit > nrwsx");
}
}
}
}
int nrws = index;
Eigen::MatrixXd rws(3, nrws);
for (int i = 0; i < nrws; i++) {
rws.col(i) = tmpResult.col(i);
}
return rws;
}
/* given the list of all vectors in the WS superCell (rws),
* determine the weight of a particular vector, r */
double wsWeight(const Eigen::VectorXd &r, const Eigen::MatrixXd &rws) {
int nreq = 1;
for (int ir = 0; ir < rws.cols(); ir++) {
double rrt = r.dot(rws.col(ir));
double ck = rrt - rws.col(ir).squaredNorm() / 2.;
if (ck > 1.0e-6) {
return 0.;
}
if (abs(ck) < 1.0e-6) {
nreq += 1;
}
}
double x = 1. / (double) nreq;
return x;
}
/* find the index of a particular vector in cellPositions */
int findIndexRow(Eigen::MatrixXd &cellPositions, Eigen::Vector3d &position) {
int ir2 = -1;
for (int i = 0; i < cellPositions.cols(); i++) {
if ((position - cellPositions.col(i)).norm() < 1.e-12) {
ir2 = i;
return ir2;
}
}
if (ir2 == -1) {
Error("index not found");
}
return ir2;
}
std::tuple<Eigen::MatrixXd, Eigen::Tensor<double, 3>, Eigen::MatrixXd, Eigen::Tensor<double, 3>>
reorderDynamicalMatrix(
Crystal &crystal, const Eigen::Vector3i &qCoarseGrid, const Eigen::MatrixXd &rws,
Eigen::Tensor<double, 5> &mat3R, Eigen::MatrixXd &cellPositions,
const std::vector<
std::vector<std::vector<std::vector<std::vector<std::vector<double>>>>>>
&ifc3Tensor,
const std::vector<int> &cellMap) {
int numAtoms = crystal.getNumAtoms();
Eigen::MatrixXd atomicPositions = crystal.getAtomicPositions();
int nr1Big = qCoarseGrid(0) * 2;
int nr2Big = qCoarseGrid(1) * 2;
int nr3Big = qCoarseGrid(2) * 2;
Eigen::MatrixXd directUnitCell = crystal.getDirectUnitCell();
// Count the number of bravais vectors we need to loop over
int numBravaisVectors = 0;
// Record how many BV with non-zero weight
// belong to each atom, so that we can index iR3
// properly later in the code
Eigen::VectorXi startBVForAtom(numAtoms);
int numBVThisAtom = 0;
std::set<std::vector<double>> setBravaisVectors;
for (int na = 0; na < numAtoms; na++) {
startBVForAtom(na) = numBVThisAtom;
for (int nb = 0; nb < numAtoms; nb++) {
// loop over all possible indices for the first vector
for (int nr1 = -nr1Big; nr1 < nr1Big; nr1++) {
for (int nr2 = -nr2Big; nr2 < nr2Big; nr2++) {
for (int nr3 = -nr3Big; nr3 < nr3Big; nr3++) {
// calculate the R2 vector for atom nb
Eigen::Vector3d r2;
std::vector<double> R2(3);
for (int i : {0, 1, 2}) {
R2[i] = nr1 * directUnitCell(i, 0) + nr2 * directUnitCell(i, 1) + nr3 * directUnitCell(i, 2);
r2(i) = R2[i] - atomicPositions(na, i) + atomicPositions(nb, i);
}
double weightR2 = wsWeight(r2, rws);
// count this vector if it contributes
if (weightR2 > 0) {
numBravaisVectors += 1;
numBVThisAtom += 1;
setBravaisVectors.insert(R2);
}
}
}
}
}
}
int numR = setBravaisVectors.size();
std::vector<Eigen::Vector3d> listBravaisVectors;
for (auto x : setBravaisVectors) {
Eigen::Vector3d R2;
for (int i : {0, 1, 2}) {
R2(i) = x[i];
}
listBravaisVectors.push_back(R2);
}
Eigen::MatrixXd bravaisVectors(3, numR);
Eigen::Tensor<double, 3> weights(numR, numAtoms, numAtoms);
bravaisVectors.setZero();
weights.setConstant(0.);
for (int na = 0; na < numAtoms; na++) {
for (int nb = 0; nb < numAtoms; nb++) {
// loop over all possible indices for the first vector
for (int nr1 = -nr1Big; nr1 < nr1Big; nr1++) {
for (int nr2 = -nr2Big; nr2 < nr2Big; nr2++) {
for (int nr3 = -nr3Big; nr3 < nr3Big; nr3++) {
// calculate the R2 vector for atom nb
Eigen::Vector3d r2, R2;
for (int i : {0, 1, 2}) {
R2(i) = nr1 * directUnitCell(i, 0) + nr2 * directUnitCell(i, 1) + nr3 * directUnitCell(i, 2);
r2(i) = R2(i) - atomicPositions(na, i) + atomicPositions(nb, i);
}
double weightR2 = wsWeight(r2, rws);
// count this vector if it contributes
if (weightR2 > 0) {
int ir;
{
auto it = std::find(listBravaisVectors.begin(), listBravaisVectors.end(), R2);
if (it == listBravaisVectors.end()) Error("phono3py parser index not found");
ir = it - listBravaisVectors.begin();
}
for (int i : {0, 1, 2}) {
bravaisVectors(i, ir) = R2(i);
}
weights(ir, na, nb) = weightR2;
}
}
}
}
}
}
//---------
// next, we reorder the dynamical matrix along the bravais lattice vectors
// similarly to what was done in the harmonic class.
mat3R.resize(3 * numAtoms, 3 * numAtoms, 3 * numAtoms, numR, numR);
mat3R.setZero();
double conversion = pow(distanceBohrToAng, 3) / energyRyToEv;
// Note: it may be possible to make these loops faster.
// It is likely possible to avoid using findIndexRow,
// and there could be a faster order of loops.
// loop over all possible indices for the first vector
for (int nr3 = -nr3Big; nr3 < nr3Big; nr3++) {
for (int nr2 = -nr2Big; nr2 < nr2Big; nr2++) {
for (int nr1 = -nr1Big; nr1 < nr1Big; nr1++) {
Eigen::Vector3d r2;
for (int i : {0, 1, 2}) {
r2(i) = nr1 * directUnitCell(i, 0) + nr2 * directUnitCell(i, 1) + nr3 * directUnitCell(i, 2);
}
int iR2;
{
auto it = std::find(listBravaisVectors.begin(), listBravaisVectors.end(), r2);
if (it == listBravaisVectors.end()) continue;
iR2 = it - listBravaisVectors.begin();
}
// calculate the positive quadrant equivalents
int m1 = mod((nr1 + 1), qCoarseGrid(0));
if (m1 <= 0) {
m1 += qCoarseGrid(0);
}
int m2 = mod((nr2 + 1), qCoarseGrid(1));
if (m2 <= 0) {
m2 += qCoarseGrid(1);
}
int m3 = mod((nr3 + 1), qCoarseGrid(2));
if (m3 <= 0) {
m3 += qCoarseGrid(2);
}
m1 += -1;
m2 += -1;
m3 += -1;
// build the unit cell equivalent vectors to look up
Eigen::Vector3d rp2;
for (int i : {0, 1, 2}) {
rp2(i) = m1 * directUnitCell(i, 0) + m2 * directUnitCell(i, 1) + m3 * directUnitCell(i, 2);
}
// look up the index of the original atom
auto ir2 = findIndexRow(cellPositions, rp2);
// loop over all possible indices for the R3 vector
for (int mr3 = -nr3Big; mr3 < nr3Big; mr3++) {
for (int mr2 = -nr2Big; mr2 < nr2Big; mr2++) {
for (int mr1 = -nr1Big; mr1 < nr1Big; mr1++) {
// calculate the R3 vector for atom nc
Eigen::Vector3d r3;
for (int i : {0, 1, 2}) {
r3(i) = mr1 * directUnitCell(i, 0) + mr2 * directUnitCell(i, 1) + mr3 * directUnitCell(i, 2);
}
int iR3;
{
auto it = std::find(listBravaisVectors.begin(), listBravaisVectors.end(), r3);
if (it == listBravaisVectors.end()) continue;
iR3 = it - listBravaisVectors.begin();
}
// calculate the positive quadrant equivalents
int p1 = mod((mr1 + 1), qCoarseGrid(0));
if (p1 <= 0) {
p1 += qCoarseGrid(0);
}
int p2 = mod((mr2 + 1), qCoarseGrid(1));
if (p2 <= 0) {
p2 += qCoarseGrid(1);
}
int p3 = mod((mr3 + 1), qCoarseGrid(2));
if (p3 <= 0) {
p3 += qCoarseGrid(2);
}
p1 += -1;
p2 += -1;
p3 += -1;
// build the unit cell equivalent vectors to look up
Eigen::Vector3d rp3;
for (int i : {0, 1, 2}) {
rp3(i) = p1 * directUnitCell(i, 0) + p2 * directUnitCell(i, 1) + p3 * directUnitCell(i, 2);
}
// look up the index of the original atom
auto ir3 = findIndexRow(cellPositions, rp3);
// loop over the atoms involved in the first vector
for (int na = 0; na < numAtoms; na++) {
for (int nb = 0; nb < numAtoms; nb++) {
// calculate the R2 vector for atom nb
Eigen::Vector3d ra2;
for (int i : {0, 1, 2}) {
ra2(i) = r2(i) - atomicPositions(na, i) + atomicPositions(nb, i);
}
// skip vectors which do not contribute
double weightR2 = wsWeight(ra2, rws);
if (weightR2 == 0) continue;
// loop over atoms involved in R3 vector
for (int nc = 0; nc < numAtoms; nc++) {
// calculate the R3 vector for atom nc
Eigen::Vector3d ra3;
for (int i : {0, 1, 2}) {
ra3(i) = r3(i) - atomicPositions(na, i) + atomicPositions(nc, i);
}
// continue only if this vector matters
double weightR3 = wsWeight(ra3, rws);
if (weightR3 == 0) continue;
// index back to superCell positions
int sat2 = cellMap[nb] + ir2;
int sat3 = cellMap[nc] + ir3;
// loop over the cartesian directions
for (int i : {0, 1, 2}) {
for (int j : {0, 1, 2}) {
for (int k : {0, 1, 2}) {
// compress the cartesian indices and unit cell atom
// indices for the first three indices of FC3
auto ind1 = compress2Indices(na, i, numAtoms, 3);
auto ind2 = compress2Indices(nb, j, numAtoms, 3);
auto ind3 = compress2Indices(nc, k, numAtoms, 3);
if ( mat3R(ind1, ind2, ind3, iR3, iR2) != 0 ) {
// this doesn't happen, so I am picking each element only once
std::cout << "already visited\n";
std::cout << ind1 << " " << ind2 << " " << ind3 << " "
<< iR3 << " " << iR2 << "\n";
}
mat3R(ind1, ind2, ind3, iR3, iR2) +=
ifc3Tensor[cellMap[na]][sat2][sat3][i][j][k] * conversion;
// ifc3Tensor[cellMap[na]][sat2][sat3][i][j][k] * conversion;
}// close cartesian loops
}
}
}// r3 loops
}
}
}// close nc loop
} // close R2 loops
}
}
}// close nb loop
} // close na loop
return std::make_tuple(bravaisVectors, weights, bravaisVectors, weights);
}
Interaction3Ph IFC3Parser::parseFromPhono3py(Context &context,
Crystal &crystal) {
#ifndef HDF5_AVAIL
Error(
"Phono3py HDF5 output cannot be read if Phoebe is not built with HDF5.");
// return void;
#else
// Notes about p3py's fc3.hdf5 file:
// 3rd order fcs are listed as (num_atom, num_atom, num_atom, 3, 3, 3)
// stored in eV/Angstrom3
// Look here for additional details
// https://phonopy.github.io/phono3py/output-files.html#fc3-hdf5
// the information we need outside the ifcs3 is in a file called
// disp_fc3.yaml, which contains the atomic positions of the
// superCell and the displacements of the atoms
// The mapping between the superCell and unit cell atoms is
// set up so that the first nAtoms*dimSup of the superCell are unit cell
// atom #1, and the second nAtoms*dimSup are atom #2, and so on.
// First, get num atoms from the crystal
int numAtoms = crystal.getNumAtoms();
// Open disp_fc3 file, read superCell positions, nSupAtoms
// ==========================================================
auto fileName = context.getPhonopyDispFileName();
std::ifstream infile(fileName);
std::string line;
if (fileName.empty()) {
Error("Phono3py required file phonopyDispFileName "
"(phono3py_disp.yaml) not specified in input file.");
}
if (not infile.is_open()) {
Error("Phono3py required file phonopyDispFileName "
"phono3py_disp.yaml) file not found at "
+ fileName);
}
if (mpi->mpiHead())
std::cout << "Reading in " + fileName + "." << std::endl;
// read in the dimension information.
Eigen::Vector3i qCoarseGrid;
while (infile) {
std::getline(infile, line);
if (line.find("dim:") != std::string::npos) {
std::vector<std::string> tok = tokenize(line);
//std::istringstream iss(temp);
//iss >> qCoarseGrid(0) >> qCoarseGrid(1) >> qCoarseGrid(2);
qCoarseGrid(0) = std::stoi(tok[1]);
qCoarseGrid(1) = std::stoi(tok[2]);
qCoarseGrid(2) = std::stoi(tok[3]);
break;
}
}
// First, we open the phonopyDispFileName to check the distance units.
// Phono3py uses Bohr for QE calculations and Angstrom for VASP
// so, here we decide which is the correct unit,
// by parsing the phono3py_disp.yaml file
double distanceConversion = 1. / distanceBohrToAng;
while (infile) {
std::getline(infile, line);
if (line.find("length") != std::string::npos) {
if (line.find("au") != std::string::npos) {
distanceConversion = 1.; // distances already in Bohr
}
break;
}
}
// read the rest of the file to look for superCell positions
std::vector<std::vector<double>> supPositionsVec;
Eigen::MatrixXd lattice(3, 3);
int ilatt = 3;
bool readSupercell = false;
while (infile) {
getline(infile, line);
// we dont want to read the positions after phonon_supercell_matrix,
// so we break here
if(line.find("phonon_supercell_matrix") != std::string::npos) {
break;
}
// read all the lines after we see the flag for the supercell
// no matter what, the ifc3 info will always come after "supercell:"
// and supercell comes before phonon_supercell in the output file
if (line.find("supercell:") != std::string::npos) {
readSupercell = true;
}
// if this is a cell position, save it
if (line.find("coordinates: ") != std::string::npos && readSupercell) {
std::vector<double> position = {0.,0.,0.};
std::vector<std::string> tok = tokenize(line);
position[0] = std::stod(tok[2]);
position[1] = std::stod(tok[3]);
position[2] = std::stod(tok[4]);
supPositionsVec.push_back(position);
}
if (ilatt < 3 && readSupercell) { // count down lattice lines
// convert from angstrom to bohr
std::vector<std::string> tok = tokenize(line);
lattice(ilatt, 0) = std::stod(tok[2]);
lattice(ilatt, 1) = std::stod(tok[3]);
lattice(ilatt, 2) = std::stod(tok[4]);
ilatt++;
}
if (line.find("lattice:") != std::string::npos && readSupercell) {
ilatt = 0;
}
}
infile.close();
infile.clear();
// number of atoms in the supercell for later use
int numSupAtoms = supPositionsVec.size();
int nr = numSupAtoms / numAtoms;
// check that this matches the ifc2 atoms
int numAtomsCheck = numSupAtoms/
(qCoarseGrid[0]*qCoarseGrid[1]*qCoarseGrid[2]);
if (numAtomsCheck != numAtoms) {
Error("IFC3s seem to come from a cell with a different number\n"
"of atoms than the IFC2s. Check your inputs."
"FC2 atoms: " + std::to_string(numAtoms) +
" FC3 atoms: " + std::to_string(numAtomsCheck));
}
// convert std::vectors to Eigen formats required by the
// next part of phoebe
Eigen::MatrixXd supPositions(numSupAtoms, 3);
for ( int n = 0; n < numSupAtoms; n++) {
for (int i : {0, 1, 2}) {
supPositions(n,i) = supPositionsVec[n][i];
}
}
// convert distances to Bohr
lattice *= distanceConversion;
// convert positions to cartesian, in bohr
for (int i = 0; i < numSupAtoms; i++) {
Eigen::Vector3d temp(supPositions(i, 0), supPositions(i, 1),
supPositions(i, 2));
Eigen::Vector3d temp2 = lattice.transpose() * temp;
supPositions(i, 0) = temp2(0);
supPositions(i, 1) = temp2(1);
supPositions(i, 2) = temp2(2);
}
// Open the hdf5 file containing the IFC3s
// ===================================================
fileName = context.getPhFC3FileName();
if (fileName.empty()) {
Error("Phono3py phFC3FileName (fc3.hdf5) file not "
"specified in input file.");
}
if (mpi->mpiHead())
std::cout << "Reading in " + fileName + "." << std::endl;
// user info about memory
// note, this is for a temporary array --
// later we reduce to (numAtoms*3)^3 * numRVecs
{
double rx;
double x = pow(numSupAtoms * 3, 3) / pow(1024., 3) * sizeof(rx);
if (mpi->mpiHead()) {
std::cout << "Allocating " << x
<< " (GB) (per MPI process) for the 3-ph coupling matrix."
<< std::endl;
}
}
// set up buffer to read entire matrix
// have to use this monstrosity because the
// phono3py data is shaped as a 6 dimensional array,
// and eigen tensor is not supported by highFive
std::vector<
std::vector<std::vector<std::vector<std::vector<std::vector<double>>>>>>
ifc3Tensor;
std::vector<int> cellMap;
try {
HighFive::File file(fileName, HighFive::File::ReadOnly);
// Set up hdf5 datasets
HighFive::DataSet difc3 = file.getDataSet("/fc3");
HighFive::DataSet dcellMap = file.getDataSet("/p2s_map");
// read in the ifc3 data
difc3.read(ifc3Tensor);
dcellMap.read(cellMap);
} catch (std::exception &error) {
if(mpi->mpiHead()) std::cout << error.what() << std::endl;
Error("Issue reading fc3.hdf5 file. Make sure it exists at " + fileName +
"\n and is not open by some other persisting processes.");
}
// Determine the list of possible R2, R3 vectors
// the distances from the origin unit cell to another
// unit cell in the positive quadrant superCell
Eigen::MatrixXd cellPositions(3, nr);
cellPositions.setZero();
// get all possible ws cell vectors
Eigen::MatrixXd rws = wsInit(crystal, qCoarseGrid);
// find all possible vectors R2, R3, which are
// position of atomPosSuperCell - atomPosUnitCell = R
for (int is = 0; is < nr; is++) {
cellPositions(0, is) = supPositions(is, 0) - supPositions(0, 0);
cellPositions(1, is) = supPositions(is, 1) - supPositions(0, 1);
cellPositions(2, is) = supPositions(is, 2) - supPositions(0, 2);
}
// reshape to FC3 format
Eigen::Tensor<double, 5> FC3;
auto tup = reorderDynamicalMatrix(crystal, qCoarseGrid, rws, FC3,
cellPositions, ifc3Tensor, cellMap);
auto bravaisVectors2 = std::get<0>(tup);
auto weights2 = std::get<1>(tup);
auto bravaisVectors3 = std::get<2>(tup);
auto weights3 = std::get<3>(tup);
if (mpi->mpiHead()) {
std::cout << "Successfully parsed anharmonic "
"phono3py files.\n"
<< std::endl;
}
// Create interaction3Ph object
Interaction3Ph interaction3Ph(crystal, FC3, bravaisVectors2, bravaisVectors3,
weights2, weights3);
return interaction3Ph;
#endif
}
Interaction3Ph IFC3Parser::parseFromShengBTE(Context &context,
Crystal &crystal) {
auto fileName = context.getPhFC3FileName();
// Open IFC3 file
std::ifstream infile(fileName);
std::string line;
if (not infile.is_open()) {
Error("FC3 file not found");
}
if (mpi->mpiHead())
std::cout << "Reading in " + fileName + "." << std::endl;
// Number of triplets
std::getline(infile, line);
int numTriplets = std::stoi(line);
// user info about memory
{
double rx;
double x = 27 * numTriplets / pow(1024., 3) * sizeof(rx);
if (mpi->mpiHead()) {
std::cout << "Allocating " << x
<< " (GB) (per MPI process) for the 3-ph coupling matrix.\n"
<< std::endl;
}
}
// Allocate quantities to be read
Eigen::Tensor<double, 4> ifc3Tensor(3, 3, 3, numTriplets);
ifc3Tensor.setZero();
Eigen::Tensor<double, 3> cellPositions(numTriplets, 2, 3);
cellPositions.setZero();
Eigen::Tensor<int, 2> displacedAtoms(numTriplets, 3);
displacedAtoms.setZero();
for (int i = 0; i < numTriplets; i++) {// loop over all triplets
// empty line
std::getline(infile, line);
// line with a counter
std::getline(infile, line);
// Read position of 2nd cell
std::getline(infile, line);
std::istringstream iss(line);
std::string item;
int j = 0;
while (iss >> item) {
cellPositions(i, 0, j) = std::stod(item) / distanceBohrToAng;
j++;
}
// Read position of 3rd cell
std::getline(infile, line);
std::istringstream iss2(line);
j = 0;
while (iss2 >> item) {
cellPositions(i, 1, j) = std::stod(item) / distanceBohrToAng;
j++;
}
// Read triplet atom indices
std::getline(infile, line);
std::istringstream iss3(line);
j = 0;
int i0;
while (iss3 >> i0) {
displacedAtoms(i, j) = i0 - 1;
j++;
}
// Read the 3x3x3 force constants tensor
int i1, i2, i3;
double d4;
double conversion = pow(distanceBohrToAng, 3) / energyRyToEv;
for (int a : {0, 1, 2}) {
for (int b : {0, 1, 2}) {
for (int c : {0, 1, 2}) {
std::getline(infile, line);
std::istringstream iss4(line);
while (iss4 >> i1 >> i2 >> i3 >> d4) {
ifc3Tensor(c, b, a, i) = d4 * conversion;
}
}
}
}
}
// Close IFC3 file
infile.close();
// TODO Round cellPositions to the nearest lattice vectors
// start processing ifc3s into FC3 matrix
int numAtoms = crystal.getNumAtoms();
int numBands = numAtoms * 3;
int nr2 = 0;
int nr3 = 0;
std::vector<Eigen::Vector3d> tmpCellPositions2, tmpCellPositions3;
for (int it = 0; it < numTriplets; it++) {
// load the position of the 2 atom in the current triplet
Eigen::Vector3d position2, position3;
for (int ic : {0, 1, 2}) {
position2(ic) = cellPositions(it, 0, ic);
position3(ic) = cellPositions(it, 1, ic);
}
// now check if this element is in the list.
bool found2 = false;
if (std::find(tmpCellPositions2.begin(), tmpCellPositions2.end(),
position2)
!= tmpCellPositions2.end()) {
found2 = true;
}
bool found3 = false;
if (std::find(tmpCellPositions3.begin(), tmpCellPositions3.end(),
position3)
!= tmpCellPositions3.end()) {
found3 = true;
}
if (!found2) {
tmpCellPositions2.push_back(position2);
nr2++;
}
if (!found3) {
tmpCellPositions3.push_back(position3);
nr3++;
}
}
Eigen::MatrixXd cellPositions2(3, nr2);
Eigen::MatrixXd cellPositions3(3, nr3);
cellPositions2.setZero();
cellPositions3.setZero();
for (int i = 0; i < nr2; i++) {
cellPositions2.col(i) = tmpCellPositions2[i];
}
for (int i = 0; i < nr3; i++) {
cellPositions3.col(i) = tmpCellPositions3[i];
}
Eigen::Tensor<double, 5> FC3(numBands, numBands, numBands, nr2, nr3);
FC3.setZero();
for (int it = 0; it < numTriplets; it++) {// sum over all triplets
int ia1 = displacedAtoms(it, 0);
int ia2 = displacedAtoms(it, 1);
int ia3 = displacedAtoms(it, 2);
Eigen::Vector3d position2, position3;
for (int ic : {0, 1, 2}) {
position2(ic) = cellPositions(it, 0, ic);
position3(ic) = cellPositions(it, 1, ic);
}
int ir2 = findIndexRow(cellPositions2, position2);
int ir3 = findIndexRow(cellPositions3, position3);
for (int ic1 : {0, 1, 2}) {
for (int ic2 : {0, 1, 2}) {
for (int ic3 : {0, 1, 2}) {
auto ind1 = compress2Indices(ia1, ic1, numAtoms, 3);
auto ind2 = compress2Indices(ia2, ic2, numAtoms, 3);
auto ind3 = compress2Indices(ia3, ic3, numAtoms, 3);
FC3(ind1, ind2, ind3, ir3, ir2) = ifc3Tensor(ic3, ic2, ic1, it);
}
}
}
}
Eigen::Tensor<double, 3> weights(nr2, numAtoms, numAtoms);
weights.setConstant(1.);
Interaction3Ph interaction3Ph(crystal, FC3, cellPositions2,
cellPositions3, weights, weights);
if (mpi->mpiHead()) {
std::cout << "Successfully parsed anharmonic "
"ShengBTE files.\n"
<< std::endl;
}
return interaction3Ph;
}
| 33.334568 | 109 | 0.560757 | bostonceltics20 |
8ad93e641a30183442ab18bb01ef7af9edafcf80 | 2,806 | hpp | C++ | boost/actor/response_promise.hpp | syoummer/boost.actor | 58f35499bac8871b8f5b0b024246a467b63c6fb0 | [
"BSL-1.0"
] | 2 | 2015-03-20T21:11:16.000Z | 2020-01-20T08:05:41.000Z | boost/actor/response_promise.hpp | syoummer/boost.actor | 58f35499bac8871b8f5b0b024246a467b63c6fb0 | [
"BSL-1.0"
] | null | null | null | boost/actor/response_promise.hpp | syoummer/boost.actor | 58f35499bac8871b8f5b0b024246a467b63c6fb0 | [
"BSL-1.0"
] | null | null | null | /******************************************************************************\
* *
* ____ _ _ _ *
* | __ ) ___ ___ ___| |_ / \ ___| |_ ___ _ __ *
* | _ \ / _ \ / _ \/ __| __| / _ \ / __| __/ _ \| '__| *
* | |_) | (_) | (_) \__ \ |_ _ / ___ \ (__| || (_) | | *
* |____/ \___/ \___/|___/\__(_)_/ \_\___|\__\___/|_| *
* *
* *
* *
* Copyright (C) 2011 - 2014 *
* Dominik Charousset <[email protected]> *
* *
* Distributed under the Boost Software License, Version 1.0. See *
* accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt *
\******************************************************************************/
#ifndef BOOST_ACTOR_RESPONSE_PROMISE_HPP
#define BOOST_ACTOR_RESPONSE_PROMISE_HPP
#include "boost/actor/actor.hpp"
#include "boost/actor/message.hpp"
#include "boost/actor/actor_addr.hpp"
#include "boost/actor/message_id.hpp"
namespace boost {
namespace actor {
/**
* @brief A response promise can be used to deliver a uniquely identifiable
* response message from the server (i.e. receiver of the request)
* to the client (i.e. the sender of the request).
*/
class response_promise {
public:
response_promise() = default;
response_promise(response_promise&&) = default;
response_promise(const response_promise&) = default;
response_promise& operator=(response_promise&&) = default;
response_promise& operator=(const response_promise&) = default;
response_promise(const actor_addr& from,
const actor_addr& to,
const message_id& response_id);
/**
* @brief Queries whether this promise is still valid, i.e., no response
* was yet delivered to the client.
*/
inline explicit operator bool() const {
// handle is valid if it has a receiver
return static_cast<bool>(m_to);
}
/**
* @brief Sends @p response_message and invalidates this handle afterwards.
*/
void deliver(message response_message);
private:
actor_addr m_from;
actor_addr m_to;
message_id m_id;
};
} // namespace actor
} // namespace boost
#endif // BOOST_ACTOR_RESPONSE_PROMISE_HPP
| 36.921053 | 80 | 0.465075 | syoummer |
8adaf485d11acb911b7c988d600c130fce03a36e | 1,927 | cpp | C++ | Filesystem/Problem33/main.cpp | vegemil/ModernCppChallengeStudy | 52c2bb22c76ae3f3a883ae479cd70ac27513e78d | [
"MIT"
] | null | null | null | Filesystem/Problem33/main.cpp | vegemil/ModernCppChallengeStudy | 52c2bb22c76ae3f3a883ae479cd70ac27513e78d | [
"MIT"
] | null | null | null | Filesystem/Problem33/main.cpp | vegemil/ModernCppChallengeStudy | 52c2bb22c76ae3f3a883ae479cd70ac27513e78d | [
"MIT"
] | null | null | null | // 33. Tabular printing of a list of processes
// Suppose you have a snapshot of the list of all processes in a system. The
// information for each process includes name, identifier, status (which can be
// either running or suspended), account name (under which the process runs),
// memory size in bytes, and platform (which can be either 32-bit or 64-bit). Your
// task is to writer a function that takes such a list of processes and prints them
// to the console alphabetically, in tabular format. All columns must be left-
// aligned, except for the memory column which must be right-aligned. The value
// of the memory size must be displayed in KB. The following is an example of the
// output of this function:
// chrome.exe 1044 Running marius.bancila 25180 32-bit
// chrome.exe 10100 Running marius.bancila 227756 32-bit
// cmd.exe 512 Running SYSTEM 48 64-bit
// explorer.exe 7108 Running marius.bancila 29529 64-bit
// skype.exe 22456 Syspended marius.bancila 656 64-bit
// 33. 표로 정리된 프로세스들의 목록을 출력
// 당신이 어떤 시스템의 모든 프로세스들의 목록을 스냅샷으로 가지고 있다고 가정하자. 각 프로세
// 스의 정보는 이름, 식별자, 상태(running 또는 suspended 두 가지 상태일 수 있다), 계정 이름
// (프로세스가 동작중인 계정), 메모리 크기(byte), 그리고 플랫폼(32-bit 또는 64-bit 일 수 있
// 다)을 포함한다. 당신의 임무는 프로세스의 목록을 가져와서, 콘솔에 알파벳 표의 형식으로 목록
// 을 출력하는 함수를 작성하는 것이다. 모든 컬럼은 반드시 left-aligned 여야 하며, 메모리 컬럼
// 만 예외적으로 right-aligned 이다. 메모리 크기 값은 반드시 KB로 보여져야 한다. 아래에 보여
// 지는 것은, 이 하마수의 출력 예제이다:
// chrome.exe 1044 Running marius.bancila 25180 32-bit
// chrome.exe 10100 Running marius.bancila 227756 32-bit
// cmd.exe 512 Running SYSTEM 48 64-bit
// explorer.exe 7108 Running marius.bancila 29529 64-bit
// skype.exe 22456 Syspended marius.bancila 656 64-bit
#include "gsl/gsl"
// create `main` function for catch
#define CATCH_CONFIG_MAIN
#include "catch2/catch.hpp"
// Redirect CMake's #define to C++ constexpr string
constexpr auto TestName = PROJECT_NAME_STRING;
TEST_CASE("tokenize", "[Joining strings]") {
} | 48.175 | 83 | 0.741048 | vegemil |
8add19cc54e5ebc2f76a2f519d709fc650857952 | 1,090 | cpp | C++ | src/rendering/ui/ui_object.cpp | krait-games/hyperion-engine | 5c52085658630fbf0992f794ecfcb25325b80b1c | [
"MIT"
] | 21 | 2022-01-23T15:20:59.000Z | 2022-03-31T22:10:14.000Z | src/rendering/ui/ui_object.cpp | krait-games/hyperion-engine | 5c52085658630fbf0992f794ecfcb25325b80b1c | [
"MIT"
] | 2 | 2022-01-30T22:24:58.000Z | 2022-03-28T02:37:07.000Z | src/rendering/ui/ui_object.cpp | krait-games/hyperion-engine | 5c52085658630fbf0992f794ecfcb25325b80b1c | [
"MIT"
] | 2 | 2022-02-10T13:55:26.000Z | 2022-03-31T22:10:16.000Z | #include "ui_object.h"
#include "../shader_manager.h"
#include "../shaders/ui/ui_object_shader.h"
#include "../../util/mesh_factory.h"
#include <algorithm>
namespace hyperion {
namespace ui {
UIObject::UIObject(const std::string &name)
: Node(name)
{
GetMaterial().depth_test = false;
GetMaterial().depth_write = false;
GetMaterial().alpha_blended = true;
SetRenderable(MeshFactory::CreateQuad());
GetRenderable()->SetShader(ShaderManager::GetInstance()->GetShader<UIObjectShader>(ShaderProperties()));
GetSpatial().SetBucket(Spatial::Bucket::RB_SCREEN);
}
void UIObject::UpdateTransform()
{
Node::UpdateTransform();
}
bool UIObject::IsMouseOver(double x, double y) const
{
if (x < GetGlobalTranslation().x) {
return false;
}
if (x > GetGlobalTranslation().x + GetGlobalScale().x) {
return false;
}
if (y < GetGlobalTranslation().y) {
return false;
}
if (y > GetGlobalTranslation().y + GetGlobalScale().y) {
return false;
}
return true;
}
} // namespace ui
} // namespace hyperion
| 22.244898 | 108 | 0.659633 | krait-games |
8ae4e2ebf43f447bb0a682a75c0a49e80ec0fec8 | 32,004 | hpp | C++ | include/GlobalNamespace/PlayerSpecificSettings.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/PlayerSpecificSettings.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/PlayerSpecificSettings.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: NoteJumpDurationTypeSettings
#include "GlobalNamespace/NoteJumpDurationTypeSettings.hpp"
// Including type: EnvironmentEffectsFilterPreset
#include "GlobalNamespace/EnvironmentEffectsFilterPreset.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Nullable`1<T>
template<typename T>
struct Nullable_1;
}
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: BeatmapDifficulty
struct BeatmapDifficulty;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Forward declaring type: PlayerSpecificSettings
class PlayerSpecificSettings;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::GlobalNamespace::PlayerSpecificSettings);
DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::PlayerSpecificSettings*, "", "PlayerSpecificSettings");
// Type namespace:
namespace GlobalNamespace {
// Size: 0x44
#pragma pack(push, 1)
// Autogenerated type: PlayerSpecificSettings
// [TokenAttribute] Offset: FFFFFFFF
class PlayerSpecificSettings : public ::Il2CppObject {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// private System.Boolean _leftHanded
// Size: 0x1
// Offset: 0x10
bool leftHanded;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: leftHanded and: playerHeight
char __padding0[0x3] = {};
// private System.Single _playerHeight
// Size: 0x4
// Offset: 0x14
float playerHeight;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Boolean _automaticPlayerHeight
// Size: 0x1
// Offset: 0x18
bool automaticPlayerHeight;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: automaticPlayerHeight and: sfxVolume
char __padding2[0x3] = {};
// private System.Single _sfxVolume
// Size: 0x4
// Offset: 0x1C
float sfxVolume;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Boolean _reduceDebris
// Size: 0x1
// Offset: 0x20
bool reduceDebris;
// Field size check
static_assert(sizeof(bool) == 0x1);
// private System.Boolean _noTextsAndHuds
// Size: 0x1
// Offset: 0x21
bool noTextsAndHuds;
// Field size check
static_assert(sizeof(bool) == 0x1);
// private System.Boolean _noFailEffects
// Size: 0x1
// Offset: 0x22
bool noFailEffects;
// Field size check
static_assert(sizeof(bool) == 0x1);
// private System.Boolean _advancedHud
// Size: 0x1
// Offset: 0x23
bool advancedHud;
// Field size check
static_assert(sizeof(bool) == 0x1);
// private System.Boolean _autoRestart
// Size: 0x1
// Offset: 0x24
bool autoRestart;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: autoRestart and: saberTrailIntensity
char __padding8[0x3] = {};
// private System.Single _saberTrailIntensity
// Size: 0x4
// Offset: 0x28
float saberTrailIntensity;
// Field size check
static_assert(sizeof(float) == 0x4);
// private NoteJumpDurationTypeSettings _noteJumpDurationTypeSettings
// Size: 0x4
// Offset: 0x2C
::GlobalNamespace::NoteJumpDurationTypeSettings noteJumpDurationTypeSettings;
// Field size check
static_assert(sizeof(::GlobalNamespace::NoteJumpDurationTypeSettings) == 0x4);
// private System.Single _noteJumpFixedDuration
// Size: 0x4
// Offset: 0x30
float noteJumpFixedDuration;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Single _noteJumpStartBeatOffset
// Size: 0x4
// Offset: 0x34
float noteJumpStartBeatOffset;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Boolean _hideNoteSpawnEffect
// Size: 0x1
// Offset: 0x38
bool hideNoteSpawnEffect;
// Field size check
static_assert(sizeof(bool) == 0x1);
// private System.Boolean _adaptiveSfx
// Size: 0x1
// Offset: 0x39
bool adaptiveSfx;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: adaptiveSfx and: environmentEffectsFilterDefaultPreset
char __padding14[0x2] = {};
// private EnvironmentEffectsFilterPreset _environmentEffectsFilterDefaultPreset
// Size: 0x4
// Offset: 0x3C
::GlobalNamespace::EnvironmentEffectsFilterPreset environmentEffectsFilterDefaultPreset;
// Field size check
static_assert(sizeof(::GlobalNamespace::EnvironmentEffectsFilterPreset) == 0x4);
// private EnvironmentEffectsFilterPreset _environmentEffectsFilterExpertPlusPreset
// Size: 0x4
// Offset: 0x40
::GlobalNamespace::EnvironmentEffectsFilterPreset environmentEffectsFilterExpertPlusPreset;
// Field size check
static_assert(sizeof(::GlobalNamespace::EnvironmentEffectsFilterPreset) == 0x4);
public:
// Get instance field reference: private System.Boolean _leftHanded
bool& dyn__leftHanded();
// Get instance field reference: private System.Single _playerHeight
float& dyn__playerHeight();
// Get instance field reference: private System.Boolean _automaticPlayerHeight
bool& dyn__automaticPlayerHeight();
// Get instance field reference: private System.Single _sfxVolume
float& dyn__sfxVolume();
// Get instance field reference: private System.Boolean _reduceDebris
bool& dyn__reduceDebris();
// Get instance field reference: private System.Boolean _noTextsAndHuds
bool& dyn__noTextsAndHuds();
// Get instance field reference: private System.Boolean _noFailEffects
bool& dyn__noFailEffects();
// Get instance field reference: private System.Boolean _advancedHud
bool& dyn__advancedHud();
// Get instance field reference: private System.Boolean _autoRestart
bool& dyn__autoRestart();
// Get instance field reference: private System.Single _saberTrailIntensity
float& dyn__saberTrailIntensity();
// Get instance field reference: private NoteJumpDurationTypeSettings _noteJumpDurationTypeSettings
::GlobalNamespace::NoteJumpDurationTypeSettings& dyn__noteJumpDurationTypeSettings();
// Get instance field reference: private System.Single _noteJumpFixedDuration
float& dyn__noteJumpFixedDuration();
// Get instance field reference: private System.Single _noteJumpStartBeatOffset
float& dyn__noteJumpStartBeatOffset();
// Get instance field reference: private System.Boolean _hideNoteSpawnEffect
bool& dyn__hideNoteSpawnEffect();
// Get instance field reference: private System.Boolean _adaptiveSfx
bool& dyn__adaptiveSfx();
// Get instance field reference: private EnvironmentEffectsFilterPreset _environmentEffectsFilterDefaultPreset
::GlobalNamespace::EnvironmentEffectsFilterPreset& dyn__environmentEffectsFilterDefaultPreset();
// Get instance field reference: private EnvironmentEffectsFilterPreset _environmentEffectsFilterExpertPlusPreset
::GlobalNamespace::EnvironmentEffectsFilterPreset& dyn__environmentEffectsFilterExpertPlusPreset();
// public System.Boolean get_leftHanded()
// Offset: 0x1372B30
bool get_leftHanded();
// public System.Single get_playerHeight()
// Offset: 0x1372B38
float get_playerHeight();
// public System.Boolean get_automaticPlayerHeight()
// Offset: 0x1372B40
bool get_automaticPlayerHeight();
// public System.Single get_sfxVolume()
// Offset: 0x1372B48
float get_sfxVolume();
// public System.Boolean get_reduceDebris()
// Offset: 0x1372B50
bool get_reduceDebris();
// public System.Boolean get_noTextsAndHuds()
// Offset: 0x1372B58
bool get_noTextsAndHuds();
// public System.Boolean get_noFailEffects()
// Offset: 0x1372B60
bool get_noFailEffects();
// public System.Boolean get_advancedHud()
// Offset: 0x1372B68
bool get_advancedHud();
// public System.Boolean get_autoRestart()
// Offset: 0x1372B70
bool get_autoRestart();
// public System.Single get_saberTrailIntensity()
// Offset: 0x1372B78
float get_saberTrailIntensity();
// public NoteJumpDurationTypeSettings get_noteJumpDurationTypeSettings()
// Offset: 0x1372B80
::GlobalNamespace::NoteJumpDurationTypeSettings get_noteJumpDurationTypeSettings();
// public System.Single get_noteJumpFixedDuration()
// Offset: 0x1372B88
float get_noteJumpFixedDuration();
// public System.Single get_noteJumpStartBeatOffset()
// Offset: 0x1372B90
float get_noteJumpStartBeatOffset();
// public System.Boolean get_hideNoteSpawnEffect()
// Offset: 0x1372B98
bool get_hideNoteSpawnEffect();
// public System.Boolean get_adaptiveSfx()
// Offset: 0x1372BA0
bool get_adaptiveSfx();
// public EnvironmentEffectsFilterPreset get_environmentEffectsFilterDefaultPreset()
// Offset: 0x1372BA8
::GlobalNamespace::EnvironmentEffectsFilterPreset get_environmentEffectsFilterDefaultPreset();
// public EnvironmentEffectsFilterPreset get_environmentEffectsFilterExpertPlusPreset()
// Offset: 0x1372BB0
::GlobalNamespace::EnvironmentEffectsFilterPreset get_environmentEffectsFilterExpertPlusPreset();
// public System.Void .ctor(System.Boolean leftHanded, System.Single playerHeight, System.Boolean automaticPlayerHeight, System.Single sfxVolume, System.Boolean reduceDebris, System.Boolean noTextsAndHuds, System.Boolean noFailEffects, System.Boolean advancedHud, System.Boolean autoRestart, System.Single saberTrailIntensity, NoteJumpDurationTypeSettings noteJumpDurationTypeSettings, System.Single noteJumpFixedDuration, System.Single noteJumpStartBeatOffset, System.Boolean hideNoteSpawnEffect, System.Boolean adaptiveSfx, EnvironmentEffectsFilterPreset environmentEffectsFilterDefaultPreset, EnvironmentEffectsFilterPreset environmentEffectsFilterExpertPlusPreset)
// Offset: 0x1372C2C
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static PlayerSpecificSettings* New_ctor(bool leftHanded, float playerHeight, bool automaticPlayerHeight, float sfxVolume, bool reduceDebris, bool noTextsAndHuds, bool noFailEffects, bool advancedHud, bool autoRestart, float saberTrailIntensity, ::GlobalNamespace::NoteJumpDurationTypeSettings noteJumpDurationTypeSettings, float noteJumpFixedDuration, float noteJumpStartBeatOffset, bool hideNoteSpawnEffect, bool adaptiveSfx, ::GlobalNamespace::EnvironmentEffectsFilterPreset environmentEffectsFilterDefaultPreset, ::GlobalNamespace::EnvironmentEffectsFilterPreset environmentEffectsFilterExpertPlusPreset) {
static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::PlayerSpecificSettings::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<PlayerSpecificSettings*, creationType>(leftHanded, playerHeight, automaticPlayerHeight, sfxVolume, reduceDebris, noTextsAndHuds, noFailEffects, advancedHud, autoRestart, saberTrailIntensity, noteJumpDurationTypeSettings, noteJumpFixedDuration, noteJumpStartBeatOffset, hideNoteSpawnEffect, adaptiveSfx, environmentEffectsFilterDefaultPreset, environmentEffectsFilterExpertPlusPreset)));
}
// public PlayerSpecificSettings CopyWith(System.Nullable`1<System.Boolean> leftHanded, System.Nullable`1<System.Single> playerHeight, System.Nullable`1<System.Boolean> automaticPlayerHeight, System.Nullable`1<System.Single> sfxVolume, System.Nullable`1<System.Boolean> reduceDebris, System.Nullable`1<System.Boolean> noTextsAndHuds, System.Nullable`1<System.Boolean> noFailEffects, System.Nullable`1<System.Boolean> advancedHud, System.Nullable`1<System.Boolean> autoRestart, System.Nullable`1<System.Single> saberTrailIntensity, System.Nullable`1<NoteJumpDurationTypeSettings> noteJumpDurationTypeSettings, System.Nullable`1<System.Single> noteJumpFixedDuration, System.Nullable`1<System.Single> noteJumpStartBeatOffset, System.Nullable`1<System.Boolean> hideNoteSpawnEffect, System.Nullable`1<System.Boolean> adaptiveSfx, System.Nullable`1<EnvironmentEffectsFilterPreset> environmentEffectsFilterDefaultPreset, System.Nullable`1<EnvironmentEffectsFilterPreset> environmentEffectsFilterExpertPlusPreset)
// Offset: 0x1371A10
::GlobalNamespace::PlayerSpecificSettings* CopyWith(::System::Nullable_1<bool> leftHanded, ::System::Nullable_1<float> playerHeight, ::System::Nullable_1<bool> automaticPlayerHeight, ::System::Nullable_1<float> sfxVolume, ::System::Nullable_1<bool> reduceDebris, ::System::Nullable_1<bool> noTextsAndHuds, ::System::Nullable_1<bool> noFailEffects, ::System::Nullable_1<bool> advancedHud, ::System::Nullable_1<bool> autoRestart, ::System::Nullable_1<float> saberTrailIntensity, ::System::Nullable_1<::GlobalNamespace::NoteJumpDurationTypeSettings> noteJumpDurationTypeSettings, ::System::Nullable_1<float> noteJumpFixedDuration, ::System::Nullable_1<float> noteJumpStartBeatOffset, ::System::Nullable_1<bool> hideNoteSpawnEffect, ::System::Nullable_1<bool> adaptiveSfx, ::System::Nullable_1<::GlobalNamespace::EnvironmentEffectsFilterPreset> environmentEffectsFilterDefaultPreset, ::System::Nullable_1<::GlobalNamespace::EnvironmentEffectsFilterPreset> environmentEffectsFilterExpertPlusPreset);
// public EnvironmentEffectsFilterPreset GetEnvironmentEffectsFilterPreset(BeatmapDifficulty difficulty)
// Offset: 0x1372D4C
::GlobalNamespace::EnvironmentEffectsFilterPreset GetEnvironmentEffectsFilterPreset(::GlobalNamespace::BeatmapDifficulty difficulty);
// public System.Void .ctor()
// Offset: 0x1372BB8
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static PlayerSpecificSettings* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::PlayerSpecificSettings::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<PlayerSpecificSettings*, creationType>()));
}
}; // PlayerSpecificSettings
#pragma pack(pop)
static check_size<sizeof(PlayerSpecificSettings), 64 + sizeof(::GlobalNamespace::EnvironmentEffectsFilterPreset)> __GlobalNamespace_PlayerSpecificSettingsSizeCheck;
static_assert(sizeof(PlayerSpecificSettings) == 0x44);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_leftHanded
// Il2CppName: get_leftHanded
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_leftHanded)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_leftHanded", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_playerHeight
// Il2CppName: get_playerHeight
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_playerHeight)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_playerHeight", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_automaticPlayerHeight
// Il2CppName: get_automaticPlayerHeight
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_automaticPlayerHeight)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_automaticPlayerHeight", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_sfxVolume
// Il2CppName: get_sfxVolume
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_sfxVolume)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_sfxVolume", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_reduceDebris
// Il2CppName: get_reduceDebris
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_reduceDebris)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_reduceDebris", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_noTextsAndHuds
// Il2CppName: get_noTextsAndHuds
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_noTextsAndHuds)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_noTextsAndHuds", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_noFailEffects
// Il2CppName: get_noFailEffects
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_noFailEffects)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_noFailEffects", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_advancedHud
// Il2CppName: get_advancedHud
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_advancedHud)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_advancedHud", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_autoRestart
// Il2CppName: get_autoRestart
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_autoRestart)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_autoRestart", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_saberTrailIntensity
// Il2CppName: get_saberTrailIntensity
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_saberTrailIntensity)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_saberTrailIntensity", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_noteJumpDurationTypeSettings
// Il2CppName: get_noteJumpDurationTypeSettings
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::NoteJumpDurationTypeSettings (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_noteJumpDurationTypeSettings)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_noteJumpDurationTypeSettings", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_noteJumpFixedDuration
// Il2CppName: get_noteJumpFixedDuration
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_noteJumpFixedDuration)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_noteJumpFixedDuration", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_noteJumpStartBeatOffset
// Il2CppName: get_noteJumpStartBeatOffset
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_noteJumpStartBeatOffset)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_noteJumpStartBeatOffset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_hideNoteSpawnEffect
// Il2CppName: get_hideNoteSpawnEffect
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_hideNoteSpawnEffect)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_hideNoteSpawnEffect", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_adaptiveSfx
// Il2CppName: get_adaptiveSfx
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_adaptiveSfx)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_adaptiveSfx", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_environmentEffectsFilterDefaultPreset
// Il2CppName: get_environmentEffectsFilterDefaultPreset
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::EnvironmentEffectsFilterPreset (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_environmentEffectsFilterDefaultPreset)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_environmentEffectsFilterDefaultPreset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_environmentEffectsFilterExpertPlusPreset
// Il2CppName: get_environmentEffectsFilterExpertPlusPreset
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::EnvironmentEffectsFilterPreset (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_environmentEffectsFilterExpertPlusPreset)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_environmentEffectsFilterExpertPlusPreset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::CopyWith
// Il2CppName: CopyWith
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::PlayerSpecificSettings* (GlobalNamespace::PlayerSpecificSettings::*)(::System::Nullable_1<bool>, ::System::Nullable_1<float>, ::System::Nullable_1<bool>, ::System::Nullable_1<float>, ::System::Nullable_1<bool>, ::System::Nullable_1<bool>, ::System::Nullable_1<bool>, ::System::Nullable_1<bool>, ::System::Nullable_1<bool>, ::System::Nullable_1<float>, ::System::Nullable_1<::GlobalNamespace::NoteJumpDurationTypeSettings>, ::System::Nullable_1<float>, ::System::Nullable_1<float>, ::System::Nullable_1<bool>, ::System::Nullable_1<bool>, ::System::Nullable_1<::GlobalNamespace::EnvironmentEffectsFilterPreset>, ::System::Nullable_1<::GlobalNamespace::EnvironmentEffectsFilterPreset>)>(&GlobalNamespace::PlayerSpecificSettings::CopyWith)> {
static const MethodInfo* get() {
static auto* leftHanded = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg;
static auto* playerHeight = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Single")})->byval_arg;
static auto* automaticPlayerHeight = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg;
static auto* sfxVolume = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Single")})->byval_arg;
static auto* reduceDebris = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg;
static auto* noTextsAndHuds = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg;
static auto* noFailEffects = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg;
static auto* advancedHud = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg;
static auto* autoRestart = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg;
static auto* saberTrailIntensity = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Single")})->byval_arg;
static auto* noteJumpDurationTypeSettings = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "NoteJumpDurationTypeSettings")})->byval_arg;
static auto* noteJumpFixedDuration = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Single")})->byval_arg;
static auto* noteJumpStartBeatOffset = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Single")})->byval_arg;
static auto* hideNoteSpawnEffect = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg;
static auto* adaptiveSfx = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg;
static auto* environmentEffectsFilterDefaultPreset = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "EnvironmentEffectsFilterPreset")})->byval_arg;
static auto* environmentEffectsFilterExpertPlusPreset = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "EnvironmentEffectsFilterPreset")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "CopyWith", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{leftHanded, playerHeight, automaticPlayerHeight, sfxVolume, reduceDebris, noTextsAndHuds, noFailEffects, advancedHud, autoRestart, saberTrailIntensity, noteJumpDurationTypeSettings, noteJumpFixedDuration, noteJumpStartBeatOffset, hideNoteSpawnEffect, adaptiveSfx, environmentEffectsFilterDefaultPreset, environmentEffectsFilterExpertPlusPreset});
}
};
// Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::GetEnvironmentEffectsFilterPreset
// Il2CppName: GetEnvironmentEffectsFilterPreset
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::EnvironmentEffectsFilterPreset (GlobalNamespace::PlayerSpecificSettings::*)(::GlobalNamespace::BeatmapDifficulty)>(&GlobalNamespace::PlayerSpecificSettings::GetEnvironmentEffectsFilterPreset)> {
static const MethodInfo* get() {
static auto* difficulty = &::il2cpp_utils::GetClassFromName("", "BeatmapDifficulty")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "GetEnvironmentEffectsFilterPreset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{difficulty});
}
};
// Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 70.030635 | 1,010 | 0.76731 | RedBrumbler |
8ae5d409101796e92d796219f8f8aed03f9df2df | 741 | cpp | C++ | FortuneHunter/FortuneHunter/ConfirmQuitCommandProcessor.cpp | playdeezgames/FortuneHunter | 44bbf19e728aa8c3330a08876809dd471b92311b | [
"MIT"
] | null | null | null | FortuneHunter/FortuneHunter/ConfirmQuitCommandProcessor.cpp | playdeezgames/FortuneHunter | 44bbf19e728aa8c3330a08876809dd471b92311b | [
"MIT"
] | null | null | null | FortuneHunter/FortuneHunter/ConfirmQuitCommandProcessor.cpp | playdeezgames/FortuneHunter | 44bbf19e728aa8c3330a08876809dd471b92311b | [
"MIT"
] | null | null | null | #include "ConfirmQuitCommandProcessor.h"
void ConfirmQuitCommandProcessor::OnCommand(const Command& command)
{
switch (command)
{
case Command::UP:
case Command::DOWN:
confirmState = (confirmState==ConfirmState::YES) ? (ConfirmState::NO) : (ConfirmState::YES);
return;
case Command::BACK:
SetUIState(UIState::MAIN_MENU);
return;
case Command::GREEN:
switch (confirmState)
{
case ConfirmState::YES:
SetUIState(UIState::QUIT);
return;
case ConfirmState::NO:
SetUIState(UIState::MAIN_MENU);
return;
default:
return;
}
}
}
ConfirmQuitCommandProcessor::ConfirmQuitCommandProcessor
(
UIState& uiState,
ConfirmState& confirmState
)
: BaseCommandProcessor(uiState)
, confirmState(confirmState)
{
} | 20.027027 | 94 | 0.731444 | playdeezgames |
8ae6248f6889794f112db1896ac4c959f75d3c90 | 712 | cpp | C++ | casbin/persist/file_adapter/batch_file_adapter.cpp | xcaptain/casbin-cpp | d90e72d921f4a3369692913cfbcab2047343a49b | [
"Apache-2.0"
] | null | null | null | casbin/persist/file_adapter/batch_file_adapter.cpp | xcaptain/casbin-cpp | d90e72d921f4a3369692913cfbcab2047343a49b | [
"Apache-2.0"
] | null | null | null | casbin/persist/file_adapter/batch_file_adapter.cpp | xcaptain/casbin-cpp | d90e72d921f4a3369692913cfbcab2047343a49b | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "pch.h"
#include "./batch_file_adapter.h"
#include "../../exception/unsupported_operation_exception.h"
// NewAdapter is the constructor for Adapter.
BatchFileAdapter* BatchFileAdapter :: NewAdapter(string file_path) {
BatchFileAdapter* adapter = new BatchFileAdapter;
adapter->file_path = file_path;
adapter->filtered = false;
return adapter;
}
void BatchFileAdapter :: AddPolicies(string sec, string p_type, vector<vector<string>> rules) {
throw UnsupportedOperationException("not implemented hello");
}
void BatchFileAdapter :: RemovePolicies(string sec, string p_type, vector<vector<string>> rules) {
throw UnsupportedOperationException("not implemented");
} | 32.363636 | 98 | 0.761236 | xcaptain |
8aef81e187d39ab8b4eb1c25fb16944072ff28a5 | 3,382 | cc | C++ | src/lib/hooks/tests/full_callout_library.cc | sebschrader/debian-pkg-isc-kea | 1bdb18f90c48dd9674374fb8454d0efb846656bc | [
"Apache-2.0"
] | null | null | null | src/lib/hooks/tests/full_callout_library.cc | sebschrader/debian-pkg-isc-kea | 1bdb18f90c48dd9674374fb8454d0efb846656bc | [
"Apache-2.0"
] | null | null | null | src/lib/hooks/tests/full_callout_library.cc | sebschrader/debian-pkg-isc-kea | 1bdb18f90c48dd9674374fb8454d0efb846656bc | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2013-2015 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
/// @file
/// @brief Full callout library
///
/// This is source of a test library for various test (LibraryManager and
/// HooksManager). The characteristics of the library produced from this
/// file are:
///
/// The characteristics of this library are:
///
/// - All three framework functions are supplied (version(), load() and
/// unload()), with unload() creating a marker file. The test code checks
/// for the presence of this file, so verifying that unload() has been run.
///
/// - One standard and two non-standard callouts are supplied, with the latter
/// being registered by the load() function.
///
/// All callouts do trivial calculations, the result of all being called in
/// sequence being
///
/// @f[ ((7 * data_1) - data_2) * data_3 @f]
///
/// ...where data_1, data_2 and data_3 are the values passed in arguments of
/// the same name to the three callouts (data_1 passed to hookpt_one, data_2
/// to hookpt_two etc.) and the result is returned in the argument "result".
#include <config.h>
#include <hooks/hooks.h>
#include <hooks/tests/marker_file.h>
#include <fstream>
using namespace isc::hooks;
extern "C" {
// Callouts
int
context_create(CalloutHandle& handle) {
handle.setContext("result", static_cast<int>(7));
handle.setArgument("result", static_cast<int>(7));
return (0);
}
// First callout adds the passed "data_1" argument to the initialized context
// value of 7. (Note that the value set by context_create is accessed through
// context and not the argument, so checking that context is correctly passed
// between callouts in the same library.)
int
hookpt_one(CalloutHandle& handle) {
int data;
handle.getArgument("data_1", data);
int result;
handle.getArgument("result", result);
result *= data;
handle.setArgument("result", result);
return (0);
}
// Second callout subtracts the passed value of data_2 from the current
// running total.
static int
hook_nonstandard_two(CalloutHandle& handle) {
int data;
handle.getArgument("data_2", data);
int result;
handle.getArgument("result", result);
result -= data;
handle.setArgument("result", result);
return (0);
}
// Final callout multiplies the current running total by data_3.
static int
hook_nonstandard_three(CalloutHandle& handle) {
int data;
handle.getArgument("data_3", data);
int result;
handle.getArgument("result", result);
result *= data;
handle.setArgument("result", result);
return (0);
}
// Framework functions
int
version() {
return (KEA_HOOKS_VERSION);
}
int
load(LibraryHandle& handle) {
// Initialize if the main image was statically linked
#ifdef USE_STATIC_LINK
hooksStaticLinkInit();
#endif
// Register the non-standard functions
handle.registerCallout("hookpt_two", hook_nonstandard_two);
handle.registerCallout("hookpt_three", hook_nonstandard_three);
return (0);
}
int
unload() {
// Create the marker file.
std::fstream marker;
marker.open(MARKER_FILE, std::fstream::out);
marker.close();
return (0);
}
};
| 24.867647 | 78 | 0.693968 | sebschrader |
8af10568434c6c5ef925481bedf9d47380ad0372 | 3,167 | cpp | C++ | tests/stage2/motion/motion.cpp | PtCu/RenderToy | a53be2b6d8c91f7b132cee47b377e327a9605fbb | [
"MIT"
] | 2 | 2021-03-17T07:32:18.000Z | 2021-04-01T14:58:51.000Z | tests/stage2/motion/motion.cpp | PtCu/RenderToy | a53be2b6d8c91f7b132cee47b377e327a9605fbb | [
"MIT"
] | null | null | null | tests/stage2/motion/motion.cpp | PtCu/RenderToy | a53be2b6d8c91f7b132cee47b377e327a9605fbb | [
"MIT"
] | null | null | null |
#include <render_toy.h>
#include <ROOT_PATH.h>
using namespace platinum;
using namespace glm;
using namespace std;
const static string root_path(ROOT_PATH);
const static string assets_path = root_path + "/assets/";
void random_scene(Scene &world)
{
int n = 500;
shared_ptr<Object> sph;
sph = make_shared<Sphere>(vec3(0, -1000, 0), 1000, make_shared<Lambertian>(vec3(0.5, 0.5, 0.5)));
world.AddObject(sph);
int i = 1;
for (int a = -11; a < 11; a++)
{
for (int b = -11; b < 11; b++)
{
float choose_mat = Random::RandomInUnitFloat();
vec3 center(a + 0.9 * Random::RandomInUnitFloat(), 0.2, b + 0.9 * Random::RandomInUnitFloat());
if (length(center - vec3(4, 0.2, 0)) > 0.9)
{
if (choose_mat < 0.8)
{ // diffuse
sph = make_shared<MovingSphere>(center,
center + vec3(0, 0.5 * Random::RandomInUnitFloat(), 0),
0.0, 1.0, 0.2,
make_shared<Lambertian>(vec3(Random::RandomInUnitFloat() * Random::RandomInUnitFloat(),
Random::RandomInUnitFloat() * Random::RandomInUnitFloat(),
Random::RandomInUnitFloat() * Random::RandomInUnitFloat())));
}
else if (choose_mat < 0.95)
{ // metal
sph = make_shared<Sphere>(center, 0.2f,
make_shared<Metal>(vec3(0.5 * (1 + Random::RandomInUnitFloat()),
0.5 * (1 + Random::RandomInUnitFloat()),
0.5 * (1 + Random::RandomInUnitFloat())),
0.5 * Random::RandomInUnitFloat()));
}
else
{ // glass
sph = make_shared<Sphere>(center, 0.2f,
make_shared<Dielectric>(1.5));
}
world.AddObject(sph);
}
}
}
world.AddObject(make_shared<Sphere>(vec3(0, 1, 0), 1.0, make_shared<Dielectric>(1.5)));
world.AddObject(make_shared<Sphere>(vec3(-4, 1, 0), 1.0, make_shared<Lambertian>(vec3(0.4, 0.2, 0.1))));
world.AddObject(make_shared<Sphere>(vec3(4, 1, 0), 1.0, make_shared<Metal>(vec3(0.7, 0.6, 0.5), 0.0)));
}
int main()
{
int nx = 1200;
int ny = 800;
int ns = 100;
Scene world(true,false);
random_scene(world);
vec3 lookfrom(13, 2, 3);
vec3 lookat(0, 0, 0);
float dist_to_focus = 10.0f;
float aperture = 0.1f;
Camera cam(lookfrom, lookat, vec3(0, -1, 0), 45, static_cast<float>(nx) / static_cast<float>(ny), aperture, dist_to_focus);
Renderer render(nx, ny, 3, "motion.png", ns);
render.Render(world, cam);
world.Reset();
return 0;
}
| 39.098765 | 142 | 0.462899 | PtCu |
8af2d89b5a52efc264df5851264851c7046575bc | 463 | cpp | C++ | gameboy/src/harucar/LuaCommandViewer.cpp | JJhuk/study_emu | 24f8a55496486d534edd1cb713b056d862641a22 | [
"MIT"
] | 9 | 2020-05-22T09:42:42.000Z | 2022-01-06T00:51:15.000Z | gameboy/src/harucar/LuaCommandViewer.cpp | JJhuk/study_emu | 24f8a55496486d534edd1cb713b056d862641a22 | [
"MIT"
] | 1 | 2021-04-18T06:56:03.000Z | 2021-04-18T06:56:03.000Z | gameboy/src/harucar/LuaCommandViewer.cpp | JJhuk/study_emu | 24f8a55496486d534edd1cb713b056d862641a22 | [
"MIT"
] | 3 | 2020-05-17T15:31:14.000Z | 2022-01-06T12:18:03.000Z | //
// Created by nhy20 on 2020-11-01.
//
#include "LuaCommandViewer.h"
#include "imgui.h"
void LuaCommandViewer::Render(std::shared_ptr<Base::Interface::Provider> provider_ptr,
std::shared_ptr<UI::Structure::UIEventProtocol> protocol_ptr)
{
ImGui::Begin("Lua Command Viewer");
if (ImGui::Button("Reload"))
{
protocol_ptr->AddEvent("Lua:Reload");
}
if (ImGui::Button("Execute"))
{
protocol_ptr->AddEvent("Lua:Execute");
}
ImGui::End();
}
| 18.52 | 86 | 0.682505 | JJhuk |
8af594afdcbf53ad17242d6af37d99888f3303bb | 2,599 | hpp | C++ | source/Utilities/BasicCameraControllers.hpp | dantros/MonaEngine | e3d0048c2fe2dd282b84686f0e31e5741714222b | [
"MIT"
] | null | null | null | source/Utilities/BasicCameraControllers.hpp | dantros/MonaEngine | e3d0048c2fe2dd282b84686f0e31e5741714222b | [
"MIT"
] | null | null | null | source/Utilities/BasicCameraControllers.hpp | dantros/MonaEngine | e3d0048c2fe2dd282b84686f0e31e5741714222b | [
"MIT"
] | 1 | 2021-09-07T03:06:01.000Z | 2021-09-07T03:06:01.000Z | #pragma once
#ifndef BASICCAMERACONTROLLER_HPP
#define BASICCAMERACONTROLLER_HPP
#include "../World/World.hpp"
#include "../Platform/KeyCodes.hpp"
namespace Mona {
class BasicPerspectiveCamera : public GameObject {
public:
BasicPerspectiveCamera() = default;
virtual void UserStartUp(World& world) noexcept override
{
m_transform = world.AddComponent<TransformComponent>(*this);
m_camera = world.AddComponent<CameraComponent>(*this);
m_transform->Translate(glm::vec3(0.0f, -5.0f, 0.0f));
auto& input = world.GetInput();
glm::vec2 res = world.GetWindow().GetWindowDimensions();
screenPos = glm::vec2(1 / res.x, 1 / res.y) * glm::vec2(input.GetMousePosition());
}
void SetActive(bool active) { m_active = active; }
virtual void UserUpdate(World& world, float timeStep) noexcept override
{
auto& input = world.GetInput();
if(m_active) {
if (input.IsKeyPressed(MONA_KEY_A)) {
glm::vec3 right = m_transform->GetRightVector();
m_transform->Translate(-m_cameraSpeed * timeStep * right);
}
else if (input.IsKeyPressed(MONA_KEY_D)) {
glm::vec3 right = m_transform->GetRightVector();
m_transform->Translate(m_cameraSpeed * timeStep * right);
}
if (input.IsKeyPressed(MONA_KEY_W)) {
glm::vec3 front = m_transform->GetFrontVector();
m_transform->Translate(m_cameraSpeed * timeStep * front);
}
else if (input.IsKeyPressed(MONA_KEY_S)) {
glm::vec3 front = m_transform->GetFrontVector();
m_transform->Translate(-m_cameraSpeed * timeStep * front);
}
if (input.IsKeyPressed(MONA_KEY_E)) {
m_transform->Rotate(glm::vec3(0.0f,1.0f,0.0f), m_rollSpeed * timeStep);
}
else if (input.IsKeyPressed(MONA_KEY_Q)) {
m_transform->Rotate(glm::vec3(0.0f, 1.0f, 0.0f), -m_rollSpeed * timeStep);
}
}
glm::vec2 res = world.GetWindow().GetWindowDimensions();
glm::vec2 newScreenPos = glm::vec2(1/res.x, 1/res.y) * glm::vec2(input.GetMousePosition());
glm::vec2 delta = newScreenPos - screenPos;
if (glm::length2(delta) != 0.0f && m_active)
{
float amountX = delta.x * m_rotationSpeed;
float amountY = delta.y * m_rotationSpeed;
m_transform->Rotate(glm::vec3(0.0f,0.0f,-1.0f), amountX);
m_transform->Rotate(glm::vec3(-1.0, 0.0f, 0.0f), amountY);
}
screenPos = newScreenPos;
}
private:
bool m_active = true;
float m_cameraSpeed = 2.0f;
float m_rollSpeed = 1.5f;
float m_rotationSpeed = 1.5f;
TransformHandle m_transform;
CameraHandle m_camera;
glm::vec2 screenPos;
};
}
#endif | 30.576471 | 94 | 0.671027 | dantros |
c10084d69335f87a04e35a413d4e8101307b5f0d | 1,497 | hpp | C++ | include/LIEF/Abstract/json.hpp | lkollar/LIEF | 04037644af42c75fbace582bd2eb64c061a197e5 | [
"Apache-2.0"
] | 4 | 2020-09-19T21:23:47.000Z | 2020-10-02T19:17:04.000Z | include/LIEF/Abstract/json.hpp | prarthanats/LIEF | b26abae9a9b0dc0e82dd803b7b54a2a9dfe1034a | [
"Apache-2.0"
] | 1 | 2018-12-22T16:08:03.000Z | 2018-12-22T16:08:21.000Z | include/LIEF/Abstract/json.hpp | prarthanats/LIEF | b26abae9a9b0dc0e82dd803b7b54a2a9dfe1034a | [
"Apache-2.0"
] | 1 | 2018-12-30T10:00:48.000Z | 2018-12-30T10:00:48.000Z | /* Copyright 2017 R. Thomas
* Copyright 2017 Quarkslab
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LIEF_ABSTRACT_JSON_H_
#define LIEF_ABSTRACT_JSON_H_
#include "LIEF/config.h"
#ifdef LIEF_JSON_SUPPORT
#include "LIEF/visibility.h"
#include "LIEF/visitors/json.hpp"
#include "LIEF/Abstract.hpp"
namespace LIEF {
LIEF_API json to_json_from_abstract(const Object& v);
LIEF_API std::string to_json_str_from_abstract(const Object& v);
class LIEF_API AbstractJsonVisitor : public LIEF::JsonVisitor {
public:
using LIEF::JsonVisitor::JsonVisitor;
public:
virtual void visit(const Binary& binary) override;
virtual void visit(const Header& header) override;
virtual void visit(const Section& section) override;
virtual void visit(const Symbol& symbol) override;
virtual void visit(const Relocation& relocation) override;
virtual void visit(const Function& f) override;
};
}
#endif // LIEF_JSON_SUPPORT
#endif
| 29.352941 | 75 | 0.741483 | lkollar |
c10392664e47ce224775b7ff50610219c4869736 | 23,489 | cpp | C++ | src/Simulation.cpp | ericwolter/position-based-fluids | 30e92ead037b397573a0b7fb9fbac3770093793a | [
"MIT"
] | 2 | 2018-01-03T01:26:54.000Z | 2022-01-01T08:43:04.000Z | src/Simulation.cpp | ericwolter/position-based-fluids | 30e92ead037b397573a0b7fb9fbac3770093793a | [
"MIT"
] | null | null | null | src/Simulation.cpp | ericwolter/position-based-fluids | 30e92ead037b397573a0b7fb9fbac3770093793a | [
"MIT"
] | null | null | null |
#include "Precomp_OpenGL.h"
#include "Simulation.hpp"
#include "Resources.hpp"
#include "ParamUtils.hpp"
#include "ocl/OCLUtils.hpp"
#include "SOIL.h"
#define _USE_MATH_DEFINES
#include <math.h>
#include <cmath>
#include <sstream>
#include <algorithm>
using namespace std;
cl::Memory Simulation::CreateCachedBuffer(cl::ImageFormat& format, int elements)
{
if (format.image_channel_order != CL_RGBA)
throw "Image type is not supported";
// Choose what type should be created
if (Params.EnableCachedBuffers)
return cl::Image2D(mCLContext, CL_MEM_READ_WRITE, format, 2048, DivCeil(elements, 2048));
else
return cl::Buffer(mCLContext, CL_MEM_READ_WRITE, elements * sizeof(float) * 4);
}
void OCL_InitMemory(cl::CommandQueue& queue, cl::Memory& mem, void* pData = NULL, int nDataSize = 0)
{
// Get buffer size
int memSize = mem.getInfo<CL_MEM_SIZE>();
// Create memory
char* pBuf = new char[memSize];
memset(pBuf, 0, memSize);
// Fill with data
if ((pData != NULL) && (nDataSize > 0))
for (int i = 0; i < memSize; i++)
pBuf[i] = ((char*)pData)[i % nDataSize];
// Choose the way to transfer the data
switch (mem.getInfo<CL_MEM_TYPE>())
{
case CL_MEM_OBJECT_BUFFER:
queue.enqueueWriteBuffer(*((cl::Buffer*)&mem), CL_TRUE, 0, memSize, pBuf);
break;
}
// Release memory
delete[] pBuf;
}
Simulation::Simulation(const cl::Context &clContext, const cl::Device &clDevice)
: mCLContext(clContext),
mCLDevice(clDevice),
bDumpParticlesData(false)
{
// Create Queue
mQueue = cl::CommandQueue(mCLContext, mCLDevice, CL_QUEUE_PROFILING_ENABLE);
}
Simulation::~Simulation()
{
glFinish();
mQueue.finish();
}
void Simulation::CreateParticles()
{
// Create buffers
cl_float4* positions = new cl_float4[Params.particleCount];
// Compute particle count per axis
int ParticlesPerAxis = (int)ceil(pow(Params.particleCount, 1 / 3.0));
// Build particles blcok
float d = Params.h * Params.setupSpacing;
float offsetX = (1.0f - ParticlesPerAxis * d) / 2.0f;
float offsetY = 0.3f;
float offsetZ = (1.0f - ParticlesPerAxis * d) / 2.0f;
for (cl_uint i = 0; i < Params.particleCount; i++)
{
cl_uint x = ((cl_uint)(i / pow(ParticlesPerAxis, 1)) % ParticlesPerAxis);
cl_uint y = ((cl_uint)(i / pow(ParticlesPerAxis, 0)) % ParticlesPerAxis);
cl_uint z = ((cl_uint)(i / pow(ParticlesPerAxis, 2)) % ParticlesPerAxis);
positions[i].s[0] = offsetX + (x /*+ (y % 2) * .5*/) * d;
positions[i].s[1] = offsetY + (y) * d;
positions[i].s[2] = offsetZ + (z /*+ (y % 2) * .5*/) * d;
positions[i].s[3] = 0;
}
// Copy data from Host to GPU
OCL_InitMemory(mQueue, mPositionsPingBuffer, positions , sizeof(positions[0]) * Params.particleCount);
OCL_InitMemory(mQueue, mVelocitiesBuffer);
delete[] positions;
}
const std::string *Simulation::KernelFileList()
{
static const std::string kernels[] =
{
"hesp.hpp",
"parameters.hpp",
"logging.cl",
"utilities.cl",
"predict_positions.cl",
"update_cells.cl",
"build_friends_list.cl",
"reset_grid.cl",
"compute_scaling.cl",
"compute_delta.cl",
"update_predicted.cl",
"pack_data.cl",
"update_velocities.cl",
"apply_viscosity.cl",
"apply_vorticity.cl",
"radixsort.cl",
""
};
return kernels;
}
bool Simulation::InitKernels()
{
// Setup OpenCL Ranges
const cl_uint globalSize = (cl_uint)ceil(Params.particleCount / 32.0f) * 32;
mGlobalRange = cl::NDRange(globalSize);
mLocalRange = cl::NullRange;
// Notify OCL logging that we're about to start new kernel processing
oclLog.StartKernelProcessing(mCLContext, mCLDevice, 4096);
// setup kernel sources
OCLUtils clSetup;
vector<string> kernelSources;
// Load kernel sources
const std::string *pKernels = KernelFileList();
for (int iSrc = 0; pKernels[iSrc] != ""; iSrc++)
{
// Read source from disk
string source = getKernelSource(pKernels[iSrc]);
// Patch kernel for logging
if (pKernels[iSrc] != "logging.cl")
source = oclLog.PatchKernel(source);
// Load into compile list
kernelSources.push_back(source);
}
// Setup kernel compiler flags
std::ostringstream clflags;
clflags << "-cl-mad-enable -cl-no-signed-zeros -cl-fast-relaxed-math ";
// Vendor related flags
string devVendor = mCLDevice.getInfo<CL_DEVICE_VENDOR>();
if (devVendor.find("NVIDIA") != std::string::npos)
clflags << "-cl-nv-verbose ";
clflags << std::showpoint;
clflags << "-DLOG_SIZE=" << (int)1024 << " ";
clflags << "-DEND_OF_CELL_LIST=" << (int)(-1) << " ";
clflags << "-DMAX_PARTICLES_COUNT=" << (int)(Params.particleCount) << " ";
clflags << "-DMAX_FRIENDS_CIRCLES=" << (int)(Params.friendsCircles) << " ";
clflags << "-DMAX_FRIENDS_IN_CIRCLE=" << (int)(Params.particlesPerCircle) << " ";
clflags << "-DFRIENDS_BLOCK_SIZE=" << (int)(Params.particleCount * Params.friendsCircles) << " ";
clflags << "-DGRID_BUF_SIZE=" << (int)(Params.gridBufSize) << " ";
clflags << "-DPOLY6_FACTOR=" << 315.0f / (64.0f * M_PI * pow(Params.h, 9)) << "f ";
clflags << "-DGRAD_SPIKY_FACTOR=" << 45.0f / (M_PI * pow(Params.h, 6)) << "f ";
if (Params.EnableCachedBuffers)
clflags << "-DENABLE_CACHED_BUFFERS ";
// Compile kernels
cl::Program program = clSetup.createProgram(kernelSources, mCLContext, mCLDevice, clflags.str());
if (program() == 0)
return false;
// save BuildLog
string buildLog = program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(mCLDevice);
ofstream f("build.log", ios::out | ios::trunc);
f << buildLog;
f.close();
// Build kernels table
mKernels = clSetup.createKernelsMap(program);
// Write kernel info
cout << "CL_KERNEL_WORK_GROUP_SIZE=" << mKernels["computeDelta"].getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(mCLDevice) << endl;
cout << "CL_KERNEL_LOCAL_MEM_SIZE =" << mKernels["computeDelta"].getWorkGroupInfo<CL_KERNEL_LOCAL_MEM_SIZE>(mCLDevice) << endl;
return true;
}
void Simulation::InitBuffers()
{
// Create buffers
mPositionsPingBuffer = cl::BufferGL(mCLContext, CL_MEM_READ_WRITE, mSharedPingBufferID); // buffer could be changed to be CL_MEM_WRITE_ONLY but for debugging also reading it might be helpful
mPositionsPongBuffer = cl::BufferGL(mCLContext, CL_MEM_READ_WRITE, mSharedPongBufferID); // buffer could be changed to be CL_MEM_WRITE_ONLY but for debugging also reading it might be helpful
mParticlePosImg = cl::Image2DGL(mCLContext, CL_MEM_READ_WRITE, GL_TEXTURE_2D, 0, mSharedParticlesPos);
mPredictedPingBuffer = CreateCachedBuffer(cl::ImageFormat(CL_RGBA, CL_FLOAT), Params.particleCount);
mPredictedPongBuffer = CreateCachedBuffer(cl::ImageFormat(CL_RGBA, CL_FLOAT), Params.particleCount);
mVelocitiesBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, Params.particleCount * sizeof(cl_float4));
mDeltaBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, Params.particleCount * sizeof(cl_float4));
mOmegaBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, Params.particleCount * sizeof(cl_float4));
mDensityBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, Params.particleCount * sizeof(cl_float));
mLambdaBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, Params.particleCount * sizeof(cl_float));
mParameters = cl::Buffer(mCLContext, CL_MEM_READ_ONLY, sizeof(Params));
// Radix buffers
mKeysCount = IntCeil(Params.particleCount, _ITEMS * _GROUPS);
mInKeysBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, sizeof(cl_uint) * mKeysCount);
mInPermutationBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, sizeof(cl_uint) * mKeysCount);
mOutKeysBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, sizeof(cl_uint) * mKeysCount);
mOutPermutationBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, sizeof(cl_uint) * mKeysCount);
mHistogramBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, sizeof(cl_uint) * _RADIX * _GROUPS * _ITEMS);
mGlobSumBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, sizeof(cl_uint) * _HISTOSPLIT);
mHistoTempBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, sizeof(cl_uint) * _HISTOSPLIT);
// Update OpenGL lock list
mGLLockList.push_back(mPositionsPingBuffer);
mGLLockList.push_back(mPositionsPongBuffer);
mGLLockList.push_back(mParticlePosImg);
// Update mPositionsPingBuffer and mVelocitiesBuffer
LockGLObjects();
CreateParticles();
UnlockGLObjects();
// Copy Params (Host) => mParams (GPU)
mQueue.enqueueWriteBuffer(mParameters, CL_TRUE, 0, sizeof(Params), &Params);
}
void Simulation::InitCells()
{
// Write buffer for cells
mCellsBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, Params.gridBufSize * 2 * sizeof(cl_uint));
OCL_InitMemory(mQueue, mCellsBuffer, (void*)&END_OF_CELL_LIST, sizeof(END_OF_CELL_LIST));
// Init Friends list buffer
mFriendsListBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, Params.particleCount * Params.friendsCircles * (1 + Params.particlesPerCircle) * sizeof(cl_uint));
OCL_InitMemory(mQueue, mFriendsListBuffer);
}
void Simulation::LoadForceMasks()
{
// Load file
int width = 0, height = 0, channels = 0;
byte* data = SOIL_load_image(getPathForTexture(string("Scene_fp_mask.png")).c_str(), &width, &height, &channels, 4);
// Clear alpha
for (int i = 0; i < width * height * 4; i+=4)
{
data[i+1] = 0;
data[i+2] = 0;
data[i+3] = 0;
}
// Create OpenCL image
mSurfacesMask = cl::Image2D(mCLContext, CL_MEM_READ_WRITE, cl::ImageFormat(CL_R, CL_UNSIGNED_INT32), width, height);
// Write data
cl::size_t<3> org, region; region[0] = width; region[1] = height; region[2] = 1;
mQueue.enqueueWriteImage(mSurfacesMask, true, org, region, 0, 0, data);
//mQueue.enqueueReadImage(mSurfacesMask, true, org, region, 0, 0, data);
// Release image data
SOIL_free_image_data(data);
}
int dumpSession = 0;
int dumpCounter = 0;
int cycleCounter = 0;
void SaveFile(cl::CommandQueue queue, cl::Buffer buffer, const char *szFilename)
{
// Exit if dump session is disabled
if (dumpSession == 0)
return;
// Get buffer size
int bufSize = buffer.getInfo<CL_MEM_SIZE>();
// Read data from GPU
char *buf = new char[bufSize];
queue.enqueueReadBuffer(buffer, CL_TRUE, 0, bufSize, buf);
queue.finish();
// Compose file name
dumpCounter++;
char szTarget[256];
sprintf(szTarget, "%s/dump%d/%d_%d_%s.bin", getRootPath().c_str(), dumpSession, dumpCounter, cycleCounter, szFilename);
// Save to disk
ofstream f(szTarget, ios::out | ios::trunc | ios::binary);
f.seekp(0);
f.write((const char *)buf, bufSize);
f.close();
delete[] buf;
}
void Simulation::updateVelocities()
{
int param = 0; cl::Kernel kernel = mKernels["updateVelocities"];
kernel.setArg(param++, mParameters);
kernel.setArg(param++, mPositionsPingBuffer);
kernel.setArg(param++, mPredictedPingBuffer);
kernel.setArg(param++, mParticlePosImg);
kernel.setArg(param++, mVelocitiesBuffer);
kernel.setArg(param++, Params.particleCount);
mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("updateVelocities"));
}
void Simulation::applyViscosity()
{
int param = 0; cl::Kernel kernel = mKernels["applyViscosity"];
kernel.setArg(param++, mParameters);
kernel.setArg(param++, mPredictedPingBuffer);
kernel.setArg(param++, mVelocitiesBuffer);
kernel.setArg(param++, mOmegaBuffer);
kernel.setArg(param++, mFriendsListBuffer);
kernel.setArg(param++, Params.particleCount);
mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("applyViscosity"));
}
void Simulation::applyVorticity()
{
int param = 0; cl::Kernel kernel = mKernels["applyVorticity"];
kernel.setArg(param++, mParameters);
kernel.setArg(param++, mPredictedPingBuffer);
kernel.setArg(param++, mVelocitiesBuffer);
kernel.setArg(param++, mOmegaBuffer);
kernel.setArg(param++, mFriendsListBuffer);
kernel.setArg(param++, Params.particleCount);
mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("applyVorticity"));
}
void Simulation::predictPositions()
{
int param = 0; cl::Kernel kernel = mKernels["predictPositions"];
kernel.setArg(param++, mParameters);
kernel.setArg(param++, (cl_uint)bPauseSim);
kernel.setArg(param++, mPositionsPingBuffer);
kernel.setArg(param++, mPredictedPingBuffer);
kernel.setArg(param++, mVelocitiesBuffer);
kernel.setArg(param++, Params.particleCount);
mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("predictPositions"));
}
void Simulation::buildFriendsList()
{
int param = 0; cl::Kernel kernel = mKernels["buildFriendsList"];
kernel.setArg(param++, mParameters);
kernel.setArg(param++, mPredictedPingBuffer);
kernel.setArg(param++, mCellsBuffer);
kernel.setArg(param++, mFriendsListBuffer);
kernel.setArg(param++, Params.particleCount);
mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("buildFriendsList"));
param = 0; kernel = mKernels["resetGrid"];
kernel.setArg(param++, mParameters);
kernel.setArg(param++, mInKeysBuffer);
kernel.setArg(param++, mCellsBuffer);
kernel.setArg(param++, Params.particleCount);
mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("resetPartList"));
}
void Simulation::updatePredicted(int iterationIndex)
{
int param = 0; cl::Kernel kernel = mKernels["updatePredicted"];
kernel.setArg(param++, mPredictedPingBuffer);
kernel.setArg(param++, mPredictedPongBuffer);
kernel.setArg(param++, mDeltaBuffer);
kernel.setArg(param++, Params.particleCount);
mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("updatePredicted", iterationIndex));
SWAP(cl::Memory, mPredictedPingBuffer, mPredictedPongBuffer);
}
void Simulation::packData(cl::Memory& sourceImg, cl::Memory& pongImg, cl::Buffer packSource, int iterationIndex)
{
int param = 0; cl::Kernel kernel = mKernels["packData"];
kernel.setArg(param++, pongImg);
kernel.setArg(param++, sourceImg);
kernel.setArg(param++, packSource);
kernel.setArg(param++, Params.particleCount);
mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("packData", iterationIndex));
// Swap between source and pong
SWAP(cl::Memory, sourceImg, pongImg);
}
void Simulation::computeDelta(int iterationIndex)
{
int param = 0; cl::Kernel kernel = mKernels["computeDelta"];
kernel.setArg(param++, mParameters);
kernel.setArg(param++, oclLog.GetDebugBuffer());
kernel.setArg(param++, mDeltaBuffer);
kernel.setArg(param++, mPositionsPingBuffer);
kernel.setArg(param++, mPredictedPingBuffer); // xyz=Predicted z=Scaling
kernel.setArg(param++, mFriendsListBuffer);
kernel.setArg(param++, fWavePos);
kernel.setArg(param++, mSurfacesMask);
kernel.setArg(param++, Params.particleCount);
#ifdef LOCALMEM
mQueue.enqueueNDRangeKernel(kernel, 0, cl::NDRange(DivCeil(Params.particleCount, 256)*256), cl::NDRange(256), NULL, PerfData.GetTrackerEvent("computeDelta", iterationIndex));
#else
mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("computeDelta", iterationIndex));
#endif
}
void Simulation::computeScaling(int iterationIndex)
{
int param = 0; cl::Kernel kernel = mKernels["computeScaling"];
kernel.setArg(param++, mParameters);
kernel.setArg(param++, mPredictedPingBuffer);
kernel.setArg(param++, mDensityBuffer);
kernel.setArg(param++, mLambdaBuffer);
kernel.setArg(param++, mFriendsListBuffer);
kernel.setArg(param++, Params.particleCount);
mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("computeScaling", iterationIndex));
// mQueue.enqueueNDRangeKernel(kernel, 0, cl::NDRange(((Params.particleCount + 399) / 400) * 400), cl::NDRange(400), NULL, PerfData.GetTrackerEvent("computeScaling", iterationIndex));
}
void Simulation::updateCells()
{
int param = 0; cl::Kernel kernel = mKernels["updateCells"];
kernel.setArg(param++, mParameters);
kernel.setArg(param++, mInKeysBuffer);
kernel.setArg(param++, mCellsBuffer);
kernel.setArg(param++, Params.particleCount);
mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("updateCells"));
}
void Simulation::radixsort()
{
int param = 0; cl::Kernel kernel = mKernels["computeKeys"];
kernel.setArg(param++, mParameters);
kernel.setArg(param++, mPredictedPingBuffer);
kernel.setArg(param++, mInKeysBuffer);
kernel.setArg(param++, mInPermutationBuffer);
kernel.setArg(param++, Params.particleCount);
mQueue.enqueueNDRangeKernel(kernel, 0, cl::NDRange(mKeysCount), mLocalRange, NULL, PerfData.GetTrackerEvent("computeKeys"));
for (size_t pass = 0; pass < _PASS; pass++)
{
// Histogram(pass);
const size_t h_nblocitems = _ITEMS;
const size_t h_nbitems = _GROUPS * _ITEMS;
param = 0; kernel = mKernels["histogram"];
kernel.setArg(param++, mInKeysBuffer);
kernel.setArg(param++, mHistogramBuffer);
kernel.setArg(param++, pass);
kernel.setArg(param++, sizeof(cl_uint) * _RADIX * _ITEMS, NULL);
kernel.setArg(param++, mKeysCount);
mQueue.enqueueNDRangeKernel(kernel, 0, cl::NDRange(h_nbitems), cl::NDRange(h_nblocitems), NULL, PerfData.GetTrackerEvent("histogram", pass));
// ScanHistogram();
param = 0; kernel = mKernels["scanhistograms"];
const size_t sh1_nbitems = _RADIX * _GROUPS * _ITEMS / 2;
const size_t sh1_nblocitems = sh1_nbitems / _HISTOSPLIT ;
const int maxmemcache = max(_HISTOSPLIT, _ITEMS * _GROUPS * _RADIX / _HISTOSPLIT);
kernel.setArg(param++, mHistogramBuffer);
kernel.setArg(param++, sizeof(cl_uint)* maxmemcache, NULL);
kernel.setArg(param++, mGlobSumBuffer);
mQueue.enqueueNDRangeKernel(kernel, 0, cl::NDRange(sh1_nbitems), cl::NDRange(sh1_nblocitems), NULL, PerfData.GetTrackerEvent("scanhistograms1", pass));
mQueue.finish();
param = 0; kernel = mKernels["scanhistograms"];
const size_t sh2_nbitems = _HISTOSPLIT / 2;
const size_t sh2_nblocitems = sh2_nbitems;
kernel.setArg(0, mGlobSumBuffer);
kernel.setArg(2, mHistoTempBuffer);
mQueue.enqueueNDRangeKernel(kernel, 0, cl::NDRange(sh2_nbitems), cl::NDRange(sh2_nblocitems), NULL, PerfData.GetTrackerEvent("scanhistograms2", pass));
param = 0; kernel = mKernels["pastehistograms"];
const size_t ph_nbitems = _RADIX * _GROUPS * _ITEMS / 2;
const size_t ph_nblocitems = ph_nbitems / _HISTOSPLIT;
kernel.setArg(param++, mHistogramBuffer);
kernel.setArg(param++, mGlobSumBuffer);
mQueue.enqueueNDRangeKernel(kernel, 0, cl::NDRange(ph_nbitems), cl::NDRange(ph_nblocitems), NULL, PerfData.GetTrackerEvent("pastehistograms", pass));
// Reorder(pass);
param = 0; kernel = mKernels["reorder"];
const size_t r_nblocitems = _ITEMS;
const size_t r_nbitems = _GROUPS * _ITEMS;
kernel.setArg(param++, mInKeysBuffer);
kernel.setArg(param++, mOutKeysBuffer);
kernel.setArg(param++, mHistogramBuffer);
kernel.setArg(param++, pass);
kernel.setArg(param++, mInPermutationBuffer);
kernel.setArg(param++, mOutPermutationBuffer);
kernel.setArg(param++, sizeof(cl_uint)* _RADIX * _ITEMS, NULL);
kernel.setArg(param++, mKeysCount);
mQueue.enqueueNDRangeKernel(kernel, 0, cl::NDRange(r_nbitems), cl::NDRange(r_nblocitems), NULL, PerfData.GetTrackerEvent("reorder", pass));
SWAP(cl::Buffer, mInKeysBuffer, mOutKeysBuffer);
SWAP(cl::Buffer, mInPermutationBuffer, mOutPermutationBuffer);
}
// Execute particle reposition
param = 0; kernel = mKernels["sortParticles"];
kernel.setArg(param++, mInPermutationBuffer);
kernel.setArg(param++, mPositionsPingBuffer);
kernel.setArg(param++, mPositionsPongBuffer);
kernel.setArg(param++, mPredictedPingBuffer);
kernel.setArg(param++, mPredictedPongBuffer);
kernel.setArg(param++, Params.particleCount);
mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("sortParticles"));
// Double buffering of positions and velocity buffers
SWAP(cl::BufferGL, mPositionsPingBuffer, mPositionsPongBuffer);
SWAP(cl::Memory, mPredictedPingBuffer, mPredictedPongBuffer);
SWAP(GLuint, mSharedPingBufferID, mSharedPongBufferID);
}
void Simulation::LockGLObjects()
{
// Make sure OpenGL finish doing things (This is required according to OpenCL spec, see enqueueAcquireGLObjects)
glFinish();
// Request lock
mQueue.enqueueAcquireGLObjects(&mGLLockList);
}
void Simulation::UnlockGLObjects()
{
// Release lock
mQueue.enqueueReleaseGLObjects(&mGLLockList);
mQueue.finish();
}
void Simulation::Step()
{
// Lock OpenGL objects
LockGLObjects();
// Inc sample counter
cycleCounter++;
// Predicit positions
this->predictPositions();
// sort particles buffer
if (!bPauseSim)
this->radixsort();
// Update cells
this->updateCells();
// Build friends list
this->buildFriendsList();
for (unsigned int i = 0; i < Params.simIterations; ++i)
{
// Compute scaling value
this->computeScaling(i);
// Place lambda in "mPredictedPingBuffer[x].w"
this->packData(mPredictedPingBuffer, mPredictedPongBuffer, mLambdaBuffer, i);
// Compute position delta
this->computeDelta(i);
// Update predicted position
this->updatePredicted(i);
}
// Place density in "mPredictedPingBuffer[x].w"
this->packData(mPredictedPingBuffer, mPredictedPongBuffer, mDensityBuffer, -1);
// Recompute velocities
this->updateVelocities();
// Update vorticity and Viscosity
this->applyViscosity();
this->applyVorticity();
// [DEBUG] Read back friends information (if needed)
//if (bReadFriendsList || bDumpParticlesData)
// TODO: Get frients list to host
// [DEBUG] Do we need to dump particle data
if (bDumpParticlesData)
{
// Turn off flag
bDumpParticlesData = false;
// TODO: Dump particles to disk
}
// Release OpenGL shared object, allowing openGL do to it's thing...
UnlockGLObjects();
// Collect performance data
PerfData.UpdateTimings();
// Allow OpenCL logger to process
oclLog.CycleExecute(mQueue);
}
| 37.763666 | 196 | 0.680787 | ericwolter |
c105302eb2ae2bf3b741dcf95bda20b6215e954a | 3,446 | cpp | C++ | examples/KNeighbors.cpp | aniketsharma00411/alpha | 4a1010150388022a6c799e9204621c281b1f92cb | [
"MIT"
] | 1 | 2021-04-04T12:12:54.000Z | 2021-04-04T12:12:54.000Z | examples/KNeighbors.cpp | mlcpp/alpha | 4a1010150388022a6c799e9204621c281b1f92cb | [
"MIT"
] | 3 | 2020-09-17T05:14:58.000Z | 2020-09-20T11:12:29.000Z | examples/KNeighbors.cpp | mlcpp/alpha | 4a1010150388022a6c799e9204621c281b1f92cb | [
"MIT"
] | 1 | 2020-09-16T10:30:11.000Z | 2020-09-16T10:30:11.000Z | // import header files
#include <KNeighborsClassifier.hpp>
#include <matplotlibcpp.hpp>
#include <model_selection.hpp>
namespace plt = matplotlibcpp;
// Example program
// Read csv files to get a Matrix object.
// Slice the Matrix object to a suitable size.
// Plot known data points
// Run KNeighborsClustering and predict the cluster label for a Matrix
// Print score and plot necessary graphs
int main() {
// Specify backend renderer for matplotlib
plt::backend("GTK3Agg");
// create dataset with two feature
Matrix mat = read_csv("./datasets/blobs/blobs.csv");
Matrix X = mat.slice(1, mat.row_length(), 0, 2);
Matrix Y = mat.slice(1, mat.row_length(), 2, 3);
X.to_double();
Y.to_double();
// Split the data and targets into training/testing sets
auto [X_train, X_test, Y_train, Y_test] = model_selection.train_test_split(X, Y, 0);
// plot training dataset
plt::figure_size(800, 600);
plt::title("KNeighbors Known Dataset");
plt::plot(matrix.slice_select(X_train, Y_train, 0.0, 0).get_col(0),
matrix.slice_select(X_train, Y_train, 0.0, 1).get_col(0), "ro");
plt::plot(matrix.slice_select(X_train, Y_train, 1.0, 0).get_col(0),
matrix.slice_select(X_train, Y_train, 1.0, 1).get_col(0), "g^");
plt::plot(matrix.slice_select(X_train, Y_train, 2.0, 0).get_col(0),
matrix.slice_select(X_train, Y_train, 2.0, 1).get_col(0), "bD");
plt::save("./build/plots/KNeighbors Known Dataset.png");
plt::show();
// plot test data
plt::figure_size(800, 600);
plt::title("KNeighbors Unknown Dataset");
plt::plot(X_test.get_col(0), X_test.get_col(1), "mo");
plt::save("./build/plots/KNeighbors Unknown Dataset.png");
plt::show();
// create KMeans object with k and epochs as parameters
KNeighborsClassifier knn(1);
knn.fit(X_train, Y_train);
std::cout << "K Neighbors Clustering Algorithm: " << std::endl;
Matrix Y_pred = knn.predict(X_test);
// plot predicted dataset
plt::figure_size(800, 600);
plt::title("KNeighbors Predicted Dataset along with Known Dataset");
plt::named_plot("Known red", matrix.slice_select(X_train, Y_train, 0.0, 0).get_col(0),
matrix.slice_select(X_train, Y_train, 0.0, 1).get_col(0), "ro");
plt::named_plot("Known green", matrix.slice_select(X_train, Y_train, 1.0, 0).get_col(0),
matrix.slice_select(X_train, Y_train, 1.0, 1).get_col(0), "g^");
plt::named_plot("Known blue", matrix.slice_select(X_train, Y_train, 2.0, 0).get_col(0),
matrix.slice_select(X_train, Y_train, 2.0, 1).get_col(0), "bD");
plt::named_plot("Predicted red", matrix.slice_select(X_test, Y_pred, 0.0, 0).get_col(0),
matrix.slice_select(X_test, Y_pred, 0.0, 1).get_col(0), "rP");
plt::named_plot("Predicted green", matrix.slice_select(X_test, Y_pred, 1.0, 0).get_col(0),
matrix.slice_select(X_test, Y_pred, 1.0, 1).get_col(0), "gP");
plt::named_plot("Predicted blue", matrix.slice_select(X_test, Y_pred, 2.0, 0).get_col(0),
matrix.slice_select(X_test, Y_pred, 2.0, 1).get_col(0), "bP");
plt::legend();
plt::save("./build/plots/KNeighbors Predicted Dataset.png");
plt::show();
// Comparison of predicted and actual cluster label
std::cout << "KNN Model Score: " << knn.score(Y_pred, Y_test) << std::endl;
return 0;
}
| 43.075 | 94 | 0.652351 | aniketsharma00411 |
c106c1d7cbab7d15f10e6b3920c90895042bd2b8 | 1,559 | cpp | C++ | fastSLAMproject/src/gmapping/openslam_gmapping/grid/graphmap.cpp | HouCongCN/Gmapping-Code | 946db1678a99043fc179a5a82499c4bd98cd19d6 | [
"MIT"
] | null | null | null | fastSLAMproject/src/gmapping/openslam_gmapping/grid/graphmap.cpp | HouCongCN/Gmapping-Code | 946db1678a99043fc179a5a82499c4bd98cd19d6 | [
"MIT"
] | null | null | null | fastSLAMproject/src/gmapping/openslam_gmapping/grid/graphmap.cpp | HouCongCN/Gmapping-Code | 946db1678a99043fc179a5a82499c4bd98cd19d6 | [
"MIT"
] | null | null | null | #ifndef GRAPHMAP_H
#define GRAPHMAP_H
#include <list>
#include "../include/gmapping/utils/point.h"
#include "../include/gmapping/grid/map.h"
#include <utils/graph.h>
/*
* 这个地方感觉像是用用来做图优化的。
* 不过不知道为什么最终没有用来做这个。
*/
namespace GMapping {
class RasterMap;
struct GraphMapPatch
{
typedef typename std::list<IntPoint> PointList;
/**Renders the map relatively to the center of the patch*/
//void render(RenderMap rmap);
/**returns the lower left corner of the patch, relative to the center*/
//Point minBoundary() const;
/**returns the upper right corner of the patch, relative to the center*/
//Point maxBoundary() const; //
OrientedPoint center;
PointList m_points;
};
struct Covariance3
{
double sxx, sxy, sxt, syy, syt ,stt;
};
struct GraphMapEdge
{
Covariance3 covariance;
GraphMapPatch* first, *second;
inline operator double() const
{
return sqrt((first->center-second->center)*(first->center-second->center));
}
};
struct GraphPatchGraph: public Graph<GraphMapPatch, Covariance3>
{
void addEdge(Vertex* v1, Vertex* v2, const Covariance3& covariance);
};
void GraphPatchGraph::addEdge(GraphPatchGraph::Vertex* v1, GraphPatchGraph::VertexVertex* v2,
const Covariance3& cov)
{
GraphMapEdge gme;
gme.covariance=cov;
gme.first=v1;
gme.second=v2;
return Graph<GraphMapPatch, Covariance3>::addEdge(v1,v2,gme);
}
struct GraphPatchDirectoryCell: public std::set<GraphMapPatch::Vertex*>
{
GraphPatchDirectoryCell(double);
};
typedef Map<GraphPatchDirectoryCell>, Array2D::set<GraphPatchDirectoryCell> >
};
#endif
| 21.067568 | 94 | 0.738935 | HouCongCN |
c10a693697c48bb72d21c2338637ca7d0e4c8943 | 3,699 | hxx | C++ | include/criterion/internal/assert/op.hxx | Keenuts/Criterion | 982e569233fac4c1e3b984611fe52bdb991d82ec | [
"MIT"
] | 6 | 2019-01-18T13:36:55.000Z | 2021-03-15T05:59:34.000Z | include/criterion/internal/assert/op.hxx | Keenuts/Criterion | 982e569233fac4c1e3b984611fe52bdb991d82ec | [
"MIT"
] | null | null | null | include/criterion/internal/assert/op.hxx | Keenuts/Criterion | 982e569233fac4c1e3b984611fe52bdb991d82ec | [
"MIT"
] | 1 | 2019-06-09T11:44:00.000Z | 2019-06-09T11:44:00.000Z | /*
* The MIT License (MIT)
*
* Copyright © 2016 Franklin "Snaipe" Mathieu <http://snai.pe/>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef CRITERION_INTERNAL_ASSERT_OP_HXX_
#define CRITERION_INTERNAL_ASSERT_OP_HXX_
#include <cwchar>
/* *INDENT-OFF* */
namespace criterion { namespace internal { namespace operators {
/* *INDENT-ON* */
#define CRI_DEFINE_MEMBER_DETECTOR(Member) \
template <class T> \
class HasMember_ ## Member { \
private: \
using yes = char[2]; \
using no = char[1]; \
struct fallback { int Member; }; \
struct derived : T, fallback {}; \
template <class U> static no &test(decltype (U::Member) *); \
template <typename U> static yes &test(U *); \
public: \
static constexpr bool result = sizeof (test<derived>(nullptr)) == sizeof (yes); \
}; \
template <class T> \
struct has_member_ ## Member : public std::integral_constant<bool, HasMember_ ## Member<T>::result> {}
CRI_DEFINE_MEMBER_DETECTOR(empty);
template <typename T>
bool zero(const T *t) { return !t; }
template <typename T>
bool zero(const typename std::enable_if<!std::is_pointer<T>::value, T>::type &t) { return !t; }
template <typename T, typename = typename has_member_empty<T>::type>
bool zero(const T &t) { return t.empty(); }
template <> inline bool zero<>(const char *t) { return !*t; }
template <> inline bool zero<>(const wchar_t *t) { return !*t; }
/* relops without const */
template <typename T, typename U>
inline bool operator!= (T& t, U& u) { return !(t == u); }
template <typename T, typename U>
inline bool operator<= (T& t, U& u) { return t < u || t == u; }
template <typename T, typename U>
inline bool operator> (T& t, U& u) { return !(t <= u); }
template <typename T, typename U>
inline bool operator>= (T& t, U& u) { return !(t < u); }
/* *INDENT-OFF* */
}}}
/* *INDENT-ON* */
#endif /* !CRITERION_INTERNAL_ASSERT_OP_HXX_ */
| 45.666667 | 106 | 0.550419 | Keenuts |
c11426d3563aa8365db081c4919eb131a87f8cc4 | 2,789 | cpp | C++ | drivers/unix/ip_unix.cpp | ayrat-forks/godot | 02669e95a4975898d97aeaedc913b16f60688a01 | [
"MIT"
] | 3 | 2015-11-10T03:53:31.000Z | 2019-11-10T20:39:47.000Z | drivers/unix/ip_unix.cpp | bshawk/godot | c12a8e922ff724d7fe9909c16f9a1b5aec7f010b | [
"MIT"
] | 2 | 2021-08-18T15:38:29.000Z | 2021-08-31T08:06:16.000Z | drivers/unix/ip_unix.cpp | bshawk/godot | c12a8e922ff724d7fe9909c16f9a1b5aec7f010b | [
"MIT"
] | null | null | null | /*************************************************************************/
/* ip_unix.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "ip_unix.h"
#if defined(UNIX_ENABLED) || defined(WINDOWS_ENABLED)
#ifdef WINDOWS_ENABLED
#include <ws2tcpip.h>
#include <winsock2.h>
#include <windows.h>
#else
#include <netdb.h>
#endif
IP_Address IP_Unix::_resolve_hostname(const String& p_hostname) {
struct hostent *he;
if ((he=gethostbyname(p_hostname.utf8().get_data())) == NULL) { // get the host info
ERR_PRINT("gethostbyname failed!");
return IP_Address();
}
IP_Address ip;
ip.host= *((unsigned long*)he->h_addr);
return ip;
}
void IP_Unix::make_default() {
_create=_create_unix;
}
IP* IP_Unix::_create_unix() {
return memnew( IP_Unix );
}
IP_Unix::IP_Unix() {
}
#endif
| 40.42029 | 86 | 0.498745 | ayrat-forks |
c11c3ec3e0ee66d9266874f466fe8a91a4c39dd6 | 10,080 | hpp | C++ | include/GlobalNamespace/RemoteProcedureCall.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/RemoteProcedureCall.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/RemoteProcedureCall.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: IRemoteProcedureCall
#include "GlobalNamespace/IRemoteProcedureCall.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
}
// Forward declaring namespace: LiteNetLib::Utils
namespace LiteNetLib::Utils {
// Forward declaring type: NetDataWriter
class NetDataWriter;
// Forward declaring type: NetDataReader
class NetDataReader;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Size: 0x14
#pragma pack(push, 1)
// Autogenerated type: RemoteProcedureCall
// [TokenAttribute] Offset: FFFFFFFF
class RemoteProcedureCall : public ::Il2CppObject/*, public GlobalNamespace::IRemoteProcedureCall*/ {
public:
// Nested type: GlobalNamespace::RemoteProcedureCall::TypeWrapper_1<T>
template<typename T>
struct TypeWrapper_1;
// private System.Single <syncTime>k__BackingField
// Size: 0x4
// Offset: 0x10
float syncTime;
// Field size check
static_assert(sizeof(float) == 0x4);
// Creating value type constructor for type: RemoteProcedureCall
RemoteProcedureCall(float syncTime_ = {}) noexcept : syncTime{syncTime_} {}
// Creating interface conversion operator: operator GlobalNamespace::IRemoteProcedureCall
operator GlobalNamespace::IRemoteProcedureCall() noexcept {
return *reinterpret_cast<GlobalNamespace::IRemoteProcedureCall*>(this);
}
// Creating conversion operator: operator float
constexpr operator float() const noexcept {
return syncTime;
}
// Get instance field: private System.Single <syncTime>k__BackingField
float _get_$syncTime$k__BackingField();
// Set instance field: private System.Single <syncTime>k__BackingField
void _set_$syncTime$k__BackingField(float value);
// public System.Single get_syncTime()
// Offset: 0x23CEFB0
float get_syncTime();
// public System.Void set_syncTime(System.Single value)
// Offset: 0x23CEFB8
void set_syncTime(float value);
// protected System.Void SerializeData(LiteNetLib.Utils.NetDataWriter writer)
// Offset: 0x23CEFC0
void SerializeData(LiteNetLib::Utils::NetDataWriter* writer);
// protected System.Void DeserializeData(LiteNetLib.Utils.NetDataReader reader)
// Offset: 0x23CEFC4
void DeserializeData(LiteNetLib::Utils::NetDataReader* reader);
// private System.Void LiteNetLib.Utils.INetSerializable.Serialize(LiteNetLib.Utils.NetDataWriter writer)
// Offset: 0x23CEFC8
void LiteNetLib_Utils_INetSerializable_Serialize(LiteNetLib::Utils::NetDataWriter* writer);
// private System.Void LiteNetLib.Utils.INetSerializable.Deserialize(LiteNetLib.Utils.NetDataReader reader)
// Offset: 0x23CF010
void LiteNetLib_Utils_INetSerializable_Deserialize(LiteNetLib::Utils::NetDataReader* reader);
// public System.Void Release()
// Offset: 0x23CF058
void Release();
// public IRemoteProcedureCall Init(System.Single syncTime)
// Offset: 0x23CF178
GlobalNamespace::IRemoteProcedureCall* Init(float syncTime);
// protected System.Void .ctor()
// Offset: 0x23CF180
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static RemoteProcedureCall* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::RemoteProcedureCall::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<RemoteProcedureCall*, creationType>()));
}
}; // RemoteProcedureCall
#pragma pack(pop)
static check_size<sizeof(RemoteProcedureCall), 16 + sizeof(float)> __GlobalNamespace_RemoteProcedureCallSizeCheck;
static_assert(sizeof(RemoteProcedureCall) == 0x14);
}
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::RemoteProcedureCall*, "", "RemoteProcedureCall");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::get_syncTime
// Il2CppName: get_syncTime
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::RemoteProcedureCall::*)()>(&GlobalNamespace::RemoteProcedureCall::get_syncTime)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RemoteProcedureCall*), "get_syncTime", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::set_syncTime
// Il2CppName: set_syncTime
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::RemoteProcedureCall::*)(float)>(&GlobalNamespace::RemoteProcedureCall::set_syncTime)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RemoteProcedureCall*), "set_syncTime", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::SerializeData
// Il2CppName: SerializeData
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::RemoteProcedureCall::*)(LiteNetLib::Utils::NetDataWriter*)>(&GlobalNamespace::RemoteProcedureCall::SerializeData)> {
static const MethodInfo* get() {
static auto* writer = &::il2cpp_utils::GetClassFromName("LiteNetLib.Utils", "NetDataWriter")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RemoteProcedureCall*), "SerializeData", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{writer});
}
};
// Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::DeserializeData
// Il2CppName: DeserializeData
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::RemoteProcedureCall::*)(LiteNetLib::Utils::NetDataReader*)>(&GlobalNamespace::RemoteProcedureCall::DeserializeData)> {
static const MethodInfo* get() {
static auto* reader = &::il2cpp_utils::GetClassFromName("LiteNetLib.Utils", "NetDataReader")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RemoteProcedureCall*), "DeserializeData", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{reader});
}
};
// Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::LiteNetLib_Utils_INetSerializable_Serialize
// Il2CppName: LiteNetLib.Utils.INetSerializable.Serialize
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::RemoteProcedureCall::*)(LiteNetLib::Utils::NetDataWriter*)>(&GlobalNamespace::RemoteProcedureCall::LiteNetLib_Utils_INetSerializable_Serialize)> {
static const MethodInfo* get() {
static auto* writer = &::il2cpp_utils::GetClassFromName("LiteNetLib.Utils", "NetDataWriter")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RemoteProcedureCall*), "LiteNetLib.Utils.INetSerializable.Serialize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{writer});
}
};
// Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::LiteNetLib_Utils_INetSerializable_Deserialize
// Il2CppName: LiteNetLib.Utils.INetSerializable.Deserialize
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::RemoteProcedureCall::*)(LiteNetLib::Utils::NetDataReader*)>(&GlobalNamespace::RemoteProcedureCall::LiteNetLib_Utils_INetSerializable_Deserialize)> {
static const MethodInfo* get() {
static auto* reader = &::il2cpp_utils::GetClassFromName("LiteNetLib.Utils", "NetDataReader")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RemoteProcedureCall*), "LiteNetLib.Utils.INetSerializable.Deserialize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{reader});
}
};
// Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::Release
// Il2CppName: Release
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::RemoteProcedureCall::*)()>(&GlobalNamespace::RemoteProcedureCall::Release)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RemoteProcedureCall*), "Release", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::Init
// Il2CppName: Init
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::IRemoteProcedureCall* (GlobalNamespace::RemoteProcedureCall::*)(float)>(&GlobalNamespace::RemoteProcedureCall::Init)> {
static const MethodInfo* get() {
static auto* syncTime = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RemoteProcedureCall*), "Init", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{syncTime});
}
};
// Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 58.604651 | 241 | 0.754365 | marksteward |
c11d9c294e7f6cd4f7f77911292c4233a1cda89a | 4,966 | hh | C++ | RecoDataProducts/inc/TrackSummary.hh | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 9 | 2020-03-28T00:21:41.000Z | 2021-12-09T20:53:26.000Z | RecoDataProducts/inc/TrackSummary.hh | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 684 | 2019-08-28T23:37:43.000Z | 2022-03-31T22:47:45.000Z | RecoDataProducts/inc/TrackSummary.hh | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 61 | 2019-08-16T23:28:08.000Z | 2021-12-20T08:29:48.000Z | // TrackSummary is a persistable class to communicate track
// reconstruction results to physics analyses.
//
// Andrei Gaponenko, 2014
#ifndef RecoDataProducts_TrackSummary_hh
#define RecoDataProducts_TrackSummary_hh
#include "CLHEP/Vector/ThreeVector.h"
#include "CLHEP/Matrix/SymMatrix.h"
#include <ostream>
class TrkSimpTraj; // BaBar class
namespace mu2e {
class TrackSummary {
public:
//================================================================
class HelixParams {
public:
// See docdb-781 for parameter definitions
double d0() const { return d0_; }
double phi0() const { return phi0_; }
double omega() const { return omega_; }
double z0() const { return z0_; }
double tanDip() const { return tanDip_; }
// Picked from BTrk/BaBar/BTrk/TrkBase/include/HelixParams.hh
enum ParIndex {d0Index=0, phi0Index, omegaIndex, z0Index, tanDipIndex, NHLXPRM};
const CLHEP::HepSymMatrix& covariance() const { return covariance_; }
//Not yet implemented - commented out until it is.
//double parErr(ParIndex i);
// Some derived quantities
double dOut() const; // max distance to Z axis, opposite to d0()
double radius() const; // of the helix
double wavelength() const; // of the helix
explicit HelixParams(const TrkSimpTraj& ltraj);
// Default constructor is required by ROOT persistency
HelixParams() : d0_(), phi0_(), omega_(), z0_(), tanDip_(), covariance_(NHLXPRM) {}
private:
double d0_;
double phi0_;
double omega_;
double z0_;
double tanDip_;
CLHEP::HepSymMatrix covariance_;
};
//================================================================
class TrackStateAtPoint {
public:
const HelixParams& helix() const { return helix_; }
const CLHEP::Hep3Vector& position() const { return position_; }
const CLHEP::Hep3Vector& momentum() const { return momentum_; }
const CLHEP::HepSymMatrix& momentumCovariance() const { return momentumCovariance_; }
double arrivalTime() const { return arrivalTime_; }
double flightLength() const { return flightLength_; }
// Derived quantities
double momentumError() const;
double costh() const; // momentum vector cosine to the Z axis
TrackStateAtPoint(const HelixParams& h,
const CLHEP::Hep3Vector& pos,
const CLHEP::Hep3Vector& mom, const CLHEP::HepSymMatrix& momCov,
double arrivalTime, double flightLength)
: helix_(h)
, position_(pos), momentum_(mom)
, momentumCovariance_(momCov)
, arrivalTime_(arrivalTime), flightLength_(flightLength)
{}
// Default constructor is required by ROOT persistency
TrackStateAtPoint() : arrivalTime_(), flightLength_() {}
private:
// Converting (pos,mom) to a helix depends on B field and we want
// to decouple from that. Therefore we store redundant info here.
HelixParams helix_;
CLHEP::Hep3Vector position_;
CLHEP::Hep3Vector momentum_;
CLHEP::HepSymMatrix momentumCovariance_;
double arrivalTime_;
double flightLength_;
};
//================================================================
int fitstatus() const { return fitstatus_; }
int charge() const { return charge_; }
int nactive() const { return nactive_; }
int ndof() const { return ndof_; }
double chi2() const { return chi2_; }
double fitcon() const;
double t0() const { return t0_; }
double t0Err() const { return t0Err_; }
// flight length associated with t0.
double flt0() const { return flt0_; }
const std::vector<TrackStateAtPoint>& states() const { return states_; }
TrackSummary(int fitstatus, int charge, int nactive,
int ndof, double chi2,
double t0, double t0Err, double flt0)
: fitstatus_(fitstatus), charge_(charge), nactive_(nactive)
, ndof_(ndof), chi2_(chi2)
, t0_(t0), t0Err_(t0Err), flt0_(flt0)
{}
void addState(const TrackStateAtPoint& st);
// Default constructor is required by ROOT persistency
TrackSummary() : fitstatus_(), charge_(), nactive_(), ndof_(), chi2_(), t0_(), t0Err_(), flt0_() {}
private:
std::vector<TrackStateAtPoint> states_;
int fitstatus_;
int charge_;
int nactive_;
int ndof_;
double chi2_;
double t0_;
double t0Err_;
double flt0_;
};
//================================================================
typedef std::vector<TrackSummary> TrackSummaryCollection;
std::ostream& operator<<(std::ostream& os, const TrackSummary::TrackStateAtPoint& st);
std::ostream& operator<<(std::ostream& os, const TrackSummary& sum);
std::ostream& operator<<(std::ostream& os, const TrackSummaryCollection& sc);
} // namespace mu2e
#endif /* RecoDataProducts_TrackSummary_hh */
| 32.457516 | 103 | 0.622634 | bonventre |
c11fbfd64ba4424d553bca0891eb247a02330666 | 35,836 | cpp | C++ | src/OpenSpaceToolkit/Core/Types/Integer.cpp | open-space-collective/library-core | 0b031edb403e2d657d02761b07dd4b35680fcafc | [
"Apache-2.0"
] | 8 | 2018-06-13T06:50:34.000Z | 2019-07-15T03:36:50.000Z | src/OpenSpaceToolkit/Core/Types/Integer.cpp | open-space-collective/library-core | 0b031edb403e2d657d02761b07dd4b35680fcafc | [
"Apache-2.0"
] | 37 | 2018-06-12T07:42:38.000Z | 2020-01-05T01:13:27.000Z | src/OpenSpaceToolkit/Core/Types/Integer.cpp | open-space-collective/library-core | 0b031edb403e2d657d02761b07dd4b35680fcafc | [
"Apache-2.0"
] | 2 | 2020-03-05T18:17:24.000Z | 2020-04-07T18:18:24.000Z | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @project Open Space Toolkit ▸ Core
/// @file OpenSpaceToolkit/Core/Types/Integer.cpp
/// @author Lucas Brémond <[email protected]>
/// @license Apache License 2.0
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <OpenSpaceToolkit/Core/Types/Integer.hpp>
#include <OpenSpaceToolkit/Core/Error.hpp>
#include <boost/lexical_cast.hpp>
#include <limits>
#include <iostream>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace ostk
{
namespace core
{
namespace types
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Integer::Integer ( Integer::ValueType anInteger )
: type_(Integer::Type::Defined),
value_(anInteger)
{
}
Integer& Integer::operator = ( Integer::ValueType anInteger )
{
type_ = Integer::Type::Defined ;
value_ = anInteger ;
return *this ;
}
bool Integer::operator == ( const Integer& anInteger ) const
{
return (type_ == Integer::Type::Defined) && (anInteger.type_ == Integer::Type::Defined) && (value_ == anInteger.value_) ;
}
bool Integer::operator != ( const Integer& anInteger ) const
{
return (type_ == Integer::Type::Defined) && (anInteger.type_ == Integer::Type::Defined) && (value_ != anInteger.value_) ;
}
bool Integer::operator < ( const Integer& anInteger ) const
{
return (type_ == Integer::Type::Defined) && (anInteger.type_ == Integer::Type::Defined) && (value_ < anInteger.value_) ;
}
bool Integer::operator <= ( const Integer& anInteger ) const
{
return (type_ == Integer::Type::Defined) && (anInteger.type_ == Integer::Type::Defined) && (value_ <= anInteger.value_) ;
}
bool Integer::operator > ( const Integer& anInteger ) const
{
return (type_ == Integer::Type::Defined) && (anInteger.type_ == Integer::Type::Defined) && (value_ > anInteger.value_) ;
}
bool Integer::operator >= ( const Integer& anInteger ) const
{
return (type_ == Integer::Type::Defined) && (anInteger.type_ == Integer::Type::Defined) && (value_ >= anInteger.value_) ;
}
bool Integer::operator == ( const Integer::ValueType& anInteger ) const
{
return (type_ == Integer::Type::Defined) && (value_ == anInteger) ;
}
bool Integer::operator != ( const Integer::ValueType& anInteger ) const
{
return (type_ == Integer::Type::Defined) && (value_ != anInteger) ;
}
bool Integer::operator < ( const Integer::ValueType& anInteger ) const
{
return (type_ == Integer::Type::Defined) && (value_ < anInteger) ;
}
bool Integer::operator <= ( const Integer::ValueType& anInteger ) const
{
return (type_ == Integer::Type::Defined) && (value_ <= anInteger) ;
}
bool Integer::operator > ( const Integer::ValueType& anInteger ) const
{
return (type_ == Integer::Type::Defined) && (value_ > anInteger) ;
}
bool Integer::operator >= ( const Integer::ValueType& anInteger ) const
{
return (type_ == Integer::Type::Defined) && (value_ >= anInteger) ;
}
Integer Integer::operator + ( const Integer& anInteger ) const
{
if ((type_ != Integer::Type::Undefined) && (anInteger.type_ != Integer::Type::Undefined))
{
if ((type_ == Integer::Type::PositiveInfinity) && (anInteger.type_ == Integer::Type::PositiveInfinity))
{
return Integer::PositiveInfinity() ;
}
else if ((type_ == Integer::Type::NegativeInfinity) && (anInteger.type_ == Integer::Type::NegativeInfinity))
{
return Integer::NegativeInfinity() ;
}
else if ((type_ == Integer::Type::Defined) || (anInteger.type_ == Integer::Type::Defined))
{
if (type_ != Integer::Type::Defined)
{
return *this ;
}
else if (anInteger.type_ != Integer::Type::Defined)
{
return anInteger ;
}
// [TBC] Use __builtin_add_overflow instead?
if ((anInteger.value_ > 0) && (value_ > (std::numeric_limits<Integer::ValueType>::max() - anInteger.value_))) // Addition would overflow
{
return Integer::PositiveInfinity() ;
}
if ((anInteger.value_ < 0) && (value_ < (std::numeric_limits<Integer::ValueType>::min() - anInteger.value_))) // Addition would underflow
{
return Integer::NegativeInfinity() ;
}
return Integer(value_ + anInteger.value_) ;
}
}
return Integer::Undefined() ;
}
Integer Integer::operator - ( const Integer& anInteger ) const
{
if ((type_ != Integer::Type::Undefined) && (anInteger.type_ != Integer::Type::Undefined))
{
if ((type_ == Integer::Type::PositiveInfinity) && (anInteger.type_ == Integer::Type::NegativeInfinity))
{
return Integer::PositiveInfinity() ;
}
else if ((type_ == Integer::Type::NegativeInfinity) && (anInteger.type_ == Integer::Type::PositiveInfinity))
{
return Integer::NegativeInfinity() ;
}
else if ((type_ == Integer::Type::Defined) || (anInteger.type_ == Integer::Type::Defined))
{
if (type_ != Integer::Type::Defined)
{
return *this ;
}
else if (anInteger.type_ != Integer::Type::Defined)
{
if (anInteger.type_ == Integer::Type::PositiveInfinity)
{
return Integer::NegativeInfinity() ;
}
return Integer::PositiveInfinity() ;
}
if ((anInteger.value_ < 0) && (value_ > (std::numeric_limits<Integer::ValueType>::max() + anInteger.value_))) // Subtraction would overflow
{
return Integer::PositiveInfinity() ;
}
if ((anInteger.value_ > 0) && (value_ < (std::numeric_limits<Integer::ValueType>::min() + anInteger.value_))) // Subtraction would underflow
{
return Integer::NegativeInfinity() ;
}
return Integer(value_ - anInteger.value_) ;
}
}
return Integer::Undefined() ;
}
Integer Integer::operator * ( const Integer& anInteger ) const
{
if ((type_ != Integer::Type::Undefined) && (anInteger.type_ != Integer::Type::Undefined))
{
if (type_ == Integer::Type::PositiveInfinity)
{
if (anInteger.isStrictlyPositive())
{
return Integer::PositiveInfinity() ;
}
else if (anInteger.isStrictlyNegative())
{
return Integer::NegativeInfinity() ;
}
return Integer::Undefined() ;
}
else if (type_ == Integer::Type::NegativeInfinity)
{
if (anInteger.isStrictlyPositive())
{
return Integer::NegativeInfinity() ;
}
else if (anInteger.isStrictlyNegative())
{
return Integer::PositiveInfinity() ;
}
return Integer::Undefined() ;
}
else if (anInteger.type_ == Integer::Type::PositiveInfinity)
{
if (this->isStrictlyPositive())
{
return Integer::PositiveInfinity() ;
}
else if (this->isStrictlyNegative())
{
return Integer::NegativeInfinity() ;
}
return Integer::Undefined() ;
}
else if (anInteger.type_ == Integer::Type::NegativeInfinity)
{
if (this->isStrictlyPositive())
{
return Integer::NegativeInfinity() ;
}
else if (this->isStrictlyNegative())
{
return Integer::PositiveInfinity() ;
}
return Integer::Undefined() ;
}
else
{
if (this->isZero() || anInteger.isZero())
{
return Integer::Zero() ;
}
// Check for -1 for two's complement machines
if ((value_ < 0) && (anInteger.value_ == std::numeric_limits<Integer::ValueType>::min())) // Multiplication can overflow
{
return Integer::PositiveInfinity() ;
}
if ((anInteger.value_ < 0) && (value_ == std::numeric_limits<Integer::ValueType>::min())) // Multiplication can overflow
{
return Integer::PositiveInfinity() ;
}
if ((this->getSign() == anInteger.getSign()) && (std::abs(value_) > (std::numeric_limits<Integer::ValueType>::max() / std::abs(anInteger.value_)))) // Multiplication would overflow
{
return Integer::PositiveInfinity() ;
}
if ((value_ == +1) && (anInteger.value_ == std::numeric_limits<Integer::ValueType>::min()))
{
return Integer(std::numeric_limits<Integer::ValueType>::min()) ;
}
if ((value_ == -1) && (anInteger.value_ == std::numeric_limits<Integer::ValueType>::min()))
{
return Integer::PositiveInfinity() ;
}
if ((anInteger.value_ != -1) && (this->getSign() != anInteger.getSign()) && ((-std::abs(value_)) < (std::numeric_limits<Integer::ValueType>::min() / std::abs(anInteger.value_)))) // Multiplication would underflow
{
return Integer::NegativeInfinity() ;
}
return Integer(value_ * anInteger.value_) ;
}
}
return Integer::Undefined() ;
}
Integer Integer::operator / ( const Integer& anInteger ) const
{
if (anInteger.isZero())
{
return Integer::Undefined() ;
}
if ((type_ != Integer::Type::Undefined) && (anInteger.type_ != Integer::Type::Undefined))
{
if (type_ == Integer::Type::PositiveInfinity)
{
if (anInteger.isInfinity())
{
return Integer::Undefined() ;
}
else if (anInteger.isStrictlyPositive())
{
return Integer::PositiveInfinity() ;
}
else if (anInteger.isStrictlyNegative())
{
return Integer::NegativeInfinity() ;
}
return Integer::Undefined() ;
}
else if (type_ == Integer::Type::NegativeInfinity)
{
if (anInteger.isInfinity())
{
return Integer::Undefined() ;
}
else if (anInteger.isStrictlyPositive())
{
return Integer::NegativeInfinity() ;
}
else if (anInteger.isStrictlyNegative())
{
return Integer::PositiveInfinity() ;
}
return Integer::Undefined() ;
}
else
{
if (this->isZero() || anInteger.isInfinity())
{
return Integer::Zero() ;
}
else
{
if ((value_ == std::numeric_limits<Integer::ValueType>::min()) && (anInteger.value_ == -1))
{
return Integer::PositiveInfinity() ;
}
return Integer(value_ / anInteger.value_) ;
}
}
}
return Integer::Undefined() ;
}
Integer Integer::operator % ( const Integer& anInteger ) const
{
if (anInteger.isZero())
{
return Integer::Undefined() ;
}
if ((type_ != Integer::Type::Undefined) && (anInteger.type_ != Integer::Type::Undefined))
{
if (this->isZero())
{
return Integer::Zero() ;
}
else if (!this->isInfinity() && anInteger.isInfinity())
{
return *this ;
}
else if ((!this->isInfinity()) && this->isStrictlyPositive() && (!anInteger.isInfinity()) && (anInteger.value_ == std::numeric_limits<Integer::ValueType>::min()))
{
return *this ;
}
else if ((!anInteger.isInfinity()) && (std::abs(anInteger.value_) == 1))
{
return Integer::Zero() ;
}
else if (this->isInfinity())
{
return Integer::Undefined() ;
}
else
{
return Integer(value_ % anInteger.value_) ;
}
}
return Integer::Undefined() ;
}
Integer Integer::operator + ( const Integer::ValueType& anInteger ) const
{
return (*this) + Integer(anInteger) ;
}
Integer Integer::operator - ( const Integer::ValueType& anInteger ) const
{
return (*this) - Integer(anInteger) ;
}
Integer Integer::operator * ( const Integer::ValueType& anInteger ) const
{
return (*this) * Integer(anInteger) ;
}
Integer Integer::operator / ( const Integer::ValueType& anInteger ) const
{
return (*this) / Integer(anInteger) ;
}
Integer Integer::operator % ( const Integer::ValueType& anInteger ) const
{
return (*this) % Integer(anInteger) ;
}
Integer& Integer::operator += ( const Integer& anInteger )
{
(*this) = (*this) + anInteger ;
return *this ;
}
Integer& Integer::operator -= ( const Integer& anInteger )
{
(*this) = (*this) - anInteger ;
return *this ;
}
Integer& Integer::operator *= ( const Integer& anInteger )
{
(*this) = (*this) * anInteger ;
return *this ;
}
Integer& Integer::operator /= ( const Integer& anInteger )
{
(*this) = (*this) / anInteger ;
return *this ;
}
Integer& Integer::operator %= ( const Integer& anInteger )
{
(*this) = (*this) % anInteger ;
return *this ;
}
Integer& Integer::operator += ( const Integer::ValueType& anInteger )
{
(*this) = (*this) + Integer(anInteger) ;
return *this ;
}
Integer& Integer::operator -= ( const Integer::ValueType& anInteger )
{
(*this) = (*this) - Integer(anInteger) ;
return *this ;
}
Integer& Integer::operator *= ( const Integer::ValueType& anInteger )
{
(*this) = (*this) * Integer(anInteger) ;
return *this ;
}
Integer& Integer::operator /= ( const Integer::ValueType& anInteger )
{
(*this) = (*this) / Integer(anInteger) ;
return *this ;
}
Integer& Integer::operator %= ( const Integer::ValueType& anInteger )
{
(*this) = (*this) % Integer(anInteger) ;
return *this ;
}
Integer operator + ( const Integer::ValueType& anInt,
const Integer& anInteger )
{
return Integer(anInt) + anInteger ;
}
Integer operator - ( const Integer::ValueType& anInt,
const Integer& anInteger )
{
return Integer(anInt) - anInteger ;
}
Integer operator * ( const Integer::ValueType& anInt,
const Integer& anInteger )
{
return Integer(anInt) * anInteger ;
}
Integer operator / ( const Integer::ValueType& anInt,
const Integer& anInteger )
{
return Integer(anInt) / anInteger ;
}
Integer operator % ( const Integer::ValueType& anInt,
const Integer& anInteger )
{
return Integer(anInt) % anInteger ;
}
Integer Integer::operator + ( ) const
{
return *this ;
}
Integer Integer::operator - ( ) const
{
switch (type_)
{
case Integer::Type::Defined:
{
if (value_ == std::numeric_limits<Integer::ValueType>::min())
{
return Integer::PositiveInfinity() ;
}
return Integer(-value_) ;
}
case Integer::Type::Undefined:
return Integer::Undefined() ;
case Integer::Type::PositiveInfinity:
return Integer::NegativeInfinity() ;
case Integer::Type::NegativeInfinity:
return Integer::PositiveInfinity() ;
default:
break ;
}
return Integer::Undefined() ;
}
Integer& Integer::operator ++ ( )
{
switch (type_)
{
case Integer::Type::Defined:
{
if (value_ == std::numeric_limits<Integer::ValueType>::max())
{
type_ = Integer::Type::PositiveInfinity ;
}
else
{
++value_ ;
}
break ;
}
case Integer::Type::Undefined:
case Integer::Type::PositiveInfinity:
case Integer::Type::NegativeInfinity:
default:
break ;
}
return *this ;
}
Integer& Integer::operator -- ( )
{
switch (type_)
{
case Integer::Type::Defined:
{
if (value_ == std::numeric_limits<Integer::ValueType>::min())
{
type_ = Integer::Type::NegativeInfinity ;
}
else
{
--value_ ;
}
break ;
}
case Integer::Type::Undefined:
case Integer::Type::PositiveInfinity:
case Integer::Type::NegativeInfinity:
default:
break ;
}
return *this ;
}
Integer Integer::operator ++ ( int anInteger )
{
(void) anInteger ;
Integer integerCopy(*this) ;
switch (type_)
{
case Integer::Type::Defined:
{
if (value_ == std::numeric_limits<Integer::ValueType>::max())
{
type_ = Integer::Type::PositiveInfinity ;
}
else
{
value_++ ;
}
break ;
}
case Integer::Type::Undefined:
case Integer::Type::PositiveInfinity:
case Integer::Type::NegativeInfinity:
default:
break ;
}
return integerCopy ;
}
Integer Integer::operator -- ( int anInteger )
{
(void) anInteger ;
Integer integerCopy(*this) ;
switch (type_)
{
case Integer::Type::Defined:
{
if (value_ == std::numeric_limits<Integer::ValueType>::min())
{
type_ = Integer::Type::NegativeInfinity ;
}
else
{
value_-- ;
}
break ;
}
case Integer::Type::Undefined:
case Integer::Type::PositiveInfinity:
case Integer::Type::NegativeInfinity:
default:
break ;
}
return integerCopy ;
}
Integer::operator Integer::ValueType ( ) const
{
if (type_ != Integer::Type::Defined)
{
throw ostk::core::error::runtime::Undefined("Integer") ;
}
return value_ ;
}
std::ostream& operator << ( std::ostream& anOutputStream,
const Integer& anInteger )
{
(void) anInteger ;
switch (anInteger.type_)
{
case Integer::Type::Undefined:
anOutputStream << "Undefined" ;
break ;
case Integer::Type::Defined:
anOutputStream << anInteger.value_ ;
break ;
case Integer::Type::PositiveInfinity:
anOutputStream << "+Inf" ;
break ;
case Integer::Type::NegativeInfinity:
anOutputStream << "-Inf" ;
break ;
}
// ostk::core::utilities::Output::Header(anOutputStream, "Integer") ;
// ostk::core::utilities::Output::Line(anOutputStream) << "Type:" << anInteger.type_ ;
// ostk::core::utilities::Output::Line(anOutputStream) << "Value:" << anInteger.value_ ;
// ostk::core::utilities::Output::Footer(anOutputStream) ;
return anOutputStream ;
}
bool Integer::isDefined ( ) const
{
return type_ != Integer::Type::Undefined ;
}
bool Integer::isZero ( ) const
{
return (type_ == Integer::Type::Defined) && (value_ == 0) ;
}
bool Integer::isPositive ( ) const
{
return ((type_ == Integer::Type::Defined) && (value_ >= 0)) || this->isPositiveInfinity() ;
}
bool Integer::isNegative ( ) const
{
return ((type_ == Integer::Type::Defined) && (value_ <= 0)) || this->isNegativeInfinity() ;
}
bool Integer::isStrictlyPositive ( ) const
{
return ((type_ == Integer::Type::Defined) && (value_ > 0)) || this->isPositiveInfinity() ;
}
bool Integer::isStrictlyNegative ( ) const
{
return ((type_ == Integer::Type::Defined) && (value_ < 0)) || this->isNegativeInfinity() ;
}
bool Integer::isInfinity ( ) const
{
return this->isPositiveInfinity() || this->isNegativeInfinity() ;
}
bool Integer::isPositiveInfinity ( ) const
{
return type_ == Integer::Type::PositiveInfinity ;
}
bool Integer::isNegativeInfinity ( ) const
{
return type_ == Integer::Type::NegativeInfinity ;
}
bool Integer::isFinite ( ) const
{
return type_ == Integer::Type::Defined ;
}
bool Integer::isEven ( ) const
{
return this->isFinite() && (value_ % 2 == 0) ;
}
bool Integer::isOdd ( ) const
{
return this->isFinite() && (value_ % 2 != 0) ;
}
types::Sign Integer::getSign ( ) const
{
switch (type_)
{
case Integer::Type::Undefined:
return types::Sign::Undefined ;
case Integer::Type::Defined:
{
if (value_ > 0)
{
return types::Sign::Positive ;
}
else if (value_ < 0)
{
return types::Sign::Negative ;
}
return types::Sign::None ;
}
case Integer::Type::PositiveInfinity:
return types::Sign::Positive ;
case Integer::Type::NegativeInfinity:
return types::Sign::Negative ;
default:
return types::Sign::Undefined ;
}
return types::Sign::Undefined ;
}
types::String Integer::toString ( ) const
{
switch (type_)
{
case Integer::Type::Undefined:
return "Undefined" ;
case Integer::Type::Defined:
return boost::lexical_cast<std::string>(value_) ;
case Integer::Type::PositiveInfinity:
return "+Inf" ;
case Integer::Type::NegativeInfinity:
return "-Inf" ;
}
return types::String::Empty() ;
}
Integer Integer::Undefined ( )
{
return Integer(Integer::Type::Undefined, 0) ;
}
Integer Integer::Zero ( )
{
return Integer(Integer::Type::Defined, 0) ;
}
Integer Integer::PositiveInfinity ( )
{
return Integer(Integer::Type::PositiveInfinity, std::numeric_limits<Integer::ValueType>::max()) ;
}
Integer Integer::NegativeInfinity ( )
{
return Integer(Integer::Type::NegativeInfinity, std::numeric_limits<Integer::ValueType>::min()) ;
}
Integer Integer::Int8 ( types::Int8 anInteger )
{
return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anInteger)) ;
}
Integer Integer::Int16 ( types::Int16 anInteger )
{
return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anInteger)) ;
}
Integer Integer::Int32 ( types::Int32 anInteger )
{
return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anInteger)) ;
}
Integer Integer::Int64 ( types::Int64 anInteger )
{
if ((anInteger < static_cast<types::Int64>(std::numeric_limits<Integer::ValueType>::min())) || (anInteger > static_cast<types::Int64>(std::numeric_limits<Integer::ValueType>::max())))
{
throw ostk::core::error::RuntimeError("Int64 value [" + boost::lexical_cast<std::string>(anInteger) + "] is out of Integer supported range [" + boost::lexical_cast<std::string>(std::numeric_limits<Integer::ValueType>::min()) + ", " + boost::lexical_cast<std::string>(std::numeric_limits<Integer::ValueType>::max()) + "].") ;
}
return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anInteger)) ;
}
Integer Integer::Uint8 ( types::Uint8 anInteger )
{
return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anInteger)) ;
}
Integer Integer::Uint16 ( types::Uint16 anInteger )
{
return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anInteger)) ;
}
Integer Integer::Uint32 ( types::Uint32 anInteger )
{
if (anInteger > static_cast<types::Uint32>(std::numeric_limits<Integer::ValueType>::max()))
{
throw ostk::core::error::RuntimeError("Uint32 value [" + boost::lexical_cast<std::string>(anInteger) + "] is out of Integer supported range [" + boost::lexical_cast<std::string>(std::numeric_limits<Integer::ValueType>::min()) + ", " + boost::lexical_cast<std::string>(std::numeric_limits<Integer::ValueType>::max()) + "].") ;
}
return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anInteger)) ;
}
Integer Integer::Uint64 ( types::Uint64 anInteger )
{
if (anInteger > static_cast<types::Uint64>(std::numeric_limits<Integer::ValueType>::max()))
{
throw ostk::core::error::RuntimeError("Uint64 value [" + boost::lexical_cast<std::string>(anInteger) + "] is out of Integer supported range [" + boost::lexical_cast<std::string>(std::numeric_limits<Integer::ValueType>::min()) + ", " + boost::lexical_cast<std::string>(std::numeric_limits<Integer::ValueType>::max()) + "].") ;
}
return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anInteger)) ;
}
Integer Integer::Index ( const types::Index& anIndex )
{
if (!(anIndex < std::numeric_limits<Integer::ValueType>::max()))
{
throw ostk::core::error::RuntimeError("Index out of bounds.") ;
}
return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anIndex)) ;
}
Integer Integer::Size ( const types::Size& aSize )
{
if (!(aSize < std::numeric_limits<Integer::ValueType>::max()))
{
throw ostk::core::error::RuntimeError("Size out of bounds.") ;
}
return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(aSize)) ;
}
bool Integer::CanParse ( char aCharacter )
{
return std::isdigit(aCharacter) ;
}
bool Integer::CanParse ( const types::String& aString )
{
if (aString.isEmpty())
{
return false ;
}
if ((aString == "Undefined") || (aString == "Inf") || (aString == "+Inf") || (aString == "-Inf"))
{
return true ;
}
Integer::ValueType integer ;
return boost::conversion::try_lexical_convert<Integer::ValueType>(aString, integer) ;
}
Integer Integer::Parse ( char aCharacter )
{
try
{
return Integer(boost::lexical_cast<Integer::ValueType>(aCharacter)) ;
}
catch (const boost::bad_lexical_cast&)
{
throw ostk::core::error::RuntimeError("Cannot cast character [" + String::Char(aCharacter) + "] to Integer.") ;
}
return Integer::Undefined() ;
}
Integer Integer::Parse ( const types::String& aString )
{
if (aString.isEmpty())
{
throw ostk::core::error::runtime::Undefined("String") ;
}
if (aString == "Undefined")
{
return Integer::Undefined() ;
}
if ((aString == "Inf") || (aString == "+Inf"))
{
return Integer::PositiveInfinity() ;
}
if (aString == "-Inf")
{
return Integer::NegativeInfinity() ;
}
try
{
return Integer(boost::lexical_cast<Integer::ValueType>(aString)) ;
}
catch (const boost::bad_lexical_cast&)
{
throw ostk::core::error::RuntimeError("Cannot cast string [" + aString + "] to Integer.") ;
}
return Integer::Undefined() ;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Integer::Integer ( const Integer::Type& aType,
const Integer::ValueType& anInteger )
: type_(aType),
value_(anInteger)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| 31.352581 | 333 | 0.426024 | open-space-collective |
c12012ee4cad24b03a03b597d150b1a9011f1fa5 | 4,156 | hpp | C++ | main/app_camera.hpp | andriyadi/esp32-custom-vision | ebc3f781fd85bf063d96ae89bb56bfa263fa6af5 | [
"Apache-2.0"
] | 44 | 2019-02-11T04:53:38.000Z | 2021-10-04T12:00:38.000Z | main/app_camera.hpp | andriyadi/esp32-custom-vision | ebc3f781fd85bf063d96ae89bb56bfa263fa6af5 | [
"Apache-2.0"
] | 2 | 2019-06-20T18:03:10.000Z | 2021-01-07T09:18:38.000Z | main/app_camera.hpp | andriyadi/esp32-custom-vision | ebc3f781fd85bf063d96ae89bb56bfa263fa6af5 | [
"Apache-2.0"
] | 12 | 2019-02-12T06:27:11.000Z | 2021-02-16T22:46:45.000Z | /*
* app_camera.hpp
*
* Created on: Feb 8, 2019
* Author: andri
*/
#ifndef MAIN_APP_CAMERA_HPP_
#define MAIN_APP_CAMERA_HPP_
#include "esp_err.h"
#include "esp_camera.h"
#include "sdkconfig.h"
/**
* PIXFORMAT_RGB565, // 2BPP/RGB565
* PIXFORMAT_YUV422, // 2BPP/YUV422
* PIXFORMAT_GRAYSCALE, // 1BPP/GRAYSCALE
* PIXFORMAT_JPEG, // JPEG/COMPRESSED
* PIXFORMAT_RGB888, // 3BPP/RGB888
*/
#define CAMERA_PIXEL_FORMAT PIXFORMAT_JPEG
/*
* FRAMESIZE_QQVGA, // 160x120
* FRAMESIZE_QQVGA2, // 128x160
* FRAMESIZE_QCIF, // 176x144
* FRAMESIZE_HQVGA, // 240x176
* FRAMESIZE_QVGA, // 320x240
* FRAMESIZE_CIF, // 400x296
* FRAMESIZE_VGA, // 640x480
* FRAMESIZE_SVGA, // 800x600
* FRAMESIZE_XGA, // 1024x768
* FRAMESIZE_SXGA, // 1280x1024
* FRAMESIZE_UXGA, // 1600x1200
*/
#define CAMERA_FRAME_SIZE FRAMESIZE_QVGA
#if CONFIG_CAMERA_BOARD_WROVER
//WROVER-KIT PIN Map
#define PWDN_GPIO_NUM -1
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 21
#define SIOD_GPIO_NUM 26
#define SIOC_GPIO_NUM 27
#define Y9_GPIO_NUM 35
#define Y8_GPIO_NUM 34
#define Y7_GPIO_NUM 39
#define Y6_GPIO_NUM 36
#define Y5_GPIO_NUM 19
#define Y4_GPIO_NUM 18
#define Y3_GPIO_NUM 5
#define Y2_GPIO_NUM 4
#define VSYNC_GPIO_NUM 25
#define HREF_GPIO_NUM 23
#define PCLK_GPIO_NUM 22
//Specific
#define USER_BUTTON_1_PIN_NUM 34
#define XCLK_FREQ 20000000
#elif CONFIG_CAMERA_BOARD_EYE
//ESP-EYE Pin Map
#define PWDN_GPIO_NUM -1
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 4
#define SIOD_GPIO_NUM 18
#define SIOC_GPIO_NUM 23
#define Y9_GPIO_NUM 36
#define Y8_GPIO_NUM 37
#define Y7_GPIO_NUM 38
#define Y6_GPIO_NUM 39
#define Y5_GPIO_NUM 35
#define Y4_GPIO_NUM 14
#define Y3_GPIO_NUM 13
#define Y2_GPIO_NUM 34
#define VSYNC_GPIO_NUM 5
#define HREF_GPIO_NUM 27
#define PCLK_GPIO_NUM 25
#define XCLK_FREQ 20000000
#else //CAMERA_BOARD_TTGO_TCAM
//TTGO_T-CAM
#define PWDN_GPIO_NUM 26
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 32
#define SIOD_GPIO_NUM 13
#define SIOC_GPIO_NUM 12
#define Y9_GPIO_NUM 39
#define Y8_GPIO_NUM 36
#define Y7_GPIO_NUM 23
#define Y6_GPIO_NUM 18
#define Y5_GPIO_NUM 15
#define Y4_GPIO_NUM 4
#define Y3_GPIO_NUM 14
#define Y2_GPIO_NUM 5
#define VSYNC_GPIO_NUM 27
#define HREF_GPIO_NUM 25
#define PCLK_GPIO_NUM 19
//Specific
#define AS312_PIN_NUM 33
#define USER_BUTTON_1_PIN_NUM 34
#define I2C_SDA_PIN_NUM 21
#define I2C_SCL_PIN_NUM 22
#define XCLK_FREQ 20000000
#endif
esp_err_t camera_init() {
gpio_config_t conf;
conf.mode = GPIO_MODE_INPUT;
conf.pull_up_en = GPIO_PULLUP_ENABLE;
conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
conf.intr_type = GPIO_INTR_DISABLE;
conf.pin_bit_mask = 1LL << 13;
gpio_config(&conf);
conf.pin_bit_mask = 1LL << 14;
gpio_config(&conf);
camera_config_t config;
config.ledc_channel = LEDC_CHANNEL_0;
config.ledc_timer = LEDC_TIMER_0;
config.pin_d0 = Y2_GPIO_NUM;
config.pin_d1 = Y3_GPIO_NUM;
config.pin_d2 = Y4_GPIO_NUM;
config.pin_d3 = Y5_GPIO_NUM;
config.pin_d4 = Y6_GPIO_NUM;
config.pin_d5 = Y7_GPIO_NUM;
config.pin_d6 = Y8_GPIO_NUM;
config.pin_d7 = Y9_GPIO_NUM;
config.pin_xclk = XCLK_GPIO_NUM;
config.pin_pclk = PCLK_GPIO_NUM;
config.pin_vsync = VSYNC_GPIO_NUM;
config.pin_href = HREF_GPIO_NUM;
config.pin_sscb_sda = SIOD_GPIO_NUM;
config.pin_sscb_scl = SIOC_GPIO_NUM;
config.pin_pwdn = PWDN_GPIO_NUM;
config.pin_reset = RESET_GPIO_NUM;
config.xclk_freq_hz = XCLK_FREQ;
config.pixel_format = CAMERA_PIXEL_FORMAT;
//init with high specs to pre-allocate larger buffers
config.frame_size = FRAMESIZE_UXGA;
config.jpeg_quality = 10;
config.fb_count = 2;
esp_err_t res = esp_camera_init(&config);
if (res == ESP_OK) {
//drop down frame size for higher initial frame rate
sensor_t * s = esp_camera_sensor_get();
s->set_framesize(s, CAMERA_FRAME_SIZE);
#if CONFIG_CAMERA_BOARD_TTGO_TCAM
s->set_vflip(s, 1);
#endif
}
return res;
}
#endif /* MAIN_APP_CAMERA_HPP_ */
| 24.304094 | 54 | 0.723532 | andriyadi |
c12483522d334171d00dd497d723554af35243af | 4,122 | hpp | C++ | include/System/Net/Http/Headers/HttpHeaders_HeaderBucket.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/System/Net/Http/Headers/HttpHeaders_HeaderBucket.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/System/Net/Http/Headers/HttpHeaders_HeaderBucket.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Net.Http.Headers.HttpHeaders
#include "System/Net/Http/Headers/HttpHeaders.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Func`2<T, TResult>
template<typename T, typename TResult>
class Func_2;
}
// Completed forward declares
// Type namespace: System.Net.Http.Headers
namespace System::Net::Http::Headers {
// Size: 0x28
#pragma pack(push, 1)
// Autogenerated type: System.Net.Http.Headers.HttpHeaders/HeaderBucket
class HttpHeaders::HeaderBucket : public ::Il2CppObject {
public:
// public System.Object Parsed
// Size: 0x8
// Offset: 0x10
::Il2CppObject* Parsed;
// Field size check
static_assert(sizeof(::Il2CppObject*) == 0x8);
// private System.Collections.Generic.List`1<System.String> values
// Size: 0x8
// Offset: 0x18
System::Collections::Generic::List_1<::Il2CppString*>* values;
// Field size check
static_assert(sizeof(System::Collections::Generic::List_1<::Il2CppString*>*) == 0x8);
// public readonly System.Func`2<System.Object,System.String> CustomToString
// Size: 0x8
// Offset: 0x20
System::Func_2<::Il2CppObject*, ::Il2CppString*>* CustomToString;
// Field size check
static_assert(sizeof(System::Func_2<::Il2CppObject*, ::Il2CppString*>*) == 0x8);
// Creating value type constructor for type: HeaderBucket
HeaderBucket(::Il2CppObject* Parsed_ = {}, System::Collections::Generic::List_1<::Il2CppString*>* values_ = {}, System::Func_2<::Il2CppObject*, ::Il2CppString*>* CustomToString_ = {}) noexcept : Parsed{Parsed_}, values{values_}, CustomToString{CustomToString_} {}
// public System.Void .ctor(System.Object parsed, System.Func`2<System.Object,System.String> converter)
// Offset: 0x157A55C
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static HttpHeaders::HeaderBucket* New_ctor(::Il2CppObject* parsed, System::Func_2<::Il2CppObject*, ::Il2CppString*>* converter) {
static auto ___internal__logger = ::Logger::get().WithContext("System::Net::Http::Headers::HttpHeaders::HeaderBucket::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<HttpHeaders::HeaderBucket*, creationType>(parsed, converter)));
}
// public System.Boolean get_HasStringValues()
// Offset: 0x157B15C
bool get_HasStringValues();
// public System.Collections.Generic.List`1<System.String> get_Values()
// Offset: 0x157A598
System::Collections::Generic::List_1<::Il2CppString*>* get_Values();
// public System.Void set_Values(System.Collections.Generic.List`1<System.String> value)
// Offset: 0x157B64C
void set_Values(System::Collections::Generic::List_1<::Il2CppString*>* value);
// public System.String ParsedToString()
// Offset: 0x157B0D8
::Il2CppString* ParsedToString();
}; // System.Net.Http.Headers.HttpHeaders/HeaderBucket
#pragma pack(pop)
static check_size<sizeof(HttpHeaders::HeaderBucket), 32 + sizeof(System::Func_2<::Il2CppObject*, ::Il2CppString*>*)> __System_Net_Http_Headers_HttpHeaders_HeaderBucketSizeCheck;
static_assert(sizeof(HttpHeaders::HeaderBucket) == 0x28);
}
DEFINE_IL2CPP_ARG_TYPE(System::Net::Http::Headers::HttpHeaders::HeaderBucket*, "System.Net.Http.Headers", "HttpHeaders/HeaderBucket");
| 51.525 | 268 | 0.707181 | darknight1050 |
c1250230f3a33c676940b4fbbe97fdc9b0d3729c | 1,400 | cpp | C++ | code/data-structures/avl_tree.test.cpp | guru-raj/CompetitiveProgramming | 5b326ad153f52d46a84f3d670f035af59a3ec016 | [
"MIT"
] | 549 | 2015-02-13T00:46:04.000Z | 2022-03-10T07:35:32.000Z | code/data-structures/avl_tree.test.cpp | guru-raj/CompetitiveProgramming | 5b326ad153f52d46a84f3d670f035af59a3ec016 | [
"MIT"
] | 6 | 2016-12-02T10:51:31.000Z | 2022-02-22T16:47:42.000Z | code/data-structures/avl_tree.test.cpp | guru-raj/CompetitiveProgramming | 5b326ad153f52d46a84f3d670f035af59a3ec016 | [
"MIT"
] | 143 | 2015-06-14T17:59:20.000Z | 2022-01-07T19:47:49.000Z | void test() {
/* Field testing: UVa 978, UVa 1513, UVa 12049, Kattis turbo */
int cnt = 10000,
range = 1000;
avl_tree<int> t1;
set<int> t2;
assert_equal(0, t1.size());
for (int i = 0; i < cnt; i++) {
int n = rand() % range;
avl_tree<int>::node *p = t1.insert(n);
assert_equal(n, p->item);
t2.insert(n);
assert_equal((int)size(t2), (int)size(t1));
int n1 = rand() % range;
avl_tree<int>::node *b = t1.find(n1);
if (b) assert_equal(n1, b->item);
assert_equal(b == NULL, t2.find(n1) == t2.end());
int n2 = rand() % range;
t1.erase(n2);
t2.erase(n2);
assert_equal((int)size(t2), (int)size(t1));
}
t1.clear();
t2.clear();
assert_equal(0, t1.size());
for (int i = 0; i < cnt; i++) {
int n = rand() % range;
avl_tree<int>::node *p = t1.insert(n);
assert_equal(n, p->item);
t2.insert(n);
assert_equal((int)size(t2), (int)size(t1));
int n1 = rand() % range;
avl_tree<int>::node *b = t1.find(n1);
if (b) assert_equal(n1, b->item);
assert_equal(b == NULL, t2.find(n1) == t2.end());
int n2 = rand() % range;
t1.erase(n2);
t2.erase(n2);
assert_equal((int)size(t2), (int)size(t1));
}
for (int i = 0; i < range; i++) {
t1.erase(i);
t2.erase(i);
assert_equal((int)size(t2), (int)size(t1));
}
assert_equal(0, t1.size());
}
// vim: cc=60 ts=2 sts=2 sw=2:
| 22.580645 | 65 | 0.544286 | guru-raj |
c125f43b11f6c55d13dd21d99ce11d0a61d0003b | 187,622 | cpp | C++ | wxWidgets/UserInterface/MainFrame.cpp | st-gb/CPUinfoAndControl | 5e93d4a195b4692d147bb05cfef534e38d7f8b64 | [
"MIT"
] | null | null | null | wxWidgets/UserInterface/MainFrame.cpp | st-gb/CPUinfoAndControl | 5e93d4a195b4692d147bb05cfef534e38d7f8b64 | [
"MIT"
] | null | null | null | wxWidgets/UserInterface/MainFrame.cpp | st-gb/CPUinfoAndControl | 5e93d4a195b4692d147bb05cfef534e38d7f8b64 | [
"MIT"
] | 1 | 2021-07-16T21:01:26.000Z | 2021-07-16T21:01:26.000Z | /* Do not remove this header/ copyright information.
*
* Copyright © Trilobyte Software Engineering GmbH, Berlin, Germany 2010-2011.
* You are allowed to modify and use the source code from
* Trilobyte Software Engineering GmbH, Berlin, Germany for free if you are not
* making profit with it or its adaption. Else you may contact Trilobyte SE.
*/
//"For compilers that support precompilation, includes "wx/wx.h"."
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
// for all others, include the necessary headers (this file is usually all you
// need because it includes almost all "standard" wxWidgets headers)
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "MainFrame.hpp"
//wxWidgets include files
#include <wx/defs.h> //for wxBG_STYLE_CUSTOM
#include <wx/dcbuffer.h> //for class wxBufferedPaintDC
#include <wx/dynlib.h> //wxDynamicLibrary::GetDllExt()
#include <wx/filename.h> //wxFileName::GetPathSeparator(...)
#include "wx/frame.h" //for base class wxFrame
//#include <wx/icon.h> //for class wxIcon
#include <wx/menu.h> //for class wxMenu, class wxMenuBar
#include <wx/menuitem.h> //class wxMenuItem
#include <wx/numdlg.h> //for ::wxGetNumberFromUser(...)
#include <wx/stattext.h> //for wxStaticText
#include <wx/string.h> //for wxString::Format(...)
#include <wx/timer.h> //for EVT_TIMER (,...?)
//#include <wx/tooltip.h> //for wxToolTip::SetDelay(...)
#include <wx/wx.h> //for wxMessageBox(...) (,etc.)
//#include "wx/window.h"
//#include <wx/menubar.h>
//#include "../Controller/RunAsService.h" //for MyServiceStart etc.
#include "FreqAndVoltageSettingDlg.hpp"
//SUPPRESS_UNUSED_VARIABLE_WARNING(...)
#include <compiler/GCC/suppress_unused_variable.h>
#include <Controller/CalculationThreadProc.h>
//for GetInterpolatedVoltageFromFreq(
// WORD wFreqInMHzToGetVoltageFrom
// , float & r_fVoltageInVolt
// , const std::set<VoltageAndFreq> & r_stdsetvoltageandfreq
// );
#include <Controller/CPU-related/GetInterpolatedVoltageFromFreq.hpp>
//::wxGetApp().mp_cpucoreusagegetter
#include <Controller/CPU-related/ICPUcoreUsageGetter.hpp>
#include <Controller/CPU-related/I_CPUcontroller.hpp>
////GetFilenameWithoutExtension(const std::string &)
//#include <Controller/FileSystem/GetFilenameWithoutExtension/\_
//GetFilenameWithoutExtension.hpp>
////for ::GetErrorMessageFromLastErrorCodeA(...)
//#include <Controller/GetErrorMessageFromLastErrorCode.hpp>
#include <Controller/IDynFreqScalingAccess.hpp>
#include <Controller/I_CPUaccess.hpp> //class I_CPUaccess
//WriteFileContent(...)
#include <InputOutput/WriteFileContent/WriteFileContent.hpp>
//for member m_stdmapwmenuid2i_cpucontrolleraction
#include <Controller/I_CPUcontrollerAction.hpp>//class I_CPUcontrollerAction
#include <Controller/IPC/I_IPC.hpp> //enum IPCcontrolCodes
#include <Controller/character_string/stdtstr.hpp> //Getstdtstring(...)
//DISable g++ "deprecated conversion from string constant to 'char*'" warning,
//from
//http://stackoverflow.com/questions/59670/how-to-get-rid-of-deprecated-conversion-from-string-constant-to-char-warning
// : "I believe passing -Wno-write-strings to gcc will suppress this warning."
#pragma GCC diagnostic ignored "-Wwrite-strings"
#include <x86IandC.xpm>
//ENable g++ "deprecated conversion from string constant to 'char*'" warning
#pragma GCC diagnostic warning "-Wwrite-strings"
#include <ModelData/ModelData.hpp> //class CPUcoreData
#include <ModelData/PerCPUcoreAttributes.hpp> //class PerCPUcoreAttributes
#include <ModelData/RegisterData.hpp>
//#include <ModelData/HighLoadThreadAttributes.hpp>
#include <ModelData/SpecificCPUcoreActionAttributes.hpp>
#include <preprocessor_macros/logging_preprocessor_macros.h> //LOGN(...)
//Pre-defined preprocessor macro under MSVC, MinGW for 32 and 64 bit Windows.
#ifdef _WIN32 //Built-in macro for MSVC, MinGW (also for 64 bit Windows)
//#include <Windows/CalculationThread.hpp>
#include <OperatingSystem/Windows/DLLloadError.hpp>
#include <OperatingSystem/Windows/ErrorCode/ErrorCodeFromGetLastErrorToString.h>
#include <OperatingSystem/Windows/ErrorCode/LocalLanguageMessageFromErrorCode.h>
#include <OperatingSystem/Windows/Service/ServiceBase.hpp>
#endif
#include <wxWidgets/App.hpp> //for wxGetApp() / DECLARE_APP
#include <wxWidgets/Controller/wxDynLibCPUcontroller.hpp>
#include <wxWidgets/Controller/wxDynLibCPUcoreUsageGetter.hpp>
//#include <wxWidgets/wxStringHelper.h>
//getwxString(const std::string &) / getwxString(const std::wstring &)
#include <wxWidgets/Controller/character_string/wxStringHelper.hpp>
//class NonBlocking::wxServiceSocketClient
#include <wxWidgets/Controller/non-blocking_socket/client/\
wxServiceSocketClient.hpp>
#include <wxWidgets/DynFreqScalingThread.hpp>
#include <wxWidgets/icon/CreateTextIcon.hpp> //CreateTextIcon(...)
#include <wxWidgets/ModelData/wxCPUcoreID.hpp>
//#ifdef COMPILE_WITH_SYSTEM_TRAY_ICON
#include <wxWidgets/UserInterface/TaskBarIcon.hpp>//class TaskBarIcon
//#endif
#include <wxWidgets/UserInterface/AboutDialog.hpp> //class AboutDialog
#include <wxWidgets/UserInterface/DynFreqScalingDlg.hpp>
#include <Xerces/XMLAccess.hpp>
#include "wxExamineCPUregistersDialog.hpp"
#ifdef COMPILE_WITH_MSR_EXAMINATION
#include "CPUregisterReadAndWriteDialog.hpp"
#endif //COMPILE_WITH_MSR_EXAMINATION
//#include <limits.h>
#ifndef MAXWORD
#define MAXWORD 65535
#endif //#ifndef MAXWORD
#include <map> //std::map
#include <set> //std::set
#include <valarray> //class std::valarray
//#include <xercesc/framework/MemBufInputSource.hpp>
#include <hardware/CPU/fastest_data_type.h> //typedef
#ifdef USE_WINDOWS_API_DIRECTLY_FOR_SYSTEM_TRAY_ICON
#include "SystemTrayAccess.hpp"
#endif //#ifdef USE_WINDOWS_API_DIRECTLY_FOR_SYSTEM_TRAY_ICON
#ifdef _MSC_VER
#define __FLT_MIN__ FLT_MIN
#endif
class wxObject ;
extern CPUcontrolBase * gp_cpucontrolbase ;
//Static class variables must (also) be declared/ defined in the source file.
float * MainFrame::s_arfTemperatureInDegreesCelsius = NULL ;
wxIcon MainFrame::s_wxiconTemperature ;
wxIcon MainFrame::s_wxiconCPUcoreUsages;
wxIcon MainFrame::s_wxiconCPUcoresMultipliers;
wxString MainFrame::s_wxstrHighestCPUcoreTemperative ;
wxString MainFrame::s_wxstrTaskBarIconToolTip =
wxT("x86IandC--highest CPU core temperature [°C]") ;
DEFINE_LOCAL_EVENT_TYPE( wxEVT_COMMAND_REDRAW_EVERYTHING )
BEGIN_EVENT_TABLE(MainFrame, wxFrame)
EVT_COMMAND(wxID_ANY, wxEVT_COMMAND_REDRAW_EVERYTHING,
MainFrame::OnRedrawEverything)
//"Cross-Platform GUI Programming with wxWidgets"
// (Copyright © 2006 Pearson Education, Inc.)
// ISBN 0-13-147381-6 "First printing, July 2005"
//"CHAPTER 5 Drawing and Printing" ->
//"UNDERSTANDING DEVICE CONTEXTS" -> "Drawing on Windows with wxPaintDC" :
// "[...] another thing you can do to make
// drawing smoother (particularly when resizing) is to paint the background in
// your paint handler, and not in an erase background handler. All the painting
// will then be done in your buffered paint handler, so you don’t see the back-
// ground being erased before the paint handler is called. Add an empty erase
// background handler, and call SetBackgroundStyle with wxBG_STYLE_CUSTOM to
// hint to some systems not to clear the background automatically."
EVT_ERASE_BACKGROUND(MainFrame::OnEraseBackground)
EVT_MENU(ID_Quit, MainFrame::OnQuit)
EVT_MENU(ID_About, MainFrame::OnAbout)
EVT_MENU(ID_AttachCPUcontrollerDynLib, MainFrame::OnAttachCPUcontrollerDLL)
EVT_MENU(ID_DetachCPUcontrollerDynamicLibrary, MainFrame::OnDetachCPUcontrollerDLL)
EVT_MENU(ID_AttachCPUusageGetterDynLib, MainFrame::OnAttachCPUcoreUsageGetterDLL)
EVT_MENU(ID_DetachCPUusageGetterDynLib, MainFrame::OnDetachCPUcoreUsageGetterDLL)
//Pre-defined preprocessor macro under MSVC, MinGW for 32 and 64 bit Windows.
#ifdef _WIN32 //Built-in macro for MSVC, MinGW (also for 64 bit Windows)
EVT_MENU(ID_MinimizeToSystemTray, MainFrame::OnMinimizeToSystemTray)
#endif
#ifdef COMPILE_WITH_MSR_EXAMINATION
EVT_MENU(ID_ShowExamineCPUregistersDialog, MainFrame::OnShowExamineCPUregistersDialog)
EVT_MENU(ID_WriteToMSRdialog, MainFrame::OnShowCPUregistersReadAndWriteDialog)
#endif
//EVT_MENU( ID_MinAndMaxCPUcoreFreqInPercentOfMaxFreq ,
// MainFrame::OnDynamicallyCreatedUIcontrol )
EVT_MENU( ID_DisableOtherVoltageOrFrequencyAccess ,
MainFrame::OnDisableOtherVoltageOrFrequencyAccess )
EVT_MENU( ID_EnableOtherVoltageOrFrequencyAccess ,
MainFrame::OnEnableOtherVoltageOrFrequencyAccess )
EVT_MENU( ID_EnableOrDisableOwnDVFS ,
MainFrame::OnOwnDynFreqScaling )
EVT_MENU( ID_LoadDetectInstableCPUcoreVoltageDynLib,
MainFrame::OnLoadDetectInstableCPUcoreVoltageDynLib)
EVT_MENU( ID_UnloadDetectInstableCPUcoreVoltageDynLib,
MainFrame::OnUnloadDetectInstableCPUcoreVoltageDynLib)
EVT_MENU( ID_UpdateViewInterval ,
MainFrame::OnUpdateViewInterval )
EVT_MENU( ID_SetCPUcontrollerDynLibForThisCPU ,
MainFrame::OnSaveAsCPUcontrollerDynLibForThisCPU )
EVT_MENU( ID_SaveAsDefaultPstates ,
MainFrame::OnSaveVoltageForFrequencySettings )
EVT_MENU( ID_FindDifferentPstates ,
MainFrame::OnFindDifferentPstates )
EVT_MENU( ID_Collect_As_Default_Voltage_PerfStates ,
MainFrame::OnCollectAsDefaultVoltagePerfStates )
EVT_MENU( ID_ShowVoltageAndFrequencySettingsDialog ,
MainFrame:://OnShowVoltageAndFrequencySettingsDialog
OnVoltageAndFrequencySettingsDialog)
#ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL
EVT_MENU( ID_ContinueService ,
MainFrame::OnContinueService )
EVT_MENU( ID_PauseService ,
MainFrame::OnPauseService )
EVT_MENU( ID_StartService ,
MainFrame::OnStartService )
EVT_MENU( ID_StopService ,
MainFrame::OnStopService )
EVT_MENU( ID_ConnectToService ,
MainFrame::OnConnectToService )
EVT_MENU( ID_ConnectToOrDisconnectFromService ,
MainFrame::OnConnectToOrDisconnectFromService )
EVT_MENU( ID_DisconnectFromService ,
MainFrame::OnDisconnectFromService )
#endif //#ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL
//#endif
//#ifdef _WINDOWS
#ifdef COMPILE_WITH_SERVICE_CAPABILITY
EVT_MENU(ID_Service, MainFrame::OnStartService)
#endif
//EVT_MENU(ID_SetPstate0ForBothCores, MyFrame::OnSetPstate0ForBothCores)
//EVT_MENU(ID_SetPstate1ForBothCores, MyFrame::OnSetPstate1ForBothCores)
//EVT_MENU(ID_SetPstate2ForBothCores, MyFrame::OnSetPstate2ForBothCores)
//EVT_MENU(ID_FindLowestOperatingVoltage, MainFrame::OnFindLowestOperatingVoltage)
#ifdef PRIVATE_RELEASE //hide the other possibilities
EVT_MENU(ID_IncreaseVoltageForCurrentPstate, MainFrame::OnIncreaseVoltageForCurrentPstate)
#endif //#ifdef PRIVATE_RELEASE //hide the other possibilities
#ifdef wxHAS_POWER_EVENTS
EVT_POWER_RESUME(MainFrame::OnResume)
EVT_POWER_SUSPENDING(MainFrame::OnSuspending)
EVT_POWER_SUSPENDED(MainFrame::OnSuspended)
EVT_POWER_SUSPEND_CANCEL(MainFrame::OnSuspendCancel)
#endif // wxHAS_POWER_EVENTS
//For stopping the DynVoltAndFreqScal thread that accesses the wxApp.
//So stop the DVFS thread before destroying the wxApp object to avoid
//crashes.
EVT_CLOSE( MainFrame::OnClose )
// EVT_INIT_DIALOG(MainFrame::OnInitDialog)
//If no EVT_PAINT macro and Connect(wxEVT_PAINT,
// wxPaintEventHandler(MyFrame::OnPaint));
// : 100% CPU load.
EVT_PAINT (MainFrame::OnPaint)
EVT_SIZE(MainFrame::OnSize)
EVT_SIZING(MainFrame::OnSizing)
EVT_MOTION(MainFrame::OnMoveMouse)
EVT_LEFT_DOWN(MainFrame::OnLeftMouseButtonDown)
//EVT_TIMER(-1,MainFrame::OnTimerEvent)
EVT_TIMER(TIMER_ID, MainFrame::OnTimerEvent)
//EVT_COMMAND_RIGHT_CLICK(FIRST_TRAYNOTIFY_ID, MainFrame::OnSysTrayIconClick)
// EVT_MOUSE_EVENTS(FIRST_TRAYNOTIFY_ID, MainFrame::OnSysTrayIconClick)
END_EVENT_TABLE()
#define ATTACH_CPU_CONTROLLER_DYNAMIC_LIBRARY_T_STRING \
_T("Attach CPU &controller dynamic library...")
#define ATTACH_CPU_CORE_USAGE_GETTER_DYNAMIC_LIBRARY_T_STRING \
_T("Attach CPU &usage getter dynamic library...")
#define DETACH_CPU_CONTROLLER_DYNAMIC_LIBRARY_T_STRING \
_T("Detach CPU controller dynamic library")
#define DETACH_CPU_CORE_USAGE_GETTER_DYNAMIC_LIBRARY_T_STRING \
_T("Detach CPU usage getter dynamic library")
//for CPU_TEMP_IS_BELOW_CRITICAL, CPU_TEMP_IS_CRITICAL
#include <Controller/CPU-related/CPU_core_temperature_defs.h>
inline void MainFrame::CreateFileMenu()
{
LOGN(/*"CreateFileMenu()"*/ "begin")
wxMenuItem * p_wxmenuitem ;
mp_wxmenuFile = new wxMenu;
//wxMenu * p_wxmenuCore1 = new wxMenu;
// wxMenu * p_wxmenuNorthBridge = new wxMenu;
mp_wxmenuFile->Append( ID_About, _T("&About...") );
mp_wxmenuFile->AppendSeparator();
p_wxmenuitem = mp_wxmenuFile->Append( ID_AttachCPUcontrollerDynLib,
ATTACH_CPU_CONTROLLER_DYNAMIC_LIBRARY_T_STRING );
if( ! mp_wxx86infoandcontrolapp->GetCPUaccess() )
p_wxmenuitem->SetHelp (
//TODO more imformative/ user-friendly message (but may not be too long)
wxT("No CPU access. See log file/ start this program as admin.") ) ;
mp_wxmenuFile->Append( ID_DetachCPUcontrollerDynamicLibrary,
DETACH_CPU_CONTROLLER_DYNAMIC_LIBRARY_T_STRING );
mp_wxmenuFile->Append( ID_SetCPUcontrollerDynLibForThisCPU,
wxString::Format(
wxT("save as CPU controller dynamic library for this CPU "
"(vendor:%s family:%u model:%u stepping:%u)")
, wxWidgets::getwxString( mp_model->m_cpucoredata.m_strVendorID.c_str() ).c_str()
, mp_model->m_cpucoredata.m_wFamily
, (WORD) mp_model->m_cpucoredata.m_byModel
, (WORD) mp_model->m_cpucoredata.m_byStepping
)
);
if( ! //gp_cpucontrolbase->mp_wxdynlibcpucontroller
mp_wxx86infoandcontrolapp->m_p_cpucontrollerDynLib
)
{
mp_wxmenuFile->Enable( ID_SetCPUcontrollerDynLibForThisCPU, false ) ;
mp_wxmenuFile->Enable( ID_DetachCPUcontrollerDynamicLibrary, false ) ;
}
mp_wxmenuFile->AppendSeparator();
p_wxmenuitem = mp_wxmenuFile->Append( ID_AttachCPUusageGetterDynLib,
ATTACH_CPU_CORE_USAGE_GETTER_DYNAMIC_LIBRARY_T_STRING );
if( ! mp_wxx86infoandcontrolapp->GetCPUaccess() )
p_wxmenuitem->SetHelp (
//TODO more imformative/ user-friendly message (but may not be too long)
wxT("No CPU access. See log file/ start this program as admin.") ) ;
mp_wxmenuFile->Append( ID_DetachCPUusageGetterDynLib,
DETACH_CPU_CORE_USAGE_GETTER_DYNAMIC_LIBRARY_T_STRING );
if( ! //gp_cpucontrolbase->mp_wxdynlibcpucoreusagegetter
mp_wxx86infoandcontrolapp->m_p_cpucoreusagegetterDynLib
)
mp_wxmenuFile->Enable( ID_DetachCPUusageGetterDynLib, false ) ;
mp_wxmenuFile->AppendSeparator();
mp_wxmenuFile->Append( ID_SaveAsDefaultPstates,
//wxT("Save &performance states settings...")
wxT("Save \"&voltage at/for frequency\" settings...")
);
//Only add menu item if creating the system tray icon succeeded: else one
// can hide the window but can not restore it: if this process started
//elevated one can't even close it!
if( mp_wxx86infoandcontrolapp->ShowTaskBarIcon(this) )
{
mp_wxmenuFile->AppendSeparator();
// mp_wxx86infoandcontrolapp->ShowTaskBarIcon(this) ;
mp_wxmenuFile->Append( ID_MinimizeToSystemTray,
_T("minimize this window to the "
//"system tray"
"task bar") );
}
//#endif //COMPILE_WITH_TASKBAR
mp_wxmenuFile->AppendSeparator();
//mp_wxmenuFile->Append( ID_Service, _T("Run As Service") );
mp_wxmenuFile->Append( ID_Quit, _T("E&xit") );
//p_wxmenuBar->Append( mp_wxmenuFile, _T("&File") );
//m_wxmenubar.Append( mp_wxmenuFile, _T("&File") );
mp_wxmenubar->Append( mp_wxmenuFile, _T("&File") );
LOG("after file menu creation"//\n"
)
}
/** @brief creates menu items for the "GUI" menu. */
inline void MainFrame::CreateGUImenuItems()
{
m_p_wxmenuGUI = NULL ;
//#ifdef COMPILE_WITH_SERVICE_CONTROL
#ifdef COMPILE_WITH_OTHER_DVFS_ACCESS
if( ! m_p_wxmenuGUI )
m_p_wxmenuGUI = new wxMenu;
mp_wxmenuitemOtherDVFS = m_p_wxmenuGUI->Append(
//ID_MinAndMaxCPUcoreFreqInPercentOfMaxFreq
ID_DisableOtherVoltageOrFrequencyAccess
//_T("&CPU % min and max.")
//_T("enable or disable OS's dynamic frequency scaling")
, wxT("DISable OS's dynamic frequency scaling")
);
mp_wxmenuitemOtherDVFS = m_p_wxmenuGUI->Append(
ID_EnableOtherVoltageOrFrequencyAccess
, wxT("ENable OS's dynamic frequency scaling")
);
LOGN("after appending menu item \"disable OS's dynamic frequency scaling\"")
//If one can not change the power scheme (Windows) etc.
if( //mp_i_cpucontroller->mp_dynfreqscalingaccess->
mp_wxx86infoandcontrolapp->mp_dynfreqscalingaccess->
ChangeOtherDVFSaccessPossible()
)
LOGN("Changing other DVFS is possible." )
else
{
LOGN("Changing other DVFS is not possible." )
mp_wxmenuitemOtherDVFS->Enable(false);
mp_wxmenuitemOtherDVFS->SetHelp (
wxT("Start e.g. as administrator to gain access") ) ;
//mp_wxmenuitemOtherDVFS->SetItemLabel (wxT("dd") ) ;
LOGN("changing other DVFS not possible")
}
if( //mp_i_cpucontroller->mp_dynfreqscalingaccess->EnablingIsPossible()
mp_wxx86infoandcontrolapp->mp_dynfreqscalingaccess->EnablingIsPossible()
)
{
LOGN("enabling other DVFS is possible")
// std::tstring stdtstr = p_wxx86infoandcontrolapp->mp_dynfreqscalingaccess->
// GetEnableDescription() ;
std::wstring stdwstr = mp_wxx86infoandcontrolapp->mp_dynfreqscalingaccess->
GetEnableDescription() ;
mp_wxmenuitemOtherDVFS = m_p_wxmenuGUI->Append(
ID_EnableOtherVoltageOrFrequencyAccess
//_T("enable OS's dynamic frequency scaling")
//GetDisableDescrpition() under Windows may return "activate 'performance' power scheme ".
//Use GetwxString(...) because GetEnableDescription() may return
// -std::wstring although wxString uses char strings.
// -std::string although wxString uses wchar_t strings.
, wxWidgets::getwxString(
//mp_i_cpucontroller->mp_dynfreqscalingaccess->GetEnableDescription()
// stdtstr
stdwstr
)
);
LOGN("after appending menu item \"" << GetStdString(stdwstr) << "\"")
}
#endif //#ifdef COMPILE_WITH_OTHER_DVFS_ACCESS
LOG("after extras menu creation"//\n"
)
if( ! m_p_wxmenuGUI )
m_p_wxmenuGUI = new wxMenu;
std::string stdstr = "set update view interval" ;
LOGN("before appending menu item " << stdstr )
m_p_wxmenuGUI->Append(
ID_UpdateViewInterval,
//_T("&CPU % min and max.")
wxWidgets::getwxString( stdstr )
);
stdstr = "collect p-states as default voltage p-states" ;
LOGN("before appending menu item " << stdstr )
mp_wxmenuitemCollectAsDefaultVoltagePerfStates = m_p_wxmenuGUI->
AppendCheckItem(
ID_Collect_As_Default_Voltage_PerfStates,
//_T("&CPU % min and max.")
wxWidgets::getwxString( stdstr )
);
//#ifdef _WIN32 //Built-in macro for MSVC, MinGW (also for 64 bit Windows)
//wxMenu * m_p_wxmenuGUI = new wxMenu;
//#endif
//if( ! p_cpucontroller->mp_model->m_cpucoredata.
// m_stdsetvoltageandfreqDefault.empty()
// )
{
if( ! m_p_wxmenuGUI )
m_p_wxmenuGUI = new wxMenu;//(wxT("Graphical User Interface"));
stdstr = "enable own Dynamic Voltage and Frequency Scaling" ;
LOGN("before appending menu item " << stdstr )
mp_wxmenuitemOwnDVFS = m_p_wxmenuGUI->Append(
ID_EnableOrDisableOwnDVFS
, wxWidgets::getwxString( stdstr )
);
if( //p_cpucontroller->mp_model->m_cpucoredata.
mp_model->m_cpucoredata.
m_stdsetvoltageandfreqWanted.empty()
)
{
//Does not work.
// mp_wxmenuitemOwnDVFS->Enable(false) ;
// m_p_wxmenuGUI->Enable(ID_EnableOrDisableOwnDVFS , false ) ;
// mp_wxmenuitemOwnDVFS->Enable(false) ;
mp_wxmenuitemOwnDVFS->SetHelp( wxT("no desired voltages for frequencies"
" available->no DVFS possible") ) ;
}
}
//#endif //#ifdef _WIN32
#ifdef COMPILE_WITH_MSR_EXAMINATION
if( ! m_p_wxmenuGUI )
m_p_wxmenuGUI = new wxMenu;
m_p_wxmenuGUI->Append(ID_ShowExamineCPUregistersDialog,
wxT("e&xamine CPUID and MSR CPU registers...")
);
m_p_wxmenuGUI->Append(ID_WriteToMSRdialog,
wxT("read from and write to MSR dialog...") );
#endif
m_p_wxmenuGUI->Append( ID_LoadDetectInstableCPUcoreVoltageDynLib,
wxT("Load dynamic library for detecting an instable CPU core voltage...")
);
m_p_wxmenuitemUnloadDetectInstableCPUcoreVoltageDynLib = m_p_wxmenuGUI->
Append( ID_UnloadDetectInstableCPUcoreVoltageDynLib,
wxT("Unload dynamic library for detecting an instable CPU core voltage")
);
if( m_p_wxmenuGUI )
{
LOGN("before adding menu \"GUI\"")
mp_wxmenubar->Append(m_p_wxmenuGUI, //_T("E&xtras")
wxT("&GUI") );
}
}
MainFrame::MainFrame(
const wxString & cr_wxstrTitle,
const wxPoint & cr_wxpointTopLeftCornerPosition,
const wxSize & cr_wxsize
, I_CPUcontroller * p_cpucontroller
//, CPUcoreData * p_cpucoredata
, Model * p_model
, wxX86InfoAndControlApp * p_wxx86infoandcontrolapp
)
: wxFrame( (wxFrame *) NULL, -1, cr_wxstrTitle,
cr_wxpointTopLeftCornerPosition, cr_wxsize
//http://docs.wxwidgets.org/2.6/wx_wxwindow.html#wxwindow:
//"Use this style to force a complete redraw of the window whenever it is
//resized instead of redrawing just the part of the window affected by
//resizing. Note that this was the behaviour by default before 2.5.1
//release and that if you experience redraw problems with code which
//previously used to work you may want to try this. Currently this style
//applies on GTK+ 2 and Windows only, and full repainting is always done
//on other platforms."
//kurz: Stil ist notwendig, um das ganze Diagramm neu zu zeichnen
, wxFULL_REPAINT_ON_RESIZE //| wxCLIP_CHILDREN
//Necessary for showing a title bar
| wxDEFAULT_FRAME_STYLE
)
//, mp_cpucoredata(p_cpucoredata)
//Initialize in the same order as textual in the declaration?
//(to avoid g++ warnings)
, m_bAllowCPUcontrollerAccess ( true )
, m_bCPUcoreUsageConsumed( true )
, m_bDiagramNotDrawn(true)
, mp_ar_voltage_and_multi( NULL )
, m_bNotFirstTime(false)
, m_bRangeBeginningFromMinVoltage ( true )
// , s_arfTemperatureInDegreesCelsius( NULL )
#ifdef COMPILE_WITH_CALC_THREAD
, mp_calculationthread( NULL )
#endif
, mp_cpucoredata( & p_model->m_cpucoredata )
, m_dwTimerIntervalInMilliseconds (1000)
// , m_fPreviousCPUusage(0.0f)
// , mp_freqandvoltagesettingdlg(NULL)
, m_arp_freqandvoltagesettingdlg ( NULL )
, m_p_freqandvoltagesettingsdialog(NULL)
, mp_i_cpucontroller ( p_cpucontroller)
, mp_model ( p_model )
//, m_bConfirmedYet(true)
, m_vbAnotherWindowIsActive(false)
, m_wMaximumCPUcoreFrequency ( 0 )
, m_wMaxFreqInMHzTextWidth ( 0 )
, m_wMaxVoltageInVoltTextWidth ( 0 )
, m_wMaxTemperatureTextWidth ( 0 )
//, m_wxbufferedpaintdcStatic( this )
//Necessary for the timer to run:
, mp_wxbitmap(NULL)
, mp_wxbitmapStatic (NULL)
, mp_wxbufferedpaintdcStatic( NULL)
// , m_wxicon_drawer(16,16//,8
//// ,wxBITMAP_SCREEN_DEPTH
// )
//, mp_wxdynlibcpucontroller ( NULL )
//, mp_wxdynlibcpucoreusagegetter ( NULL )
, m_wxstrTitle(cr_wxstrTitle)
, m_wxtimer(this)
, mp_wxx86infoandcontrolapp ( p_wxx86infoandcontrolapp )
// , m_xerces_voltage_for_frequency_configuration( p_model )
{
LOGN("begin of main frame creation"//\n"
)
wxIcon wxicon;
if( p_wxx86infoandcontrolapp->GetX86IandCiconFromFile(wxicon) )
{
SetIcon( wxicon);
}
else
{
// p_wxx86infoandcontrolapp->MessageWithTimeStamp(
// GetStdWstring( wxT("setting icon for the main frame failed") )
// );
LOGN("setting icon from file for the main frame failed")
wxIcon wxiconThisDialog( x86IandC_xpm ) ;
SetIcon(x86IandC_xpm);
}
LOGN("# CPU cores: " <<
(WORD) mp_model->m_cpucoredata.m_byNumberOfCPUCores)
// m_p_wxtimer = new wxTimer( this ) ;
mp_ar_voltage_and_multi = new VoltageAndMulti[
mp_model->m_cpucoredata.m_byNumberOfCPUCores ] ;
//"Cross-Platform GUI Programming with wxWidgets"
// (Copyright © 2006 Pearson Education, Inc.)
// ISBN 0-13-147381-6 "First printing, July 2005"
//"CHAPTER 5 Drawing and Printing" ->
//"UNDERSTANDING DEVICE CONTEXTS" -> "Drawing on Windows with wxPaintDC" :
//"[...] call SetBackgroundStyle with wxBG_STYLE_CUSTOM to
// hint to some systems not to clear the background automatically."
SetBackgroundStyle(wxBG_STYLE_CUSTOM );
// m_bConfirmedYet = true ;
mp_wxmenubar = new wxMenuBar;
CreateFileMenu() ;
//#ifdef COMPILE_WITH_OTHER_DVFS_ACCESS
#ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL
CreateServiceMenuItems() ;
#endif
// CreateAndInitMenuItemPointers() ;
//p_wxmenuCore0->Append( ID_FindLowestOperatingVoltage,
// _T("find lowest operating voltage") );
//p_wxmenuAllCores->Append( ID_FindLowestOperatingVoltage,
//_T("find lowest operating voltage") );
//#ifdef PRIVATE_RELEASE //hide the other possibilities
// p_wxmenuCore0->Append( ID_IncreaseVoltageForCurrentPstate,
// _T("increase voltage for current p-state (stabilize machine)") );
//#endif //#ifdef PRIVATE_RELEASE //hide the other possibilities
//UpdatePowerSettings(wxPOWER_UNKNOWN, wxBATTERY_UNKNOWN_STATE);
CreateGUImenuItems();
if( mp_i_cpucontroller != NULL )
{
CreateDynamicMenus();
}
//#ifdef COMPILE_WITH_VISTA_POWERPROFILE_ACCESS
// ////Connect the action, that is a class derived from class xx directly
// ////with the menu item so that it is ensured to be the correct action
// ////(calling the action in an event function is more error-prone)
// ////TODO release memory
// ////, new CalculationThread(byCoreID, HighALUloadThreadProc)
// //, wxCommandEventHandler( MainFrame::OnOwnDynFreqScaling )
// //) ;
// mp_wxmenubar->Append(m_p_wxmenuGUI, _T("E&xtras") );
//#endif
//mp_wxmenubar->Append( p_wxmenuNorthBridge, _T("&NorthBridge") );
//TODO program crash here for unicode versions (for working versions
// an OnSize() event was intermediate)
LOGN("before setting menu bar " << mp_wxmenubar)
//Just for testing.
// wxSleep(5) ;
//SetMenuBar( p_wxmenuBar );
//SetMenuBar( & m_wxmenubar );
SetMenuBar( mp_wxmenubar );
LOGN("before creating status bar")
CreateStatusBar();
// const char bits [] = {
// 0,0,0,0,
// 1,1,1,1,
// 0,0,0,0,
// 1,1,1,1
// } ;
// wxIcon wxicon(bits,4,4) ;
// SetIcon(wxicon);
// Connect(wxEVT_PAINT, wxPaintEventHandler(MainFrame::OnPaint));
//SetStatusText( _T("Welcome to wxWidgets!") );
LOGN("before starting the update view timer")
//m_wxtimer.Start(1000);
m_wxtimer.Start(m_dwTimerIntervalInMilliseconds);
// m_p_wxtimer->Start(m_dwTimerIntervalInMilliseconds);
//http://docs.wxwidgets.org/stable/wx_wxtimer.html#wxtimersetowner:
//"Associates the timer with the given owner object. When the timer is
//running, the owner will receive timer events with id equal to id
//specified here."
m_wxtimer.SetOwner(this, TIMER_ID) ;
// Connect(wxEVT_SIZE, wxSizeEventHandler(MainFrame::OnSize));
if( mp_wxx86infoandcontrolapp->//mp_wxdynlibcpucontroller
m_p_cpucontrollerDynLib
)
{
wxString wxstrCPUcontrollerDynLibPath(
// //Use getwxString() to enable to compile with both unicode and ANSI.
// getwxString(
// mp_model->m_stdstrCPUcontrollerDynLibPath )
// ) ;
//http://wiki.wxwidgets.org/Converting_everything_to_and_from_wxString#std::string_to_wxString:
mp_model->m_stdstrCPUcontrollerDynLibPath.c_str(), wxConvUTF8 );
#if wxUSE_UNICODE == 1
DEBUGWN_WSPRINTF(L"CPU controller path as wide string:%ls",
//wxstrCPUcontrollerDynLibPath.c_str()
wxstrCPUcontrollerDynLibPath.wc_str() ) ;
#endif
CPUcontrollerDynLibAttached(wxstrCPUcontrollerDynLibPath) ;
}
if( mp_wxx86infoandcontrolapp->//mp_wxdynlibcpucoreusagegetter
m_p_cpucoreusagegetterDynLib
)
{
wxString wxstrCPUcoreUsageGetterDynLibPath(
//Use getwxString() to enable to compile with both unicode and ANSI.
wxWidgets::getwxString(
mp_model->m_stdstrCPUcoreUsageGetterDynLibPath)
) ;
CPUcoreUsageGetterAttached(wxstrCPUcoreUsageGetterDynLibPath) ;
}
// mp_wxx86infoandcontrolapp->ShowTaskBarIcon(this) ;
LOGN("end of main frame creation"//\n"
)
// RedrawEverything() ;
// Refresh() ;
// InitDialog() ;
}
MainFrame::~MainFrame()
{
LOGN("begin" /*" of main frame's destructor"*/ )
//TODO Error here.the problem was with destructor of wxMenuBar.->create
//wxMenuBar via "new"?
//for(BYTE byCoreID = 0 ; byCoreID < //m_byCoreNumber
// mp_cpucoredata->m_byNumberOfCPUCores ; ++ byCoreID )
//{
// //Release memory from the heap.
// delete m_vecp_wxmenuCore.at(byCoreID) ;
//}
//Release memory for array of pointers.
// delete [] m_arp_wxmenuitemPstate ;
// delete [] marp_wxmenuItemHighLoadThread ;
#ifdef COMPILE_WITH_CALC_THREAD
if( mp_calculationthread )
delete mp_calculationthread ;
#endif
//Only terminates correctly when deleted from here (is also deleted in
//the wxTopLevelWindow's (wxDialog's) destructor in wxWidgets' "tbtest.cpp"
//from the "taskbar" sample.
mp_wxx86infoandcontrolapp->DeleteTaskBarIcons();
LOGN("end" /*" of main frame's destructor"*/ )
}
//void MyFrame::AddMenu()
//{
// //wxEventTableEntry(type, winid, idLast, fn, obj)
// EVT_MENU(ID_LastStaticEventID+1,MyFrame::OnDynamicMenu);
//}
//
//void MyFrame::OnDynamicMenu(wxCommandEvent &event)
//{
//
//}
//wxString MainFrame::BuildHighLoadThreadMenuText(
// std::string str,
// BYTE byPreviousAction)
//{
// wxString wxstr = byPreviousAction == //ENDED ?
// ICalculationThread::ended ?
// //We need a _T() macro (wide char-> L"", char->"") for EACH
// //line to make it compatible between char and wide char.
// _T("Start") :
// //We need a _T() macro (wide char-> L"", char->"") for EACH
// //line to make it compatible between char and wide char.
// _T("End") ;
// ////Invert the menu item's checked state.
// //marp_wxmenuItemHighLoadThread[byCoreID]->Check(
// // ! marp_wxmenuItemHighLoadThread[byCoreID]->IsChecked () ) ;
//// marp_wxmenuItemHighLoadThread[byCoreID]->SetText(
//// wxstr +
//// str
//// );
// return wxstr + wxString(
// //TODO this conversion may not work
// (const wxChar*) str.c_str() ) ;
//}
//bool MainFrame::Confirm(const std::string & str)
//{
// //::AfxMessageBox(str.c_str());
//
// //To not show too many dialogs that the timer would bring up.
//// if( m_bConfirmedYet )
//// {
//// m_bConfirmedYet = false ;
//// ::wxMessageBox(wxString(
//// //TODO this conversion may not work
//// (const wxChar * ) str.c_str() )
//// );
//// m_bConfirmedYet = true ;
//// }
// //m_bConfirmedYet = true ;
// return true;
//}
//bool MainFrame::Confirm(std::ostrstream & r_ostrstream
// //std::ostream & r_ostream
// )
//{
// bool bReturn = true ;
// DEBUGN("begin");
// //Must set this, else text may follow after the string we want.
// //I had program crashes with the following method:
// //pch[r_ostrstream.pcount()] = '\0' ;
// //r_ostrstream.ends();
// r_ostrstream.put('\0'); //the same as "ends()" does.
//// char *pch = r_ostrstream.str() ;
// //r_ostrstream.flush();
// //To not show too many dialogs that the timer would bring up.
//// if( m_bConfirmedYet )
//// {
//// m_bConfirmedYet = false ;
//// int nReturn = ::wxMessageBox( wxString(
//// //TODO this conversion may not work
//// (const wxChar * ) pch ) ,
//// //We need a _T() macro (wide char-> L"", char->"") for EACH
//// //line to make it compatible between char and wide char.
//// wxString( _T("Message") ) , wxCANCEL | wxOK ) ;
//// if( nReturn == wxCANCEL )
//// bReturn = false ;
//// m_bConfirmedYet = true ;
//// }
// //return true;
// DEBUGN("end");
// return bReturn ;
//}
inline void MainFrame::ConnectToDataProvider_Inline()
{
mp_wxx86infoandcontrolapp->ConnectToDataProviderAndShowResult() ;
}
#ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL
void MainFrame::CreateServiceMenuItems()
{
wxString wxstrConnectOrDisconnect ;
p_wxmenuService = new wxMenu ;
//TODO: set bitmap for item
//http://docs.wxwidgets.org/trunk/classwx_menu_item.html#a2b5d6bcb820b992b1e4709facbf6d4fb:
//"SetBitmap() must be called before the item is appended to the menu"
// wxMenuItem * p_wxmenuitem = new wxMenuItem();
// p_wxmenuitem->SetBitmap();
if( ServiceBase::CanStartService() )
{
p_wxmenuService->Append( ID_StartService , wxT("&start"),
wxT("start the x86I&C service via the Service Control Manager") ) ;
}
else
p_wxmenuService->Append( ID_StartService , wxT("&start"),
wxT("insufficient rights to start the x86I&C service via the Service "
"Control Manager") ) ;
//Stopping a service can be done via Inter Process Communication. (Else if
//via Service Control manager then needs the same? rights/ privileges as
//starting a service).
p_wxmenuService->Append( ID_StopService , wxT("s&top"),
wxT("stop the x86I&C service via InterProcess Communication or via "
"Service Control Manager") );
#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE
p_wxmenuService->Append( ID_ConnectToService,
wxT("connect..."), wxT("connect to an arbitrary address to the (x86IandC) "
"CPU core data provider/ server/ service") );
// if( mp_wxx86infoandcontrolapp->m_ipcclient.IsConnected() )
// wxstrConnectOrDisconnect = wxT("disconnect") ;
// else
wxstrConnectOrDisconnect = wxT("c&onnect to ") + wxWidgets::getwxString(
mp_model->m_userinterfaceattributes.m_std_wstrServiceAddress);
p_wxmenuService->Append( ID_ConnectToOrDisconnectFromService,
wxstrConnectOrDisconnect, wxT("connect to the (x86IandC) "
"CPU core data provider/ server/ service"
// " specified in the x86IandC "
// "config file"
) );
p_wxmenuService->Append( ID_DisconnectFromService, wxT("&DISCOnnect"),
wxT("DISconnect from the (x86IandC) "
"CPU core data provider/ server/ service if currently connected") );
#endif //#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE
//pause and continue is possible via service ctrl mgr
p_wxmenuService->Append( ID_ContinueService, wxT("&Continue"), wxT("continue "
"the Dynamic Voltage and Frequency Scaling done by the x86IandC service/ "
"server") );
p_wxmenuService->Append( ID_PauseService , wxT("&Pause"), wxT("pause "
"the Dynamic Voltage and Frequency Scaling done by the x86IandC service/ "
"server") );
// p_wxmenuService->Append( ID_StartService , _T("&Start") );
// p_wxmenuService->Append( ID_StopService , _T("Sto&p") );
mp_wxmenubar->Append( p_wxmenuService, wxT("&Service") ) ;
LOGN("end" /*" of CreateServiceMenuItems"*/ )
}
#endif //#ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL
////void
//wxMenuItem * MainFrame::AddDynamicallyCreatedMenu(
// wxMenu * p_wxmenu,
// WORD & r_wMenuID,
// const wxString & r_wxstr
// )
//{
// wxMenuItem * p_wxmenuitemAppended = p_wxmenu->Append(r_wMenuID, r_wxstr );
// Connect( r_wMenuID ++ , //wxID_ANY,
// wxEVT_COMMAND_MENU_SELECTED ,
// wxCommandEventHandler(MainFrame::OnDynamicallyCreatedUIcontrol)
// );
// return p_wxmenuitemAppended ;
//}
//wxMenuItem * MainFrame::AddDynamicallyCreatedMenu(
// wxMenu * p_wxmenu,
// WORD & r_wMenuID,
// const wxString & r_wxstr
// , //void (wxEvtHandler::*wxEventFunction)(wxEvent&)
// wxObjectEventFunction wxeee
// , SpecificCPUcoreActionAttributes * p_scaa
// )
//{
// m_stdmapwxuicontroldata.insert(
// std::make_pair(
// r_wMenuID ,
// //TODO release memory
// p_scaa
// )
// ) ;
// wxMenuItem * p_wxmenuitemAppended = p_wxmenu->Append(r_wMenuID, r_wxstr );
// Connect( r_wMenuID ++ , //wxID_ANY,
// wxEVT_COMMAND_MENU_SELECTED ,
// //wxCommandEventHandler(
// //wxEventFunction //)
// wxeee
// );
// return p_wxmenuitemAppended ;
//}
//wxMenuItem * MainFrame::AddDynamicallyCreatedMenu(
// wxMenu * p_wxmenu,
// WORD & r_wMenuID,
// const wxString & r_wxstr,
// //Use a concrete class as parameter because this is more flexible than
// //using a function with (a) fixed parameter type(s).
// //Another option: use C functions: then parameter here would be:
// //"void func(PVOID)"
// //function A (PVOID pv)
// //{ ActionAParamStruct * paramstr = (ActionAParamStruct)
// // ActionAParamStruct: necessary parameters for execution (like CPU core ID)
// // pv ; }
// //
// I_CPUcontrollerAction * icpuca
// )
//{
// wxMenuItem * p_wxmenuitemAppended = p_wxmenu->Append(r_wMenuID, r_wxstr );
// m_stdmapwmenuid2i_cpucontrolleraction.insert(
// std::make_pair (r_wMenuID,icpuca)
// ) ;
// Connect( r_wMenuID ++, wxID_ANY, wxEVT_COMMAND_MENU_SELECTED,
// wxCommandEventHandler(MainFrame::OnDynamicallyCreatedUIcontrol)
// );
// return p_wxmenuitemAppended ;
//}
//void MainFrame::CreateAndInitMenuItemPointers()
//{
// marp_wxmenuItemHighLoadThread = new wxMenuItem * [
// mp_cpucoredata->m_byNumberOfCPUCores ] ;
// for( BYTE byIndex = 0 ; byIndex < mp_cpucoredata->m_byNumberOfCPUCores ;
// ++ byIndex )
// marp_wxmenuItemHighLoadThread[ byIndex ] = NULL ;
//}
//
////void
////Return: TRUE: success.
//BYTE MainFrame::AddSetPstateMenuItem(
// wxMenu * p_wxmenuCore
// , BYTE byCoreID
// , BYTE byPstateID
// //Must be a reference because changes to the variable should be
// //maintained OUTside this function.
// , WORD & r_wMenuID
// )
//{
// BYTE byReturnValue = FALSE ;
// return byReturnValue ;
//}
void MainFrame::Create1DialogAndMenuForAllCores()
{
wxMenu * p_wxmenuCore ;
p_wxmenuCore = new wxMenu;
if( p_wxmenuCore )
{
m_p_wxmenuCore = p_wxmenuCore;
p_wxmenuCore->Append(//ID_LastStaticEventID
ID_ShowVoltageAndFrequencySettingsDialog,
_T("set frequency and voltage ") );
mp_wxmenubar->Append(
p_wxmenuCore,
//We need a wxT() macro (wide char-> L"", char->"") for EACH
//line to make it compatible between char and wide char.
wxT("core(s)")
);
// Connect( ID_LastStaticEventID, wxID_ANY, wxEVT_COMMAND_MENU_SELECTED,
// wxCommandEventHandler(
// MainFrame::OnVoltageAndFrequencySettingsDialog )
// );
// LOGN("Connected event ID" << ID_LastStaticEventID << " to" <<
// "MainFrame::OnPstateDialog.")
}
}
void MainFrame::CreateDialogAndMenuForEveryCore()
{
// BYTE byReturnValue ;
WORD wMenuID = ID_LastStaticEventID;
wxMenu * p_wxmenuCore ;
m_arp_freqandvoltagesettingdlg = new FreqAndVoltageSettingDlg * [
mp_cpucoredata->m_byNumberOfCPUCores];
if(m_arp_freqandvoltagesettingdlg)
{
BYTE byPointerSize = sizeof( m_arp_freqandvoltagesettingdlg[0] ) ;
//important: init pointers with NULL
memset(
m_arp_freqandvoltagesettingdlg
, //NULL
0
, byPointerSize * mp_cpucoredata->m_byNumberOfCPUCores );
//TRACE("sizeof: %u\n", sizeof(m_arp_freqandvoltagesettingdlg));
#ifdef _DEBUG
// int i = sizeof(m_arp_freqandvoltagesettingdlg) ;
#endif
for( BYTE byCoreID = 0 ; byCoreID < //m_byCoreNumber
mp_cpucoredata->m_byNumberOfCPUCores ; ++ byCoreID )
{
p_wxmenuCore = new wxMenu;
//Memorize dynamically created menus in order to delete them of a
// CPU controller DLL is attached more than once (else the wxWindows
// are deleted automatically when the superordinate window is closed).
m_vecp_wxmenuCore.push_back(p_wxmenuCore);
p_wxmenuCore->Append(wMenuID, _T("set frequency and voltage ") );
//for(BYTE byDivisorID = 0 ; byDivisorID < FIRST_RESERVED_DIVISOR_ID ;
// ++ byDivisorID )
//{
// Connect( wMenuID ++, wxID_ANY, wxEVT_COMMAND_MENU_SELECTED,
// wxCommandEventHandler(MyFrame::OnRuntimeCreatedMenu)//, & m_vecwxstring.back()
// );
//}
if( byCoreID == 0 )
m_nLowestIDForSetVIDnFIDnDID = wMenuID ;
// wxCPUcoreID wxcpucoreid(byCoreID) ;
// m_stdvectorwxuicontroldata.push_back( //wxCPUcoreID(byCoreID)
// wxcpucoreid
// //wxObject()
// ) ;
m_stdmapwxuicontroldata.insert(
std::make_pair(
wMenuID ,
//TODO release memory
//new wxCPUcoreID(byCoreID)
new SpecificCPUcoreActionAttributes(byCoreID)
//wxcpucoreid
//wxObject()
)
) ;
#ifdef _DEBUG
// wxCPUcoreID * p_wxcpucoreid = (wxCPUcoreID *) //wxevent.m_callbackUserData ;
//&
m_stdmapwxuicontroldata.find( wMenuID )->second ;
//wxCPUcoreID & r_wxcpucoreid = (wxCPUcoreID &) //wxevent.m_callbackUserData ;
// m_stdmapwxuicontroldata.find( wMenuID )->second ;
#endif
// Connect( wMenuID ++, wxID_ANY, wxEVT_COMMAND_MENU_SELECTED,
// wxCommandEventHandler(
// //MainFrame::OnDynamicallyCreatedUIcontrol
// MainFrame::OnVoltageAndFrequencySettingsDialog )//, & m_vecwxstring.back()
// //new wx
// //, & m_stdvectorwxuicontroldata.back()
// );
// LOGN("connected event ID" << wMenuID - 1 << " to" <<
// "MainFrame::OnPstateDialog")
p_wxmenuCore->Append(wMenuID, _T("find different p-states") );
Connect( wMenuID ++, wxID_ANY, wxEVT_COMMAND_MENU_SELECTED,
wxCommandEventHandler(
MainFrame::OnFindDifferentPstates )
);
LOGN("connected event ID" << wMenuID - 1 << " to" <<
"MainFrame::OnFindDifferentPstates")
#ifdef COMPILE_WITH_CALC_THREAD
marp_wxmenuItemHighLoadThread[byCoreID] = AddDynamicallyCreatedMenu(
p_wxmenuCore,
wMenuID, //_T("high load thread (for stability check)")
BuildHighLoadThreadMenuText(
"high FPU load thread (for stability check)"
)
//Connect the action, that is a class derived from class xx directly
//with the menu item so that it is ensured to be the correct action
//(calling the action in an event function is more error-prone)
//TODO release memory
//, new CalculationThread(byCoreID, FPUcalculationThreadProc)
, wxCommandEventHandler( MainFrame::OnHighLoadThread )
, new CalculationThread(
byCoreID
, FPUcalculationThreadProc
, & ::wxGetApp()
, ::wxGetApp().GetCPUcontroller()
)
) ;
//#endif //#ifdef COMPILE_WITH_CALC_THREAD
marp_wxmenuItemHighLoadThread[byCoreID] = AddDynamicallyCreatedMenu(
p_wxmenuCore,wMenuID, //_T("high load thread (for stability check)")
BuildHighLoadThreadMenuText(
std::string( "high ALU load thread (for stability check)" )
)
//Connect the action, that is a class derived from class xx directly
//with the menu item so that it is ensured to be the correct action
//(calling the action in an event function is more error-prone)
//TODO release memory
//, new CalculationThread(byCoreID, HighALUloadThreadProc)
, wxCommandEventHandler( MainFrame::OnHighLoadThread )
, new CalculationThread(
byCoreID
, HighALUloadThreadProc
, & ::wxGetApp()
, ::wxGetApp().GetCPUcontroller()
)
) ;
#endif // #ifdef COMPILE_WITH_CALC_THREAD
//marp_wxmenuItemHighLoadThread[byCoreID] = AddDynamicallyCreatedMenu(
// p_wxmenuCore,
// wMenuID, //_T("high load thread (for stability check)")
// _T("own DVFS")
// //Connect the action, that is a class derived from class xx directly
// //with the menu item so that it is ensured to be the correct action
// //(calling the action in an event function is more error-prone)
// //TODO release memory
// //, new CalculationThread(byCoreID, HighALUloadThreadProc)
// , wxCommandEventHandler( MainFrame::OnOwnDynFreqScaling )
// , new SpecificCPUcoreActionAttributes(byCoreID)
// ) ;
//OnOwnDynFreqScaling
//m_arp_wxmenuitemPstate[byCoreID * NUMBER_OF_PSTATES + 1] =
// AddDynamicallyCreatedMenu(p_wxmenuCore,wMenuID, _T("Set p-state &1")) ;
m_byNumberOfSettablePstatesPerCore = //NUMBER_OF_PSTATES ;
0 ;
if( byCoreID == 0 )
m_byMenuIndexOf1stPstate = wMenuID - m_nLowestIDForSetVIDnFIDnDID ;
//if( typeid (mp_i_cpucontroller ) == typeid(GriffinController) )
//{
// for( byPstateID = 0 ; byPstateID < //3
// m_byNumberOfSettablePstatesPerCore ; ++ byPstateID &&
// //if == TRUE
// byReturnValue
// )
// byReturnValue = AddSetPstateMenuItem(
// p_wxmenuCore, byCoreID, byPstateID, wMenuID ) ;
//}
// if( byReturnValue )
{
if( byCoreID == 0 )
{
m_nNumberOfMenuIDsPerCPUcore = wMenuID - ID_LastStaticEventID ;
//For removing per-core menus after unloading a CPU controller.
m_byIndexOf1stCPUcontrollerRelatedMenu = mp_wxmenubar->GetMenuCount()
;
}
//marp_wxmenuItemHighLoadThread[byCoreID] = AddDynamicallyCreatedMenu(
// p_wxmenuCore,wMenuID, _T("high load thread (for stability check)")) ;
//m_wxmenubar.Append(p_wxmenuCore, _T("for core &")+ byCoreID);
mp_wxmenubar->Append(
p_wxmenuCore,
wxString::Format(
//We need a _T() macro (wide char-> L"", char->"") for EACH
//line to make it compatible between char and wide char.
_T("%s%u")
//, _T("for core &")
, _T("core &")
, //_T('0'+byCoreID)
byCoreID )
);
//marp_wxmenuItemHighLoadThread[byCoreID]->Check(true) ;
//marp_wxmenuItemHighLoadThread[byCoreID]->Enable(false);
}
} //for-loop
}
}
//void
//Return value:
BYTE MainFrame::CreateDynamicMenus()
{
// BYTE byPstateID = 0 ;
BYTE byReturnValue =
//Needs to be TRUE for the 1st loop condition evaluation.
TRUE ;
// WORD wMenuID = ID_LastStaticEventID;
//m_vecwxstring.push_back(wxString)
// wxMenu * p_wxmenuCore ;
LOGN("CPU core menu creation--number of CPU cores: " <<
(WORD) mp_cpucoredata->m_byNumberOfCPUCores )
// byReturnValue =
// CreateDialogAndMenuForEveryCore() ;
Create1DialogAndMenuForAllCores() ;
//SetMenuBar(&m_wxmenubar);
return byReturnValue ;
}
void MainFrame::AllowCPUcontrollerAccess()
{
wxCriticalSectionLocker wxcriticalsectionlocker(
m_wxcriticalsectionCPUctlAccess ) ;
m_bAllowCPUcontrollerAccess = true ;
}
void MainFrame::DenyCPUcontrollerAccess()
{
DEBUGN("MainFrame::DenyCPUcontrollerAccess() begin" )
wxCriticalSectionLocker wxcriticalsectionlocker(
m_wxcriticalsectionCPUctlAccess ) ;
m_bAllowCPUcontrollerAccess = false ;
DEBUGN("MainFrame::DenyCPUcontrollerAccess() end" )
}
void MainFrame::DisableWindowsDynamicFreqScalingHint()
{
wxMessageBox(
//We need a _T() macro (wide char-> L"", char->"") for EACH
//line to make it compatible between char and wide char.
_T("Remember: the OS' dynamic frequency scaling should be ")
_T("deactivated the change to take effect\n")
_T("see help/ disable by: ")
_T("Start->control panel->energy options")
_T("->change the current power plan")
_T("->change extended energy options")
_T("->set minimal and maximal CPU load to the same percentage")
);
}
void MainFrame::OnClose(wxCloseEvent & event )
{
LOGN("begin" /*"Requested to close the main frame"*/)
//Stop the timer (indirectly calls OnPaint()-> so another IPC thread could
//be spawned).
m_wxtimer.Stop() ;
LOGN("Stopped the \"update view\" timer")
// m_p_wxtimer->Stop() ;
mp_wxx86infoandcontrolapp->EndGetCPUcoreDataViaIPCthread() ;
//May be NULL at startup.
if( mp_cpucoredata->m_arp_percpucoreattributes
// CPU cores > 0
&& mp_cpucoredata->m_byNumberOfCPUCores )
{
PerCPUcoreAttributes * p_percpucoreattributes = & mp_cpucoredata->
m_arp_percpucoreattributes[ //p_atts->m_byCoreID
0 ] ;
if ( p_percpucoreattributes->mp_dynfreqscalingthread )
{
p_percpucoreattributes->mp_dynfreqscalingthread->Stop() ;
LOGN("stopped the Dynamic Voltage and Frequency Scaling thread")
//p_percpucoreattributes->mp_dynfreqscalingthread->Delete() ;
p_percpucoreattributes->mp_dynfreqscalingthread = NULL ;
}
}
mp_wxx86infoandcontrolapp->CheckForChangedVoltageForFrequencyConfiguration();
mp_wxx86infoandcontrolapp->DeleteTaskBarIcons();
LOGN("before destroying the mainframe")
//see http://docs.wxwidgets.org/2.8/wx_windowdeletionoverview.html:
this->Destroy() ;
LOGN("after destroying the mainframe")
}
void MainFrame::OnCollectAsDefaultVoltagePerfStates(
wxCommandEvent & WXUNUSED(event) )
{
mp_model->m_bCollectPstatesAsDefault =
mp_wxmenuitemCollectAsDefaultVoltagePerfStates->IsChecked () ;
}
void MainFrame::OnConnectToService( wxCommandEvent & WXUNUSED(event) )
{
wxString wxstrTextFromUser = ::wxGetTextFromUser(
wxT("enter server address") //const wxString & message,
//const wxString & caption = "Input text",
//const wxString & default_value = "",
//wxWindow * parent = NULL,
//int x = wxDefaultCoord,
//int y = wxDefaultCoord,
//bool centre = true
) ;
// std::string strstrMessage ;
mp_wxx86infoandcontrolapp->ConnectIPCclient(
wxstrTextFromUser //,
//strstrMessage
) ;
}
void MainFrame::OnConnectToOrDisconnectFromService(
wxCommandEvent & WXUNUSED(event) )
{
#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE
if( //::wxGetApp().m_ipcclient.IsConnected()
mp_wxx86infoandcontrolapp->IPC_ClientIsConnected()
)
::wxMessageBox(
//Use wxT() to enable to compile with both unicode and ANSI.
wxT("already connected to the service")
) ;
else
{
// if( ::wxGetApp().m_ipcclient.ConnectToDataProvider() )
// p_wxmenuService->SetLabel( ID_ConnectToOrDisconnectFromService ,
// wxT( "disconnect" )
// ) ;
ConnectToDataProvider_Inline() ;
}
#endif
}
void MainFrame::OnContinueService(wxCommandEvent & WXUNUSED(event))
{
LOGN(//"OnContinueService--"
"begin")
//ServiceBase::ContinueService( //mp_model->m_strServiceName.c_str()
// "CPUcontrolService" );
#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE
wxString wxstrMessageFromDataProvider;
if( ! mp_wxx86infoandcontrolapp->
ContinueServiceViaIPC(wxstrMessageFromDataProvider)
)
// ::wxMessageBox( wxT("message from the service:\n") +
// wxstrMessageFromDataProvider ) ;
// else
::wxMessageBox(
//Use wxT() to enable to compile with both unicode and ANSI.
wxT("could not continue because not connected to the service")
) ;
#endif //#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE
}
void MainFrame::OnDisableOtherVoltageOrFrequencyAccess(
wxCommandEvent & WXUNUSED(event) )
{
#ifdef COMPILE_WITH_OTHER_DVFS_ACCESS
::wxGetApp().mp_dynfreqscalingaccess->DisableFrequencyScalingByOS() ;
#endif //#ifdef COMPILE_WITH_OTHER_DVFS_ACCESS
}
void MainFrame::OnDisconnectFromService(
wxCommandEvent & WXUNUSED(event) )
{
#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE
if( //mp_wxx86infoandcontrolapp->m_ipcclient.IsConnected()
mp_wxx86infoandcontrolapp->IPC_ClientIsConnected()
)
//mp_wxx86infoandcontrolapp->m_ipcclient.Disconnect_Inline() ;
mp_wxx86infoandcontrolapp->IPCclientDisconnect() ;
else
{
::wxMessageBox(
//Use wxT() to enable to compile with both unicode and ANSI.
wxT("NOT connected to the service")
) ;
}
#endif
}
void MainFrame::OnEnableOtherVoltageOrFrequencyAccess(
wxCommandEvent & WXUNUSED(event) )
{
#ifdef COMPILE_WITH_OTHER_DVFS_ACCESS
::wxGetApp().mp_dynfreqscalingaccess->EnableFrequencyScalingByOS() ;
#endif //#ifdef COMPILE_WITH_OTHER_DVFS_ACCESS
}
void MainFrame::OnFindDifferentPstates( wxCommandEvent & WXUNUSED(event) )
{
//May be NULL at startup (before a controller DLL becomes attached).
if( mp_i_cpucontroller )
{
//wxString wxstrInput = ::wxGetTextFromUser( wxstrMessage , wxT("input"),
// wxT("1000") ) ;
////::wxGetNumberFromUser
////If the user has input text (and has NOT pressed "cancel")
//if( ! wxstrInput.empty() )
//{
// unsigned long ulMs ;
// bool bSuccess = wxstrInput.ToULong(& ulMs) ;
// if ( bSuccess )
// {
// //ReadMsrEx() returned false results if used with a time and a 10 ms interval.
// if( ulMs < 100 )
// wxMessageBox( wxT("the number is too low. "
// "Getting the current CPU frequency returned wrong values with < 100 ms") ) ;
// else
// {
// m_dwTimerIntervalInMilliseconds = ulMs ;
// m_wxtimer.Stop() ;
// m_wxtimer.Start(ulMs) ;
// }
// }
// else
// {
// wxMessageBox( wxT("You did not enter a valid integer number") ) ;
// }
//}
//Must create dynamically, else the CalculationThread is destroyed after leaving
//this block.
//if( ! mp_calculationthread )
//{
// mp_calculationthread = new CalculationThread(
// 0
// , FindDifferentPstatesThreadProc
// , & ::wxGetApp()
// , ::wxGetApp().GetCPUcontroller()
// ) ;
//}
//if( mp_calculationthread )
// mp_calculationthread->Execute() ;
long lMin = ::wxGetNumberFromUser(
wxT("input mininum frequency:"),
wxT("prompt:"),
wxT("caption:"),
mp_i_cpucontroller->GetMinimumFrequencyInMHz() ,
0 ,
mp_i_cpucontroller->GetMaximumFrequencyInMHz()
) ;
//If the user enters an invalid value or cancels the dialog, the function will return -1.
if( lMin == -1 )
::wxMessageBox(wxT("either invalid value or cancel") ) ;
else
{
long lMax = ::wxGetNumberFromUser(
wxT("input maxinum frequency:"),
wxT("prompt:"),
wxT("caption:"),
mp_i_cpucontroller->GetMaximumFrequencyInMHz() ,
lMin ,
mp_i_cpucontroller->GetMaximumFrequencyInMHz()
) ;
if( lMax == -1 )
::wxMessageBox(wxT("either invalid value or cancel") ) ;
else
{
//TODO use available _mulipliers_ and call GetVoltageAndFrequency(
// voltage, multiplier, refclock, )
//instead of frequencies
// std::set<VoltageAndFreq> stdsetvoltageandfreq ;
// std::set<VoltageAndFreq>::iterator iter ;
// mp_i_cpucontroller->GetAllPossibleFrequencies( stdsetvoltageandfreq ) ;
// //iter = stdsetvoltageandfreq.find(lMin) ;
// iter = stdsetvoltageandfreq.begin() ;
// while( iter != stdsetvoltageandfreq.end() )
// {
// if( lMin >= iter->m_wFreqInMHz )
// break ;
// iter ++ ;
// }
//
//
// //if( iter != stdsetvoltageandfreq.end() )
// {
// float fVolt ;
// WORD wFreq ;
// //for( WORD wFreq = lMin ; wFreq < lMax ; wFreq += 50 )
// while( iter != stdsetvoltageandfreq.end() )
// {
// //mp_i_cpucontroller->GetNearestHigherPossibleFreqInMHz( lMin ) ;
// mp_i_cpucontroller->SetFreqAndVoltageFromFreq( //wFreq,
// iter->m_wFreqInMHz ,
// mp_model->m_cpucoredata.m_stdsetvoltageandfreqDefault
// //mp_model->m_cpucoredata.m_stdsetvoltageandfreqPossibleByCPU
// //stdsetvoltageandfreq
// , 0 ) ;
// ::wxMilliSleep(100) ;
// mp_i_cpucontroller->GetCurrentPstate( //wFreq,
// wFreq ,
// fVolt
// , 0 ) ;
// if( wFreq == iter->m_wFreqInMHz )
// if( mp_model->m_cpucoredata.AddDefaultVoltageForFreq( fVolt, wFreq ) )
// RedrawEverything() ;
// ++ iter ;
// }
// }
}
}
//::wxMilliSleep()
} //if( mp_i_cpucontroller )
}
void MainFrame::OnLoadDetectInstableCPUcoreVoltageDynLib(wxCommandEvent & event)
{
#ifdef _WIN32
mp_wxx86infoandcontrolapp->LoadDetectInstableCPUcoreVoltageDynLib();
#endif
}
void MainFrame::OnUnloadDetectInstableCPUcoreVoltageDynLib(wxCommandEvent & event)
{
#ifdef _WIN32
mp_wxx86infoandcontrolapp->UnloadDetectInstableCPUcoreVoltageDynLib();
#endif
}
void MainFrame::OnMinimizeToSystemTray(wxCommandEvent & WXUNUSED(event))
{
Hide() ;
}
void MainFrame::OnMoveMouse(wxMouseEvent & r_wxmouseevent)
{
LOGN( "begin")
wxPoint wxpoint = r_wxmouseevent.GetPosition();
float fReferenceClockInMHz;
const float fMultiplier = GetClosestMultiplier(wxpoint.x,
fReferenceClockInMHz);
const float fClosestFrequency = fMultiplier * fReferenceClockInMHz;
const float fClosestVoltageToYcoordinate = GetClosestVoltageForYcoordinate(
wxpoint.y);
SetStatusText( wxString::Format( wxT("(%f Volt,%f MHz)"),
fClosestVoltageToYcoordinate, fClosestFrequency ) );
LOGN( "end")
}
void MainFrame::OnLeftMouseButtonDown(wxMouseEvent & r_wxmouseevent)
{
const wxPoint & c_r_wxpointPos = r_wxmouseevent.GetPosition();
if( m_p_freqandvoltagesettingsdialog )
{
float fVoltageInVolt = GetClosestVoltageForYcoordinate(c_r_wxpointPos.y);
float fReferenceClockInMHz;
float fMultiplier = GetClosestMultiplier(c_r_wxpointPos.x,
fReferenceClockInMHz);
m_p_freqandvoltagesettingsdialog->SetMultiplierSliderToClosestValue(
fMultiplier);
m_p_freqandvoltagesettingsdialog->HandleMultiplierValueChanged() ;
BYTE byIndexForClosestVoltage = m_p_freqandvoltagesettingsdialog->
SetVoltageSliderToClosestValue(fVoltageInVolt) ;
m_p_freqandvoltagesettingsdialog->ChangeVoltageSliderValue(
byIndexForClosestVoltage) ;
m_p_freqandvoltagesettingsdialog = NULL;
SetCursor(wxNullCursor);
}
}
void MainFrame::OnPauseService(wxCommandEvent & WXUNUSED(event))
{
LOGN( //"OnPauseService"
"begin")
#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE
wxString wxstrMessageFromService;
mp_wxx86infoandcontrolapp->PauseService(wxstrMessageFromService);
// ::wxMessageBox( wxT("message from the service:\n") + wxstrMessageFromService
// ) ;
#endif //#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE
}
//void MainFrame::OnShowVoltageAndFrequencySettingsDialog(
// wxCommandEvent & WXUNUSED(event) )
//{
//
//}
void MainFrame::OnStartService(wxCommandEvent & WXUNUSED(event))
{
#ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL
mp_wxx86infoandcontrolapp->StartService() ;
#endif //#ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL
}
void MainFrame::OnStopService(wxCommandEvent & WXUNUSED(event))
{
#ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL
//ServiceBase::StopService( //mp_model->m_strServiceName.c_str()
// "CPUcontrolService" );
mp_wxx86infoandcontrolapp->StopService() ;
#endif //#ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL
}
void MainFrame::OnSysTrayIconClick(wxCommandEvent & WXUNUSED(event))
{
::wxMessageBox( wxT("OnSysTrayIconClick") ) ;
}
void MainFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
{
// wxString wxstrMessage ;
// GetAboutMessage(wxstrMessage) ;
// ::wxMessageBox(
// wxstrMessage ,
// _T("About ") //_T(PROGRAM_NAME)
// //+ mp_i_cpucontroller->mp_model->m_stdtstrProgramName
// + mp_model->m_stdtstrProgramName
// ,
// wxOK | wxICON_INFORMATION //,
//// this
// );
AboutDialog * p_aboutdialog = new AboutDialog(
* mp_model, wxWidgets::getwxString( mp_model->m_stdtstrProgramName) ) ;
p_aboutdialog->//Show() ;
ShowModal();
p_aboutdialog->Destroy() ;
}
void MainFrame::OnAttachCPUcontrollerDLL (wxCommandEvent & event)
{
wxString wxstrExtension = wxT("") ;
//Under Windows it returns ".dll"
//wxstrExtension = wxDynamicLibrary::CanonicalizeName(wxstrExtension) ;
wxstrExtension = wxDynamicLibrary::GetDllExt() ;
//Get rid of the leading ".".
wxstrExtension = wxstrExtension.Right( wxstrExtension.length() - 1 ) ;
wxString wxstrCPUcontrollerDynLibFilePath = ::wxFileSelector(
wxT("Select dynamic library for CPU info and/or control")
, wxEmptyString //default_path
, wxEmptyString //default_filename
, wxstrExtension //default_extension
, wxT("Dynamic Library files|*.") + wxstrExtension + wxT("|all files|*.*")//wildcard
, wxFD_OPEN
) ;
if ( ! wxstrCPUcontrollerDynLibFilePath.empty() )
{
try
{
//wxDynLibCPUcontroller * p_wxdynlibcpucontroller = new
//wxDynLibCPUcontroller(
LOGN("before creating dyn lib controller object")
DEBUGN("address of model: " << mp_model )
DEBUGN("address of cpucoredata: " << & mp_model->m_cpucoredata )
//Before creating a new controller the old one should be deleted.
gp_cpucontrolbase->PossiblyDeleteCPUcontrollerDynLib() ;
// gp_cpucontrolbase->mp_wxdynlibcpucontroller = new wxDynLibCPUcontroller(
// wxstrFilePath
// , mp_wxx86infoandcontrolapp->GetCPUaccess()
// , mp_wxx86infoandcontrolapp
// ) ;
// mp_wxx86infoandcontrolapp->CreateDynLibCPUcontroller(
//TODO ANSI string may fail if Chinese localization (->use wchar_t)
std::string stdstrCPUcontrollerDynLibFilePath = wxWidgets::GetStdString(
wxstrCPUcontrollerDynLibFilePath ) ;
wxGetApp().m_wxstrCPUcontrollerDynLibFilePath =
wxstrCPUcontrollerDynLibFilePath ;
if( mp_wxx86infoandcontrolapp->m_dynlibhandler.CreateDynLibCPUcontroller(
stdstrCPUcontrollerDynLibFilePath )
)
{
LOGN("before setting dyn lib controller as CPU controller")
mp_wxx86infoandcontrolapp->SetCPUcontroller( //p_wxdynlibcpucontroller
// gp_cpucontrolbase->mp_wxdynlibcpucontroller
mp_wxx86infoandcontrolapp->m_p_cpucontrollerDynLib
) ;
LOGN("after setting dyn lib controller as CPU controller")
CreateDynamicMenus() ;
LOGN("after creating per CPU core menus " )
CPUcontrollerDynLibAttached(wxstrCPUcontrollerDynLibFilePath) ;
//(Re-)start the "update view" timer.
m_wxtimer.Start(m_dwTimerIntervalInMilliseconds);
}
}
catch( const CPUaccessException & ex )
{
::wxMessageBox( wxT("Error message: ") +
//wxString(
//Use getwxString() to enable to compile with both unicode and ANSI.
wxWidgets::getwxString(
ex.m_stdstrErrorMessage)
// )
, wxT("DLL error")
) ;
}
LOGN(//"OnAttachCPUcontrollerDLL "
"end" )
}
}
void MainFrame::OnAttachCPUcoreUsageGetterDLL (wxCommandEvent & event)
{
wxString wxstrExtension = wxT("") ;
//Under Windows it returns ".dll"
//wxstrExtension = wxDynamicLibrary::CanonicalizeName(wxstrExtension) ;
wxstrExtension = wxDynamicLibrary::GetDllExt() ;
//Get rid of the leading ".".
wxstrExtension = wxstrExtension.Right( wxstrExtension.length() - 1 ) ;
wxString wxstrFilePath = ::wxFileSelector(
wxT("Select CPU core usage getter dynamic library")
, wxEmptyString
, wxEmptyString
, wxstrExtension
, wxT("Dynamic Library files|*.") + wxstrExtension + wxT("|all files|*.*")//wildcard
, wxFD_OPEN
) ;
if ( ! wxstrFilePath.empty() )
{
try
{
gp_cpucontrolbase->PossiblyDeleteCPUcoreUsageGetter() ;
//wxDynLibCPUcontroller * p_wxdynlibcpucontroller = new wxDynLibCPUcontroller(
// gp_cpucontrolbase->mp_wxdynlibcpucoreusagegetter = new
// wxDynLibCPUcoreUsageGetter(
// //std::string(
// wxstrFilePath
// //.//fn_str()
// //c_str() )
// , mp_wxx86infoandcontrolapp->GetCPUaccess()
// , * mp_cpucoredata
// ) ;
// mp_wxx86infoandcontrolapp->CreateDynLibCPUcoreUsageGetter(
std::string stdstr = wxWidgets::GetStdString( wxstrFilePath) ;
if( mp_wxx86infoandcontrolapp->m_dynlibhandler.CreateDynLibCPUcoreUsageGetter(
stdstr )
)
{
mp_wxx86infoandcontrolapp->//SetCPUcoreUsageGetter( //p_wxdynlibcpucontroller
//mp_wxdynlibcpucoreusagegetter ) ;
mp_cpucoreusagegetter =
//gp_cpucontrolbase->mp_wxdynlibcpucoreusagegetter ;
mp_wxx86infoandcontrolapp->m_p_cpucoreusagegetterDynLib ;
//CreateDynamicMenus() ;
CPUcoreUsageGetterAttached(wxstrFilePath) ;
//TODO necessary? (because the CPU core number got from the usage
//getter may change )
RedrawEverything() ;
}
}
catch( CPUaccessException & ex )
{
wxMessageBox( wxT("Error message: ") +
//wxString(
//Use getwxString() to enable to compile with both unicode and ANSI.
wxWidgets::getwxString(
ex.m_stdstrErrorMessage)
, wxT("DLL error")
) ;
}
}
}
void MainFrame::CPUcontrollerDynLibAttached(const wxString & wxstrFilePath )
{
// if( ! mp_ar_voltage_and_multi )
// mp_ar_voltage_and_multi = new VoltageAndMulti[
// mp_model->m_cpucoredata.m_byNumberOfCPUCores ] ;
mp_wxmenuFile->Enable( ID_DetachCPUcontrollerDynamicLibrary
, //const bool enable
true ) ;
mp_wxmenuFile->SetLabel( ID_DetachCPUcontrollerDynamicLibrary ,
wxT( //"detach"
//"unload" is a better word because it expresses that the Dynamic
//library is removed from the memory(?)
"unload"
" CPU controller ") + wxstrFilePath ) ;
mp_wxmenuFile->Enable( ID_SetCPUcontrollerDynLibForThisCPU, true ) ;
//If both CPU controller and the CPU usage getter exist, DVFS is possible.
if( mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter )
m_p_wxmenuGUI->Enable( ID_EnableOrDisableOwnDVFS
, //const bool enable
true ) ;
}
void MainFrame::CPUcontrollerDeleted()
{
mp_i_cpucontroller = NULL;
PossiblyReleaseMemForCPUcontrollerUIcontrols() ;
//mp_model->m_cpucoredata.ClearCPUcontrollerSpecificAtts() ;
mp_wxmenuFile->Enable( ID_DetachCPUcontrollerDynamicLibrary
, //const bool enable
false ) ;
m_p_wxmenuGUI->Enable( ID_EnableOrDisableOwnDVFS
, //const bool enable
false ) ;
}
void MainFrame::CPUcoreUsageGetterAttached(const wxString & wxstrFilePath)
{
mp_wxmenuFile->Enable( ID_DetachCPUusageGetterDynLib
, //const bool enable
true ) ;
mp_wxmenuFile->SetLabel( ID_DetachCPUusageGetterDynLib ,
wxT( //"detach"
//"unload" is a better word because it expresses that the Dynamic
//library is removed from the memory(?)
"unload "
" core usage getter ") + wxstrFilePath ) ;
if( mp_wxx86infoandcontrolapp->GetCPUcontroller() )
m_p_wxmenuGUI->Enable( ID_EnableOrDisableOwnDVFS
, //const bool enable
true ) ;
//TODO do the folowing in base class (CPUcontrolBase)
WORD wNumberOfLogicalCPUcores = mp_wxx86infoandcontrolapp->
mp_cpucoreusagegetter->GetNumberOfLogicalCPUcores() ;
if( wNumberOfLogicalCPUcores == 0 && ! mp_cpucoredata->m_byNumberOfCPUCores )
{
wNumberOfLogicalCPUcores = 1 ;
LOGN("setting # CPU cores to " << wNumberOfLogicalCPUcores)
//TODO correct CPU core number
//Set -> allocate array for OnPaint()
mp_cpucoredata->SetCPUcoreNumber(wNumberOfLogicalCPUcores) ;
}
}
void MainFrame::CPUcoreUsageGetterDeleted()
{
mp_wxmenuFile->Enable( ID_DetachCPUusageGetterDynLib
, //const bool enable
false ) ;
m_p_wxmenuGUI->Enable( ID_EnableOrDisableOwnDVFS
, //const bool enable
false ) ;
}
void MainFrame::OnDetachCPUcontrollerDLL (wxCommandEvent & event)
{
gp_cpucontrolbase->PossiblyDeleteCPUcontrollerDynLib() ;
}
void MainFrame::OnDetachCPUcoreUsageGetterDLL (wxCommandEvent & event)
{
gp_cpucontrolbase->PossiblyDeleteCPUcoreUsageGetter() ;
}
void MainFrame::OnHighLoadThread( wxCommandEvent & //WXUNUSED(wxevent)
wxevent )
{
// WORD wEventID = wxevent.GetId() ;
#ifdef COMPILE_WITH_CALC_THREAD
// HighLoadThreadAttributes p_hlta = (HighLoadThreadAttributes * )
// m_stdmapwxuicontroldata.find( wEventID )->second ;
CalculationThread * p_ct = (CalculationThread *)
m_stdmapwxuicontroldata.find( wEventID )->second ;
if( p_ct )
p_ct->Execute() ;
#endif //#ifdef COMPILE_WITH_CALC_THREAD
}
void MainFrame::OnOwnDynFreqScaling( wxCommandEvent & //WXUNUSED(wxevent)
wxevent )
{
mp_wxx86infoandcontrolapp->StartDynamicVoltageAndFrequencyScaling() ;
}
void MainFrame::Show1VoltnFreqSettingsDialogForEveryCPUcore(wxCommandEvent &
wxevent )
{
WORD wEventID = wxevent.GetId() ;
//wxCPUcoreID * p_wxcpucoreid = (wxCPUcoreID *) //wxevent.m_callbackUserData ;
// & m_stdmapwxuicontroldata.find( wxevent.GetId() )->second ;
//wxCPUcoreID & r_wxcpucoreid = (wxCPUcoreID &) //wxevent.m_callbackUserData ;
// m_stdmapwxuicontroldata.find( wxevent.GetId() )->second ;
//const wxObject & wxobj = //wxevent.m_callbackUserData ;
// m_stdmapwxuicontroldata.find( wxevent.GetId() )->second ;
//wxCPUcoreID & r_wxcpucoreid2 = (wxCPUcoreID &) wxobj ;
//const wxCPUcoreID * p_wxcpucoreid2 = (const wxCPUcoreID *) & wxobj ;
//std::map <WORD, wxObject> :: iterator iter =
// m_stdmapwxuicontroldata.find( wxevent.GetId() ) ;
//wxCPUcoreID wxcpucoreid = (wxCPUcoreID ) iter->second ;
// wxCPUcoreID * p_wxcpucoreid = (wxCPUcoreID *) //wxevent.m_callbackUserData ;
// //&
// m_stdmapwxuicontroldata.find( wEventID )->second ;
SpecificCPUcoreActionAttributes * p = (SpecificCPUcoreActionAttributes *)
m_stdmapwxuicontroldata.find( wEventID )->second ;
BYTE byCoreID = //p_wxcpucoreid->m_byID
p->m_byCoreID ;
//BYTE byCoreID = 0 ;
if( m_arp_freqandvoltagesettingdlg[byCoreID] )
m_arp_freqandvoltagesettingdlg[byCoreID]->Show(true);
else
{
//If created as local vaiable on stack the dialog would disappear
//immediately.
m_arp_freqandvoltagesettingdlg[byCoreID] = new
FreqAndVoltageSettingDlg(
this
, mp_i_cpucontroller
, byCoreID
);
//Allocating succeeded.
if( m_arp_freqandvoltagesettingdlg[byCoreID] )
m_arp_freqandvoltagesettingdlg[byCoreID]->Show(true);
}
}
void MainFrame::OnVoltageAndFrequencySettingsDialog( wxCommandEvent &
//WXUNUSED(event)
wxevent )
{
LOGN(/*"OnVoltageAndFrequencySettingsDialog"*/ "begin" )
//May be NULL at startup.
if( mp_i_cpucontroller )
{
#ifdef ONE_P_STATE_DIALOG_FOR_EVERY_CPU_CORE
Show1VoltnFreqSettingsDialogForEveryCPUcore();
#else
FreqAndVoltageSettingDlg * p_freqandvoltagesettingdlg = new
FreqAndVoltageSettingDlg(
this
, mp_i_cpucontroller
, 0
);
//Allocating succeeded.
if( p_freqandvoltagesettingdlg )
{
#ifdef USE_CRIT_SEC_FOR_FREQ_AND_VOLT_SETTINGS_DLG_CONTAINER
m_crit_secVoltAndFreqDlgs.Enter();
m_stdvec_p_freqandvoltagesettingdlg.push_back(
p_freqandvoltagesettingdlg) ;
m_crit_secVoltAndFreqDlgs.Leave();
#endif //#ifdef USE_CRIT_SEC_FOR_FREQ_AND_VOLT_SETTINGS_DLG_CONTAINER
p_freqandvoltagesettingdlg->Show(true);
LOGN( "after showing the volt n freq dialog")
}
#endif
}
}
void MainFrame::OnQuit(wxCommandEvent& //WXUNUSED(event)
event)
{
Close(TRUE);
}
void MainFrame::DrawAllPossibleOperatingPoints(
wxDC & r_wxdcDrawOn
)
{
//May be NULL at startup.
if( mp_i_cpucontroller )
{
//float fCurrentVoltageInVolt ;
//WORD wXcoordinate ;
//WORD wYcoordinate ;
// WORD wMaxFreqInMHz =
// mp_i_cpucontroller->mp_model->m_cpucoredata.
// m_wMaxFreqInMHz ;
// WORD wCurrentFreqInMHz =
// mp_i_cpucontroller->mp_model->m_cpucoredata.m_wMaxFreqInMHz ;
// BYTE byMinVoltageID = mp_cpucoredata->m_byMinVoltageID ;
// BYTE byMaxVoltageID = mp_cpucoredata->m_byMaxVoltageID ;
//BYTE byCurrentVoltageID ;
//do
//{
// for( byCurrentVoltageID = byMinVoltageID ;
// byCurrentVoltageID <= byMaxVoltageID ; ++ byCurrentVoltageID )
// {
// fCurrentVoltageInVolt = PState::GetVoltageInVolt( byCurrentVoltageID ) ;
// wXcoordinate =
// m_wXcoordOfBeginOfYaxis +
// (float) wCurrentFreqInMHz /
// (float) wMaxFreqInMHz * m_wDiagramWidth ;
// wYcoordinate =
// m_wDiagramHeight - fCurrentVoltageInVolt
// / m_fMaxVoltage * m_wDiagramHeight ;
// r_wxdcDrawOn.DrawLine(
// //wCurrentXcoordinateInDiagram + m_wXcoordOfBeginOfYaxis,
// wXcoordinate
// , wYcoordinate
// , //wCurrentXcoordinateInDiagram + m_wXcoordOfBeginOfYaxis
// wXcoordinate
// //"+ 1" because: http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcdrawline:
// //"Note that the point (x2, y2) is not part of the line and is
// //not drawn by this function (this is consistent with the
// //behaviour of many other toolkits)."
// + 1
// , //(200-fVoltage*100)
// wYcoordinate
// //"+ 1" because: http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcdrawline:
// //"Note that the point (x2, y2) is not part of the line and is
// //not drawn by this function (this is consistent with the
// //behaviour of many other toolkits)."
// + 1
// ) ;
// }
// mp_cpucontroller->GetNearestHigherPossibleFreqInMHz(
// wCurrentFreqInMHz + 1 ) ;
//} while( wCurrentFreqInMHz != mp_cpucoredata->m_wMaxFreqInMHz ) ;
}
}
void MainFrame::DrawPerformanceStatesCrosses(
wxDC & r_wxdc
, const std::set<VoltageAndFreq> & cr_stdsetmaxvoltageforfreq
, const wxColor * cp_wxcolor
)
{
LOGN(//"DrawPerformanceStatesCrosses "
"begin")
const wxPen wxpenCurrent = r_wxdc.GetPen() ;
#ifdef _DEBUG
const wxColor wxcolor = wxpenCurrent.GetColour() ;
int nPenWidth = wxpenCurrent.GetWidth() ;
#endif
std::set<VoltageAndFreq>::const_iterator iter =
cr_stdsetmaxvoltageforfreq.begin() ;
while( iter != cr_stdsetmaxvoltageforfreq.end() )
{
DrawVoltageFreqCross(
r_wxdc
, iter->m_fVoltageInVolt
, iter->m_wFreqInMHz
, cp_wxcolor
) ;
++ iter ;
}
#ifdef _DEBUG
if( nPenWidth == 3 )
nPenWidth = 3 ;
#endif
//Restore the pen.
r_wxdc.SetPen( wxpenCurrent ) ;
}
void MainFrame::DrawDiagramScale(
wxDC & r_wxdc ,
//std::set<MaxVoltageForFreq>::iterator & iterstdsetmaxvoltageforfreq
std::set<VoltageAndFreq>::iterator & r_iterstdsetvoltageandfreq
)
{
LOGN_DEBUG(//"DrawDiagramScale "
"mp_i_cpucontroller:" << mp_i_cpucontroller)
LOGN(//"DrawDiagramScale "
"m_wMaximumCPUcoreFrequency:" <<
m_wMaximumCPUcoreFrequency)
//May be NULL at startup.
if( //mp_i_cpucontroller
m_wMaximumCPUcoreFrequency )
{
// WORD wXcoordinate = 0, wYcoordinate = 0;
//float fMinVoltage ;
//float fMaxMinusMinVoltage ;
std::set<VoltageAndFreq> & r_stdsetvoltageandfreq =
//mp_i_cpucontroller->
mp_model->m_cpucoredata.m_stdsetvoltageandfreqDefault ;
//Prevents a concurrent modification e.g. by
// "mp_model->m_cpucoredata.AddDefaultVoltageForFreq(...)"
// in wxDynLibCPUcontroller::GetCurrentVoltageAndFrequency(...)
wxCriticalSectionLocker wxcriticalsectionlockerVoltageAndFreq(
mp_model->m_cpucoredata.m_wxcriticalsection) ;
// std::set<WORD> setRightEndOfFreqString ;
r_iterstdsetvoltageandfreq = r_stdsetvoltageandfreq.begin() ;
#ifdef _DEBUG
const wxPen & wxpenCurrent = r_wxdc.GetPen() ;
const wxColor wxcolor = wxpenCurrent.GetColour() ;
// int nPenWidth = wxpenCurrent.GetWidth() ;
#endif
LOGN( //"DrawDiagramScale "
"m_wDiagramWidth:" << m_wDiagramWidth )
//fMinVoltage = mp_i_cpucontroller->GetMinimumVoltageInVolt() ;
//fMaxMinusMinVoltage = m_fMaxVoltage - fMinVoltage ;
// for( ; r_iterstdsetvoltageandfreq !=
// //mp_i_cpucontroller->mp_model->
// //m_setmaxvoltageforfreq.end() ; //++ iterstdvecmaxvoltageforfreq
// r_stdsetvoltageandfreq.end() ;
// //++ iterstdsetmaxvoltageforfreq
// ++ r_iterstdsetvoltageandfreq
// )
// {
//// DrawFrequency(
//// r_wxdc,
//// //wFrequencyInMHz
//// r_iterstdsetvoltageandfreq->m_wFreqInMHz ,
//// wxcoordWidth ,
//// wxcoordHeight ,
//// wLeftEndOfCurrFreqText ,
//// wxstrFreq ,
//// wXcoordinate ,
//// wYcoordinate ,
//// r_iterstdmapYcoord2RightEndOfFreqString ,
//// stdmapYcoord2RightEndOfFreqString ,
//// r_iterstdmap_ycoord2rightendoffreqstringToUse
//// ) ;
// wXcoordinate = GetXcoordinateForFrequency( r_iterstdsetvoltageandfreq->
// m_wFreqInMHz) ;
//// wYcoordinate = r_iterstdmap_ycoord2rightendoffreqstringToUse->first ;
// LOGN( "DrawDiagramScale
//x coord:" << wXcoordinate
// << "y coord:" << wYcoordinate )
// //mapRightEndOfFreqString2yCoord.insert(
// // std::pair<WORD,WORD> ( wLeftEndOfCurrFreqText + wxcoordWidth, wYcoordinate ) ) ;
// //Draw vertical line for current frequency mark.
// //p_wxpaintdc->DrawLine(wXcoordinate, 0, wXcoordinate, wDiagramHeight) ;
// //wxmemorydc.DrawLine(wXcoordinate, 0, wXcoordinate, wDiagramHeight) ;
// r_wxdc.DrawLine(wXcoordinate, 0, wXcoordinate, m_wDiagramHeight
// //wYcoordinate
// ) ;
//// DrawVoltage(
//// r_wxdc ,
//// ( * r_iterstdsetvoltageandfreq).m_fVoltageInVolt
//// ) ;
// //Draw horizontal line for current voltage mark.
// //p_wxpaintdc->DrawLine(wXcoordOfBeginOfYaxis, wYcoordinate,
// //wxmemorydc.DrawLine(wXcoordOfBeginOfYaxis, wYcoordinate,
// r_wxdc.DrawLine(m_wXcoordOfBeginOfYaxis, wYcoordinate,
// m_wDiagramWidth + m_wXcoordOfBeginOfYaxis, wYcoordinate ) ;
// }
} //if( m_wMaximumCPUcoreFrequency )
// else //m_wMaximumCPUcoreFrequency = 0
// {
// }
WORD wMaximumYcoordinateForFrequency = 0;
WORD wMaximumHeightForFrequencyMarks = 0;
wxCoord wxcoordTextWidth, wxcoordTextHeight;
r_wxdc.GetTextExtent(
wxT("I")
, & wxcoordTextWidth
, & wxcoordTextHeight
//, wxCoord *descent = NULL, wxCoord *externalLeading = NULL, wxFont *font = NULL
) ;
// int nHalfTextHeightInPixels = wxcoordTextHeight / 2;
if( mp_i_cpucontroller->m_fReferenceClockInMHz )
{
//Do not draw: only calculate the max. (text) height of the frequency
//scale.
DrawFrequencyMarksAndLines(r_wxdc, wMaximumYcoordinateForFrequency);
wMaximumHeightForFrequencyMarks = wMaximumYcoordinateForFrequency -
m_wDiagramHeight
//For the 1st line.
+ wxcoordTextHeight;
}
//->line for min./ lowest voltage/ 0V directly above frequency marks.
m_wDiagramHeight += 50 - wMaximumHeightForFrequencyMarks //-
//nHalfTextHeightInPixels
;
DrawVoltageScale(r_wxdc);
// //The frequency should start under min. voltage.
// m_wDiagramHeight += nHalfTextHeightInPixels;
if( mp_i_cpucontroller->m_fReferenceClockInMHz )
{
//Now do really draw.
DrawFrequencyMarksAndLines(r_wxdc, wMaximumYcoordinateForFrequency);
}
LOGN(//"DrawDiagramScale "
"end")
}
void MainFrame::DrawLowestStableVoltageCurve(
wxDC & wxdc
, float fMaxVoltage
)
{
//May be NULL at startup.
if( mp_i_cpucontroller )
{
std::set<VoltageAndFreq>::const_iterator ciLower =
mp_cpucoredata->m_stdsetvoltageandfreqLowestStable.begin() ;
////because of the "MaxVoltageForFreq::<" operator the set is sorted in
////DESCENDING order.
////Points BEYOND the last element now.
//mp_cpucoredata->m_stdsetvoltageandfreqLowestStable.end() ;
////Now it should point to the last element.
//-- ciLower ;
if( ciLower != mp_cpucoredata->m_stdsetvoltageandfreqLowestStable.end()
)
{
std::set<VoltageAndFreq>::const_iterator ciHigher =
ciLower ;
ciHigher ++ ;
//ciHigher -- ;
if( ciHigher != mp_cpucoredata->m_stdsetvoltageandfreqLowestStable.end()
)
{
float fVoltage ;
WORD wYcoordinate ;
WORD wMaxFreqInMHz =
//mp_i_cpucontroller->mp_model->m_cpucoredata.m_wMaxFreqInMHz ;
m_wMaximumCPUcoreFrequency ;
WORD wCurrentFreqInMHz ;
for( WORD wCurrentXcoordinateInDiagram = //wXcoordOfBeginOfYaxis
//0
//Begin with 1 to avoid div by zero.
1 ;
wCurrentXcoordinateInDiagram < //wxcoordWidth
m_wDiagramWidth ; ++ wCurrentXcoordinateInDiagram
)
{
wCurrentFreqInMHz =
//Explicit cast to avoid (g++) warning.
(WORD)
(
(float) wMaxFreqInMHz /
( (float) m_wDiagramWidth / (float) wCurrentXcoordinateInDiagram )
) ;
if( ciHigher->m_wFreqInMHz < wCurrentFreqInMHz )
{
std::set<VoltageAndFreq>::const_iterator ciBeyondHigher = ciHigher ;
++ ciBeyondHigher ;
if( ciBeyondHigher != mp_cpucoredata->
m_stdsetvoltageandfreqLowestStable.end()
)
{
++ ciLower ;
++ ciHigher ;
//-- ciLower ;
//-- ciHigher ;
}
}
//If current freq is in between.
if( ciHigher != mp_cpucoredata->m_stdsetvoltageandfreqLowestStable.end()
&& ciLower->m_wFreqInMHz <= wCurrentFreqInMHz &&
ciHigher->m_wFreqInMHz >= wCurrentFreqInMHz
)
{
//mp_i_cpucontroller->GetInterpolatedVoltageFromFreq(
// wCurrentFreqInMHz
// , *ciHigher
// , *ciLower
// , fVoltage
// ) ;
//mp_i_cpucontroller->
GetInterpolatedVoltageFromFreq(
wCurrentFreqInMHz
, fVoltage
, mp_cpucoredata->m_stdsetvoltageandfreqLowestStable
) ;
wYcoordinate = GetYcoordinateForVoltage(fVoltage);
//p_wxpaintdc->DrawLine(
wxdc.DrawLine(
wCurrentXcoordinateInDiagram + m_wXcoordOfBeginOfYaxis,
//wDiagramHeight -
//fVoltage/ (*iterstdvecmaxvoltageforfreq).m_fVoltageInVolt
//* wDiagramHeight ,
wYcoordinate ,
wCurrentXcoordinateInDiagram + m_wXcoordOfBeginOfYaxis
//"+ 1" because: http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcdrawline:
//"Note that the point (x2, y2) is not part of the line and is
//not drawn by this function (this is consistent with the
//behaviour of many other toolkits)."
+ 1
, wYcoordinate
//"+ 1" because: http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcdrawline:
//"Note that the point (x2, y2) is not part of the line and is
//not drawn by this function (this is consistent with the
//behaviour of many other toolkits)."
+ 1
) ;
}
}// for
}
}
}
}
void MainFrame::DrawVoltageGraph(
//wxPaintDC * p_wxpaintdc
wxDC & wxdc
// , WORD wDiagramWidth
// , WORD wDiagramHeight
, float fMaxVoltage
// , WORD wXcoordOfBeginOfYaxis
, const std::set<VoltageAndFreq> & c_r_stdsetvoltageandfreq
)
{
LOGN(//"DrawOvervoltageProtectionCurve "
"begin" )
//May be NULL at startup.
if( mp_i_cpucontroller
//and ref clock <> 0
&& mp_i_cpucontroller->m_fReferenceClockInMHz )
{
float fVoltage ;
WORD wYcoordinate ;
// std::set<float> & r_stdset_fMultipliers = mp_model->m_cpucoredata.
// m_stdset_floatAvailableMultipliers ;
// std::set<float>::const_reverse_iterator c_iter_stdset_fMultipliers =
// r_stdset_fMultipliers.rbegin() ;
// if( c_iter_stdset_fMultipliers != r_stdset_fMultipliers.rend() )
// float fMaxMulti = mp_model->m_cpucoredata.GetMaximumMultiplier() ;
// if( fMaxMulti )
{
WORD wMaxFreqInMHz = //mp_i_cpucontroller->
//mp_model->m_cpucoredata.m_wMaxFreqInMHz ;
//max. freq = max. multi * ref clock
//*c_iter_stdset_fMultipliers
//fMaxMulti * mp_i_cpucontroller->m_fReferenceClockInMHz ;
m_wMaximumCPUcoreFrequency ;
for( WORD wCurrentXcoordinateInDiagram = //wXcoordOfBeginOfYaxis
//0
//Begin with 1 to avoid div by zero.
1 ;
wCurrentXcoordinateInDiagram < //wxcoordWidth
m_wDiagramWidth ; ++ wCurrentXcoordinateInDiagram )
{
//mp_i_cpucontroller->
GetInterpolatedVoltageFromFreq(
//Explicit cast to avoid (g++) compiler warning.
(WORD)
(
(float) wMaxFreqInMHz /
( (float) m_wDiagramWidth / (float) wCurrentXcoordinateInDiagram )
)
, fVoltage
, c_r_stdsetvoltageandfreq ) ;
wYcoordinate = GetYcoordinateForVoltage(fVoltage);
//p_wxpaintdc->DrawLine(
//TODO draw lines from last point to current point. So gaps are avoided if
//the angle is > 45 degrees
wxdc.DrawLine(
wCurrentXcoordinateInDiagram + m_wXcoordOfBeginOfYaxis,
//wDiagramHeight -
//fVoltage/ (*iterstdvecmaxvoltageforfreq).m_fVoltageInVolt
//* wDiagramHeight ,
wYcoordinate ,
wCurrentXcoordinateInDiagram + m_wXcoordOfBeginOfYaxis
//"+ 1" because:
//http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcdrawline:
//"Note that the point (x2, y2) is not part of the line and is
//not drawn by this function (this is consistent with the
//behaviour of many other toolkits)."
+ 1
, wYcoordinate
//"+ 1" because:
//http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcdrawline:
//"Note that the point (x2, y2) is not part of the line and is
//not drawn by this function (this is consistent with the
//behaviour of many other toolkits)."
+ 1
) ;
}
}
} //if( mp_i_cpucontroller )
}
//Purpose: the output for _all_ cores should be (left-)aligned.
//So the max. width for the attribute values of the same attribute type
//(MHz,...) needs to be known.
void MainFrame::StoreCurrentVoltageAndFreqInArray(
wxDC & r_wxdc
// VoltageAndFreq * & r_ar_voltageandfreq
, wxString r_ar_wxstrFreqInMHz []
, wxString r_ar_wxstrVoltageInVolt []
// , float r_ar_fTempInCelsius []
, wxString r_ar_wxstrTempInCelsius []
, I_CPUcontroller * p_cpucontroller
)
{
LOGN(//"StoreCurrentVoltageAndFreqInArray"
"begin")
if( //mp_i_cpucontroller
p_cpucontroller )
{
int nWidth ;
PerCPUcoreAttributes * arp_percpucoreattributes = mp_model->m_cpucoredata.
m_arp_percpucoreattributes ;
// WORD wFreqInMHz = 0 ;
wxCoord wxcoordWidth, wxcoordHeight ;
wxString wxstr ;
wxSize wxsize ;
float fVoltageInVolt = 0.0f ;
float fTempInCelsius ;
float fThrottleLevel;
float fMultiplier ;
float fReferenceClockInMHz ;
WORD wFrequencyInMHz ;
// WORD wCoreID ;
//mp_cpucoredata->
//respect # of cpu cores
for( fastestUnsignedDataType CPUcoreID = 0 ; CPUcoreID <
mp_cpucoredata->m_byNumberOfCPUCores ; ++ CPUcoreID )
{
// wFreqInMHz = 0 ;
// fVoltageInVolt = 0.0f ;
// if( mp_i_cpucontroller->GetCurrentPstate(wFreqInMHz, fVoltageInVolt,
// byCPUcoreID )
if( //mp_i_cpucontroller->GetCurrentVoltageAndFrequency(
p_cpucontroller->//GetCurrentVoltageAndFrequency(
//Storing in the array is needed for showing the multis in the task
//bar icon.
GetCurrentVoltageAndFrequencyAndStoreValues(
// fVoltageInVolt
// , fMultiplier
// , fReferenceClockInMHz
//,
CPUcoreID
)
)
{
fVoltageInVolt = arp_percpucoreattributes[CPUcoreID].m_fVoltageInVolt;
fThrottleLevel = arp_percpucoreattributes[CPUcoreID].m_fThrottleLevel;
fMultiplier = arp_percpucoreattributes[CPUcoreID].m_fMultiplier;
fReferenceClockInMHz = arp_percpucoreattributes[CPUcoreID].
m_fReferenceClockInMhz;
wFrequencyInMHz = (WORD) ( fReferenceClockInMHz * fMultiplier ) ;
// arp_percpucoreattributes[CPUcoreID].GetFreqInMHz();
if( wFrequencyInMHz > m_wMaximumCPUcoreFrequency )
m_wMaximumCPUcoreFrequency = wFrequencyInMHz ;
LOGN("fMultiplier:" << fMultiplier )
mp_ar_voltage_and_multi[CPUcoreID ].m_fMultiplier = fMultiplier ;
mp_ar_voltage_and_multi[CPUcoreID ].m_fVoltageInVolt = fVoltageInVolt;
if(fThrottleLevel == -1.0f)
r_ar_wxstrFreqInMHz[ CPUcoreID ] = wxT("?*");
else
r_ar_wxstrFreqInMHz[ CPUcoreID ] = wxString::Format(
wxT("%.3f*"), fThrottleLevel);
{
if( fMultiplier == 0.0f)
r_ar_wxstrFreqInMHz[ CPUcoreID ] += wxString::Format(
wxT("?*%.3fMHz=? MHz "),
fThrottleLevel,
fReferenceClockInMHz);
else if( fReferenceClockInMHz == 0.0f )
r_ar_wxstrFreqInMHz[ CPUcoreID ] += wxString::Format(
wxT("%.3f*?MHz=? MHz "),
fThrottleLevel,
fMultiplier);
else
{
if(fThrottleLevel == -1.0f)
r_ar_wxstrFreqInMHz[ CPUcoreID ] += wxString::Format(
//Use wxT() to enable to compile with both unicode and ANSI.
// wxT("%u MHz "),
// wFreqInMHz ) ;
wxT("%.3f*%.3fMHz=%.3f?MHz "),
// wxT("%.3g*%.3gMHz=%.3gMHz "),
// fThrottleLevel,
fMultiplier ,
fReferenceClockInMHz ,
fMultiplier * fReferenceClockInMHz
) ;
else
r_ar_wxstrFreqInMHz[ CPUcoreID ] += wxString::Format(
//Use wxT() to enable to compile with both unicode and ANSI.
// wxT("%u MHz "),
// wFreqInMHz ) ;
wxT("%.3f*%.3fMHz=%.3fMHz "),
// wxT("%.3g*%.3gMHz=%.3gMHz "),
// fThrottleLevel,
fMultiplier ,
fReferenceClockInMHz ,
fThrottleLevel * fMultiplier * fReferenceClockInMHz
) ;
}
}
LOGN( "frequency string:\"" << wxWidgets::GetStdString(
r_ar_wxstrFreqInMHz[ CPUcoreID ]) << "\"")
// LOGN("r_ar_wxstrFreqInMHz[ CPUcoreID ]:" << GetStdString(
// r_ar_wxstrFreqInMHz[ CPUcoreID ]) )
// wxstr = wxString::Format( wxT("%u"), wFreqInMHz ) ;
// wxsize = r_wxdc.GetTextExtent(//wxstr
// r_ar_wxstrFreqInMHz[ CPUcoreID ] ) ;
// nWidth = wxsize.GetWidth() ;
r_wxdc.GetTextExtent( r_ar_wxstrFreqInMHz[ CPUcoreID ] ,
& wxcoordWidth, & wxcoordHeight ) ;
nWidth = wxcoordWidth ;
//The max freq text widthcan not easyily be determined at startup:
//if e.g. the documented max. multiplier is "10" and the reference
//clock is 100MHz, then the freq can also get > 1000 MHz because the
//reference clock can be a bittle higher frequented or increased via
// BIOS etc.
//So it's best to determine it at runtime.
if( nWidth > m_wMaxFreqInMHzTextWidth )
m_wMaxFreqInMHzTextWidth = nWidth ;
if( fVoltageInVolt == 0.0 )
r_ar_wxstrVoltageInVolt[ CPUcoreID ] = wxT("?V ") ;
else
r_ar_wxstrVoltageInVolt[ CPUcoreID ] = wxString::Format(
//Use wxT() to enable to compile with both unicode and ANSI.
wxT("%.4f"
//"%.3g"
"V "), fVoltageInVolt ) ;
wxsize = r_wxdc.GetTextExtent(//wxstr
r_ar_wxstrVoltageInVolt[ CPUcoreID ] ) ;
nWidth = wxsize.GetWidth() ;
if( nWidth > m_wMaxVoltageInVoltTextWidth )
m_wMaxVoltageInVoltTextWidth = nWidth ;
// r_ar_voltageandfreq[byCPUcoreID].m_fVoltageInVolt = fVoltageInVolt ;
// r_ar_voltageandfreq[byCPUcoreID].m_wFreqInMHz = wFreqInMHz ;
}
else
{
LOGN_ERROR("error getting the current CPU core voltage and frequency "
"CPU controller via the CPU controller->not using their results" )
}
fTempInCelsius = //mp_i_cpucontroller->
p_cpucontroller->
GetTemperatureInCelsius(CPUcoreID) ;
s_arfTemperatureInDegreesCelsius[ CPUcoreID ] = fTempInCelsius ;
// switch(fTempInCelsius)
// {
// case __FLT_MIN__ :
// r_ar_wxstrTempInCelsius[ CPUcoreID ] = wxT("?°C ");
// break;
// case CPU_TEMP_IS_CRITICAL:
// r_ar_wxstrTempInCelsius[ CPUcoreID ] = wxT("<C ");
// break;
// case CPU_TEMP_IS_BELOW_CRITICAL:
// r_ar_wxstrTempInCelsius[ CPUcoreID ] = wxT(">C ");
// break;
// default:
// //http://www.cplusplus.com/reference/clibrary/cstdio/printf/:
// //"Use the shorter of %e or %f"
// //-> if "%.3g" (max 3 digits after decimal point):
// // for "60.0" it is "60"
// // for "60.1755" it is "60.175"
// r_ar_wxstrTempInCelsius[ CPUcoreID ] = wxString::Format(
// //Use wxT() to enable to compile with both unicode and ANSI.
// wxT("%.3g°C "),
// fTempInCelsius ) ;
// }
wxGetApp().GetTemperatureString(fTempInCelsius,
r_ar_wxstrTempInCelsius[ CPUcoreID ]);
r_ar_wxstrTempInCelsius[ CPUcoreID ] += wxT(" ");
// LOGN("r_ar_wxstrTempInCelsius[ CPUcoreID ]:" << GetStdString(
// r_ar_wxstrTempInCelsius[ CPUcoreID ]) )
wxsize = r_wxdc.GetTextExtent(//wxstr
r_ar_wxstrTempInCelsius[ CPUcoreID ] ) ;
nWidth = wxsize.GetWidth() ;
if( nWidth > m_wMaxTemperatureTextWidth )
m_wMaxTemperatureTextWidth = nWidth ;
}
}
LOGN( "end")
}
void MainFrame::DrawCPUcoreIDs(
wxDC & r_wxdc,
wxCoord & wxcoordX, //must be call by reference
wxCoord wxcoordTextHeight
)
{
LOGN("before drawing the CPU core numbers")
static wxString wxstr;
int nWidth ;
wxSize wxsize ;
WORD wMaxCoreNumberTextWidth = 0 ;
for ( WORD wCoreID = 0 ; wCoreID < mp_cpucoredata->m_byNumberOfCPUCores ;
++ wCoreID )
{
wxstr = wxString::Format(
//We need a _T() macro (wide char-> L"", char->"") for EACH
//line to make it compatible between char and wide char.
wxT("core%u:")
, wCoreID
) ;
wxsize = r_wxdc.GetTextExtent( wxstr ) ;
nWidth = wxsize.GetWidth() ;
if( nWidth > wMaxCoreNumberTextWidth )
wMaxCoreNumberTextWidth = nWidth ;
r_wxdc.DrawText(
wxstr
, wxcoordX //x-coord
, wCoreID * //m_wTextHeight //y-coord
wxcoordTextHeight
) ;
}
wxcoordX += wMaxCoreNumberTextWidth ;
}
void MainFrame::DrawCurrentCPUcoreFrequency(
wxDC & r_wxdc,
const wxString ar_wxstrFreqInMHz [],
wxCoord & wxcoordX,
wxCoord wxcoordTextHeight
)
{
LOGN("before drawing the CPU core frequency")
for ( fastestUnsignedDataType wCoreID = 0 ; wCoreID <
mp_cpucoredata->m_byNumberOfCPUCores ; ++ wCoreID )
{
#ifdef _DEBUG
const wxString & r_wxstr = ar_wxstrFreqInMHz[ wCoreID ] ;
//Avoid g++ warning "unused variable ‘r_wxstr’"
SUPPRESS_UNUSED_VARIABLE_WARNING(r_wxstr)
#endif
r_wxdc.DrawText(
ar_wxstrFreqInMHz[ wCoreID ]
, wxcoordX //x-coord
, wCoreID * //m_wTextHeight //y-coord
wxcoordTextHeight
) ;
}
wxcoordX += m_wMaxFreqInMHzTextWidth ;
}
void MainFrame::DrawCurrentCPUcoreTemperature(
wxDC & r_wxdc,
const wxString ar_wxstrCPUcoreTemperature [],
wxCoord & wxcoordX,
wxCoord wxcoordTextHeight
)
{
for ( WORD wCoreID = 0 ; wCoreID < mp_cpucoredata->m_byNumberOfCPUCores ;
++ wCoreID )
{
r_wxdc.DrawText(
ar_wxstrCPUcoreTemperature[ wCoreID ]
, wxcoordX //x-coord
, wCoreID * //m_wTextHeight //y-coord
wxcoordTextHeight
) ;
}
wxcoordX += m_wMaxTemperatureTextWidth ;
}
void MainFrame::DrawCPUcoreVoltage(
wxDC & r_wxdc,
const wxString ar_wxstrCPUcoreVoltageInVolt [],
wxCoord & wxcoordX,
wxCoord wxcoordTextHeight
)
{
LOGN("before drawing the CPU core voltage")
for ( WORD wCoreID = 0 ; wCoreID < mp_cpucoredata->m_byNumberOfCPUCores ;
++ wCoreID )
{
r_wxdc.DrawText(
ar_wxstrCPUcoreVoltageInVolt[ wCoreID ]
, wxcoordX //x-coord
, wCoreID * //m_wTextHeight //y-coord
wxcoordTextHeight
) ;
}
wxcoordX += m_wMaxVoltageInVoltTextWidth ;
}
void MainFrame::DrawCPUcoreUsages(
wxDC & r_wxdc,
const ICPUcoreUsageGetter * p_cpucoreusagegetter,
wxCoord wxcoordX,
wxCoord wxcoordTextHeight
)
{
//mp_i_cpucontroller->
if( //mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter
p_cpucoreusagegetter )
{
float fCPUload ;
wxSize wxsize ;
fCPUload = -1.0 ;
static wxString wxstr;
for ( WORD wCoreID = 0 ; wCoreID < mp_cpucoredata->m_byNumberOfCPUCores ;
++ wCoreID )
{
fCPUload = mp_cpucoredata->m_arfCPUcoreLoadInPercent[ wCoreID ] ;
wxstr = wxString::Format(
//#ifdef _WINDOWS
#ifdef _MSC_VER //If MicroSoft compiler.
_T("%.3f percent usage")
#else
//when compiled with MSVC and running under WinXP the executable
//crashes with this format string (surely because of the 1st "%")
//http://www.cplusplus.com/reference/clibrary/cstdio/printf/:
//" A % followed by another % character will write % to stdout."
wxT("%.3f%% usage")
#endif
, fCPUload * 100.0f
) ;
r_wxdc.DrawText(
wxstr
, wxcoordX //x-coord
, wCoreID * //m_wTextHeight //y-coord
wxcoordTextHeight
) ;
}
}
}
/**
* Draws current CPU core data onto a wxDC:
* -core ID
* -frequency
* -voltage
* -temperature
* -usage
*/
void MainFrame::DrawCurrentCPUcoreInfo(
wxDC & r_wxdc
)
{
LOGN(//"DrawCurrentCPUcoreData"
"begin")
// wxString wxstrCPUcoreUsage ;
wxString wxstrCPUcoreVoltage ;
wxString wxstrTemperature ;
wxString wxstrFreqInMHz ;
ICPUcoreUsageGetter * p_cpucoreusagegetter ;
I_CPUcontroller * p_cpucontroller ;
if( GetCPUcoreInfoDirectlyOrFromService(
p_cpucoreusagegetter,
p_cpucontroller //,
// wxstrCPUcoreUsage
, true
)
)
{
// DEBUGN("DrawCurrentCPUcoreInfo--Number of CPU cores:" <<
// (WORD) mp_cpucoredata->m_byNumberOfCPUCores )
//TODO do not create arrays every time this func is called
wxString ar_wxstrCPUcoreVoltage [ mp_cpucoredata->m_byNumberOfCPUCores] ;
wxString ar_wxstrCPUcoreTemperature [ mp_cpucoredata->m_byNumberOfCPUCores] ;
wxString ar_wxstrCPUcoreFreqInMHz [ mp_cpucoredata->m_byNumberOfCPUCores] ;
const wxFont & wxfont = r_wxdc.GetFont();
// int nFontPointSize = wxfont.GetPointSize();
if( mp_model->m_userinterfaceattributes.mainframe.
m_nCurrentCPUcoreInfoSizeInPoint)
{
//TODO make font a member var and move font creation to the c'to
wxFont wxfont2(wxfont);
wxfont2.SetPointSize(mp_model->m_userinterfaceattributes.mainframe.
m_nCurrentCPUcoreInfoSizeInPoint);
r_wxdc.SetFont(wxfont2);
}
//if( m_wxfontCPUcoreInfo.GetPointSize() )
if( //mp_i_cpucontroller
p_cpucontroller )
{
// VoltageAndFreq ar_voltageandfreq[mp_cpucoredata->m_byNumberOfCPUCores] ;
// float ar_fTempInDegCelsius [ mp_cpucoredata->m_byNumberOfCPUCores] ;
LOGN(//"DrawCurrentCPUcoreData "
"before StoreCurrentVoltageAndFreqInArray" )
StoreCurrentVoltageAndFreqInArray(
// ar_voltageandfreq,
// ar_fTempInDegCelsius
r_wxdc
, ar_wxstrCPUcoreFreqInMHz
, ar_wxstrCPUcoreVoltage
, ar_wxstrCPUcoreTemperature
, p_cpucontroller
) ;
// float fHighestTemperature = GetHighestTemperature(
// s_arfTemperatureInDegreesCelsius) ;
#ifdef _WIN32
//TODO use correct icon size for (both Windows and) Linux.
ShowHighestCPUcoreTemperatureInTaskBar(p_cpucontroller) ;
ShowCPUcoreUsagesInTaskBar(p_cpucontroller);
ShowCPUcoresMultipliersInTaskBar(p_cpucontroller);
#endif
LOGN(//"DrawCurrentCPUcoreData "
"after StoreCurrentVoltageAndFreqInArray" )
}
else
{
for ( WORD wCoreID = 0 ; wCoreID < mp_cpucoredata->m_byNumberOfCPUCores ;
++ wCoreID )
{
ar_wxstrCPUcoreVoltage [ wCoreID ] = wxT("?");
ar_wxstrCPUcoreTemperature [ wCoreID ] = wxT("?");
ar_wxstrCPUcoreFreqInMHz [ wCoreID ] = wxT("?");
}
}
LOGN(//"DrawCurrentCPUcoreData "
"leaving IPC 2 in-program data crit sec")
mp_cpucoredata->wxconditionIPC2InProgramData.Leave() ;
LOGN(//"DrawCurrentCPUcoreData "
"after leaving IPC 2 in-program data crit sec")
//#ifdef _DEBUG
// if ( fCPUload == 0.0 )
// {
//// //Breakpoint possibility
//// int i = 0 ;
// }
//#endif
//wxmemorydc
wxString wxstr ;
wxCoord wxcoordX ;
wxcoordX = //45 ;
m_uiRightmostEndOfVoltageString;
wxCoord wxcoordTextWidth, wxcoordTextHeight;
r_wxdc.GetTextExtent(
wxT("I")
, & wxcoordTextWidth
, & wxcoordTextHeight
//, wxCoord *descent = NULL, wxCoord *externalLeading = NULL, wxFont *font = NULL
) ;
DrawCPUcoreIDs(r_wxdc, wxcoordX, wxcoordTextHeight);
if( //mp_i_cpucontroller
p_cpucontroller )
{
DrawCPUcoreVoltage(r_wxdc, ar_wxstrCPUcoreVoltage, wxcoordX,
wxcoordTextHeight);
DrawCurrentCPUcoreFrequency(r_wxdc, ar_wxstrCPUcoreFreqInMHz, wxcoordX,
wxcoordTextHeight);
DrawCurrentCPUcoreTemperature(r_wxdc, ar_wxstrCPUcoreTemperature,
wxcoordX, wxcoordTextHeight);
}
DrawCPUcoreUsages(r_wxdc, p_cpucoreusagegetter, wxcoordX,
wxcoordTextHeight);
// } //for-loop
if( mp_model->m_userinterfaceattributes.mainframe.m_nCurrentCPUcoreInfoSizeInPoint)
{
// wxfont.SetPointSize(nFontPointSize);
r_wxdc.SetFont(wxfont);
}
}
else
{
LOGN(//"DrawCurrentCPUcoreData "
"before leaving IPC 2 in-program data crit sec")
mp_cpucoredata->wxconditionIPC2InProgramData.Leave() ;
LOGN(//"DrawCurrentCPUcoreData "
"After leaving IPC 2 in-program data crit sec")
}
LOGN(//"DrawCurrentCPUcoreData "
"end")
}
void MainFrame::DrawCurrentVoltageSettingsCurve(
wxDC & wxdc
, float fMaxVoltage
)
{
//May be NULL at startup.
if( mp_i_cpucontroller )
{
float fVoltage ;
WORD wYcoordinate ;
WORD wMaxFreqInMHz = //mp_i_cpucontroller->
//mp_model->m_cpucoredata.m_wMaxFreqInMHz ;
m_wMaximumCPUcoreFrequency ;
if( //If max. freq is assigned
wMaxFreqInMHz != 0 )
for( WORD wCurrentXcoordinateInDiagram = //wXcoordOfBeginOfYaxis
//0
//Begin with 1 to avoid div by zero.
1 ;
wCurrentXcoordinateInDiagram < //wxcoordWidth
m_wDiagramWidth ; ++ wCurrentXcoordinateInDiagram )
{
//mp_i_cpucontroller->GetMinFreqToPreventOvervoltage( iter ) ;
if( //mp_i_cpucontroller->
GetInterpolatedVoltageFromFreq(
//Explicit cast to avoid (g++) compiler warning.
(WORD)
(
(float) wMaxFreqInMHz /
( (float) m_wDiagramWidth / (float) wCurrentXcoordinateInDiagram )
)
, fVoltage
, mp_cpucoredata->m_stdsetvoltageandfreqWanted )
)
{
wYcoordinate = GetYcoordinateForVoltage(fVoltage);
//p_wxpaintdc->DrawLine(
wxdc.DrawLine(
wCurrentXcoordinateInDiagram + m_wXcoordOfBeginOfYaxis,
//wDiagramHeight -
//fVoltage/ (*iterstdvecmaxvoltageforfreq).m_fVoltageInVolt
//* wDiagramHeight ,
wYcoordinate ,
wCurrentXcoordinateInDiagram + m_wXcoordOfBeginOfYaxis
//"+ 1" because: http://docs.wxwidgets.org/stable/wx_wxdc.html
// #wxdcdrawline:
//"Note that the point (x2, y2) is not part of the line and is
//not drawn by this function (this is consistent with the
//behaviour of many other toolkits)."
+ 1
, wYcoordinate
//"+ 1" because: http://docs.wxwidgets.org/stable/wx_wxdc.html
// #wxdcdrawline:
//"Note that the point (x2, y2) is not part of the line and is
//not drawn by this function (this is consistent with the
//behaviour of many other toolkits)."
+ 1
) ;
}
}//for-loop
} // if( mp_i_cpucontroller )
}
void MainFrame::DrawFrequency(
wxDC & r_wxdc ,
WORD wFrequencyInMHz ,
// WORD wMaxFreqInMHz ,
wxCoord wxcoordWidth ,
wxCoord wxcoordHeight ,
WORD wLeftEndOfCurrFreqText ,
wxString wxstrFreq ,
WORD & wXcoordinate ,
WORD & wYcoordinate ,
// stdmapYcoord2RightEndOfFreqString
// std::set<WORD> & setRightEndOfFreqString
// std::map<WORD,WORD> & mapRightEndOfFreqString2yCoord ,
// std::map<WORD,WORD>::const_reverse_iterator
// r_iterstdmapRightEndOfFreqString2yCoord ,
std::map<WORD,WORD>::iterator & r_iterstdmapYcoord2RightEndOfFreqString ,
std::map<WORD,WORD> & stdmapYcoord2RightEndOfFreqString ,
std::map<WORD,WORD>::iterator & r_iterstdmap_ycoord2rightendoffreqstringToUse
, bool bCalculateMaxTextHeight
)
{
wXcoordinate = GetXcoordinateForFrequency(wFrequencyInMHz) ;
//Draw frequency mark.
//p_wxpaintdc->DrawText(
//wxmemorydc.DrawText(
wxstrFreq = wxString::Format(
//We need a _T() macro (wide char-> L"", char->"") for EACH
//line to make it compatible between char and wide char.
wxT("%u") ,
// (*r_iterstdsetvoltageandfreq).m_wFreqInMHz
wFrequencyInMHz
) ;
r_wxdc.GetTextExtent(
wxstrFreq
, & wxcoordWidth
, & wxcoordHeight
//, wxCoord *descent = NULL, wxCoord *externalLeading = NULL, wxFont *font = NULL
) ;
wLeftEndOfCurrFreqText = wXcoordinate
//Position the line at the horizontal middle of the text.
- ( wxcoordWidth / 2 ) ;
//If the iterator is not set::end() then there is at least 1 strings that would
//overlap with the current string if all were drawn with the same y coordinate.
//iterstdsetword = setRightEndOfFreqString.
// //Finds the first element whose key greater than k.
// upper_bound(wLeftEndOfCurrFreqText) ;
//r_iterstdmapRightEndOfFreqString2yCoord =
// mapRightEndOfFreqString2yCoord.rbegin() ;
//while( r_iterstdmapRightEndOfFreqString2yCoord !=
// mapRightEndOfFreqString2yCoord.rend()
// )
//{
// //If space between the right end is of a prev string and the left end
// //of this string.
// if( r_iterstdmapRightEndOfFreqString2yCoord->first <
// wLeftEndOfCurrFreqText )
// break ;
// ++ r_iterstdmapRightEndOfFreqString2yCoord ;
//}
////Avoid overlapping of frequency strings.
////if( wLeftEndOfCurrFreqText < wRightEndOfPrevFreqText )
//// wYcoordinate = m_wDiagramHeight + wxcoordHeight ;
//if( r_iterstdmapRightEndOfFreqString2yCoord !=
// mapRightEndOfFreqString2yCoord.rend()
// )
// wYcoordinate = r_iterstdmapRightEndOfFreqString2yCoord->second ;
//else
// if( mapRightEndOfFreqString2yCoord.empty() )
// wYcoordinate = m_wDiagramHeight ;
// else // no right text end that is left from the current text to draw.
// {
// //wYcoordinate = m_wDiagramHeight + wxcoordHeight ;
// //e.g.: 500
// // 600
// // 650
// //Draw 1 line below the previous freq text.
// wYcoordinate = mapRightEndOfFreqString2yCoord.rbegin()->second +
// wxcoordHeight ;
// }
r_iterstdmapYcoord2RightEndOfFreqString =
stdmapYcoord2RightEndOfFreqString.begin() ;
r_iterstdmap_ycoord2rightendoffreqstringToUse =
stdmapYcoord2RightEndOfFreqString.end() ;
while( r_iterstdmapYcoord2RightEndOfFreqString !=
stdmapYcoord2RightEndOfFreqString.end()
)
{
//If space between the right end is of a prev string and the left end
//of this string.
//The first entry is the topmost. This is also the entry
if( r_iterstdmapYcoord2RightEndOfFreqString->second <
wLeftEndOfCurrFreqText )
{
r_iterstdmap_ycoord2rightendoffreqstringToUse =
r_iterstdmapYcoord2RightEndOfFreqString ;
break ;
}
++ r_iterstdmapYcoord2RightEndOfFreqString ;
}
if( r_iterstdmap_ycoord2rightendoffreqstringToUse !=
stdmapYcoord2RightEndOfFreqString.end()
)
{
//Update the new right end of string to draw.
r_iterstdmap_ycoord2rightendoffreqstringToUse->second =
wLeftEndOfCurrFreqText + wxcoordWidth ;
wYcoordinate = r_iterstdmap_ycoord2rightendoffreqstringToUse->first ;
}
else
{
if( stdmapYcoord2RightEndOfFreqString.empty() )
wYcoordinate = m_wDiagramHeight ;
else // no right text end that is left from the current text to draw.
{
//wYcoordinate = m_wDiagramHeight + wxcoordHeight ;
//e.g.: 500
// 600
// 650
//Draw 1 line below the previous freq text.
wYcoordinate = stdmapYcoord2RightEndOfFreqString.rbegin()->first +
wxcoordHeight ;
}
stdmapYcoord2RightEndOfFreqString.insert(
std::pair<WORD,WORD> ( wYcoordinate , wLeftEndOfCurrFreqText + wxcoordWidth ) ) ;
}
LOGN(//"DrawDiagramScale "
"drawing " << wxWidgets::GetStdString( wxstrFreq )
<< " at " << wLeftEndOfCurrFreqText << ","
<< wYcoordinate )
if( ! bCalculateMaxTextHeight)
r_wxdc.DrawText(
wxstrFreq
,
//wXcoordOfBeginOfYaxis +
//(float) wMaxFreqInMHz * wDiagramWidth
wLeftEndOfCurrFreqText
, //m_wDiagramHeight
wYcoordinate
) ;
}
void MainFrame::DrawFrequencyMarksAndLines(wxDC & r_wxdc,
//0=calculate max height
WORD & wMaximumYcoordinateForFrequency)
{
LOGN_DEBUG( "begin")
WORD wInitialMaximumYcoordinateForFrequency = wMaximumYcoordinateForFrequency;
wMaximumYcoordinateForFrequency = 0;
//Initialize to avoid g++ warnings like
//"'wLeftEndOfCurrFreqText' might be used uninitialized in this function"
wxCoord wxcoordWidth = 0 ;
wxCoord wxcoordHeight = 0 ;
wxString wxstrFreq ;
fastestUnsignedDataType wLeftEndOfCurrFreqText = 0 ;
WORD wXcoordinate ;
//Initialize to avoid g++ warning
//"'wYcoordinate' may be used uninitialized in this function"
WORD wYcoordinate = 0;
std::map<WORD,WORD>::iterator
r_iterstdmapYcoord2RightEndOfFreqString ;
std::map<WORD,WORD> stdmapYcoord2RightEndOfFreqString ;
std::map<WORD,WORD>::iterator
r_iterstdmap_ycoord2rightendoffreqstringToUse ;
float fReferenceClockInMHz = mp_i_cpucontroller->m_fReferenceClockInMHz ;
WORD wFrequencyInMHz ;
wxPen penLine( * wxLIGHT_GREY, 1); // pen of width 1
const wxPen & c_r_penCurrent = r_wxdc.GetPen();
const wxFont & wxfont = r_wxdc.GetFont();
// int nFontPointSize = wxfont.GetPointSize();
if( mp_model->m_userinterfaceattributes.mainframe.
m_nCPUcoreFrequencyScaleSizeInPoint)
{ //TODO possibly create font in c'tor and not for every call to this function
wxFont wxfont2(wxfont);
wxfont2.SetPointSize(mp_model->m_userinterfaceattributes.mainframe.
m_nCPUcoreFrequencyScaleSizeInPoint);
r_wxdc.SetFont(wxfont2);
}
// wxCoord wxcoordTextWidth, wxcoordTextHeight;
// r_wxdc.GetTextExtent(
// wxT("I")
// , & wxcoordTextWidth
// , & wxcoordTextHeight
// //, wxCoord *descent = NULL, wxCoord *externalLeading = NULL, wxFont *font = NULL
// ) ;
const fastestSignedDataType numMultipliers = mp_cpucoredata->
m_stdset_floatAvailableMultipliers.size();
for( fastestUnsignedDataType multiplierArrayIndex = 0 ;
multiplierArrayIndex < numMultipliers ; ++ multiplierArrayIndex )
{
wFrequencyInMHz =
//Avoid g++ warning "converting to `WORD' from `float'" .
(WORD)
( mp_cpucoredata->m_arfAvailableMultipliers[
multiplierArrayIndex ] * fReferenceClockInMHz ) ;
LOGN("should draw frequency "
<< wFrequencyInMHz
<< " for frequency scale")
DrawFrequency(
r_wxdc,
wFrequencyInMHz ,
wxcoordWidth ,
wxcoordHeight ,
wLeftEndOfCurrFreqText ,
wxstrFreq ,
wXcoordinate ,
wYcoordinate ,
r_iterstdmapYcoord2RightEndOfFreqString ,
stdmapYcoord2RightEndOfFreqString ,
r_iterstdmap_ycoord2rightendoffreqstringToUse,
! wInitialMaximumYcoordinateForFrequency
) ;
if( wYcoordinate >
wMaximumYcoordinateForFrequency )
wMaximumYcoordinateForFrequency = wYcoordinate;
if( wInitialMaximumYcoordinateForFrequency > 0)
{
r_wxdc.SetPen(penLine);
r_wxdc.DrawLine( wXcoordinate, 0, wXcoordinate, wYcoordinate);
r_wxdc.SetPen(c_r_penCurrent);
}
}
if( mp_model->m_userinterfaceattributes.mainframe.
m_nCPUcoreFrequencyScaleSizeInPoint)
{
// wxfont.SetPointSize(nFontPointSize);
r_wxdc.SetFont(wxfont);
}
}
void MainFrame::DrawVoltage(wxDC & r_wxdc , float fVoltageInVolt)
{
// WORD wYcoordinate ;
if( m_bRangeBeginningFromMinVoltage )
m_wYcoordinate =
//Explicit cast to avoid (g++) warning.
(WORD)
(
m_wDiagramHeight -
( fVoltageInVolt - m_fMinVoltage )
/ m_fMaxMinusMinVoltage * m_wDiagramHeight
) ;
else
m_wYcoordinate =
//Explicit cast to avoid (g++) warning.
(WORD)
(
m_wDiagramHeight -
//(*iterstdsetmaxvoltageforfreq).m_fVoltageInVolt
fVoltageInVolt
/ m_fMaxVoltage * m_wDiagramHeight
+ m_wMinYcoordInDiagram
) ;
//Draw voltage mark.
//p_wxpaintdc->DrawText(
//wxmemorydc.DrawText(
r_wxdc.DrawText(
wxString::Format(
//We need a _T() macro (wide char-> L"", char->"") for EACH
//line to make it compatible between char and wide char.
_T("%.3f") ,
fVoltageInVolt
),
5
,
//wDiagramHeight -
/// fMaxVoltage * wDiagramHeight
m_wYcoordinate
) ;
}
unsigned MainFrame::GetYcoordinateForVoltage(float fVoltageInVolt//,
// unsigned uiHalfTextHeightInPixels
)
{
WORD wYcoordinate ;
if( m_bRangeBeginningFromMinVoltage )
wYcoordinate =
//Explicit cast to avoid (g++) warning.
(WORD)
(
m_wDiagramHeight -
( fVoltageInVolt - m_fMinVoltage )
/ m_fMaxMinusMinVoltage * (m_wDiagramHeight
//The highest voltage should start at the half pixel height of the
//voltage string.
- m_wMinYcoordInDiagram)
// + //uiHalfTextHeightInPixels
// m_wMinYcoordInDiagram
) ;
else
wYcoordinate =
//Explicit cast to avoid (g++) warning.
(WORD)
(
m_wDiagramHeight -
//(*iterstdsetmaxvoltageforfreq).m_fVoltageInVolt
fVoltageInVolt
/ m_fMaxVoltage * (m_wDiagramHeight
//The highest voltage should start at the half pixel height of the
//voltage string.
- m_wMinYcoordInDiagram)
// + m_wMinYcoordInDiagram
) ;
return wYcoordinate;
}
wxCoord MainFrame::DrawVoltage(
wxDC & r_wxdc ,
float fVoltageInVolt,
WORD wYcoordinate,
unsigned uiXcoordinateInPixels
)
{
static wxCoord wxcoordTextWidth, wxcoordTextHeight;
wxString wxstrVoltage = wxString::Format(
//We need a _T() macro (wide char-> L"", char->"") for EACH
//line to make it compatible between char and wide char.
wxT("%.3f") ,
fVoltageInVolt
);
unsigned uiBeginOfVoltageString = 3 + uiXcoordinateInPixels;
//Draw voltage mark.
//p_wxpaintdc->DrawText(
//wxmemorydc.DrawText(
r_wxdc.DrawText(
wxstrVoltage ,
uiBeginOfVoltageString
,
//wDiagramHeight -
/// fMaxVoltage * wDiagramHeight
wYcoordinate
) ;
r_wxdc.GetTextExtent(
wxstrVoltage
, & wxcoordTextWidth
, & wxcoordTextHeight
//, wxCoord *descent = NULL, wxCoord *externalLeading = NULL, wxFont *font = NULL
) ;
return wxcoordTextWidth + uiBeginOfVoltageString;
}
void MainFrame::DrawVoltageFreqCross(
wxDC & r_wxdc
, float fVoltageInVolt
, WORD wFreqInMHz
, const wxColor * cp_wxcolor
)
{
LOGN("begin")
WORD wXcoordinate =
//Explicit cast to avoid (g++) warning.
(WORD)
(
m_wXcoordOfBeginOfYaxis +
(float) //(*iterstdvecmaxvoltageforfreq).m_wFreqInMHz /
//(*iterstdvecmaxvoltageforfreq).m_wFreqInMHz /
wFreqInMHz /
(float) //mp_cpucoredata->m_wMaxFreqInMHz
m_wMaximumCPUcoreFrequency * m_wDiagramWidth
) ;
WORD wYcoordinate = GetYcoordinateForVoltage(fVoltageInVolt);
//wxPen pen(*wxBLUE, 3); // pen of width 3
wxPen pen(*cp_wxcolor, 3); // pen of width 3
r_wxdc.SetPen(pen);
//Draw Cursor:
r_wxdc.DrawLine(
wXcoordinate - 3, wYcoordinate ,
wXcoordinate + 4, wYcoordinate
) ;
r_wxdc.DrawLine(
wXcoordinate , wYcoordinate - 3,
wXcoordinate , wYcoordinate + 4
) ;
}
void MainFrame::DrawVoltageScale(wxDC & r_wxdc )
{
LOGN_DEBUG( "begin")
WORD wPreviousYcoordinateForVoltage = MAXWORD ;
const wxPen & c_r_penCurrent = r_wxdc.GetPen();
//TODO possibly create pen in c'tor and not for every call to this function
wxPen penLine( * wxLIGHT_GREY, 1); // pen of width 1
r_wxdc.SetPen(penLine);
const wxFont & cr_wxfontBefore = r_wxdc.GetFont();
//wxWidgets runtime error when calling GetPointSize.
// int nFontPointSize = cr_wxfontBefore.GetPointSize();
if( mp_model->m_userinterfaceattributes.mainframe.m_nVoltageScaleSizeInPoint)
{
// cr_wxfontBefore.SetPointSize(mp_model->m_userinterfaceattributes.
// m_nVoltageScaleSizeInPoint);
//TODO possibly create font in c'tor and not for every call to this function
//wxFont copy c'tor uses reference counting.
wxFont wxfont(cr_wxfontBefore//.GetNativeFontInfoDesc()
);
wxfont.SetPointSize(mp_model->m_userinterfaceattributes.mainframe.
m_nVoltageScaleSizeInPoint);
r_wxdc.SetFont(//cr_wxfontBefore
wxfont);
}
wxCoord wxcoordTextWidth, wxcoordTextHeight;
wxCoord wxcoordVoltageStringWidth = 0;
r_wxdc.GetTextExtent(
wxT("I")
, & wxcoordTextWidth
, & wxcoordTextHeight
//, wxCoord *descent = NULL, wxCoord *externalLeading = NULL, wxFont *font = NULL
) ;
int nHalfTextHeightInPixels = wxcoordTextHeight/2;
m_wMinYcoordInDiagram = nHalfTextHeightInPixels;
unsigned uiBeginOfVoltageString = 0;
m_uiRightmostEndOfVoltageString = 0;
for( WORD wVoltageIndex = 0 ; wVoltageIndex < mp_cpucoredata->
m_stdset_floatAvailableVoltagesInVolt.size() ; ++ wVoltageIndex )
{
LOGN("should draw voltage "
<< mp_cpucoredata->m_arfAvailableVoltagesInVolt[ wVoltageIndex ]
<< " for voltage scale")
m_wYcoordinate = GetYcoordinateForVoltage(
mp_cpucoredata->m_arfAvailableVoltagesInVolt[
wVoltageIndex ]//, nHalfTextHeightInPixels
);
// wYoordinate = m_wYoordinate ;
if( //If y coord of current voltage <= y coord of prev voltage - text h
//=if the voltage string _does not overlap_ with the previous voltage
//string.
m_wYcoordinate <= wPreviousYcoordinateForVoltage - //m_wTextHeight
wxcoordTextHeight)
{
//uiBeginOfVoltageString = wxcoordVoltageStringWidth;
// //Next time start at x pos 0.
// wxcoordVoltageStringWidth = 0;
//Draw at x pos 0.
wxcoordVoltageStringWidth = 0;
}
else //Strings would overlap-> place right of previous voltage string.
{
// wxcoordVoltageStringWidth = 0;
// uiBeginOfVoltageString = 0;
// uiBeginOfVoltageString
// wxcoordVoltageStringWidth = DrawVoltage(
// r_wxdc,
// mp_cpucoredata->m_arfAvailableVoltagesInVolt[ wVoltageIndex ]
// , m_wYcoordinate - nHalfTextHeightInPixels
// , //wXcoordinateForVoltageStringBegin
// wxcoordVoltageStringWidth
//// 0
// ) ;
}
//Next time start with x pos of end of this string.
// wxcoordVoltageStringWidth =
uiBeginOfVoltageString =
DrawVoltage(
r_wxdc,
mp_cpucoredata->m_arfAvailableVoltagesInVolt[ wVoltageIndex ]
, m_wYcoordinate - nHalfTextHeightInPixels
, //wXcoordinateForVoltageStringBegin
// 0
wxcoordVoltageStringWidth
// uiBeginOfVoltageString
) ;
if( wxcoordVoltageStringWidth )
//Next time start with x pos 0.
wxcoordVoltageStringWidth = 0;
else
wxcoordVoltageStringWidth = uiBeginOfVoltageString;
wPreviousYcoordinateForVoltage = m_wYcoordinate ;
if( uiBeginOfVoltageString
//wxcoordVoltageStringWidth
> m_uiRightmostEndOfVoltageString)
m_uiRightmostEndOfVoltageString = uiBeginOfVoltageString;
//wxcoordVoltageStringWidth;
r_wxdc.DrawLine(
// m_wXcoordOfBeginOfYaxis,
// wxcoordVoltageStringWidth,
uiBeginOfVoltageString,
m_wYcoordinate, //+ nHalfTextHeightInPixels,
m_wXcoordOfBeginOfYaxis + m_wDiagramWidth,
m_wYcoordinate //+ nHalfTextHeightInPixels
);
if( uiBeginOfVoltageString)
//Start at x pos 0 the next time.
uiBeginOfVoltageString = 0;
}
r_wxdc.SetPen(c_r_penCurrent);
if( mp_model->m_userinterfaceattributes.mainframe.m_nVoltageScaleSizeInPoint)
{
// cr_wxfontBefore.SetPointSize(nFontPointSize);
r_wxdc.SetFont(cr_wxfontBefore);
}
LOGN_DEBUG( "end")
}
float MainFrame::GetClosestMultiplier(int nXcoordionate,
float & fReferenceClockInMHz)
{
LOGN( "begin--mp_i_cpucontroller:" << mp_i_cpucontroller)
if( mp_i_cpucontroller && nXcoordionate >= m_wXcoordOfBeginOfYaxis )
{
unsigned uiFreqInMHz = (unsigned) (
(float) (nXcoordionate - m_wXcoordOfBeginOfYaxis) /
(float) m_wDiagramWidth * (float) m_wMaximumCPUcoreFrequency
);
// float fReferenceClockInMHz = mp_i_cpucontroller->m_fReferenceClockInMHz ;
fReferenceClockInMHz = mp_i_cpucontroller->m_fReferenceClockInMHz ;
float fMultiplierForYcoordinate = (float) uiFreqInMHz /
fReferenceClockInMHz;
float fAvailableMultiplier;
float fLowerMultiplier = FLT_MIN, fHigherMultiplier = FLT_MAX;
for( WORD wMultiplierIndex = 0 ; wMultiplierIndex < mp_cpucoredata->
m_stdset_floatAvailableMultipliers.size() ; ++ wMultiplierIndex )
{
fAvailableMultiplier = mp_cpucoredata->m_arfAvailableMultipliers[
wMultiplierIndex ] ;
if( fAvailableMultiplier < fMultiplierForYcoordinate)
fLowerMultiplier = fAvailableMultiplier;
else
{
fHigherMultiplier = fAvailableMultiplier;
break;
}
}
float fClosestAvailabeMultiplier =
(fMultiplierForYcoordinate - fLowerMultiplier) <
fHigherMultiplier - fMultiplierForYcoordinate ?
fLowerMultiplier : fHigherMultiplier;
return fClosestAvailabeMultiplier;
}
return -1.0;
}
float MainFrame::GetClosestVoltageForYcoordinate(
//Y coordinate starts at 0,0 at top left corner.
int nYcoordinate)
{
if( ! mp_cpucoredata->m_stdset_floatAvailableVoltagesInVolt.empty() )
{
const std::set<float> & c_r_std_set_float = mp_cpucoredata->
m_stdset_floatAvailableVoltagesInVolt;
// const float fLowestVoltage = * c_r_std_set_float.begin();
// const float fHighestVoltage = * ( -- c_r_std_set_float.end() );
// const float fVoltageDiff = fHighestVoltage - fLowestVoltage;
// const float fYposToDiagramHeightRatio = (float) nYcoordinate / (float)
// m_wDiagramHeight;
// const float fVoltageAccordingToYcoordinate =
// //The maximum voltage is at the top left corner.
// m_fMaxVoltage -
// ( fYposToDiagramHeightRatio * m_fMaxMinusMinVoltage) //fVoltageDiff
// ;
// GetVoltageAccordignToYcoordinate();
// {
// uiYcoordinateForAvailableVoltage = GetYcoordinateForVoltage(* c_iter);
// }
// c_r_std_set_float.lower_bound(); upper_bound()
float fClosestLowerVoltage = FLT_MIN, fClosestHigherVoltage =
//If no voltage higher than "fVoltageAccordingToYcoordinate": then
//fClosestHigherVoltage - fVoltageAccordingToYcoordinate is a very big
//number.
//http://www.cplusplus.com/reference/clibrary/cfloat/:
FLT_MAX;
std::set<float>::const_iterator c_iter = c_r_std_set_float.begin();
unsigned uiYcoordinateForAvailableVoltage = 0;
unsigned uiClosestLowerYcoordinate = 0;
unsigned uiClosestHigherYcoordinate = 0;
while( c_iter != c_r_std_set_float.end() )
{
uiYcoordinateForAvailableVoltage = GetYcoordinateForVoltage(* c_iter);
if( //* c_iter < fVoltageAccordingToYcoordinate
//Higher coordinates=lower voltages.
uiYcoordinateForAvailableVoltage > nYcoordinate
)
{
uiClosestHigherYcoordinate = uiYcoordinateForAvailableVoltage;
fClosestLowerVoltage = * c_iter;
}
else
{
fClosestHigherVoltage = * c_iter;
uiClosestLowerYcoordinate = uiYcoordinateForAvailableVoltage;
break;
}
++ c_iter;
}
if( uiClosestHigherYcoordinate)
{
if( uiClosestLowerYcoordinate)
{
const float fClosestVoltageToYcoordinate =
// ( fVoltageAccordingToYcoordinate - fClosestLowerVoltage ) <
// ( fClosestHigherVoltage - fVoltageAccordingToYcoordinate ) ?
//Distance (in pixels) to higher voltage.
( nYcoordinate - uiClosestLowerYcoordinate ) >
//Distance (in pixels) to lower voltage.
( uiClosestHigherYcoordinate - nYcoordinate ) ?
fClosestLowerVoltage : fClosestHigherVoltage;
return fClosestVoltageToYcoordinate;
}
else
return fClosestLowerVoltage;
}
else
return //Lowest voltage.
* c_r_std_set_float.begin();
}
return -1.0;
}
/**
* data provider: usually the x86I&C Windows service
*/
void MainFrame::GetCPUcoreInfoFromDataProvider(
ICPUcoreUsageGetter * & p_cpucoreusagegetter ,
I_CPUcontroller * & p_cpucontroller //,
)
{
LOGN("begin")
// LOGN("DrawCurrentPstateInfo: connected to the service")
//TODO possibly make IPC communication into a separate thread because it
// may freeze the whole GUI.
// ::wxGetApp().m_ipcclient.SendCommandAndGetResponse(get_current_CPU_data) ;
// ::wxGetApp().m_ipcclient.SendCommand(get_current_CPU_data) ;
LOGN(//"MainFrame::DrawCurrentPstateInfo "
"m_bCPUcoreUsageConsumed"
#ifdef _DEBUG
": " << m_bCPUcoreUsageConsumed
#endif
)
LOGN("mp_wxx86infoandcontrolapp->m_vbGotCPUcoreData:" <<
mp_wxx86infoandcontrolapp->m_vbGotCPUcoreData )
//Do not run it more than once concurrently.
// if( //m_bCPUcoreUsageConsumed
// true
// // if(
// // //Do not call/ wait on the IPC thread if it is running right now.
// // && mp_wxx86infoandcontrolapp->m_vbGotCPUcoreData
// )
// {
// //set to true when the thread has finished.
// mp_wxx86infoandcontrolapp->m_vbGotCPUcoreData = false ;
mp_wxx86infoandcontrolapp->GetCurrentCPUcoreDataViaIPCNonBlocking() ;
m_bCPUcoreUsageConsumed = false ;
// }
// if( ::wxGetApp().m_ipcclient.m_arbyIPCdata )
// {
#ifdef COMPILE_WITH_INTER_PROCESS_COMMUNICATION
p_cpucontroller = & mp_wxx86infoandcontrolapp->
m_sax2_ipc_current_cpu_data_handler ;
p_cpucoreusagegetter = & mp_wxx86infoandcontrolapp->
m_sax2_ipc_current_cpu_data_handler ;
#endif //#ifdef COMPILE_WITH_INTER_PROCESS_COMMUNICATION
//Prevent the modification of in-program data of either the the CPU core usage
// or CPU controller data
// else this may happen:
// for some cores data may be from the previous retrieval.
// or even the CPU usage may be from previous and so not match the CPU
// controller data
LOGN(//"DrawCurrent CPU core info: "
"entering IPC 2 in-program data crit sec")
//Prevent the concurrent modification of the # of log(ical?). cores in the
//IPC data 2 in-program data thread.
mp_cpucoredata->wxconditionIPC2InProgramData.Enter() ;
LOGN(//"DrawCurrent CPU core info: "
"After entering IPC 2 in-program data crit sec")
//The number of CPU cores is known if the IPC data were got at first.
WORD wNumCPUcores = p_cpucoreusagegetter->GetNumberOfLogicalCPUcores() ;
LOGN(//"DrawCurrentCPUcoreData "
"after GetNumberOfLogicalCPUcores" )
// if( wNumCPUcores > mp_cpucoredata->m_byNumberOfCPUCores )
mp_cpucoredata->SetCPUcoreNumber( wNumCPUcores ) ;
wxString wxstrTitle = mp_wxx86infoandcontrolapp->m_wxstrDataProviderURL +
(p_cpucontroller->m_bDVFSfromServiceIsRunning ? wxT(" [DVFS]--") :
wxT(" [no DVFS]--") );
SetTitle( //wxT("--values from service")
wxstrTitle + m_wxstrTitle
) ;
}
bool MainFrame::GetCPUcoreInfoDirectlyOrFromService(
ICPUcoreUsageGetter * & p_cpucoreusagegetter ,
I_CPUcontroller * & p_cpucontroller //,
// wxString & wxstrCPUcoreUsage
, bool bGetCPUcoreUsage
)
{
LOGN("begin")
bool bReturn = false ;
p_cpucoreusagegetter = mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter ;
p_cpucontroller = mp_i_cpucontroller ;
// LOGN("DrawCurrentCPUcoreInfo")
#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE
// #ifdef _DEBUG
// bool bIsGettingCPUcoreData = mp_wxx86infoandcontrolapp->m_ipcclient.
// m_vbIsGettingCPUcoreData ;
// SUPPRESS_UNUSED_VARIABLE_WARNING(bIsGettingCPUcoreData)
// #endif
if( //::wxGetApp().m_ipcclient.IsConnected()
mp_wxx86infoandcontrolapp->IPC_ClientIsConnected()
//This flag should be (set to) "true" as long as writing and reading data
//to the service is successful.
// mp_wxx86infoandcontrolapp->m_ipcclient.m_vbIsGettingCPUcoreData
// false
)
{
GetCPUcoreInfoFromDataProvider(
p_cpucoreusagegetter,
p_cpucontroller //,
);
}
else
#endif //#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE
{
SetTitle( m_wxstrTitle //+ wxT("--values from CPU controller")
) ;
p_cpucoreusagegetter = mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter ;
//Prevent the modification of in-program data of either the the CPU core usage
// or CPU controller data
// else this may happen:
// for some cores data may be from the previous retrieval.
// or even the CPU usage may be from previous and so not match the CPU
// controller data
LOGN(//"DrawCurrent CPU core info: "
"entering IPC 2 in-program data crit sec")
mp_cpucoredata->wxconditionIPC2InProgramData.Enter() ;
LOGN(//"DrawCurrent CPU core info: "
"After entering IPC 2 in-program data crit sec")
}
// LOGN( p_cpucoreusagegetter << p_cpucontroller)
// DEBUGN("DrawCurrentCPUcoreInfo CPU controller address:" << mp_i_cpucontroller )
//::wxGetApp().mp_cpucoreusagegetter->
if( //mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter
p_cpucoreusagegetter
// >= 1 CPU core
&& mp_cpucoredata->m_byNumberOfCPUCores )
{
PerCPUcoreAttributes * p_percpucoreattributes = & mp_cpucoredata->
m_arp_percpucoreattributes[ //p_atts->m_byCoreID
0 ] ;
//DynFreqScalingThread * p_dynfreqscalingthread
//If the drawing thread and the dyn freq scaling thread both try to get
//the CPU usage they could interfere/ the delay between the usage retrieval
//could be too short-> So only try to get usage here if no DVFS thread.
if ( ! p_percpucoreattributes->mp_dynfreqscalingthread )
{
LOGN(//"DrawCurrentCPUcoreData "
"before GetPercentalUsageForAllCores" )
if( bGetCPUcoreUsage )
// mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter->
p_cpucoreusagegetter->
GetPercentalUsageForAllCores(
mp_cpucoredata->m_arfCPUcoreLoadInPercent) ;
m_bCPUcoreUsageConsumed = true ;
// DEBUGN("DrawCurrentCPUcoreInfo after GetPercentalUsageForAllCores" )
}
}
// else
// wxstrCPUcoreUsage = wxT("usage in percent: ?") ;
#ifdef _DEBUG
//::wxGetApp().mp_cpucoreusagegetter->Init() ;
#endif
//May be NULL at startup.
if( //mp_i_cpucontroller
( p_cpucontroller || //mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter
p_cpucoreusagegetter )
// >= 1 CPU core
&& mp_cpucoredata->m_byNumberOfCPUCores
)
{
LOGN_WARNING( "before recreating the temperature array: mustn't be from another "
"thread accessed during this time")
if( s_arfTemperatureInDegreesCelsius )
delete [] s_arfTemperatureInDegreesCelsius ;
s_arfTemperatureInDegreesCelsius = new float[ mp_cpucoredata->
m_byNumberOfCPUCores ] ;
bReturn = true ;
}
LOGN("return " << bReturn << " I_CPUcontroller *:"
<< p_cpucontroller)
return bReturn ;
}
WORD MainFrame::GetXcoordinateForFrequency(WORD wFrequencyInMHz)
{
LOGN(//"GetXcoordinateForFrequency(" <<
wFrequencyInMHz //<< ")"
)
return
//Explicit cast to avoid (g++) warning.
(WORD)
(
m_wXcoordOfBeginOfYaxis +
(float) //(*iterstdvecmaxvoltageforfreq).m_wFreqInMHz /
//(*iterstdvecmaxvoltageforfreq).m_wFreqInMHz /
//(*iterstdsetmaxvoltageforfreq).m_wFreqInMHz /
// (*r_iterstdsetvoltageandfreq).m_wFreqInMHz /
wFrequencyInMHz /
(float) m_wMaximumCPUcoreFrequency * m_wDiagramWidth
) ;
}
//"Cross-Platform GUI Programming with wxWidgets"
// (Copyright © 2006 Pearson Education, Inc.)
// ISBN 0-13-147381-6 "First printing, July 2005"
//"CHAPTER 5 Drawing and Printing" ->
//"UNDERSTANDING DEVICE CONTEXTS" -> "Drawing on Windows with wxPaintDC" :
// "[...] another thing you can do to make
// drawing smoother (particularly when resizing) is to paint the background in
// your paint handler, and not in an erase background handler. All the painting
// will then be done in your buffered paint handler, so you don’t see the back-
// ground being erased before the paint handler is called.
// Add an empty erase background handler [...]"
// ->Empty implementation, to prevent flicker
void MainFrame::OnEraseBackground(wxEraseEvent& event)
{
}
void MainFrame::HandleResumeForAllVoltAndFreqDlgs()
{
LOGN( "begin")
#ifdef USE_CRIT_SEC_FOR_FREQ_AND_VOLT_SETTINGS_DLG_CONTAINER
m_crit_secVoltAndFreqDlgs.Enter();
std::vector<FreqAndVoltageSettingDlg * >::const_iterator c_iter =
m_stdvec_p_freqandvoltagesettingdlg.begin();
// wxPowerEvent evt;
while( c_iter != m_stdvec_p_freqandvoltagesettingdlg.end() )
{
( * c_iter)->ResumendFromStandByOrHibernate();
++ c_iter;
}
m_crit_secVoltAndFreqDlgs.Leave();
#endif //#ifdef USE_CRIT_SEC_FOR_FREQ_AND_VOLT_SETTINGS_DLG_CONTAINER
LOGN( "end")
}
void MainFrame::OnPaint(wxPaintEvent & r_wx_paint_event)
{
LOGN("begin")
// DEBUGN("OnPaint CPU controller address:" << mp_i_cpucontroller <<
// "usage getter addr.:" << mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter
// << "mp_wxbitmap:" << mp_wxbitmap )
I_CPUcontroller * p_cpucontroller ;
ICPUcoreUsageGetter * p_cpucoreusagegetter ;
#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE
if( //::wxGetApp().m_ipcclient.IsConnected()
mp_wxx86infoandcontrolapp->IPC_ClientIsConnected()
)
{
p_cpucontroller = &
mp_wxx86infoandcontrolapp->m_sax2_ipc_current_cpu_data_handler ;
p_cpucoreusagegetter = &
mp_wxx86infoandcontrolapp->m_sax2_ipc_current_cpu_data_handler ;
}
else
#endif //#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE
{
p_cpucontroller = mp_i_cpucontroller ;
p_cpucoreusagegetter = mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter ;
}
//May be NULL at startup.
if( ( //mp_i_cpucontroller ||
p_cpucontroller ||
//mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter
p_cpucoreusagegetter
) &&
//Is NULL if CPUcontroller is NULL at startup.
mp_wxbitmap
)
{
//Control access to m_bAllowCPUcontrollerAccess between threads.
//m_wxCriticalSectionCPUctlAccess.Enter() ;
//wxCriticalSectionLocker wxcriticalsectionlocker(
// m_wxcriticalsectionCPUctlAccess ) ;
// bool bAllowCPUcontrollerAccess = IsCPUcontrollerAccessAllowedThreadSafe() ;
// if( //m_bAllowCPUcontrollerAccess
// bAllowCPUcontrollerAccess )
//TODO http://docs.wxwidgets.org/2.8/wx_wxbuffereddc.html:
//"GTK+ 2.0 as well as OS X provide double buffering themselves natively"
//if( IsDoubleBuffered() )
wxPaintDC * p_wxpaintdc = new wxPaintDC(this);
//wxMemoryDC wxmemorydc(wxbitmap) ;
wxBufferedPaintDC wxmemorydc( this //, wxbitmap
, *mp_wxbitmap
) ;
//"Cross-Platform GUI Programming with wxWidgets"
// (Copyright © 2006 Pearson Education, Inc.)
// ISBN 0-13-147381-6 "First printing, July 2005"
//"CHAPTER 5 Drawing and Printing" ->
//"UNDERSTANDING DEVICE CONTEXTS" -> "Drawing on Windows with wxPaintDC" :
// "Shifts the device origin so we don’t have to worry
// about the current scroll position ourselves"
PrepareDC(wxmemorydc);
//http://docs.wxwidgets.org/stable/wx_wxmemorydc.html#wxmemorydc:
//"Use the IsOk member to test whether the constructor was
//successful in creating a usable device context."
if( wxmemorydc.IsOk() )
{
wxCoord wxcoordCanvasWidth ;
wxCoord wxcoordCanvasHeight ;
// DEBUGN("OnPaint wxmemorydc.IsOk()" )
p_wxpaintdc->GetSize( & wxcoordCanvasWidth , & wxcoordCanvasHeight ) ;
//Clears the device context using the current background brush.
//(else black background?)
wxmemorydc.Clear();
//TODO maybe "dc.Blit(dcDiagramScaleAndCurves)" is faster than DrawBitmap.
//wxmemorydc.Blit(0, 0, wxcoordCanvasWidth , wxcoordCanvasHeight,
// & m_wxbufferedpaintdcStatic, 0, 0 );
//if( mp_wxbufferedpaintdcStatic )
wxmemorydc.Blit(0, 0, wxcoordCanvasWidth , wxcoordCanvasHeight,
//mp_wxbufferedpaintdcStatic
& m_wxmemorydcStatic , 0, 0 );
//wxmemorydc.DrawBitmap( //mp_wxbitmapDiagramScaleAndCurves
// *mp_wxbitmapStatic , 0, 0) ;
// DrawCurrentVoltageSettingsCurve(
// wxmemorydc ,
// m_fMaxVoltage
// ) ;
#ifdef __WXGTK__
/** The following lines are needed under Linux GTK for getting the text
* extent correctly? (else the text extent width is to small->
* if e.g. drawing multiple text from left to right then the text
* overlaps. */
// wxFont wxfont ;
/** This line caused a runtime error in wxDC::GetTextExtent() within
* DrawCurrentCPUcoreInfo(...) :
* "../src/gtk/dcclient.cpp(1480): assert "fontToUse->IsOk()" failed in DoGetTextExtent(): invalid font"
* respectively then it did not show any CPU
* information like CPU core frequency. */
// wxmemorydc.SetFont( wxfont) ;
#endif //#ifdef __WXGTK__
DrawCurrentCPUcoreInfo(wxmemorydc) ;
//Just for testing:
//wXcoordinate = wYcoordinate = 50 ;
if( mp_i_cpucontroller )
{
bool bAllowCPUcontrollerAccess =
IsCPUcontrollerAccessAllowedThreadSafe() ;
if( //m_bAllowCPUcontrollerAccess
bAllowCPUcontrollerAccess )
{
if( //m_bDrawFreqAndVoltagePointForCurrCoreSettings
m_vbAnotherWindowIsActive
)
{
DrawVoltageFreqCross(
wxmemorydc
, m_fVoltageInVoltOfCurrentActiveCoreSettings
, m_wFreqInMHzOfCurrentActiveCoreSettings
, wxBLUE
) ;
}
else
{
// float fVoltageInVolt ;
// WORD wFreqInMHz ;
WORD wNumCPUcores = mp_cpucoredata->GetNumberOfCPUcores() ;
float fRefClock = mp_i_cpucontroller->m_fReferenceClockInMHz ;
for( //Use WORD data type for guaranteed future (if > 256 logical
//CPU cores)
WORD wCPUcoreID = 0 ; wCPUcoreID < wNumCPUcores ; ++ wCPUcoreID )
{
// mp_i_cpucontroller->GetCurrentPstate(wFreqInMHz,
// fVoltageInVolt, byCoreID);
// PerCPUcoreAttributes & r_percpucoreattributes = mp_cpucoredata->
// m_arp_percpucoreattributes[ byCoreID] ;
DrawVoltageFreqCross(
wxmemorydc
//, r_percpucoreattributes.m_fVoltageInVoltCalculatedFromCPUload
, //fVoltageInVolt
mp_ar_voltage_and_multi[wCPUcoreID ].m_fVoltageInVolt
//, r_percpucoreattributes.m_wFreqInMHzCalculatedFromCPUload
, //wFreqInMHz
(WORD) ( mp_ar_voltage_and_multi[wCPUcoreID ].m_fMultiplier *
fRefClock )
, wxBLUE
) ;
}
}
} //if( bAllowCPUcontrollerAccess)
}
//m_bDrawFreqAndVoltagePointForCurrCoreSettings =
// ! m_bDrawFreqAndVoltagePointForCurrCoreSettings ;
//}
}//if( wxmemorydc.IsOk() )
else
{
DEBUGN("NOT wxmemorydc.IsOk()" )
}
delete p_wxpaintdc;
//m_wxCriticalSectionCPUctlAccess.Leave() ;
} // if( mp_i_cpucontroller )
else
{
wxPaintDC wxpaintdc(this);
//Clears the device context using the current background brush.
//(else black background?)
wxpaintdc.Clear();
wxpaintdc.DrawText( wxT("no CPU controller available->e.g. attach a DLL")
, 0 , 0 ) ;
}
LOGN("end")
}
//order of submenus/ menu items of "core x" menus.
enum
{
Settings = 0,
highLoadThread
, highFPUloadThread
};
void MainFrame::DynVoltnFreqScalingEnabled()
{
////Stop the timer (else the timer redraws additionally to the scaling thread).
//m_wxtimer.Stop() ;
mp_wxmenuitemOwnDVFS->/*SetText*/SetItemLabel(
/** We need a _T() macro (wide char-> L"", char->"") for EACH
* line to make it compatible between char and wide char. */
wxT("disable Own Dynamic Voltage and Frequency Scaling")
) ;
}
void MainFrame::EndDynVoltAndFreqScalingThread(
PerCPUcoreAttributes * p_percpucoreattributes )
{
// LOGN("ending Dynamic Voltage and Frequency scaling thread")
LOGN("begin")
p_percpucoreattributes->mp_dynfreqscalingthread->Stop() ;
//p_percpucoreattributes->mp_dynfreqscalingthread->Delete() ;
p_percpucoreattributes->mp_dynfreqscalingthread = NULL ;
////Start the timer (it should have been stopped before else the timer had redrawn
////additonally to the scaling thread).
// m_wxtimer.Start() ;
mp_wxmenuitemOwnDVFS->/*SetText*/SetItemLabel(
//We need a _T() macro (wide char-> L"", char->"") for EACH
//line to make it compatible between char and wide char.
wxT("enable Own DVFS")
) ;
LOGN( "end")
}
void MainFrame::Notify() //overrides wxTimer::Notify()
{
LOGN(/*"Notify"*/ "begin")
m_bDrawFreqAndVoltagePointForCurrCoreSettings =
! m_bDrawFreqAndVoltagePointForCurrCoreSettings ;
Refresh() ;
}
//Called by the destructor and by OnDetachCPUcontrollerDLL()
void MainFrame::PossiblyReleaseMemForCPUcontrollerUIcontrols()
{
// BYTE byMenuPosFor1stCPUcore = //2
// m_byIndexOf1stCPUcontrollerRelatedMenu ;
LOGN(//"PossiblyReleaseMemForCPUcontrollerUIcontrols "
"begin")
#ifdef ONE_P_STATE_DIALOG_FOR_EVERY_CPU_CORE
//May be NULL if the CPU controller is NULL.
if( m_arp_freqandvoltagesettingdlg )
{
//Release dynamically allocated memory (inside OnInit() ) :
for( BYTE byCPUcoreID = 0 ; byCPUcoreID < mp_cpucoredata->
m_byNumberOfCPUCores ; ++ byCPUcoreID )
{
if ( m_arp_freqandvoltagesettingdlg[ byCPUcoreID ] )
{
m_arp_freqandvoltagesettingdlg[ byCPUcoreID ]->
//http://docs.wxwidgets.org/2.6/wx_wxwindow.html#wxwindowdestroy:
//"Use this function instead of the delete operator[...]"
//"true if the window has either been successfully deleted, or it
//has been added to the list of windows pending real deletion."
Destroy() ;
}
}
//Delete the array containing the pointers
delete [] m_arp_freqandvoltagesettingdlg ;
m_arp_freqandvoltagesettingdlg = NULL ;
LOGN(//"PossiblyReleaseMemForCPUcontrollerUIcontrols "
"end")
}
//for( std::vector<wxMenu *>::const_iterator c_i = m_vecp_wxmenuCore.begin()
// ; c_i != m_vecp_wxmenuCore.end() ; ++ c_i )
//{
// //(*c_i)->Destroy() ;
// mp_wxmenubar->Remove(2) ;
// delete (*c_i) ;
//}
//if( ! m_vecp_wxmenuCore.empty() )
for( BYTE byCoreID = mp_cpucoredata->m_byNumberOfCPUCores - 1 ;
byCoreID !=
//gets 255 if it was 0 before and then 1 is subtracted.
255 ; -- byCoreID )
{
wxMenu * p_wxmenu = mp_wxmenubar->Remove(
byMenuPosFor1stCPUcore + byCoreID ) ;
delete p_wxmenu ;
}
//for( std::vector<wxMenu *>::const_iterator c_i = m_stdvecp_wxmenuCore.begin()
// ; c_i != m_vecp_wxmenuCore.end() ; ++ c_i
// )
//{
//}
#else //ONE_P_STATE_DIALOG_FOR_EVERY_CPU_CORE
m_stdvec_p_freqandvoltagesettingdlg.clear() ;
//TODO runtime error in Linux debug version
const int numMenus = mp_wxmenubar->GetMenuCount();
wxMenu * p_wxmenu = mp_wxmenubar->Remove(
//Linux does not have a "service menu"-> 1 index less than under Windows.
//Remove the "core(s)" menu.
// 3
numMenus - 1
) ;
delete p_wxmenu ;
#endif //ONE_P_STATE_DIALOG_FOR_EVERY_CPU_CORE
m_vecp_wxmenuCore.clear() ;
}
void MainFrame::PossiblyAskForOSdynFreqScalingDisabling()
{
LOGN("begin")
#ifdef COMPILE_WITH_OTHER_DVFS_ACCESS
bool bOtherDVFSisEnabled =
//mp_i_cpucontroller->mp_dynfreqscalingaccess->OtherDVFSisEnabled()
//mp_i_cpucontroller->OtherPerfCtrlMSRwriteIsActive()
mp_wxx86infoandcontrolapp->mp_dynfreqscalingaccess->OtherDVFSisEnabled();
LOGN("bOtherDVFSisEnabled: " << bOtherDVFSisEnabled)
if( bOtherDVFSisEnabled )
{
if (::wxMessageBox(
//We need a _T() macro (wide char-> L"", char->"") for EACH
//line to make it compatible between char and wide char.
_T("The OS's dynamic frequency scaling must be disabled ")
_T("in order that the p-state isn' changed by the OS afterwards.")
_T("If the OS's dynamic frequency isn't disabled, should it be done now?")
,
//We need a _T() macro (wide char-> L"", char->"") for EACH
//line to make it compatible between char and wide char.
_T("Question")
, wxYES_NO | wxICON_QUESTION )
== wxYES
)
//mp_i_cpucontroller->DisableFrequencyScalingByOS();
mp_wxx86infoandcontrolapp->mp_dynfreqscalingaccess->
DisableFrequencyScalingByOS() ;
}
#endif //#ifdef COMPILE_WITH_OTHER_DVFS_ACCESS
LOGN("end")
}
//#ifdef _TEST_PENTIUM_M
#ifdef COMPILE_WITH_MSR_EXAMINATION
void MainFrame::OnShowExamineCPUregistersDialog(wxCommandEvent& WXUNUSED(event))
{
////May be NULL at startup.
//if( mp_i_cpucontroller )
//{
wxExamineCPUregistersDialog * p_wxdlg = new wxExamineCPUregistersDialog(
this ,
//msrdata
//*mp_i_cpucontroller->mp_model,
//mp_i_cpucontroller
//mp_wxx86infoandcontrolapp->GetCPUaccess()
//,
mp_wxx86infoandcontrolapp
);
//p_wxdlg->ShowModal() ;
p_wxdlg->Show(true) ;
//} // if( mp_i_cpucontroller )
}
#endif
void MainFrame::OnDynamicallyCreatedUIcontrol(wxCommandEvent & wxevent)
{
LOGN(//"on dyn created control"
"begin")
int nMenuEventID = wxevent.GetId() ;
#ifdef COMPILE_WITH_OTHER_DVFS_ACCESS
// if( nMenuEventID == ID_MinAndMaxCPUcoreFreqInPercentOfMaxFreq )
// {
// //wxMessageDialog();
// //wxMessageBox("hh") ;
// //wxString strCurrentValue = wxT("50") ;
// //wxString sNewValue = wxGetTextFromUser(wxT("Enter min CPU %for
// CURRENT power profile (scheme)"),
////#ifndef _DEBUG
// // wxT("title"), strCurrentValue);
// if( ::wxGetApp().mp_dynfreqscalingaccess->OtherDVFSisEnabled()
// )
////#endif
// ::wxGetApp().mp_dynfreqscalingaccess->DisableFrequencyScalingByOS() ;
////#ifndef _DEBUG
// else
// ::wxGetApp().mp_dynfreqscalingaccess->EnableFrequencyScalingByOS() ;
////#endif //#ifdef _DEBUG
// mp_wxmenuitemOtherDVFS->SetText(//_T("")
// wxString::Format(
// //We need a _T() macro (wide char-> L"", char->"") for EACH
// //line to make it compatible between char and wide char.
// _T("%sable DVFS") ,
// ::wxGetApp().mp_dynfreqscalingaccess->OtherDVFSisEnabled() ?
// //We need a _T() macro (wide char-> L"", char->"") for EACH
// //line to make it compatible between char and wide char.
// _T("dis") :
// //We need a _T() macro (wide char-> L"", char->"") for EACH
// //line to make it compatible between char and wide char.
// _T("en")
// )
// ) ;
// return ;
//}
#endif //#ifdef COMPILE_WITH_OTHER_DVFS_ACCESS
//#endif
BYTE byCoreID = ( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID ) /
m_nNumberOfMenuIDsPerCPUcore ;
//EventIDToDivisorIDandFrequencyID(nMenuEventID);
if( //Array was successfully allocated.
m_arp_freqandvoltagesettingdlg
//&&
////menu item "set frequency and voltage" for any CPU core menu was selected.
//( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID ) %
//m_nNumberOfMenuIDsPerCPUcore == 0
)
{
//FreqAndVoltageSettingDlg freqandvoltagesettingdlg(this);
//freqandvoltagesettingdlg.Show(true);
//if( mp_freqandvoltagesettingdlg )
//{
// //if(mp_freqandvoltagesettingdlg )
// mp_freqandvoltagesettingdlg->Show(true);
//}
//else
//{
// //If created as local variable on stack the dialog would disappear
// //immediately.
// mp_freqandvoltagesettingdlg = new FreqAndVoltageSettingDlg(this);
// if(mp_freqandvoltagesettingdlg )
// mp_freqandvoltagesettingdlg->Show(true);
//}
BYTE bySubmenuIndexWithinPerCoreMenu = ( nMenuEventID -
m_nLowestIDForSetVIDnFIDnDID ) % m_nNumberOfMenuIDsPerCPUcore ;
switch( bySubmenuIndexWithinPerCoreMenu )
{
case //0:
Settings :
if( mp_cpucoredata->m_arfAvailableMultipliers &&
mp_cpucoredata->m_arfAvailableVoltagesInVolt )
{
if( m_arp_freqandvoltagesettingdlg[byCoreID] )
m_arp_freqandvoltagesettingdlg[byCoreID]->Show(true);
}
else
{
//TODO the dialog may be shown, but writing the p-state must be
//prevented if there are no voltages and/ or multipliers because
//_usually_ (voltage not for Nehalem/ i7 720 qm ) both are needed.
if( ! mp_cpucoredata->m_arfAvailableMultipliers )
wxMessageBox(
wxT("no multipliers available->no setting possible") ) ;
if( ! mp_cpucoredata->m_arfAvailableVoltagesInVolt )
wxMessageBox(
wxT("no multipliers available->no setting possible") ) ;
}
// else
// {
// //If created as local variable on stack the dialog would disappear
// //immediately.
// if( m_arp_freqandvoltagesettingdlg[byCoreID] )
// m_arp_freqandvoltagesettingdlg[byCoreID]->Show(true);
// }
break;
// case setp_state2:
// PossiblyAskForOSdynFreqScalingDisabling();
// Set the register where the VID and multiplier values for p-state 2
// reside as current (works at least for AMD Griffin)
// mp_i_cpucontroller->SetPstate(2,
// //1 = 1bin
// 1 <<
// //=core ID:
// //difference between current menu ID first menu ID for
// //core settings
// ( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID )
// / m_nNumberOfMenuIDsPerCPUcore);
// break;
case highLoadThread:
{
//m_byNumberOfSettablePstatesPerCore + 1:
// BYTE byCoreID =
// //=core ID:
// //difference between current menu ID first menu ID for
// //core settings
// ( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID )
// / m_nNumberOfMenuIDsPerCPUcore ;
//mp_i_cpucontroller->mp_calculationthread->StartCalculationThread(
// //=core ID:
// //difference between current menu ID first menu ID for
// //core settings
// ( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID )
// / m_nNumberOfMenuIDsPerCPUcore
// );
//TODO uncomment
//BYTE byAction = mp_i_cpucontroller->StartOrStopCalculationThread(
// byCoreID
// );
//BuildHighLoadThreadMenuText(
// " high load thread (e.g. for stability check)" , byAction ) ;
}
break;
default:
m_stdmapwmenuid2i_cpucontrolleraction.find(nMenuEventID)->
second->Execute() ;
//if( bySubmenuIndexWithinPerCoreMenu == m_byNumberOfSettablePstatesPerCore + 1)
//{
//BYTE byCoreID =
// //=core ID:
// //difference between current menu ID first menu ID for
// //core settings
// ( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID )
// / m_nNumberOfMenuIDsPerCPUcore ;
////mp_i_cpucontroller->mp_calculationthread->StartCalculationThread(
//// //=core ID:
//// //difference between current menu ID first menu ID for
//// //core settings
//// ( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID )
//// / m_nNumberOfMenuIDsPerCPUcore
//// );
//BYTE byAction = mp_i_cpucontroller->StartOrStopCalculationThread(
// byCoreID
// );
//wxString wxstr = byAction == ENDED ? "Start" : "End" ;
//////Invert the menu item's checked state.
////marp_wxmenuItemHighLoadThread[byCoreID]->Check(
//// ! marp_wxmenuItemHighLoadThread[byCoreID]->IsChecked () ) ;
//marp_wxmenuItemHighLoadThread[byCoreID]->SetText(
// wxstr +
// " high load thread (e.g. for stability check)"
// );
//}
if( bySubmenuIndexWithinPerCoreMenu //> 0
>= m_byMenuIndexOf1stPstate &&
bySubmenuIndexWithinPerCoreMenu < //bySubmenuIndexWithinPerCoreMenu
m_byMenuIndexOf1stPstate + m_byNumberOfSettablePstatesPerCore )
{
// BYTE byCoreID =
// //=core ID:
// //difference between current menu ID first menu ID for
// //core settings
// ( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID )
// / m_nNumberOfMenuIDsPerCPUcore ;
// BYTE byCoreBitMask =
// //1 = 1bin
// 1 << byCoreID ;
PossiblyAskForOSdynFreqScalingDisabling();
//mp_i_cpucontroller->SetPstate(
// bySubmenuIndexWithinPerCoreMenu - m_byMenuIndexOf1stPstate ,
// //byCoreBitMask
// byCoreID
// );
}
break;
}
}
}
void MainFrame::OnFindLowestOperatingVoltage(wxCommandEvent& WXUNUSED(event))
{
//TODO uncomment
//mp_i_cpucontroller->FindLowestOperatingVoltage(
// mp_i_cpucontroller->GetCurrentPstate(1),0);
}
#ifdef PRIVATE_RELEASE //hide the other possibilities
void MainFrame::OnIncreaseVoltageForCurrentPstate(wxCommandEvent& WXUNUSED(event))
{
mp_i_cpucontroller->IncreaseVoltageForCurrentPstate();
}
#endif //#ifdef PRIVATE_RELEASE //hide the other possibilities
void MainFrame::OnRedrawEverything(wxCommandEvent & evt )
{
LOGN( "begin")
RedrawEverything();
}
#ifdef wxHAS_POWER_EVENTS
void MainFrame::OnResume(wxPowerEvent & WXUNUSED(event) )
{
LOGN( "resumed from standby/ hibernate")
// HandleResumeForAllVoltAndFreqDlgs();
//May be NULL at startup.
if( mp_i_cpucontroller )
{
//mp_pumastatectrl->ApplyAllPStates() ;
mp_i_cpucontroller->ResumeFromS3orS4() ;
//After a resume (from standby) the counter value for CPU core 1 did not
//change.
//So re-initialize it now.
if(::wxGetApp().mp_cpucoreusagegetter)
::wxGetApp().mp_cpucoreusagegetter->Init() ;
//wxLogMessage(_T("System resumed from suspend."));
} // if( mp_i_cpucontroller )
LOGN( "end")
}
#endif // wxHAS_POWER_EVENTS
//void MainFrame::OnInitDialog(wxInitDialogEvent& event )
//{
// LOGN("OnInitDialog")
//// RedrawEverything() ;
//// Update() ;
//// Refresh() ;
//}
void MainFrame::OnSaveVoltageForFrequencySettings(wxCommandEvent & WXUNUSED(event) )
{
std::string std_strCPUtypeRelativeDirPath;
if( //wxGetApp().m_maincontroller.GetPstatesDirPath(
mp_wxx86infoandcontrolapp->m_maincontroller.GetPstatesDirPath(
std_strCPUtypeRelativeDirPath )
)
mp_wxx86infoandcontrolapp->SaveVoltageForFrequencySettings(
std_strCPUtypeRelativeDirPath);
}
void MainFrame::OnSaveAsCPUcontrollerDynLibForThisCPU(
wxCommandEvent & WXUNUSED(event) )
{
mp_wxx86infoandcontrolapp->SaveAsCPUcontrollerDynLibForThisCPU();
}
void MainFrame::OnSize( wxSizeEvent & //WXUNUSED(
sizeevent//)
)
{
LOGN( "begin" )
RedrawEverything() ;
}
void MainFrame::OnSizing(wxSizeEvent & wxSizeEvent)
{
LOGN("begin")
}
#ifdef wxHAS_POWER_EVENTS
void MainFrame::OnSuspending(wxPowerEvent & WXUNUSED(event))
{
LOGN( "suspending power event")
}
void MainFrame::OnSuspended(wxPowerEvent & WXUNUSED(event))
{
LOGN( "suspended power event")
}
void MainFrame::OnSuspendCancel(wxPowerEvent & WXUNUSED(event))
{
LOGN("cancelled suspend power event")
}
#endif //#ifdef wxHAS_POWER_EVENTS
//void GetCurrentPstateAndAddDefaultVoltage()
//{
// //Do something
// bool bNewVoltageAndFreqPair = false ;
// float fVoltageInVolt ;
// WORD wFreqInMHz ;
// std::pair <std::set<VoltageAndFreq>::iterator, bool>
// stdpairstdsetvoltageandfreq ;
// for ( BYTE byCPUcoreID = 0 ; byCPUcoreID <
// mp_cpucoredata->m_byNumberOfCPUCores ; ++ byCPUcoreID )
// {
// if( mp_i_cpucontroller->GetCurrentPstate(wFreqInMHz, fVoltageInVolt,
// byCPUcoreID ) )
// {
// #ifdef _DEBUG
// if( wFreqInMHz > 1800 )
// wFreqInMHz = wFreqInMHz ;
// #endif
// //stdpairstdsetvoltageandfreq = mp_model->m_cpucoredata.
// // m_stdsetvoltageandfreqDefault.insert(
// // VoltageAndFreq ( fVoltageInVolt , wFreqInMHz )
// // ) ;
// if( mp_model->m_bCollectPstatesAsDefault )
// bNewVoltageAndFreqPair = mp_model->m_cpucoredata.
// AddDefaultVoltageForFreq(
// fVoltageInVolt , wFreqInMHz ) ;
// ////New p-state inserted.
// //if( stdpairstdsetvoltageandfreq.second )
// // bNewVoltageAndFreqPair = true ;
// }
// }
// if( bNewVoltageAndFreqPair )
// {
// std::set<VoltageAndFreq>::reverse_iterator reviter =
// mp_model->m_cpucoredata.m_stdsetvoltageandfreqDefault.rbegin() ;
// //Need to set the max freq. Else (all) the operating points are
// // drawn at x-coord. "0".
// mp_cpucoredata->m_wMaxFreqInMHz = (*reviter).m_wFreqInMHz ;
// if( mp_model->m_cpucoredata.m_stdsetvoltageandfreqDefault.size() > 1
// //&& ! mp_wxmenuitemOwnDVFS->IsEnabled()
// )
// mp_wxmenuitemOwnDVFS->Enable(true) ;
// RedrawEverything() ;
// }
// else
//}
void MainFrame::OnTimerEvent(wxTimerEvent & event)
{
LOGN( "begin")
// DEBUGN("OnTimerEvent CPU controller pointer:" << mp_i_cpucontroller )
// LOGN("OnTimerEvent "
// "CPU controller pointer:" << mp_i_cpucontroller )
//May be NULL at startup.
I_CPUcontroller * p_cpucontroller ;
// ICPUcoreUsageGetter * p_cpucoreusagegetter ;
#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE
if( //::wxGetApp().m_ipcclient.IsConnected()
mp_wxx86infoandcontrolapp->IPC_ClientIsConnected()
)
{
p_cpucontroller = &
mp_wxx86infoandcontrolapp->m_sax2_ipc_current_cpu_data_handler ;
// p_cpucoreusagegetter = &
// mp_wxx86infoandcontrolapp->m_sax2_ipc_current_cpu_data_handler ;
if( ! mp_wxbitmap )
RecreateDisplayBuffers() ;
}
else
#endif //#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE
{
p_cpucontroller = mp_i_cpucontroller ;
// p_cpucoreusagegetter = mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter ;
}
if( //mp_i_cpucontroller
p_cpucontroller )
{
bool bAllowCPUcontrollerAccess = IsCPUcontrollerAccessAllowedThreadSafe() ;
// DEBUGN("CPU controller access allowed:" << bAllowCPUcontrollerAccess )
if( //m_bAllowCPUcontrollerAccess
bAllowCPUcontrollerAccess )
{
static bool isIconized, isVisible;
isIconized = IsIconized();
//TODO: returns true even if not visible (hidden bei other frames) ->
// get window client update regions to decide whether to redraw.
isVisible = IsVisible();
//Even if this window is not visible (iconized/ hidden) the highest
//temperature should be shown in the task bar/ system tray.
if( //If the window is hidden, "IsIconized()" returns "false"?
isIconized ||
// !
// //"Returns true if this window is currently active, i.e. if the user
// //is currently working with it."
// IsActive()
! //IsVisible() returns true (even) if the window is iconized.
isVisible
)
{
//If this window is iconized then OnPaint(...) isn't called and so
//"StoreCurrentVoltageAndFreqInArray(...)" is _not_ being called
//(indirectly), so get the current temperature here.
// if( s_arfTemperatureInDegreesCelsius )
// delete [] s_arfTemperatureInDegreesCelsius ;
// s_arfTemperatureInDegreesCelsius = new float[ mp_cpucoredata->
// m_byNumberOfCPUCores ] ;
ICPUcoreUsageGetter * p_cpucoreusagegetter ;
I_CPUcontroller * p_cpucontroller ;
if( GetCPUcoreInfoDirectlyOrFromService(
p_cpucoreusagegetter,
p_cpucontroller //,
// wxstrCPUcoreUsage
, //bool bGetCPUcoreUsage
// false
mp_model->m_userinterfaceattributes.
m_bShowCPUcoreUsagesIconInTaskBar
)
)
{
LOGN(//"DrawCurrentCPUcoreData "
"leaving IPC 2 in-program data crit sec")
mp_cpucoredata->wxconditionIPC2InProgramData.Leave() ;
LOGN(//"DrawCurrentCPUcoreData "
"after leaving IPC 2 in-program data crit sec")
#ifdef COMPILE_WITH_SYSTEM_TRAY_ICON
if( mp_wxx86infoandcontrolapp->m_p_HighestCPUcoreTemperatureTaskBarIcon )
{
//respect # of cpu cores
for ( WORD wCPUcoreID = 0 ; wCPUcoreID <
mp_cpucoredata->m_byNumberOfCPUCores ; ++ wCPUcoreID )
{
s_arfTemperatureInDegreesCelsius[ wCPUcoreID ] = p_cpucontroller->
GetTemperatureInCelsius(wCPUcoreID) ;
}
ShowHighestCPUcoreTemperatureInTaskBar(p_cpucontroller) ;
}
#endif //#ifdef COMPILE_WITH_SYSTEM_TRAY_ICON
ShowCPUcoreUsagesInTaskBar(p_cpucontroller);
if( mp_model->m_userinterfaceattributes.m_bShowCPUcoreUsagesIconInTaskBar )
{
//respect # of cpu cores
for ( WORD wCPUcoreID = 0 ; wCPUcoreID <
mp_cpucoredata->m_byNumberOfCPUCores ; ++ wCPUcoreID )
p_cpucontroller->GetCurrentVoltageAndFrequencyAndStoreValues(
wCPUcoreID);
ShowCPUcoresMultipliersInTaskBar(p_cpucontroller);
}
}
}
else // !IsIconized() && IsVisible()
{
// GetCurrentPstateAndAddDefaultVoltage();
if( m_bDiagramNotDrawn //&& mp_i_cpucontroller
&& //mp_i_cpucontroller->m_fReferenceClockInMHz
p_cpucontroller->m_fReferenceClockInMHz
)
{
LOGN("diagram not already drawn and reference clock <> 0 ")
// bool bAllowCPUcontrollerAccess =
// IsCPUcontrollerAccessAllowedThreadSafe() ;
// if( //bAllowCPUcontrollerAccess &&
// mp_i_cpucontroller->
// m_fReferenceClockInMHz )
// {
//The diagram is based on the CPU core frequency and can be drawn at
//first when the reference clock is known.
RedrawEverything() ;
m_bDiagramNotDrawn = false ;
// }
}
else
//http://docs.wxwidgets.org/trunk/classwx_window.html
// #29dc7251746154c821b17841b9877830:
//"Causes this window, and all of its children recursively (except
//under wxGTK1 where this is not implemented), to be repainted.
//Note that repainting doesn't happen immediately but only during the
//next event loop iteration, if you need to update the window
//immediately you should use Update() instead."
// -> EVT_PAINT -> MainFrame::OnPaint(...) is called.
Refresh() ;
}
}
//TRACE("OnTimerEvent\n") ;
} // if( mp_i_cpucontroller )
else //if( mp_i_cpucontroller )
{
if( mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter )
//Also refresh if just a core usage getter (for showing the usage per
//core)
Refresh() ;
}
LOGN( "end")
}
void MainFrame::OnUpdateViewInterval(wxCommandEvent & WXUNUSED(event))
{
wxString wxstrMessage = wxT("Input update view interval in milliseconds") ;
wxString wxstrInput = ::wxGetTextFromUser( wxstrMessage , wxT("input"),
wxT("1000") ) ;
//::wxGetNumberFromUser
//If the user has input text (and has NOT pressed "cancel")
if( ! wxstrInput.empty() )
{
unsigned long ulMs ;
bool bSuccess = wxstrInput.ToULong(& ulMs) ;
if ( bSuccess )
{
//ReadMsrEx() returned false results if used with a time and a 10 ms interval.
if( ulMs < 100 )
wxMessageBox( wxT("the number is too low. ")
wxT("Getting the current CPU frequency returned wrong values with < 100 ms") ) ;
else
{
m_dwTimerIntervalInMilliseconds = ulMs ;
m_wxtimer.Stop() ;
m_wxtimer.Start(ulMs) ;
// m_p_wxtimer->Stop() ;
// m_p_wxtimer->Start(ulMs) ;
}
}
else
{
wxMessageBox( wxT("You did not enter a valid integer number") ) ;
}
}
}
void MainFrame::OnShowCPUregistersReadAndWriteDialog( wxCommandEvent & WXUNUSED(event) )
{
#ifndef _DEBUG
//May be NULL at startup.
if( mp_i_cpucontroller )
#endif
{
#ifdef COMPILE_WITH_MSR_EXAMINATION
CPUregisterReadAndWriteDialog * p_wxdlg = new
CPUregisterReadAndWriteDialog(
this ,
//msrdata
//*mp_i_cpucontroller->mp_model,
* mp_model ,
mp_i_cpucontroller
//mp_i_cpucontroller->mp_cpuaccess
//, mp_wxx86infoandcontrolapp
);
//p_wxdlg->ShowModal() ;
p_wxdlg->Show(true) ;
#endif //#ifdef COMPILE_WITH_MSR_EXAMINATION
} //if( mp_i_cpucontroller )
}
void MainFrame::RecreateDisplayBuffers()
{
LOGN(//"RecreateDisplayBuffers "
"begin")
if( mp_wxbitmap )
delete mp_wxbitmap ;
wxRect rect = GetClientRect();
//wxCoord wxcoordCanvasWidth ;
//wxCoord wxcoordCanvasHeight ;
//p_wxpaintdc->GetSize( & wxcoordCanvasWidth , & wxcoordCanvasHeight ) ;
m_wDiagramHeight = rect.height
//Space for drawing scale and scale values below the x-axis.
- 50 ;
//WORD wXcoordOfBeginOfYaxis = 50 ;
m_wXcoordOfBeginOfYaxis = 50 ;
//WORD wDiagramWidth = wxcoordCanvasWidth - wXcoordOfBeginOfYaxis - 30 ;
m_wDiagramWidth = rect.width - m_wXcoordOfBeginOfYaxis - 30 ;
mp_wxbitmap = new wxBitmap(
rect.width,
rect.height ,
//http://docs.wxwidgets.org/stable/wx_wxbitmap.html#wxbitmapctor:
//"A depth of -1 indicates the depth of the current screen or visual."
-1) ;
//if( mp_wxbufferedpaintdcStatic )
// delete mp_wxbufferedpaintdcStatic ;
//create new objet so it uses internally an bitmap with the new client size.
//mp_wxbufferedpaintdcStatic = new wxBufferedPaintDC(this) ;
if( mp_wxbitmapStatic )
delete mp_wxbitmapStatic ;
mp_wxbitmapStatic = new wxBitmap(
rect.width,
rect.height ,
//http://docs.wxwidgets.org/stable/wx_wxbitmap.html#wxbitmapctor:
//"A depth of -1 indicates the depth of the current screen or visual."
-1) ;
m_wxmemorydcStatic.SelectObject(*mp_wxbitmapStatic) ;
//Clears the device context using the current background brush.
//(else black background?)
m_wxmemorydcStatic.Clear();
m_wMinYcoordInDiagram =
//Let the diagram begin at the vertical middle of the topmost voltage value.
m_wxmemorydcStatic.GetCharHeight() / 2 ;
}
//in order to draw voltage and freq aligned if more than 1 core/ to draw at
//the same pos for many intervals:
//core 0: 0.9 V 1100 MHz
//core 1: 1.11 V 550 MHz
void MainFrame::DetermineMaxVoltageAndMaxFreqDrawWidth(wxDC & r_wxdc)
{
wxString wxstrMaxFreq = wxString::Format(
//Use wxT() to enable to compile with both unicode and ANSI.
wxT("%u"),
mp_cpucoredata->m_wMaxFreqInMHz ) ;
//the max. freq. usually has the max draw width.
m_wMaxFreqWidth = r_wxdc.GetTextExtent(wxstrMaxFreq).GetWidth() ;
//Because max. voltage ID is lowest voltage for AMD Griffin but highest
//voltage for Pentium M.
float fVoltageForMaxVoltageID = mp_i_cpucontroller->GetVoltageInVolt(
mp_cpucoredata->m_byMaxVoltageID ) ;
float fVoltageForMinVoltageID = mp_i_cpucontroller->GetVoltageInVolt(
mp_cpucoredata->m_byMinVoltageID ) ;
float fMaxVoltage = fVoltageForMaxVoltageID > fVoltageForMinVoltageID ?
fVoltageForMaxVoltageID : fVoltageForMinVoltageID ;
wxString wxstrMaxVolt = wxString::Format(
//Use wxT() to enable to compile with both unicode and ANSI.
wxT("%f"), fMaxVoltage ) ;
//the max. voltage usually has the max draw width.
m_wMaxVoltageWidth = r_wxdc.GetTextExtent(wxstrMaxFreq).GetWidth() ;
}
void MainFrame::DetermineTextHeight(wxDC & r_wxdc)
{
wxCoord wxcoordWidth ;
wxCoord wxcoordHeight ;
wxCoord wxcoordDescent ;
r_wxdc.GetTextExtent(
wxT("|"),
& wxcoordWidth , //wxCoord *w,
& wxcoordHeight , //wxCoord *h,
& wxcoordDescent //wxCoord *descent = NULL,
//wxCoord *externalLeading = NULL, wxFont *font = NULL
) ;
m_wTextHeight = wxcoordHeight + wxcoordDescent ;
}
void MainFrame::RedrawEverything()
{
LOGN(//"RedrawEverything "
"mp_i_cpucontroller:" << mp_i_cpucontroller)
DetermineTextHeight(m_wxmemorydcStatic) ;
//May be NULL at startup.
if( mp_i_cpucontroller )
// I_CPUcontroller * p_cpucontroller ;
// if( ::wxGetApp().m_ipcclient.IsConnected() )
// {
// p_cpucontroller = &
// mp_wxx86infoandcontrolapp->m_sax2_ipc_current_cpu_data_handler ;
// if( !mp_wxbitmap )
// RecreateDisplayBuffers() ;
// }
// else
// {
// p_cpucontroller = mp_i_cpucontroller ;
// }
// if( p_cpucontroller )
{
DetermineMaxVoltageAndMaxFreqDrawWidth(m_wxmemorydcStatic) ;
//Control access to m_bAllowCPUcontrollerAccess between threads.
//m_wxCriticalSectionCPUctlAccess.Enter() ;
//wxCriticalSectionLocker wxcriticalsectionlocker(
// m_wxcriticalsectionCPUctlAccess ) ;
bool bAllowCPUcontrollerAccess = IsCPUcontrollerAccessAllowedThreadSafe() ;
LOGN(//"RedrawEverything "
"bAllowCPUcontrollerAccess:" <<
bAllowCPUcontrollerAccess)
if( //m_bAllowCPUcontrollerAccess
bAllowCPUcontrollerAccess )
{
// int i = 0 ;
m_fMinVoltage = //mp_i_cpucontroller->GetMinimumVoltageInVolt() ;
mp_model->m_cpucoredata.GetMinimumVoltage() ;
float fMaxMulti = mp_model->m_cpucoredata.GetMaximumMultiplier() ;
m_wMaximumCPUcoreFrequency =
(WORD) ( fMaxMulti *
mp_i_cpucontroller->m_fReferenceClockInMHz ) ;
LOGN(//"RedrawEverything "
"m_wMaximumCPUcoreFrequency="
<< m_wMaximumCPUcoreFrequency
<< "=" << mp_i_cpucontroller->m_fReferenceClockInMHz
<< "*" << fMaxMulti
)
RecreateDisplayBuffers(//m_wxmemorydcStatic
) ;
//m_wxbufferedpaintdcStatic.SelectObject(mp_wxbitmapStatic) ;
// if( mp_wxbufferedpaintdc
// wxBufferedPaintDC mp_wxbufferedpaintdc ( this ) ;
//Drawing the curves (calculate and draw ~ 400 points) takes some time.
//So do it only when the client size changes and store the drawn curves
//into a image and DrawBitmap() or do "Blit()" with the DC drawn to and
//the DC that shows it in the window.
//if( mp_wxbufferedpaintdcStatic )
{
std::set<VoltageAndFreq> & r_setvoltageforfreq = //mp_i_cpucontroller->
mp_model->m_cpucoredata.m_stdsetvoltageandfreqDefault ;
// std::set<MaxVoltageForFreq>::iterator iterstdsetmaxvoltageforfreq =
// std::set<VoltageAndFreq>::reverse_iterator iterstdsetvoltageandfreq =
// //m_setmaxvoltageforfreq.begin() ;
// r_setvoltageforfreq.rbegin() ;
if(
//mp_i_cpucontroller->mp_model->
//m_setmaxvoltageforfreq.end()
// iterstdsetvoltageandfreq !=
// r_setvoltageforfreq.rend()
! mp_cpucoredata->m_stdset_floatAvailableVoltagesInVolt.empty()
)
{
m_fMaxVoltage = //(*iterstdvecmaxvoltageforfreq).m_fVoltageInVolt ;
////P-state 0 usually has the highest voltage.
//(*iterstdsetvoltageandfreq).m_fVoltageInVolt ;
mp_cpucoredata->m_arfAvailableVoltagesInVolt[ mp_cpucoredata->
//Last element/ highest voltage.
m_stdset_floatAvailableVoltagesInVolt.size() - 1 ] ;
//for g++: assign value to created iterator and pass this to the arg
std::set<VoltageAndFreq>::iterator iter = r_setvoltageforfreq.begin() ;
DrawDiagramScale( m_wxmemorydcStatic , //iterstdsetvoltageandfreq
//r_setvoltageforfreq.begin()
iter
) ;
}
m_fMaxMinusMinVoltage = m_fMaxVoltage - m_fMinVoltage ;
DrawVoltageGraph(
//m_wxbufferedpaintdcStatic
//*mp_wxbufferedpaintdcStatic
m_wxmemorydcStatic
, m_fMaxVoltage
, mp_cpucoredata->m_stdsetvoltageandfreqDefault
) ;
DrawCurrentVoltageSettingsCurve(
//m_wxbufferedpaintdcStatic
//*mp_wxbufferedpaintdcStatic
m_wxmemorydcStatic
, m_fMaxVoltage
//, mp_cpucoredata->m_stdsetvoltageandfreqWanted
) ;
DrawLowestStableVoltageCurve(
//m_wxbufferedpaintdcStatic
//*mp_wxbufferedpaintdcStatic
m_wxmemorydcStatic
, m_fMaxVoltage
) ;
// DrawAllPossibleOperatingPoints( m_wxmemorydcStatic ) ;
DrawPerformanceStatesCrosses( m_wxmemorydcStatic ,
mp_cpucoredata->m_stdsetvoltageandfreqDefault
, wxBLACK ) ;
DrawPerformanceStatesCrosses( m_wxmemorydcStatic ,
mp_cpucoredata->m_stdsetvoltageandfreqWanted
//The wanted voltage may be above the default voltage because the
//default voltage may be too low (e.g. for AMD Turion X2 Ultra
//2400 MHz)
, wxGREEN ) ;
DrawPerformanceStatesCrosses( m_wxmemorydcStatic ,
mp_cpucoredata->m_stdsetvoltageandfreqLowestStable
, wxRED ) ;
}
} //if( bAllowCPUcontrollerAccess)
//m_wxcriticalsectionCPUctlAccess.Leave() ;
} // if( mp_i_cpucontroller )
else
{
if(
#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE
//::wxGetApp().m_ipcclient.IsConnected()
mp_wxx86infoandcontrolapp->IPC_ClientIsConnected()
||
#endif //#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE
mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter
)
//Necessary for OnPaint() ;
RecreateDisplayBuffers() ;
}
LOGN(//"RedrawEverything #"
"end")
}
//Also called when CPU controller was changed.
void MainFrame::SetCPUcontroller(I_CPUcontroller * p_cpucontroller )
{
LOGN(//"SetCPUcontroller "
"begin")
mp_i_cpucontroller = p_cpucontroller ;
m_wMaxFreqInMHzTextWidth = 0 ;
m_wMaxVoltageInVoltTextWidth = 0 ;
m_wMaxTemperatureTextWidth = 0 ;
}
void MainFrame::ShowCPUcoreUsagesInTaskBar(
I_CPUcontroller * p_i_cpucontroller)
{
#ifdef COMPILE_WITH_SYSTEM_TRAY_ICON
if( mp_model->m_userinterfaceattributes.m_bShowCPUcoreUsagesIconInTaskBar )
{
LOGN_DEBUG("mp_taskbaricon:"
<< mp_wxx86infoandcontrolapp->m_p_CPUcoreUsagesTaskbarIcon )
if( mp_wxx86infoandcontrolapp->m_p_CPUcoreUsagesTaskbarIcon )
{ //TODO make wxIcon (and other params) member variables of class TaskBarIcon
//or wxicondrawer
mp_wxx86infoandcontrolapp->m_p_CPUcoreUsagesTaskbarIcon->
m_p_wxicon_drawer->DrawColouredBarsIcon(
s_wxiconCPUcoreUsages,
mp_cpucoredata->m_arfCPUcoreLoadInPercent,
mp_cpucoredata->m_byNumberOfCPUCores
);
if( mp_wxx86infoandcontrolapp->m_p_CPUcoreUsagesTaskbarIcon->SetIcon(
s_wxiconCPUcoreUsages, wxT("x86IandC--CPU cores usages") )
)
{
#ifdef _DEBUG
wxBitmap & wxbmp //(s_wxiconCPUcoreUsages);
= * mp_wxx86infoandcontrolapp->m_p_CPUcoreUsagesTaskbarIcon->
m_p_wxicon_drawer->m_p_wxbitmapToDrawOn;
wxbmp.SaveFile(
// const wxString& name
wxT("CPUcoreUsages.bmp")
//wxBitmapType type
, //wxBITMAP_TYPE_XPM did work on Windows
wxBITMAP_TYPE_BMP
);
#endif
// if( ! mp_wxmenuFile->IsEnabled() )
//The menu item may be disabled if setting the icon failed for the
//1st time (if started via the service on logon and the the task bar
//was not ready).
//TODO wx assert here if no menu item with ID "ID_MinimizeToSystemTray"
//was added.
// mp_wxmenuFile->Enable(ID_MinimizeToSystemTray, true);
}
else
{
//::wxMessageBox( wxT("Could not set task bar icon."),
// getwxString(mp_wxx86infoandcontrolapp->m_stdtstrProgramName) ) ;
// LOGN("Could not set task bar icon.")
mp_wxmenuFile->Enable(ID_MinimizeToSystemTray, false);
}
}
}
#endif //#ifdef COMPILE_WITH_SYSTEM_TRAY_ICON
}
void MainFrame::ShowCPUcoresMultipliersInTaskBar(
I_CPUcontroller * p_i_cpucontroller)
{
#ifdef COMPILE_WITH_SYSTEM_TRAY_ICON
if( mp_model->m_userinterfaceattributes.
m_bShowCPUcoresMultipliersIconInTaskBar )
{
LOGN_DEBUG("mp_taskbaricon:" << mp_wxx86infoandcontrolapp->
m_p_CPUcoresMultipliersTaskbarIcon )
if( mp_wxx86infoandcontrolapp->m_p_CPUcoresMultipliersTaskbarIcon )
{
BYTE byNumberOfCPUcores = mp_cpucoredata->m_byNumberOfCPUCores;
float * CPUcoreMultipliersInPercentOfMinAndMax = new float [
byNumberOfCPUcores];
LOGN( "Number Of CPU cores:" <<
(WORD) byNumberOfCPUcores
<< "CPUcoreMultipliersInPercentOfMinAndMax:" <<
CPUcoreMultipliersInPercentOfMinAndMax)
if( CPUcoreMultipliersInPercentOfMinAndMax )
{
float fMaximumCPUcoreMultiplier = mp_cpucoredata->GetMaximumMultiplier();
float fMinimumCPUcoreMultiplier = mp_cpucoredata->GetMinimumMultiplier();
float fMaxMultiMinusMinMulti = fMaximumCPUcoreMultiplier -
fMinimumCPUcoreMultiplier;
// float fVoltageInVolt;
float fMultiplier;
// float fReferenceClockInMHz;
// WORD wCPUcoreID;
float currentMultiMinusMinMulti;
float CPUcoreMultiplierInPercentOfMinAndMax;
for( WORD wCPUcoreID = 0; wCPUcoreID < byNumberOfCPUcores; ++ wCPUcoreID)
{
fMultiplier = mp_cpucoredata->m_arp_percpucoreattributes[
wCPUcoreID].m_fMultiplier;
//GetCurrentVoltageAndFrequency(...) should have been called right before.
// if( p_i_cpucontroller->GetCurrentVoltageAndFrequency(
// fVoltageInVolt
// , fMultiplier
// , fReferenceClockInMHz
// , wCPUcoreID
// )
// )
{
//possible_multis: [min_multi ... max_multi].
//current_multi is_element_of possible_multis.
// max_minus_min_multi = max_multi - min_multi = 1.0 = 100%
// current_multi_minus_min_multi = current_multi - min_multi.
currentMultiMinusMinMulti = fMultiplier -
fMinimumCPUcoreMultiplier;
// current_multi in percent of possible_multis =
// current_multi_minus_min_multi / max_minus_min_multi
CPUcoreMultiplierInPercentOfMinAndMax =
// fMinimumCPUcoreMultiplier / currentMultiMinusMinMulti;
currentMultiMinusMinMulti / fMaxMultiMinusMinMulti;
if( currentMultiMinusMinMulti == 0.0f) // x / 0 = infinite
CPUcoreMultipliersInPercentOfMinAndMax[wCPUcoreID] = 0;
else
CPUcoreMultipliersInPercentOfMinAndMax[wCPUcoreID] =
CPUcoreMultiplierInPercentOfMinAndMax;
LOGN( "multiplier for CPU core # "
<< (WORD) wCPUcoreID << " in percent in range of "
"min and max=" << fMaxMultiMinusMinMulti << " / (" <<
fMultiplier << " - " << fMinimumCPUcoreMultiplier << " ) = "
<< currentMultiMinusMinMulti << " / " <<
fMaxMultiMinusMinMulti << " = "
<< CPUcoreMultiplierInPercentOfMinAndMax)
}
}
mp_wxx86infoandcontrolapp->m_p_CPUcoresMultipliersTaskbarIcon->
m_p_wxicon_drawer->DrawColouredBarsIcon(
s_wxiconCPUcoresMultipliers,
CPUcoreMultipliersInPercentOfMinAndMax,
mp_cpucoredata->m_byNumberOfCPUCores
);
delete [] CPUcoreMultipliersInPercentOfMinAndMax;
}
if( mp_wxx86infoandcontrolapp->m_p_CPUcoresMultipliersTaskbarIcon->
SetIcon(s_wxiconCPUcoresMultipliers,
wxT("x86IandC--CPU cores multipliers in % of max - min multiplier") )
)
{
#ifdef _DEBUG
wxBitmap & wxbmp //(s_wxiconCPUcoreUsages);
= * mp_wxx86infoandcontrolapp->m_p_CPUcoresMultipliersTaskbarIcon->
m_p_wxicon_drawer->m_p_wxbitmapToDrawOn;
wxbmp.SaveFile(
// const wxString& name
wxT("CPUcoreMultipliers.bmp")
//wxBitmapType type
, //wxBITMAP_TYPE_XPM did work on Windows
wxBITMAP_TYPE_BMP
);
#endif
// if( ! mp_wxmenuFile->IsEnabled() )
//The menu item may be disabled if setting the icon failed for the
//1st time (if started via the service on logon and the the task bar
//was not ready).
//TODO wxWidgets debug alert ("no such ID "ID_MinimizeToSystemTray"??)
//here?!
// mp_wxmenuFile->Enable(ID_MinimizeToSystemTray, true);
}
else
{
//::wxMessageBox( wxT("Could not set task bar icon."),
// getwxString(mp_wxx86infoandcontrolapp->m_stdtstrProgramName) ) ;
// LOGN("Could not set task bar icon.")
mp_wxmenuFile->Enable(ID_MinimizeToSystemTray, false);
}
}
}
#endif //#ifdef COMPILE_WITH_SYSTEM_TRAY_ICON
}
void MainFrame::ShowHighestCPUcoreTemperatureInTaskBar(
I_CPUcontroller * p_i_cpucontroller)
{
#ifdef COMPILE_WITH_SYSTEM_TRAY_ICON
LOGN_DEBUG("mp_taskbaricon:"
<< mp_wxx86infoandcontrolapp->m_p_HighestCPUcoreTemperatureTaskBarIcon)
if( mp_wxx86infoandcontrolapp->m_p_HighestCPUcoreTemperatureTaskBarIcon )
{
static wxLongLong_t wxlonglong_tLocalTimeMillis;
wxlonglong_tLocalTimeMillis = ::wxGetLocalTimeMillis().
GetValue();
static long long llDiffInMillis;
llDiffInMillis = wxlonglong_tLocalTimeMillis -
// mp_cpucoredata->m_llLastTimeTooHot;
p_i_cpucontroller->m_llLastTimeTooHot;
static std::basic_string<LOGGING_CHARACTER_TYPE> str;
MAKE_STRING_FROM_STRING_STREAM( str,
"diff between current time and last time too hot="
<< wxlonglong_tLocalTimeMillis << "-"
<< p_i_cpucontroller->m_llLastTimeTooHot << "="
<< llDiffInMillis
)
// g_logger.Log_inline( //FULL_FUNC_NAME,
// str);
LOGN_DEBUG( str)
//Adapted from http://www.cppreference.com/wiki/valarray/max:
std::valarray<float> stdvalarray_float(s_arfTemperatureInDegreesCelsius,
mp_cpucoredata->m_byNumberOfCPUCores);
float fHighestTemperature = stdvalarray_float.max() ;
mp_wxx86infoandcontrolapp->GetTemperatureString(fHighestTemperature,
s_wxstrHighestCPUcoreTemperative);
//TODO
// const wxFont & wxfontBefore = r_wxdc.GetFont();
//// int nFontPointSize = wxfont.GetPointSize();
// if( mp_model->m_userinterfaceattributes.m_nCurrentCPUcoreInfoSizeInPoint)
// {
// wxFont wxfont2(wxfont);
// wxfont2.SetPointSize(mp_model->m_userinterfaceattributes.
// m_nCurrentCPUcoreInfoSizeInPoint);
// mp_wxx86infoandcontrolapp->m_p_HighestCPUcoreTemperatureTaskBarIcon->
// m_wxdc.SetFont(wxfont2);
// }
if( llDiffInMillis < 5000 )
mp_wxx86infoandcontrolapp->m_p_HighestCPUcoreTemperatureTaskBarIcon->//m_wxicon_drawer.DrawText(
DrawText(
s_wxiconTemperature,
s_wxstrHighestCPUcoreTemperative,
wxRED//,
//wxWHITE
);
else
// CreateTextIcon( s_wxiconTemperature, s_wxstrHighestCPUcoreTemperative ) ;
mp_wxx86infoandcontrolapp->m_p_HighestCPUcoreTemperatureTaskBarIcon->//m_wxicon_drawer.DrawText(
DrawText(
s_wxiconTemperature,
s_wxstrHighestCPUcoreTemperative,
wxBLACK//,
// wxWHITE
);
//TODO runtime error: "../src/gtk/bitmap.cpp(1328): assert "IsOk()" failed
// in wxBitmap::GetPixbuf(): invalid bitmap"
if( mp_wxx86infoandcontrolapp->m_p_HighestCPUcoreTemperatureTaskBarIcon->SetIcon(
s_wxiconTemperature, s_wxstrTaskBarIconToolTip )
)
{
// if( ! mp_wxmenuFile->IsEnabled() )
//The menu item may be disabled if setting the icon failed for the
//1st time (if started via the service on logon and the the task bar
//was not ready).
//TODO wxWidgets debug alert ("no such ID "ID_MinimizeToSystemTray"??)
//here?!
// mp_wxmenuFile->Enable(ID_MinimizeToSystemTray, true);
}
else
{
//::wxMessageBox( wxT("Could not set task bar icon."),
// getwxString(mp_wxx86infoandcontrolapp->m_stdtstrProgramName) ) ;
// LOGN("Could not set task bar icon.")
mp_wxmenuFile->Enable(ID_MinimizeToSystemTray, false);
}
}
LOGN("end")
#endif //#ifdef COMPILE_WITH_SYSTEM_TRAY_ICON
}
//void MainFrame::UpdatePowerSettings(
// wxPowerType powerType,
// wxBatteryState batteryState
// )
//{
// LOGN("UpdatePowerSettings")
// wxString powerStr;
// switch ( m_powerType = powerType )
// {
// case wxPOWER_SOCKET:
// powerStr = _T("wall");
// break;
// case wxPOWER_BATTERY:
// powerStr = _T("battery");
// break;
// default:
// wxFAIL_MSG(_T("unknown wxPowerType value"));
// // fall through
// case wxPOWER_UNKNOWN:
// powerStr = _T("psychic");
// break;
// }
//
// wxString batteryStr;
// switch ( m_batteryState = batteryState )
// {
// case wxBATTERY_NORMAL_STATE:
// batteryStr = _T("charged");
// break;
// case wxBATTERY_LOW_STATE:
// batteryStr = _T("low");
// break;
// case wxBATTERY_CRITICAL_STATE:
// batteryStr = _T("critical");
// break;
// case wxBATTERY_SHUTDOWN_STATE:
// batteryStr = _T("empty");
// break;
// default:
// wxFAIL_MSG(_T("unknown wxBatteryState value"));
// // fall through
// case wxBATTERY_UNKNOWN_STATE:
// batteryStr = _T("unknown");
// break;
// }
// SetStatusText( wxString::Format (
// _T("System is on %s power, battery state is %s"),
// powerStr.c_str(),
// batteryStr.c_str()
// )
// );
//}
| 36.241453 | 119 | 0.677207 | st-gb |
c129ce3df2ac2821743791aa84229de703f3143c | 5,187 | cpp | C++ | src/original-content/VirtualFileSystem.cpp | KirmesBude/REGoth-bs | 2e13dc3b9005744fccd7cea9c7e7cc1f94809e4a | [
"MIT"
] | 399 | 2019-01-06T17:55:18.000Z | 2022-03-21T17:41:18.000Z | src/original-content/VirtualFileSystem.cpp | KirmesBude/REGoth-bs | 2e13dc3b9005744fccd7cea9c7e7cc1f94809e4a | [
"MIT"
] | 101 | 2019-04-18T21:03:53.000Z | 2022-01-08T13:27:01.000Z | src/original-content/VirtualFileSystem.cpp | KirmesBude/REGoth-bs | 2e13dc3b9005744fccd7cea9c7e7cc1f94809e4a | [
"MIT"
] | 56 | 2019-04-10T10:18:27.000Z | 2022-02-08T01:23:31.000Z | #include "VirtualFileSystem.hpp"
#include <FileSystem/BsFileSystem.h>
#include <exception/Throw.hpp>
#include <log/logging.hpp>
#include <vdfs/fileIndex.h>
using namespace REGoth;
class REGoth::InternalVirtualFileSystem
{
public:
InternalVirtualFileSystem() = default;
virtual ~InternalVirtualFileSystem() = default;
VDFS::FileIndex fileIndex;
bool isFinalized = false;
bool isReadyToReadFiles()
{
if (!isFinalized)
{
return false;
}
else
{
return true;
}
}
void finalizeFileIndex()
{
fileIndex.finalizeLoad();
isFinalized = true;
}
};
void VirtualFileSystem::setPathToEngineExecutable(const bs::String& argv0)
{
VDFS::FileIndex::initVDFS(argv0.c_str());
mInternal = bs::bs_shared_ptr_new<InternalVirtualFileSystem>();
}
void VirtualFileSystem::mountDirectory(const bs::Path& path)
{
throwOnMissingInternalState();
if (mInternal->isFinalized)
{
REGOTH_THROW(InvalidStateException, "Cannot mount directories on finalized file index.");
}
REGOTH_LOG(Info, Uncategorized, "[VDFS] Mounting directory (recursive): {0}", path.toString());
auto onDirectory = [&](const bs::Path& p) {
bs::Path relative = p.getRelative(path);
REGOTH_LOG(Info, Uncategorized, "[VDFS] - {0}", relative.toString());
mInternal->fileIndex.mountFolder(p.toString().c_str());
return true;
};
enum
{
Recursive = true,
NonRecursive = false,
};
bs::FileSystem::iterate(path, nullptr, onDirectory, Recursive);
}
bool VirtualFileSystem::loadPackage(const bs::Path& package)
{
throwOnMissingInternalState();
if (mInternal->isFinalized)
{
REGOTH_THROW(InvalidStateException, "Cannot load packages on finalized file index.");
}
return mInternal->fileIndex.loadVDF(package.toString().c_str());
}
bs::Vector<bs::String> VirtualFileSystem::listAllFiles()
{
std::vector<std::string> allStl = mInternal->fileIndex.getKnownFiles();
bs::Vector<bs::String> all(allStl.size());
for (size_t i = 0; i < allStl.size(); i++)
{
all[i] = allStl[i].c_str();
// Internal file index will return the files in the casing they were stored in.
// To be consistent, convert them all to uppercase here.
bs::StringUtil::toUpperCase(all[i]);
}
return all;
}
bs::Vector<bs::String> REGoth::VirtualFileSystem::listByExtension(const bs::String& ext)
{
bs::Vector<bs::String> allFilesUpperCase = listAllFiles();
// Convert extension to UPPERCASE since all files returned by listAllFiles() are also
// uppercase. That way, we make the extension-parameter case insensitive.
bs::String extUpper = ext;
bs::StringUtil::toUpperCase(extUpper);
enum
{
RespectCase = false,
LowerCase = true,
};
bs::Vector<bs::String> result;
for (const auto& fileName : allFilesUpperCase)
{
// Respect case here since our only option is converting everything to lower case
// with endsWith(). Since all our input strings are known to be uppercase, we can
// just compare them without changing cases.
if (bs::StringUtil::endsWith(fileName, extUpper, RespectCase))
{
result.push_back(fileName);
}
}
return result;
}
bs::Vector<bs::UINT8> VirtualFileSystem::readFile(const bs::String& file) const
{
throwOnMissingInternalState();
if (!mInternal->isFinalized)
{
mInternal->finalizeFileIndex();
}
if (!mInternal->isReadyToReadFiles())
{
REGOTH_THROW(InvalidStateException, "VDFS is not ready to read files yet.");
}
std::vector<uint8_t> stlData;
mInternal->fileIndex.getFileData(file.c_str(), stlData);
// FIXME: Need some other way to get the file data so we don't have to copy the data here
return bs::Vector<bs::UINT8>(stlData.begin(), stlData.end());
}
bool REGoth::VirtualFileSystem::hasFile(const bs::String& file) const
{
if (!mInternal)
{
REGOTH_THROW(InvalidStateException,
"VDFS internal state not available, call setPathToEngineExecutable()");
}
return mInternal->fileIndex.hasFile(file.c_str());
}
void REGoth::VirtualFileSystem::throwIfFileIsMissing(const bs::String& file,
const bs::String& message) const
{
if (!hasFile(file))
{
if (message.empty())
{
REGOTH_THROW(
InvalidStateException,
bs::StringUtil::format("Expected file {0} inside VDFS, but it could not be found!", file));
}
else
{
REGOTH_THROW(InvalidStateException, message);
}
}
}
bool REGoth::VirtualFileSystem::hasFoundGameFiles() const
{
throwOnMissingInternalState();
return mInternal->fileIndex.getKnownFiles().size() > 0;
}
const VDFS::FileIndex& VirtualFileSystem::getFileIndex()
{
throwOnMissingInternalState();
if (!mInternal->isFinalized)
{
mInternal->finalizeFileIndex();
}
return mInternal->fileIndex;
}
void VirtualFileSystem::throwOnMissingInternalState() const
{
if (!mInternal)
{
REGOTH_THROW(InvalidStateException,
"VDFS internal state not available, call setPathToEngineExecutable()");
}
}
VirtualFileSystem& REGoth::gVirtualFileSystem()
{
static VirtualFileSystem vdfs;
return vdfs;
}
| 23.903226 | 101 | 0.687295 | KirmesBude |
c12c43a49f468d3824e69f180c6af93dcd98ce37 | 4,289 | hpp | C++ | include/ptg/HybridMultiFractal.hpp | bobbaluba/PTG | c5d18b78aa84174e42e20a7b0ab8468bf4f2136f | [
"Zlib"
] | 12 | 2016-01-15T15:44:54.000Z | 2021-02-01T08:10:38.000Z | include/ptg/HybridMultiFractal.hpp | bobbaluba/PTG | c5d18b78aa84174e42e20a7b0ab8468bf4f2136f | [
"Zlib"
] | null | null | null | include/ptg/HybridMultiFractal.hpp | bobbaluba/PTG | c5d18b78aa84174e42e20a7b0ab8468bf4f2136f | [
"Zlib"
] | 2 | 2017-07-15T12:20:36.000Z | 2018-05-02T21:17:31.000Z | /**
* @file HybridMultiFractal.hpp
* @date 12. nov. 2012
* @author Johan Klokkhammer Helsing
*/
#ifndef HYBRIDMULTIFRACTAL_HPP
#define HYBRIDMULTIFRACTAL_HPP
#include <ptg/Continuous2DSignal.hpp>
#include <vector>
namespace ptg {
/** @brief Fractal noise generated using hybrid fractional brownian motion
*
* As described in this paper:
* http://www8.cs.umu.se/kurser/TDBD12/HT01/papers/MusgraveTerrain00.pdf
*
* THIS IS THE DOCUMENTATION FOR FRACTIONAL BROWNIAN MOTION. The hybrid fractal is a slightly modified version
*
* The algorithm takes a Continuous2DSignal as its source to create a fractal noise
* The noise is scaled to different frequencies and amplitudes, and these are added together.
*
* The algorithm is an easy way to create more interesting noise out of simple smoothed white noise,
* such as Perlin noise or value noise.
*
* Complexity
* ----------
* The complexity depends greatly on the choice of noise function.
* If the noise function's complexity is f(n), the complexity of fbm is:
*
* THETA(WIDTH^2*octaves*f(n))
*
* Where octaves is the number "layers" added together. This will usually be a number between 3 and 9.
*
* Limitations and Artifacts when used as terrain
* ----------------------------------------------
* Depending on the choice of noise function, there may be a number of visible artifacts.
* If your noise signal is repeating over a relatively short period, there will be visible artifacts in
* the resulting terrain. The reason for this, is that when we are shading terrain, the diffuse lighting
* depends on the derivative of the terrain, and therefore small changes will be visible.
*
* To solve this, you might either:
* * Adjust gain so it's low enough that the highest octaves barely change the terrain values.
* * Reduce the number of octaves, so the terrain won't repeat itself too much in the visible distance.
* * Add a post-filter with diamond-square displacement to do the smallest levels of displacement,
* as diamond square doesn't repeat itself, even on the smallest layers.
* * Reduce specular/diffuse lighting and rely more on textures to show the tiniest bumps in the terrain.
*/
class HybridMultiFractal: public ptg::Continuous2DSignal {
public:
explicit HybridMultiFractal(unsigned int seed=0);
virtual ~HybridMultiFractal();
virtual float get(float x, float y);
virtual void onReSeed(unsigned int seed);
/** @brief Sets the base noise function for the algorithm
* suitable choices are ValueNoise or Perlin Noise
*/
virtual void setBaseNoise(Continuous2DSignal* signal){baseNoise=signal;}
/** @brief Set the "depth" of the fractal noise.
* Sets how many "layers" of noise we are going to add together.
* Typical values lie between 3 and 9.
*/
virtual void setOctaves(unsigned int octaves){this->octaves=octaves; initExponents();}
// @brief Gets number of octaves, see setOctaves
virtual unsigned int getOctaves() const {return octaves;}
/** @brief sets the lacunarity
* this is the relation between the frequency of succesive layers in fbm-like algorithms
*/
virtual void setLacunarity(float lacunarity){this->lacunarity=lacunarity; initExponents();}
virtual float getLacunarity() const {return lacunarity;}
/** @brief sets the offset. This value is added to the noise before multiplications
*
* Assuming the noise value varies from -1 to 1, 0.7 will probably be a decent value
*/
virtual void setOffset(float offset){this->offset=offset;}
virtual float getOffset() const {return offset;}
/** @brief sets the H value
*
* This value controls how the amplitude changes from octave to octave.
* A high value means the amplitude will decrease faster
* 0.25 will probably be a decent value
*/
virtual void setH(float H){this->H = H; initExponents();}
virtual float getH() const {return H;}
HybridMultiFractal(const HybridMultiFractal&) = default; //copies will share the same base noise, this means that seeding one, will seed both.
HybridMultiFractal & operator=(const HybridMultiFractal&) = default;
private:
void initExponents();
Continuous2DSignal* baseNoise;
unsigned int octaves;
float lacunarity;
float offset;
float H;
std::vector<float> exponents;
};
} // namespace ptg
#endif // HYBRIDMULTIFRACTAL_HPP
| 39.348624 | 143 | 0.743064 | bobbaluba |
c132c760ea22d8d2cdd1a7ff0b7ce971edc987fe | 2,054 | cpp | C++ | unitTest/matrixDecomps.cpp | akrodger/numples-cpp | 4f0cd7b5dd66251fd02189480f3917aaefcc53f4 | [
"MIT"
] | null | null | null | unitTest/matrixDecomps.cpp | akrodger/numples-cpp | 4f0cd7b5dd66251fd02189480f3917aaefcc53f4 | [
"MIT"
] | null | null | null | unitTest/matrixDecomps.cpp | akrodger/numples-cpp | 4f0cd7b5dd66251fd02189480f3917aaefcc53f4 | [
"MIT"
] | null | null | null | /*
* C Driver file Template by Bram Rodgers.
* Original Draft Dated: 25, Feb 2018
*/
/*
* Macros and Includes go here: (Some common ones listed)
*/
#include<stdio.h>
#include<stdlib.h>
#include"../src/numples.h"
#ifndef NULL
#define NULL 0
#endif
#define MIN_ALLOWED_ARGS 4
/*
* Function declarations go here:
*/
using namespace numples;
/*
* Template main:
*/
int main(int argc, char** argv){
// Variable Declarations:
// int, double, etc
// Pre Built argv parsing: (argv[0] is executable title. e.g. "./a.out")
char* pEnd = NULL; //Points to end of a parsed string
/*
* (intger) = atoi(argv[index]);
* (double) = strtod(argv[index], &pEnd);
* (long int) = strtol(argv[index], &pEnd, base_val)
*/
srand(time(NULL));
lapack_int m, n, numSV;//matrix dimensions and loop iterators.
if(argc < MIN_ALLOWED_ARGS){
printf("\nA small script to test the various matrix products.");
printf("\n===================================================");
printf("\n%s [m] [n] [numSV]",argv[0]);
printf("\nDoes a test of SVD, obtaining only numSV singular vectors,\n"
"and Schur Decomposition.\n");
exit(1);
}
m = (lapack_int) strtol(argv[1], &pEnd, 0);
n = (lapack_int) strtol(argv[2], &pEnd, 0);
numSV = (lapack_int) strtol(argv[3], &pEnd, 0);
Matrix A = Matrix(m , n, 'U');//generate uniform random matrix.
Matrix R, Z;//Schur decomposition matrices
Matrix U, sig, Vt;//SVD matrices
Matrix Resid;
double residNorm, traceVal;
A.svd(U, sig, Vt);
Resid = A - U * sig.diag() * Vt;
residNorm = Resid.norm2();
printf("\nSVD Residual: %le\n", residNorm);
Z = A.getLeftSV(numSV);
traceVal = (Z.transp() * U).trace();
residNorm = numSV - ABS(traceVal);
printf("\n%le\n",residNorm);
if(residNorm <= (double)numSV){
printf("\nGet Left Singular Vectors passed within eps_mach: 1\n");
}else{
printf("\nGet Left Singular Vectors failed within eps_mach: 0\n");
}
A.schur(Z,R);
Resid = A*Z - Z*R;
residNorm = Resid.norm2();
printf("\nSchur Residual: %le\n", residNorm);
printf("\n%s\n\n", argv[0]);
return 0;
}
| 28.527778 | 73 | 0.636319 | akrodger |
c13441334709fa1e0692b42be0dbe628a1e606fb | 2,290 | cpp | C++ | leviathan_config.cpp | bkovacev/levd | f942946f4db7f8c2bad14c5c7025ac303855ced7 | [
"MIT"
] | 1 | 2020-04-23T11:28:55.000Z | 2020-04-23T11:28:55.000Z | leviathan_config.cpp | bkovacev/levd | f942946f4db7f8c2bad14c5c7025ac303855ced7 | [
"MIT"
] | null | null | null | leviathan_config.cpp | bkovacev/levd | f942946f4db7f8c2bad14c5c7025ac303855ced7 | [
"MIT"
] | 1 | 2020-04-23T11:28:59.000Z | 2020-04-23T11:28:59.000Z | #include "leviathan_config.hpp"
#include <exception>
#include <algorithm>
#include <glog/logging.h>
#include <yaml-cpp/yaml.h>
// TODO: Cleaner normalization
LineFunction slope_function(const Point &a, const Point &b) {
const auto ys = b.y - a.y;
const auto xs = b.x - a.x;
if (xs == 0) {
throw std::runtime_error("Infinite slope detected");
}
const auto slope = ys / xs;
const auto bFac = b.y - (slope * b.x);
return [slope, bFac](int32_t x) {
const auto newY = (slope * x) + bFac;
// Normalize to a multiple of 5
const auto evenDiff = newY % 5;
return newY - evenDiff; // hit it on the nose == 0
};
}
std::map<int32_t, LineFunction> configure_profile(
const YAML::Node &fan_profile) {
CHECK(fan_profile.IsSequence()) << "Expecting a sequence of pairs";
const auto point_compare = [](const Point &p, const Point &u) {
return p.x > u.x;
};
std::vector<Point> dataPoints { Point(0, 30) };
for (const auto &i : fan_profile.as<std::vector<std::vector<uint32_t>>>()) {
CHECK(i.size() == 2) << "Expecting array of pairs for fan/pump profile";
CHECK(i.back() % 5 == 0) << "Fan/pump profile values must be divisible by 5";
dataPoints.emplace_back(i.front(), i.back());
}
dataPoints.emplace_back(100, 100);
std::sort(dataPoints.begin(), dataPoints.end(), point_compare);
std::map<int32_t, LineFunction> temp_to_slope;
for (auto i = 0; i < dataPoints.size() - 1; ++i) {
const Point &cur_pt = dataPoints[i];
const Point &next_pt = dataPoints[i + 1];
temp_to_slope[cur_pt.x] = slope_function(cur_pt, next_pt);
}
return temp_to_slope;
}
leviathan_config parse_config_file(const char *const path) {
leviathan_config options;
try {
YAML::Node config = YAML::LoadFile(path);
options.temp_source_ = stringToTempSource(config["temperature_source"].as<std::string>());
options.fan_profile_ = configure_profile(config["fan_profile"]);
options.pump_profile_ = config["pump_profile"] ? configure_profile(config["pump_profile"]) : options.fan_profile_;
options.main_color_ = config["main_color"].as<uint32_t>();
options.interval_ = config["interval"].as<uint32_t>();
} catch (std::exception &e) {
LOG(FATAL) << "Yaml parsing error: " << e.what();
}
return options;
}
| 37.540984 | 118 | 0.666376 | bkovacev |
c137b9f83b254eb1787e60740af4331570898fc8 | 12,019 | cpp | C++ | lib/src/AMRTools/NWOQuadCFInterp.cpp | rmrsk/Chombo-3.3 | f2119e396460c1bb19638effd55eb71c2b35119e | [
"BSD-3-Clause-LBNL"
] | 10 | 2018-02-01T20:57:36.000Z | 2022-03-17T02:57:49.000Z | lib/src/AMRTools/NWOQuadCFInterp.cpp | rmrsk/Chombo-3.3 | f2119e396460c1bb19638effd55eb71c2b35119e | [
"BSD-3-Clause-LBNL"
] | 19 | 2018-10-04T21:37:18.000Z | 2022-02-25T16:20:11.000Z | lib/src/AMRTools/NWOQuadCFInterp.cpp | rmrsk/Chombo-3.3 | f2119e396460c1bb19638effd55eb71c2b35119e | [
"BSD-3-Clause-LBNL"
] | 11 | 2019-01-12T23:33:32.000Z | 2021-08-09T15:19:50.000Z | #ifdef CH_LANG_CC
/*
* _______ __
* / ___/ / ___ __ _ / / ___
* / /__/ _ \/ _ \/ V \/ _ \/ _ \
* \___/_//_/\___/_/_/_/_.__/\___/
* Please refer to Copyright.txt, in Chombo's root directory.
*/
#endif
// #include <cstdio>
//this one has getNearPeriodic
#include "PiecewiseLinearFillPatch.H"
#include "NWOQuadCFInterp.H"
#include "IntVectSet.H"
#include "DebugOut.H"
#include "NamespaceHeader.H"
void
NWOQuadCFInterp::
define(/// layout at this level
const DisjointBoxLayout& a_thisDisjointBoxLayout,
/// layout at coarser level
const DisjointBoxLayout& a_coarserDisjointBoxLayout,
/// number of variables
const int& a_numStates,
/// problem domain on the coarser level
const ProblemDomain& a_coarseDomain,
/// refinement ratio between this level and the coarser level
const int& a_refineCoarse,
/// number of layers of ghost cells to fill by interpolation
const int& a_interpRadius)
{
// Cache data
m_numStates = a_numStates;
m_coarseDomain = a_coarseDomain;
m_refineCoarse = a_refineCoarse;
m_interpRadius = a_interpRadius;
m_layout = a_thisDisjointBoxLayout;
m_coarseLayout = a_coarserDisjointBoxLayout;
m_refineVect = m_refineCoarse * IntVect::Unit;
ProblemDomain fineDomain = refine(m_coarseDomain, m_refineVect);
coarsen(m_layoutCoarsened, m_layout, m_refineVect);
int coarseGhost = a_interpRadius/a_refineCoarse + 2;
m_coarsenedFineData.define(m_layoutCoarsened, m_numStates, coarseGhost*IntVect::Unit);
m_cfivs.define(m_layout);
for(DataIterator dit = m_layout.dataIterator(); dit.ok(); ++dit)
{
Box ghostBox = m_layout[dit()];
ghostBox.grow(a_interpRadius);
ghostBox &= fineDomain;
m_cfivs[dit].define(dit(), m_layout, ghostBox);
}
// Everything is defined now.
m_defined = true;
}
//////////////////////////////////////////////////////////////////////////////
void
NWOQuadCFInterp::
coarseFineInterp(/// interpolated solution on this level
LevelData<FArrayBox>& a_fineData,
/// solution on coarser level
const LevelData<FArrayBox>& a_coarseData,
/// starting coarse data component
int a_srcComp,
/// starting fine data component
int a_dstComp,
/// number of data components to interpolate
int a_numComp)
{
CH_assert(m_defined);
const Interval srcInterval(a_srcComp, a_srcComp + a_numComp-1);
const Interval dstInterval(a_dstComp, a_dstComp + a_numComp-1);
a_coarseData.copyTo(srcInterval,
m_coarsenedFineData,
dstInterval);
int ibox = 0;
for (DataIterator dit = m_layout.dataIterator();dit.ok(); ++dit)
{
interpOnPatch(a_fineData[dit()], m_coarsenedFineData[dit()], dit(), a_srcComp, a_dstComp, a_numComp);
ibox++;
}
}
//////////////////////////////////////////////////////////////////////////////
void
NWOQuadCFInterp::
homogeneousCoarseFineInterp(/// interpolated solution on this level
LevelData<FArrayBox>& a_fineData,
/// solution on coarser level
int a_srcComp,
/// starting fine data component
int a_dstComp,
/// number of data components to interpolate
int a_numComp)
{
CH_assert(m_defined);
for(DataIterator dit = m_coarsenedFineData.dataIterator(); dit.ok(); ++dit)
{
m_coarsenedFineData[dit()].setVal(0.);
}
for (DataIterator dit = m_layout.dataIterator();dit.ok(); ++dit)
{
interpOnPatch(a_fineData[dit()], m_coarsenedFineData[dit()], dit(), a_srcComp, a_dstComp, a_numComp);
}
}
/////////////
void
NWOQuadCFInterp::
interpOnPatch(FArrayBox& a_fineData,
const FArrayBox& a_coarseData,
const DataIndex& a_dit,
int a_srcComp,
int a_dstComp,
int a_numComp)
{
const IntVectSet& cfivsFine = m_cfivs[a_dit].getIVS();
//dumpIVS(&cfivsFine);
Real dxFine = 1;
Real dxCoar = m_refineCoarse;
for(IVSIterator ivsit(cfivsFine); ivsit.ok(); ++ivsit)
{
const IntVect& ivFine = ivsit();
int ideb = 0;
if((ivFine[0]==16) && (ivFine[1]==8))
{
ideb = 1;
}
IntVect ivCoar = coarsen(ivFine, m_refineCoarse);
RealVect fineLoc, coarLoc;
for(int idir = 0; idir < SpaceDim; idir++)
{
fineLoc[idir] = dxFine*(ivFine[idir] + 0.5);
coarLoc[idir] = dxCoar*(ivCoar[idir] + 0.5);
}
for(int icomp = 0; icomp < a_numComp; icomp++)
{
int srcComp = a_srcComp + icomp;
int dstComp = a_dstComp + icomp;
RealVect firstDerivs, secondDerivs, mixedDerivs;
getDerivs(firstDerivs, secondDerivs, mixedDerivs,
a_coarseData, ivCoar, dxCoar, icomp);
Real coarValue = a_coarseData(ivCoar, srcComp);
RealVect distance = fineLoc - coarLoc;
Real fineValue;
extrapolateValue(fineValue, coarValue, firstDerivs, secondDerivs, mixedDerivs, distance);
a_fineData(ivFine, dstComp) = fineValue;
}
}
}
void
NWOQuadCFInterp::
getDerivs(RealVect& firstDerivs,
RealVect& secondDerivs,
RealVect& mixedDerivs,
const FArrayBox & a_data,
const IntVect& a_ivCoar,
const Real & a_dx,
const int & a_icomp)
{
const IntVect& iv = a_ivCoar;
int icomp = a_icomp;
Real dx = a_dx;
//single direction derivs--use centered diffs if possible, one-sided otherwise
for(int idir = 0; idir < SpaceDim; idir++)
{
IntVect ivhi = iv + BASISV(idir);
IntVect ivlo = iv - BASISV(idir);
bool hasHi = m_coarseDomain.contains(ivhi);
bool hasLo = m_coarseDomain.contains(ivlo);
if(hasHi && hasLo)
{
firstDerivs[idir] = (a_data(ivhi, icomp) - a_data(ivlo, icomp))/(2.*a_dx);
secondDerivs[idir] = (a_data(ivhi, icomp) + a_data(ivlo, icomp) - 2*a_data(iv, icomp))/(a_dx*a_dx);
}
else if(hasHi)
{
IntVect ivVeryHi = ivhi + BASISV(idir);
firstDerivs[idir] = (a_data(ivhi, icomp) - a_data(iv , icomp))/(a_dx);
secondDerivs[idir] = (a_data(ivVeryHi, icomp) + a_data(iv , icomp) - 2*a_data(ivhi, icomp))/(a_dx*a_dx);
}
else if(hasLo)
{
IntVect ivVeryLo = ivlo - BASISV(idir);
firstDerivs[idir] = (a_data(iv , icomp) - a_data(ivlo, icomp))/(a_dx);
secondDerivs[idir] = (a_data(ivVeryLo, icomp) + a_data(iv , icomp) - 2*a_data(ivlo, icomp))/(a_dx*a_dx);
}
else
{
firstDerivs[idir] = 0;
secondDerivs[idir] = 0;
}
}
//now for that evil mixed deriv stuff --- 2d only has one, 3d has 3
//this is to keep from doing each pair twice
Vector<int> doneThisPair(SpaceDim, 0);
for(int idir = 0; idir < SpaceDim; idir++)
{
for(int jdir = 0; jdir < SpaceDim; jdir++)
{
if(idir != jdir)
{
int index = getMixedIndex(idir, jdir);
if(doneThisPair[index] == 0)
{
doneThisPair[index] = 1;
IntVect ivhiI = iv + BASISV(idir);
IntVect ivloI = iv - BASISV(idir);
IntVect ivhiJ = iv + BASISV(jdir);
IntVect ivloJ = iv - BASISV(jdir);
IntVect ivhiIhiJ = iv + BASISV(idir) + BASISV(jdir);
IntVect ivloIloJ = iv - BASISV(idir) - BASISV(jdir);
IntVect ivloIhiJ = iv - BASISV(idir) + BASISV(jdir);
IntVect ivhiIloJ = iv + BASISV(idir) - BASISV(jdir);
bool hasIvhiIhiJ = m_coarseDomain.contains(ivhiIhiJ);
bool hasIvloIloJ = m_coarseDomain.contains(ivloIloJ);
bool hasIvloIhiJ = m_coarseDomain.contains(ivloIhiJ);
bool hasIvhiIloJ = m_coarseDomain.contains(ivhiIloJ);
//just go through the corners and compute each mixed deriv that you have
Real derivSum = 0;
int numDerivs = 0;
if(hasIvhiIhiJ)
{
Real dathiIhiJ = a_data(ivhiIhiJ, icomp);
Real dathiI = a_data(ivhiI , icomp);
Real dathiJ = a_data(ivhiJ , icomp);
Real datcen = a_data(iv , icomp);
Real mixedD = ((dathiIhiJ - dathiJ) - (dathiI - datcen))/dx/dx;
derivSum += mixedD;
numDerivs++;
}
if(hasIvloIloJ)
{
Real datloIloJ = a_data(ivloIloJ, icomp);
Real datloI = a_data(ivloI , icomp);
Real datloJ = a_data(ivloJ , icomp);
Real datcen = a_data(iv , icomp);
Real mixedD = ((datcen - datloI) - (datloJ - datloIloJ))/dx/dx;
derivSum += mixedD;
numDerivs++;
}
if(hasIvhiIloJ)
{
Real dathiIloJ = a_data(ivhiIloJ, icomp);
Real dathiI = a_data(ivhiI , icomp);
Real datloJ = a_data(ivloJ , icomp);
Real datcen = a_data(iv , icomp);
Real mixedD = ((dathiI - datcen) - (dathiIloJ - datloJ))/dx/dx;
derivSum += mixedD;
numDerivs++;
}
if(hasIvloIhiJ)
{
Real datloIhiJ = a_data(ivloIhiJ, icomp);
Real datloI = a_data(ivloI , icomp);
Real dathiJ = a_data(ivhiJ , icomp);
Real datcen = a_data(iv , icomp);
Real mixedD = ((dathiJ - datloIhiJ) - (datcen - datloI))/dx/dx;
derivSum += mixedD;
numDerivs++;
}
Real derivAvg = 0;
if(numDerivs > 0)
{
derivAvg = derivSum/numDerivs;
}
mixedDerivs[index] = derivAvg;
}
}
}
}
}
void
NWOQuadCFInterp::
extrapolateValue(Real & a_fineValue,
const Real & a_coarValue,
const RealVect & a_firstDerivs,
const RealVect & a_secondDerivs,
const RealVect & a_mixedDerivs,
const RealVect & a_distance)
{
a_fineValue = a_coarValue;
//add in first and second derivative contributions
for(int idir = 0; idir < SpaceDim; idir++)
{
Real dx = a_distance[idir];
a_fineValue += dx*a_firstDerivs[idir];
a_fineValue += (dx*dx/2.)*a_secondDerivs[idir];
}
//now for the evil mixed derivatives
#if CH_SPACEDIM==2
Real dxdy = a_distance[0]*a_distance[1];
a_fineValue += dxdy*a_mixedDerivs[0];
#else
for(int iindex = 0; iindex < SpaceDim; iindex++)
{
int idir, jdir;
getMixedDerivDirections(idir, jdir, iindex);
Real dx = a_distance[idir];
Real dy = a_distance[jdir];
a_fineValue += dx*dy*a_mixedDerivs[iindex];
}
#endif
}
#include "NamespaceFooter.H"
| 35.877612 | 116 | 0.52234 | rmrsk |
c13b20b4c5f957ca9facceae8d1b9ec3b149b080 | 225 | inl | C++ | node_modules/lzz-gyp/lzz-source/gram_Visitor.inl | SuperDizor/dizornator | 9f57dbb3f6af80283b4d977612c95190a3d47900 | [
"ISC"
] | 3 | 2019-09-18T16:44:33.000Z | 2021-03-29T13:45:27.000Z | node_modules/lzz-gyp/lzz-source/gram_Visitor.inl | SuperDizor/dizornator | 9f57dbb3f6af80283b4d977612c95190a3d47900 | [
"ISC"
] | null | null | null | node_modules/lzz-gyp/lzz-source/gram_Visitor.inl | SuperDizor/dizornator | 9f57dbb3f6af80283b4d977612c95190a3d47900 | [
"ISC"
] | 2 | 2019-03-29T01:06:38.000Z | 2019-09-18T16:44:34.000Z | // gram_Visitor.inl
//
#ifdef LZZ_ENABLE_INLINE
#define LZZ_INLINE inline
#else
#define LZZ_INLINE
#endif
namespace gram
{
LZZ_INLINE Visitor::Visitor (bool slippery)
: m_slippery (slippery)
{}
}
#undef LZZ_INLINE
| 14.0625 | 45 | 0.737778 | SuperDizor |
c13dc984026548a60265e21d62c2b5e041f979b1 | 1,462 | cpp | C++ | NULL Engine/Source/Component.cpp | BarcinoLechiguino/NULL_Engine | f2abecb44bee45b7cbf2d5b53609d79d38ecc5a3 | [
"MIT"
] | 4 | 2020-11-29T12:28:31.000Z | 2021-06-08T17:32:56.000Z | NULL Engine/Source/Component.cpp | BarcinoLechiguino/NULL_Engine | f2abecb44bee45b7cbf2d5b53609d79d38ecc5a3 | [
"MIT"
] | null | null | null | NULL Engine/Source/Component.cpp | BarcinoLechiguino/NULL_Engine | f2abecb44bee45b7cbf2d5b53609d79d38ecc5a3 | [
"MIT"
] | 4 | 2020-11-01T17:06:32.000Z | 2021-01-09T16:58:50.000Z | #include "Log.h"
#include "Random.h"
#include "VariableTypedefs.h"
#include "GameObject.h"
#include "Component.h"
Component::Component(GameObject* owner, COMPONENT_TYPE type, bool is_active) :
id (Random::LCG::GetRandomUint()),
type (type),
owner (owner),
is_active (is_active)
{
}
Component::~Component()
{
}
bool Component::Update()
{
return true;
}
bool Component::CleanUp()
{
return true;
}
bool Component::SaveState(ParsonNode& root) const
{
return true;
}
bool Component::LoadState(ParsonNode& root)
{
return true;
}
// --- COMPONENT METHODS ---
const char* Component::GetNameFromType() const
{
switch (type)
{
case COMPONENT_TYPE::NONE: { return "NONE"; } break;
case COMPONENT_TYPE::TRANSFORM: { return "Transform"; } break;
case COMPONENT_TYPE::MESH: { return "Mesh"; } break;
case COMPONENT_TYPE::MATERIAL: { return "Material"; } break;
case COMPONENT_TYPE::LIGHT: { return "Light"; } break;
case COMPONENT_TYPE::CAMERA: { return "Camera"; } break;
case COMPONENT_TYPE::ANIMATOR: { return "Animator"; } break;
case COMPONENT_TYPE::ANIMATION: { return "Animation"; } break;
}
return "NONE";
}
uint32 Component::GetID() const
{
return id;
}
void Component::ResetID()
{
id = Random::LCG::GetRandomUint();
}
bool Component::IsActive() const
{
return is_active;
}
void Component::SetIsActive(const bool& set_to)
{
is_active = set_to;
}
GameObject* Component::GetOwner() const
{
return owner;
} | 17.404762 | 78 | 0.69015 | BarcinoLechiguino |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.