hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequencelengths
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
sequencelengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequencelengths
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
4f1d9e36be378fb394dc7da2e912f46bf7c71a18
3,639
cpp
C++
button_events_game.cpp
darkoppressor/cosmic-runner
feeb1154ffb1af9de2a34e1b418a6432500176c3
[ "MIT" ]
null
null
null
button_events_game.cpp
darkoppressor/cosmic-runner
feeb1154ffb1af9de2a34e1b418a6432500176c3
[ "MIT" ]
null
null
null
button_events_game.cpp
darkoppressor/cosmic-runner
feeb1154ffb1af9de2a34e1b418a6432500176c3
[ "MIT" ]
null
null
null
/* Copyright (c) 2012 Cheese and Bacon Games, LLC */ /* This file is licensed under the MIT License. */ /* See the file docs/LICENSE.txt for the full license text. */ #include "game.h" #include "android_leaderboard.h" #include <button_events.h> #include <window_manager.h> #include <game_manager.h> #include <android.h> #include <gui_manager.h> #include <boost/algorithm/string.hpp> using namespace std; bool Button_Events::handle_button_event_game (string button_event, Window* parent_window, bool& window_opened_on_top) { if (button_event == "game_over") { Window_Manager::close_all_windows(); if (Game::is_score_high()) { Window_Manager::get_window("input_name")->toggle_on(); GUI_Manager::confirm_gui_object(); } else { Android_Leaderboard::submit_highscore(Android_Leaderboard::HIGH_SCORES, Game::get_score()); Android_Leaderboard::submit_highscore(Android_Leaderboard::BEST_KILL_COUNT, Game::get_kills()); Android_Leaderboard::submit_highscore(Android_Leaderboard::DEBRIS_DODGED, Game::get_dodges()); Game_Manager::stop(); Window_Manager::get_window("main_menu")->toggle_on(); Window_Manager::get_window("high_scores")->toggle_on(); } window_opened_on_top = true; return true; } else if (button_event == "gpg_toggle_sign_in") { if (Android::gpg_is_silent_sign_in_attempt_complete()) { if (!Android::gpg_is_signed_in()) { Android::gpg_sign_in(); Game::android_gpg_signing_in(); } else { Android::gpg_sign_out(); } } return true; } else if (boost::algorithm::starts_with(button_event, "gpg_show_leaderboard_")) { boost::algorithm::erase_first(button_event, "gpg_show_leaderboard_"); if (Android::gpg_is_signed_in()) { Android::gpg_show_leaderboard(button_event); } return true; } else if (button_event == "gpg_show_all_leaderboards") { if (Android::gpg_is_signed_in()) { Android::gpg_show_all_leaderboards(); } return true; } else if (button_event == "gpg_show_achievements") { if (Android::gpg_is_signed_in()) { Android::gpg_show_achievements(); } return true; } else if (button_event == "name") { Window_Manager::close_all_windows(); if (parent_window != 0) { Game::add_high_score(parent_window->get_info_text(0)); Android_Leaderboard::submit_highscore(Android_Leaderboard::HIGH_SCORES, Game::get_score()); Android_Leaderboard::submit_highscore(Android_Leaderboard::BEST_KILL_COUNT, Game::get_kills()); Android_Leaderboard::submit_highscore(Android_Leaderboard::DEBRIS_DODGED, Game::get_dodges()); } Game_Manager::stop(); Window_Manager::get_window("main_menu")->toggle_on(); Window_Manager::get_window("high_scores")->toggle_on(); window_opened_on_top = true; return true; } else if (boost::algorithm::starts_with(button_event, "select_upgrade_")) { boost::algorithm::erase_first(button_event, "select_upgrade_"); Window_Manager::close_all_windows(); Game::player_add_upgrade(button_event); Game::complete_contract(); return true; } else if (button_event == "skip_upgrade") { Window_Manager::close_all_windows(); Game::restore_hull_from_contract(); Game::complete_contract(); return true; } return false; }
31.643478
119
0.646057
darkoppressor
4f1ee99281ef141d42a038f41cd1ddb9cc86f312
26,803
cpp
C++
src/core/Variant.cpp
WilliamTambellini/godopy
7b4142ddf7acafa66e1b2b201afa5fa37a4c7f4e
[ "MIT" ]
null
null
null
src/core/Variant.cpp
WilliamTambellini/godopy
7b4142ddf7acafa66e1b2b201afa5fa37a4c7f4e
[ "MIT" ]
null
null
null
src/core/Variant.cpp
WilliamTambellini/godopy
7b4142ddf7acafa66e1b2b201afa5fa37a4c7f4e
[ "MIT" ]
null
null
null
#include "Variant.hpp" #include <gdnative/variant.h> #include "CoreTypes.hpp" #include "Defs.hpp" #include "GodotGlobal.hpp" #include "Object.hpp" #include <iostream> #include <stdexcept> #ifndef NO_IMPORT_ARRAY #define NO_IMPORT_ARRAY #endif #include "PythonGlobal.hpp" #include <_lib/godot/core/types.hpp> namespace godot { Variant::Variant() { godot::api->godot_variant_new_nil(&_godot_variant); } Variant::Variant(const Variant &v) { godot::api->godot_variant_new_copy(&_godot_variant, &v._godot_variant); } Variant::Variant(bool p_bool) { godot::api->godot_variant_new_bool(&_godot_variant, p_bool); } Variant::Variant(signed int p_int) // real one { godot::api->godot_variant_new_int(&_godot_variant, p_int); } Variant::Variant(unsigned int p_int) { godot::api->godot_variant_new_uint(&_godot_variant, p_int); } Variant::Variant(signed short p_short) // real one { godot::api->godot_variant_new_int(&_godot_variant, (int)p_short); } Variant::Variant(int64_t p_char) // real one { godot::api->godot_variant_new_int(&_godot_variant, p_char); } Variant::Variant(uint64_t p_char) { godot::api->godot_variant_new_uint(&_godot_variant, p_char); } Variant::Variant(float p_float) { godot::api->godot_variant_new_real(&_godot_variant, p_float); } Variant::Variant(double p_double) { godot::api->godot_variant_new_real(&_godot_variant, p_double); } Variant::Variant(const String &p_string) { godot::api->godot_variant_new_string(&_godot_variant, (godot_string *)&p_string); } Variant::Variant(const char *const p_cstring) { String s = String(p_cstring); godot::api->godot_variant_new_string(&_godot_variant, (godot_string *)&s); } Variant::Variant(const wchar_t *p_wstring) { String s = p_wstring; godot::api->godot_variant_new_string(&_godot_variant, (godot_string *)&s); } Variant::Variant(const Vector2 &p_vector2) { godot::api->godot_variant_new_vector2(&_godot_variant, (godot_vector2 *)&p_vector2); } Variant::Variant(const Rect2 &p_rect2) { godot::api->godot_variant_new_rect2(&_godot_variant, (godot_rect2 *)&p_rect2); } Variant::Variant(const Vector3 &p_vector3) { godot::api->godot_variant_new_vector3(&_godot_variant, (godot_vector3 *)&p_vector3); } Variant::Variant(const Plane &p_plane) { godot::api->godot_variant_new_plane(&_godot_variant, (godot_plane *)&p_plane); } Variant::Variant(const AABB &p_aabb) { godot::api->godot_variant_new_aabb(&_godot_variant, (godot_aabb *)&p_aabb); } Variant::Variant(const Quat &p_quat) { godot::api->godot_variant_new_quat(&_godot_variant, (godot_quat *)&p_quat); } Variant::Variant(const Basis &p_transform) { godot::api->godot_variant_new_basis(&_godot_variant, (godot_basis *)&p_transform); } Variant::Variant(const Transform2D &p_transform) { godot::api->godot_variant_new_transform2d(&_godot_variant, (godot_transform2d *)&p_transform); } Variant::Variant(const Transform &p_transform) { godot::api->godot_variant_new_transform(&_godot_variant, (godot_transform *)&p_transform); } Variant::Variant(const Color &p_color) { godot::api->godot_variant_new_color(&_godot_variant, (godot_color *)&p_color); } Variant::Variant(const NodePath &p_path) { godot::api->godot_variant_new_node_path(&_godot_variant, (godot_node_path *)&p_path); } Variant::Variant(const RID &p_rid) { godot::api->godot_variant_new_rid(&_godot_variant, (godot_rid *)&p_rid); } Variant::Variant(const Object *p_object) { if (p_object) godot::api->godot_variant_new_object(&_godot_variant, p_object->_owner); else godot::api->godot_variant_new_nil(&_godot_variant); } Variant::Variant(const Dictionary &p_dictionary) { godot::api->godot_variant_new_dictionary(&_godot_variant, (godot_dictionary *)&p_dictionary); } Variant::Variant(const Array &p_array) { godot::api->godot_variant_new_array(&_godot_variant, (godot_array *)&p_array); } Variant::Variant(const PoolByteArray &p_raw_array) { godot::api->godot_variant_new_pool_byte_array(&_godot_variant, (godot_pool_byte_array *)&p_raw_array); } Variant::Variant(const PoolIntArray &p_int_array) { godot::api->godot_variant_new_pool_int_array(&_godot_variant, (godot_pool_int_array *)&p_int_array); } Variant::Variant(const PoolRealArray &p_real_array) { godot::api->godot_variant_new_pool_real_array(&_godot_variant, (godot_pool_real_array *)&p_real_array); } Variant::Variant(const PoolStringArray &p_string_array) { godot::api->godot_variant_new_pool_string_array(&_godot_variant, (godot_pool_string_array *)&p_string_array); } Variant::Variant(const PoolVector2Array &p_vector2_array) { godot::api->godot_variant_new_pool_vector2_array(&_godot_variant, (godot_pool_vector2_array *)&p_vector2_array); } Variant::Variant(const PoolVector3Array &p_vector3_array) { godot::api->godot_variant_new_pool_vector3_array(&_godot_variant, (godot_pool_vector3_array *)&p_vector3_array); } Variant::Variant(const PoolColorArray &p_color_array) { godot::api->godot_variant_new_pool_color_array(&_godot_variant, (godot_pool_color_array *)&p_color_array); } Variant::Variant(const PyObject *p_python_object) { if (p_python_object == Py_None) { // Py_XDECREF(p_python_object); // XXX godot::api->godot_variant_new_nil(&_godot_variant); } else if (PyBool_Check(p_python_object)) { godot::api->godot_variant_new_bool(&_godot_variant, PyLong_AsLong((PyObject *)p_python_object)); } else if (PyLong_Check(p_python_object)) { godot::api->godot_variant_new_int(&_godot_variant, PyLong_AsLong((PyObject *)p_python_object)); } else if (PyFloat_Check(p_python_object)) { const double p_double = PyFloat_AsDouble((PyObject *)p_python_object); godot::api->godot_variant_new_real(&_godot_variant, p_double); } else if (PyUnicode_Check(p_python_object) || PyBytes_Check(p_python_object)) { String s = String(p_python_object); godot::api->godot_variant_new_string(&_godot_variant, (godot_string *)&s); } else if (PyByteArray_Check(p_python_object)) { godot_pool_byte_array *p; godot::api->godot_pool_byte_array_new(p); godot::api->godot_pool_byte_array_resize(p, PyByteArray_GET_SIZE(p_python_object)); godot_pool_byte_array_write_access *_write_access = godot::api->godot_pool_byte_array_write(p); const uint8_t *ptr = godot::api->godot_pool_byte_array_write_access_ptr(_write_access); memcpy((void *)ptr, (void *)PyByteArray_AS_STRING(p_python_object), PyByteArray_GET_SIZE(p_python_object)); godot::api->godot_variant_new_pool_byte_array(&_godot_variant, p); godot::api->godot_pool_byte_array_write_access_destroy(_write_access); godot::api->godot_pool_byte_array_destroy(p); } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_AABB) { godot_aabb *p = _python_wrapper_to_aabb((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_aabb(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Array) { godot_array *p = _python_wrapper_to_godot_array((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_array(&_godot_variant, p); } else { godot::api->godot_variant_new_nil(&_godot_variant); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Basis) { godot_basis *p = _python_wrapper_to_basis((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_basis(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Color) { godot_color *p = _python_wrapper_to_color((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_color(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Dictionary) { godot_dictionary *p = _python_wrapper_to_godot_dictionary((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_dictionary(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_NodePath) { godot_node_path *p = _python_wrapper_to_nodepath((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_node_path(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Plane) { godot_plane *p = _python_wrapper_to_plane((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_plane(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolByteArray) { godot_pool_byte_array *p = _python_wrapper_to_poolbytearray((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_byte_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolIntArray) { godot_pool_int_array *p = _python_wrapper_to_poolintarray((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_int_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolRealArray) { godot_pool_real_array *p = _python_wrapper_to_poolrealarray((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_real_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolStringArray) { godot_pool_string_array *p = _python_wrapper_to_poolstringarray((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_string_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolVector2Array) { godot_pool_vector2_array *p = _python_wrapper_to_poolvector2array((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_vector2_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolVector3Array) { godot_pool_vector3_array *p = _python_wrapper_to_poolvector3array((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_vector3_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolColorArray) { godot_pool_color_array *p = _python_wrapper_to_poolcolorarray((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_color_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Quat) { godot_quat *p = _python_wrapper_to_quat((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_quat(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Rect2) { godot_rect2 *p = _python_wrapper_to_rect2((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_rect2(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_RID) { godot_rid *p = _python_wrapper_to_rid((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_rid(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_String) { godot_string *p = _python_wrapper_to_godot_string((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_string(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Transform) { godot_transform *p = _python_wrapper_to_transform((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_transform(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Transform2D) { godot_transform2d *p = _python_wrapper_to_transform2d((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_transform2d(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Vector2) { godot_vector2 *p = _python_wrapper_to_vector2((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_vector2(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Vector3) { godot_vector3 *p = _python_wrapper_to_vector3((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_vector3(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (PyObject_IsInstance((PyObject *)p_python_object, (PyObject *)PyGodotType__Wrapped)) { godot_object *p = _cython_binding_to_godot_object((PyObject *)p_python_object); godot::api->godot_variant_new_object(&_godot_variant, p); // TODO: dict -> Dictionary, other iterables -> Array, array.Array -> PoolArray*, numpy.array -> PoolArray* } else if (PyArray_Check((PyObject *)p_python_object)) { PyArrayObject *arr = (PyArrayObject *)p_python_object; if (PyArray_NDIM(arr) == 1 && PyArray_TYPE(arr) == NPY_UINT8) { PoolByteArray _arr = PoolByteArray(arr); godot::api->godot_variant_new_pool_byte_array(&_godot_variant, (godot_pool_byte_array *)&_arr); } else if (PyArray_NDIM(arr) == 1 && PyArray_ISINTEGER(arr)) { PoolIntArray _arr(arr); godot::api->godot_variant_new_pool_int_array(&_godot_variant, (godot_pool_int_array *)&_arr); } else if (PyArray_NDIM(arr) == 1 && PyArray_ISFLOAT(arr)) { PoolRealArray _arr(arr); godot::api->godot_variant_new_pool_real_array(&_godot_variant, (godot_pool_real_array *)&_arr); } else if (PyArray_NDIM(arr) == 1 && PyArray_ISSTRING(arr)) { PoolStringArray _arr(arr); godot::api->godot_variant_new_pool_string_array(&_godot_variant, (godot_pool_string_array *)&_arr); } else if (PyArray_NDIM(arr) == 1) { Array _arr; for (int idx = 0; idx < PyArray_SIZE(arr); idx++) { PyObject *item = PyArray_GETITEM(arr, (const char *)PyArray_GETPTR1(arr, idx)); // TODO: Check NULL pointer _arr.append(Variant(item)); } godot::api->godot_variant_new_array(&_godot_variant, (godot_array *)&_arr); } else if (PyArray_NDIM(arr) == 2 && PyArray_ISNUMBER(arr) && PyArray_DIM(arr, 1) == 2) { PoolVector2Array _arr = PoolVector2Array(arr); godot::api->godot_variant_new_pool_vector2_array(&_godot_variant, (godot_pool_vector2_array *)&_arr); } else if (PyArray_NDIM(arr) == 2 && PyArray_ISNUMBER(arr) && PyArray_DIM(arr, 1) == 3) { PoolVector3Array _arr = PoolVector3Array(arr); godot::api->godot_variant_new_pool_vector3_array(&_godot_variant, (godot_pool_vector3_array *)&_arr); } else if (PyArray_NDIM(arr) == 2 && PyArray_ISNUMBER(arr) && PyArray_DIM(arr, 1) == 4) { PoolColorArray _arr = PoolColorArray(arr); godot::api->godot_variant_new_pool_color_array(&_godot_variant, (godot_pool_color_array *)&_arr); } else { throw std::invalid_argument("could not convert NumPy array"); } } else if (PySequence_Check((PyObject *)p_python_object)) { Array arr = Array(p_python_object); godot::api->godot_variant_new_array(&_godot_variant, (godot_array *)&arr); } else if (PyMapping_Check((PyObject *)p_python_object)) { Dictionary dict = Dictionary(p_python_object); godot::api->godot_variant_new_dictionary(&_godot_variant, (godot_dictionary *)&dict); } else if (PyIndex_Check((PyObject *)p_python_object)) { const Py_ssize_t p_num = PyNumber_AsSsize_t((PyObject *)p_python_object, NULL); godot::api->godot_variant_new_int(&_godot_variant, p_num); } else if (PyNumber_Check((PyObject *)p_python_object)) { PyObject *p_num = PyNumber_Float((PyObject *)p_python_object); const double p_double = PyFloat_AsDouble((PyObject *)p_num); godot::api->godot_variant_new_real(&_godot_variant, p_double); } else if (PyObject_CheckBuffer((PyObject *)p_python_object)) { throw std::invalid_argument("generic Python buffer support is not implemented yet"); } else { // raises ValueError in Cython/Python context throw std::invalid_argument("could not cast Python object to Godot Variant"); } } Variant &Variant::operator=(const Variant &v) { godot::api->godot_variant_new_copy(&_godot_variant, &v._godot_variant); return *this; } Variant::operator bool() const { return booleanize(); } Variant::operator signed int() const { return godot::api->godot_variant_as_int(&_godot_variant); } Variant::operator unsigned int() const // this is the real one { return godot::api->godot_variant_as_uint(&_godot_variant); } Variant::operator signed short() const { return godot::api->godot_variant_as_int(&_godot_variant); } Variant::operator unsigned short() const { return godot::api->godot_variant_as_uint(&_godot_variant); } Variant::operator signed char() const { return godot::api->godot_variant_as_int(&_godot_variant); } Variant::operator unsigned char() const { return godot::api->godot_variant_as_uint(&_godot_variant); } Variant::operator int64_t() const { return godot::api->godot_variant_as_int(&_godot_variant); } Variant::operator uint64_t() const { return godot::api->godot_variant_as_uint(&_godot_variant); } Variant::operator wchar_t() const { return godot::api->godot_variant_as_int(&_godot_variant); } Variant::operator float() const { return godot::api->godot_variant_as_real(&_godot_variant); } Variant::operator double() const { return godot::api->godot_variant_as_real(&_godot_variant); } Variant::operator String() const { String ret; *(godot_string *)&ret = godot::api->godot_variant_as_string(&_godot_variant); return ret; } Variant::operator Vector2() const { godot_vector2 s = godot::api->godot_variant_as_vector2(&_godot_variant); return *(Vector2 *)&s; } Variant::operator Rect2() const { godot_rect2 s = godot::api->godot_variant_as_rect2(&_godot_variant); return *(Rect2 *)&s; } Variant::operator Vector3() const { godot_vector3 s = godot::api->godot_variant_as_vector3(&_godot_variant); return *(Vector3 *)&s; } Variant::operator Plane() const { godot_plane s = godot::api->godot_variant_as_plane(&_godot_variant); return *(Plane *)&s; } Variant::operator AABB() const { godot_aabb s = godot::api->godot_variant_as_aabb(&_godot_variant); return *(AABB *)&s; } Variant::operator Quat() const { godot_quat s = godot::api->godot_variant_as_quat(&_godot_variant); return *(Quat *)&s; } Variant::operator Basis() const { godot_basis s = godot::api->godot_variant_as_basis(&_godot_variant); return *(Basis *)&s; } Variant::operator Transform() const { godot_transform s = godot::api->godot_variant_as_transform(&_godot_variant); return *(Transform *)&s; } Variant::operator Transform2D() const { godot_transform2d s = godot::api->godot_variant_as_transform2d(&_godot_variant); return *(Transform2D *)&s; } Variant::operator Color() const { godot_color s = godot::api->godot_variant_as_color(&_godot_variant); return *(Color *)&s; } Variant::operator NodePath() const { NodePath ret; *(godot_node_path *)&ret = godot::api->godot_variant_as_node_path(&_godot_variant); return ret; } Variant::operator RID() const { godot_rid s = godot::api->godot_variant_as_rid(&_godot_variant); return *(RID *)&s; } Variant::operator Dictionary() const { Dictionary ret; *(godot_dictionary *)&ret = godot::api->godot_variant_as_dictionary(&_godot_variant); return ret; } Variant::operator Array() const { Array ret; *(godot_array *)&ret = godot::api->godot_variant_as_array(&_godot_variant); return ret; } Variant::operator PoolByteArray() const { PoolByteArray ret; *(godot_pool_byte_array *)&ret = godot::api->godot_variant_as_pool_byte_array(&_godot_variant); return ret; } Variant::operator PoolIntArray() const { PoolIntArray ret; *(godot_pool_int_array *)&ret = godot::api->godot_variant_as_pool_int_array(&_godot_variant); return ret; } Variant::operator PoolRealArray() const { PoolRealArray ret; *(godot_pool_real_array *)&ret = godot::api->godot_variant_as_pool_real_array(&_godot_variant); return ret; } Variant::operator PoolStringArray() const { PoolStringArray ret; *(godot_pool_string_array *)&ret = godot::api->godot_variant_as_pool_string_array(&_godot_variant); return ret; } Variant::operator PoolVector2Array() const { PoolVector2Array ret; *(godot_pool_vector2_array *)&ret = godot::api->godot_variant_as_pool_vector2_array(&_godot_variant); return ret; } Variant::operator PoolVector3Array() const { PoolVector3Array ret; *(godot_pool_vector3_array *)&ret = godot::api->godot_variant_as_pool_vector3_array(&_godot_variant); return ret; } Variant::operator PoolColorArray() const { PoolColorArray ret; *(godot_pool_color_array *)&ret = godot::api->godot_variant_as_pool_color_array(&_godot_variant); return ret; } Variant::operator godot_object *() const { return godot::api->godot_variant_as_object(&_godot_variant); } Variant::operator PyObject *() const { PyObject *obj; switch (get_type()) { case NIL: obj = Py_None; break; case BOOL: obj = booleanize() ? Py_True : Py_False; break; case INT: obj = PyLong_FromSsize_t(godot::api->godot_variant_as_int(&_godot_variant)); break; case REAL: obj = PyFloat_FromDouble(godot::api->godot_variant_as_real(&_godot_variant)); break; case STRING: { String s = *this; obj = PyUnicode_FromWideChar(s.unicode_str(), s.length()); break; } case VECTOR2: { Vector2 cpp_obj = *this; return _vector2_to_python_wrapper(cpp_obj); } case RECT2: { Rect2 cpp_obj = *this; return _rect2_to_python_wrapper(cpp_obj); } case VECTOR3: { Vector3 cpp_obj = *this; return _vector3_to_python_wrapper(cpp_obj); } case TRANSFORM2D: { Transform2D cpp_obj = *this; return _transform2d_to_python_wrapper(cpp_obj); } case PLANE: { Plane cpp_obj = *this; return _plane_to_python_wrapper(cpp_obj); } case QUAT: { Quat cpp_obj = *this; return _quat_to_python_wrapper(cpp_obj); } case RECT3: { AABB cpp_obj = *this; return _aabb_to_python_wrapper(cpp_obj); } case BASIS: { Basis cpp_obj = *this; return _basis_to_python_wrapper(cpp_obj); } case TRANSFORM: { Transform cpp_obj = *this; return _transform_to_python_wrapper(cpp_obj); } case COLOR: { Color cpp_obj = *this; return _color_to_python_wrapper(cpp_obj); } case NODE_PATH: { NodePath cpp_obj = *this; return _nodepath_to_python_wrapper(cpp_obj); } case _RID: { RID cpp_obj = *this; return _rid_to_python_wrapper(cpp_obj); } case OBJECT: { godot_object *c_obj = godot::api->godot_variant_as_object(&_godot_variant); return _godot_object_to_python_binding(c_obj); } case DICTIONARY: { const Dictionary dict = *this; const Array keys = dict.keys(); obj = PyDict_New(); for (int i = 0; i < keys.size(); i++) { Variant _key = keys[i]; PyObject *key = _key; PyObject *val = dict[_key]; // TODO: Check unlikely NULL pointers PyDict_SetItem(obj, key, val); } break; } case ARRAY: { const Array arr = *this; obj = PyTuple_New(arr.size()); for (int i = 0; i < arr.size(); i++) { PyObject *item = arr[i]; // TODO: Check unlikely NULL pointers PyTuple_SET_ITEM(obj, i, item); } break; } case POOL_BYTE_ARRAY: { PoolByteArray cpp_obj = *this; return _poolbytearray_to_python_wrapper(cpp_obj); } case POOL_INT_ARRAY: { PoolIntArray cpp_obj = *this; return _poolintarray_to_python_wrapper(cpp_obj); } case POOL_REAL_ARRAY: { PoolRealArray cpp_obj = *this; return _poolrealarray_to_python_wrapper(cpp_obj); } case POOL_STRING_ARRAY: { PoolStringArray cpp_obj = *this; return _poolstringarray_to_numpy(cpp_obj); } case POOL_VECTOR2_ARRAY: { PoolVector2Array cpp_obj = *this; return _poolvector2array_to_python_wrapper(cpp_obj); } case POOL_VECTOR3_ARRAY: { PoolVector3Array cpp_obj = *this; return _poolvector3array_to_python_wrapper(cpp_obj); } case POOL_COLOR_ARRAY: { PoolColorArray cpp_obj = *this; return _poolcolorarray_to_python_wrapper(cpp_obj); } default: // raises ValueError in Cython/Python context throw std::invalid_argument("could not cast Python object to Godot Variant"); } Py_XINCREF(obj); return obj; } Variant::Type Variant::get_type() const { return (Type)godot::api->godot_variant_get_type(&_godot_variant); } Variant Variant::call(const String &method, const Variant **args, const int arg_count) { Variant v; *(godot_variant *)&v = godot::api->godot_variant_call(&_godot_variant, (godot_string *)&method, (const godot_variant **)args, arg_count, nullptr); return v; } bool Variant::has_method(const String &method) { return godot::api->godot_variant_has_method(&_godot_variant, (godot_string *)&method); } bool Variant::operator==(const Variant &b) const { return godot::api->godot_variant_operator_equal(&_godot_variant, &b._godot_variant); } bool Variant::operator!=(const Variant &b) const { return !(*this == b); } bool Variant::operator<(const Variant &b) const { return godot::api->godot_variant_operator_less(&_godot_variant, &b._godot_variant); } bool Variant::operator<=(const Variant &b) const { return (*this < b) || (*this == b); } bool Variant::operator>(const Variant &b) const { return !(*this <= b); } bool Variant::operator>=(const Variant &b) const { return !(*this < b); } bool Variant::hash_compare(const Variant &b) const { return godot::api->godot_variant_hash_compare(&_godot_variant, &b._godot_variant); } bool Variant::booleanize() const { return godot::api->godot_variant_booleanize(&_godot_variant); } Variant::~Variant() { godot::api->godot_variant_destroy(&_godot_variant); } } // namespace godot
32.607056
147
0.745066
WilliamTambellini
4f203c48428c692de98f2b0fdd812268d388a572
2,114
cc
C++
src/logging/log_stream.cc
xiw2-0/minids
46510205af0e0a6c14e9d360fc83e13cd45bcf9d
[ "MIT" ]
3
2020-06-09T02:31:43.000Z
2021-03-30T09:14:33.000Z
src/logging/log_stream.cc
xiw2-0/minids
46510205af0e0a6c14e9d360fc83e13cd45bcf9d
[ "MIT" ]
null
null
null
src/logging/log_stream.cc
xiw2-0/minids
46510205af0e0a6c14e9d360fc83e13cd45bcf9d
[ "MIT" ]
null
null
null
/// Copyright (c) 2020 xiw /// /// MIT License /// \author Wang Xi #include "logging/log_stream.h" #include <thread> #include <sstream> namespace logging { void LogStream::buf(char** p_buf, size_t* size) { *p_buf = buf_; *size = buf_pointer_; } LogStream &LogStream::operator<<(bool arg) { if(arg) append("true"); else append("false"); return *this; } LogStream &LogStream::operator<<(char arg) { char str[2] = {arg,'\0'}; append(str); return *this; } LogStream &LogStream::operator<<(int16_t arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(uint16_t arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(int32_t arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(uint32_t arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(int64_t arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(uint64_t arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(float arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(double arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(const char *arg) { append(arg); return *this; } LogStream &LogStream::operator<<(const string &arg) { append(arg.c_str()); return *this; } void LogStream::append(const char *s) { auto buf_left = buf_size_ - buf_pointer_ > 0 ? buf_size_ - buf_pointer_ : 0; buf_pointer_ += ::snprintf(buf_ + buf_pointer_, buf_left, "%s", s); } /// global output std::function<void(const char*, size_t)> g_out = [](const char* buf, size_t size){ ::fwrite(buf, 1, size, ::stdout); }; /// global flush std::function<void()> g_flush = [](){ ::fflush(::stdout); }; } // namespace logging
17.048387
82
0.644276
xiw2-0
4f2070c48921f7111b5e881d6412c44aa0dddea4
8,179
cpp
C++
LFFD_ncnn.cpp
Qengineering/LFFD-ncnn-Raspberry-Pi-4
edcb609603325ca97c6f02dcfefb32f937383279
[ "BSD-3-Clause" ]
2
2021-04-18T06:47:05.000Z
2021-06-16T09:52:44.000Z
LFFD_ncnn.cpp
Qengineering/LFFD-ncnn-Raspberry-Pi-4
edcb609603325ca97c6f02dcfefb32f937383279
[ "BSD-3-Clause" ]
null
null
null
LFFD_ncnn.cpp
Qengineering/LFFD-ncnn-Raspberry-Pi-4
edcb609603325ca97c6f02dcfefb32f937383279
[ "BSD-3-Clause" ]
null
null
null
#include "LFFD_ncnn.h" LFFD::LFFD(int scale_num, int num_thread_) { num_output_scales = scale_num; num_thread = num_thread_; if (num_output_scales == 5) { param_file_name = "symbol_10_320_20L_5scales_v2_deploy.param"; bin_file_name = "train_10_320_20L_5scales_v2_iter_1000000.bin"; receptive_field_list = { 20, 40, 80, 160, 320 }; receptive_field_stride = { 4, 8, 16, 32, 64 }; bbox_small_list = { 10, 20, 40, 80, 160 }; bbox_large_list = { 20, 40, 80, 160, 320 }; receptive_field_center_start = { 3, 7, 15, 31, 63 }; for (size_t i = 0; i < receptive_field_list.size(); i++) { constant.push_back(receptive_field_list[i] / 2); } output_blob_names = { "softmax0","conv8_3_bbox", "softmax1","conv11_3_bbox", "softmax2","conv14_3_bbox", "softmax3","conv17_3_bbox", "softmax4","conv20_3_bbox" }; } else if (num_output_scales == 8) { param_file_name = "symbol_10_560_25L_8scales_v1_deploy.param"; bin_file_name = "train_10_560_25L_8scales_v1_iter_1400000.bin"; receptive_field_list = { 15, 20, 40, 70, 110, 250, 400, 560 }; receptive_field_stride = { 4, 4, 8, 8, 16, 32, 32, 32 }; bbox_small_list = { 10, 15, 20, 40, 70, 110, 250, 400 }; bbox_large_list = { 15, 20, 40, 70, 110, 250, 400, 560 }; receptive_field_center_start = { 3, 3, 7, 7, 15, 31, 31, 31 }; for (size_t i = 0; i < receptive_field_list.size(); i++) { constant.push_back(receptive_field_list[i] / 2); } output_blob_names={ "softmax0","conv8_3_bbox", "softmax1","conv10_3_bbox", "softmax2","conv13_3_bbox", "softmax3","conv15_3_bbox", "softmax4","conv18_3_bbox", "softmax5","conv21_3_bbox", "softmax6","conv23_3_bbox", "softmax7","conv25_3_bbox" }; } lffd.load_param(param_file_name.data()); lffd.load_model(bin_file_name.data()); } LFFD::~LFFD() { lffd.clear(); } int LFFD::detect(ncnn::Mat& img, std::vector<FaceInfo>& face_list, int resize_h, int resize_w, float score_threshold, float nms_threshold, int top_k, std::vector<int> skip_scale_branch_list) { if (img.empty()) { std::cout << "image is empty ,please check!" << std::endl; return -1; } image_h = img.h; image_w = img.w; ncnn::Mat in; ncnn::resize_bilinear(img,in,resize_w,resize_h); float ratio_w=(float)image_w/in.w; float ratio_h=(float)image_h/in.h; ncnn::Mat ncnn_img = in; ncnn_img.substract_mean_normalize(mean_vals, norm_vals); std::vector<FaceInfo> bbox_collection; ncnn::Extractor ex = lffd.create_extractor(); ex.set_num_threads(num_thread); ex.input("data", ncnn_img); for (int i = 0; i <num_output_scales; i++) { ncnn::Mat conf; ncnn::Mat reg; ex.extract(output_blob_names[2*i].c_str(), conf); ex.extract(output_blob_names[2 * i+1].c_str(), reg); generateBBox(bbox_collection, conf, reg, score_threshold, conf.w, conf.h, in.w, in.h, i); } std::vector<FaceInfo> valid_input; get_topk_bbox(bbox_collection, valid_input, top_k); nms(valid_input, face_list, nms_threshold); for(size_t i=0;i<face_list.size();i++){ face_list[i].x1*=ratio_w; face_list[i].y1*=ratio_h; face_list[i].x2*=ratio_w; face_list[i].y2*=ratio_h; float w,h,maxSize; float cenx,ceny; w=face_list[i].x2-face_list[i].x1; h=face_list[i].y2-face_list[i].y1; maxSize = w > h ? w : h; cenx=face_list[i].x1+w/2; ceny=face_list[i].y1+h/2; face_list[i].x1=cenx-maxSize/2>0? cenx - maxSize / 2:0; face_list[i].y1=ceny-maxSize/2>0? ceny - maxSize / 2:0; face_list[i].x2=cenx+maxSize/2>image_w? image_w-1: cenx + maxSize / 2; face_list[i].y2=ceny+maxSize/2> image_h? image_h-1: ceny + maxSize / 2; } return 0; } void LFFD::generateBBox(std::vector<FaceInfo>& bbox_collection, ncnn::Mat score_map, ncnn::Mat box_map, float score_threshold, int fea_w, int fea_h, int cols, int rows, int scale_id) { float* RF_center_Xs = new float[fea_w]; float* RF_center_Xs_mat = new float[fea_w * fea_h]; float* RF_center_Ys = new float[fea_h]; float* RF_center_Ys_mat = new float[fea_h * fea_w]; for (int x = 0; x < fea_w; x++) { RF_center_Xs[x] = receptive_field_center_start[scale_id] + receptive_field_stride[scale_id] * x; } for (int x = 0; x < fea_h; x++) { for (int y = 0; y < fea_w; y++) { RF_center_Xs_mat[x * fea_w + y] = RF_center_Xs[y]; } } for (int x = 0; x < fea_h; x++) { RF_center_Ys[x] = receptive_field_center_start[scale_id] + receptive_field_stride[scale_id] * x; for (int y = 0; y < fea_w; y++) { RF_center_Ys_mat[x * fea_w + y] = RF_center_Ys[x]; } } float* x_lt_mat = new float[fea_h * fea_w]; float* y_lt_mat = new float[fea_h * fea_w]; float* x_rb_mat = new float[fea_h * fea_w]; float* y_rb_mat = new float[fea_h * fea_w]; //x-left-top float mid_value = 0; for (int j = 0; j < fea_h * fea_w; j++) { mid_value = RF_center_Xs_mat[j] - box_map.channel(0)[j] * constant[scale_id]; x_lt_mat[j] = mid_value < 0 ? 0 : mid_value; } //y-left-top for (int j = 0; j < fea_h * fea_w; j++) { mid_value = RF_center_Ys_mat[j] - box_map.channel(1)[j] * constant[scale_id]; y_lt_mat[j] = mid_value < 0 ? 0 : mid_value; } //x-right-bottom for (int j = 0; j < fea_h * fea_w; j++) { mid_value = RF_center_Xs_mat[j] - box_map.channel(2)[j] * constant[scale_id]; x_rb_mat[j] = mid_value > cols - 1 ? cols - 1 : mid_value; } //y-right-bottom for (int j = 0; j < fea_h * fea_w; j++) { mid_value = RF_center_Ys_mat[j] - box_map.channel(3)[j] * constant[scale_id]; y_rb_mat[j] = mid_value > rows - 1 ? rows - 1 : mid_value; } for (int k = 0; k < fea_h * fea_w; k++) { if (score_map.channel(0)[k] > score_threshold) { FaceInfo faceinfo; faceinfo.x1 = x_lt_mat[k]; faceinfo.y1 = y_lt_mat[k]; faceinfo.x2 = x_rb_mat[k]; faceinfo.y2 = y_rb_mat[k]; faceinfo.score = score_map[k]; faceinfo.area = (faceinfo.x2 - faceinfo.x1) * (faceinfo.y2 - faceinfo.y1); bbox_collection.push_back(faceinfo); } } delete[] RF_center_Xs; RF_center_Xs = NULL; delete[] RF_center_Ys; RF_center_Ys = NULL; delete[] RF_center_Xs_mat; RF_center_Xs_mat = NULL; delete[] RF_center_Ys_mat; RF_center_Ys_mat = NULL; delete[] x_lt_mat; x_lt_mat = NULL; delete[] y_lt_mat; y_lt_mat = NULL; delete[] x_rb_mat; x_rb_mat = NULL; delete[] y_rb_mat; y_rb_mat = NULL; } void LFFD::get_topk_bbox(std::vector<FaceInfo>& input, std::vector<FaceInfo>& output, int top_k) { std::sort(input.begin(), input.end(), [](const FaceInfo& a, const FaceInfo& b) { return a.score > b.score; }); if (input.size() > size_t(top_k)) { for (int k = 0; k < top_k; k++) { output.push_back(input[k]); } } else { output = input; } } void LFFD::nms(std::vector<FaceInfo>& input, std::vector<FaceInfo>& output, float threshold, int type) { if(input.empty()) return; std::sort(input.begin(), input.end(), [](const FaceInfo& a, const FaceInfo& b) { return a.score > b.score; }); int box_num = input.size(); std::vector<int> merged(box_num, 0); for (int i = 0; i < box_num; i++) { if (merged[i]) continue; output.push_back(input[i]); for (int j = i + 1; j < box_num; j++) { if (merged[j]) continue; float inner_x0 = input[i].x1 > input[j].x1 ? input[i].x1 : input[j].x1;//std::max(input[i].x1, input[j].x1); float inner_y0 = input[i].y1 > input[j].y1 ? input[i].y1 : input[j].y1; float inner_x1 = input[i].x2 < input[j].x2 ? input[i].x2 : input[j].x2; //bug fixed ,sorry float inner_y1 = input[i].y2 < input[j].y2 ? input[i].y2 : input[j].y2; float inner_h = inner_y1 - inner_y0 + 1; float inner_w = inner_x1 - inner_x0 + 1; if (inner_h <= 0 || inner_w <= 0) continue; float inner_area = inner_h * inner_w; float h1 = input[j].y2 - input[j].y1 + 1; float w1 = input[j].x2 - input[j].x1 + 1; float area1 = h1 * w1; float score= inner_area/area1; if (score > threshold) merged[j] = 1; } } }
30.981061
182
0.627461
Qengineering
4f21000a633dbc7b4704b27b1a2782af1fbd7e35
3,686
cpp
C++
streambox/test/test-join-2.cpp
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
3
2019-07-03T14:03:31.000Z
2021-12-19T10:18:49.000Z
streambox/test/test-join-2.cpp
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
6
2020-02-17T12:01:30.000Z
2021-12-09T22:02:33.000Z
streambox/test/test-join-2.cpp
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
2
2020-12-03T04:41:18.000Z
2021-01-11T21:44:42.000Z
/* #include<stdio.h> #include<assert.h> #include<iostream> #include<typeinfo> #include "Create.h" #include "Read.h" */ #include "core/Pipeline.h" //#include "TransformEvaluator.h" //#include "TransformEvaluate.h" #include "Source/UnboundedInMemEvaluator_Join.h" //#include "SimpleMapperEvaluator.h" #include "Join/JoinEvaluator1.h" #include "Sink/RecordBitmapBundleSinkEvaluator.h" #include <tuple> #include "test-common.h" /* * +--- SimpleMapper -- (KVPair)--\ * Unbound -(long)-> + Join --> (KVPai * +--- SimpleMapper -- (KVPair)--/ * */ /* template<class T> auto operator<<(std::ostream& os, const T& t) -> decltype(t.print(os), os) { t.print(os); return os; } */ template<class T> using BundleT = RecordBitmapBundle<T>; #ifdef DEBUG pipeline_config config = { .records_per_interval = 1000 * 1000, .target_tput = (1000 * 500), .record_size = sizeof(long), //.input_file = "/ssd/1g.txt", .input_file = "/tmp/test-digit.txt", }; #else pipeline_config config = { .records_per_interval = 1000 * 1000, //.target_tput = (10 * 1000 * 1000), .target_tput = 2000 * 1000, //k2: 2000 should be fine .record_size = sizeof(long), //.input_file = "/ssd/1g.txt", .input_file = "/tmp/test-digit.txt", }; #endif int main(int ac, char *av[]) { parse_options(ac, av, &config); print_config(); // create a new Bounded transform //UnboundedInMem<long, BundleT> unbound ("[unbounded]", 50, 0); //UnboundedInMem_Join<long, BundleT> unbound ("[unbounded]", UnboundedInMem_Join unbound ("[unbounded]", config.input_file.c_str(), config.records_per_interval , /* records per wm interval */ config.target_tput, /* target tput (rec/sec) */ config.record_size, 0 //XXX session_gap_ms = ???? ); // create a new pipeline Pipeline* p = Pipeline::create(NULL); /* vector<PCollection*> o2 = p->apply2(&unbound); o2[0]->_name = "src_out0"; o2[1]->_name = "src_out1"; SimpleMapper<long, pair<long, long>> mapper0 ("[mapper0]"); SimpleMapper<long, pair<long, long>> mapper1 ("[mapper1]"); connect_transform(unbound, mapper0); connect_transform(unbound, mapper1); */ /* old design vector<PCollection*> o2 = p->apply2(&unbound); o2[0]->_name = "src_out0"; o2[1]->_name = "src_out1"; SimpleMapper<long, pair<long, long>> mapper0 ("[mapper0]"); auto c11 = dynamic_cast<PCollection *>(o2[0]->apply1(&mapper0)); c11->_name = "mapper0_out"; mapper0.set_side_info(1); //left side SimpleMapper<long, pair<long, long>> mapper1 ("[mapper1]"); auto c12 = dynamic_cast<PCollection *>(o2[1]->apply1(&mapper1)); c12->_name = "mapper1_out"; mapper1.set_side_info(2); //right side */ PCollection *unbound_output = dynamic_cast<PCollection *>(p->apply1(&unbound)); unbound_output->_name = "unbound_output"; Join<pair<long,long>> join("[join]", seconds(1)); auto c2 = dynamic_cast<PCollection *>(unbound_output->apply1(&join)); //auto c3 = dynamic_cast<PCollection *>(c12->apply1(&join)); ///c2 = c2; //assert(c2 == c3); // same output. join.set_side_info(3); RecordBitmapBundleSink<pair<long, vector<long>>> sink("[sink]"); auto c4 = dynamic_cast<PCollection *>(c2->apply1(&sink)); c4 = c4; assert(c4); //just for fixing warning sink.set_side_info(4); RecordBitmapBundleSink<pair<long, vector<long>>> sink1("[sink1]"); auto c5 = dynamic_cast<PCollection *>(c4->apply1(&sink1)); c5 = c5; assert(c5); //just for fixing warning //assert(false && "set RecordBitmapBundleSink side_info to 4!!"); sink1.set_side_info(5); EvaluationBundleContext eval(1, config.cores); //XXX target_wm_delta_secs?? eval.runSimple(p); return 0; }
29.253968
80
0.663049
chenzongxiong
4f23b6cc5bc4a79d61a90b2c317d723d6fb33dfb
444
cpp
C++
lib/poprand/codelets/SetSeedSupervisor.cpp
giantchen2012/poplibs
2bc6b6f3d40863c928b935b5da88f40ddd77078e
[ "MIT" ]
1
2021-02-23T05:58:24.000Z
2021-02-23T05:58:24.000Z
lib/poprand/codelets/SetSeedSupervisor.cpp
giantchen2012/poplibs
2bc6b6f3d40863c928b935b5da88f40ddd77078e
[ "MIT" ]
null
null
null
lib/poprand/codelets/SetSeedSupervisor.cpp
giantchen2012/poplibs
2bc6b6f3d40863c928b935b5da88f40ddd77078e
[ "MIT" ]
null
null
null
// Copyright (c) 2019 Graphcore Ltd. All rights reserved. #include "RandomUtils.hpp" using namespace poplar; namespace poprand { class SetSeedSupervisor : public SupervisorVertexIf<ASM_CODELETS_ENABLED> { public: SetSeedSupervisor(); Input<Vector<unsigned, ONE_PTR, 8>> seed; const uint32_t seedModifierUser; const uint32_t seedModifierHw; IS_EXTERNAL_CODELET(true); bool compute() { return true; } }; } // namespace poprand
20.181818
75
0.756757
giantchen2012
4f23d25e3dd58ad9ec5517f35b4fd0e826371bd6
24,265
cpp
C++
Src/FileDialog.cpp
bluescan/tacit-texview
084e2ee2f8e516b6d4449caf9b6712181db162f5
[ "ISC" ]
76
2019-07-03T06:43:37.000Z
2020-05-08T20:23:08.000Z
Src/FileDialog.cpp
bluescan/tacit-texview
084e2ee2f8e516b6d4449caf9b6712181db162f5
[ "ISC" ]
15
2020-01-12T23:37:09.000Z
2020-05-01T04:44:14.000Z
Src/FileDialog.cpp
bluescan/tacit-texview
084e2ee2f8e516b6d4449caf9b6712181db162f5
[ "ISC" ]
2
2020-01-18T14:13:14.000Z
2020-04-05T14:17:07.000Z
// FileDialog.cpp // // Dialog that allows selection of a file or directory. May be used for opening a file/directory or saving to a file. // // Copyright (c) 2021, 2022 Tristan Grimmer. // Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby // granted, provided that the above copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN // AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. #include <Math/tVector2.h> #include <System/tTime.h> #include "imgui.h" #include "FileDialog.h" #include "TacentView.h" #include "Image.h" using namespace tStd; using namespace tMath; using namespace tSystem; using namespace tImage; using namespace tInterface; namespace tInterface { // Content items are containers used to store information about a piece of information in a file dialog. It stores // the stuff you see in the right-hand panel. Namely the information displayed in a table row about a file or // directory, as well as if it is selected or not. struct ContentItem : tLink<ContentItem> { ContentItem(const tString& dirName); ContentItem(const tSystem::tFileInfo& fileInfo); bool Selected; // Each field (column) gets its own ID. This is needed so when sorting, we know what information to use in the // sorting function. We tell ImGui about the ID, and it passes that along when it tells us to sort. enum class FieldID { Invalid = -1, Name, ModTime, FileType, FileSize }; struct CompareFunctionObject { CompareFunctionObject(ImGuiTableSortSpecs* specs) : SortSpecs(specs) { } ImGuiTableSortSpecs* SortSpecs; bool operator() (const ContentItem& a, const ContentItem& b) const; }; // Name field. tString Name; bool IsDir; // These are not valid for directories. Note that we store field data redundantly in some cases since we need to be // able to sort based on a key decoupled from the display string. For example, sorting by date should be done with // an integer, not the string representation. Same with filesizes, we may want them displayed in KB or MB is they // get large, but want to sort on num-bytes. We store the string reps because it's more efficient to cache them // rather than regenerate them every time. // Modification time (last) field. int64 ModTime; // In posix epoch. tString ModTimeString; // Displayed. // File type field. tSystem::tFileType FileType; tString FileTypeString; // Displayed. // File size field. int64 FileSize; tString FileSizeString; // Displayed. }; // Tree nodes are displayed directly in the left panel and their contained Contents list in the right. TreeNodes // represent directories and other containers like favourites and network shares. A TreeNode has children TreeNodes. class TreeNode { public: TreeNode() : Name(), Parent(nullptr) { } TreeNode(const tString& name, FileDialog* dialog, TreeNode* parent = nullptr) : Name(name), Dialog(dialog), Parent(parent) { } void AppendChild(TreeNode* treeNode) { Children.Append(treeNode); } // For windows these do a case-insensitive compare. For case sensitive filesystems like Linux uses // these to a case-sensitive compare. TreeNode* Find(const tString& name) const; bool Contains(const tString& name) const { return Find(name) ? true : false; } int Depth() const; bool IsNetworkLocation() const; ContentItem* FindSelectedItem() const; tString Name; FileDialog* Dialog; bool ChildrenPopulated = false; TreeNode* Parent; tItList<TreeNode> Children; bool NextOpen = false; // Is the Contents list below populated and valid. It is slightly different than having an empty Contents list // because a leaf empty directory may have no contents, but it HAS read the filesystem so is populated. bool ContentsPopulated = false; tList<ContentItem> Contents; }; } ContentItem::ContentItem(const tString& dirName) : Selected(false), IsDir(true) { Name = dirName; ModTime = 0; ModTimeString.Clear(); FileType = tSystem::tFileType::Invalid; FileSize = 0; FileSizeString.Clear(); } ContentItem::ContentItem(const tSystem::tFileInfo& fileInfo) : Selected(false) { // Name field. Name = tSystem::tGetFileName(fileInfo.FileName); IsDir = fileInfo.Directory; // Modification time field. Choose greater of mod and creation time. ModTime = tMath::tMax(fileInfo.ModificationTime, fileInfo.CreationTime); tsPrintf(ModTimeString, "%s", tSystem::tConvertTimeToString(tSystem::tConvertTimeToLocal(ModTime)).Chars()); // File type field. FileType = tSystem::tGetFileType(Name); FileTypeString.Set(tSystem::tGetFileTypeName(FileType)); // File size field. FileSize = fileInfo.FileSize; if (FileSize < 10000) tsPrintf(FileSizeString, "%'d B", FileSize); else if (FileSize < 10000000) tsPrintf(FileSizeString, "%'d KB", FileSize/1024); else if (FileSize < 10000000000) tsPrintf(FileSizeString, "%'d MB", FileSize/(1024*1024)); else tsPrintf(FileSizeString, "%'d GB", FileSize/(1024*1024*1024)); } bool ContentItem::CompareFunctionObject::operator() (const ContentItem& a, const ContentItem& b) const { tAssert(SortSpecs); // We always put directories at the top regardless of field contents and sorting order. if (a.IsDir && !b.IsDir) return true; // This makes both the directories (that come first) as well as the files (that come after) sort correctly. // That is, do the sorting if we're comparing file-to-file or dir-to-dir. if (a.IsDir == b.IsDir) { // NumSpecs will be > 1 if more than one column is selected for sorting. The order is important. int numSpecs = SortSpecs->SpecsCount; for (int s = 0; s < numSpecs; s++) { const ImGuiTableColumnSortSpecs& colSortSpec = SortSpecs->Specs[s]; FieldID field = FieldID(colSortSpec.ColumnUserID); int64 delta = 0; switch (field) { case FieldID::Name: delta = tStd::tStricmp(a.Name.Chars(), b.Name.Chars()); break; case FieldID::ModTime: delta = a.ModTime - b.ModTime; break; case FieldID::FileType: delta = tStd::tStricmp(a.FileTypeString.Chars(), b.FileTypeString.Chars()); break; case FieldID::FileSize: delta = a.FileSize - b.FileSize; break; } if ((delta < 0) && (colSortSpec.SortDirection == ImGuiSortDirection_Ascending)) return true; else if ((delta > 0) && (colSortSpec.SortDirection == ImGuiSortDirection_Descending)) return true; } } return false; } TreeNode* TreeNode::Find(const tString& name) const { for (tItList<TreeNode>::Iter child = Children.First(); child; child++) { #ifdef PLATFORM_WINDOWS if (child->Name.IsEqualCI(name)) #else if (child->Name == name) #endif return child; } return nullptr; } int TreeNode::Depth() const { int depth = 0; TreeNode* parent = Parent; while (parent) { depth++; parent = parent->Parent; } return depth; } ContentItem* TreeNode::FindSelectedItem() const { for (ContentItem* item = Contents.First(); item; item = item->Next()) if (item->Selected) return item; return nullptr; } bool TreeNode::IsNetworkLocation() const { bool isNet = false; const TreeNode* curr = this; while (curr) { if ((curr->Depth() == 0) && (curr->Name == "Network")) isNet = true; curr = curr->Parent; } return isNet; } FileDialog::FileDialog(DialogMode mode, const tSystem::tFileTypes& fileTypes) : Mode(mode), FileTypes(fileTypes) { BookmarkTreeNode = new TreeNode("Bookmarks", this); LocalTreeNode = new TreeNode("Local", this); #ifdef PLATFORM_WINDOWS NetworkTreeNode = new TreeNode("Network", this); #endif // @wip Bookmarks is disabled until I implement it fully. PopulateBookmarks(); PopulateLocal(); #ifdef PLATFORM_WINDOWS PopulateNetwork(); #endif } void FileDialog::OpenPopup() { //ImGui::SetNextWindowSize(tVector2(640.0f, 400.0f), ImGuiCond_FirstUseEver); switch (Mode) { case DialogMode::OpenDir: ImGui::OpenPopup("Open Directory"); break; case DialogMode::OpenFile: ImGui::OpenPopup("Open File"); break; case DialogMode::SaveFile: ImGui::OpenPopup("Save File"); break; } } void FileDialog::PopulateBookmarks() { #if defined(PLATFORM_LINUX) // All linux platforms get a 'home' bookmark. #endif #if defined(PLATFORM_WINDOWS) // All windows platforms get a 'user' bookmark. TreeNode* user = new TreeNode("User", this, BookmarkTreeNode); BookmarkTreeNode->AppendChild(user); #endif } void FileDialog::PopulateLocal() { #if defined(PLATFORM_WINDOWS) tList<tStringItem> drives; tSystem::tGetDrives(drives); for (tStringItem* drive = drives.First(); drive; drive = drive->Next()) { TreeNode* driveNode = new TreeNode(*drive, this, LocalTreeNode); LocalTreeNode->AppendChild(driveNode); } #elif defined(PLATFORM_LINUX) TreeNode* rootNode = new TreeNode("/", this, LocalTreeNode); LocalTreeNode->AppendChild(rootNode); #endif } #ifdef PLATFORM_WINDOWS void FileDialog::RequestNetworkSharesThread() { tSystem::tGetNetworkShares(NetworkShareResults); } void FileDialog::PopulateNetwork() { // Start the request on a different thread. std::thread threadGetShares(&FileDialog::RequestNetworkSharesThread, this); threadGetShares.detach(); } void FileDialog::ProcessShareResults() { // Most of time this will be empty since we remove the items when they are available, just like a message queue. tStringItem* share = NetworkShareResults.ShareNames.Remove(); if (share) { tList<tStringItem> exploded; tExplodeShareName(exploded, *share); tString machName = *exploded.First(); if (!NetworkTreeNode->Contains(machName)) { TreeNode* machine = new TreeNode(machName.Text(), this, NetworkTreeNode); NetworkTreeNode->AppendChild(machine); } TreeNode* machNode = NetworkTreeNode->Find(machName); tAssert(machNode); tStringItem* shareName = (exploded.GetNumItems() == 2) ? exploded.Last() : nullptr; if (shareName && !machNode->Contains(*shareName)) { TreeNode* shareNode = new TreeNode(shareName->Text(), this, machNode); machNode->AppendChild(shareNode); } delete share; } } #endif void FileDialog::TreeNodeRecursive(TreeNode* node) { int flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_DefaultOpen | ((node->Children.GetNumItems() == 0) ? ImGuiTreeNodeFlags_Leaf : 0) | ((SelectedNode == node) ? ImGuiTreeNodeFlags_Selected : 0); bool populate = false; // This is the magic that's needed if you select from the right-hand panel. if (node->NextOpen) { ImGui::SetNextTreeNodeOpen(true); node->NextOpen = false; populate = true; } bool isOpen = ImGui::TreeNodeEx(node->Name, flags); bool isClicked = ImGui::IsItemClicked(); if (isClicked) { SelectedNode = node; populate = true; } // We only bother populating children if we need to. if (populate && !node->ChildrenPopulated) { #ifdef PLATFORM_WINDOWS if (!ProcessingNetworkPath || (node->Depth() >= 2)) #endif { // Need to be careful here. tFindDirs would (reasonably?) use the current working dir if we passed in an empty string. tString currDir = GetSelectedDir(); tList<tStringItem> foundDirs; if (!currDir.IsEmpty()) tSystem::tFindDirs(foundDirs, currDir); for (tStringItem* dir = foundDirs.First(); dir; dir = dir->Next()) { tString relDir = tSystem::tGetRelativePath(currDir, *dir); relDir.ExtractLeft("./"); relDir.ExtractRight("/"); TreeNode* child = new TreeNode(relDir, this, node); node->AppendChild(child); } node->ChildrenPopulated = true; } } if (isOpen) { // Recurse children. for (tItList<TreeNode>::Iter child = node->Children.First(); child; child++) TreeNodeRecursive(child.GetObject()); ImGui::TreePop(); } } void FileDialog::InvalidateAllNodeContent() { #ifdef PLATFORM_WINDOWS InvalidateAllNodeContentRecursive(NetworkTreeNode); #endif InvalidateAllNodeContentRecursive(LocalTreeNode); } void FileDialog::InvalidateAllNodeContentRecursive(TreeNode* node) { node->Contents.Empty(); node->ContentsPopulated = false; for (tItList<TreeNode>::Iter child = node->Children.First(); child; child++) InvalidateAllNodeContentRecursive(child.GetObject()); } void FileDialog::DoSelectable(ContentItem* item) { tString label = item->Name; if (ImGui::Selectable(label, &item->Selected, ImGuiSelectableFlags_SpanAllColumns)) { // This block enforces single selection. if (Mode != DialogMode::OpenFiles) { if (item->Selected) { // Only allowed one selected max. Clear the others. for (ContentItem* i = SelectedNode->Contents.First(); i; i = i->Next()) { if (i == item) continue; i->Selected = false; } } // Do not allow deselection of the single item. item->Selected = true; } // If a directory is selected in the right panel, we support updating the current selected TreeNode. if (item->IsDir) { SelectedNode->NextOpen = true; TreeNode* node = SelectedNode->Find(item->Name); if (!node) { // Need to create a new one and connect it up. node = new TreeNode(item->Name, this, SelectedNode); SelectedNode->AppendChild(node); tAssert(node->ChildrenPopulated == false); } SelectedNode = node; } } } void FileDialog::TreeNodeFlat(TreeNode* node) { int flags = (node->Children.GetNumItems() == 0) ? ImGuiTreeNodeFlags_Leaf : 0; if (SelectedNode == node) flags |= ImGuiTreeNodeFlags_Selected; flags |= ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; bool isOpen = ImGui::TreeNodeEx(node->Name, flags); bool isClicked = ImGui::IsItemClicked(); if (isOpen) { // Recurse children. // for (tItList<TreeNode>::Iter child = node->Children.First(); child; child++) // FavouritesTreeNodeFlat(child.GetObject()); ImGui::TreePop(); } } FileDialog::DialogResult FileDialog::DoPopup() { // The unused isOpen bool is just so we get a close button in ImGui. bool isOpen = true; const char* label = nullptr; switch (Mode) { case DialogMode::OpenFile: label = "Open File"; break; case DialogMode::OpenFiles: label = "Open Files"; break; case DialogMode::OpenDir: label = "Open Directory"; break; case DialogMode::SaveFile: label = "Save File"; break; } ImGui::SetNextWindowSize(tVector2(660.0f, 400.0f), ImGuiCond_Appearing); if (!ImGui::BeginPopupModal(label, &isOpen, 0)) return DialogResult::Closed; DialogResult result = DialogResult::Open; Result.Clear(); // The left and right panels are cells in a 1 row, 2 column table. float bottomBarHeight = 20.0f + 28.0f; ImGui::PushStyleColor(ImGuiCol_TableBorderLight, tVector4(0.50f, 0.50f, 0.54f, 1.00f)); if (ImGui::BeginTable("FileDialogTable", 2, ImGuiTableFlags_Resizable, tVector2(0.0f, -bottomBarHeight))) { ImGui::TableSetupColumn("LeftTreeColumn", ImGuiTableColumnFlags_WidthFixed, 160.0f); ImGui::TableSetupColumn("RightContentColumn", ImGuiTableColumnFlags_WidthStretch); ImGui::TableNextRow(); // Left tree panel. ImGui::TableSetColumnIndex(0); ImGui::BeginChild("LeftTreePanel", tVector2(0.0f, -bottomBarHeight), false, ImGuiWindowFlags_HorizontalScrollbar); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, tVector2(0.0f, 3.0f)); // This block is the workhorse of the dialog. // @wip Bookmarks are disabled until implemented fully. TreeNodeFlat(BookmarkTreeNode); TreeNodeRecursive(LocalTreeNode); #ifdef PLATFORM_WINDOWS ProcessShareResults(); ProcessingNetworkPath = true; TreeNodeRecursive(NetworkTreeNode); ProcessingNetworkPath = false; #endif ImGui::PopStyleVar(); ImGui::EndChild(); // Right content panel. ImGui::TableSetColumnIndex(1); ImGui::BeginChild("RightContentPanel", tVector2(0.0f, -bottomBarHeight)); if (SelectedNode) { if (!SelectedNode->ContentsPopulated) { tString selDir = GetSelectedDir(); // Directories. tList<tStringItem> foundDirs; if (!selDir.IsEmpty()) tSystem::tFindDirs(foundDirs, selDir); for (tStringItem* dir = foundDirs.First(); dir; dir = dir->Next()) { (*dir)[dir->Length()-1] = '\0'; // Remove slash. ContentItem* contentItem = new ContentItem(tSystem::tGetFileName(*dir)); SelectedNode->Contents.Append(contentItem); } // Files. tList<tFileInfo> foundFiles; if (!selDir.IsEmpty()) { tSystem::tFileTypes selectedTypes; selectedTypes.AddSelected(FileTypes, true); tSystem::tExtensions extensions(selectedTypes); tSystem::tFindFilesFast(foundFiles, selDir, extensions); } for (tFileInfo* fileInfo = foundFiles.First(); fileInfo; fileInfo = fileInfo->Next()) { ContentItem* contentItem = new ContentItem(*fileInfo); SelectedNode->Contents.Append(contentItem); } SelectedNode->ContentsPopulated = true; } int tableFlags = ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_Reorderable | // Drag columns to an order you like. ImGuiTableFlags_Hideable | // Hide individual columns. ImGuiTableFlags_Sortable | // Sort by column. // ImGuiTableFlags_SortTristate // Ascending, Descending, None. May get 0 sort specs. ImGuiTableFlags_SortMulti | // Allow sorting multiple columns by shift-selecting them. May get > 1 sort specs. //ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_ScrollY; // This is needed so the table itself has a scroll bar that respects the top-row freeze. ImGui::PushStyleColor(ImGuiCol_TableBorderLight, tVector4(0.25f, 0.25f, 0.28f, 1.00f)); if (ImGui::BeginTable("ContentItems", 5, tableFlags)) { // The columns. Each one gets its own unique ID. int iconFlags = ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoSort; int nameFlags = ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_PreferSortAscending | ImGuiTableColumnFlags_DefaultSort | ImGuiTableColumnFlags_PreferSortAscending | ImGuiTableColumnFlags_NoHide | ImGuiTableColumnFlags_NoReorder; int propFlags = ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_PreferSortAscending; ImGui::TableSetupColumn("Icon", iconFlags, 24.0f, uint32(ContentItem::FieldID::Invalid) ); ImGui::TableSetupColumn("Name", nameFlags, 190.0f, uint32(ContentItem::FieldID::Name) ); ImGui::TableSetupColumn("Modified", propFlags, 120.0f, uint32(ContentItem::FieldID::ModTime) ); ImGui::TableSetupColumn("Type", propFlags, 36.0f, uint32(ContentItem::FieldID::FileType) ); ImGui::TableSetupColumn("Size", propFlags, 0.0f, uint32(ContentItem::FieldID::FileSize) ); ImGui::TableSetupScrollFreeze(0, 1); // Make this row always visible. ImGui::TableHeadersRow(); // Sort the rows. ImGuiTableSortSpecs* sortSpecs = ImGui::TableGetSortSpecs(); if (sortSpecs && (sortSpecs->SpecsDirty) && (sortSpecs->SpecsCount > 0)) { ContentItem::CompareFunctionObject compare(sortSpecs); SelectedNode->Contents.Sort(compare); sortSpecs->SpecsDirty = false; } // Do the content rows. We could use ImGuiListClipper here but so far, even with thousands of files in // the Contents list, it is very responsive. Also, since it's a list rather than an array, we'd still // need a 'Next' loop to get to the right clipper starting point (clipper.DisplayStart). for (ContentItem* item = SelectedNode->Contents.First(); item; item = item->Next()) { ImGui::TableNextRow(); ImGui::TableNextColumn(); uint64 imgID = item->IsDir ? Viewer::FolderImage.Bind() : Viewer::FileImage.Bind(); ImGui::SetCursorPosX(ImGui::GetCursorPosX()+4.0f); ImGui::Image(ImTextureID(imgID), tVector2(16, 16), tVector2(0, 1), tVector2(1, 0), Viewer::ColourEnabledTint); // The name column selectable spans all columns. ImGui::TableNextColumn(); DoSelectable(item); ImGui::TableNextColumn(); if (!item->IsDir) ImGui::Text("%s", item->ModTimeString.Text()); ImGui::TableNextColumn(); if (!item->IsDir) ImGui::Text("%s", item->FileTypeString.Text()); ImGui::TableNextColumn(); if (!item->IsDir) ImGui::Text("%s", item->FileSizeString.Text()); } ImGui::EndTable(); } ImGui::PopStyleColor(); } ImGui::EndChild(); ImGui::EndTable(); } ImGui::PopStyleColor(); ContentItem* selItem = SelectedNode ? SelectedNode->FindSelectedItem() : nullptr; bool resultAvail = false; if (selItem) { resultAvail = ( ((Mode == DialogMode::OpenFile) && !selItem->IsDir) || ((Mode == DialogMode::SaveFile) && !selItem->IsDir) || ((Mode == DialogMode::OpenDir) && selItem->IsDir) // @todo multiple files. ); } if (!resultAvail && (Mode == DialogMode::OpenDir) && SelectedNode) { // OK to select dir in left-hand pane. int depth = SelectedNode->Depth(); resultAvail = ( (depth > 1) || (!SelectedNode->IsNetworkLocation() && (depth > 0)) ); } // For file modes, display the filename and types combo. if (Mode != DialogMode::OpenDir) { int flags = ImGuiInputTextFlags_ReadOnly; ImGui::SetNextItemWidth( ImGui::GetWindowContentRegionMax().x / 2.0f ); if (!resultAvail) ImGui::PushStyleColor(ImGuiCol_Text, tVector4(0.5f, 0.5f, 0.52f, 1.0f) ); tString fname = resultAvail ? selItem->Name : "File Name"; ImGui::InputText("##File Name", fname.Text(), fname.Length()+1, flags); if (!resultAvail) ImGui::PopStyleColor(); ImGui::SameLine(); ImGui::SetNextItemWidth(140); ImGui::SetCursorPosX(ImGui::GetWindowContentRegionMax().x - 140.0f); // Nothing selected means all types used. bool allTypes = !FileTypes.AnySelected(); tString currChosen = allTypes ? "All Image Types" : FileTypes.GetSelectedString(tSystem::tFileTypes::Separator::CommaSpace, 4); if (ImGui::BeginCombo("##TypeFilter", currChosen.Chars())) //, ImGuiComboFlags_NoArrowButton)) { if (ImGui::Selectable("All Image Types", allTypes)) { FileTypes.ClearSelected(); InvalidateAllNodeContent(); } for (tFileTypes::tFileTypeItem* typeItem = FileTypes.First(); typeItem; typeItem = typeItem->Next()) { tFileType fileType = typeItem->FileType; const char* fileTypeName = tSystem::tGetFileTypeName(fileType); if (!fileTypeName) continue; if (ImGui::Selectable(fileTypeName, typeItem->Selected)) { typeItem->Selected = !typeItem->Selected; InvalidateAllNodeContent(); } if (typeItem->Selected) ImGui::SetItemDefaultFocus(); } // Update the filters. ImGui::EndCombo(); } } // Cancel and OK buttons. ImGui::SetCursorPosY(ImGui::GetWindowContentRegionMax().y - 20.0f); if (resultAvail) { ImGui::SetCursorPosX(ImGui::GetWindowContentRegionMax().x - 140.0f); if (ImGui::Button("Open", tVector2(70.0f, 0.0f))) { Result = GetSelectedDir(); if ((Mode == DialogMode::OpenFile) && selItem) Result += selItem->Name; result = DialogResult::OK; } ImGui::SameLine(); } ImGui::SetCursorPosX(ImGui::GetWindowContentRegionMax().x - 70.0f); if (ImGui::Button("Cancel", tVector2(70.0f, 0.0f))) result = DialogResult::Cancel; if (result != DialogResult::Open) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); return result; } tString FileDialog::GetResult() { return Result; } tString FileDialog::GetSelectedDir() { if (!SelectedNode) return tString(); bool isNetworkLoc = SelectedNode->IsNetworkLocation(); tString dir; TreeNode* curr = SelectedNode; while (curr) { if (!curr->Name.IsEmpty() && (curr->Depth() > 0)) { if (isNetworkLoc && (curr->Depth() == 1)) dir = curr->Name + "\\" + dir; else dir = curr->Name + "/" + dir; } curr = curr->Parent; } if (isNetworkLoc) dir = tString("\\\\") + dir; return dir; }
30.068154
242
0.705131
bluescan
4f2605188c3c8162aa30dfb72b435008f808b798
24,573
cpp
C++
Mac_Libraries/FreeImage_3_18/Source/FreeImage/MultiPage.cpp
aws4y/OpenNebulosity
406162ea39de7e8fb90147ee43f6ee95dd56dfde
[ "BSD-3-Clause" ]
111
2015-01-13T18:14:31.000Z
2022-02-20T14:26:55.000Z
Mac_Libraries/FreeImage_3_18/Source/FreeImage/MultiPage.cpp
aws4y/OpenNebulosity
406162ea39de7e8fb90147ee43f6ee95dd56dfde
[ "BSD-3-Clause" ]
54
2015-02-23T16:57:41.000Z
2021-02-19T08:16:27.000Z
Mac_Libraries/FreeImage_3_18/Source/FreeImage/MultiPage.cpp
aws4y/OpenNebulosity
406162ea39de7e8fb90147ee43f6ee95dd56dfde
[ "BSD-3-Clause" ]
26
2015-01-17T13:07:56.000Z
2021-12-02T07:43:29.000Z
// ========================================================== // Multi-Page functions // // Design and implementation by // - Floris van den Berg (flvdberg@wxs.nl) // - Laurent Rocher (rocherl@club-internet.fr) // - Steve Johnson (steve@parisgroup.net) // - Petr Pytelka (pyta@lightcomp.com) // - Hervé Drolon (drolon@infonie.fr) // - Vadim Alexandrov (vadimalexandrov@users.sourceforge.net // - Martin Dyring-Andersen (mda@spamfighter.com) // - Volodymyr Goncharov (volodymyr.goncharov@gmail.com) // - Mihail Naydenov (mnaydenov@users.sourceforge.net) // // This file is part of FreeImage 3 // // COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES // THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE // OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED // CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT // THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY // SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL // PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER // THIS DISCLAIMER. // // Use at your own risk! // ========================================================== #ifdef _MSC_VER #pragma warning (disable : 4786) // identifier was truncated to 'number' characters #endif #include "CacheFile.h" #include "FreeImageIO.h" #include "Plugin.h" #include "Utilities.h" #include "FreeImage.h" namespace { // ---------------------------------------------------------- enum BlockType { BLOCK_CONTINUEUS, BLOCK_REFERENCE }; // ---------------------------------------------------------- class PageBlock { union { struct { int m_start; int m_end; }; struct { int m_reference; int m_size; }; }; public: BlockType m_type; PageBlock(BlockType type = BLOCK_CONTINUEUS, int val1 = -1, int val2 = -1) : m_type(type) { if(m_type == BLOCK_CONTINUEUS) { m_start = val1; m_end = val2; } else { m_reference = val1; m_size = val2; } } bool isValid() const { return !(m_type == BLOCK_CONTINUEUS && m_start == -1 && m_end == -1); } /*explicit*/ operator bool() const { return isValid(); } int getStart() const { assert(isValid() && m_type == BLOCK_CONTINUEUS); return m_start; } int getEnd() const { assert(isValid() && m_type == BLOCK_CONTINUEUS); return m_end; } bool isSinglePage() const { assert(isValid()); return m_type == BLOCK_CONTINUEUS ? (m_start == m_end) : true; } int getPageCount() const { assert(isValid()); return m_type == BLOCK_CONTINUEUS ? (m_end - m_start + 1) : 1;} int getReference() const { assert(isValid() && m_type == BLOCK_REFERENCE); return m_reference; } int getSize() const { assert(isValid() && m_type == BLOCK_REFERENCE); return m_size; } }; // ---------------------------------------------------------- typedef std::list<PageBlock> BlockList; typedef BlockList::iterator BlockListIterator; // ---------------------------------------------------------- struct MULTIBITMAPHEADER { MULTIBITMAPHEADER() : node(NULL) , fif(FIF_UNKNOWN) , handle(NULL) , changed(FALSE) , page_count(0) , read_only(TRUE) , cache_fif(fif) , load_flags(0) { SetDefaultIO(&io); } PluginNode *node; FREE_IMAGE_FORMAT fif; FreeImageIO io; fi_handle handle; CacheFile m_cachefile; std::map<FIBITMAP *, int> locked_pages; BOOL changed; int page_count; BlockList m_blocks; std::string m_filename; BOOL read_only; FREE_IMAGE_FORMAT cache_fif; int load_flags; }; // ===================================================================== // Helper functions // ===================================================================== inline void ReplaceExtension(std::string& dst_filename, const std::string& src_filename, const std::string& dst_extension) { size_t lastDot = src_filename.find_last_of('.'); if (lastDot == std::string::npos) { dst_filename = src_filename; dst_filename += "."; dst_filename += dst_extension; } else { dst_filename = src_filename.substr(0, lastDot + 1); dst_filename += dst_extension; } } } //< ns // ===================================================================== // Internal Multipage functions // ===================================================================== inline MULTIBITMAPHEADER * FreeImage_GetMultiBitmapHeader(FIMULTIBITMAP *bitmap) { return (MULTIBITMAPHEADER *)bitmap->data; } static BlockListIterator DLL_CALLCONV FreeImage_FindBlock(FIMULTIBITMAP *bitmap, int position) { assert(NULL != bitmap); MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); // step 1: find the block that matches the given position int prev_count = 0; int count = 0; BlockListIterator i; for (i = header->m_blocks.begin(); i != header->m_blocks.end(); ++i) { prev_count = count; count += i->getPageCount(); if (count > position) { break; } } // step 2: make sure we found the node. from here it gets a little complicated: // * if the block is single page, just return it // * if the block is a span of pages, split it in 3 new blocks // and return the middle block, which is now a single page if ((i != header->m_blocks.end()) && (count > position)) { if (i->isSinglePage()) { return i; } const int item = i->getStart() + (position - prev_count); // left part if (item != i->getStart()) { header->m_blocks.insert(i, PageBlock(BLOCK_CONTINUEUS, i->getStart(), item - 1)); } // middle part BlockListIterator block_target = header->m_blocks.insert(i, PageBlock(BLOCK_CONTINUEUS, item, item)); // right part if (item != i->getEnd()) { header->m_blocks.insert(i, PageBlock(BLOCK_CONTINUEUS, item + 1, i->getEnd())); } // remove the old block that was just splitted header->m_blocks.erase(i); // return the splitted block return block_target; } // we should never go here ... assert(false); return header->m_blocks.end(); } int DLL_CALLCONV FreeImage_InternalGetPageCount(FIMULTIBITMAP *bitmap) { if (bitmap) { if (((MULTIBITMAPHEADER *)bitmap->data)->handle) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); header->io.seek_proc(header->handle, 0, SEEK_SET); void *data = FreeImage_Open(header->node, &header->io, header->handle, TRUE); int page_count = (header->node->m_plugin->pagecount_proc != NULL) ? header->node->m_plugin->pagecount_proc(&header->io, header->handle, data) : 1; FreeImage_Close(header->node, &header->io, header->handle, data); return page_count; } } return 0; } // ===================================================================== // Multipage functions // ===================================================================== FIMULTIBITMAP * DLL_CALLCONV FreeImage_OpenMultiBitmap(FREE_IMAGE_FORMAT fif, const char *filename, BOOL create_new, BOOL read_only, BOOL keep_cache_in_memory, int flags) { FILE *handle = NULL; try { // sanity check on the parameters if (create_new) { read_only = FALSE; } // retrieve the plugin list to find the node belonging to this plugin PluginList *list = FreeImage_GetPluginList(); if (list) { PluginNode *node = list->FindNodeFromFIF(fif); if (node) { if (!create_new) { handle = fopen(filename, "rb"); if (handle == NULL) { return NULL; } } std::auto_ptr<FIMULTIBITMAP> bitmap (new FIMULTIBITMAP); std::auto_ptr<MULTIBITMAPHEADER> header (new MULTIBITMAPHEADER); header->m_filename = filename; // io is default header->node = node; header->fif = fif; header->handle = handle; header->read_only = read_only; header->cache_fif = fif; header->load_flags = flags; // store the MULTIBITMAPHEADER in the surrounding FIMULTIBITMAP structure bitmap->data = header.get(); // cache the page count header->page_count = FreeImage_InternalGetPageCount(bitmap.get()); // allocate a continueus block to describe the bitmap if (!create_new) { header->m_blocks.push_back(PageBlock(BLOCK_CONTINUEUS, 0, header->page_count - 1)); } // set up the cache if (!read_only) { std::string cache_name; ReplaceExtension(cache_name, filename, "ficache"); if (!header->m_cachefile.open(cache_name, keep_cache_in_memory)) { // an error occured ... fclose(handle); return NULL; } } // return the multibitmap // std::bad_alloc won't be thrown from here on header.release(); // now owned by bitmap return bitmap.release(); // now owned by caller } } } catch (std::bad_alloc &) { /** @todo report error */ } if (handle) { fclose(handle); } return NULL; } FIMULTIBITMAP * DLL_CALLCONV FreeImage_OpenMultiBitmapFromHandle(FREE_IMAGE_FORMAT fif, FreeImageIO *io, fi_handle handle, int flags) { try { BOOL read_only = FALSE; // modifications (if any) will be stored into the memory cache if (io && handle) { // retrieve the plugin list to find the node belonging to this plugin PluginList *list = FreeImage_GetPluginList(); if (list) { PluginNode *node = list->FindNodeFromFIF(fif); if (node) { std::auto_ptr<FIMULTIBITMAP> bitmap (new FIMULTIBITMAP); std::auto_ptr<MULTIBITMAPHEADER> header (new MULTIBITMAPHEADER); header->io = *io; header->node = node; header->fif = fif; header->handle = handle; header->read_only = read_only; header->cache_fif = fif; header->load_flags = flags; // store the MULTIBITMAPHEADER in the surrounding FIMULTIBITMAP structure bitmap->data = header.get(); // cache the page count header->page_count = FreeImage_InternalGetPageCount(bitmap.get()); // allocate a continueus block to describe the bitmap header->m_blocks.push_back(PageBlock(BLOCK_CONTINUEUS, 0, header->page_count - 1)); // no need to open cache - it is in-memory by default header.release(); return bitmap.release(); } } } } catch (std::bad_alloc &) { /** @todo report error */ } return NULL; } BOOL DLL_CALLCONV FreeImage_SaveMultiBitmapToHandle(FREE_IMAGE_FORMAT fif, FIMULTIBITMAP *bitmap, FreeImageIO *io, fi_handle handle, int flags) { if(!bitmap || !bitmap->data || !io || !handle) { return FALSE; } BOOL success = TRUE; // retrieve the plugin list to find the node belonging to this plugin PluginList *list = FreeImage_GetPluginList(); if (list) { PluginNode *node = list->FindNodeFromFIF(fif); if(node) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); // dst data void *data = FreeImage_Open(node, io, handle, FALSE); // src data void *data_read = NULL; if(header->handle) { // open src header->io.seek_proc(header->handle, 0, SEEK_SET); data_read = FreeImage_Open(header->node, &header->io, header->handle, TRUE); } // write all the pages to the file using handle and io int count = 0; for (BlockListIterator i = header->m_blocks.begin(); i != header->m_blocks.end(); i++) { if (success) { switch(i->m_type) { case BLOCK_CONTINUEUS: { for (int j = i->getStart(); j <= i->getEnd(); j++) { // load the original source data FIBITMAP *dib = header->node->m_plugin->load_proc(&header->io, header->handle, j, header->load_flags, data_read); // save the data success = node->m_plugin->save_proc(io, dib, handle, count, flags, data); count++; FreeImage_Unload(dib); } break; } case BLOCK_REFERENCE: { // read the compressed data BYTE *compressed_data = (BYTE*)malloc(i->getSize() * sizeof(BYTE)); header->m_cachefile.readFile((BYTE *)compressed_data, i->getReference(), i->getSize()); // uncompress the data FIMEMORY *hmem = FreeImage_OpenMemory(compressed_data, i->getSize()); FIBITMAP *dib = FreeImage_LoadFromMemory(header->cache_fif, hmem, 0); FreeImage_CloseMemory(hmem); // get rid of the buffer free(compressed_data); // save the data success = node->m_plugin->save_proc(io, dib, handle, count, flags, data); count++; // unload the dib FreeImage_Unload(dib); break; } } } else { break; } } // close the files FreeImage_Close(header->node, &header->io, header->handle, data_read); FreeImage_Close(node, io, handle, data); return success; } } return FALSE; } BOOL DLL_CALLCONV FreeImage_CloseMultiBitmap(FIMULTIBITMAP *bitmap, int flags) { if (bitmap) { BOOL success = TRUE; if (bitmap->data) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); // saves changes only of images loaded directly from a file if (header->changed && !header->m_filename.empty()) { try { // open a temp file std::string spool_name; ReplaceExtension(spool_name, header->m_filename, "fispool"); // open the spool file and the source file FILE *f = fopen(spool_name.c_str(), "w+b"); // saves changes if (f == NULL) { FreeImage_OutputMessageProc(header->fif, "Failed to open %s, %s", spool_name.c_str(), strerror(errno)); success = FALSE; } else { success = FreeImage_SaveMultiBitmapToHandle(header->fif, bitmap, &header->io, (fi_handle)f, flags); // close the files if (fclose(f) != 0) { success = FALSE; FreeImage_OutputMessageProc(header->fif, "Failed to close %s, %s", spool_name.c_str(), strerror(errno)); } } if (header->handle) { fclose((FILE *)header->handle); } // applies changes to the destination file if (success) { remove(header->m_filename.c_str()); success = (rename(spool_name.c_str(), header->m_filename.c_str()) == 0) ? TRUE:FALSE; if(!success) { FreeImage_OutputMessageProc(header->fif, "Failed to rename %s to %s", spool_name.c_str(), header->m_filename.c_str()); } } else { remove(spool_name.c_str()); } } catch (std::bad_alloc &) { success = FALSE; } } else { if (header->handle && !header->m_filename.empty()) { fclose((FILE *)header->handle); } } // delete the last open bitmaps while (!header->locked_pages.empty()) { FreeImage_Unload(header->locked_pages.begin()->first); header->locked_pages.erase(header->locked_pages.begin()->first); } // delete the FIMULTIBITMAPHEADER delete header; } delete bitmap; return success; } return FALSE; } int DLL_CALLCONV FreeImage_GetPageCount(FIMULTIBITMAP *bitmap) { if (bitmap) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); if (header->page_count == -1) { header->page_count = 0; for (BlockListIterator i = header->m_blocks.begin(); i != header->m_blocks.end(); ++i) { header->page_count += i->getPageCount(); } } return header->page_count; } return 0; } static PageBlock FreeImage_SavePageToBlock(MULTIBITMAPHEADER *header, FIBITMAP *data) { PageBlock res; if (header->read_only || !header->locked_pages.empty()) { return res; } DWORD compressed_size = 0; BYTE *compressed_data = NULL; // compress the bitmap data // open a memory handle FIMEMORY *hmem = FreeImage_OpenMemory(); if(hmem==NULL) { return res; } // save the file to memory if(!FreeImage_SaveToMemory(header->cache_fif, data, hmem, 0)) { FreeImage_CloseMemory(hmem); return res; } // get the buffer from the memory stream if(!FreeImage_AcquireMemory(hmem, &compressed_data, &compressed_size)) { FreeImage_CloseMemory(hmem); return res; } // write the compressed data to the cache int ref = header->m_cachefile.writeFile(compressed_data, compressed_size); // get rid of the compressed data FreeImage_CloseMemory(hmem); res = PageBlock(BLOCK_REFERENCE, ref, compressed_size); return res; } void DLL_CALLCONV FreeImage_AppendPage(FIMULTIBITMAP *bitmap, FIBITMAP *data) { if (!bitmap || !data) { return; } MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); if(const PageBlock block = FreeImage_SavePageToBlock(header, data)) { // add the block header->m_blocks.push_back(block); header->changed = TRUE; header->page_count = -1; } } void DLL_CALLCONV FreeImage_InsertPage(FIMULTIBITMAP *bitmap, int page, FIBITMAP *data) { if (!bitmap || !data) { return; } if (page >= FreeImage_GetPageCount(bitmap)) { return; } MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); if(const PageBlock block = FreeImage_SavePageToBlock(header, data)) { // add a block if (page > 0) { BlockListIterator block_source = FreeImage_FindBlock(bitmap, page); header->m_blocks.insert(block_source, block); } else { header->m_blocks.push_front(block); } header->changed = TRUE; header->page_count = -1; } } void DLL_CALLCONV FreeImage_DeletePage(FIMULTIBITMAP *bitmap, int page) { if (bitmap) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); if ((!header->read_only) && (header->locked_pages.empty())) { if (FreeImage_GetPageCount(bitmap) > 1) { BlockListIterator i = FreeImage_FindBlock(bitmap, page); if (i != header->m_blocks.end()) { switch(i->m_type) { case BLOCK_CONTINUEUS : header->m_blocks.erase(i); break; case BLOCK_REFERENCE : header->m_cachefile.deleteFile(i->getReference()); header->m_blocks.erase(i); break; } header->changed = TRUE; header->page_count = -1; } } } } } FIBITMAP * DLL_CALLCONV FreeImage_LockPage(FIMULTIBITMAP *bitmap, int page) { if (bitmap) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); // only lock if the page wasn't locked before... for (std::map<FIBITMAP *, int>::iterator i = header->locked_pages.begin(); i != header->locked_pages.end(); ++i) { if (i->second == page) { return NULL; } } // open the bitmap header->io.seek_proc(header->handle, 0, SEEK_SET); void *data = FreeImage_Open(header->node, &header->io, header->handle, TRUE); // load the bitmap data if (data != NULL) { FIBITMAP *dib = (header->node->m_plugin->load_proc != NULL) ? header->node->m_plugin->load_proc(&header->io, header->handle, page, header->load_flags, data) : NULL; // close the file FreeImage_Close(header->node, &header->io, header->handle, data); // if there was still another bitmap open, get rid of it if (dib) { header->locked_pages[dib] = page; return dib; } return NULL; } } return NULL; } void DLL_CALLCONV FreeImage_UnlockPage(FIMULTIBITMAP *bitmap, FIBITMAP *page, BOOL changed) { if ((bitmap) && (page)) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); // find out if the page we try to unlock is actually locked... if (header->locked_pages.find(page) != header->locked_pages.end()) { // store the bitmap compressed in the cache for later writing if (changed && !header->read_only) { header->changed = TRUE; // cut loose the block from the rest BlockListIterator i = FreeImage_FindBlock(bitmap, header->locked_pages[page]); // compress the data DWORD compressed_size = 0; BYTE *compressed_data = NULL; // open a memory handle FIMEMORY *hmem = FreeImage_OpenMemory(); // save the page to memory FreeImage_SaveToMemory(header->cache_fif, page, hmem, 0); // get the buffer from the memory stream FreeImage_AcquireMemory(hmem, &compressed_data, &compressed_size); // write the data to the cache if (i->m_type == BLOCK_REFERENCE) { header->m_cachefile.deleteFile(i->getReference()); } int iPage = header->m_cachefile.writeFile(compressed_data, compressed_size); *i = PageBlock(BLOCK_REFERENCE, iPage, compressed_size); // get rid of the compressed data FreeImage_CloseMemory(hmem); } // reset the locked page so that another page can be locked FreeImage_Unload(page); header->locked_pages.erase(page); } } } BOOL DLL_CALLCONV FreeImage_MovePage(FIMULTIBITMAP *bitmap, int target, int source) { if (bitmap) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); if ((!header->read_only) && (header->locked_pages.empty())) { if ((target != source) && ((target >= 0) && (target < FreeImage_GetPageCount(bitmap))) && ((source >= 0) && (source < FreeImage_GetPageCount(bitmap)))) { BlockListIterator block_source = FreeImage_FindBlock(bitmap, target); BlockListIterator block_target = FreeImage_FindBlock(bitmap, source); header->m_blocks.insert(block_target, *block_source); header->m_blocks.erase(block_source); header->changed = TRUE; return TRUE; } } } return FALSE; } BOOL DLL_CALLCONV FreeImage_GetLockedPageNumbers(FIMULTIBITMAP *bitmap, int *pages, int *count) { if ((bitmap) && (count)) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); if ((pages == NULL) || (*count == 0)) { *count = (int)header->locked_pages.size(); } else { int c = 0; for (std::map<FIBITMAP *, int>::iterator i = header->locked_pages.begin(); i != header->locked_pages.end(); ++i) { pages[c] = i->second; c++; if (c == *count) { break; } } } return TRUE; } return FALSE; } // ===================================================================== // Memory IO Multipage functions // ===================================================================== FIMULTIBITMAP * DLL_CALLCONV FreeImage_LoadMultiBitmapFromMemory(FREE_IMAGE_FORMAT fif, FIMEMORY *stream, int flags) { BOOL read_only = FALSE; // modifications (if any) will be stored into the memory cache // retrieve the plugin list to find the node belonging to this plugin PluginList *list = FreeImage_GetPluginList(); if (list) { PluginNode *node = list->FindNodeFromFIF(fif); if (node) { FIMULTIBITMAP *bitmap = new(std::nothrow) FIMULTIBITMAP; if (bitmap) { MULTIBITMAPHEADER *header = new(std::nothrow) MULTIBITMAPHEADER; if (header) { header->node = node; header->fif = fif; SetMemoryIO(&header->io); header->handle = (fi_handle)stream; header->read_only = read_only; header->cache_fif = fif; header->load_flags = flags; // store the MULTIBITMAPHEADER in the surrounding FIMULTIBITMAP structure bitmap->data = header; // cache the page count header->page_count = FreeImage_InternalGetPageCount(bitmap); // allocate a continueus block to describe the bitmap header->m_blocks.push_back(PageBlock(BLOCK_CONTINUEUS, 0, header->page_count - 1)); // no need to open cache - it is in-memory by default return bitmap; } delete bitmap; } } } return NULL; } BOOL DLL_CALLCONV FreeImage_SaveMultiBitmapToMemory(FREE_IMAGE_FORMAT fif, FIMULTIBITMAP *bitmap, FIMEMORY *stream, int flags) { if (stream && stream->data) { FreeImageIO io; SetMemoryIO(&io); return FreeImage_SaveMultiBitmapToHandle(fif, bitmap, &io, (fi_handle)stream, flags); } return FALSE; }
27.364143
168
0.613722
aws4y
4f261cdeb0b5320194a0a3c3fa545dbdb6fcccbb
1,582
hpp
C++
cli_args.hpp
iszczesniak/ddpp
bc27ad2b7f699d8ef2e11dcb3b56d538d92e4b4e
[ "BSL-1.0" ]
null
null
null
cli_args.hpp
iszczesniak/ddpp
bc27ad2b7f699d8ef2e11dcb3b56d538d92e4b4e
[ "BSL-1.0" ]
null
null
null
cli_args.hpp
iszczesniak/ddpp
bc27ad2b7f699d8ef2e11dcb3b56d538d92e4b4e
[ "BSL-1.0" ]
null
null
null
#ifndef CLI_ARGS_HPP #define CLI_ARGS_HPP #include "connection.hpp" #include "routing.hpp" #include <optional> #include <string> /** * These are the program arguments. In this single class we store all * information passed at the command line. */ struct cli_args { /// ----------------------------------------------------------------- /// The network and routing options /// ----------------------------------------------------------------- /// The network file name. std::string net; /// The number of units. int units; // Use the generic Dijkstra search. bool gd = false; // Use the brute force search. bool bf = false; // Use the edge exclusion search. bool ee = false; /// ----------------------------------------------------------------- /// The traffic options /// ----------------------------------------------------------------- /// The mean client arrival time. double mcat; /// The offered load. double ol; /// The mean holding time. double mht; /// The mean number of units. double mnu; /// ----------------------------------------------------------------- /// The simulation options /// ----------------------------------------------------------------- /// The seed int seed; /// The population name. std::string population; /// The kickoff time for stats. double kickoff; /// The limit on the simulation time. double sim_time; }; /** * This function parses the command-line arguments. */ cli_args process_cli_args(int argc, const char* argv[]); #endif /* CLI_ARGS_HPP */
21.093333
71
0.484829
iszczesniak
4f26672294b4cc622c3bd4f079929719d6af4fc7
7,896
cpp
C++
src/dgetrs_nopiv_batched.cpp
shengren/magma-1.6.1
1adfee30b763e9491a869403e0f320b3888923b6
[ "BSD-3-Clause" ]
21
2017-10-06T05:05:05.000Z
2022-03-13T15:39:20.000Z
src/dgetrs_nopiv_batched.cpp
shengren/magma-1.6.1
1adfee30b763e9491a869403e0f320b3888923b6
[ "BSD-3-Clause" ]
1
2017-03-23T00:27:24.000Z
2017-03-23T00:27:24.000Z
src/dgetrs_nopiv_batched.cpp
shengren/magma-1.6.1
1adfee30b763e9491a869403e0f320b3888923b6
[ "BSD-3-Clause" ]
4
2018-01-09T15:49:58.000Z
2022-03-13T15:39:27.000Z
/* -- MAGMA (version 1.6.1) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver November 2013 @author Azzam Haidar @generated from zgetrs_nopiv_batched.cpp normal z -> d, Fri Jan 30 19:00:19 2015 */ #include "common_magma.h" #include "batched_kernel_param.h" /** Purpose ------- Solves a system of linear equations A * X = B, A**T * X = B, or A**H * X = B with a general N-by-N matrix A using the LU factorization computed by DGETRF_GPU. Arguments --------- @param[in] trans magma_trans_t Specifies the form of the system of equations: - = MagmaNoTrans: A * X = B (No transpose) - = MagmaTrans: A**T * X = B (Transpose) - = MagmaConjTrans: A**H * X = B (Conjugate transpose) @param[in] n INTEGER The order of the matrix A. N >= 0. @param[in] nrhs INTEGER The number of right hand sides, i.e., the number of columns of the matrix B. NRHS >= 0. @param[in] dA DOUBLE_PRECISION array on the GPU, dimension (LDA,N) The factors L and U from the factorization A = P*L*U as computed by DGETRF_GPU. @param[in] ldda INTEGER The leading dimension of the array A. LDA >= max(1,N). @param[in] ipiv INTEGER array, dimension (N) The pivot indices from DGETRF; for 1 <= i <= N, row i of the matrix was interchanged with row IPIV(i). @param[in,out] dB DOUBLE_PRECISION array on the GPU, dimension (LDB,NRHS) On entry, the right hand side matrix B. On exit, the solution matrix X. @param[in] lddb INTEGER The leading dimension of the array B. LDB >= max(1,N). @param[out] info INTEGER - = 0: successful exit - < 0: if INFO = -i, the i-th argument had an illegal value @ingroup magma_dgesv_comp ********************************************************************/ extern "C" magma_int_t magma_dgetrs_nopiv_batched( magma_trans_t trans, magma_int_t n, magma_int_t nrhs, double **dA_array, magma_int_t ldda, double **dB_array, magma_int_t lddb, magma_int_t *info_array, magma_int_t batchCount, magma_queue_t queue) { /* Local variables */ magma_int_t notran = (trans == MagmaNoTrans); magma_int_t info = 0; if ( (! notran) && (trans != MagmaTrans) && (trans != MagmaConjTrans) ) { info = -1; } else if (n < 0) { info = -2; } else if (nrhs < 0) { info = -3; } else if (ldda < max(1,n)) { info = -5; } else if (lddb < max(1,n)) { info = -8; } if (info != 0) { magma_xerbla( __func__, -(info) ); return info; } /* Quick return if possible */ if (n == 0 || nrhs == 0) { return info; } double **dA_displ = NULL; double **dB_displ = NULL; double **dW1_displ = NULL; double **dW2_displ = NULL; double **dW3_displ = NULL; double **dW4_displ = NULL; double **dinvA_array = NULL; double **dwork_array = NULL; magma_malloc((void**)&dA_displ, batchCount * sizeof(*dA_displ)); magma_malloc((void**)&dB_displ, batchCount * sizeof(*dB_displ)); magma_malloc((void**)&dW1_displ, batchCount * sizeof(*dW1_displ)); magma_malloc((void**)&dW2_displ, batchCount * sizeof(*dW2_displ)); magma_malloc((void**)&dW3_displ, batchCount * sizeof(*dW3_displ)); magma_malloc((void**)&dW4_displ, batchCount * sizeof(*dW4_displ)); magma_malloc((void**)&dinvA_array, batchCount * sizeof(*dinvA_array)); magma_malloc((void**)&dwork_array, batchCount * sizeof(*dwork_array)); magma_int_t invA_msize = ((n+TRI_NB-1)/TRI_NB)*TRI_NB*TRI_NB; magma_int_t dwork_msize = n*nrhs; double* dinvA = NULL; double* dwork = NULL;// dinvA and dwork are workspace in dtrsm magma_dmalloc( &dinvA, invA_msize * batchCount); magma_dmalloc( &dwork, dwork_msize * batchCount ); /* check allocation */ if ( dW1_displ == NULL || dW2_displ == NULL || dW3_displ == NULL || dW4_displ == NULL || dinvA_array == NULL || dwork_array == NULL || dinvA == NULL || dwork == NULL || dA_displ == NULL || dB_displ == NULL ) { magma_free(dA_displ); magma_free(dB_displ); magma_free(dW1_displ); magma_free(dW2_displ); magma_free(dW3_displ); magma_free(dW4_displ); magma_free(dinvA_array); magma_free(dwork_array); magma_free( dinvA ); magma_free( dwork ); info = MAGMA_ERR_DEVICE_ALLOC; magma_xerbla( __func__, -(info) ); return info; } magmablas_dlaset_q(MagmaFull, invA_msize, batchCount, MAGMA_D_ZERO, MAGMA_D_ZERO, dinvA, invA_msize, queue); magmablas_dlaset_q(MagmaFull, dwork_msize, batchCount, MAGMA_D_ZERO, MAGMA_D_ZERO, dwork, dwork_msize, queue); dset_pointer(dwork_array, dwork, n, 0, 0, dwork_msize, batchCount, queue); dset_pointer(dinvA_array, dinvA, TRI_NB, 0, 0, invA_msize, batchCount, queue); magma_ddisplace_pointers(dA_displ, dA_array, ldda, 0, 0, batchCount, queue); magma_ddisplace_pointers(dB_displ, dB_array, lddb, 0, 0, batchCount, queue); magma_queue_t cstream; magmablasGetKernelStream(&cstream); //printf(" I am after malloc getri\n"); if (notran) { // solve dwork = L^-1 * NRHS magmablas_dtrsm_outofplace_batched(MagmaLeft, MagmaLower, MagmaNoTrans, MagmaUnit, 1, n, nrhs, MAGMA_D_ONE, dA_displ, ldda, // dA dB_displ, lddb, // dB dwork_array, n, // dX //output dinvA_array, invA_msize, dW1_displ, dW2_displ, dW3_displ, dW4_displ, 1, batchCount, queue); // solve X = U^-1 * dwork magmablas_dtrsm_outofplace_batched(MagmaLeft, MagmaUpper, MagmaNoTrans, MagmaNonUnit, 1, n, nrhs, MAGMA_D_ONE, dA_displ, ldda, // dA dwork_array, n, // dB dB_displ, lddb, // dX //output dinvA_array, invA_msize, dW1_displ, dW2_displ, dW3_displ, dW4_displ, 1, batchCount, queue); } else{ /* Solve A**T * X = B or A**H * X = B. */ // solve magmablas_dtrsm_outofplace_batched(MagmaLeft, MagmaUpper, trans, MagmaUnit, 1, n, nrhs, MAGMA_D_ONE, dA_displ, ldda, // dA dB_displ, lddb, // dB dwork_array, n, // dX //output dinvA_array, invA_msize, dW1_displ, dW2_displ, dW3_displ, dW4_displ, 1, batchCount, queue); // solve magmablas_dtrsm_outofplace_batched(MagmaLeft, MagmaLower, trans, MagmaNonUnit, 1, n, nrhs, MAGMA_D_ONE, dA_displ, ldda, // dA dwork_array, n, // dB dB_displ, lddb, // dX //output dinvA_array, invA_msize, dW1_displ, dW2_displ, dW3_displ, dW4_displ, 1, batchCount, queue); } magma_queue_sync(cstream); magma_free(dA_displ); magma_free(dB_displ); magma_free(dW1_displ); magma_free(dW2_displ); magma_free(dW3_displ); magma_free(dW4_displ); magma_free(dinvA_array); magma_free(dwork_array); magma_free( dinvA ); magma_free( dwork ); return info; }
33.457627
114
0.556864
shengren
4f272caf25db73404a223d05b9618e45e9ad4f6c
983
cpp
C++
src/point.cpp
ASjet/GreedySnake
c07a22ede63a8c4f42bc6af2d8c8c95cd46b0311
[ "MIT" ]
1
2020-05-30T07:15:18.000Z
2020-05-30T07:15:18.000Z
src/point.cpp
ITFS777/GreedySnake
c07a22ede63a8c4f42bc6af2d8c8c95cd46b0311
[ "MIT" ]
null
null
null
src/point.cpp
ITFS777/GreedySnake
c07a22ede63a8c4f42bc6af2d8c8c95cd46b0311
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include "point.h" #include "cursor.h" //////////////////////////////////////////////////////////////////////////////// Point Point::setPos(int px, int py) { x = px; y = py; return *this; } //////////////////////////////////////////////////////////////////////////////// Point Point::print(string str) const { SetCursorPosition(x, y); std::cout << str; return *this; } //////////////////////////////////////////////////////////////////////////////// Point Point::clear(void) const { SetCursorPosition(x, y); std::cout << " "; return *this; } //////////////////////////////////////////////////////////////////////////////// Point Point::setCursorHere(void) const { SetCursorPosition(x, y); return *this; } //////////////////////////////////////////////////////////////////////////////// Point Point::move(int movement_x, int movement_y) { x += movement_x; y += movement_y; return *this; }
25.868421
80
0.364191
ASjet
4f27ecd1cb71c6a135ca2cb4186af73b73d21aaf
6,378
cpp
C++
clang/test/CodeGenCXX/reference-cast.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
clang/test/CodeGenCXX/reference-cast.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
clang/test/CodeGenCXX/reference-cast.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
// RUN: %clang_cc1 -emit-llvm -triple x86_64-apple-darwin10 -o - %s | FileCheck %s // PR6024 extern int i; // CHECK: define{{.*}} nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) i32* @_Z16lvalue_noop_castv() [[NUW:#[0-9]+]] const int &lvalue_noop_cast() { if (i == 0) // CHECK: store i32 17, i32* return (const int&)17; else if (i == 1) // CHECK: store i32 17, i32* return static_cast<const int&>(17); // CHECK: store i32 17, i32* return 17; } // CHECK-LABEL: define{{.*}} nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) i16* @_Z20lvalue_integral_castv() const short &lvalue_integral_cast() { if (i == 0) // CHECK: store i16 17, i16* return (const short&)17; else if (i == 1) // CHECK: store i16 17, i16* return static_cast<const short&>(17); // CHECK: store i16 17, i16* return 17; } // CHECK-LABEL: define{{.*}} nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) i16* @_Z29lvalue_floating_integral_castv() const short &lvalue_floating_integral_cast() { if (i == 0) // CHECK: store i16 17, i16* return (const short&)17.5; else if (i == 1) // CHECK: store i16 17, i16* return static_cast<const short&>(17.5); // CHECK: store i16 17, i16* return 17.5; } // CHECK-LABEL: define{{.*}} nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) float* @_Z29lvalue_integral_floating_castv() const float &lvalue_integral_floating_cast() { if (i == 0) // CHECK: store float 1.700000e+{{0*}}1, float* return (const float&)17; else if (i == 1) // CHECK: store float 1.700000e+{{0*}}1, float* return static_cast<const float&>(17); // CHECK: store float 1.700000e+{{0*}}1, float* return 17; } // CHECK-LABEL: define{{.*}} nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) float* @_Z20lvalue_floating_castv() const float &lvalue_floating_cast() { if (i == 0) // CHECK: store float 1.700000e+{{0*}}1, float* return (const float&)17.0; else if (i == 1) // CHECK: store float 1.700000e+{{0*}}1, float* return static_cast<const float&>(17.0); // CHECK: store float 1.700000e+{{0*}}1, float* return 17.0; } int get_int(); // CHECK-LABEL: define{{.*}} nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) i8* @_Z24lvalue_integer_bool_castv() const bool &lvalue_integer_bool_cast() { if (i == 0) // CHECK: call i32 @_Z7get_intv() // CHECK: store i8 return (const bool&)get_int(); else if (i == 1) // CHECK: call i32 @_Z7get_intv() // CHECK: store i8 return static_cast<const bool&>(get_int()); // CHECK: call i32 @_Z7get_intv() // CHECK: store i8 return get_int(); } float get_float(); // CHECK-LABEL: define{{.*}} nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) i8* @_Z25lvalue_floating_bool_castv() const bool &lvalue_floating_bool_cast() { if (i == 0) // CHECK: call float @_Z9get_floatv() // CHECK: fcmp une float // CHECK: store i8 return (const bool&)get_float(); else if (i == 1) // CHECK: call float @_Z9get_floatv() // CHECK: fcmp une float // CHECK: store i8 return static_cast<const bool&>(get_float()); // CHECK: call float @_Z9get_floatv() // CHECK: fcmp une float // CHECK: store i8 return get_float(); } struct X { }; typedef int X::*pm; typedef int (X::*pmf)(int); pm get_pointer_to_member_data(); pmf get_pointer_to_member_function(); // CHECK-LABEL: define{{.*}} nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) i8* @_Z26lvalue_ptrmem_to_bool_castv() const bool &lvalue_ptrmem_to_bool_cast() { if (i == 0) // CHECK: call i64 @_Z26get_pointer_to_member_datav() // CHECK: store i8 // CHECK: store i8* return (const bool&)get_pointer_to_member_data(); else if (i == 1) // CHECK: call i64 @_Z26get_pointer_to_member_datav() // CHECK: store i8 // CHECK: store i8* return static_cast<const bool&>(get_pointer_to_member_data()); // CHECK: call i64 @_Z26get_pointer_to_member_datav() // CHECK: store i8 // CHECK: store i8* return get_pointer_to_member_data(); } // CHECK-LABEL: define{{.*}} nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) i8* @_Z27lvalue_ptrmem_to_bool_cast2v const bool &lvalue_ptrmem_to_bool_cast2() { if (i == 0) // CHECK: {{call.*_Z30get_pointer_to_member_functionv}} // CHECK: store i8 // CHECK: store i8* return (const bool&)get_pointer_to_member_function(); else if (i == 1) // CHECK: {{call.*_Z30get_pointer_to_member_functionv}} // CHECK: store i8 // CHECK: store i8* return static_cast<const bool&>(get_pointer_to_member_function()); // CHECK: {{call.*_Z30get_pointer_to_member_functionv}} // CHECK: store i8 // CHECK: store i8* return get_pointer_to_member_function(); } _Complex double get_complex_double(); // CHECK: {{define.*_Z2f1v}} const _Complex float &f1() { if (i == 0) // CHECK: {{call.*_Z18get_complex_doublev}} // CHECK: fptrunc // CHECK: fptrunc // CHECK: store float // CHECK: store float return (const _Complex float&)get_complex_double(); else if (i == 1) // CHECK: {{call.*_Z18get_complex_doublev}} // CHECK: fptrunc // CHECK: fptrunc // CHECK: store float // CHECK: store float return static_cast<const _Complex float&>(get_complex_double()); // CHECK: {{call.*_Z18get_complex_doublev}} // CHECK: fptrunc // CHECK: fptrunc // CHECK: store float // CHECK: store float return get_complex_double(); } // CHECK-LABEL: define{{.*}} i32 @_Z7pr10592RKi(i32* unsigned pr10592(const int &v) { // CHECK: [[VADDR:%[a-zA-Z0-9.]+]] = alloca i32* // CHECK-NEXT: [[REFTMP:%[a-zA-Z0-9.]+]] = alloca i32 // CHECK-NEXT: store i32* [[V:%[a-zA-Z0-9.]+]], i32** [[VADDR]] // CHECK-NEXT: [[VADDR_1:%[a-zA-Z0-9.]+]] = load i32*, i32** [[VADDR]] // CHECK-NEXT: [[VVAL:%[a-zA-Z0-9.]+]] = load i32, i32* [[VADDR_1]] // CHECK-NEXT: store i32 [[VVAL]], i32* [[REFTMP]] // CHECK-NEXT: [[VVAL_I:%[a-zA-Z0-9.]+]] = load i32, i32* [[REFTMP]] // CHECK-NEXT: ret i32 [[VVAL_I]] return static_cast<const unsigned &>(v); } namespace PR10650 { struct Helper { unsigned long long id(); }; unsigned long long test(Helper *obj) { return static_cast<const unsigned long long&>(obj->id()); } // CHECK-LABEL: define{{.*}} i64 @_ZN7PR106504testEPNS_6HelperE // CHECK: store i64 } // CHECK: attributes [[NUW]] = { mustprogress noinline nounwind{{.*}} }
32.375635
126
0.6328
mkinsner
4f28ed79035c5618b5d7b8c757caa1390ed920f6
13,010
cc
C++
src/yb/util/decimal.cc
pritamdamania87/yugabyte-db
70355f6c9248356e84cf21588013ea477fd04a5d
[ "Apache-2.0", "CC0-1.0" ]
1
2021-01-15T00:24:31.000Z
2021-01-15T00:24:31.000Z
src/yb/util/decimal.cc
pritamdamania87/yugabyte-db
70355f6c9248356e84cf21588013ea477fd04a5d
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
src/yb/util/decimal.cc
pritamdamania87/yugabyte-db
70355f6c9248356e84cf21588013ea477fd04a5d
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
// Copyright (c) YugaByte, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations // under the License. // #include <vector> #include <limits> #include <iomanip> #include <glog/logging.h> #include "yb/gutil/strings/substitute.h" #include "yb/util/decimal.h" using std::string; using std::vector; namespace yb { namespace util { void Decimal::clear() { digits_ = {}; exponent_ = VarInt(0); is_positive_ = true; } string Decimal::ToDebugString() const { string output = "[ "; output += is_positive_ ? "+" : "-"; output += " 10^"; output += exponent_.is_positive_ ? "+" : ""; output += exponent_.ToString() + " * 0."; for (int digit : digits_) { output += '0' + digit; } output += " ]"; return output; } Status Decimal::ToPointString(string* string_val, const int max_length) const { if (digits_.empty()) { *string_val = "0"; return Status::OK(); } int64_t exponent = 0; RETURN_NOT_OK(exponent_.ToInt64(&exponent)); if (exponent > max_length || exponent < -max_length) { return STATUS_SUBSTITUTE(InvalidArgument, "Max length $0 too small to encode decimal with exponent $1", max_length, exponent); } string output; if (!is_positive_) { output = "-"; } if (exponent <= 0) { output += "0."; for (int i = 0; i < -exponent; i++) { output.push_back('0'); } for (size_t i = 0; i < digits_.size(); i++) { output.push_back('0' + digits_[i]); if (output.size() > max_length) { return STATUS_SUBSTITUTE(InvalidArgument, "Max length $0 too small to encode Decimal", max_length); } } } else { for (size_t i = 0; i < digits_.size(); i++) { if (exponent == i) { output.push_back('.'); } output.push_back('0' + digits_[i]); if (output.size() > max_length) { return STATUS_SUBSTITUTE(InvalidArgument, "Max length $0 too small to encode Decimal", max_length); } } for (size_t i = digits_.size(); i < exponent; i++) { output.push_back('0'); if (output.size() > max_length) { return STATUS_SUBSTITUTE(InvalidArgument, "Max length $0 too small to encode Decimal", max_length); } } } *string_val = std::move(output); return Status::OK(); } string Decimal::ToScientificString() const { if (digits_.empty()) { return "0"; } string output; if (!is_positive_) { output = "-"; } output.push_back('0' + digits_[0]); output.push_back('.'); for (size_t i = 1; i < digits_.size(); i++) { output.push_back('0' + digits_[i]); } output.push_back('e'); VarInt exponent = exponent_ + VarInt(-1); if (exponent.is_positive_) { output += "+"; } output += exponent.ToString(); return output; } string Decimal::ToString() const { string output; if (Decimal::ToPointString(&output).ok()) { return output; } else { return ToScientificString(); } } Status Decimal::ToDouble(double* double_val) const { try { *double_val = std::stod(ToString()); } catch (std::exception& e) { // Possible exception types: std::invalid_argument, std::out_of_range. return STATUS(InvalidArgument, e.what()); } return Status::OK(); } Status Decimal::ToVarInt(VarInt *varint_value, const int max_length) const { int64_t exponent = 0; RETURN_NOT_OK(exponent_.ToInt64(&exponent)); if (exponent <= 0) { *varint_value = VarInt(0); return Status::OK(); } if (exponent > max_length) { return STATUS_SUBSTITUTE(InvalidArgument, "Max length $0 too small to convert Decimal to VarInt, need $1", max_length, exponent); } vector<uint8_t> digits(digits_.begin(), digits_.size() > exponent ? digits_.begin() + exponent : digits_.end()); while (digits.size() < exponent) { digits.push_back(0); } std::reverse(digits.begin(), digits.end()); *varint_value = VarInt(digits, 10, is_positive_); return Status::OK(); } Status Decimal::FromString(const Slice &slice) { if (slice.empty()) { return STATUS(InvalidArgument, "Cannot decode empty slice to Decimal"); } is_positive_ = slice[0] != '-'; size_t i = 0; if (slice[0] == '+' || slice[0] == '-') { i++; } bool point_found = false; size_t point_position = 0; digits_.clear(); for (; i < slice.size() && slice[i] != 'e' && slice[i] != 'E'; i++) { if (slice[i] == '.' && !point_found) { point_found = true; point_position = digits_.size(); continue; } if (PREDICT_TRUE(slice[i] >= '0' && slice[i] <= '9')) { digits_.push_back(slice[i]-'0'); } else { return STATUS_SUBSTITUTE( InvalidArgument, "Invalid character $0 found at position $1 when parsing Decimal $2", slice[i], i, slice.ToString()); } } if (PREDICT_FALSE(digits_.empty())) { return STATUS_SUBSTITUTE( InvalidArgument, "There are no digits in the decimal $0 before the e / E", slice.ToString()); } if (!point_found) { point_position = digits_.size(); } if (i < slice.size()) { Slice exponent_slice(slice); exponent_slice.remove_prefix(i+1); RETURN_NOT_OK(exponent_.FromString(exponent_slice)); } else { exponent_ = VarInt(0); } exponent_ = exponent_ + VarInt(static_cast<int64_t> (point_position)); make_canonical(); return Status::OK(); } constexpr size_t kPrecisionLimit = 20; namespace { string StringFromDouble(double double_val, int precision_limit = kPrecisionLimit) { std::stringstream ss; ss << std::setprecision(precision_limit); ss << double_val; return ss.str(); } } // namespace Status Decimal::FromDouble(double double_val) { string str = StringFromDouble(double_val); if (str == "nan") { return STATUS(Corruption, "Cannot convert nan to Decimal"); } else if (str == "inf") { return STATUS(Corruption, "Cannot convert inf to Decimal"); } else if (str == "-inf") { return STATUS(Corruption, "Cannot convert -inf to Decimal"); } return FromString(str); } Status Decimal::FromVarInt(const VarInt &varint_val) { return FromString(varint_val.ToString()); } bool Decimal::is_integer() const { return digits_.empty() || exponent_ >= VarInt(static_cast<int64_t>(digits_.size())); } int Decimal::CompareTo(const Decimal &other) const { if (is_positive_ != other.is_positive_) { return static_cast<int>(is_positive_) - static_cast<int>(other.is_positive_); } int comp; // We must compare zeros in a special way because the exponent logic doesn't work with special // canonicalization for zero. if (digits_.empty() || other.digits_.empty()) { comp = static_cast<int>(digits_.empty()) - static_cast<int>(other.digits_.empty()); return is_positive_ ? -comp : comp; } comp = exponent_.CompareTo(other.exponent_); if (comp != 0) { return is_positive_ ? comp : -comp; } for (size_t i = 0; i < digits_.size() && i < other.digits_.size(); i++) { comp = static_cast<int>(digits_[i]) - static_cast<int>(other.digits_[i]); if (comp != 0) { return is_positive_ ? comp : -comp; } } comp = static_cast<int>(this->digits_.size()) - static_cast<int>(other.digits_.size()); return is_positive_ ? comp : -comp; } string Decimal::EncodeToComparable() const { // Zero is encoded to the special value 128. if (digits_.empty()) { return string(1, 128); } // We reserve two bits for sign: -, zero, and +. Their sign portions are resp. '00', '10', '11'. string exponent = exponent_.EncodeToComparable(/* is_signed */ true, /* num_reserved_bits */ 2); const string mantissa = VarInt(digits_, 10).EncodeToDigitPairs(); string output = exponent + mantissa; // The first two (reserved) bits are set to 1 here. output[0] += 192; // For negatives, everything is complemented (including the sign bits) which were set to 1 above. if (!is_positive_) { for (int i = 0; i < output.size(); i++) { output[i] = ~output[i]; // Bitwise not. } } return output; } Status Decimal::DecodeFromComparable(const Slice& slice, size_t *num_decoded_bytes) { if (slice.empty()) { return STATUS(Corruption, "Cannot decode Decimal from empty slice."); } // Zero is specially decoded from the value 128. if (slice[0] == 128) { clear(); *num_decoded_bytes = 1; return Status::OK(); } // The first bit is enough to decode the sign. is_positive_ = slice[0] >= 128; // We have to complement everything if negative, so we are making a copy. string encoded = slice.ToString(); if (!is_positive_) { for (size_t i = 0; i < encoded.size(); i++) { encoded[i] = ~encoded[i]; } } size_t num_exponent_bytes = 0; RETURN_NOT_OK(exponent_.DecodeFromComparable( encoded, &num_exponent_bytes, /* is signed */ true, /* num_reserved_bits */ 2)); Slice remaining_slice(encoded); remaining_slice.remove_prefix(num_exponent_bytes); VarInt mantissa; size_t num_mantissa_bytes = 0; RETURN_NOT_OK(mantissa.DecodeFromDigitPairs(remaining_slice, &num_mantissa_bytes)); digits_ = vector<uint8_t>(mantissa.digits_.begin(), mantissa.digits_.end()); *num_decoded_bytes = num_exponent_bytes + num_mantissa_bytes; return Status::OK(); } Status Decimal::DecodeFromComparable(const Slice& slice) { size_t num_decoded_bytes; return DecodeFromComparable(slice, &num_decoded_bytes); } Status Decimal::DecodeFromComparable(const string& str) { return DecodeFromComparable(Slice(str)); } string Decimal::EncodeToSerializedBigDecimal(bool* is_out_of_range) const { // Note that BigDecimal's scale is not the same as our exponent, but related by the following: VarInt varint_scale = VarInt(static_cast<int64_t> (digits_.size())) - exponent_; // Must use 4 bytes for the two's complement encoding of the scale. bool is_overflow = false; string scale = varint_scale.EncodeToTwosComplement(&is_overflow, 4); *is_out_of_range = is_overflow; vector<uint8_t> digits(digits_); // VarInt representation needs reversed digits. std::reverse(digits.begin(), digits.end()); // Note that the mantissa varint needs to have the same sign as the current decimal. // Get the digit array in int from int8_t in this class. string mantissa = VarInt(digits, 10, is_positive_).EncodeToTwosComplement(&is_overflow); return scale + mantissa; } Status Decimal::DecodeFromSerializedBigDecimal(const Slice &slice) { if (slice.size() < 5) { return STATUS_SUBSTITUTE( Corruption, "Serialized BigDecimal must have at least 5 bytes. Found $0", slice.size()); } // Decode the scale from the first 4 bytes. VarInt scale; RETURN_NOT_OK(scale.DecodeFromTwosComplement(Slice(slice.data(), 4))); VarInt mantissa; RETURN_NOT_OK(mantissa.DecodeFromTwosComplement(Slice(slice.data() + 4, slice.size() - 4))); // Must convert to base 10 before we can interpret as digits in our Decimal representation mantissa = mantissa.ConvertToBase(10); // The sign of the BigDecimal is the sign of the mantissa is_positive_ = mantissa.is_positive_; digits_ = vector <uint8_t> (mantissa.digits_.begin(), mantissa.digits_.end()); // The varint has the digits in reverse order std::reverse(digits_.begin(), digits_.end()); exponent_ = VarInt(static_cast<int64_t> (digits_.size())) - scale; make_canonical(); return Status::OK(); } bool Decimal::IsIdenticalTo(const Decimal &other) const { return is_positive_ == other.is_positive_ && exponent_ == other.exponent_ && digits_ == other.digits_; } bool Decimal::is_canonical() const { if (digits_.empty()) { return is_positive_ && exponent_ == VarInt(0); } return digits_.front() != 0 && digits_.back() != 0; } void Decimal::make_canonical() { if (is_canonical()) { return; } size_t num_zeros = 0; while (num_zeros < digits_.size() && digits_[num_zeros] == 0) { num_zeros++; } exponent_ = exponent_ - VarInt(num_zeros); for (size_t i = num_zeros; i < digits_.size() + num_zeros; i++) { digits_[i-num_zeros] = i < digits_.size() ? digits_[i] : 0; } while (!digits_.empty() && digits_.back() == 0) { digits_.pop_back(); } if (digits_.empty()) { clear(); } } Decimal DecimalFromComparable(const Slice& slice) { Decimal decimal; CHECK_OK(decimal.DecodeFromComparable(slice)); return decimal; } Decimal DecimalFromComparable(const std::string& str) { return DecimalFromComparable(Slice(str)); } std::ostream& operator<<(ostream& os, const Decimal& d) { os << d.ToString(); return os; } } // namespace util } // namespace yb
31.274038
100
0.661337
pritamdamania87
4f29447f962c137f6be33b5b63db77efaf3c0b91
1,479
cpp
C++
HackerRank/ProblemSolving/cppSolutions/Data Structures/Trees/treePreorderTraversal.cpp
pakosel/competitive-coding-problems
187a2f13725e06ab3301ae2be37f16fbec0c0588
[ "MIT" ]
17
2017-08-12T14:42:46.000Z
2022-02-26T16:35:44.000Z
HackerRank/ProblemSolving/cppSolutions/Data Structures/Trees/treePreorderTraversal.cpp
pakosel/competitive-coding-problems
187a2f13725e06ab3301ae2be37f16fbec0c0588
[ "MIT" ]
21
2019-09-20T07:06:27.000Z
2021-11-02T10:30:50.000Z
HackerRank/ProblemSolving/cppSolutions/Data Structures/Trees/treePreorderTraversal.cpp
pakosel/competitive-coding-problems
187a2f13725e06ab3301ae2be37f16fbec0c0588
[ "MIT" ]
21
2017-05-28T10:15:07.000Z
2021-07-20T07:19:58.000Z
#include <bits/stdc++.h> using namespace std; class Node { public: int data; Node *left; Node *right; Node(int d) { data = d; left = NULL; right = NULL; } }; class Solution { public: Node* insert(Node* root, int data) { if(root == NULL) { return new Node(data); } else { Node* cur; if(data <= root->data) { cur = insert(root->left, data); root->left = cur; } else { cur = insert(root->right, data); root->right = cur; } return root; } } /* you only have to complete the function given below. Node is defined as class Node { public: int data; Node *left; Node *right; Node(int d) { data = d; left = NULL; right = NULL; } }; */ void preOrder(Node *root) { if(root==NULL){ return; } cout<<root->data<<" "; preOrder(root->left); preOrder(root->right); } }; //End of Solution int main() { Solution myTree; Node* root = NULL; int t; int data; std::cin >> t; while(t-- > 0) { std::cin >> data; root = myTree.insert(root, data); } myTree.preOrder(root); return 0; }
18.036585
56
0.415822
pakosel
4f2acf2ee7baf76ba9ec40965975179cc65cc4c0
14,878
cpp
C++
src/InstructionWalker.cpp
Mookel/VC4C
d72978253820e4175fa591206dedda6c586068b3
[ "MIT" ]
null
null
null
src/InstructionWalker.cpp
Mookel/VC4C
d72978253820e4175fa591206dedda6c586068b3
[ "MIT" ]
null
null
null
src/InstructionWalker.cpp
Mookel/VC4C
d72978253820e4175fa591206dedda6c586068b3
[ "MIT" ]
null
null
null
/* * Author: doe300 * * See the file "LICENSE" for the full license governing this code. */ #include "InstructionWalker.h" #include "BasicBlock.h" #include "CompilationError.h" #include "Method.h" #include "analysis/ControlFlowGraph.h" using namespace vc4c; const InstructionWalker tombstone_traits<InstructionWalker>::tombstone; bool InstructionVisitor::visit(const InstructionWalker& start) const { InstructionWalker it(start); while(true) { auto res = op(it); switch(res) { case InstructionVisitResult::CONTINUE: { if(followJumps && it.get<intermediate::Branch>()) { intermediate::Branch* jump = it.get<intermediate::Branch>(); auto jumpIt = it; for(auto target : jump->getTargetLabels()) { if(auto nextBlock = it.getBasicBlock()->method.findBasicBlock(target)) { bool cont = visit(nextBlock->walk()); if(!cont) return false; } } if(jump->isUnconditional()) // the control-flow always jumps, destination is already processed return true; // handle either-or-jumps, check previous instruction intermediate::Branch* prevJump = it.copy().previousInBlock().get<intermediate::Branch>(); auto prevJumpIt = it; if(prevJump != nullptr && jump->branchCondition.isInversionOf(prevJump->branchCondition)) { auto lastBranchCond = it.getBasicBlock()->findLastSettingOfFlags(jumpIt); auto secondLastBranchCond = it.getBasicBlock()->findLastSettingOfFlags(prevJumpIt); if(lastBranchCond == secondLastBranchCond) // the branches are only guaranteed to cover all cases if they refer to the same branch // condition return true; } } if(stopAtBlock) { it.nextInBlock(); if(it.isEndOfBlock()) return true; continue; } else { it.nextInMethod(); if(it.isEndOfMethod()) return true; continue; } } case InstructionVisitResult::STOP_BRANCH: // stop this branch, but continue with other branches return true; case InstructionVisitResult::STOP_ALL: // stop all return false; } throw CompilationError(CompilationStep::GENERAL, "Unhandled case of instruction visiting"); } } bool InstructionVisitor::visitReverse(const InstructionWalker& start, analysis::ControlFlowGraph* blockGraph) const { // FIXME has problems with instructionwalkers freed in Method::cleanEmptyInstructions() (e.g. TestEmulator) InstructionWalker it(start); while(true) { auto res = op(it); switch(res) { case InstructionVisitResult::CONTINUE: { if(!it.isStartOfBlock()) { it.previousInBlock(); continue; } else if(stopAtBlock) { return true; } else if(!followJumps) { it.previousInMethod(); continue; } else // start of block and follow jumps -> follow jumps backwards { bool continueBranches = true; if(blockGraph != nullptr) { // use pre-calculated graph of basic blocks blockGraph->assertNode(it.getBasicBlock()) .forAllIncomingEdges([&continueBranches, this, blockGraph]( const analysis::CFGNode& node, const analysis::CFGEdge& edge) -> bool { // this makes sure, a STOP_ALL skips other predecessors if(continueBranches) continueBranches = visitReverse(edge.data.getPredecessor(node.key), blockGraph); return true; }); } else { // re-calculate predecessor blocks it.getBasicBlock()->forPredecessors([&continueBranches, this](InstructionWalker it) -> void { // this makes sure, a STOP_ALL skips other predecessors if(continueBranches) continueBranches = visitReverse(it); }); } return continueBranches; } } case InstructionVisitResult::STOP_BRANCH: // stop this branch, but continue with other branches return true; case InstructionVisitResult::STOP_ALL: // stop all return false; } throw CompilationError(CompilationStep::GENERAL, "Unhandled case of instruction visiting"); } } InstructionWalker::InstructionWalker() : basicBlock(nullptr), pos(nullptr) {} InstructionWalker::InstructionWalker(BasicBlock* basicBlock, intermediate::InstructionsIterator pos) : basicBlock(basicBlock), pos(pos) { } BasicBlock* InstructionWalker::getBasicBlock() { return basicBlock; } const BasicBlock* InstructionWalker::getBasicBlock() const { return basicBlock; } InstructionWalker& InstructionWalker::nextInBlock() { ++pos; return *this; } InstructionWalker& InstructionWalker::previousInBlock() { --pos; return *this; } InstructionWalker& InstructionWalker::nextInMethod() { if(!isEndOfBlock()) // we need this check since for a linked list it seems that last->next == first, which would jump back to the // label of the block nextInBlock(); if(isEndOfBlock()) { if(auto tmp = basicBlock->method.getNextBlockAfter(basicBlock)) { basicBlock = tmp; pos = basicBlock->instructions.begin(); } } return *this; } InstructionWalker& InstructionWalker::previousInMethod() { previousInBlock(); if(isStartOfBlock()) { if(auto tmp = basicBlock->method.getPreviousBlock(basicBlock)) { basicBlock = tmp; pos = basicBlock->instructions.end(); --pos; } } return *this; } InstructionWalker InstructionWalker::copy() const { return InstructionWalker(basicBlock, pos); } bool InstructionWalker::operator==(const InstructionWalker& other) const { return basicBlock == other.basicBlock && pos == other.pos; } bool InstructionWalker::isEndOfMethod() const { if(basicBlock == nullptr) return true; if(!isEndOfBlock()) return false; const auto& lastBlock = *(--basicBlock->method.end()); return &lastBlock == basicBlock; } bool InstructionWalker::isStartOfMethod() const { return isStartOfBlock() && basicBlock->isStartOfMethod(); } bool InstructionWalker::isEndOfBlock() const { if(basicBlock == nullptr) return true; return pos == basicBlock->instructions.end(); } bool InstructionWalker::isStartOfBlock() const { if(basicBlock == nullptr) return false; return pos == basicBlock->instructions.begin(); } static inline void throwOnEnd(bool isEnd) { if(isEnd) throw CompilationError(CompilationStep::GENERAL, "End of method or block reached!"); } intermediate::IntermediateInstruction* InstructionWalker::get() { throwOnEnd(isEndOfBlock()); return (*pos).get(); } const intermediate::IntermediateInstruction* InstructionWalker::get() const { throwOnEnd(isEndOfBlock()); return (*pos).get(); } intermediate::IntermediateInstruction* InstructionWalker::release() { throwOnEnd(isEndOfBlock()); if(get<intermediate::BranchLabel>()) basicBlock->method.updateCFGOnBlockRemoval(basicBlock); if(get<intermediate::Branch>()) { // need to remove the branch from the block before triggering the CFG update std::unique_ptr<intermediate::IntermediateInstruction> tmp(pos->release()); basicBlock->method.updateCFGOnBranchRemoval( *basicBlock, dynamic_cast<intermediate::Branch*>(tmp.get())->getTargetLabels()); return tmp.release(); } return (*pos).release(); } InstructionWalker& InstructionWalker::reset(intermediate::IntermediateInstruction* instr) { throwOnEnd(isEndOfBlock()); if(dynamic_cast<intermediate::BranchLabel*>(instr) != dynamic_cast<intermediate::BranchLabel*>((*pos).get())) throw CompilationError(CompilationStep::GENERAL, "Can't add labels into a basic block", instr->to_string()); // if we reset the label with another label, the CFG dos not change if(get<intermediate::Branch>()) { // need to remove the branch from the block before triggering the CFG update std::unique_ptr<intermediate::IntermediateInstruction> tmp(pos->release()); basicBlock->method.updateCFGOnBranchRemoval( *basicBlock, dynamic_cast<intermediate::Branch*>(tmp.get())->getTargetLabels()); } (*pos).reset(instr); if(dynamic_cast<intermediate::Branch*>(instr)) basicBlock->method.updateCFGOnBranchInsertion(*this); return *this; } InstructionWalker& InstructionWalker::erase() { throwOnEnd(isEndOfBlock()); if(get<intermediate::BranchLabel>()) basicBlock->method.updateCFGOnBlockRemoval(basicBlock); if(get<intermediate::Branch>()) { // need to remove the branch from the block before triggering the CFG update std::unique_ptr<intermediate::IntermediateInstruction> tmp(pos->release()); basicBlock->method.updateCFGOnBranchRemoval( *basicBlock, dynamic_cast<intermediate::Branch*>(tmp.get())->getTargetLabels()); } pos = basicBlock->instructions.erase(pos); return *this; } InstructionWalker& InstructionWalker::safeErase() { if(!isEndOfBlock() && get() && get()->hasDecoration(intermediate::InstructionDecorations::MANDATORY_DELAY)) { reset((new intermediate::Nop(intermediate::DelayType::WAIT_REGISTER)) ->addDecorations(intermediate::InstructionDecorations::MANDATORY_DELAY)); return nextInBlock(); } return erase(); } InstructionWalker& InstructionWalker::emplace(intermediate::IntermediateInstruction* instr) { if(isStartOfBlock()) throw CompilationError( CompilationStep::GENERAL, "Can't emplace at the start of a basic block", instr->to_string()); if(basicBlock == nullptr) throw CompilationError( CompilationStep::GENERAL, "Can't emplace into an iterator which is not associated with a basic block"); if(dynamic_cast<intermediate::BranchLabel*>(instr) != nullptr) throw CompilationError(CompilationStep::GENERAL, "Can't add labels into a basic block", instr->to_string()); pos = basicBlock->instructions.emplace(pos, instr); if(dynamic_cast<intermediate::Branch*>(instr)) basicBlock->method.updateCFGOnBranchInsertion(*this); return *this; } ConstInstructionWalker::ConstInstructionWalker() : basicBlock(nullptr), pos(nullptr) {} ConstInstructionWalker::ConstInstructionWalker(InstructionWalker it) : basicBlock(it.basicBlock), pos(it.pos) {} ConstInstructionWalker::ConstInstructionWalker( const BasicBlock* basicBlock, intermediate::ConstInstructionsIterator pos) : basicBlock(basicBlock), pos(pos) { } const BasicBlock* ConstInstructionWalker::getBasicBlock() const { return basicBlock; } ConstInstructionWalker& ConstInstructionWalker::nextInBlock() { ++pos; return *this; } ConstInstructionWalker& ConstInstructionWalker::previousInBlock() { --pos; return *this; } ConstInstructionWalker& ConstInstructionWalker::nextInMethod() { if(!isEndOfBlock()) // we need this check since for a linked list it seems that last->next == first, which would jump back to the // label of the block nextInBlock(); if(isEndOfBlock()) { if(auto tmp = basicBlock->method.getNextBlockAfter(basicBlock)) { basicBlock = tmp; pos = basicBlock->instructions.begin(); } } return *this; } bool InstructionWalker::replaceValueInBlock( const Value& oldValue, const Value& newValue, LocalUse::Type type, bool forward, bool stopWhenWritten) { bool replaced = false; auto it = copy(); if(forward) { it.nextInBlock(); while(!it.isEndOfBlock()) { replaced = it->replaceValue(oldValue, newValue, type); if(it->getOutput().has_value() && it->getOutput().value() == oldValue && stopWhenWritten) break; it.nextInBlock(); } } else { it.previousInBlock(); while(!it.isStartOfBlock()) { replaced = it->replaceValue(oldValue, newValue, type); if(it->getOutput().has_value() && it->getOutput().value() == oldValue && stopWhenWritten) break; it.previousInBlock(); } } return replaced; } ConstInstructionWalker& ConstInstructionWalker::previousInMethod() { previousInBlock(); if(isStartOfBlock()) { if(auto tmp = basicBlock->method.getPreviousBlock(basicBlock)) { basicBlock = tmp; pos = basicBlock->instructions.end(); --pos; } } return *this; } ConstInstructionWalker ConstInstructionWalker::copy() const { return ConstInstructionWalker(basicBlock, pos); } bool ConstInstructionWalker::operator==(const ConstInstructionWalker& other) const { return basicBlock == other.basicBlock && pos == other.pos; } bool ConstInstructionWalker::isEndOfMethod() const { if(basicBlock == nullptr) return true; const auto& lastBlock = *(--basicBlock->method.end()); return isEndOfBlock() && &lastBlock == basicBlock; } bool ConstInstructionWalker::isStartOfMethod() const { return isStartOfBlock() && basicBlock->isStartOfMethod(); } bool ConstInstructionWalker::isEndOfBlock() const { if(basicBlock == nullptr) return true; return pos == basicBlock->instructions.end(); } bool ConstInstructionWalker::isStartOfBlock() const { if(basicBlock == nullptr) return false; return pos == basicBlock->instructions.begin(); } const intermediate::IntermediateInstruction* ConstInstructionWalker::get() const { throwOnEnd(isEndOfBlock()); return (*pos).get(); }
31.190776
120
0.617556
Mookel
4f2c7c45a4c6a2a344655c2da31ef6e080d04499
2,810
hpp
C++
libraries/blockchain/include/bts/blockchain/snapshot_state.hpp
jasonqin/bitshares1-core
b575445f31d9d5955414a178b9128fd1a423c3fa
[ "Unlicense" ]
82
2015-01-04T21:11:35.000Z
2015-06-08T17:53:49.000Z
libraries/blockchain/include/bts/blockchain/snapshot_state.hpp
jasonqin/bitshares1-core
b575445f31d9d5955414a178b9128fd1a423c3fa
[ "Unlicense" ]
428
2015-01-01T18:42:04.000Z
2015-06-08T16:08:08.000Z
libraries/blockchain/include/bts/blockchain/snapshot_state.hpp
jasonqin/bitshares1-core
b575445f31d9d5955414a178b9128fd1a423c3fa
[ "Unlicense" ]
53
2015-01-05T02:31:30.000Z
2015-06-05T18:50:57.000Z
#pragma once #include <bts/blockchain/graphene.hpp> #include <bts/blockchain/types.hpp> #include <fc/time.hpp> namespace bts { namespace blockchain { struct snapshot_summary { uint64_t num_balance_owners = 0; uint64_t num_asset_balances = 0; uint64_t num_vesting_balances = 0; uint64_t num_canceled_asks = 0; uint64_t num_canceled_bids = 0; uint64_t num_canceled_shorts = 0; uint64_t num_account_names = 0; uint64_t num_witnesses = 0; uint64_t num_workers = 0; uint64_t num_mias = 0; uint64_t num_collateral_positions = 0; uint64_t num_uias = 0; }; struct snapshot_vesting_balance { time_point_sec start_time; uint32_t duration_seconds = 0; share_type original_balance = 0; share_type current_balance = 0; }; struct snapshot_balance { map<string, share_type> assets; optional<snapshot_vesting_balance> vesting; }; struct snapshot_account { uint32_t id; time_point_sec timestamp; public_key_type owner_key; public_key_type active_key; optional<public_key_type> signing_key; optional<share_type> daily_pay; }; struct snapshot_debt { share_type collateral = 0; share_type debt = 0; }; struct snapshot_asset { uint32_t id; string owner; string description; uint64_t precision = 1; share_type max_supply = 0; share_type collected_fees = 0; map<address, snapshot_debt> debts; }; struct snapshot_state { signed_block_header head_block; share_type max_core_supply = 0; snapshot_summary summary; map<address, snapshot_balance> balances; map<string, snapshot_account> accounts; map<string, snapshot_asset> assets; }; } } // bts::blockchain FC_REFLECT( bts::blockchain::snapshot_summary, (num_balance_owners)(num_asset_balances)(num_vesting_balances) (num_canceled_asks)(num_canceled_bids)(num_canceled_shorts) (num_account_names)(num_witnesses)(num_workers) (num_mias)(num_collateral_positions)(num_uias)) FC_REFLECT( bts::blockchain::snapshot_vesting_balance, (start_time)(duration_seconds)(original_balance)(current_balance) ) FC_REFLECT( bts::blockchain::snapshot_balance, (assets)(vesting) ) FC_REFLECT( bts::blockchain::snapshot_account, (id)(timestamp)(owner_key)(active_key)(signing_key)(daily_pay) ) FC_REFLECT( bts::blockchain::snapshot_debt, (collateral)(debt) ) FC_REFLECT( bts::blockchain::snapshot_asset, (id)(owner)(description)(precision)(max_supply)(collected_fees)(debts) ) FC_REFLECT( bts::blockchain::snapshot_state, (head_block)(max_core_supply)(summary)(balances)(accounts)(assets) )
29.893617
122
0.690036
jasonqin
4f2d49c583b36f4b94fc624a8c5079ed09d03b47
1,030
cpp
C++
unit2/2_2.cpp
Helio452b/essential_Cpp_coding
57ac4b28874da099581054ef6db809fade032c37
[ "MIT" ]
2
2020-05-06T16:27:10.000Z
2020-05-06T16:27:14.000Z
unit2/2_2.cpp
Helio452b/essential_Cpp_coding
57ac4b28874da099581054ef6db809fade032c37
[ "MIT" ]
null
null
null
unit2/2_2.cpp
Helio452b/essential_Cpp_coding
57ac4b28874da099581054ef6db809fade032c37
[ "MIT" ]
2
2020-05-06T16:12:41.000Z
2021-01-20T15:52:52.000Z
#include <iostream> #include <windows.h> #include <vector> #include <string> using namespace std; bool pentagonal_get(int num,vector<int> &vect) { int fx_i; if (num<=0 || num>1024) { return false; } else { for (int i = 1; i <= num; i++) { fx_i = i*(i*3-1)/2; vect.push_back(fx_i); } } return true; } bool vect_printf(vector<int> &vects,string type_str) { cout<<"The type "<<type_str<<" and the pentagonal is:"<<endl; for (int i = 0; i < vects.size(); i++) { cout<<vects[i]<<" "; } cout<<endl<<endl; return true; } int main(void) { vector<int> vect; bool res; int num; cout<<"please enter num"<<endl<<endl; while (cin>>num) { res = pentagonal_get(num,vect); if (res == false) { cout<<"overflow"<<endl; } else { vect_printf(vect,"int"); } vector<int>().swap(vect); } return 0; }
16.349206
65
0.484466
Helio452b
4f2ec7e8b4afeda72473ecf93ed7a7594185e807
15,934
cpp
C++
apiwzem/PnlWzemUsgAAccess.cpp
mpsitech/wzem-WhizniumSBE-Engine-Monitor
0d9a204660bfad57f25dbd641fd86713986f32f1
[ "MIT" ]
null
null
null
apiwzem/PnlWzemUsgAAccess.cpp
mpsitech/wzem-WhizniumSBE-Engine-Monitor
0d9a204660bfad57f25dbd641fd86713986f32f1
[ "MIT" ]
null
null
null
apiwzem/PnlWzemUsgAAccess.cpp
mpsitech/wzem-WhizniumSBE-Engine-Monitor
0d9a204660bfad57f25dbd641fd86713986f32f1
[ "MIT" ]
null
null
null
/** * \file PnlWzemUsgAAccess.cpp * API code for job PnlWzemUsgAAccess (implementation) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author Alexander Wirthmueller (auto-generation) * \date created: 6 Dec 2020 */ // IP header --- ABOVE #include "PnlWzemUsgAAccess.h" using namespace std; using namespace Sbecore; using namespace Xmlio; /****************************************************************************** class PnlWzemUsgAAccess::VecVDo ******************************************************************************/ uint PnlWzemUsgAAccess::VecVDo::getIx( const string& sref ) { string s = StrMod::lc(sref); if (s == "butnewclick") return BUTNEWCLICK; if (s == "butduplicateclick") return BUTDUPLICATECLICK; if (s == "butdeleteclick") return BUTDELETECLICK; if (s == "butrefreshclick") return BUTREFRESHCLICK; return(0); }; string PnlWzemUsgAAccess::VecVDo::getSref( const uint ix ) { if (ix == BUTNEWCLICK) return("ButNewClick"); if (ix == BUTDUPLICATECLICK) return("ButDuplicateClick"); if (ix == BUTDELETECLICK) return("ButDeleteClick"); if (ix == BUTREFRESHCLICK) return("ButRefreshClick"); return(""); }; /****************************************************************************** class PnlWzemUsgAAccess::ContInf ******************************************************************************/ PnlWzemUsgAAccess::ContInf::ContInf( const uint numFCsiQst ) : Block() { this->numFCsiQst = numFCsiQst; mask = {NUMFCSIQST}; }; bool PnlWzemUsgAAccess::ContInf::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContInfWzemUsgAAccess"); else basefound = checkXPath(docctx, basexpath); string itemtag = "ContitemInfWzemUsgAAccess"; if (basefound) { if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFCsiQst", numFCsiQst)) add(NUMFCSIQST); }; return basefound; }; set<uint> PnlWzemUsgAAccess::ContInf::comm( const ContInf* comp ) { set<uint> items; if (numFCsiQst == comp->numFCsiQst) insert(items, NUMFCSIQST); return(items); }; set<uint> PnlWzemUsgAAccess::ContInf::diff( const ContInf* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {NUMFCSIQST}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWzemUsgAAccess::StatApp ******************************************************************************/ PnlWzemUsgAAccess::StatApp::StatApp( const uint ixWzemVExpstate ) : Block() { this->ixWzemVExpstate = ixWzemVExpstate; mask = {IXWZEMVEXPSTATE}; }; bool PnlWzemUsgAAccess::StatApp::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); string srefIxWzemVExpstate; bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StatAppWzemUsgAAccess"); else basefound = checkXPath(docctx, basexpath); string itemtag = "StatitemAppWzemUsgAAccess"; if (basefound) { if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "srefIxWzemVExpstate", srefIxWzemVExpstate)) { ixWzemVExpstate = VecWzemVExpstate::getIx(srefIxWzemVExpstate); add(IXWZEMVEXPSTATE); }; }; return basefound; }; set<uint> PnlWzemUsgAAccess::StatApp::comm( const StatApp* comp ) { set<uint> items; if (ixWzemVExpstate == comp->ixWzemVExpstate) insert(items, IXWZEMVEXPSTATE); return(items); }; set<uint> PnlWzemUsgAAccess::StatApp::diff( const StatApp* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {IXWZEMVEXPSTATE}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWzemUsgAAccess::StatShr ******************************************************************************/ PnlWzemUsgAAccess::StatShr::StatShr( const bool ButNewAvail , const bool ButDuplicateAvail , const bool ButDuplicateActive , const bool ButDeleteAvail , const bool ButDeleteActive ) : Block() { this->ButNewAvail = ButNewAvail; this->ButDuplicateAvail = ButDuplicateAvail; this->ButDuplicateActive = ButDuplicateActive; this->ButDeleteAvail = ButDeleteAvail; this->ButDeleteActive = ButDeleteActive; mask = {BUTNEWAVAIL, BUTDUPLICATEAVAIL, BUTDUPLICATEACTIVE, BUTDELETEAVAIL, BUTDELETEACTIVE}; }; bool PnlWzemUsgAAccess::StatShr::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StatShrWzemUsgAAccess"); else basefound = checkXPath(docctx, basexpath); string itemtag = "StatitemShrWzemUsgAAccess"; if (basefound) { if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButNewAvail", ButNewAvail)) add(BUTNEWAVAIL); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButDuplicateAvail", ButDuplicateAvail)) add(BUTDUPLICATEAVAIL); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButDuplicateActive", ButDuplicateActive)) add(BUTDUPLICATEACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButDeleteAvail", ButDeleteAvail)) add(BUTDELETEAVAIL); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButDeleteActive", ButDeleteActive)) add(BUTDELETEACTIVE); }; return basefound; }; set<uint> PnlWzemUsgAAccess::StatShr::comm( const StatShr* comp ) { set<uint> items; if (ButNewAvail == comp->ButNewAvail) insert(items, BUTNEWAVAIL); if (ButDuplicateAvail == comp->ButDuplicateAvail) insert(items, BUTDUPLICATEAVAIL); if (ButDuplicateActive == comp->ButDuplicateActive) insert(items, BUTDUPLICATEACTIVE); if (ButDeleteAvail == comp->ButDeleteAvail) insert(items, BUTDELETEAVAIL); if (ButDeleteActive == comp->ButDeleteActive) insert(items, BUTDELETEACTIVE); return(items); }; set<uint> PnlWzemUsgAAccess::StatShr::diff( const StatShr* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {BUTNEWAVAIL, BUTDUPLICATEAVAIL, BUTDUPLICATEACTIVE, BUTDELETEAVAIL, BUTDELETEACTIVE}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWzemUsgAAccess::StgIac ******************************************************************************/ PnlWzemUsgAAccess::StgIac::StgIac( const uint TcoFegWidth , const uint TcoFeaWidth , const uint TcoAccWidth ) : Block() { this->TcoFegWidth = TcoFegWidth; this->TcoFeaWidth = TcoFeaWidth; this->TcoAccWidth = TcoAccWidth; mask = {TCOFEGWIDTH, TCOFEAWIDTH, TCOACCWIDTH}; }; bool PnlWzemUsgAAccess::StgIac::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StgIacWzemUsgAAccess"); else basefound = checkXPath(docctx, basexpath); string itemtag = "StgitemIacWzemUsgAAccess"; if (basefound) { if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoFegWidth", TcoFegWidth)) add(TCOFEGWIDTH); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoFeaWidth", TcoFeaWidth)) add(TCOFEAWIDTH); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoAccWidth", TcoAccWidth)) add(TCOACCWIDTH); }; return basefound; }; void PnlWzemUsgAAccess::StgIac::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "StgIacWzemUsgAAccess"; string itemtag; if (shorttags) itemtag = "Si"; else itemtag = "StgitemIacWzemUsgAAccess"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeUintAttr(wr, itemtag, "sref", "TcoFegWidth", TcoFegWidth); writeUintAttr(wr, itemtag, "sref", "TcoFeaWidth", TcoFeaWidth); writeUintAttr(wr, itemtag, "sref", "TcoAccWidth", TcoAccWidth); xmlTextWriterEndElement(wr); }; set<uint> PnlWzemUsgAAccess::StgIac::comm( const StgIac* comp ) { set<uint> items; if (TcoFegWidth == comp->TcoFegWidth) insert(items, TCOFEGWIDTH); if (TcoFeaWidth == comp->TcoFeaWidth) insert(items, TCOFEAWIDTH); if (TcoAccWidth == comp->TcoAccWidth) insert(items, TCOACCWIDTH); return(items); }; set<uint> PnlWzemUsgAAccess::StgIac::diff( const StgIac* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {TCOFEGWIDTH, TCOFEAWIDTH, TCOACCWIDTH}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWzemUsgAAccess::Tag ******************************************************************************/ PnlWzemUsgAAccess::Tag::Tag( const string& Cpt , const string& TxtRecord1 , const string& TxtRecord2 , const string& Trs , const string& TxtShowing1 , const string& TxtShowing2 , const string& TcoFeg , const string& TcoFea , const string& TcoAcc ) : Block() { this->Cpt = Cpt; this->TxtRecord1 = TxtRecord1; this->TxtRecord2 = TxtRecord2; this->Trs = Trs; this->TxtShowing1 = TxtShowing1; this->TxtShowing2 = TxtShowing2; this->TcoFeg = TcoFeg; this->TcoFea = TcoFea; this->TcoAcc = TcoAcc; mask = {CPT, TXTRECORD1, TXTRECORD2, TRS, TXTSHOWING1, TXTSHOWING2, TCOFEG, TCOFEA, TCOACC}; }; bool PnlWzemUsgAAccess::Tag::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "TagWzemUsgAAccess"); else basefound = checkXPath(docctx, basexpath); string itemtag = "TagitemWzemUsgAAccess"; if (basefound) { if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "Cpt", Cpt)) add(CPT); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TxtRecord1", TxtRecord1)) add(TXTRECORD1); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TxtRecord2", TxtRecord2)) add(TXTRECORD2); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "Trs", Trs)) add(TRS); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TxtShowing1", TxtShowing1)) add(TXTSHOWING1); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TxtShowing2", TxtShowing2)) add(TXTSHOWING2); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TcoFeg", TcoFeg)) add(TCOFEG); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TcoFea", TcoFea)) add(TCOFEA); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TcoAcc", TcoAcc)) add(TCOACC); }; return basefound; }; /****************************************************************************** class PnlWzemUsgAAccess::DpchAppData ******************************************************************************/ PnlWzemUsgAAccess::DpchAppData::DpchAppData( const string& scrJref , StgIac* stgiac , QryWzemUsgAAccess::StgIac* stgiacqry , const set<uint>& mask ) : DpchAppWzem(VecWzemVDpch::DPCHAPPWZEMUSGAACCESSDATA, scrJref) { if (find(mask, ALL)) this->mask = {SCRJREF, STGIAC, STGIACQRY}; else this->mask = mask; if (find(this->mask, STGIAC) && stgiac) this->stgiac = *stgiac; if (find(this->mask, STGIACQRY) && stgiacqry) this->stgiacqry = *stgiacqry; }; string PnlWzemUsgAAccess::DpchAppData::getSrefsMask() { vector<string> ss; string srefs; if (has(SCRJREF)) ss.push_back("scrJref"); if (has(STGIAC)) ss.push_back("stgiac"); if (has(STGIACQRY)) ss.push_back("stgiacqry"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWzemUsgAAccess::DpchAppData::writeXML( xmlTextWriter* wr ) { xmlTextWriterStartElement(wr, BAD_CAST "DpchAppWzemUsgAAccessData"); xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wzem"); if (has(SCRJREF)) writeString(wr, "scrJref", scrJref); if (has(STGIAC)) stgiac.writeXML(wr); if (has(STGIACQRY)) stgiacqry.writeXML(wr); xmlTextWriterEndElement(wr); }; /****************************************************************************** class PnlWzemUsgAAccess::DpchAppDo ******************************************************************************/ PnlWzemUsgAAccess::DpchAppDo::DpchAppDo( const string& scrJref , const uint ixVDo , const set<uint>& mask ) : DpchAppWzem(VecWzemVDpch::DPCHAPPWZEMUSGAACCESSDO, scrJref) { if (find(mask, ALL)) this->mask = {SCRJREF, IXVDO}; else this->mask = mask; this->ixVDo = ixVDo; }; string PnlWzemUsgAAccess::DpchAppDo::getSrefsMask() { vector<string> ss; string srefs; if (has(SCRJREF)) ss.push_back("scrJref"); if (has(IXVDO)) ss.push_back("ixVDo"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWzemUsgAAccess::DpchAppDo::writeXML( xmlTextWriter* wr ) { xmlTextWriterStartElement(wr, BAD_CAST "DpchAppWzemUsgAAccessDo"); xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wzem"); if (has(SCRJREF)) writeString(wr, "scrJref", scrJref); if (has(IXVDO)) writeString(wr, "srefIxVDo", VecVDo::getSref(ixVDo)); xmlTextWriterEndElement(wr); }; /****************************************************************************** class PnlWzemUsgAAccess::DpchEngData ******************************************************************************/ PnlWzemUsgAAccess::DpchEngData::DpchEngData() : DpchEngWzem(VecWzemVDpch::DPCHENGWZEMUSGAACCESSDATA) { feedFCsiQst.tag = "FeedFCsiQst"; }; string PnlWzemUsgAAccess::DpchEngData::getSrefsMask() { vector<string> ss; string srefs; if (has(SCRJREF)) ss.push_back("scrJref"); if (has(CONTINF)) ss.push_back("continf"); if (has(FEEDFCSIQST)) ss.push_back("feedFCsiQst"); if (has(STATAPP)) ss.push_back("statapp"); if (has(STATSHR)) ss.push_back("statshr"); if (has(STGIAC)) ss.push_back("stgiac"); if (has(TAG)) ss.push_back("tag"); if (has(RST)) ss.push_back("rst"); if (has(STATAPPQRY)) ss.push_back("statappqry"); if (has(STATSHRQRY)) ss.push_back("statshrqry"); if (has(STGIACQRY)) ss.push_back("stgiacqry"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWzemUsgAAccess::DpchEngData::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchEngWzemUsgAAccessData"); else basefound = checkXPath(docctx, basexpath); if (basefound) { if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) add(SCRJREF); if (continf.readXML(docctx, basexpath, true)) add(CONTINF); if (feedFCsiQst.readXML(docctx, basexpath, true)) add(FEEDFCSIQST); if (statapp.readXML(docctx, basexpath, true)) add(STATAPP); if (statshr.readXML(docctx, basexpath, true)) add(STATSHR); if (stgiac.readXML(docctx, basexpath, true)) add(STGIAC); if (tag.readXML(docctx, basexpath, true)) add(TAG); if (rst.readXML(docctx, basexpath, true)) add(RST); if (statappqry.readXML(docctx, basexpath, true)) add(STATAPPQRY); if (statshrqry.readXML(docctx, basexpath, true)) add(STATSHRQRY); if (stgiacqry.readXML(docctx, basexpath, true)) add(STGIACQRY); } else { continf = ContInf(); feedFCsiQst.clear(); statapp = StatApp(); statshr = StatShr(); stgiac = StgIac(); tag = Tag(); rst.clear(); statappqry = QryWzemUsgAAccess::StatApp(); statshrqry = QryWzemUsgAAccess::StatShr(); stgiacqry = QryWzemUsgAAccess::StgIac(); }; };
29.076642
135
0.654324
mpsitech
4f303e8177e6e2c2ab36a9127a8c223d00524ef3
1,038
cpp
C++
Sources/Overload/OvCore/src/OvCore/ECS/Components/CDirectionalLight.cpp
kmqwerty/Overload
f3b8c751a05815400ed35dd2be20a3900f3454fd
[ "MIT" ]
755
2019-07-10T01:26:39.000Z
2022-03-31T12:43:19.000Z
Sources/Overload/OvCore/src/OvCore/ECS/Components/CDirectionalLight.cpp
kmqwerty/Overload
f3b8c751a05815400ed35dd2be20a3900f3454fd
[ "MIT" ]
111
2020-02-28T23:30:10.000Z
2022-01-18T13:57:30.000Z
Sources/Overload/OvCore/src/OvCore/ECS/Components/CDirectionalLight.cpp
kmqwerty/Overload
f3b8c751a05815400ed35dd2be20a3900f3454fd
[ "MIT" ]
97
2019-11-06T15:19:56.000Z
2022-03-25T08:40:04.000Z
/** * @project: Overload * @author: Overload Tech. * @licence: MIT */ #include <OvUI/Widgets/Texts/Text.h> #include <OvUI/Widgets/Drags/DragFloat.h> #include <OvUI/Widgets/Selection/ColorEdit.h> #include "OvCore/ECS/Actor.h" #include "OvCore/ECS/Components/CDirectionalLight.h" OvCore::ECS::Components::CDirectionalLight::CDirectionalLight(ECS::Actor & p_owner) : CLight(p_owner) { m_data.type = static_cast<float>(OvRendering::Entities::Light::Type::DIRECTIONAL); } std::string OvCore::ECS::Components::CDirectionalLight::GetName() { return "Directional Light"; } void OvCore::ECS::Components::CDirectionalLight::OnSerialize(tinyxml2::XMLDocument & p_doc, tinyxml2::XMLNode * p_node) { CLight::OnSerialize(p_doc, p_node); } void OvCore::ECS::Components::CDirectionalLight::OnDeserialize(tinyxml2::XMLDocument & p_doc, tinyxml2::XMLNode * p_node) { CLight::OnDeserialize(p_doc, p_node); } void OvCore::ECS::Components::CDirectionalLight::OnInspector(OvUI::Internal::WidgetContainer& p_root) { CLight::OnInspector(p_root); }
25.95
121
0.757225
kmqwerty
4f32cec6c164bf925e351ea56d5c1a7e66213368
7,791
cpp
C++
clients/common/rocsparse_matrix_factory_laplace3d.cpp
xupinjie/rocSPARSE
5583492046ece092900f815d76fe98dd32cb8d36
[ "MIT" ]
null
null
null
clients/common/rocsparse_matrix_factory_laplace3d.cpp
xupinjie/rocSPARSE
5583492046ece092900f815d76fe98dd32cb8d36
[ "MIT" ]
null
null
null
clients/common/rocsparse_matrix_factory_laplace3d.cpp
xupinjie/rocSPARSE
5583492046ece092900f815d76fe98dd32cb8d36
[ "MIT" ]
null
null
null
/*! \file */ /* ************************************************************************ * Copyright (c) 2021 Advanced Micro Devices, Inc. * * 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 "rocsparse_init.hpp" #include "rocsparse_matrix_utils.hpp" #include "rocsparse_matrix_factory_laplace3d.hpp" template <typename T, typename I, typename J> rocsparse_matrix_factory_laplace3d<T, I, J>::rocsparse_matrix_factory_laplace3d(J dimx, J dimy, J dimz) : m_dimx(dimx) , m_dimy(dimy) , m_dimz(dimz){}; template <typename T, typename I, typename J> void rocsparse_matrix_factory_laplace3d<T, I, J>::init_csr(std::vector<I>& csr_row_ptr, std::vector<J>& csr_col_ind, std::vector<T>& csr_val, J& M, J& N, I& nnz, rocsparse_index_base base, rocsparse_matrix_type matrix_type, rocsparse_fill_mode uplo) { switch(matrix_type) { case rocsparse_matrix_type_symmetric: case rocsparse_matrix_type_hermitian: case rocsparse_matrix_type_triangular: { std::vector<I> ptr; std::vector<J> ind; std::vector<T> val; rocsparse_init_csr_laplace3d( ptr, ind, val, this->m_dimx, this->m_dimy, this->m_dimz, M, N, nnz, base); rocsparse_matrix_utils::host_csrtri(ptr.data(), ind.data(), val.data(), csr_row_ptr, csr_col_ind, csr_val, M, N, nnz, base, uplo); break; } case rocsparse_matrix_type_general: { rocsparse_init_csr_laplace3d(csr_row_ptr, csr_col_ind, csr_val, this->m_dimx, this->m_dimy, this->m_dimz, M, N, nnz, base); break; } } } template <typename T, typename I, typename J> void rocsparse_matrix_factory_laplace3d<T, I, J>::init_coo(std::vector<I>& coo_row_ind, std::vector<I>& coo_col_ind, std::vector<T>& coo_val, I& M, I& N, I& nnz, rocsparse_index_base base) { rocsparse_init_coo_laplace3d(coo_row_ind, coo_col_ind, coo_val, this->m_dimx, this->m_dimy, this->m_dimz, M, N, nnz, base); } template <typename T, typename I, typename J> void rocsparse_matrix_factory_laplace3d<T, I, J>::init_gebsr(std::vector<I>& bsr_row_ptr, std::vector<J>& bsr_col_ind, std::vector<T>& bsr_val, rocsparse_direction dirb, J& Mb, J& Nb, I& nnzb, J& row_block_dim, J& col_block_dim, rocsparse_index_base base) { rocsparse_init_gebsr_laplace3d(bsr_row_ptr, bsr_col_ind, bsr_val, this->m_dimx, this->m_dimy, this->m_dimz, Mb, Nb, nnzb, row_block_dim, col_block_dim, base); } template struct rocsparse_matrix_factory_laplace3d<float, int32_t, int32_t>; template struct rocsparse_matrix_factory_laplace3d<float, int64_t, int32_t>; template struct rocsparse_matrix_factory_laplace3d<float, int64_t, int64_t>; template struct rocsparse_matrix_factory_laplace3d<double, int32_t, int32_t>; template struct rocsparse_matrix_factory_laplace3d<double, int64_t, int32_t>; template struct rocsparse_matrix_factory_laplace3d<double, int64_t, int64_t>; template struct rocsparse_matrix_factory_laplace3d<rocsparse_float_complex, int32_t, int32_t>; template struct rocsparse_matrix_factory_laplace3d<rocsparse_float_complex, int64_t, int32_t>; template struct rocsparse_matrix_factory_laplace3d<rocsparse_float_complex, int64_t, int64_t>; template struct rocsparse_matrix_factory_laplace3d<rocsparse_double_complex, int32_t, int32_t>; template struct rocsparse_matrix_factory_laplace3d<rocsparse_double_complex, int64_t, int32_t>; template struct rocsparse_matrix_factory_laplace3d<rocsparse_double_complex, int64_t, int64_t>;
50.590909
96
0.432294
xupinjie
4f334f91904e6278ac8a1dd9a6cdce874b11659c
2,783
cpp
C++
src/emu_6502/test/opcodes/stack_test.cpp
pgrabas/emu6502
5b46d624cdbb3cffcfd76939d6cdda371f61ed6a
[ "MIT" ]
null
null
null
src/emu_6502/test/opcodes/stack_test.cpp
pgrabas/emu6502
5b46d624cdbb3cffcfd76939d6cdda371f61ed6a
[ "MIT" ]
null
null
null
src/emu_6502/test/opcodes/stack_test.cpp
pgrabas/emu6502
5b46d624cdbb3cffcfd76939d6cdda371f61ed6a
[ "MIT" ]
null
null
null
#include "base_test.hpp" #include <functional> #include <gtest/gtest.h> #include <optional> namespace emu::emu6502::test { namespace { using StackTestArg = std::tuple<Opcode, const char *, uint8_t, Reg8Ptr>; class StackTest : public BaseTest, public ::testing::WithParamInterface<StackTestArg> { public: // Stack Instructions // These instructions are implied mode, have a length of one byte and require machine cycles as indicated. // The "PuLl" operations are known as "POP" on most other microprocessors. With the 6502, the stack is always // on page one ($100-$1FF) and works top down. void SetUp() override { // BaseTest::SetUp(); expected_regs.stack_pointer = 0x80; cpu.reg = expected_regs; expected_code_length = 1; } }; TEST_F(StackTest, PHA) { // MNEMONIC HEX TIM // PHA (PusH Accumulator) $48 3 target_address = expected_regs.StackPointerMemoryAddress(); memory.WriteRange(target_address, {0}); expected_regs.stack_pointer--; expected_regs.a = cpu.reg.a = target_byte; expected_cycles = 3; Execute(MakeCode(INS_PHA)); VerifyMemory(target_address, {target_byte}); } TEST_F(StackTest, PLA) { // MNEMONIC HEX TIM // PLA (PuLl Accumulator) $68 4 expected_regs.stack_pointer++; target_address = expected_regs.StackPointerMemoryAddress(); WriteMemory(target_address, {target_byte}); expected_regs.SetFlag(Flags::Negative, (target_byte & 0x80) > 0); expected_regs.SetFlag(Flags::Zero, target_byte == 0); expected_regs.a = target_byte; expected_cycles = 4; Execute(MakeCode(INS_PLA)); } TEST_F(StackTest, PHP) { // MNEMONIC HEX TIM // PHP (PusH Processor status) $08 3 target_address = expected_regs.StackPointerMemoryAddress(); memory.WriteRange(target_address, {0}); expected_regs.stack_pointer--; expected_regs.flags = cpu.reg.flags = target_byte; expected_cycles = 3; Execute(MakeCode(INS_PHP)); uint8_t expected = target_byte | static_cast<uint8_t>(Flags::Brk) | static_cast<uint8_t>(Flags::NotUsed); VerifyMemory(target_address, {expected}); } TEST_F(StackTest, PLP) { // MNEMONIC HEX TIM // PLP (PuLl Processor status) $28 4 expected_regs.stack_pointer++; target_address = expected_regs.StackPointerMemoryAddress(); expected_regs.flags = target_byte & ~(static_cast<uint8_t>(Flags::Brk) | static_cast<uint8_t>(Flags::NotUsed)); WriteMemory(target_address, {target_byte}); expected_cycles = 4; Execute(MakeCode(INS_PLP)); } } // namespace } // namespace emu::emu6502::test
34.358025
113
0.654689
pgrabas
4f3391c9e7767dbe626123133097b4296537b3e0
5,335
cpp
C++
src/ngraph/runtime/cpu/builder/rnn.cpp
tzerrell/ngraph
b02b0812745ca1cb5f73d426ae9e0ad729eb0bbd
[ "Apache-2.0" ]
null
null
null
src/ngraph/runtime/cpu/builder/rnn.cpp
tzerrell/ngraph
b02b0812745ca1cb5f73d426ae9e0ad729eb0bbd
[ "Apache-2.0" ]
null
null
null
src/ngraph/runtime/cpu/builder/rnn.cpp
tzerrell/ngraph
b02b0812745ca1cb5f73d426ae9e0ad729eb0bbd
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2017-2019 Intel Corporation // // 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 "ngraph/runtime/cpu/op/rnn.hpp" #include "ngraph/runtime/cpu/cpu_builder.hpp" #include "ngraph/runtime/cpu/mkldnn_invoke.hpp" #include "ngraph/runtime/cpu/mkldnn_utils.hpp" using namespace std; using namespace ngraph; namespace ngraph { namespace runtime { namespace cpu { template <> void Builder::BUILDER_DECL(ngraph::op::Rnn) { if (!runtime::cpu::mkldnn_utils::use_mkldnn_kernel(node)) { throw ngraph_error( "Rnn is supported only through MKLDNN and doesnt have reference " "INTERPRETER implementation"); } auto& functors = external_function->get_functors(); auto src_layer_buffer_index = external_function->get_buffer_index(args[0].get_name()); auto src_iter_buffer_index = external_function->get_buffer_index(args[1].get_name()); auto weights_layer_buffer_index = external_function->get_buffer_index(args[2].get_name()); auto weights_iter_buffer_index = external_function->get_buffer_index(args[3].get_name()); auto bias_buffer_index = external_function->get_buffer_index(args[4].get_name()); auto dst_layer_buffer_index = external_function->get_buffer_index(out[0].get_name()); auto dst_iter_buffer_index = external_function->get_buffer_index(out[1].get_name()); auto& mkldnn_emitter = external_function->get_mkldnn_emitter(); auto rnn_desc = mkldnn_emitter->get_rnn_forward_desc<ngraph::op::Rnn>(node, args, out); // Rnn needs 9 primitives: src_layer, src_iter, weights_layer, weights_iter, bias, // dst_layer, dst_iter, workspace, and rnn_forward. // It needs a new workspace. auto rnn_index = mkldnn_emitter->reserve_primitive_space(9, true /* new workspace */); auto& deps = mkldnn_emitter->get_primitive_deps(rnn_index); auto functor = [&, rnn_desc, rnn_index, src_layer_buffer_index, src_iter_buffer_index, weights_layer_buffer_index, weights_iter_buffer_index, bias_buffer_index, dst_layer_buffer_index, dst_iter_buffer_index](CPURuntimeContext* ctx, CPUExecutionContext* ectx) { if (ctx->first_iteration) { mkldnn_emitter->build_rnn_forward(ctx->mkldnn_primitives, ctx->mkldnn_workspaces, rnn_desc, deps, rnn_index); } cpu::mkldnn_utils::set_memory_ptr( ctx, deps[0], ctx->buffer_data[src_layer_buffer_index]); cpu::mkldnn_utils::set_memory_ptr( ctx, deps[1], ctx->buffer_data[src_iter_buffer_index]); cpu::mkldnn_utils::set_memory_ptr( ctx, deps[2], ctx->buffer_data[weights_layer_buffer_index]); cpu::mkldnn_utils::set_memory_ptr( ctx, deps[3], ctx->buffer_data[weights_iter_buffer_index]); cpu::mkldnn_utils::set_memory_ptr( ctx, deps[4], ctx->buffer_data[bias_buffer_index]); cpu::mkldnn_utils::set_memory_ptr( ctx, deps[5], ctx->buffer_data[dst_layer_buffer_index]); cpu::mkldnn_utils::set_memory_ptr( ctx, deps[6], ctx->buffer_data[dst_iter_buffer_index]); cpu::mkldnn_utils::set_memory_ptr( ctx, deps[7], ctx->mkldnn_workspaces[deps[8]]); cpu::mkldnn_utils::mkldnn_invoke_primitive(ctx, rnn_index); }; functors.emplace_back(functor); } REGISTER_OP_BUILDER(Rnn); } } }
48.944954
100
0.519213
tzerrell
4f3478b4fdaa44bc561c7d3648dc2ad4f6e3f4e4
5,354
cc
C++
source/common/http/filter/ratelimit.cc
vanillahsu/envoy
49dc064843035ff980e1ed1d1a7f1574b66f7305
[ "Apache-2.0" ]
null
null
null
source/common/http/filter/ratelimit.cc
vanillahsu/envoy
49dc064843035ff980e1ed1d1a7f1574b66f7305
[ "Apache-2.0" ]
null
null
null
source/common/http/filter/ratelimit.cc
vanillahsu/envoy
49dc064843035ff980e1ed1d1a7f1574b66f7305
[ "Apache-2.0" ]
null
null
null
#include "common/http/filter/ratelimit.h" #include "envoy/http/codes.h" #include "common/common/assert.h" #include "common/common/empty_string.h" #include "common/common/enum_to_int.h" #include "common/http/codes.h" #include "common/router/config_impl.h" namespace Http { namespace RateLimit { namespace { static const Http::HeaderMap* getTooManyRequestsHeader() { static const Http::HeaderMap* header_map = new Http::HeaderMapImpl{ {Http::Headers::get().Status, std::to_string(enumToInt(Code::TooManyRequests))}}; return header_map; } } // namespace; void Filter::initiateCall(const HeaderMap& headers) { bool is_internal_request = headers.EnvoyInternalRequest() && (headers.EnvoyInternalRequest()->value() == "true"); if ((is_internal_request && config_->requestType() == FilterRequestType::External) || (!is_internal_request && config_->requestType() == FilterRequestType::Internal)) { return; } Router::RouteConstSharedPtr route = callbacks_->route(); if (!route || !route->routeEntry()) { return; } const Router::RouteEntry* route_entry = route->routeEntry(); Upstream::ThreadLocalCluster* cluster = config_->cm().get(route_entry->clusterName()); if (!cluster) { return; } cluster_ = cluster->info(); std::vector<::RateLimit::Descriptor> descriptors; // Get all applicable rate limit policy entries for the route. populateRateLimitDescriptors(route_entry->rateLimitPolicy(), descriptors, route_entry, headers); // Get all applicable rate limit policy entries for the virtual host. populateRateLimitDescriptors(route_entry->virtualHost().rateLimitPolicy(), descriptors, route_entry, headers); if (!descriptors.empty()) { state_ = State::Calling; initiating_call_ = true; client_->limit( *this, config_->domain(), descriptors, {headers.RequestId() ? headers.RequestId()->value().c_str() : EMPTY_STRING, headers.OtSpanContext() ? headers.OtSpanContext()->value().c_str() : EMPTY_STRING}); initiating_call_ = false; } } FilterHeadersStatus Filter::decodeHeaders(HeaderMap& headers, bool) { if (!config_->runtime().snapshot().featureEnabled("ratelimit.http_filter_enabled", 100)) { return FilterHeadersStatus::Continue; } initiateCall(headers); return (state_ == State::Calling || state_ == State::Responded) ? FilterHeadersStatus::StopIteration : FilterHeadersStatus::Continue; } FilterDataStatus Filter::decodeData(Buffer::Instance&, bool) { ASSERT(state_ != State::Responded); return state_ == State::Calling ? FilterDataStatus::StopIterationAndBuffer : FilterDataStatus::Continue; } FilterTrailersStatus Filter::decodeTrailers(HeaderMap&) { ASSERT(state_ != State::Responded); return state_ == State::Calling ? FilterTrailersStatus::StopIteration : FilterTrailersStatus::Continue; } void Filter::setDecoderFilterCallbacks(StreamDecoderFilterCallbacks& callbacks) { callbacks_ = &callbacks; callbacks.addResetStreamCallback([this]() -> void { if (state_ == State::Calling) { client_->cancel(); } }); } void Filter::complete(::RateLimit::LimitStatus status) { state_ = State::Complete; switch (status) { case ::RateLimit::LimitStatus::OK: cluster_->statsScope().counter("ratelimit.ok").inc(); break; case ::RateLimit::LimitStatus::Error: cluster_->statsScope().counter("ratelimit.error").inc(); break; case ::RateLimit::LimitStatus::OverLimit: cluster_->statsScope().counter("ratelimit.over_limit").inc(); Http::CodeUtility::ResponseStatInfo info{ config_->globalStore(), cluster_->statsScope(), EMPTY_STRING, *getTooManyRequestsHeader(), true, EMPTY_STRING, EMPTY_STRING, EMPTY_STRING, EMPTY_STRING, false}; Http::CodeUtility::chargeResponseStat(info); break; } if (status == ::RateLimit::LimitStatus::OverLimit && config_->runtime().snapshot().featureEnabled("ratelimit.http_filter_enforcing", 100)) { state_ = State::Responded; Http::HeaderMapPtr response_headers{new HeaderMapImpl(*getTooManyRequestsHeader())}; callbacks_->encodeHeaders(std::move(response_headers), true); callbacks_->requestInfo().setResponseFlag(Http::AccessLog::ResponseFlag::RateLimited); } else if (!initiating_call_) { callbacks_->continueDecoding(); } } void Filter::populateRateLimitDescriptors(const Router::RateLimitPolicy& rate_limit_policy, std::vector<::RateLimit::Descriptor>& descriptors, const Router::RouteEntry* route_entry, const HeaderMap& headers) const { for (const Router::RateLimitPolicyEntry& rate_limit : rate_limit_policy.getApplicableRateLimit(config_->stage())) { const std::string& disable_key = rate_limit.disableKey(); if (!disable_key.empty() && !config_->runtime().snapshot().featureEnabled( fmt::format("ratelimit.{}.http_filter_enabled", disable_key), 100)) { continue; } rate_limit.populateDescriptors(*route_entry, descriptors, config_->localInfo().clusterName(), headers, callbacks_->downstreamAddress()); } } } // RateLimit } // Http
36.671233
98
0.683227
vanillahsu
4f34b190fc49b969608edc1c87f78451d9d24a15
319
cpp
C++
c++/Booking/bookingTest.cpp
taku-xhift/labo
89dc28fdb602c7992c6f31920714225f83a11218
[ "MIT" ]
null
null
null
c++/Booking/bookingTest.cpp
taku-xhift/labo
89dc28fdb602c7992c6f31920714225f83a11218
[ "MIT" ]
null
null
null
c++/Booking/bookingTest.cpp
taku-xhift/labo
89dc28fdb602c7992c6f31920714225f83a11218
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> class Test; class Test { public: static std::vector<const Test*> allData; Test() : data(3) { allData.push_back(this); } int data; }; int main() { Test test; std::cout << Test::allData.at(0)->data << std::endl; return 0; }
9.114286
54
0.54232
taku-xhift
4f3538763c856e0fd6bf336958b1dab6d40b8dcd
6,262
cc
C++
chrome/browser/android/ntp/most_visited_sites_bridge.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
chrome/browser/android/ntp/most_visited_sites_bridge.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
chrome/browser/android/ntp/most_visited_sites_bridge.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/android/ntp/most_visited_sites_bridge.h" #include <utility> #include "base/android/jni_android.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/ntp_tiles/chrome_most_visited_sites_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_android.h" #include "chrome/browser/thumbnails/thumbnail_list_source.h" #include "components/ntp_tiles/metrics.h" #include "components/ntp_tiles/most_visited_sites.h" #include "components/rappor/rappor_service_impl.h" #include "jni/MostVisitedSites_jni.h" #include "ui/gfx/android/java_bitmap.h" using base::android::AttachCurrentThread; using base::android::ConvertJavaStringToUTF8; using base::android::ConvertUTF8ToJavaString; using base::android::JavaParamRef; using base::android::ScopedJavaGlobalRef; using base::android::ScopedJavaLocalRef; using base::android::ToJavaArrayOfStrings; using base::android::ToJavaIntArray; using ntp_tiles::MostVisitedSites; using ntp_tiles::NTPTileSource; using ntp_tiles::NTPTilesVector; using ntp_tiles::metrics::MostVisitedTileType; using ntp_tiles::metrics::TileImpression; class MostVisitedSitesBridge::JavaObserver : public MostVisitedSites::Observer { public: JavaObserver(JNIEnv* env, const JavaParamRef<jobject>& obj); void OnMostVisitedURLsAvailable(const NTPTilesVector& tiles) override; void OnIconMadeAvailable(const GURL& site_url) override; private: ScopedJavaGlobalRef<jobject> observer_; DISALLOW_COPY_AND_ASSIGN(JavaObserver); }; MostVisitedSitesBridge::JavaObserver::JavaObserver( JNIEnv* env, const JavaParamRef<jobject>& obj) : observer_(env, obj) {} void MostVisitedSitesBridge::JavaObserver::OnMostVisitedURLsAvailable( const NTPTilesVector& tiles) { JNIEnv* env = AttachCurrentThread(); std::vector<base::string16> titles; std::vector<std::string> urls; std::vector<std::string> whitelist_icon_paths; std::vector<int> sources; titles.reserve(tiles.size()); urls.reserve(tiles.size()); whitelist_icon_paths.reserve(tiles.size()); sources.reserve(tiles.size()); for (const auto& tile : tiles) { titles.emplace_back(tile.title); urls.emplace_back(tile.url.spec()); whitelist_icon_paths.emplace_back(tile.whitelist_icon_path.value()); sources.emplace_back(static_cast<int>(tile.source)); } Java_MostVisitedURLsObserver_onMostVisitedURLsAvailable( env, observer_, ToJavaArrayOfStrings(env, titles), ToJavaArrayOfStrings(env, urls), ToJavaArrayOfStrings(env, whitelist_icon_paths), ToJavaIntArray(env, sources)); } void MostVisitedSitesBridge::JavaObserver::OnIconMadeAvailable( const GURL& site_url) { JNIEnv* env = AttachCurrentThread(); Java_MostVisitedURLsObserver_onIconMadeAvailable( env, observer_, ConvertUTF8ToJavaString(env, site_url.spec())); } MostVisitedSitesBridge::MostVisitedSitesBridge(Profile* profile) : most_visited_(ChromeMostVisitedSitesFactory::NewForProfile(profile)) { // Register the thumbnails debugging page. // TODO(sfiera): find thumbnails a home. They don't belong here. content::URLDataSource::Add(profile, new ThumbnailListSource(profile)); DCHECK(!profile->IsOffTheRecord()); } MostVisitedSitesBridge::~MostVisitedSitesBridge() {} void MostVisitedSitesBridge::Destroy( JNIEnv* env, const JavaParamRef<jobject>& obj) { delete this; } void MostVisitedSitesBridge::SetMostVisitedURLsObserver( JNIEnv* env, const JavaParamRef<jobject>& obj, const JavaParamRef<jobject>& j_observer, jint num_sites) { java_observer_.reset(new JavaObserver(env, j_observer)); most_visited_->SetMostVisitedURLsObserver(java_observer_.get(), num_sites); } void MostVisitedSitesBridge::AddOrRemoveBlacklistedUrl( JNIEnv* env, const JavaParamRef<jobject>& obj, const JavaParamRef<jstring>& j_url, jboolean add_url) { GURL url(ConvertJavaStringToUTF8(env, j_url)); most_visited_->AddOrRemoveBlacklistedUrl(url, add_url); } void MostVisitedSitesBridge::RecordPageImpression( JNIEnv* env, const JavaParamRef<jobject>& obj, const JavaParamRef<jintArray>& jtile_types, const JavaParamRef<jintArray>& jsources, const JavaParamRef<jobjectArray>& jtile_urls) { std::vector<int> int_sources; base::android::JavaIntArrayToIntVector(env, jsources, &int_sources); std::vector<int> int_tile_types; base::android::JavaIntArrayToIntVector(env, jtile_types, &int_tile_types); std::vector<std::string> string_tile_urls; base::android::AppendJavaStringArrayToStringVector(env, jtile_urls, &string_tile_urls); DCHECK_EQ(int_sources.size(), int_tile_types.size()); DCHECK_EQ(int_sources.size(), string_tile_urls.size()); std::vector<TileImpression> tiles; for (size_t i = 0; i < int_sources.size(); i++) { NTPTileSource source = static_cast<NTPTileSource>(int_sources[i]); MostVisitedTileType tile_type = static_cast<MostVisitedTileType>(int_tile_types[i]); tiles.emplace_back(source, tile_type, GURL(string_tile_urls[i])); } ntp_tiles::metrics::RecordPageImpression(tiles, g_browser_process->rappor_service()); } void MostVisitedSitesBridge::RecordOpenedMostVisitedItem( JNIEnv* env, const JavaParamRef<jobject>& obj, jint index, jint tile_type, jint source) { ntp_tiles::metrics::RecordTileClick( index, static_cast<NTPTileSource>(source), static_cast<MostVisitedTileType>(tile_type)); } // static bool MostVisitedSitesBridge::Register(JNIEnv* env) { return RegisterNativesImpl(env); } static jlong Init(JNIEnv* env, const JavaParamRef<jobject>& obj, const JavaParamRef<jobject>& jprofile) { MostVisitedSitesBridge* most_visited_sites = new MostVisitedSitesBridge( ProfileAndroid::FromProfileAndroid(jprofile)); return reinterpret_cast<intptr_t>(most_visited_sites); }
35.782857
80
0.757266
google-ar
4f375fb260c29c6a3182017ae64250da405d3dae
570
cpp
C++
cf/ac/0178A3.cpp
vitorgt/problem-solving
11fa59de808f7a113c08454b4aca68b01410892e
[ "MIT" ]
null
null
null
cf/ac/0178A3.cpp
vitorgt/problem-solving
11fa59de808f7a113c08454b4aca68b01410892e
[ "MIT" ]
null
null
null
cf/ac/0178A3.cpp
vitorgt/problem-solving
11fa59de808f7a113c08454b4aca68b01410892e
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define ll long long const int INF = 0x3f3f3f3f; int main() { std::ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL); int n = 0, log2n = 0, i = 0; ll count = 0; cin >> n; vector<ll> a(n); log2n = floor(log2(n)); for (i = 0; i < n; i++) cin >> a[i]; for (i = 0; i < n - 1; i++) { while ((1 << log2n) + i >= n) log2n--; a[(1 << log2n) + i] += a[i]; count += a[i]; a[i] = 0; cout << count << endl; } return 0; }
19
68
0.445614
vitorgt
4f387b63cad2886f2805f3d81d50cd69ff85cde2
9,276
cpp
C++
src/demos/vehicle/demo_DeformableSoil/demo_VEH_DeformableSoil.cpp
bluescarni/chrono
5804345dc23733196c6740afbc0c1432553dfb1d
[ "BSD-3-Clause" ]
null
null
null
src/demos/vehicle/demo_DeformableSoil/demo_VEH_DeformableSoil.cpp
bluescarni/chrono
5804345dc23733196c6740afbc0c1432553dfb1d
[ "BSD-3-Clause" ]
null
null
null
src/demos/vehicle/demo_DeformableSoil/demo_VEH_DeformableSoil.cpp
bluescarni/chrono
5804345dc23733196c6740afbc0c1432553dfb1d
[ "BSD-3-Clause" ]
null
null
null
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Demo code (advanced), about // // - using the SCM semi-empirical model for deformable soil // ============================================================================= #include "chrono/core/ChFileutils.h" #include "chrono/geometry/ChTriangleMeshConnected.h" #include "chrono/physics/ChLoadContainer.h" #include "chrono/physics/ChSystemSMC.h" #include "chrono/solver/ChSolverMINRES.h" #include "chrono/utils/ChUtilsInputOutput.h" #include "chrono_irrlicht/ChIrrApp.h" #include "chrono_vehicle/ChVehicleModelData.h" #include "chrono_vehicle/terrain/SCMDeformableTerrain.h" using namespace chrono; using namespace chrono::irrlicht; using namespace irr; bool output = false; const std::string out_dir = GetChronoOutputPath() + "SCM_DEF_SOIL"; int main(int argc, char* argv[]) { GetLog() << "Copyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n"; // Global parameter for tire: double tire_rad = 0.8; double tire_vel_z0 = -3; ChVector<> tire_center(0, 0.02 + tire_rad, 0); double tire_w0 = tire_vel_z0 / tire_rad; // Create a Chrono::Engine physical system ChSystemSMC my_system; // Create the Irrlicht visualization (open the Irrlicht device, // bind a simple user interface, etc. etc.) ChIrrApp application(&my_system, L"Deformable soil", core::dimension2d<u32>(1280, 720), false, true); // Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene: application.AddTypicalLogo(); application.AddTypicalSky(); application.AddTypicalLights(); application.AddTypicalCamera(core::vector3df(1.0f, 1.4f, -1.2f), core::vector3df(0, (f32)tire_rad, 0)); application.AddLightWithShadow(core::vector3df(1.5f, 5.5f, -2.5f), core::vector3df(0, 0, 0), 3, 2.2, 7.2, 40, 512, video::SColorf(0.8f, 0.8f, 1.0f)); std::shared_ptr<ChBody> mtruss(new ChBody); mtruss->SetBodyFixed(true); my_system.Add(mtruss); // Initialize output if (output) { if (ChFileutils::MakeDirectory(out_dir.c_str()) < 0) { std::cout << "Error creating directory " << out_dir << std::endl; return 1; } } utils::CSV_writer csv(" "); // // CREATE A RIGID BODY WITH A MESH // std::shared_ptr<ChBody> mrigidbody(new ChBody); my_system.Add(mrigidbody); mrigidbody->SetMass(500); mrigidbody->SetInertiaXX(ChVector<>(20, 20, 20)); mrigidbody->SetPos(tire_center + ChVector<>(0, 0.3, 0)); auto trimesh = std::make_shared<geometry::ChTriangleMeshConnected>(); trimesh->LoadWavefrontMesh(GetChronoDataFile("tractor_wheel.obj")); std::shared_ptr<ChTriangleMeshShape> mrigidmesh(new ChTriangleMeshShape); mrigidmesh->SetMesh(trimesh); mrigidbody->AddAsset(mrigidmesh); mrigidbody->GetCollisionModel()->ClearModel(); mrigidbody->GetCollisionModel()->AddTriangleMesh(trimesh, false, false, VNULL, ChMatrix33<>(1), 0.01); mrigidbody->GetCollisionModel()->BuildModel(); mrigidbody->SetCollide(true); std::shared_ptr<ChColorAsset> mcol(new ChColorAsset); mcol->SetColor(ChColor(0.3f, 0.3f, 0.3f)); mrigidbody->AddAsset(mcol); std::shared_ptr<ChLinkEngine> myengine(new ChLinkEngine); myengine->Set_shaft_mode(ChLinkEngine::ENG_SHAFT_OLDHAM); myengine->Set_eng_mode(ChLinkEngine::ENG_MODE_ROTATION); myengine->Set_rot_funct(std::make_shared<ChFunction_Ramp>(0, CH_C_PI / 4.0)); // phase, speed myengine->Initialize(mrigidbody, mtruss, ChCoordsys<>(tire_center, Q_from_AngAxis(CH_C_PI_2, VECT_Y))); my_system.Add(myengine); // // THE DEFORMABLE TERRAIN // // Create the 'deformable terrain' object vehicle::SCMDeformableTerrain mterrain(&my_system); // Optionally, displace/tilt/rotate the terrain reference plane: mterrain.SetPlane(ChCoordsys<>(ChVector<>(0, 0, 0.5))); // Initialize the geometry of the soil: use either a regular grid: mterrain.Initialize(0.2, 1.5, 5, 20, 60); // or use a height map: ////mterrain.Initialize(vehicle::GetDataFile("terrain/height_maps/test64.bmp"), "test64", 1.6, 1.6, 0, 0.3); // Set the soil terramechanical parameters: mterrain.SetSoilParametersSCM(0.2e6, // Bekker Kphi 0, // Bekker Kc 1.1, // Bekker n exponent 0, // Mohr cohesive limit (Pa) 30, // Mohr friction limit (degrees) 0.01, // Janosi shear coefficient (m) 4e7, // Elastic stiffness (Pa/m), before plastic yield, must be > Kphi 3e4 // Damping (Pa s/m), proportional to negative vertical speed (optional) ); // LETE sand parameters ////mterrain.SetSoilParametersSCM(5301e3, // Bekker Kphi //// 102e3, // Bekker Kc //// 0.793, // Bekker n exponent //// 1.3e3, // Mohr cohesive limit (Pa) //// 31.1, // Mohr friction limit (degrees) //// 1.2e-2, // Janosi shear coefficient (m) //// 4e8, // Elastic stiffness (Pa/m), before plastic yield, must be > Kphi //// 3e4 // Damping (Pa s/m), proportional to negative vertical speed (optional) ////); mterrain.SetBulldozingFlow(true); // inflate soil at the border of the rut mterrain.SetBulldozingParameters( 55, // angle of friction for erosion of displaced material at the border of the rut 1, // displaced material vs downward pressed material. 5, // number of erosion refinements per timestep 10); // number of concentric vertex selections subject to erosion // Turn on the automatic level of detail refinement, so a coarse terrain mesh // is automatically improved by adding more points under the wheel contact patch: mterrain.SetAutomaticRefinement(true); mterrain.SetAutomaticRefinementResolution(0.04); // Set some visualization parameters: either with a texture, or with falsecolor plot, etc. ////mterrain.SetTexture(vehicle::GetDataFile("terrain/textures/grass.jpg"), 16, 16); mterrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_PRESSURE, 0, 30000.2); ////mterrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_PRESSURE_YELD, 0, 30000.2); ////mterrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_SINKAGE, 0, 0.15); ////mterrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_SINKAGE_PLASTIC, 0, 0.15); ////mterrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_SINKAGE_ELASTIC, 0, 0.05); ////mterrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_STEP_PLASTIC_FLOW, 0, 0.0001); ////mterrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_ISLAND_ID, 0, 8); ////mterrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_IS_TOUCHED, 0, 8); mterrain.GetMesh()->SetWireframe(true); // ==IMPORTANT!== Use this function for adding a ChIrrNodeAsset to all items application.AssetBindAll(); // ==IMPORTANT!== Use this function for 'converting' into Irrlicht meshes the assets application.AssetUpdateAll(); // Use shadows in realtime view application.AddShadowAll(); // ==IMPORTANT!== Mark completion of system construction my_system.SetupInitial(); // // THE SOFT-REAL-TIME CYCLE // /* // Change the timestepper to HHT: my_system.SetTimestepperType(ChTimestepper::Type::HHT); auto integrator = std::static_pointer_cast<ChTimestepperHHT>(my_system.GetTimestepper()); integrator->SetAlpha(-0.2); integrator->SetMaxiters(8); integrator->SetAbsTolerances(1e-05, 1.8e00); integrator->SetMode(ChTimestepperHHT::POSITION); integrator->SetModifiedNewton(true); integrator->SetScaling(true); integrator->SetVerbose(true); */ /* my_system.SetTimestepperType(ChTimestepper::Type::EULER_IMPLICIT); */ application.SetTimestep(0.002); while (application.GetDevice()->run()) { if (output) { vehicle::TerrainForce frc = mterrain.GetContactForce(mrigidbody); csv << my_system.GetChTime() << frc.force << frc.moment << frc.point << std::endl; } application.BeginScene(); application.DrawAll(); application.DoStep(); ChIrrTools::drawColorbar(0, 30000, "Pressure yield [Pa]", application.GetDevice(), 1180); application.EndScene(); } if (output) { csv.write_to_file(out_dir + "/output.dat"); } return 0; }
41.596413
118
0.631738
bluescarni
4f3911284077eaa525ae693c116101bee6ac505a
2,675
cpp
C++
ProcessLib/SurfaceFlux/SurfaceFlux.cpp
zhangning737/ogs
53a892f4ce2f133e4d00534d33ad4329e5c0ccb2
[ "BSD-4-Clause" ]
1
2021-06-25T13:43:06.000Z
2021-06-25T13:43:06.000Z
ProcessLib/SurfaceFlux/SurfaceFlux.cpp
boyanmeng/ogs
8172d20e61ae6dad076b3cc064846db7ef622020
[ "BSD-4-Clause" ]
1
2019-08-09T12:13:22.000Z
2019-08-09T12:13:22.000Z
ProcessLib/SurfaceFlux/SurfaceFlux.cpp
zhangning737/ogs
53a892f4ce2f133e4d00534d33ad4329e5c0ccb2
[ "BSD-4-Clause" ]
null
null
null
/** * \file * \copyright * Copyright (c) 2012-2019, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #include "SurfaceFlux.h" #include <cassert> #include "ProcessLib/Utils/CreateLocalAssemblers.h" namespace ProcessLib { SurfaceFlux::SurfaceFlux( MeshLib::Mesh& boundary_mesh, std::size_t bulk_property_number_of_components, unsigned const integration_order) { DBUG("Create local balance assemblers."); // Populate the vector of local assemblers. _local_assemblers.resize(boundary_mesh.getElements().size()); // needed to create dof table auto mesh_subset_all_nodes = std::make_unique<MeshLib::MeshSubset>( boundary_mesh, boundary_mesh.getNodes()); // Collect the mesh subsets in a vector. std::vector<MeshLib::MeshSubset> all_mesh_subsets; std::generate_n(std::back_inserter(all_mesh_subsets), bulk_property_number_of_components, [&]() { return *mesh_subset_all_nodes; }); // needed for creation of local assemblers auto dof_table = std::make_unique<NumLib::LocalToGlobalIndexMap const>( std::move(all_mesh_subsets), NumLib::ComponentOrder::BY_LOCATION); auto const bulk_element_ids = boundary_mesh.getProperties().template getPropertyVector<std::size_t>( "bulk_element_ids", MeshLib::MeshItemType::Cell, 1); auto const bulk_face_ids = boundary_mesh.getProperties().template getPropertyVector<std::size_t>( "bulk_face_ids", MeshLib::MeshItemType::Cell, 1); ProcessLib::createLocalAssemblers<SurfaceFluxLocalAssembler>( boundary_mesh.getDimension() + 1, // or bulk_mesh.getDimension()? boundary_mesh.getElements(), *dof_table, 1, _local_assemblers, boundary_mesh.isAxiallySymmetric(), integration_order, *bulk_element_ids, *bulk_face_ids); } void SurfaceFlux::integrate( std::vector<GlobalVector*> const& x, MeshLib::PropertyVector<double>& balance, double const t, MeshLib::Mesh const& bulk_mesh, std::vector<std::size_t> const& active_element_ids, std::function<Eigen::Vector3d( std::size_t const, MathLib::Point3d const&, double const, std::vector<GlobalVector*> const&)> const& getFlux) { DBUG("Integrate SurfaceFlux."); GlobalExecutor::executeSelectedMemberOnDereferenced( &SurfaceFluxLocalAssemblerInterface::integrate, _local_assemblers, active_element_ids, x, balance, t, bulk_mesh, getFlux); } } // namespace ProcessLib
36.148649
82
0.702804
zhangning737
4f396e14fec3b619ea47854dd842c7f67199e950
4,346
cc
C++
src/libdeltafs/mds_srv_test.cc
chuckcranor/deltafs
34c6b60e225c19b363aaafa7c755fd9ffea4ffba
[ "Xnet", "X11" ]
93
2016-09-28T12:32:05.000Z
2022-03-25T03:29:21.000Z
src/libdeltafs/mds_srv_test.cc
chuckcranor/deltafs
34c6b60e225c19b363aaafa7c755fd9ffea4ffba
[ "Xnet", "X11" ]
3
2016-08-30T04:15:23.000Z
2021-03-26T05:33:24.000Z
src/libdeltafs/mds_srv_test.cc
chuckcranor/deltafs
34c6b60e225c19b363aaafa7c755fd9ffea4ffba
[ "Xnet", "X11" ]
12
2016-10-24T20:03:08.000Z
2022-03-30T14:12:51.000Z
/* * Copyright (c) 2019 Carnegie Mellon University, * Copyright (c) 2019 Triad National Security, LLC, as operator of * Los Alamos National Laboratory. * * All rights reserved. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. See the AUTHORS file for names of contributors. */ #include <fcntl.h> #include <stdio.h> #include <string.h> #include <sys/stat.h> #include "mds_srv.h" #include "pdlfs-common/testharness.h" #include "pdlfs-common/testutil.h" namespace pdlfs { class ServerTest { private: std::string dbname_; MDSEnv mds_env_; MDS* mds_; MDB* mdb_; DB* db_; public: ServerTest() { Env* env = Env::Default(); dbname_ = test::PrepareTmpDir("mds_srv_test", env); DBOptions dbopts; dbopts.env = env; DestroyDB(dbname_, dbopts); dbopts.create_if_missing = true; ASSERT_OK(DB::Open(dbopts, dbname_, &db_)); MDBOptions mdbopts; mdbopts.db = db_; mdb_ = new MDB(mdbopts); mds_env_.env = env; MDSOptions mdsopts; mdsopts.mds_env = &mds_env_; mdsopts.mdb = mdb_; mds_ = MDS::Open(mdsopts); } ~ServerTest() { delete mds_; delete mdb_; delete db_; } static std::string NodeName(int i) { char tmp[50]; snprintf(tmp, sizeof(tmp), "node%d", i); return tmp; } // Return the ino of the node being searched, or "-err_code" on errors. int Fstat(int dir_ino, int nod_no) { MDS::FstatOptions options; options.dir_id = DirId(0, 0, dir_ino); std::string name = NodeName(nod_no); options.name = name; std::string name_hash; DirIndex::PutHash(&name_hash, name); options.name_hash = name_hash; MDS::FstatRet ret; Status s = mds_->Fstat(options, &ret); if (s.ok()) { return static_cast<int>(ret.stat.InodeNo()); } else { return -1 * s.err_code(); } } // Return the ino of the newly created file, or "-err_code" on errors. int Mknod(int dir_ino, int nod_no) { MDS::FcreatOptions options; options.dir_id = DirId(0, 0, dir_ino); options.flags = O_EXCL; options.mode = ACCESSPERMS; options.uid = 0; options.gid = 0; std::string name = NodeName(nod_no); options.name = name; std::string name_hash; DirIndex::PutHash(&name_hash, name); options.name_hash = name_hash; MDS::FcreatRet ret; Status s = mds_->Fcreat(options, &ret); if (s.ok()) { return static_cast<int>(ret.stat.InodeNo()); } else { return -1 * s.err_code(); } } int Mkdir(int dir_ino, int nod_no) { MDS::MkdirOptions options; options.dir_id = DirId(0, 0, dir_ino); options.flags = O_EXCL; options.mode = ACCESSPERMS; options.uid = 0; options.gid = 0; std::string name = NodeName(nod_no); options.name = name; std::string name_hash; DirIndex::PutHash(&name_hash, name); options.name_hash = name_hash; MDS::MkdirRet ret; Status s = mds_->Mkdir(options, &ret); if (s.ok()) { return static_cast<int>(ret.stat.InodeNo()); } else { return -1 * s.err_code(); } } int Listdir(int dir_ino) { MDS::ListdirOptions options; options.dir_id = DirId(0, 0, dir_ino); std::vector<std::string> names; MDS::ListdirRet ret; ret.names = &names; Status s = mds_->Listdir(options, &ret); if (s.ok()) { return names.size(); } else { return -1 * s.err_code(); } } }; TEST(ServerTest, StartStop) { // empty } TEST(ServerTest, Files) { int r1 = Fstat(0, 1); ASSERT_TRUE(r1 == -1 * Status::kNotFound); int r2 = Mknod(0, 1); ASSERT_TRUE(r2 > 0); int r3 = Fstat(0, 1); ASSERT_TRUE(r3 == r2); int r4 = Mknod(0, 1); ASSERT_TRUE(r4 == -1 * Status::kAlreadyExists); } TEST(ServerTest, Dirs) { int r1 = Fstat(0, 1); ASSERT_TRUE(r1 == -1 * Status::kNotFound); int r2 = Mkdir(0, 1); ASSERT_TRUE(r2 > 0); int r3 = Fstat(0, 1); ASSERT_TRUE(r3 == r2); int r4 = Mkdir(0, 1); ASSERT_TRUE(r4 == -1 * Status::kAlreadyExists); } TEST(ServerTest, Scan) { Mknod(0, 1); Mknod(0, 2); Mknod(0, 3); Mknod(0, 4); Mknod(0, 5); Mkdir(0, 6); Mkdir(0, 7); Mkdir(0, 8); Mkdir(0, 9); int r = Listdir(0); ASSERT_TRUE(r == 9); } } // namespace pdlfs int main(int argc, char* argv[]) { return ::pdlfs::test::RunAllTests(&argc, &argv); }
23.748634
77
0.617809
chuckcranor
4f39c862d9220466ed1eefcac00838e198565067
6,591
cpp
C++
src/collisions/CCollisionAABBTree.cpp
RoboticsDesignLab/chai3d
66927fb9c81a173b988e1fc81cf6bfd57d69dcd7
[ "BSD-3-Clause" ]
75
2016-12-22T14:53:01.000Z
2022-03-31T08:04:19.000Z
src/collisions/CCollisionAABBTree.cpp
RoboticsDesignLab/chai3d
66927fb9c81a173b988e1fc81cf6bfd57d69dcd7
[ "BSD-3-Clause" ]
6
2017-04-03T21:27:16.000Z
2019-08-28T17:05:23.000Z
src/collisions/CCollisionAABBTree.cpp
RoboticsDesignLab/chai3d
66927fb9c81a173b988e1fc81cf6bfd57d69dcd7
[ "BSD-3-Clause" ]
53
2017-03-16T16:38:34.000Z
2022-02-25T14:31:01.000Z
//============================================================================== /* Software License Agreement (BSD License) Copyright (c) 2003-2016, CHAI3D. (www.chai3d.org) 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 CHAI3D nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \author <http://www.chai3d.org> \author Chris Sewell \author Charity Lu \author Francois Conti \version 3.2.0 $Rev: 1869 $ */ //============================================================================== //------------------------------------------------------------------------------ #include "collisions/CCollisionAABBTree.h" //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ namespace chai3d { //------------------------------------------------------------------------------ //============================================================================== /*! Constructor of cCollisionAABBNode. */ //============================================================================== cCollisionAABBNode::cCollisionAABBNode() { m_bbox.setEmpty(); m_depth = -1; m_nodeType = C_AABB_NOT_DEFINED; m_leftSubTree = -1; m_rightSubTree = -1; } //============================================================================== /*! This method creates a boundary box to enclose a point belonging to the leaf node. \param a_radius Radius around the point. \param a_vertex0 Vertex 0. */ //============================================================================== void cCollisionAABBNode::fitBBox(double a_radius, cVector3d& a_vertex0) { // empty box m_bbox.setEmpty(); // enclose vertex m_bbox.enclose(a_vertex0); // retrieve boundary box min and max values cVector3d min = m_bbox.m_min; cVector3d max = m_bbox.m_max; // add radius envelope min.sub(a_radius, a_radius, a_radius); max.add(a_radius, a_radius, a_radius); // store new values m_bbox.setValue(min, max); } //============================================================================== /*! This method creates a boundary box to enclose the two vertices of a segment belonging to the leaf node. \param a_radius Radius around the segment. \param a_vertex0 Vertex 0. \param a_vertex1 Vertex 1. */ //============================================================================== void cCollisionAABBNode::fitBBox(double a_radius, cVector3d& a_vertex0, cVector3d& a_vertex1) { // empty box m_bbox.setEmpty(); // enclose vertices m_bbox.enclose(a_vertex0); m_bbox.enclose(a_vertex1); // retrieve boundary box min and max values cVector3d min = m_bbox.m_min; cVector3d max = m_bbox.m_max; // add radius envelope min.sub(a_radius, a_radius, a_radius); max.add(a_radius, a_radius, a_radius); // store new values m_bbox.setValue(min, max); } //============================================================================== /*! This method creates a boundary box to enclose the three vertices of a triangle belonging to the leaf node. \param a_radius Radius around the element. \param a_vertex0 Vertex 0. \param a_vertex1 Vertex 1. \param a_vertex2 Vertex 2. */ //============================================================================== void cCollisionAABBNode::fitBBox(double a_radius, cVector3d& a_vertex0, cVector3d& a_vertex1, cVector3d& a_vertex2) { // empty box m_bbox.setEmpty(); // enclose all vertices m_bbox.enclose(a_vertex0); m_bbox.enclose(a_vertex1); m_bbox.enclose(a_vertex2); // retrieve boundary box min and max values cVector3d min = m_bbox.m_min; cVector3d max = m_bbox.m_max; // add radius envelope min.sub(a_radius, a_radius, a_radius); max.add(a_radius, a_radius, a_radius); // store new values m_bbox.setValue(min, max); } //============================================================================== /*! This method draws the edges of the boundary box for an internal tree node if it is at depth a_depth in the tree, and calls the draw function for its children. \param a_depth If a_depth > 0, then only draw nodes at this level in the tree. If a_depth < 0 render all nodes up to this level. */ //============================================================================== void cCollisionAABBNode::render(int a_depth) { #ifdef C_USE_OPENGL if ( ((a_depth < 0) && (abs(a_depth) >= m_depth)) || (a_depth == m_depth)) { m_bbox.render(); } #endif } //------------------------------------------------------------------------------ } // namespace chai3d //------------------------------------------------------------------------------
33.627551
85
0.515552
RoboticsDesignLab
4f3bc97ffe92b766ca5fd223c1408671a5d9f37d
2,848
cpp
C++
problemsets/Codeforces/C++/A260.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/Codeforces/C++/A260.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/Codeforces/C++/A260.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
/** * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * */ #define _USE_MATH_DEFINES #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> pi; typedef pair<ll,ll> pl; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<ll> vl; typedef vector<pi> vpi; typedef vector<pl> vpl; #define FOR(i, a, b) for (int i = (a); i < (b); i++) #define ROF(i,a,b) for (int i = (b)-1; i >= (a); i--) #define FORE(a, x) for (auto& a : x) #define eb emplace_back #define mp make_pair #define mt make_tuple #define f first #define s second #define sz(v) ((int) (v).size()) #define beg(x) begin(x) #define all(v) beg(v), end(v) #define sqr(x) ((x)*(x)) #define ms(x,b) memset(x,b,sizeof(x)) const int MOD = 1000000007; const ll INF = 1E18; const double EPS = 1E-10; template<class T> T ckmin(T &a, T b) { return a = min(a, b); } template<class T> T ckmax(T &a, T b) { return a = max(a, b); } namespace input { template<class T1, class T2> void re(pair<T1,T2>& p); template<class T> void re(vector<T>& a); template<class T> void re(T& x) { cin >> x; } void re(double& x) { string t; re(t); x = stod(t); } template<class A, class... As> void re(A& head, As&... tail) { re(head); re(tail...); } template<class T1, class T2> void re(pair<T1,T2>& p) { re(p.f,p.s); } template<class T> void re(vector<T>& a) { FOR(i,0,sz(a)) re(a[i]); } } using namespace input; namespace output { template<class T1, class T2> void pr(const pair<T1,T2>& x); template<class T> void pr(const vector<T>& x); template<class T> void pr(const set<T>& x); template<class T1, class T2> void pr(const map<T1,T2>& x); template<class T> void pr(const T& x) { cout << x; } template<class A, class... As> void pr(const A& head, const As&... tail) { pr(head); pr(tail...); } template<class T1, class T2> void pr(const pair<T1,T2>& x) { pr("{",x.f,", ",x.s,"}"); } template<class T> void prc(const T& x) { pr("{"); bool fi = 1; FORE(a,x) pr(!fi?", ":"",a), fi = 0; pr("}"); } template<class T> void pr(const vector<T>& x) { prc(x); } template<class T> void pr(const set<T>& x) { prc(x); } template<class T1, class T2> void pr(const map<T1,T2>& x) { prc(x); } void ps() { pr("\n"); } template<class A, class... As> void ps(const A& head, const As&... tail) { pr(head," "); ps(tail...); } } using namespace output; inline int cmp(double x, double y = 0, double tol = EPS) { return (x <= y + tol) ? (x + tol < y) ? -1 : 0 : 1; } int main() { //setbuf(stdout, NULL); cin.tie(0); ios::sync_with_stdio(0); int a, b, n; re(a,b,n); FOR(i,0,10) if ((a*10+i)%b==0) { pr(to_string(a*10+i) + string(n-1,'0')); return 0; } pr(-1); }
27.12381
79
0.570927
juarezpaulino
4f3be9cdfd8841e1b1156a3c1b68731caf68a254
9,802
cpp
C++
tools/legacy/sample_common/src/v4l2_util.cpp
cyew3/oneVPL
0a7182acc895d895537bfc08b0e61f71523756c9
[ "MIT" ]
null
null
null
tools/legacy/sample_common/src/v4l2_util.cpp
cyew3/oneVPL
0a7182acc895d895537bfc08b0e61f71523756c9
[ "MIT" ]
null
null
null
tools/legacy/sample_common/src/v4l2_util.cpp
cyew3/oneVPL
0a7182acc895d895537bfc08b0e61f71523756c9
[ "MIT" ]
null
null
null
/*############################################################################ # Copyright (C) Intel Corporation # # SPDX-License-Identifier: MIT ############################################################################*/ #if defined(ENABLE_V4L2_SUPPORT) #include "v4l2_util.h" #include <assert.h> #include <fcntl.h> #include <linux/videodev2.h> #include <poll.h> #include <pthread.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <sys/ioctl.h> /* Global Declaration */ Buffer *buffers, *CurBuffers; bool CtrlFlag = false; int m_q[5], m_first = 0, m_last = 0, m_numInQ = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t empty = PTHREAD_MUTEX_INITIALIZER; v4l2Device::v4l2Device(const char *devname, uint32_t width, uint32_t height, uint32_t num_buffers, enum AtomISPMode MipiMode, enum V4L2PixelFormat v4l2Format) : m_devname(devname), m_height(height), m_width(width), m_num_buffers(num_buffers), m_MipiPort(0), m_MipiMode(MipiMode), m_v4l2Format(v4l2Format), m_fd(-1) {} v4l2Device::~v4l2Device() { if (m_fd > -1) { BYE_ON(close(m_fd) < 0, "V4L2 device close failed: %s\n", ERRSTR); } } int v4l2Device::blockIOCTL(int handle, int request, void *args) { int ioctlStatus; do { ioctlStatus = ioctl(handle, request, args); } while (-1 == ioctlStatus && EINTR == errno); return ioctlStatus; } int v4l2Device::GetAtomISPModes(enum AtomISPMode mode) { switch (mode) { case VIDEO: return _ISP_MODE_VIDEO; case PREVIEW: return _ISP_MODE_PREVIEW; case CONTINUOUS: return _ISP_MODE_CONTINUOUS; case STILL: return _ISP_MODE_STILL; case NONE: default: return _ISP_MODE_NONE; } } int v4l2Device::ConvertToMFXFourCC(enum V4L2PixelFormat v4l2Format) { switch (v4l2Format) { case UYVY: return MFX_FOURCC_UYVY; case YUY2: return MFX_FOURCC_YUY2; case NO_FORMAT: default: assert(!"Unsupported mfx fourcc"); return 0; } } int v4l2Device::ConvertToV4L2FourCC() { switch (m_v4l2Format) { case UYVY: return V4L2_PIX_FMT_UYVY; case YUY2: return V4L2_PIX_FMT_YUYV; case NO_FORMAT: default: assert(!"Unsupported v4l2 fourcc"); return 0; } } void v4l2Device::Init(const char *devname, uint32_t width, uint32_t height, uint32_t num_buffers, enum V4L2PixelFormat v4l2Format, enum AtomISPMode MipiMode, int MipiPort) { (devname != NULL) ? m_devname = devname : m_devname; (m_width != width) ? m_width = width : m_width; (m_height != height) ? m_height = height : m_height; (m_num_buffers != num_buffers) ? m_num_buffers = num_buffers : m_num_buffers; (m_v4l2Format != v4l2Format) ? m_v4l2Format = v4l2Format : m_v4l2Format; (m_MipiMode != MipiMode) ? m_MipiMode = MipiMode : m_MipiMode; (m_MipiPort != MipiPort) ? m_MipiPort = MipiPort : m_MipiPort; memset(&m_format, 0, sizeof m_format); m_format.width = m_width; m_format.height = m_height; m_format.pixelformat = ConvertToV4L2FourCC(); V4L2Init(); } void v4l2Device::V4L2Init() { int ret; struct v4l2_format fmt; struct v4l2_capability caps; struct v4l2_streamparm parm; struct v4l2_requestbuffers rqbufs; CLEAR(parm); m_fd = open(m_devname, O_RDWR); BYE_ON(m_fd < 0, "failed to open %s: %s\n", m_devname, ERRSTR); CLEAR(caps); /* Specifically for setting up mipi configuration. DMABUFF is * also enable by default here. */ if (m_MipiPort > -1 && m_MipiMode != NONE) { parm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; parm.parm.capture.capturemode = GetAtomISPModes(m_MipiMode); ret = blockIOCTL(m_fd, VIDIOC_S_INPUT, &m_MipiPort); BYE_ON(ret < 0, "VIDIOC_S_INPUT failed: %s\n", ERRSTR); ret = blockIOCTL(m_fd, VIDIOC_S_PARM, &parm); BYE_ON(ret < 0, "VIDIOC_S_PARAM failed: %s\n", ERRSTR); } ret = blockIOCTL(m_fd, VIDIOC_QUERYCAP, &caps); msdk_printf("Driver Caps:\n" " Driver: \"%s\"\n" " Card: \"%s\"\n" " Bus: \"%s\"\n" " Version: %d.%d\n" " Capabilities: %08x\n", caps.driver, caps.card, caps.bus_info, (caps.version >> 16) && 0xff, (caps.version >> 24) && 0xff, caps.capabilities); BYE_ON(ret, "VIDIOC_QUERYCAP failed: %s\n", ERRSTR); BYE_ON(~caps.capabilities & V4L2_CAP_VIDEO_CAPTURE, "video: singleplanar capture is not supported\n"); CLEAR(fmt); fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; ret = blockIOCTL(m_fd, VIDIOC_G_FMT, &fmt); BYE_ON(ret < 0, "VIDIOC_G_FMT failed: %s\n", ERRSTR); msdk_printf( "G_FMT(start): width = %u, height = %u, 4cc = %.4s, BPP = %u sizeimage = %d field = %d\n", fmt.fmt.pix.width, fmt.fmt.pix.height, (char *)&fmt.fmt.pix.pixelformat, fmt.fmt.pix.bytesperline, fmt.fmt.pix.sizeimage, fmt.fmt.pix.field); fmt.fmt.pix = m_format; msdk_printf( "G_FMT(pre): width = %u, height = %u, 4cc = %.4s, BPP = %u sizeimage = %d field = %d\n", fmt.fmt.pix.width, fmt.fmt.pix.height, (char *)&fmt.fmt.pix.pixelformat, fmt.fmt.pix.bytesperline, fmt.fmt.pix.sizeimage, fmt.fmt.pix.field); ret = blockIOCTL(m_fd, VIDIOC_S_FMT, &fmt); BYE_ON(ret < 0, "VIDIOC_S_FMT failed: %s\n", ERRSTR); ret = blockIOCTL(m_fd, VIDIOC_G_FMT, &fmt); BYE_ON(ret < 0, "VIDIOC_G_FMT failed: %s\n", ERRSTR); msdk_printf("G_FMT(final): width = %u, height = %u, 4cc = %.4s, BPP = %u\n", fmt.fmt.pix.width, fmt.fmt.pix.height, (char *)&fmt.fmt.pix.pixelformat, fmt.fmt.pix.bytesperline); CLEAR(rqbufs); rqbufs.count = m_num_buffers; rqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; rqbufs.memory = V4L2_MEMORY_DMABUF; ret = blockIOCTL(m_fd, VIDIOC_REQBUFS, &rqbufs); BYE_ON(ret < 0, "VIDIOC_REQBUFS failed: %s\n", ERRSTR); BYE_ON(rqbufs.count < m_num_buffers, "video node allocated only " "%u of %u buffers\n", rqbufs.count, m_num_buffers); m_format = fmt.fmt.pix; } void v4l2Device::V4L2Alloc() { buffers = (Buffer *)malloc(sizeof(Buffer) * (int)m_num_buffers); } void v4l2Device::V4L2QueueBuffer(Buffer *buffer) { struct v4l2_buffer buf; int ret; memset(&buf, 0, sizeof buf); buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_DMABUF; buf.index = buffer->index; buf.m.fd = buffer->fd; ret = blockIOCTL(m_fd, VIDIOC_QBUF, &buf); BYE_ON(ret < 0, "VIDIOC_QBUF for buffer %d failed: %s (fd %u) (i %u)\n", buf.index, ERRSTR, buffer->fd, buffer->index); } Buffer *v4l2Device::V4L2DeQueueBuffer(Buffer *buffer) { struct v4l2_buffer buf; int ret; memset(&buf, 0, sizeof buf); buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_DMABUF; ret = blockIOCTL(m_fd, VIDIOC_DQBUF, &buf); BYE_ON(ret, "VIDIOC_DQBUF failed: %s\n", ERRSTR); return &buffer[buf.index]; } void v4l2Device::V4L2StartCapture() { int type = V4L2_BUF_TYPE_VIDEO_CAPTURE; int ret = 0; ret = blockIOCTL(m_fd, VIDIOC_STREAMON, &type); BYE_ON(ret < 0, "STREAMON failed: %s\n", ERRSTR); } void v4l2Device::V4L2StopCapture() { int type = V4L2_BUF_TYPE_VIDEO_CAPTURE; int ret = 0; ret = blockIOCTL(m_fd, VIDIOC_STREAMOFF, &type); BYE_ON(ret < 0, "STREAMOFF failed: %s\n", ERRSTR); } void v4l2Device::PutOnQ(int x) { pthread_mutex_lock(&mutex); m_q[m_first] = x; m_first = (m_first + 1) % 5; m_numInQ++; pthread_mutex_unlock(&mutex); pthread_mutex_unlock(&empty); } int v4l2Device::GetOffQ() { int thing; /* wait if the queue is empty. */ while (m_numInQ == 0) pthread_mutex_lock(&empty); pthread_mutex_lock(&mutex); thing = m_q[m_last]; m_last = (m_last + 1) % 5; m_numInQ--; pthread_mutex_unlock(&mutex); return thing; } int v4l2Device::GetV4L2TerminationSignal() { return (CtrlFlag && m_numInQ == 0) ? 1 : 0; } static void CtrlCTerminationHandler(int s) { CtrlFlag = true; } void *PollingThread(void *data) { v4l2Device *v4l2 = (v4l2Device *)data; struct sigaction sigIntHandler; sigIntHandler.sa_handler = CtrlCTerminationHandler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGINT, &sigIntHandler, NULL); struct pollfd fd; fd.fd = v4l2->GetV4L2DisplayID(); fd.events = POLLIN; while (1) { if (poll(&fd, 1, 5000) > 0) { if (fd.revents & POLLIN) { CurBuffers = v4l2->V4L2DeQueueBuffer(buffers); v4l2->PutOnQ(CurBuffers->index); if (CtrlFlag) break; if (CurBuffers) v4l2->V4L2QueueBuffer(&buffers[CurBuffers->index]); } } } } #endif // ifdef ENABLE_V4L2_SUPPORT
29
98
0.574679
cyew3
4f3c5ca1426a95256ec2b17b7f34f1ed0a32587b
25,355
cc
C++
src/main/cpp/startup_options.cc
FengRillian/bazel
c962975f152e30741a3affb1d41dd885543bbea6
[ "Apache-2.0" ]
3
2019-03-18T23:49:16.000Z
2021-05-30T09:44:18.000Z
src/main/cpp/startup_options.cc
installation00/bazel
6f38f345a1bd278a71170c5d80aba3928afdc6ec
[ "Apache-2.0" ]
null
null
null
src/main/cpp/startup_options.cc
installation00/bazel
6f38f345a1bd278a71170c5d80aba3928afdc6ec
[ "Apache-2.0" ]
1
2020-03-14T09:39:13.000Z
2020-03-14T09:39:13.000Z
// Copyright 2014 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "src/main/cpp/startup_options.h" #include <assert.h> #include <cstdio> #include <cstdlib> #include <cstring> #include "src/main/cpp/blaze_util.h" #include "src/main/cpp/blaze_util_platform.h" #include "src/main/cpp/util/errors.h" #include "src/main/cpp/util/exit_code.h" #include "src/main/cpp/util/file.h" #include "src/main/cpp/util/logging.h" #include "src/main/cpp/util/numbers.h" #include "src/main/cpp/util/path.h" #include "src/main/cpp/util/path_platform.h" #include "src/main/cpp/util/strings.h" #include "src/main/cpp/workspace_layout.h" namespace blaze { using std::string; using std::vector; StartupFlag::~StartupFlag() {} bool UnaryStartupFlag::NeedsParameter() const { return true; } bool UnaryStartupFlag::IsValid(const std::string &arg) const { // The second argument of GetUnaryOption is not relevant to determine // whether the option is unary or not, hence we set it to the empty string // by default. // // TODO(lpino): Improve GetUnaryOption to only require the arg and the // option we are looking for. return GetUnaryOption(arg.c_str(), "", ("--" + name_).c_str()) != NULL; } bool NullaryStartupFlag::NeedsParameter() const { return false; } bool NullaryStartupFlag::IsValid(const std::string &arg) const { return GetNullaryOption(arg.c_str(), ("--" + name_).c_str()) || GetNullaryOption(arg.c_str(), ("--no" + name_).c_str()); } void StartupOptions::RegisterNullaryStartupFlag(const std::string &flag_name) { valid_startup_flags.insert(std::unique_ptr<NullaryStartupFlag>( new NullaryStartupFlag(flag_name))); } void StartupOptions::RegisterUnaryStartupFlag(const std::string &flag_name) { valid_startup_flags.insert(std::unique_ptr<UnaryStartupFlag>( new UnaryStartupFlag(flag_name))); } StartupOptions::StartupOptions(const string &product_name, const WorkspaceLayout *workspace_layout) : product_name(product_name), ignore_all_rc_files(false), deep_execroot(true), block_for_lock(true), host_jvm_debug(false), batch(false), batch_cpu_scheduling(false), io_nice_level(-1), shutdown_on_low_sys_mem(false), oom_more_eagerly(false), oom_more_eagerly_threshold(100), write_command_log(true), watchfs(false), fatal_event_bus_exceptions(false), command_port(0), connect_timeout_secs(30), have_invocation_policy_(false), client_debug(false), java_logging_formatter( "com.google.devtools.build.lib.util.SingleLineFormatter"), expand_configs_in_place(true), digest_function(), idle_server_tasks(true), original_startup_options_(std::vector<RcStartupFlag>()), #if defined(__APPLE__) macos_qos_class(QOS_CLASS_DEFAULT), #endif unlimit_coredumps(false) { if (blaze::IsRunningWithinTest()) { output_root = blaze_util::MakeAbsolute(blaze::GetPathEnv("TEST_TMPDIR")); max_idle_secs = 15; BAZEL_LOG(USER) << "$TEST_TMPDIR defined: output root default is '" << output_root << "' and max_idle_secs default is '" << max_idle_secs << "'."; } else { output_root = workspace_layout->GetOutputRoot(); max_idle_secs = 3 * 3600; BAZEL_LOG(INFO) << "output root is '" << output_root << "' and max_idle_secs default is '" << max_idle_secs << "'."; } #if defined(_WIN32) || defined(__CYGWIN__) string windows_unix_root = DetectBashAndExportBazelSh(); if (!windows_unix_root.empty()) { host_jvm_args.push_back(string("-Dbazel.windows_unix_root=") + windows_unix_root); } #endif // defined(_WIN32) || defined(__CYGWIN__) const string product_name_lower = GetLowercaseProductName(); output_user_root = blaze_util::JoinPath( output_root, "_" + product_name_lower + "_" + GetUserName()); // IMPORTANT: Before modifying the statements below please contact a Bazel // core team member that knows the internal procedure for adding/deprecating // startup flags. RegisterNullaryStartupFlag("batch"); RegisterNullaryStartupFlag("batch_cpu_scheduling"); RegisterNullaryStartupFlag("block_for_lock"); RegisterNullaryStartupFlag("client_debug"); RegisterNullaryStartupFlag("deep_execroot"); RegisterNullaryStartupFlag("expand_configs_in_place"); RegisterNullaryStartupFlag("experimental_oom_more_eagerly"); RegisterNullaryStartupFlag("fatal_event_bus_exceptions"); RegisterNullaryStartupFlag("host_jvm_debug"); RegisterNullaryStartupFlag("idle_server_tasks"); RegisterNullaryStartupFlag("shutdown_on_low_sys_mem"); RegisterNullaryStartupFlag("ignore_all_rc_files"); RegisterNullaryStartupFlag("unlimit_coredumps"); RegisterNullaryStartupFlag("watchfs"); RegisterNullaryStartupFlag("write_command_log"); RegisterUnaryStartupFlag("command_port"); RegisterUnaryStartupFlag("connect_timeout_secs"); RegisterUnaryStartupFlag("digest_function"); RegisterUnaryStartupFlag("experimental_oom_more_eagerly_threshold"); RegisterUnaryStartupFlag("server_javabase"); RegisterUnaryStartupFlag("host_jvm_args"); RegisterUnaryStartupFlag("host_jvm_profile"); RegisterUnaryStartupFlag("invocation_policy"); RegisterUnaryStartupFlag("io_nice_level"); RegisterUnaryStartupFlag("install_base"); RegisterUnaryStartupFlag("macos_qos_class"); RegisterUnaryStartupFlag("max_idle_secs"); RegisterUnaryStartupFlag("output_base"); RegisterUnaryStartupFlag("output_user_root"); RegisterUnaryStartupFlag("server_jvm_out"); } StartupOptions::~StartupOptions() {} string StartupOptions::GetLowercaseProductName() const { string lowercase_product_name = product_name; blaze_util::ToLower(&lowercase_product_name); return lowercase_product_name; } bool StartupOptions::IsNullary(const string& arg) const { for (const auto& flag : valid_startup_flags) { if (!flag->NeedsParameter() && flag->IsValid(arg)) { return true; } } return false; } bool StartupOptions::IsUnary(const string& arg) const { for (const auto& flag : valid_startup_flags) { if (flag->NeedsParameter() && flag->IsValid(arg)) { return true; } } return false; } void StartupOptions::AddExtraOptions(vector<string> *result) const {} blaze_exit_code::ExitCode StartupOptions::ProcessArg( const string &argstr, const string &next_argstr, const string &rcfile, bool *is_space_separated, string *error) { // We have to parse a specific option syntax, so GNU getopts won't do. All // options begin with "--" or "-". Values are given together with the option // delimited by '=' or in the next option. const char* arg = argstr.c_str(); const char* next_arg = next_argstr.empty() ? NULL : next_argstr.c_str(); const char* value = NULL; if ((value = GetUnaryOption(arg, next_arg, "--output_base")) != NULL) { output_base = blaze::AbsolutePathFromFlag(value); option_sources["output_base"] = rcfile; } else if ((value = GetUnaryOption(arg, next_arg, "--install_base")) != NULL) { install_base = blaze::AbsolutePathFromFlag(value); option_sources["install_base"] = rcfile; } else if ((value = GetUnaryOption(arg, next_arg, "--output_user_root")) != NULL) { output_user_root = blaze::AbsolutePathFromFlag(value); option_sources["output_user_root"] = rcfile; } else if ((value = GetUnaryOption(arg, next_arg, "--server_jvm_out")) != NULL) { server_jvm_out = blaze::AbsolutePathFromFlag(value); option_sources["server_jvm_out"] = rcfile; } else if (GetNullaryOption(arg, "--deep_execroot")) { deep_execroot = true; option_sources["deep_execroot"] = rcfile; } else if (GetNullaryOption(arg, "--nodeep_execroot")) { deep_execroot = false; option_sources["deep_execroot"] = rcfile; } else if (GetNullaryOption(arg, "--block_for_lock")) { block_for_lock = true; option_sources["block_for_lock"] = rcfile; } else if (GetNullaryOption(arg, "--noblock_for_lock")) { block_for_lock = false; option_sources["block_for_lock"] = rcfile; } else if (GetNullaryOption(arg, "--host_jvm_debug")) { host_jvm_debug = true; option_sources["host_jvm_debug"] = rcfile; } else if ((value = GetUnaryOption(arg, next_arg, "--host_jvm_profile")) != NULL) { host_jvm_profile = value; option_sources["host_jvm_profile"] = rcfile; } else if ((value = GetUnaryOption(arg, next_arg, "--server_javabase")) != NULL) { // TODO(bazel-team): Consider examining the javabase and re-execing in case // of architecture mismatch. server_javabase_ = blaze::AbsolutePathFromFlag(value); option_sources["server_javabase"] = rcfile; } else if ((value = GetUnaryOption(arg, next_arg, "--host_jvm_args")) != NULL) { host_jvm_args.push_back(value); option_sources["host_jvm_args"] = rcfile; // NB: This is incorrect } else if (GetNullaryOption(arg, "--ignore_all_rc_files")) { if (!rcfile.empty()) { *error = "Can't specify --ignore_all_rc_files in an rc file."; return blaze_exit_code::BAD_ARGV; } ignore_all_rc_files = true; option_sources["ignore_all_rc_files"] = rcfile; } else if (GetNullaryOption(arg, "--noignore_all_rc_files")) { if (!rcfile.empty()) { *error = "Can't specify --noignore_all_rc_files in an rc file."; return blaze_exit_code::BAD_ARGV; } ignore_all_rc_files = false; option_sources["ignore_all_rc_files"] = rcfile; } else if (GetNullaryOption(arg, "--batch")) { batch = true; option_sources["batch"] = rcfile; } else if (GetNullaryOption(arg, "--nobatch")) { batch = false; option_sources["batch"] = rcfile; } else if (GetNullaryOption(arg, "--batch_cpu_scheduling")) { batch_cpu_scheduling = true; option_sources["batch_cpu_scheduling"] = rcfile; } else if (GetNullaryOption(arg, "--nobatch_cpu_scheduling")) { batch_cpu_scheduling = false; option_sources["batch_cpu_scheduling"] = rcfile; } else if (GetNullaryOption(arg, "--fatal_event_bus_exceptions")) { fatal_event_bus_exceptions = true; option_sources["fatal_event_bus_exceptions"] = rcfile; } else if (GetNullaryOption(arg, "--nofatal_event_bus_exceptions")) { fatal_event_bus_exceptions = false; option_sources["fatal_event_bus_exceptions"] = rcfile; } else if ((value = GetUnaryOption(arg, next_arg, "--io_nice_level")) != NULL) { if (!blaze_util::safe_strto32(value, &io_nice_level) || io_nice_level > 7) { blaze_util::StringPrintf(error, "Invalid argument to --io_nice_level: '%s'. Must not exceed 7.", value); return blaze_exit_code::BAD_ARGV; } option_sources["io_nice_level"] = rcfile; } else if ((value = GetUnaryOption(arg, next_arg, "--max_idle_secs")) != NULL) { if (!blaze_util::safe_strto32(value, &max_idle_secs) || max_idle_secs < 0) { blaze_util::StringPrintf(error, "Invalid argument to --max_idle_secs: '%s'.", value); return blaze_exit_code::BAD_ARGV; } option_sources["max_idle_secs"] = rcfile; } else if ((value = GetUnaryOption(arg, next_arg, "--macos_qos_class")) != NULL) { // We parse the value of this flag on all platforms even if it is // macOS-specific to ensure that rc files mentioning it are valid. if (strcmp(value, "user-interactive") == 0) { #if defined(__APPLE__) macos_qos_class = QOS_CLASS_USER_INTERACTIVE; #endif } else if (strcmp(value, "user-initiated") == 0) { #if defined(__APPLE__) macos_qos_class = QOS_CLASS_USER_INITIATED; #endif } else if (strcmp(value, "default") == 0) { #if defined(__APPLE__) macos_qos_class = QOS_CLASS_DEFAULT; #endif } else if (strcmp(value, "utility") == 0) { #if defined(__APPLE__) macos_qos_class = QOS_CLASS_UTILITY; #endif } else if (strcmp(value, "background") == 0) { #if defined(__APPLE__) macos_qos_class = QOS_CLASS_BACKGROUND; #endif } else { blaze_util::StringPrintf( error, "Invalid argument to --macos_qos_class: '%s'.", value); return blaze_exit_code::BAD_ARGV; } option_sources["macos_qos_class"] = rcfile; } else if (GetNullaryOption(arg, "--shutdown_on_low_sys_mem")) { shutdown_on_low_sys_mem = true; option_sources["shutdown_on_low_sys_mem"] = rcfile; } else if (GetNullaryOption(arg, "--noshutdown_on_low_sys_mem")) { shutdown_on_low_sys_mem = false; option_sources["shutdown_on_low_sys_mem"] = rcfile; } else if (GetNullaryOption(arg, "--experimental_oom_more_eagerly")) { oom_more_eagerly = true; option_sources["experimental_oom_more_eagerly"] = rcfile; } else if (GetNullaryOption(arg, "--noexperimental_oom_more_eagerly")) { oom_more_eagerly = false; option_sources["experimental_oom_more_eagerly"] = rcfile; } else if ((value = GetUnaryOption( arg, next_arg, "--experimental_oom_more_eagerly_threshold")) != NULL) { if (!blaze_util::safe_strto32(value, &oom_more_eagerly_threshold) || oom_more_eagerly_threshold < 0) { blaze_util::StringPrintf(error, "Invalid argument to " "--experimental_oom_more_eagerly_threshold: " "'%s'.", value); return blaze_exit_code::BAD_ARGV; } option_sources["experimental_oom_more_eagerly_threshold"] = rcfile; } else if (GetNullaryOption(arg, "--write_command_log")) { write_command_log = true; option_sources["write_command_log"] = rcfile; } else if (GetNullaryOption(arg, "--nowrite_command_log")) { write_command_log = false; option_sources["write_command_log"] = rcfile; } else if (GetNullaryOption(arg, "--watchfs")) { watchfs = true; option_sources["watchfs"] = rcfile; } else if (GetNullaryOption(arg, "--nowatchfs")) { watchfs = false; option_sources["watchfs"] = rcfile; } else if (GetNullaryOption(arg, "--client_debug")) { client_debug = true; option_sources["client_debug"] = rcfile; } else if (GetNullaryOption(arg, "--noclient_debug")) { client_debug = false; option_sources["client_debug"] = rcfile; } else if (GetNullaryOption(arg, "--expand_configs_in_place")) { expand_configs_in_place = true; option_sources["expand_configs_in_place"] = rcfile; } else if (GetNullaryOption(arg, "--noexpand_configs_in_place")) { expand_configs_in_place = false; option_sources["expand_configs_in_place"] = rcfile; } else if (GetNullaryOption(arg, "--idle_server_tasks")) { idle_server_tasks = true; option_sources["idle_server_tasks"] = rcfile; } else if (GetNullaryOption(arg, "--noidle_server_tasks")) { idle_server_tasks = false; option_sources["idle_server_tasks"] = rcfile; } else if ((value = GetUnaryOption(arg, next_arg, "--connect_timeout_secs")) != NULL) { if (!blaze_util::safe_strto32(value, &connect_timeout_secs) || connect_timeout_secs < 1 || connect_timeout_secs > 120) { blaze_util::StringPrintf(error, "Invalid argument to --connect_timeout_secs: '%s'.\n" "Must be an integer between 1 and 120.\n", value); return blaze_exit_code::BAD_ARGV; } option_sources["connect_timeout_secs"] = rcfile; } else if ((value = GetUnaryOption(arg, next_arg, "--digest_function")) != NULL) { digest_function = value; option_sources["digest_function"] = rcfile; } else if ((value = GetUnaryOption(arg, next_arg, "--command_port")) != NULL) { if (!blaze_util::safe_strto32(value, &command_port) || command_port < 0 || command_port > 65535) { blaze_util::StringPrintf(error, "Invalid argument to --command_port: '%s'.\n" "Must be a valid port number or 0.\n", value); return blaze_exit_code::BAD_ARGV; } option_sources["command_port"] = rcfile; } else if ((value = GetUnaryOption(arg, next_arg, "--invocation_policy")) != NULL) { if (!have_invocation_policy_) { have_invocation_policy_ = true; invocation_policy = value; option_sources["invocation_policy"] = rcfile; } else { *error = "The startup flag --invocation_policy cannot be specified " "multiple times."; return blaze_exit_code::BAD_ARGV; } } else if (GetNullaryOption(arg, "--unlimit_coredumps")) { unlimit_coredumps = true; option_sources["unlimit_coredumps"] = rcfile; } else if (GetNullaryOption(arg, "--nounlimit_coredumps")) { unlimit_coredumps = false; option_sources["unlimit_coredumps"] = rcfile; } else { bool extra_argument_processed; blaze_exit_code::ExitCode process_extra_arg_exit_code = ProcessArgExtra( arg, next_arg, rcfile, &value, &extra_argument_processed, error); if (process_extra_arg_exit_code != blaze_exit_code::SUCCESS) { return process_extra_arg_exit_code; } if (!extra_argument_processed) { blaze_util::StringPrintf( error, "Unknown startup option: '%s'.\n" " For more info, run '%s help startup_options'.", arg, GetLowercaseProductName().c_str()); return blaze_exit_code::BAD_ARGV; } } *is_space_separated = ((value == next_arg) && (value != NULL)); return blaze_exit_code::SUCCESS; } blaze_exit_code::ExitCode StartupOptions::ProcessArgs( const std::vector<RcStartupFlag>& rcstartup_flags, std::string *error) { std::vector<RcStartupFlag>::size_type i = 0; while (i < rcstartup_flags.size()) { bool is_space_separated = false; const std::string next_value = (i == rcstartup_flags.size() - 1) ? "" : rcstartup_flags[i + 1].value; const blaze_exit_code::ExitCode process_arg_exit_code = ProcessArg(rcstartup_flags[i].value, next_value, rcstartup_flags[i].source, &is_space_separated, error); // Store the provided option in --flag(=value)? form. Store these before // propagating any error code, since we want to have the correct // information for the output. The fact that the options aren't parseable // doesn't matter for this step. if (is_space_separated) { const std::string combined_value = rcstartup_flags[i].value + "=" + next_value; original_startup_options_.push_back( RcStartupFlag(rcstartup_flags[i].source, combined_value)); i += 2; } else { original_startup_options_.push_back( RcStartupFlag(rcstartup_flags[i].source, rcstartup_flags[i].value)); i++; } if (process_arg_exit_code != blaze_exit_code::SUCCESS) { return process_arg_exit_code; } } return blaze_exit_code::SUCCESS; } string StartupOptions::GetSystemJavabase() const { return blaze::GetSystemJavabase(); } string StartupOptions::GetEmbeddedJavabase() { string bundled_jre_path = blaze_util::JoinPath( install_base, "_embedded_binaries/embedded_tools/jdk"); if (blaze_util::CanExecuteFile(blaze_util::JoinPath( bundled_jre_path, GetJavaBinaryUnderJavabase()))) { return bundled_jre_path; } return ""; } string StartupOptions::GetServerJavabase() { // 1) Allow overriding the server_javabase via --server_javabase. if (!server_javabase_.empty()) { return server_javabase_; } if (default_server_javabase_.empty()) { string bundled_jre_path = GetEmbeddedJavabase(); if (!bundled_jre_path.empty()) { // 2) Use a bundled JVM if we have one. default_server_javabase_ = bundled_jre_path; } else { // 3) Otherwise fall back to using the default system JVM. string system_javabase = GetSystemJavabase(); if (system_javabase.empty()) { BAZEL_DIE(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR) << "Could not find system javabase. Ensure JAVA_HOME is set, or " "javac is on your PATH."; } default_server_javabase_ = system_javabase; } } return default_server_javabase_; } string StartupOptions::GetExplicitServerJavabase() const { return server_javabase_; } string StartupOptions::GetJvm() { string java_program = blaze_util::JoinPath(GetServerJavabase(), GetJavaBinaryUnderJavabase()); if (!blaze_util::CanExecuteFile(java_program)) { if (!blaze_util::PathExists(java_program)) { BAZEL_LOG(ERROR) << "Couldn't find java at '" << java_program << "'."; } else { BAZEL_LOG(ERROR) << "Java at '" << java_program << "' exists but is not executable: " << blaze_util::GetLastErrorString(); } exit(1); } // If the full JDK is installed string jdk_rt_jar = blaze_util::JoinPath(GetServerJavabase(), "jre/lib/rt.jar"); // If just the JRE is installed string jre_rt_jar = blaze_util::JoinPath(GetServerJavabase(), "lib/rt.jar"); // rt.jar does not exist in java 9+ so check for java instead string jre_java = blaze_util::JoinPath(GetServerJavabase(), "bin/java"); string jre_java_exe = blaze_util::JoinPath(GetServerJavabase(), "bin/java.exe"); if (blaze_util::CanReadFile(jdk_rt_jar) || blaze_util::CanReadFile(jre_rt_jar) || blaze_util::CanReadFile(jre_java) || blaze_util::CanReadFile(jre_java_exe)) { return java_program; } BAZEL_LOG(ERROR) << "Problem with java installation: couldn't find/access " "rt.jar or java in " << GetServerJavabase(); exit(1); } string StartupOptions::GetExe(const string &jvm, const string &jar_path) { return jvm; } void StartupOptions::AddJVMArgumentPrefix(const string &javabase, std::vector<string> *result) const { } void StartupOptions::AddJVMArgumentSuffix(const string &real_install_dir, const string &jar_path, std::vector<string> *result) const { result->push_back("-jar"); result->push_back(blaze_util::PathAsJvmFlag( blaze_util::JoinPath(real_install_dir, jar_path))); } blaze_exit_code::ExitCode StartupOptions::AddJVMArguments( const string &server_javabase, std::vector<string> *result, const vector<string> &user_options, string *error) const { AddJVMLoggingArguments(result); // Disable the JVM's own unlimiting of file descriptors. We do this // ourselves in blaze.cc so we want our setting to propagate to the JVM. // // The reason to do this is that the JVM's unlimiting is suboptimal on // macOS. Under that platform, the JVM limits the open file descriptors // to the OPEN_MAX constant... which is much lower than the per-process // kernel allowed limit of kern.maxfilesperproc (which is what we set // ourselves to). result->push_back("-XX:-MaxFDLimit"); return AddJVMMemoryArguments(server_javabase, result, user_options, error); } static std::string GetSimpleLogHandlerProps( const std::string &java_log, const std::string &java_logging_formatter) { return "handlers=com.google.devtools.build.lib.util.SimpleLogHandler\n" ".level=INFO\n" "com.google.devtools.build.lib.util.SimpleLogHandler.level=INFO\n" "com.google.devtools.build.lib.util.SimpleLogHandler.prefix=" + java_log + "\n" "com.google.devtools.build.lib.util.SimpleLogHandler.limit=1024000\n" "com.google.devtools.build.lib.util.SimpleLogHandler.total_limit=" "20971520\n" // 20 MB. "com.google.devtools.build.lib.util.SimpleLogHandler.formatter=" + java_logging_formatter + "\n"; } void StartupOptions::AddJVMLoggingArguments(std::vector<string> *result) const { // Configure logging const string propFile = blaze_util::PathAsJvmFlag( blaze_util::JoinPath(output_base, "javalog.properties")); const string java_log( blaze_util::PathAsJvmFlag(blaze_util::JoinPath(output_base, "java.log"))); const std::string loggingProps = GetSimpleLogHandlerProps(java_log, java_logging_formatter); if (!blaze_util::WriteFile(loggingProps, propFile)) { perror(("Couldn't write logging file " + propFile).c_str()); } else { result->push_back("-Djava.util.logging.config.file=" + propFile); result->push_back( "-Dcom.google.devtools.build.lib.util.LogHandlerQuerier.class=" "com.google.devtools.build.lib.util.SimpleLogHandler$HandlerQuerier"); } } blaze_exit_code::ExitCode StartupOptions::AddJVMMemoryArguments( const string &, std::vector<string> *, const vector<string> &, string *) const { return blaze_exit_code::SUCCESS; } } // namespace blaze
40.118671
80
0.688069
FengRillian
4f3f451ae508e57f46b41a5bc2e5998a517e9af4
14,535
cpp
C++
evo-X-Scriptdev2/scripts/eastern_kingdoms/magisters_terrace/boss_selin_fireheart.cpp
Gigelf-evo-X/evo-X
d0e68294d8cacfc7fb3aed5572f51d09a47136b9
[ "OpenSSL" ]
1
2019-01-19T06:35:40.000Z
2019-01-19T06:35:40.000Z
evo-X-Scriptdev2/scripts/eastern_kingdoms/magisters_terrace/boss_selin_fireheart.cpp
Gigelf-evo-X/evo-X
d0e68294d8cacfc7fb3aed5572f51d09a47136b9
[ "OpenSSL" ]
null
null
null
evo-X-Scriptdev2/scripts/eastern_kingdoms/magisters_terrace/boss_selin_fireheart.cpp
Gigelf-evo-X/evo-X
d0e68294d8cacfc7fb3aed5572f51d09a47136b9
[ "OpenSSL" ]
null
null
null
/* Copyright (C) 2006 - 2010 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Boss_Selin_Fireheart SD%Complete: 90 SDComment: Heroic and Normal Support. Needs further testing. SDCategory: Magister's Terrace EndScriptData */ #include "precompiled.h" #include "magisters_terrace.h" #define SAY_AGGRO -1585000 #define SAY_ENERGY -1585001 #define SAY_EMPOWERED -1585002 #define SAY_KILL_1 -1585003 #define SAY_KILL_2 -1585004 #define SAY_DEATH -1585005 #define EMOTE_CRYSTAL -1585006 //Crystal effect spells #define SPELL_FEL_CRYSTAL_COSMETIC 44374 #define SPELL_FEL_CRYSTAL_DUMMY 44329 #define SPELL_FEL_CRYSTAL_VISUAL 44355 #define SPELL_MANA_RAGE 44320 // This spell triggers 44321, which changes scale and regens mana Requires an entry in spell_script_target //Selin's spells #define SPELL_DRAIN_LIFE 44294 #define SPELL_FEL_EXPLOSION 44314 #define SPELL_DRAIN_MANA 46153 // Heroic only #define CRYSTALS_NUMBER 5 #define DATA_CRYSTALS 6 #define CREATURE_FEL_CRYSTAL 24722 struct MANGOS_DLL_DECL boss_selin_fireheartAI : public ScriptedAI { boss_selin_fireheartAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); m_bIsRegularMode = pCreature->GetMap()->IsRegularDifficulty(); Crystals.clear(); //GUIDs per instance is static, so we only need to load them once. if (m_pInstance) { uint32 size = m_pInstance->GetData(DATA_FEL_CRYSTAL_SIZE); for(uint8 i = 0; i < size; ++i) { uint64 guid = m_pInstance->GetData64(DATA_FEL_CRYSTAL); debug_log("SD2: Selin: Adding Fel Crystal " UI64FMTD " to list", guid); Crystals.push_back(guid); } } Reset(); } ScriptedInstance* m_pInstance; bool m_bIsRegularMode; std::list<uint64> Crystals; uint32 DrainLifeTimer; uint32 DrainManaTimer; uint32 FelExplosionTimer; uint32 DrainCrystalTimer; uint32 EmpowerTimer; bool IsDraining; bool DrainingCrystal; uint64 CrystalGUID; // This will help us create a pointer to the crystal we are draining. We store GUIDs, never units in case unit is deleted/offline (offline if player of course). void Reset() { if (m_pInstance) { //for(uint8 i = 0; i < CRYSTALS_NUMBER; ++i) for(std::list<uint64>::iterator itr = Crystals.begin(); itr != Crystals.end(); ++itr) { //Unit* pUnit = Unit::GetUnit(*m_creature, FelCrystals[i]); Unit* pUnit = Unit::GetUnit(*m_creature, *itr); if (pUnit) { if (!pUnit->isAlive()) ((Creature*)pUnit)->Respawn(); // Let MaNGOS handle setting death state, etc. // Only need to set unselectable flag. You can't attack unselectable units so non_attackable flag is not necessary here. pUnit->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); } } if (GameObject* pDoor = m_pInstance->instance->GetGameObject(m_pInstance->GetData64(DATA_SELIN_ENCOUNTER_DOOR))) pDoor->SetGoState(GO_STATE_ACTIVE); // Open the big encounter door. Close it in Aggro and open it only in JustDied(and here) // Small door opened after event are expected to be closed by default // Set Inst data for encounter m_pInstance->SetData(DATA_SELIN_EVENT, NOT_STARTED); }else error_log(ERROR_INST_DATA); DrainLifeTimer = urand(3000, 7000); DrainManaTimer = DrainLifeTimer + 5000; FelExplosionTimer = 2100; DrainCrystalTimer = urand(10000, 15000); DrainCrystalTimer = urand(20000, 25000); EmpowerTimer = 10000; IsDraining = false; DrainingCrystal = false; CrystalGUID = 0; } void SelectNearestCrystal() { if (Crystals.empty()) return; float ShortestDistance = 0; CrystalGUID = 0; Unit* pCrystal = NULL; Unit* CrystalChosen = NULL; //for(uint8 i = 0; i < CRYSTALS_NUMBER; ++i) for(std::list<uint64>::iterator itr = Crystals.begin(); itr != Crystals.end(); ++itr) { pCrystal = NULL; //pCrystal = Unit::GetUnit(*m_creature, FelCrystals[i]); pCrystal = Unit::GetUnit(*m_creature, *itr); if (pCrystal && pCrystal->isAlive()) { // select nearest if (!CrystalChosen || m_creature->GetDistanceOrder(pCrystal, CrystalChosen, false)) { CrystalGUID = pCrystal->GetGUID(); CrystalChosen = pCrystal; // Store a copy of pCrystal so we don't need to recreate a pointer to closest crystal for the movement and yell. } } } if (CrystalChosen) { DoScriptText(SAY_ENERGY, m_creature); DoScriptText(EMOTE_CRYSTAL, m_creature); CrystalChosen->CastSpell(CrystalChosen, SPELL_FEL_CRYSTAL_COSMETIC, true); float x, y, z; // coords that we move to, close to the crystal. CrystalChosen->GetClosePoint(x, y, z, m_creature->GetObjectSize(), CONTACT_DISTANCE); m_creature->RemoveSplineFlag(SPLINEFLAG_WALKMODE); m_creature->GetMotionMaster()->MovePoint(1, x, y, z); DrainingCrystal = true; } } void ShatterRemainingCrystals() { if (Crystals.empty()) return; //for(uint8 i = 0; i < CRYSTALS_NUMBER; ++i) for(std::list<uint64>::iterator itr = Crystals.begin(); itr != Crystals.end(); ++itr) { //Creature* pCrystal = ((Creature*)Unit::GetUnit(*m_creature, FelCrystals[i])); Creature* pCrystal = ((Creature*)Unit::GetUnit(*m_creature, *itr)); if (pCrystal && pCrystal->isAlive()) pCrystal->DealDamage(pCrystal, pCrystal->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); } } void Aggro(Unit* who) { DoScriptText(SAY_AGGRO, m_creature); if (m_pInstance) { //Close the encounter door, open it in JustDied/Reset if (GameObject* pEncounterDoor = m_pInstance->instance->GetGameObject(m_pInstance->GetData64(DATA_SELIN_ENCOUNTER_DOOR))) pEncounterDoor->SetGoState(GO_STATE_READY); } } void KilledUnit(Unit* victim) { DoScriptText(urand(0, 1) ? SAY_KILL_1 : SAY_KILL_2, m_creature); } void MovementInform(uint32 type, uint32 id) { if (type == POINT_MOTION_TYPE && id == 1) { Unit* CrystalChosen = Unit::GetUnit(*m_creature, CrystalGUID); if (CrystalChosen && CrystalChosen->isAlive()) { // Make the crystal attackable // We also remove NON_ATTACKABLE in case the database has it set. CrystalChosen->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE + UNIT_FLAG_NOT_SELECTABLE); CrystalChosen->CastSpell(m_creature, SPELL_MANA_RAGE, true); IsDraining = true; } else { // Make an error message in case something weird happened here error_log("SD2: Selin Fireheart unable to drain crystal as the crystal is either dead or despawned"); DrainingCrystal = false; } } } void JustDied(Unit* killer) { DoScriptText(SAY_DEATH, m_creature); if (!m_pInstance) { error_log(ERROR_INST_DATA); return; } m_pInstance->SetData(DATA_SELIN_EVENT, DONE); // Encounter complete! if (GameObject* pEncounterDoor = m_pInstance->instance->GetGameObject(m_pInstance->GetData64(DATA_SELIN_ENCOUNTER_DOOR))) pEncounterDoor->SetGoState(GO_STATE_ACTIVE); // Open the encounter door if (GameObject* pContinueDoor = m_pInstance->instance->GetGameObject(m_pInstance->GetData64(DATA_SELIN_DOOR))) pContinueDoor->SetGoState(GO_STATE_ACTIVE); // Open the door leading further in ShatterRemainingCrystals(); } void UpdateAI(const uint32 diff) { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; if (!DrainingCrystal) { uint32 maxPowerMana = m_creature->GetMaxPower(POWER_MANA); if (maxPowerMana && ((m_creature->GetPower(POWER_MANA)*100 / maxPowerMana) < 10)) { if (DrainLifeTimer < diff) { if (Unit* pTarget = SelectUnit(SELECT_TARGET_RANDOM, 0)) DoCastSpellIfCan(pTarget, SPELL_DRAIN_LIFE); DrainLifeTimer = 10000; }else DrainLifeTimer -= diff; // Heroic only if (!m_bIsRegularMode) { if (DrainManaTimer < diff) { if (Unit* pTarget = SelectUnit(SELECT_TARGET_RANDOM, 1)) DoCastSpellIfCan(pTarget, SPELL_DRAIN_MANA); DrainManaTimer = 10000; }else DrainManaTimer -= diff; } } if (FelExplosionTimer < diff) { if (!m_creature->IsNonMeleeSpellCasted(false)) { DoCastSpellIfCan(m_creature, SPELL_FEL_EXPLOSION); FelExplosionTimer = 2000; } }else FelExplosionTimer -= diff; // If below 10% mana, start recharging maxPowerMana = m_creature->GetMaxPower(POWER_MANA); if (maxPowerMana && ((m_creature->GetPower(POWER_MANA)*100 / maxPowerMana) < 10)) { if (DrainCrystalTimer < diff) { SelectNearestCrystal(); if (m_bIsRegularMode) DrainCrystalTimer = urand(20000, 25000); else DrainCrystalTimer = urand(10000, 15000); }else DrainCrystalTimer -= diff; } }else { if (IsDraining) { if (EmpowerTimer < diff) { IsDraining = false; DrainingCrystal = false; DoScriptText(SAY_EMPOWERED, m_creature); Unit* CrystalChosen = Unit::GetUnit(*m_creature, CrystalGUID); if (CrystalChosen && CrystalChosen->isAlive()) // Use Deal Damage to kill it, not setDeathState. CrystalChosen->DealDamage(CrystalChosen, CrystalChosen->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); CrystalGUID = 0; m_creature->GetMotionMaster()->Clear(); m_creature->GetMotionMaster()->MoveChase(m_creature->getVictim()); }else EmpowerTimer -= diff; } } DoMeleeAttackIfReady(); // No need to check if we are draining crystal here, as the spell has a stun. } }; CreatureAI* GetAI_boss_selin_fireheart(Creature* pCreature) { return new boss_selin_fireheartAI(pCreature); }; struct MANGOS_DLL_DECL mob_fel_crystalAI : public ScriptedAI { mob_fel_crystalAI(Creature* pCreature) : ScriptedAI(pCreature) { Reset(); } void Reset() {} void AttackStart(Unit* who) {} void MoveInLineOfSight(Unit* who) {} void UpdateAI(const uint32 diff) {} void JustDied(Unit* killer) { if (ScriptedInstance* pInstance = ((ScriptedInstance*)m_creature->GetInstanceData())) { Creature* Selin = ((Creature*)Unit::GetUnit(*m_creature, pInstance->GetData64(DATA_SELIN))); if (Selin && Selin->isAlive()) { if (((boss_selin_fireheartAI*)Selin->AI())->CrystalGUID == m_creature->GetGUID()) { // Set this to false if we are the creature that Selin is draining so his AI flows properly ((boss_selin_fireheartAI*)Selin->AI())->DrainingCrystal = false; ((boss_selin_fireheartAI*)Selin->AI())->IsDraining = false; ((boss_selin_fireheartAI*)Selin->AI())->EmpowerTimer = 10000; if (Selin->getVictim()) { Selin->AI()->AttackStart(Selin->getVictim()); Selin->GetMotionMaster()->MoveChase(Selin->getVictim()); } } } }else error_log(ERROR_INST_DATA); } }; CreatureAI* GetAI_mob_fel_crystal(Creature* pCreature) { return new mob_fel_crystalAI(pCreature); }; void AddSC_boss_selin_fireheart() { Script *newscript; newscript = new Script; newscript->Name = "boss_selin_fireheart"; newscript->GetAI = &GetAI_boss_selin_fireheart; newscript->RegisterSelf(); newscript = new Script; newscript->Name = "mob_fel_crystal"; newscript->GetAI = &GetAI_mob_fel_crystal; newscript->RegisterSelf(); }
37.753247
220
0.578535
Gigelf-evo-X
4f4043f254089a663a5bb28a481138e3aee6ec0a
9,804
cpp
C++
src/ngraph/pass/concat_fusion.cpp
ilya-lavrenov/ngraph
2d8b2b4b30dbcabda0c3de2ae458418e63da057a
[ "Apache-2.0" ]
1
2021-10-04T21:55:19.000Z
2021-10-04T21:55:19.000Z
src/ngraph/pass/concat_fusion.cpp
ilya-lavrenov/ngraph
2d8b2b4b30dbcabda0c3de2ae458418e63da057a
[ "Apache-2.0" ]
1
2019-02-20T20:56:47.000Z
2019-02-22T20:10:28.000Z
src/ngraph/pass/concat_fusion.cpp
darchr/ngraph
7c540e5230f8143ecb6926685c7b49305f0f988a
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2017-2019 Intel Corporation // // 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 "concat_fusion.hpp" #include <algorithm> #include <iostream> #include <numeric> #include <unordered_set> #include "ngraph/graph_util.hpp" #include "ngraph/log.hpp" #include "ngraph/op/broadcast.hpp" #include "ngraph/op/concat.hpp" #include "ngraph/op/parameter.hpp" #include "ngraph/op/reshape.hpp" #include "ngraph/pattern/matcher.hpp" #include "ngraph/pattern/op/label.hpp" #include "ngraph/pattern/op/skip.hpp" #include "ngraph/util.hpp" using namespace ngraph; namespace { bool check_self_concat_op(const std::shared_ptr<Node>& op) { auto input_args = op->get_arguments(); std::set<std::shared_ptr<Node>> input_args_set(input_args.begin(), input_args.end()); return (input_args_set.size() == 1); } bool check_concat_axis_dim_value(const std::shared_ptr<Node>& concat_op) { auto input_shape = concat_op->get_input_shape(0); size_t concat_axis = std::static_pointer_cast<op::Concat>(concat_op)->get_concatenation_axis(); return (input_shape[concat_axis] == 1); } bool check_concat_has_no_fan_out(const std::shared_ptr<Node>& op) { auto no_fan_out = ngraph::pass::get_no_fan_out_function(); return no_fan_out(op); } bool valid_self_concat(const std::shared_ptr<Node>& Op) { if (!check_self_concat_op(Op)) { NGRAPH_DEBUG << "self_concat_fusion: Matcher matched " << Op->get_name() << " but it is not a self concat\n"; return false; } if (!check_concat_axis_dim_value(Op)) { NGRAPH_DEBUG << "self_concat_fusion: Input shape value along concat axis of " << Op->get_name() << " is not equal to 1\n"; return false; } return true; } std::vector<size_t> get_concatenation_axis_vector(const NodeVector& bounded_concat_ops) { std::vector<size_t> concat_axis_vec; for (auto iter : bounded_concat_ops) { auto concat_op = std::static_pointer_cast<op::Concat>(iter); concat_axis_vec.push_back(concat_op->get_concatenation_axis()); } return concat_axis_vec; } } void pass::ConcatElimination::construct_concat_elimination() { auto op_label = std::make_shared<pattern::op::Label>(element::f32, Shape{1, 3}); auto concat = std::make_shared<op::Concat>(NodeVector{op_label}, 0); auto concat_label = std::make_shared<pattern::op::Label>(concat, nullptr, NodeVector{concat}); auto callback = [op_label](pattern::Matcher& m) { NGRAPH_DEBUG << "concat_elimination: In callback for construct_concat_elimination against node = " << m.get_match_root()->get_name(); auto pattern_map = m.get_pattern_map(); auto op = pattern_map[op_label]; auto root = std::dynamic_pointer_cast<op::Concat>(m.get_match_root()); if (root && (root->get_input_shape(0) == root->get_output_shape(0))) { NGRAPH_DEBUG << " eliminated " << m.get_match_root() << "\n"; replace_node(m.get_match_root(), op); return true; } NGRAPH_DEBUG << " Incorrect match in callback\n"; return false; }; auto m = std::make_shared<pattern::Matcher>(concat_label, "ConcatElimination"); this->add_matcher(m, callback, PassProperty::REQUIRE_STATIC_SHAPE); } bool ngraph::pass::SelfConcatFusion::run_on_function(std::shared_ptr<Function> function) { bool modify_graph = false; auto has_multiple_inputs = [](std::shared_ptr<Node> n) { auto input_size = n->get_input_size(); auto root = std::dynamic_pointer_cast<op::Concat>(n); return (root && input_size > 1); }; auto print_state_of_bounded_vectors = [this]() -> std::string { std::stringstream ss; ss << "-----------------------------------------------------------" << std::endl; ss << "State of bounded pattern node vectors: " << std::endl; ss << "-----------------------------------------------------------" << std::endl; ss << "Number of pattern node vectors: " << this->m_concat_pattern_vectors.size() << std::endl; size_t c = 0; for (auto iter : this->m_concat_pattern_vectors) { ss << "For vector " << c << std::endl; auto iter_node_vec = iter; ss << "concat_op_vector: "; for (auto it : iter_node_vec) { ss << it->get_name() << " "; } ss << std::endl; c++; } ss << "-----------------------------" << std::endl; return ss.str(); }; auto concat_op_label = std::make_shared<pattern::op::Label>(element::f32, Shape{1, 3}, has_multiple_inputs); auto matcher = std::make_shared<pattern::Matcher>(concat_op_label); for (auto n : function->get_ordered_ops()) { construct_concat_patterns(matcher, concat_op_label, n); } NGRAPH_DEBUG << print_state_of_bounded_vectors(); remove_single_concat_op_pattern(); for (auto concat_op_pattern_node_vector : this->m_concat_pattern_vectors) { modify_graph = replace_patterns(concat_op_pattern_node_vector); } return modify_graph; } void ngraph::pass::SelfConcatFusion::construct_concat_patterns( const std::shared_ptr<pattern::Matcher>& matcher, const std::shared_ptr<pattern::op::Label>& concat_op_label, const std::shared_ptr<Node>& n) { if (matcher->match(n)) { auto concat_op = matcher->get_pattern_map()[concat_op_label]; if (!std::dynamic_pointer_cast<op::Concat>(concat_op)) { NGRAPH_DEBUG << "self_concat_fusion: Pattern matcher matched incorrect op. Matched " << concat_op->get_name() << " instead of a self concat"; return; } if (!valid_self_concat(concat_op)) { NGRAPH_DEBUG << "self_concat_fusion: " << concat_op->get_name() << " is not a valid self concat\n"; return; } else { NGRAPH_DEBUG << "self_concat_fusion: " << concat_op->get_name() << " is a VALID self concat\n"; } auto& concat_vectors = this->m_concat_pattern_vectors; if (concat_vectors.empty()) { concat_vectors.push_back(NodeVector{concat_op}); } else { update_concat_pattern_vectors(concat_op); } } } void ngraph::pass::SelfConcatFusion::update_concat_pattern_vectors( const std::shared_ptr<Node>& concat_op) { bool concat_source_found = false; for (auto& concat_pattern_vec : this->m_concat_pattern_vectors) { auto last_op_in_pattern_vec = concat_pattern_vec.back(); if ((concat_op->get_argument(0) == last_op_in_pattern_vec) && (check_concat_has_no_fan_out(last_op_in_pattern_vec))) { concat_pattern_vec.push_back(concat_op); concat_source_found = true; break; } } if (!concat_source_found) { this->m_concat_pattern_vectors.push_back(NodeVector{concat_op}); } } void ngraph::pass::SelfConcatFusion::remove_single_concat_op_pattern() { auto iter = m_concat_pattern_vectors.begin(); while (iter != m_concat_pattern_vectors.end()) { if (iter->size() == 1) { iter = m_concat_pattern_vectors.erase(iter); } else { iter++; } } } bool ngraph::pass::SelfConcatFusion::replace_patterns(const NodeVector& bounded_concat_ops) { auto scalarize_dim = [](std::vector<size_t> concat_axis_vector, const Shape& input_shape) -> Shape { Shape scalarized_shape; for (size_t i = 0; i < input_shape.size(); i++) { auto it = std::find(concat_axis_vector.begin(), concat_axis_vector.end(), i); if (it == concat_axis_vector.end()) { scalarized_shape.push_back(input_shape[i]); } } return scalarized_shape; }; auto concat_axis_vector = get_concatenation_axis_vector(bounded_concat_ops); auto& first_bounded_concat = (*bounded_concat_ops.begin()); auto driver_op = first_bounded_concat->get_argument(0); const Shape& input_shape = first_bounded_concat->get_input_shape(0); auto scalarized_shape = scalarize_dim(concat_axis_vector, input_shape); AxisVector axis_order = get_default_order(input_shape); auto reshape = std::make_shared<op::Reshape>(driver_op, axis_order, scalarized_shape); auto last_bounded_concat_op = bounded_concat_ops.back(); auto broadcast_out_shape = last_bounded_concat_op->get_shape(); auto broadcast = std::make_shared<op::Broadcast>(reshape, broadcast_out_shape, concat_axis_vector); replace_node(last_bounded_concat_op, broadcast); return true; }
34.64311
98
0.611179
ilya-lavrenov
4f40fb04ace20a1405092d8ec816fa716d6d4dad
2,267
hpp
C++
legacy/include/distconv/tensor/algorithms/common_cuda.hpp
benson31/DiHydrogen
f12d1e0281ae58e40eadf98b3e2209208c82f5e2
[ "ECL-2.0", "Apache-2.0" ]
3
2020-01-06T17:26:58.000Z
2021-12-11T01:17:43.000Z
legacy/include/distconv/tensor/algorithms/common_cuda.hpp
benson31/DiHydrogen
f12d1e0281ae58e40eadf98b3e2209208c82f5e2
[ "ECL-2.0", "Apache-2.0" ]
7
2020-02-26T06:07:42.000Z
2022-02-15T22:51:36.000Z
legacy/include/distconv/tensor/algorithms/common_cuda.hpp
benson31/DiHydrogen
f12d1e0281ae58e40eadf98b3e2209208c82f5e2
[ "ECL-2.0", "Apache-2.0" ]
6
2020-01-06T18:08:42.000Z
2021-07-26T14:53:07.000Z
#pragma once #include "distconv/tensor/tensor.hpp" #include <type_traits> namespace distconv { namespace tensor { namespace algorithms_cuda { constexpr int DEFAULT_BLOCK_SIZE = 256; constexpr int DEFAULT_MAX_THREAD_WORK_SIZE = 8; template <int BLOCK_SIZE, int MAX_THREAD_WORK_SIZE> void get_grid_dims(const Shape &region, dim3 &grid_dims, int &thread_work_size) { const int nd = region.num_dims(); index_t inner_size = 1; // default grid_dims = dim3(1, 1, 1); int inner_dim_exclude = 0; if (nd == 3) { grid_dims.y = region[-1]; ++inner_dim_exclude; } else if (nd > 3) { grid_dims.y = region[-2]; grid_dims.z = region[-1]; inner_dim_exclude += 2; } for (int i = 0; i < nd - inner_dim_exclude; ++i) { inner_size *= region[i]; } thread_work_size = std::min((int)((inner_size + BLOCK_SIZE - 1)/ BLOCK_SIZE), MAX_THREAD_WORK_SIZE); const int block_work_size = BLOCK_SIZE * thread_work_size; const size_t num_blocks_per_space = (inner_size + block_work_size - 1) / block_work_size; grid_dims.x = num_blocks_per_space; return; } template <int BLOCK_SIZE, int MAX_THREAD_WORK_SIZE> void get_grid_dims2(const Shape &region, dim3 &grid_dims, int &thread_work_size, int &inner_dim, int &num_inner_blocks) { const int nd = region.num_dims(); // default grid_dims = dim3(1, 1, 1); // determine which dimensions are traversed by a single block index_t inner_size = 1; inner_dim = 0; for (; inner_dim < nd; ++inner_dim) { inner_size *= region[inner_dim]; if (inner_size >= BLOCK_SIZE * MAX_THREAD_WORK_SIZE) { break; } } if (inner_dim == nd) { inner_dim = nd - 1; } thread_work_size = std::min((int)((inner_size + BLOCK_SIZE - 1)/ BLOCK_SIZE), MAX_THREAD_WORK_SIZE); const int block_work_size = BLOCK_SIZE * thread_work_size; num_inner_blocks = (inner_size + block_work_size - 1) / block_work_size; int num_outer_blocks = 1; for (int i = inner_dim + 1; i < nd; ++i) { num_outer_blocks *= region[i]; } grid_dims.x = num_inner_blocks * num_outer_blocks; return; } } // namespace algorithms_cuda } // namespace tensor } // namespace distconv
26.988095
64
0.660785
benson31
4f40fe19e8b8c54d4c1c2c589f96773c463f2b79
148,016
cc
C++
tensorflow/compiler/mlir/tensorflow/translate/import_model.cc
joshz123/tensorflow
7841ca029060ab78e221e757d4b1ee6e3e0ffaa4
[ "Apache-2.0" ]
1
2020-05-28T12:54:27.000Z
2020-05-28T12:54:27.000Z
tensorflow/compiler/mlir/tensorflow/translate/import_model.cc
joshz123/tensorflow
7841ca029060ab78e221e757d4b1ee6e3e0ffaa4
[ "Apache-2.0" ]
3
2019-03-21T17:56:51.000Z
2019-11-13T21:02:35.000Z
tensorflow/compiler/mlir/tensorflow/translate/import_model.cc
joshz123/tensorflow
7841ca029060ab78e221e757d4b1ee6e3e0ffaa4
[ "Apache-2.0" ]
2
2019-09-08T09:52:41.000Z
2019-12-11T19:49:52.000Z
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/mlir/tensorflow/translate/import_model.h" #include <iterator> #include <string> #include <tuple> #include <type_traits> #include <unordered_set> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/container/inlined_vector.h" #include "absl/strings/escaping.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/raw_ostream.h" #include "mlir/Analysis/Verifier.h" // from @llvm-project #include "mlir/Dialect/StandardOps/IR/Ops.h" // from @llvm-project #include "mlir/IR/Attributes.h" // from @llvm-project #include "mlir/IR/Builders.h" // from @llvm-project #include "mlir/IR/Diagnostics.h" // from @llvm-project #include "mlir/IR/Function.h" // from @llvm-project #include "mlir/IR/Identifier.h" // from @llvm-project #include "mlir/IR/Location.h" // from @llvm-project #include "mlir/IR/MLIRContext.h" // from @llvm-project #include "mlir/IR/Module.h" // from @llvm-project #include "mlir/IR/OpDefinition.h" // from @llvm-project #include "mlir/IR/OperationSupport.h" // from @llvm-project #include "mlir/IR/StandardTypes.h" // from @llvm-project #include "mlir/IR/Types.h" // from @llvm-project #include "tensorflow/compiler/jit/shape_inference_helpers.h" #include "tensorflow/compiler/mlir/op_or_arg_name_mapper.h" #include "tensorflow/compiler/mlir/tensorflow/ir/control_flow_ops.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_attributes.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_executor.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_saved_model.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_types.h" #include "tensorflow/compiler/mlir/tensorflow/translate/mlir_roundtrip_flags.h" #include "tensorflow/compiler/mlir/tensorflow/utils/convert_tensor.h" #include "tensorflow/compiler/mlir/tensorflow/utils/convert_type.h" #include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h" #include "tensorflow/compiler/mlir/tensorflow/utils/mangling_util.h" #include "tensorflow/compiler/mlir/tensorflow/utils/translate_utils.h" #include "tensorflow/compiler/tf2xla/functionalize_control_flow.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/core/common_runtime/function.h" #include "tensorflow/core/common_runtime/shape_refiner.h" #include "tensorflow/core/framework/attr_value.pb.h" #include "tensorflow/core/framework/function.pb.h" #include "tensorflow/core/framework/graph.pb.h" #include "tensorflow/core/framework/node_def.pb.h" #include "tensorflow/core/framework/node_def_util.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/resource_var.h" #include "tensorflow/core/framework/shape_inference.h" #include "tensorflow/core/framework/tensor.pb.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/framework/types.pb.h" #include "tensorflow/core/framework/versions.pb.h" #include "tensorflow/core/graph/algorithm.h" #include "tensorflow/core/graph/graph.h" #include "tensorflow/core/graph/graph_constructor.h" #include "tensorflow/core/graph/node_builder.h" #include "tensorflow/core/graph/tensor_id.h" #include "tensorflow/core/grappler/utils/transitive_fanin.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/platform/protobuf.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/protobuf/graph_debug_info.pb.h" #include "tensorflow/core/protobuf/meta_graph.pb.h" #include "tensorflow/core/protobuf/saved_object_graph.pb.h" #include "tensorflow/core/protobuf/struct.pb.h" #include "tensorflow/core/protobuf/trackable_object_graph.pb.h" #include "tensorflow/stream_executor/lib/statusor.h" static inline absl::string_view StringRefToView(llvm::StringRef ref) { return {ref.data(), ref.size()}; } namespace tensorflow { using stream_executor::port::StatusOr; namespace { bool IsDisableCallShapeInferenceAttribute(const AttrValue& attr_value, llvm::StringRef attr_name) { return attr_name.compare("_disable_call_shape_inference") == 0 && attr_value.value_case() == AttrValue::kB; } bool IsOutputShapesAttribute(const AttrValue& attr_value, llvm::StringRef attr_name) { return attr_name.compare("_output_shapes") == 0 && attr_value.value_case() == AttrValue::kList; } // This class is used to generate new MLIR function name strings that are both // unique in the TF function library `flib_` and unique among the name strings // generated by the class object during its lifetime. // // In theory, this class is not necessary because we should simply take // the TF function name and use it as MLIR function name. However, for some // unknown reasons (callout for investigation in b/142268695), keeping the // function names unchanged in an MLIR roundtrip causes test failures. // TODO(b/142268695) Re-evaluate whether we need this class v.s. directly using // and TF function name as MLIR function name after b/142268695 is root caused. class NameUniquifier : public OpOrArgNameMapper { public: explicit NameUniquifier(const FunctionLibraryDefinition& flib) : flib_(flib) {} private: bool IsUnique(llvm::StringRef name) override { return !flib_.Contains(std::string(name)); } std::string GetName(OpOrVal op_or_val) override { DCHECK(false) << "Unimplemented"; return ""; } const FunctionLibraryDefinition& flib_; }; // Stateful helper class to import a TensorFlow model into an MLIR Module. // // This is the base class that contains common utilities shared between the // GraphDef importer and SavedModel importer. // // A subclass is expected to call `PrepareConvert` first to perform necessary // preparation over the graph and also certain internal bookkeeping data. // Afterwards the other protected methods can be called. class ImporterBase { protected: explicit ImporterBase( const FunctionLibraryDefinition& flib, const GraphDebugInfo& debug_info, const GraphImportConfig& specs, mlir::ModuleOp module, std::unordered_map<std::string, std::string>* tf_name_to_mlir_name, NameUniquifier* function_name_uniquifier, llvm::StringRef function_name_for_debug_info = "") : builder_(module.getContext()), module_(module), context_(module.getContext()), tf_name_to_mlir_name_(tf_name_to_mlir_name), graph_flib_(flib), specs_(specs), debug_info_(debug_info), function_name_for_debug_info_(function_name_for_debug_info), function_name_uniquifier_(function_name_uniquifier), error_handler_(module.getContext()) {} // Returns the inferred function signature of the given function body. Input // types are unranked tensor of the respective datatype in the function and // result types are inferred by the shape_refiner_. Result types need not be // unranked tensors and could be ranked tensors in cases where result type // depends on an op with static output shape like tf.Const. StatusOr<mlir::FunctionType> InferLibFunctionType(const FunctionBody& fbody); // Extracts arg and ret nodes from FunctionBody. // `resource_arg_unique_ids` will be filled with the unique IDs of resource // variables, as a list of {index, ID} pairs. void GetArgsAndRetsFromFunctionBody( const FunctionBody& fbody, absl::InlinedVector<OutputTensor, 4>* arg_nodes, absl::InlinedVector<OutputTensor, 4>* ret_nodes, absl::InlinedVector<Node*, 4>* control_ret_nodes, absl::InlinedVector<std::pair<int64_t, int64_t>, 4>* resource_arg_unique_ids); // Prepares converting the graph to an MLIR module. This step removes the // backedges of the graph, orders the nodes and infers the shapes. Status PrepareConvert(const Graph& graph); // Converts the prepared graph to a Function and adds it to the module. A set // of nodes from the graph are given to converted to the arguments and returns // of the function. Status Convert(llvm::StringRef func_name, mlir::FunctionType func_type, const absl::InlinedVector<OutputTensor, 4>& arg_nodes, const absl::InlinedVector<OutputTensor, 4>& ret_nodes, const absl::InlinedVector<Node*, 4>& control_ret_nodes, llvm::ArrayRef<mlir::NamedAttribute> attrs, const absl::InlinedVector<std::pair<int64_t, int64_t>, 4>& resource_arg_unique_ids); // Finds out the function definition for the given function name from the // graph and converts it to a function of the module. This method is called // on demand because the graph flib_def does not provide an iterator // interface. Status ConvertLibFunction(llvm::StringRef func_name); // Returns the list of nodes in the graph. Nodes are presented in the reverse // order of a post-order depth-first visit starting from the graph's source // nodes. llvm::ArrayRef<Node*> GetOrderedNodes() const { return ordered_nodes_; } // Returns the inferred input type at index `idx` of the `node` in the // context. StatusOr<mlir::Type> InferInputType(const Node& node, int idx, mlir::Builder builder); // Returns the inferred output type at index `idx` of the `node` in the // context. StatusOr<mlir::Type> InferOutputType(const Node& node, int idx, mlir::Builder builder); private: // Most types with subtypes have only one subtype. using ElementSubtypes = llvm::SmallVector<mlir::TensorType, 1>; // Adds all the ordered_nodes to the shape refiner shape_refiner_. Then all // data type and shape information is maintained by the shape_refiner_. // TODO(jpienaar): Remove once shape inference on import is removed. Status AddNodesToShapeRefiner( std::unordered_map<string, Node*>* node_name_map); // Prune nodes that do not feed into fetch nodes. Status PruneUnreachableNodes( std::unordered_map<string, Node*>* node_name_map); // Converts feeds to Placeholder nodes. Status ConvertFeedsToPlaceholders( std::unordered_map<string, Node*>* node_name_map); // Converts the inferred shape referred to by 'handle' in 'context', with // given element type, and returns an MLIR tensor type. StatusOr<mlir::TensorType> ConvertDataTypeAndShape( DataType dtype, const shape_inference::ShapeHandle& handle, const std::vector<shape_inference::ShapeAndType>* handle_subtypes, shape_inference::InferenceContext* context, mlir::Builder builder); // Converts the inferred shape referred to by 'handle' in 'context', with // given element type, and returns an MLIR tensor type. StatusOr<mlir::TensorType> ConvertElementTypeAndShape( mlir::Type element_type, const shape_inference::ShapeHandle& handle, shape_inference::InferenceContext* context, mlir::Builder builder); // Converts the inferred subtypes for an element type to corresponding MLIR // types in 'context'. StatusOr<ElementSubtypes> ConvertSubtypes( const std::vector<shape_inference::ShapeAndType>* handle_subtypes, shape_inference::InferenceContext* context, mlir::Builder builder); // Converts the tensor proto into an MLIR elements attribute. StatusOr<mlir::ElementsAttr> ConvertTensorProto(const TensorProto& value) { return ::tensorflow::ConvertTensorProto(value, &builder_); } // Converts the tensor shape proto into an MLIR shape attribute. StatusOr<mlir::TF::ShapeAttr> ConvertTensorShapeProto( const TensorShapeProto& shape) { if (shape.unknown_rank()) return mlir::TF::ShapeAttr::get(builder_.getContext(), llvm::None); llvm::SmallVector<int64_t, 4> dims; dims.reserve(shape.dim().size()); for (const auto& dim : shape.dim()) { dims.push_back(dim.size()); } return mlir::TF::ShapeAttr::get(builder_.getContext(), llvm::makeArrayRef(dims)); } // Converts func name in graphdef to mlir::SymbolRefAttribute. StatusOr<mlir::FlatSymbolRefAttr> ConvertFunctionCallName( const std::string& func_name); // Converts the given non-function-call AttrValue to an MLIR Attribute. StatusOr<mlir::Attribute> ConvertAttributeValue(const AttrValue& value); // Converts the given function-call AttrValue to MLIR Attributes and pushes // them to the given attributes list. For example, if there is a kFunc // AttrValue {name : foo, attrs : {k1 : bar, k2 : rfc}}, it will convert it to // a list of MLIR Attributes: [{base_name : foo}, {base_name.k1 : bar}, // {base_name.k2 : rfc}}. Status ConvertFunctionCallAttribute( const std::string& base_name, const AttrValue& value, llvm::SmallVector<mlir::NamedAttribute, 4>* attributes); // Helper to create either a tf_executor operation or a TF operation wrapped // in an island. When convert_to_legacy_call is true, converts the operation // representing a call to a library function with a name represented in // node_type_name to LegacyCallOp. mlir::Operation* createOperation( const Node& node, llvm::StringRef node_type_name, const mlir::OperationState& result, const llvm::SmallVectorImpl<mlir::Value>& control_operands, bool convert_to_legacy_call = false); // Converts one NodeDef from the input GraphDef into an Operation and // inserts it into the MLIR module using builder_. Status ConvertNode(const Node& node); // If the input graph represents a while-loop, the edges pointing from a // "NextIteration" node to a "Merge" node add cyclic dependencies and make the // topological sorting impossible. We need to remove these edges from the // input graph to infer shapes and construct a Function. For each // "NextIteration" node, there are two operations, "NextIteration.source" // and "NextIteration.sink" are added to the MLIR module. using BackEdge = BackEdgeHelper::BackEdge; // Removes backedges from the input graph. The removed edges are added back to // to OpBuilder after the remaining graph is converted to the Function. Status RemoveBackedges(const Graph& graph); // Restores backedges removed during shape inference to the final Function. Status AddBackedges(); // Restores a single backedge in the Function by adding a replicated // operation before the dst operation. Status AddBackedge(mlir::Operation* sink, mlir::Operation* dst, int dst_input); // Adds the input arguments and return operation to the function. The // arguments are added as basic block argument. Also the argument types and // the id of the nodes from the input graph needs to be specified. Status ConvertFunctionArgAndRets( mlir::FuncOp func, mlir::tf_executor::GraphOp graph_op, llvm::ArrayRef<mlir::Type> arg_types, const absl::InlinedVector<OutputTensor, 4>& arg_nodes, const absl::InlinedVector<OutputTensor, 4>& ret_nodes, const absl::InlinedVector<Node*, 4>& control_ret_nodes); // Gets the location information of the given node. It uses the // "original_node_name" in the NodeDef to get the corresponding file location // (FileLineColLoc) from the input DebugInfo and returns an CallSiteLoc. If // there are multiple "original_node_names", a FusedLoc is returned. If the // node name couldn't be found in the input DebugInfo, a NameLoc is used as // the location. mlir::Location GetLocation(const NodeDef& node); // Appends the location string for the node to the error message and returns // the combined error status. Status EmitErrorWithLocationStr(const Node& node, const Status& error_status); // Inserts a placeholder node in the graph to replace a feed output tensor, // and returns the new placeholder node and a boolean indicating if the // original input node was removed from the graph. Uses of the feed output // tensor are replaced with this placeholder node. If the feed output tensor // is of a single output node, the control dependencies are forwarded to the // the placeholder node, and the original node will be removed. // Note: This modifies the graph, and so any list of ordered nodes needs to be // reconstructed. StatusOr<std::pair<Node*, bool>> CreatePlaceholderNodeForFeed( const TensorShapeProto& shape, DataType dtype, Node* node, int index, const std::unordered_map<string, Node*>& node_name_map); // Gets the input and output nodes corresponding to the specified input and // output nodes in specs_. If there are no input or output nodes specified, // nodes will be empty. Status GetInputOutputNodes( const std::unordered_map<string, Node*>& node_name_map, std::unordered_set<const Node*>* nodes); // The input graph with backedges removed. The removed backedges are stored // in the back_edge_helper. BackEdgeHelper back_edge_helper_; // A map between node and output index, for each backedge. absl::flat_hash_map<const Node*, int> back_edge_node_output_; absl::flat_hash_map<const Node*, BackEdge> back_edge_dst_inputs_; // A map between sink and source operation of NextIteration absl::flat_hash_map<mlir::Operation*, mlir::Operation*> next_iteration_sink_source_; // All nodes and version information about the (copied) imported graph. std::unique_ptr<Graph> graph_; std::vector<Node*> ordered_nodes_; // Maps from a Node ID to a MLIR value. using NodeValueMap = absl::flat_hash_map<int, mlir::Operation*>; mlir::OpBuilder builder_; mlir::ModuleOp module_; mlir::MLIRContext* context_; std::unordered_map<std::string, std::string>* tf_name_to_mlir_name_; const FunctionLibraryDefinition& graph_flib_; const GraphImportConfig& specs_; const GraphDebugInfo& debug_info_; llvm::StringRef function_name_for_debug_info_; NodeValueMap node_values_; // TODO(jpienaar): Remove once shape inference on import is removed. // The shape_refinner_ will be nullptr if shape inference on import is // not enabled. std::unique_ptr<ShapeRefiner> shape_refiner_ = nullptr; NameUniquifier* function_name_uniquifier_; mlir::StatusScopedDiagnosticHandler error_handler_; protected: // Maps feed as TensorId to new Placeholder node name. absl::flat_hash_map<TensorId, absl::string_view> remapped_feeds_; }; // Returns true if the node with given name has a non primary output that is // used by some other node as an input. Returns false if no outputs are in use // or only the first output is in use. bool HasNonPrimaryOutputInUse(const GraphDef& graph_def, const std::string& node) { for (const auto& node_def : graph_def.node()) { for (const auto& input : node_def.input()) { if (absl::StartsWith(input, node + ":") && input != node + ":0") { return true; } } } return false; } // Updates the given LegacyFedInput node with Placeholder node if it is one of // the inputs. Returns an error if non primary output of the LegacyFedInput node // is in use and therefore can not be replaced by the Placeholder node that only // has a single output. Status UpdateLegacyFedInputNode(const GraphDef& graph_def, const GraphImportConfig::InputArrays& inputs, NodeDef* node) { const std::string& node_name = node->name(); auto it = inputs.find(node_name); // Node is not an input. if (it == inputs.end()) return Status::OK(); if (HasNonPrimaryOutputInUse(graph_def, node_name)) { return errors::InvalidArgument( "LegacyFedInput node ", node->name(), " has non primary output in use and can not be replaced with " "Placeholder node"); } DataType dtype = it->second.imported_dtype; // Uses the existing output type if it isn't specified by the user. if (dtype == DT_INVALID) { dtype = node->attr().at("output_types").list().type(0); } // Update op name, drop inputs and set attributes required by the Placeholder // op. *node->mutable_op() = "Placeholder"; node->clear_attr(); node->clear_input(); AddNodeAttr("dtype", dtype, node); AddNodeAttr("shape", it->second.shape, node); return Status::OK(); } // Preprocesses GraphDef before it can be converted to Graph by, // - Adding the default attributes to each node def if they are missing from // the GraphDef. // - Replacing LegacyFedInput nodes with Placeholder nodes if // convert_legacy_fed_inputs option is enabled. Status PreprocessGraphDef(const GraphImportConfig* specs, GraphDef* graph_def) { for (auto& node_def : *graph_def->mutable_node()) { // TODO(hinsu): Completely deprecate support for LegacyFedInput ops. One // solution could be have a tool to let users upgrade old serialized graphs. if (specs && specs->convert_legacy_fed_inputs && node_def.op() == "LegacyFedInput") { TF_RETURN_IF_ERROR( UpdateLegacyFedInputNode(*graph_def, specs->inputs, &node_def)); } const tensorflow::OpRegistrationData* op_reg_data = tensorflow::OpRegistry::Global()->LookUp(node_def.op()); if (!op_reg_data) { // This is likely a function call node, so we should continue. continue; } ::tensorflow::AddDefaultsToNodeDef(op_reg_data->op_def, &node_def); } return Status::OK(); } // Mapping from node name to feed (index and ArrayInfo). Node name must outlive // this map. using FeedsByNode = absl::flat_hash_map< absl::string_view, absl::flat_hash_map<int, const std::pair<std::string, ArrayInfo>*>>; // Creates from a `GraphImportConfig::InputArrays` a mapping from a feeds output // tensor name to index and ArrayInfo. Keys and values are backed by // `GraphImportConfig::InputArrays`. StatusOr<FeedsByNode> GetFeedsByNode( const GraphImportConfig::InputArrays& inputs) { FeedsByNode feeds_by_node; feeds_by_node.reserve(inputs.size()); for (const auto& input : inputs) { TensorId tensor = ParseTensorName(input.first); if (tensor.index() < 0) return errors::FailedPrecondition( "Feed output tensor must be a data output '", tensor.ToString(), "'"); auto& node = feeds_by_node[tensor.node()]; if (!node.insert({tensor.index(), &input}).second) return errors::FailedPrecondition( "Multiple feeds for the same output tensor '", tensor.ToString(), "'"); } return feeds_by_node; } // Creates a unique name for a node that will be replacing a feed output tensor. std::string GetUniqueNodeName( absl::string_view node_name, int index, const std::unordered_map<string, Node*>& node_name_map) { std::string new_node_name_base = absl::StrCat(node_name, "_", index); int count = 0; std::string new_node_name = new_node_name_base; while (node_name_map.find(new_node_name) != node_name_map.end()) { new_node_name = absl::StrCat(new_node_name_base, "_", count++); } return new_node_name; } Status ImporterBase::RemoveBackedges(const Graph& graph) { // TODO(fengliuai): Converting to GraphDef and back is the easiest way to // clone a graph. // TODO(fengliuai): clone the graph without going to graph_def first. GraphDef graph_def; graph.ToGraphDef(&graph_def); graph_ = absl::make_unique<Graph>(graph.flib_def()); GraphConstructorOptions opts; opts.allow_internal_ops = true; opts.add_default_attributes = false; TF_RETURN_IF_ERROR(::tensorflow::ConvertGraphDefToGraph( opts, std::move(graph_def), graph_.get())); // Remove all the backedges. So the nodes can be added to the shape refiner. TF_RETURN_IF_ERROR(back_edge_helper_.Remove(graph_.get())); VLOG(1) << "Found " << (back_edge_helper_.RemovedEdges().size()) << " backedges."; // Creates a map for quickly identifying whether a node output is a backedge. for (const auto& edge : back_edge_helper_.RemovedEdges()) { if (back_edge_node_output_.find(edge.src) != back_edge_node_output_.end() && back_edge_node_output_[edge.src] != edge.src_output) { return errors::FailedPrecondition( "More than one of the src node outputs are backedges!"); } back_edge_node_output_[edge.src] = edge.src_output; // We expect a merge to receive a single backedge (multiple NextIteration // nodes feeding into the same merge is unexpected here). DCHECK(!back_edge_dst_inputs_.contains(edge.dst)); back_edge_dst_inputs_[edge.dst] = edge; } // Obtains a RPO ordering, using node names as a tiebreak for stable sorting. GetReversePostOrder( *graph_, &ordered_nodes_, [](const Node* n1, const Node* n2) { return n1->name() < n2->name(); }); return Status::OK(); } StatusOr<std::pair<Node*, bool>> ImporterBase::CreatePlaceholderNodeForFeed( const TensorShapeProto& shape, DataType dtype, Node* node, int index, const std::unordered_map<string, Node*>& node_name_map) { DCHECK_LT(index, node->num_outputs()); const bool update_inplace = node->num_outputs() == 1 && index == 0; std::string new_node_name = update_inplace ? node->name() : GetUniqueNodeName(node->name(), index, node_name_map); Node* placeholder_node; NodeBuilder builder(new_node_name, "Placeholder"); builder.Attr("shape", shape); builder.Attr("dtype", dtype); TF_RETURN_IF_ERROR(builder.Finalize(graph_.get(), &placeholder_node)); // Update edges from original feed with Placeholder node. std::vector<const Edge*> data_edges; std::vector<const Edge*> control_edges; for (const tensorflow::Edge* edge : node->out_edges()) { if (edge->src_output() == index) { data_edges.push_back(edge); } else if (update_inplace && edge->IsControlEdge()) { control_edges.push_back(edge); } } for (const auto* edge : data_edges) { TF_RETURN_IF_ERROR(graph_->UpdateEdge(placeholder_node, 0, edge->dst(), edge->dst_input())); } // TODO(lyandy): Preserve control dependencies properly by not forwarding // control dependencies to data outputs and not removing single output nodes. // When a data output is replaced as a feed, unless there is another non feed // data output or an explicit control output used by the same node, transitive // control dependencies are not to be executed. For single output nodes, // Placeholders can be converted to a NoOp if there are no uses, and // PlaceholderWithDefault can be converted to an Identity. for (const auto* edge : control_edges) { graph_->AddControlEdge(placeholder_node, edge->dst()); graph_->RemoveControlEdge(edge); } if (update_inplace) { graph_->RemoveNode(node); } return std::pair<Node*, bool>(placeholder_node, update_inplace); } Status ImporterBase::GetInputOutputNodes( const std::unordered_map<string, Node*>& node_name_map, std::unordered_set<const Node*>* nodes) { auto add_node = [&](absl::string_view name) { auto it = node_name_map.find(std::string(name)); if (it == node_name_map.end()) { return errors::FailedPrecondition( absl::StrCat("Graph does not contain node: ", name)); } nodes->insert(it->second); return Status::OK(); }; // Remap feeds and fetches to newly created Placeholder nodes. for (const auto& input : specs_.inputs) { TensorId tensor = ParseTensorName(input.first); auto remapped_it = remapped_feeds_.find(tensor); if (remapped_it != remapped_feeds_.end()) { TF_RETURN_IF_ERROR(add_node(remapped_it->second)); } else { TF_RETURN_IF_ERROR(add_node(tensor.node())); } } for (const auto& output : specs_.outputs) { TensorId tensor = ParseTensorName(output); auto remapped_it = remapped_feeds_.find(tensor); if (remapped_it != remapped_feeds_.end()) { TF_RETURN_IF_ERROR(add_node(remapped_it->second)); } else { TF_RETURN_IF_ERROR(add_node(tensor.node())); } } for (const auto& control_output : specs_.control_outputs) TF_RETURN_IF_ERROR(add_node(control_output)); return Status::OK(); } // TODO(jpienaar): Remove this post shape inference on import flag is removed. Status ImporterBase::AddNodesToShapeRefiner( std::unordered_map<string, Node*>* node_name_map) { shape_refiner_ = absl::make_unique<ShapeRefiner>(graph_->versions(), graph_->op_registry()); // Some operations (for example "TPUExecute") don't have shape inference // function defined, so we should set this to false for adding nodes with // these types of operations. shape_refiner_->set_require_shape_inference_fns(false); shape_refiner_->set_function_library_for_shape_inference(&graph_flib_); TF_ASSIGN_OR_RETURN(auto feeds_by_node, GetFeedsByNode(specs_.inputs)); // First add all nodes to the refiner. for (Node* node : ordered_nodes_) { // We need to use a TensorFlow node to teach the shape refiner that user // specifies certain data type and shape for the inputs in the `specs_`. // This node shouldn't have any inputs, only have one output and its // output type/shape is only determined by its "named" attributes. (The // attributes should have fixed names so we can use the info from `specs_` // to set the value of them.) `Placeholder` satisfies these constraints. // // Therefore, if the input node isn't a `Placeholder`, we create one and use // it to replace the original input node, so the shape refiner can // successfully propagate the user's input type and shape to the rest of the // graph. bool node_added_to_shape_refiner = false; auto it = feeds_by_node.find(node->name()); if (it != feeds_by_node.end()) { auto op_name = node->op_def().name(); if (op_name != "Placeholder" && op_name != "LegacyFedInput" && op_name != FunctionLibraryDefinition::kArgOp) { for (const auto& output_tensor : it->second) { const int index = output_tensor.first; const ArrayInfo& array_info = output_tensor.second->second; DataType dtype = array_info.imported_dtype; // Uses the existing output type if it isn't specified by the user. if (dtype == DT_INVALID) { dtype = node->output_type(index); } TF_ASSIGN_OR_RETURN( auto placeholder_node_and_removed, CreatePlaceholderNodeForFeed(array_info.shape, dtype, node, index, *node_name_map)); Node* placeholder_node = placeholder_node_and_removed.first; if (placeholder_node_and_removed.second) { // Original node has been removed from the graph. node = placeholder_node; node_added_to_shape_refiner = true; } remapped_feeds_[{it->first, index}] = placeholder_node->name(); (*node_name_map)[placeholder_node->name()] = placeholder_node; // Add the new placeholder node to the shape refiner. Status status = shape_refiner_->AddNode(placeholder_node); if (!status.ok()) { return EmitErrorWithLocationStr(*placeholder_node, status); } } } else { auto index_it = it->second.find(0); if (index_it == it->second.end()) { return errors::FailedPrecondition( "Missing feed output tensor at index 0 for node '", node->name(), "'"); } node->AddAttr("shape", index_it->second->second.shape); DataType dtype = index_it->second->second.imported_dtype; // Uses the existing output type if it isn't specified by the user. if (dtype == DT_INVALID) { dtype = node->output_type(0); } node->AddAttr("dtype", dtype); } } if (!node_added_to_shape_refiner) { // Add the node to the shape refiner if the node hasn't been removed. Status status = shape_refiner_->AddNode(node); if (!status.ok()) { return EmitErrorWithLocationStr(*node, status); } } auto set_shape_from_list_attr = [&](const AttrValue* attr) { auto& list = attr->list(); for (auto shape : llvm::enumerate(list.shape())) { auto* node_context = shape_refiner_->GetContext(node); shape_inference::ShapeHandle handle; Status status = node_context->MakeShapeFromShapeProto(shape.value(), &handle); if (!status.ok()) { return EmitErrorWithLocationStr(*node, status); } node_context->set_output(shape.index(), handle); } return Status::OK(); }; // We currently have no other way to get shapes from ReadVariableOp's. // Some graphs seem to have _output_shapes attributes on them, so use that // if possible. // TODO(silvasean): Ideally, we would do this in a separate shape inference // pass to avoid adding complexity to the importer. But right now, we don't // have an MLIR-native shape inference pass, so we need to do this while we // still have the Graph around, i.e. here, in the importer. if (node->op_def().name() == "ReadVariableOp") { // TODO(silvasean): In some graphs, this seems to be annotated on every // node. Why and by whom? // TODO(b/140588338): We should ideally incorporate that information for // all nodes, but right now, this can result in e.g. an Identity node with // signature such as // `(tensor<?x?xf32>) -> tensor<?x9216xf32>` which fails the verifier // (which checks for exact type equality; _output_shapes results in // us shoehorning in the more-precise type on the output). if (const AttrValue* attr = node->attrs().Find("_output_shapes")) TF_RETURN_IF_ERROR(set_shape_from_list_attr(attr)); } // If it is the argument node, the shape handle is set explicitly, so it // can be propagated to the body nodes of the function. if (StringPiece(node->type_string()) == FunctionLibraryDefinition::kArgOp) { auto* node_context = shape_refiner_->GetContext(node); DCHECK(node_context != nullptr); if (const AttrValue* attr = node->attrs().Find("shape")) { shape_inference::ShapeHandle handle; Status status = node_context->MakeShapeFromShapeProto(attr->shape(), &handle); if (!status.ok()) { return EmitErrorWithLocationStr(*node, status); } node_context->set_output(0, handle); } else if (const AttrValue* attr = node->attrs().Find("_output_shapes")) { TF_RETURN_IF_ERROR(set_shape_from_list_attr(attr)); } else { node_context->set_output(0, node_context->UnknownShape()); } } } // Since we might have inserted and removed nodes from the graph, fix // source/sink edges and reconstruct the RPO ordering of nodes FixupSourceAndSinkEdges(graph_.get()); // Prune nodes in the graph that are not reachable from the output. if (specs_.prune_unused_nodes) { std::unordered_set<const Node*> prune_start; TF_RETURN_IF_ERROR(GetInputOutputNodes(*node_name_map, &prune_start)); if (!prune_start.empty()) { if (PruneForReverseReachability(graph_.get(), prune_start)) { VLOG(1) << "Pruned unused nodes in graphdef"; } else { VLOG(1) << "No unused nodes in graphdef to prune"; } } else { VLOG(1) << "No output nodes specified, skipping pruning"; } } else { VLOG(1) << "Pruning unused nodes in graphdef is disabled"; } // Re-initialize ordered_nodes_ since we might have modified the graph. GetReversePostOrder( *graph_, &ordered_nodes_, [](const Node* n1, const Node* n2) { return n1->name() < n2->name(); }); VLOG(1) << "Inferring graph shapes to fixpoint"; // The "changed" information from UpdateNode can give false positives, so we // create a dedicated method to verify the shapes are not changed before and // after the shape refine. auto same_inferred_shape = [](shape_inference::InferenceContext* c, shape_inference::ShapeHandle s0, shape_inference::ShapeHandle s1) -> bool { if (s0.SameHandle(s1) || (!c->RankKnown(s0) && !c->RankKnown(s1))) { return true; } if (c->Rank(s0) != c->Rank(s1)) { return false; } for (int i = 0; i < c->Rank(s0); ++i) { if (!c->Dim(s0, i).SameHandle(c->Dim(s1, i))) { int64 val0 = c->Value(c->Dim(s0, i)); int64 val1 = c->Value(c->Dim(s1, i)); // Negative value is treated as unknown so all negative values indicate // the same dimension. if (val0 >= 0 && val1 >= 0 && val0 != val1) return false; } } return true; }; bool changed = true; int i = 0; const int kMaxIterationCount = 2; while (changed && i != kMaxIterationCount) { changed = false; for (const Node* node : ordered_nodes_) { auto* shape_context = shape_refiner_->GetContext(node); DCHECK(shape_context != nullptr); absl::InlinedVector<shape_inference::ShapeHandle, 4> existing; existing.reserve(shape_context->num_outputs()); for (int o = 0; o < shape_context->num_outputs(); ++o) { existing.push_back(shape_context->output(o)); } bool inferred = false; shape_inference::ShapeHandle handle; Status status = shape_refiner_->UpdateNode(node, /*relax=*/false, &inferred); if (!status.ok()) { return EmitErrorWithLocationStr(*node, status); } for (int o = 0; o < shape_context->num_outputs(); ++o) { if (!same_inferred_shape(shape_context, shape_context->output(o), existing[o])) { changed = true; break; } } } ++i; } if (i >= kMaxIterationCount) { LOG(WARNING) << "Graph shapes did not converge to a fixpoint within " << kMaxIterationCount << " iterations. Graph shapes may be conservative."; } VLOG(1) << "Graph shapes were inferred with " << (i - 1) << " extra rounds of analysis to reach a fixpoint."; return Status::OK(); } StatusOr<mlir::Type> ImporterBase::InferInputType(const Node& node, int idx, mlir::Builder builder) { if (specs_.enable_shape_inference) { // TODO(jpienaar): Remove this if shape inference on import flag is removed. ExtendedInferenceContext* shape_context = shape_refiner_->GetExtendedContext(&node); DataType dtype = shape_context->input_type(idx); auto* context = shape_context->get_context(); return ConvertDataTypeAndShape(dtype, context->input(idx), context->input_handle_shapes_and_types(idx), context, builder); } DataType dtype = node.properties()->input_types[idx]; mlir::Type element_type; TF_RETURN_IF_ERROR(ConvertDataType(dtype, builder, &element_type)); return mlir::UnrankedTensorType::get(element_type); } StatusOr<mlir::Type> ImporterBase::InferOutputType(const Node& node, int idx, mlir::Builder builder) { if (specs_.enable_shape_inference) { // TODO(jpienaar): Remove this if shape inference on import flag is removed. ExtendedInferenceContext* shape_context = shape_refiner_->GetExtendedContext(&node); DataType dtype = shape_context->output_type(idx); auto* context = shape_context->get_context(); return ConvertDataTypeAndShape(dtype, context->output(idx), context->output_handle_shapes_and_types(idx), context, builder); } DataType dtype = node.properties()->output_types[idx]; if (node.IsArg()) { if (auto shape = node.attrs().Find("_output_shapes")) { if (shape->has_list() && shape->list().shape_size() == 1) { return ConvertToMlirTensorType(shape->list().shape().at(0), dtype, &builder); } } } mlir::Type element_type; TF_RETURN_IF_ERROR(ConvertDataType(dtype, builder, &element_type)); return mlir::UnrankedTensorType::get(element_type); } StatusOr<mlir::TensorType> ImporterBase::ConvertDataTypeAndShape( DataType dtype, const shape_inference::ShapeHandle& handle, const std::vector<shape_inference::ShapeAndType>* handle_subtypes, shape_inference::InferenceContext* context, mlir::Builder builder) { TF_ASSIGN_OR_RETURN(auto subtypes, ConvertSubtypes(handle_subtypes, context, builder)); mlir::Type element_type; if (dtype == DT_VARIANT) element_type = mlir::TF::VariantType::get(subtypes, context_); else if (dtype == DT_RESOURCE) element_type = mlir::TF::ResourceType::get(subtypes, context_); else TF_RETURN_IF_ERROR( ::tensorflow::ConvertDataType(dtype, builder, &element_type)); return ConvertElementTypeAndShape(element_type, handle, context, builder); } StatusOr<mlir::TensorType> ImporterBase::ConvertElementTypeAndShape( mlir::Type element_type, const shape_inference::ShapeHandle& handle, shape_inference::InferenceContext* context, mlir::Builder builder) { if (!context->RankKnown(handle)) { return mlir::UnrankedTensorType::get(element_type); } // Sentinel for an unknown dimension size. getTensorType interprets any // negative value as an unknown dimension. // TODO(jmolloy): Ideally this shouldn't be a local sentinel. const int64_t kUnknownDim = -1; absl::InlinedVector<int64_t, 4> dimensions; int32 rank = context->Rank(handle); dimensions.reserve(rank); for (int i = 0; i < rank; ++i) { auto dim_handle = context->Dim(handle, i); if (!context->ValueKnown(dim_handle)) dimensions.push_back(kUnknownDim); else dimensions.push_back(context->Value(dim_handle)); } return mlir::RankedTensorType::get( llvm::makeArrayRef(dimensions.begin(), dimensions.end()), element_type); } StatusOr<ImporterBase::ElementSubtypes> ImporterBase::ConvertSubtypes( const std::vector<shape_inference::ShapeAndType>* handle_subtypes, shape_inference::InferenceContext* context, mlir::Builder builder) { ElementSubtypes subtypes; if (!handle_subtypes) return subtypes; subtypes.reserve(handle_subtypes->size()); for (const auto& subtype : *handle_subtypes) { mlir::Type element_type; TF_RETURN_IF_ERROR( ::tensorflow::ConvertDataType(subtype.dtype, builder, &element_type)); TF_ASSIGN_OR_RETURN(mlir::TensorType type, ConvertElementTypeAndShape(element_type, subtype.shape, context, builder)); subtypes.push_back(type); } return subtypes; } Status ImporterBase::ConvertFunctionCallAttribute( const std::string& base_name, const AttrValue& value, llvm::SmallVector<mlir::NamedAttribute, 4>* attributes) { TF_ASSIGN_OR_RETURN(auto func_attr, ConvertFunctionCallName(value.func().name())); attributes->push_back(builder_.getNamedAttr(base_name, func_attr)); for (const auto& it : value.func().attr()) { auto name = absl::StrCat(base_name, ".", it.first); TF_ASSIGN_OR_RETURN(auto value, ConvertAttributeValue(it.second)); attributes->push_back(builder_.getNamedAttr(name, value)); } return Status::OK(); } StatusOr<mlir::FlatSymbolRefAttr> ImporterBase::ConvertFunctionCallName( const std::string& func_name) { TF_RETURN_IF_ERROR(ConvertLibFunction(func_name)); auto mlir_func_name = (*tf_name_to_mlir_name_)[func_name]; auto func = module_.lookupSymbol<mlir::FuncOp>(mlir_func_name); return builder_.getSymbolRefAttr(func); } StatusOr<mlir::Attribute> ImporterBase::ConvertAttributeValue( const AttrValue& value) { switch (value.value_case()) { case AttrValue::kI: return builder_.getI64IntegerAttr(value.i()); case AttrValue::kS: return builder_.getStringAttr(value.s()); case AttrValue::kF: return builder_.getFloatAttr(builder_.getF32Type(), value.f()); case AttrValue::kB: return builder_.getBoolAttr(value.b()); case AttrValue::kType: { mlir::Type type; TF_RETURN_IF_ERROR(ConvertDataType(value.type(), builder_, &type)); return mlir::TypeAttr::get(type); } case AttrValue::kShape: return ConvertTensorShapeProto(value.shape()); case AttrValue::kTensor: return ConvertTensorProto(value.tensor()); case AttrValue::kList: { absl::InlinedVector<mlir::Attribute, 8> attrs; for (const auto& item : value.list().i()) attrs.push_back(builder_.getI64IntegerAttr(item)); for (const auto& item : value.list().s()) attrs.push_back(builder_.getStringAttr(item)); for (const auto& item : value.list().f()) attrs.push_back(builder_.getFloatAttr(builder_.getF32Type(), item)); for (const auto& item : value.list().b()) attrs.push_back(builder_.getBoolAttr(item)); for (const auto& item : value.list().type()) { attrs.push_back(builder_.getStringAttr( mangling_util::MangleDataType(static_cast<DataType>(item)))); } for (const auto& item : value.list().shape()) { TF_ASSIGN_OR_RETURN(auto attr, ConvertTensorShapeProto(item)); attrs.push_back(attr); } for (const auto& item : value.list().tensor()) { TF_ASSIGN_OR_RETURN(auto attr, ConvertTensorProto(item)); attrs.push_back(attr); } for (const auto& item : value.list().func()) { TF_ASSIGN_OR_RETURN(auto attr, ConvertFunctionCallName(item.name())); if (item.attr_size() != 0) return errors::Unimplemented( "func attributes with non-zero attr.size()"); attrs.push_back(attr); } return builder_.getArrayAttr( llvm::makeArrayRef(attrs.begin(), attrs.end())); } case AttrValue::kFunc: return errors::Unknown("kFunc type should be handled separately!"); case AttrValue::VALUE_NOT_SET: return builder_.getUnitAttr(); // kPlaceholder is not implemented. default: return errors::Unimplemented( absl::StrCat("Attribute ", value.DebugString())); } } void ImporterBase::GetArgsAndRetsFromFunctionBody( const FunctionBody& fbody, absl::InlinedVector<OutputTensor, 4>* arg_nodes, absl::InlinedVector<OutputTensor, 4>* ret_nodes, absl::InlinedVector<Node*, 4>* control_ret_nodes, absl::InlinedVector<std::pair<int64_t, int64_t>, 4>* resource_arg_unique_ids) { arg_nodes->reserve(fbody.arg_nodes.size()); ret_nodes->reserve(fbody.ret_nodes.size()); for (auto arg : fbody.arg_nodes) { arg_nodes->emplace_back(arg, 0); } for (auto ret : fbody.ret_nodes) { ret_nodes->emplace_back(ret, 0); } for (const auto& entry : fbody.fdef.resource_arg_unique_id()) { resource_arg_unique_ids->push_back(entry); } *control_ret_nodes = fbody.control_ret_nodes; } Status ImporterBase::ConvertLibFunction(llvm::StringRef func_name) { // If the library function has been converted already, nothing needs to be // done. if (tf_name_to_mlir_name_->find(std::string(func_name)) != tf_name_to_mlir_name_->end()) return Status::OK(); std::string mlir_func_name( function_name_uniquifier_->GetUniqueName(func_name)); (*tf_name_to_mlir_name_)[std::string(func_name)] = mlir_func_name; const auto& func_lib = graph_flib_; const auto* func_def = func_lib.Find(std::string(func_name)); if (func_def == nullptr) { return errors::FailedPrecondition( absl::StrCat("Failed to find function '", StringRefToView(func_name), "'. The imported TensorFlow GraphDef is ill-formed.")); } // Converts the function definition to a graph. std::unique_ptr<FunctionBody> fbody; TF_RETURN_IF_ERROR( FunctionDefToBodyHelper(*func_def, AttrSlice(), &func_lib, &fbody)); // Converts the argument and return types to MLIR types. absl::InlinedVector<mlir::NamedAttribute, 8> attributes; attributes.reserve(func_def->attr_size()); for (const auto& name_and_value : func_def->attr()) { // This is a function definition attribute, so it shouldn't contain // kFunc attribute and it is treated as normal one. TF_ASSIGN_OR_RETURN(auto attr, ConvertAttributeValue(name_and_value.second)); std::string attr_name = mangling_util::MangleAttributeName(name_and_value.first); attributes.push_back(builder_.getNamedAttr(attr_name, attr)); } // Checks opdef stateful attribute and import that as Function Attribute if (func_def->signature().is_stateful()) { auto stateful_str = mlir::TF::TensorFlowDialect::GetStatefulAttrName(); attributes.push_back( builder_.getNamedAttr(stateful_str, builder_.getUnitAttr())); } // Checks for an associated custom gradient function. Adds it to the attribute // list of this function. auto grad_func_name = func_lib.FindGradient(std::string(func_name)); if (!grad_func_name.empty()) { TF_RETURN_IF_ERROR(ConvertLibFunction(grad_func_name)); auto mlir_grad_func_name = (*tf_name_to_mlir_name_)[grad_func_name]; auto grad_func = module_.lookupSymbol<mlir::FuncOp>(mlir_grad_func_name); auto gradient_attr = builder_.getSymbolRefAttr(grad_func); auto grad_string = mlir::TF::TensorFlowDialect::GetGradientAttrName(); attributes.push_back(builder_.getNamedAttr(grad_string, gradient_attr)); } // Converts the graph to an MLIR function and adds it to the module. // We populate the NodeSpec so that all the _Arg ops get their shape // added correctly. GraphImportConfig specs; specs.enable_shape_inference = specs_.enable_shape_inference; for (const auto& name_and_value : func_def->attr()) { if (name_and_value.first == "_input_shapes") { auto& list = name_and_value.second.list(); auto& signature = func_def->signature(); if (list.shape_size() != signature.input_arg_size()) { return errors::FailedPrecondition( "Number of input arguments must be equal to the length of " "_input_shapes attribute in function '", StringRefToView(func_name), "'."); } for (int i = 0; i < list.shape_size(); i++) { auto& input_arg = signature.input_arg(i); auto& array_info = specs.inputs[input_arg.name()]; array_info.imported_dtype = input_arg.type(); array_info.shape = list.shape(i); } } } ImporterBase child_importer(graph_flib_, debug_info_, specs, module_, tf_name_to_mlir_name_, function_name_uniquifier_, func_name); TF_RETURN_IF_ERROR(child_importer.PrepareConvert(*fbody->graph)); TF_ASSIGN_OR_RETURN(auto func_type, child_importer.InferLibFunctionType(*fbody)); absl::InlinedVector<OutputTensor, 4> arg_nodes; absl::InlinedVector<OutputTensor, 4> ret_nodes; absl::InlinedVector<Node*, 4> control_ret_nodes; absl::InlinedVector<std::pair<int64_t, int64_t>, 4> resource_arg_unique_ids; GetArgsAndRetsFromFunctionBody(*fbody, &arg_nodes, &ret_nodes, &control_ret_nodes, &resource_arg_unique_ids); TF_RETURN_IF_ERROR(child_importer.Convert( mlir_func_name, func_type, arg_nodes, ret_nodes, control_ret_nodes, llvm::makeArrayRef(attributes.begin(), attributes.end()), resource_arg_unique_ids)); return Status::OK(); } Status ImporterBase::PruneUnreachableNodes( std::unordered_map<string, Node*>* node_name_map) { std::unordered_set<const Node*> prune_start; TF_RETURN_IF_ERROR(GetInputOutputNodes(*node_name_map, &prune_start)); if (!prune_start.empty()) { if (PruneForReverseReachability(graph_.get(), prune_start)) { VLOG(1) << "Pruned unused nodes in graphdef"; } else { VLOG(1) << "No unused nodes in graphdef to prune"; } } else { VLOG(1) << "No output nodes specified, skipping pruning"; } return Status::OK(); } Status ImporterBase::ConvertFeedsToPlaceholders( std::unordered_map<string, Node*>* node_name_map) { // Feeds (edges) are converted into single-output placeholder nodes to // simplify the conversion process. TF_ASSIGN_OR_RETURN(auto feeds_by_node, GetFeedsByNode(specs_.inputs)); for (const auto& it : feeds_by_node) { TensorId tensor = ParseTensorName(it.first); auto jt = node_name_map->find(std::string(tensor.node())); if (jt == node_name_map->end()) { return errors::FailedPrecondition( absl::StrCat("Graph does not contain node: ", tensor.node())); } Node* node = jt->second; auto op_name = node->op_def().name(); if (op_name != "Placeholder" && op_name != "LegacyFedInput" && op_name != FunctionLibraryDefinition::kArgOp) { for (const auto& output_tensor : it.second) { const int index = output_tensor.first; const ArrayInfo& array_info = output_tensor.second->second; DataType dtype = array_info.imported_dtype; // Uses the existing output type if it isn't specified by the user. if (dtype == DT_INVALID) { dtype = node->output_type(index); } TF_ASSIGN_OR_RETURN( auto placeholder_node_and_removed, CreatePlaceholderNodeForFeed(array_info.shape, dtype, node, index, *node_name_map)); Node* placeholder_node = placeholder_node_and_removed.first; if (placeholder_node->in_edges().empty()) { graph_->AddControlEdge(graph_->source_node(), placeholder_node, true /* skip test for duplicates */); } if (placeholder_node->out_edges().empty()) { graph_->AddControlEdge(placeholder_node, graph_->sink_node(), true /* skip test for duplicates */); } remapped_feeds_[{it.first, index}] = placeholder_node->name(); (*node_name_map)[placeholder_node->name()] = placeholder_node; } } } return Status::OK(); } Status ImporterBase::PrepareConvert(const Graph& graph) { TF_RETURN_IF_ERROR(RemoveBackedges(graph)); auto node_name_map = graph_->BuildNodeNameIndex(); if (specs_.enable_shape_inference) { // TODO(jpienaar): Remove once infer shapes on import flag is removed. TF_RETURN_IF_ERROR(AddNodesToShapeRefiner(&node_name_map)); } else { TF_RETURN_IF_ERROR(ConvertFeedsToPlaceholders(&node_name_map)); } // Prune nodes in the graph that are not reachable from the output. if (specs_.prune_unused_nodes) { TF_RETURN_IF_ERROR(PruneUnreachableNodes(&node_name_map)); } if (!specs_.enable_shape_inference) { // Re-initialize ordered_nodes_ since we might have modified the graph. GetReversePostOrder( *graph_, &ordered_nodes_, [](const Node* n1, const Node* n2) { return n1->name() < n2->name(); }); } return Status::OK(); } Status ImporterBase::Convert( llvm::StringRef func_name, mlir::FunctionType func_type, const absl::InlinedVector<OutputTensor, 4>& arg_nodes, const absl::InlinedVector<OutputTensor, 4>& ret_nodes, const absl::InlinedVector<Node*, 4>& control_ret_nodes, llvm::ArrayRef<mlir::NamedAttribute> attrs, const absl::InlinedVector<std::pair<int64_t, int64_t>, 4>& resource_arg_unique_ids) { // TODO(b/122040776): Uses debug info for FunctionDef. auto function = mlir::FuncOp::create(mlir::UnknownLoc::get(context_), func_name, func_type, attrs); module_.push_back(function); // Seeds the builder with an initial block. function.addEntryBlock(); builder_ = mlir::OpBuilder(function.getBody()); // Create the graph operation in which we will convert the individual nodes. auto graph = builder_.create<mlir::tf_executor::GraphOp>( function.getLoc(), func_type.getResults()); builder_.createBlock(&graph.body()); for (const Node* node : ordered_nodes_) { TF_RETURN_IF_ERROR(ConvertNode(*node)); } // Adds the backedges back to the function by creating the source and sink // pairs. TF_RETURN_IF_ERROR(AddBackedges()); TF_RETURN_IF_ERROR(ConvertFunctionArgAndRets(function, graph, func_type.getInputs(), arg_nodes, ret_nodes, control_ret_nodes)); for (const auto& entry : resource_arg_unique_ids) { function.setArgAttr(entry.first, "tf.resource_arg_unique_id", builder_.getI64IntegerAttr(entry.second)); } // TODO(jpienaar): Update post removing shape_refinier_. if (!specs_.enable_shape_inference) { // Refine graph's type given more precise fetch. auto fetch_op = graph.GetFetch(); bool all_equal = true; for (auto it : llvm::zip(fetch_op.getOperandTypes(), graph.getResultTypes())) { if (std::get<0>(it) != std::get<1>(it)) { all_equal = false; break; } } if (all_equal) return Status::OK(); llvm::SmallVector<mlir::Type, 4> return_types; return_types.reserve(fetch_op.getNumOperands()); for (mlir::Type t : fetch_op.getOperandTypes()) return_types.push_back(t); builder_.setInsertionPointToStart(&function.getBody().front()); auto new_graph = builder_.create<mlir::tf_executor::GraphOp>( function.getLoc(), return_types, mlir::ValueRange{}, graph.getAttrs()); new_graph.body().takeBody(graph.body()); graph.replaceAllUsesWith(new_graph); graph.erase(); function.setType(mlir::FunctionType::get( func_type.getInputs(), return_types, function.getContext())); } return Status::OK(); } Status ImporterBase::ConvertFunctionArgAndRets( mlir::FuncOp func, mlir::tf_executor::GraphOp graph_op, llvm::ArrayRef<mlir::Type> arg_types, const absl::InlinedVector<OutputTensor, 4>& arg_nodes, const absl::InlinedVector<OutputTensor, 4>& ret_nodes, const absl::InlinedVector<Node*, 4>& control_ret_nodes) { auto* bb = &func.front(); llvm::SmallDenseMap<std::pair<Node*, int>, mlir::Value, 4> arg_nodes_to_values; for (int i = 0, e = arg_types.size(); i < e; ++i) { auto& arg_node = arg_nodes[i]; // The lookup can't fail here: otherwise some nodes in the function haven't // be converted to mlir operations and don't have a mapping. mlir::Operation* island = node_values_.find(arg_node.node->id())->second; auto bb_arg = bb->getArgument(i); mlir::Value arg_def = bb_arg; if (island->getNumResults() != 2) return errors::InvalidArgument( "Only feed output tensors of single output nodes are supported"); // Collect mapping of OutputTensor to associated block arg. arg_nodes_to_values.try_emplace({arg_node.node, arg_node.index}, arg_def); island->getResult(0).replaceAllUsesWith(arg_def); // Erase control outputs from feed. auto control_uses = island->getResult(1).getUses(); for (auto& control_use : llvm::make_early_inc_range(control_uses)) control_use.getOwner()->eraseOperand(control_use.getOperandNumber()); if (!arg_node.node->requested_device().empty()) func.setArgAttr( i, "tf.device", builder_.getStringAttr(arg_node.node->requested_device())); island->dropAllReferences(); island->erase(); } llvm::SmallVector<mlir::Value, 8> inst_to_return; for (const auto& ret : ret_nodes) { auto* inst = node_values_[ret.node->id()]; auto op = absl::string_view(ret.node->type_string()); if (op == FunctionLibraryDefinition::kRetOp || op == FunctionLibraryDefinition::kDeviceRetOp) { // Lookup the instruction inside the island auto island_op = llvm::cast<mlir::tf_executor::IslandOp>(inst); mlir::Operation* inner_op = &island_op.GetBody().front(); // Remove kRetOp or kDeviceRetOp operation and return its operand. // kRetOp and kDeviceRetOp should have just one operand unless they have // control dependencies. if (inner_op->getNumOperands() != 1) return errors::Unimplemented("Return node with multiple inputs."); inst_to_return.push_back(inner_op->getOperand(0)); inst->dropAllReferences(); inst->erase(); } else { // Lookup and use block arg if fetch is a feed. auto it = arg_nodes_to_values.find({ret.node, ret.index}); if (it != arg_nodes_to_values.end()) inst_to_return.push_back(it->second); else inst_to_return.push_back(inst->getResult(ret.index)); } } for (Node* control_ret : control_ret_nodes) { auto* inst = node_values_[control_ret->id()]; inst_to_return.push_back(*std::prev(inst->result_end())); } // Terminate the function by adding a Fetch operation to terminate the graph // and a return operation to return the Graph results. builder_.setInsertionPointToEnd(&graph_op.body().front()); builder_.create<mlir::tf_executor::FetchOp>(graph_op.getLoc(), inst_to_return); builder_.setInsertionPointToEnd(bb); builder_.create<mlir::ReturnOp>(mlir::UnknownLoc::get(context_), graph_op.getResults()); return Status::OK(); } mlir::Location ImporterBase::GetLocation(const NodeDef& node_def) { // TODO(b/142400497): What is the semantic contract for locations? const auto& debug_info = debug_info_.traces(); // Create a location for node `name` in function `function_name`. auto create_location = [&](llvm::StringRef name, llvm::StringRef function_name) -> mlir::Location { // Use the catenation of function and node names as the lookup key into the // debug info. This matches the way that the key is formed on the python // side. // // We also use this as the name for the NameLoc for ops in function, since // otherwise our names could collide across functions. // For ops in the main graph, we omit the "@function_name" (which, would be // just "@" since function_name would be empty) because some code seems to // depend on the name being this way for correctness. std::string debug_info_key = (name + "@" + function_name).str(); std::string name_for_name_loc = function_name.empty() ? name.str() : (name + "@" + function_name).str(); auto name_loc_id = mlir::Identifier::get(name_for_name_loc, context_); const auto location_it = debug_info.find(debug_info_key); if (location_it == debug_info.end()) { return mlir::NameLoc::get(name_loc_id, context_); } // Convert the stack trace to a chain of mlir::CallSiteLocs. const auto& trace = location_it->second; llvm::SmallVector<mlir::Location, 4> locations; locations.reserve(trace.file_line_cols_size()); for (const auto& location : trace.file_line_cols()) { const auto& file = debug_info_.files(location.file_index()); auto file_name = mlir::Identifier::get(file, context_); auto file_line_loc = mlir::FileLineColLoc::get(file_name, location.line(), location.col(), context_); locations.push_back(file_line_loc); } // If there are no locations in the stack trace, fall back to just a // NameLoc with no child. if (locations.empty()) return mlir::NameLoc::get(name_loc_id, context_); // Use the front FileLineColLoc to generate a NameLoc. mlir::Location node_name_loc = mlir::NameLoc::get(name_loc_id, locations.front()); // If there are more locations then generate a stack trace, otherwise just // return the name loc. auto callsite_locs = llvm::makeArrayRef(locations).drop_front(); return callsite_locs.empty() ? node_name_loc : mlir::CallSiteLoc::get(node_name_loc, callsite_locs); }; // For NextIteration nodes, location is used to pair source and sink nodes. // Hence, we use node name as location to keep it unique. // TODO(prakalps): In future the plan is to use tokens to pair source/sink // nodes. Then NextIteration nodes would not need to be handled separately. if (node_def.op() == "NextIteration") return create_location(node_def.name(), function_name_for_debug_info_); auto original_nodes = node_def.experimental_debug_info().original_node_names(); auto original_funcs = node_def.experimental_debug_info().original_func_names(); if (original_nodes.empty()) { return create_location(node_def.name(), function_name_for_debug_info_); } else { // If the original nodes are defined, then we use them to get a list of // call sites, and then fuse them to a single fused location, with the name // of the node_def. llvm::SmallVector<mlir::Location, 4> node_locations; node_locations.reserve(original_nodes.size() + 1); // store the names in the experimental_debug_info for (int i = 0, e = original_nodes.size(); i != e; ++i) { auto node_name = original_nodes[i]; auto func_name = (i < original_funcs.size()) ? original_funcs[i] : ""; node_locations.push_back(create_location(node_name, func_name)); } // store the name of the node_def node_locations.push_back( create_location(node_def.name(), function_name_for_debug_info_)); return mlir::FusedLoc::get(node_locations, context_); } } Status ImporterBase::EmitErrorWithLocationStr(const Node& node, const Status& error_status) { const mlir::Location location = GetLocation(node.def()); mlir::emitError(location); return error_handler_.Combine(error_status); } mlir::Operation* ImporterBase::createOperation( const Node& node, llvm::StringRef node_type_name, const mlir::OperationState& result, const llvm::SmallVectorImpl<mlir::Value>& control_operands, bool convert_to_legacy_call) { // For the tf.executor specific operations (not wrapped in an island), we // have an extra returned value for the control result, and we concatenate // control and non-control operands. mlir::SmallVector<mlir::Type, 4> types(result.types); types.push_back(mlir::tf_executor::ControlType::get(builder_.getContext())); mlir::SmallVector<mlir::Value, 4> operands(result.operands); operands.append(control_operands.begin(), control_operands.end()); auto loc = result.location; // Dispatch based on the name and create the appropriate operation. if (node.IsSwitch()) { // Switch and _SwitchN both are in switch class, differentiate based on // op name. if (node.op_def().name() == "_SwitchN") { return builder_.create<mlir::tf_executor::SwitchNOp>(loc, types, operands, result.attributes); } return builder_.create<mlir::tf_executor::SwitchOp>(loc, types, operands, result.attributes); } if (node.IsMerge()) { return builder_.create<mlir::tf_executor::MergeOp>(loc, types, operands, result.attributes); } if (node.IsNextIteration()) { // NextIteration is a bit special, we create a pair of operations that are // linked together through a token returned by the source. // We make use of a separate builder to insert the source at the top of // the block. mlir::OpBuilder builder_at_begin(builder_.getBlock(), builder_.getBlock()->begin()); auto source_op = builder_at_begin.create<mlir::tf_executor::NextIterationSourceOp>( loc, operands[0].getType(), result.attributes); return builder_.create<mlir::tf_executor::NextIterationSinkOp>( loc, source_op.token(), operands, result.attributes); } if (node.IsLoopCond()) { return builder_.create<mlir::tf_executor::LoopCondOp>(loc, types, operands, result.attributes); } if (node.IsEnter()) { return builder_.create<mlir::tf_executor::EnterOp>(loc, types, operands, result.attributes); } if (node.IsExit()) { return builder_.create<mlir::tf_executor::ExitOp>(loc, types, operands, result.attributes); } if (node.IsControlTrigger()) { return builder_.create<mlir::tf_executor::ControlTriggerOp>( loc, operands, result.attributes); } // Regular TensorFlow operation are wrapped in a tf_executor.island. auto island = builder_.create<mlir::tf_executor::IslandOp>( result.location, types, control_operands, mlir::ArrayRef<mlir::NamedAttribute>{}); island.body().push_back(new mlir::Block); mlir::OpBuilder island_builder = mlir::OpBuilder::atBlockEnd(&island.GetBody()); // Create the operation inside the island now. mlir::Operation* inner_op; if (convert_to_legacy_call) { bool disable_call_shape_inference = false; for (const auto& name_and_value : node.attrs()) { const auto& attr_name = name_and_value.first; const AttrValue& attr_value = name_and_value.second; if (IsDisableCallShapeInferenceAttribute(attr_value, attr_name)) { disable_call_shape_inference = attr_value.b(); } } mlir::BoolAttr attribute = builder_.getBoolAttr(disable_call_shape_inference); inner_op = island_builder.create<mlir::TF::LegacyCallOp>( result.location, result.types, result.operands, island_builder.getSymbolRefAttr(node_type_name), attribute); } else { inner_op = island_builder.createOperation(result); } // Sets operand_segment_sizes or result_segment_sizes attribute to the op. const auto set_segment_sizes_attr = [&](const NameRangeMap& arg_ranges, const protobuf::RepeatedPtrField<OpDef::ArgDef>& args, llvm::StringRef attr_name) { std::vector<mlir::Attribute> values; values.reserve(args.size()); for (const auto& arg : args) { auto range = arg_ranges.at(arg.name()); values.push_back( island_builder.getI32IntegerAttr(range.second - range.first)); } auto attr_type = mlir::VectorType::get(args.size(), builder_.getIntegerType(32)); auto attr_value = mlir::DenseElementsAttr::get(attr_type, values); inner_op->setAttr(attr_name, attr_value); }; if (inner_op->hasTrait<mlir::OpTrait::AttrSizedOperandSegments>() || inner_op->hasTrait<mlir::OpTrait::AttrSizedResultSegments>()) { // The op has multiple variadic operands or results. // Calculate operand and result segment sizes using the OpDef. NameRangeMap input_ranges, output_ranges; // This will fail only if the OpDef is syntactically invalid. // TODO(jpienaar): Convert this CHECK into a properly propagated error. TF_CHECK_OK( NameRangesForNode(node, node.op_def(), &input_ranges, &output_ranges)); if (inner_op->hasTrait<mlir::OpTrait::AttrSizedOperandSegments>()) { // Add derived "operand_segment_sizes" attr to the created operation. // TODO(b/146937733): Don't use <void> here. set_segment_sizes_attr(input_ranges, node.op_def().input_arg(), mlir::OpTrait::AttrSizedOperandSegments< void>::getOperandSegmentSizeAttr()); } if (inner_op->hasTrait<mlir::OpTrait::AttrSizedResultSegments>()) { // Add derived "result_segment_sizes" attr to the created operation. // TODO(b/146937733): Don't use <void> here. set_segment_sizes_attr(output_ranges, node.op_def().output_arg(), mlir::OpTrait::AttrSizedResultSegments< void>::getResultSegmentSizeAttr()); } } // Add the terminator for the island island_builder.create<mlir::tf_executor::YieldOp>(result.location, inner_op->getResults()); return island.getOperation(); } Status ImporterBase::ConvertNode(const Node& node) { if (!node.IsOp()) { // Don't import the pseudo-nodes _SOURCE or _SINK. These are added by // Graph and don't exist in GraphDef. return Status::OK(); } // If it is a custom OP, its definition should be found in the library. We // create the MLIR function and insert it to the module if it doesn't exist. std::string node_type_name = node.type_string(); const auto* func_def = graph_flib_.Find(node_type_name); bool convert_to_legacy_call = false; if (func_def) { TF_RETURN_IF_ERROR(ConvertLibFunction(node_type_name)); node_type_name = (*tf_name_to_mlir_name_)[node_type_name]; convert_to_legacy_call = true; } auto get_full_op_name = [&](const std::string& op_name) { const char* kTfPrefix = "tf."; return kTfPrefix + op_name; }; std::string op_name = get_full_op_name(node_type_name); if (back_edge_node_output_.contains(&node)) { op_name = op_name + ".sink"; } const auto& node_def = node.def(); mlir::OperationState result(GetLocation(node_def), op_name); for (int i = 0; i < node.num_outputs(); ++i) { // The backedge has been removed, so we shouldn't count the corresponding // output from the src node when converting to an operation. if (back_edge_node_output_.contains(&node) && back_edge_node_output_[&node] == i) { continue; } TF_ASSIGN_OR_RETURN(auto type, InferOutputType(node, i, builder_)); result.types.push_back(type); } // Surprisingly input edges can be nondeterministically ordered. This // particularly seems to be the case for the control edges between _SOURCE // and _SINK that the Graph constructor inserts. Copy the input edges and // sort the edges, but only the control edges, not data edges! // TODO(jmolloy): We should probably just ignore _SOURCE and _SINK nodes. // They'll break roundtripping anyway unless we strip them when converting // back to graphdef. absl::InlinedVector<const Edge*, 8> in_edges(node.in_edges().size()); absl::c_copy(node.in_edges(), in_edges.begin()); absl::c_stable_sort(in_edges, [](const Edge* e1, const Edge* e2) { if (e1->IsControlEdge() && !e2->IsControlEdge()) return false; if (!e1->IsControlEdge() && e2->IsControlEdge()) return true; return e1->dst_input() < e2->dst_input(); }); result.operands.reserve(in_edges.size()); // Collect the control operands separately, they will be held by the island. mlir::SmallVector<mlir::Value, 8> control_operands; for (const auto* input_edge : in_edges) { const Node& input_node = *input_edge->src(); if (input_node.IsSource()) { if (in_edges.size() != 1) { return errors::FailedPrecondition( "The node has other inputs besides the _Source node"); } // We don't import the _SOURCE node. continue; } if (input_node.IsArg() && input_edge->IsControlEdge()) { // Currently we have not reached consensus as to what TF function // semantics are (b/133509504). Here we assume that all arguments to a // function should be available before we start execution of any internal // node. This makes the control dependencies between function arguments // and internal nodes redundant, and so we do not import them. The TF // inliner however assumes no such dependency between function args and // internal nodes exists, unless explicitly stated. Since we drop control // dependencies here, it leads to loss of information. If the function is // inlined later, the inliner would not know of these explicit control // dependencies present in the original graph. continue; } if (node_values_.find(input_node.id()) == node_values_.end()) return errors::FailedPrecondition( "Graph not traversed in reverse post order; use seen before def!"); mlir::Operation* inst = node_values_[input_node.id()]; if (input_edge->IsControlEdge()) control_operands.push_back(inst->getResult(inst->getNumResults() - 1)); else result.operands.push_back(inst->getResult(input_edge->src_output())); } using FuncPairType = std::pair<const std::string*, const AttrValue*>; std::vector<FuncPairType> funcs; result.attributes.reserve(node.attrs().size() + 2); auto abstract_op = result.name.getAbstractOperation(); auto derived_op = abstract_op ? abstract_op->getInterface<mlir::DerivedAttributeOpInterface>() : nullptr; for (const auto& name_and_value : node.attrs()) { const auto& attr_name = name_and_value.first; // Skip adding derived attributes to the generated op. if (derived_op && derived_op->isDerivedAttribute(attr_name)) continue; const AttrValue& attr_value = name_and_value.second; // Remove _output_shapes attribute that will be added by the exporter. if (IsOutputShapesAttribute(attr_value, attr_name)) continue; // We represent the _diable_call_shape_inference attribute and remove // the _output_shapes attribute for LegacyCall. If a call has other // attributes, we can't convert it to LegacyCall. if (convert_to_legacy_call && !IsDisableCallShapeInferenceAttribute(attr_value, attr_name)) { convert_to_legacy_call = false; } if (attr_value.value_case() == AttrValue::kFunc) { // Attribute iteration order is not defined for protocol buffer Map. // Process function attributes separately in the lexicographical order to // have deterministic order of functions in the constructed IR. funcs.emplace_back(&attr_name, &attr_value); } else { TF_ASSIGN_OR_RETURN(auto attr, ConvertAttributeValue(attr_value)); result.attributes.push_back(builder_.getNamedAttr(attr_name, attr)); } } auto comparator = [](const FuncPairType& a, const FuncPairType& b) { return *a.first < *b.first; }; std::sort(funcs.begin(), funcs.end(), comparator); for (const auto& func : funcs) { TF_RETURN_IF_ERROR(ConvertFunctionCallAttribute(*func.first, *func.second, &result.attributes)); } result.attributes.push_back(builder_.getNamedAttr( "device", builder_.getStringAttr(std::string(node_def.device())))); // Map If and StatelessIf op in TensorFlow to the common If op in MLIR and add // the differentiating attribute. if (node.IsIfNode()) { result.name = mlir::OperationName(get_full_op_name("If"), context_); mlir::BoolAttr val = builder_.getBoolAttr(node_type_name == "StatelessIf"); result.attributes.push_back(builder_.getNamedAttr("is_stateless", val)); } // Map While and StatelessWhile op in TensorFlow to the common While op in // MLIR and add the differentiating attribute. if (node.IsWhileNode()) { result.name = mlir::OperationName(get_full_op_name("While"), context_); mlir::BoolAttr val = builder_.getBoolAttr(node_type_name == "StatelessWhile"); result.attributes.push_back(builder_.getNamedAttr("is_stateless", val)); } // Register the mapping between the TF node and the newly created operation. node_values_[node.id()] = createOperation( node, node_type_name, result, control_operands, convert_to_legacy_call); return Status::OK(); } // Add the backedges to the CFG. Given a backedge, we replace the original // source and destination operations by two new operations. Most of the // fields of the replacements are copied from the original operations. // However, // - for the src operation, one output is inserted to the front of the output // list. The type of the output is set to the type of the non-control result // of the dst operation, and // - for the dst operation, one operand is inserted to the front of the // operand list. This operand is using the first result of the src // operation. // TODO(fengliuai): Preserve the order of the results and operands if // necessary. Status ImporterBase::AddBackedges() { for (auto it : back_edge_dst_inputs_) { BackEdge& edge = it.second; if (!edge.src->IsNextIteration() || !edge.dst->IsMerge()) { return errors::FailedPrecondition( "Invalid backedge; should be from NextIteration to Merge!"); } auto* sink = node_values_[edge.src->id()]; auto* dst = node_values_[edge.dst->id()]; TF_RETURN_IF_ERROR(AddBackedge(sink, dst, edge.dst_input)); } return Status::OK(); } Status ImporterBase::AddBackedge(mlir::Operation* sink, mlir::Operation* dst, int dst_input) { // Get the NextIteration.Source operation from the token operand of the sink. mlir::Operation* source = sink->getOperand(0).getDefiningOp(); // Adds the "source" to the operands of the dst by creating a new dst // operation. mlir::OperationState state(dst->getLoc(), dst->getName()); auto num_operands = dst->getNumOperands(); state.operands.reserve(num_operands + 1); for (int input = 0, e = num_operands + 1; input != e; ++input) { if (input < dst_input) { state.operands.push_back(dst->getOperand(input)); } else if (input == dst_input) { state.operands.push_back(source->getResult(0)); } else { state.operands.push_back(dst->getOperand(input - 1)); } } state.attributes.assign(dst->getAttrs().begin(), dst->getAttrs().end()); state.types.assign(dst->getResultTypes().begin(), dst->getResultTypes().end()); builder_.setInsertionPoint(dst); auto* new_dst = builder_.createOperation(state); // Replaces the output uses of the old operation by the corresponding // result of the new operation, and deletes the old operation. for (unsigned i = 0, e = dst->getNumResults(); i != e; ++i) { auto new_output = new_dst->getResult(i); dst->getResult(i).replaceAllUsesWith(new_output); } dst->dropAllReferences(); dst->erase(); return Status::OK(); } StatusOr<mlir::FunctionType> ImporterBase::InferLibFunctionType( const FunctionBody& fbody) { mlir::Builder builder(context_); // The FunctionBody contains a graph with a single-output _Arg node for each // function argument and a single-input _Retval node for each function return // value. // // We already populated the ShapeRefiner with all the information about the // shapes of these graph edges, so we just query it to build the corresponding // MLIR function type signature. llvm::SmallVector<mlir::Type, 4> arg_types; if (specs_.inputs.empty()) { arg_types.reserve(fbody.arg_types.size()); for (auto arg : fbody.arg_nodes) { // Find node in the graph using the node id instead of using `arg` // directly because the graph has been cloned. auto* node = graph_->FindNodeId(arg->id()); TF_ASSIGN_OR_RETURN(auto type, InferOutputType(*node, /*idx=*/0, builder)); arg_types.push_back(type); } } else { arg_types.reserve(fbody.arg_types.size()); for (const auto& it : llvm::enumerate(specs_.inputs)) { mlir::Type element_type; const auto& node_info = it.value().second; DataType dtype = node_info.imported_dtype; // Uses the existing output type of the arg node if the data type of the // the node isn't specified through the import configuration. if (dtype == DT_INVALID) { auto arg = fbody.arg_nodes[it.index()]; auto* node = graph_->FindNodeId(arg->id()); dtype = node->output_type(0); if (dtype == DT_INVALID) { return errors::InvalidArgument("Input ", it.index(), "has invalid data type"); } } TF_RETURN_IF_ERROR( ::tensorflow::ConvertDataType(dtype, builder, &element_type)); if (node_info.shape.unknown_rank()) { arg_types.push_back(mlir::UnrankedTensorType::get(element_type)); } else { llvm::SmallVector<int64_t, 4> shape; TF_RETURN_IF_ERROR(ConvertToMlirShape(node_info.shape, &shape)); arg_types.push_back(mlir::RankedTensorType::get(shape, element_type)); } } } llvm::SmallVector<mlir::Type, 4> ret_types; ret_types.reserve(fbody.ret_types.size()); for (auto ret : fbody.ret_nodes) { // Find node in the graph using the node id instead of using `ret` directly // because the graph has been cloned. auto* node = graph_->FindNodeId(ret->id()); TF_ASSIGN_OR_RETURN(auto type, InferInputType(*node, /*idx=*/0, builder)); ret_types.push_back(type); } return builder.getFunctionType(arg_types, ret_types); } // Stateful helper class to import a TensorFlow model expressed in GraphDef into // an MLIR Module. // // The nodes defined in the graph are converted to a function called // 'func_name'. All library function definitions are converted to MLIR functions // in the module. class GraphDefImporter : public ImporterBase { public: // Main entry point: converts the given graph to an MLIR Module. static StatusOr<mlir::OwningModuleRef> Convert( mlir::MLIRContext* context, const Graph& graph, const GraphDebugInfo& debug_info, const FunctionLibraryDefinition& flib_def, const GraphImportConfig& specs, llvm::StringRef func_name); private: explicit GraphDefImporter( const FunctionLibraryDefinition& flib, const GraphDebugInfo& debug_info, const GraphImportConfig& specs, mlir::ModuleOp module, std::unordered_map<std::string, std::string>* tf_name_to_mlir_name, NameUniquifier* function_name_uniquifier) : ImporterBase(flib, debug_info, specs, module, tf_name_to_mlir_name, function_name_uniquifier) {} // Returns the function signature of the main function of converted MLIR // module, the input nodes and output nodes. The type and shape information // for the function arguments are read from `specs`, but the type and shape // information for the function returns are inferred by the shape refiner in // ImporterBase. StatusOr<mlir::FunctionType> InferMainFunctionType( const GraphImportConfig& specs, mlir::MLIRContext* context, absl::InlinedVector<OutputTensor, 4>* arg_nodes, absl::InlinedVector<OutputTensor, 4>* ret_nodes); // Returns the function signature of the main function, alongside input and // output nodes, for function graphs. Arguments and return values are // determined by node op type. Type and shape information of the function are // inferred by the shape refiner in ImporterBase. // `resource_arg_unique_ids` will be filled with the unique IDs of resource // variables, as a list of {index, ID} pairs. StatusOr<mlir::FunctionType> GetArgsRetsAndTypesFromFunctionGraph( mlir::MLIRContext* context, absl::InlinedVector<OutputTensor, 4>* arg_nodes, absl::InlinedVector<OutputTensor, 4>* ret_nodes, absl::InlinedVector<std::pair<int64_t, int64_t>, 4>* resource_arg_unique_ids); // Finds the graph's target nodes/function's control ret nodes based on // supplied node names in `control_outputs`. If `control_outputs` are not // unique or a control ret node is missing, an error will be returned. Status GetControlRetsFromGraph( llvm::ArrayRef<std::string> control_outputs, absl::InlinedVector<Node*, 4>* control_ret_nodes); }; StatusOr<mlir::OwningModuleRef> GraphDefImporter::Convert( mlir::MLIRContext* context, const Graph& graph, const GraphDebugInfo& debug_info, const FunctionLibraryDefinition& flib_def, const GraphImportConfig& specs, llvm::StringRef func_name) { mlir::OwningModuleRef module = mlir::ModuleOp::create(mlir::UnknownLoc::get(context)); std::unordered_map<std::string, std::string> tf_name_to_mlir_name; NameUniquifier function_name_uniquifier(flib_def); GraphDefImporter importer(flib_def, debug_info, specs, module.get(), &tf_name_to_mlir_name, &function_name_uniquifier); TF_RETURN_IF_ERROR(importer.PrepareConvert(graph)); mlir::FunctionType func_type; absl::InlinedVector<OutputTensor, 4> arg_nodes; absl::InlinedVector<OutputTensor, 4> ret_nodes; absl::InlinedVector<Node*, 4> control_ret_nodes; absl::InlinedVector<std::pair<int64_t, int64_t>, 4> resource_arg_unique_ids; llvm::SmallVector<mlir::NamedAttribute, 1> attrs; if (specs.graph_as_function) { if (specs.prune_unused_nodes || !specs.inputs.empty() || !specs.outputs.empty()) return errors::InvalidArgument( "Pruning of graph is currently unsupported when the main graph is " "converted to a function."); TF_ASSIGN_OR_RETURN( func_type, importer.GetArgsRetsAndTypesFromFunctionGraph( context, &arg_nodes, &ret_nodes, &resource_arg_unique_ids)); TF_RETURN_IF_ERROR(importer.GetControlRetsFromGraph(specs.control_outputs, &control_ret_nodes)); if (!arg_nodes.empty() || !ret_nodes.empty() || !control_ret_nodes.empty()) { mlir::Builder b(context); std::string s; llvm::raw_string_ostream ss(s); auto node_name = [&](const OutputTensor& tensor) { ss << tensor.node->name(); }; llvm::interleave(arg_nodes, ss, node_name, ","); auto inputs = b.getNamedAttr("inputs", b.getStringAttr(ss.str())); s.clear(); llvm::interleave(ret_nodes, ss, node_name, ","); auto outputs = b.getNamedAttr("outputs", b.getStringAttr(ss.str())); s.clear(); llvm::interleave(specs.control_outputs, ss, ","); auto control_outputs = b.getNamedAttr("control_outputs", b.getStringAttr(ss.str())); attrs.push_back(b.getNamedAttr( "tf.entry_function", b.getDictionaryAttr({inputs, outputs, control_outputs}))); } } else { // Collects the argument and return nodes by looking up the node names // specified by the user. TF_ASSIGN_OR_RETURN(func_type, importer.InferMainFunctionType( specs, context, &arg_nodes, &ret_nodes)); TF_RETURN_IF_ERROR(importer.GetControlRetsFromGraph(specs.control_outputs, &control_ret_nodes)); // TODO(prakalps): Refactor to keep tf.entry_function attribute encoding and // decoding in a centralized place. // Record the input and output mapping. if (!specs.inputs.empty() || !specs.outputs.empty() || !specs.control_outputs.empty()) { mlir::Builder b(context); std::string s; llvm::raw_string_ostream ss(s); llvm::interleave( specs.inputs, ss, [&](const std::pair<std::string, ArrayInfo>& v) { ss << v.first; }, ","); auto inputs = b.getNamedAttr("inputs", b.getStringAttr(ss.str())); s.clear(); llvm::interleave(specs.outputs, ss, ","); auto outputs = b.getNamedAttr("outputs", b.getStringAttr(ss.str())); s.clear(); llvm::interleave(specs.control_outputs, ss, ","); auto control_outputs = b.getNamedAttr("control_outputs", b.getStringAttr(ss.str())); attrs.push_back(b.getNamedAttr( "tf.entry_function", b.getDictionaryAttr({inputs, outputs, control_outputs}))); } } // Record version info. PopulateTfVersions(module.get(), graph.versions()); TF_RETURN_IF_ERROR(importer.ImporterBase::Convert( func_name, func_type, arg_nodes, ret_nodes, control_ret_nodes, attrs, resource_arg_unique_ids)); return module; } StatusOr<mlir::FunctionType> GraphDefImporter::InferMainFunctionType( const GraphImportConfig& specs, mlir::MLIRContext* context, absl::InlinedVector<OutputTensor, 4>* arg_nodes, absl::InlinedVector<OutputTensor, 4>* ret_nodes) { // Find all the input nodes and output nodes. // Feeds have been remapped to single output nodes (Placeholder), so an exact // name match is sufficient. absl::flat_hash_map<absl::string_view, int> inputs; for (auto input_and_idx : llvm::enumerate(specs.inputs)) { TensorId tensor = ParseTensorName(input_and_idx.value().first); auto remapped_it = remapped_feeds_.find(tensor); if (remapped_it != remapped_feeds_.end()) { inputs.insert({remapped_it->second, input_and_idx.index()}); } else { inputs.insert({tensor.node(), input_and_idx.index()}); } } absl::flat_hash_set<absl::string_view> output_node_names; std::vector<TensorId> outputs; output_node_names.reserve(specs.outputs.size()); for (const auto& output : specs.outputs) { TensorId tensor = ParseTensorName(output); auto remapped_it = remapped_feeds_.find(tensor); if (remapped_it != remapped_feeds_.end()) { output_node_names.insert(remapped_it->second); outputs.push_back({remapped_it->second, 0}); } else { output_node_names.insert(tensor.node()); outputs.push_back(tensor); } } if (!inputs.empty() || !outputs.empty()) { arg_nodes->resize(inputs.size()); ret_nodes->resize(outputs.size()); for (Node* n : GetOrderedNodes()) { // Handle inputs/arguments. auto input_it = inputs.find(n->name()); if (input_it != inputs.end()) { (*arg_nodes)[input_it->second] = {n, 0}; } // Handle outputs/returns. if (output_node_names.contains(n->name())) { for (int i = 0, e = outputs.size(); i != e; ++i) { TensorId tensor = outputs[i]; if (n->name() != tensor.node()) continue; (*ret_nodes)[i] = {n, tensor.index()}; } } } } // Starts to construct the function type. mlir::Builder builder(context); llvm::SmallVector<mlir::Type, 4> arg_types; arg_types.reserve(specs.inputs.size()); int i = 0; for (const auto& it : specs.inputs) { Node* arg_node = arg_nodes->at(i).node; if (arg_node == nullptr) { return errors::InvalidArgument("Input ", it.first, " was not found in graph"); } mlir::Type element_type; const auto& node_info = it.second; DataType imported_dtype = node_info.imported_dtype; // Uses the existing output type of the arg node if the data type of the // the node isn't specified through the import configuration. if (imported_dtype == DT_INVALID) { imported_dtype = arg_node->output_type(0); if (imported_dtype == DT_INVALID) { return errors::InvalidArgument("Input ", i, "has invalid data type"); } } TF_RETURN_IF_ERROR( ::tensorflow::ConvertDataType(imported_dtype, builder, &element_type)); if (node_info.shape.unknown_rank()) { arg_types.push_back(mlir::UnrankedTensorType::get(element_type)); } else { llvm::SmallVector<int64_t, 4> shape; TF_RETURN_IF_ERROR(ConvertToMlirShape(node_info.shape, &shape)); arg_types.push_back(mlir::RankedTensorType::get(shape, element_type)); } i++; } llvm::SmallVector<mlir::Type, 4> ret_types; ret_types.reserve(specs.outputs.size()); for (int i = 0, e = specs.outputs.size(); i != e; ++i) { if (ret_nodes->at(i).node == nullptr) { return errors::InvalidArgument("Output ", specs.outputs[i], " was not found in graph"); } } for (const auto& ret : *ret_nodes) { if (ret.node->num_outputs() <= ret.index) { return errors::InvalidArgument("Invalid output index ", ret.index, " specified for node: ", ret.node->name()); } TF_ASSIGN_OR_RETURN(auto type, InferOutputType(*ret.node, ret.index, builder)); ret_types.push_back(type); } return builder.getFunctionType(arg_types, ret_types); } StatusOr<mlir::FunctionType> GraphDefImporter::GetArgsRetsAndTypesFromFunctionGraph( mlir::MLIRContext* context, absl::InlinedVector<OutputTensor, 4>* arg_nodes, absl::InlinedVector<OutputTensor, 4>* ret_nodes, absl::InlinedVector<std::pair<int64_t, int64_t>, 4>* resource_arg_unique_ids) { auto add_node = [](Node* node, absl::InlinedVector<OutputTensor, 4>* nodes) { auto* attr = node->attrs().Find("index"); if (!attr) return errors::InvalidArgument(node->type_string(), " node '", node->name(), "' is missing attribute 'index'"); auto index = attr->i(); if (nodes->size() < index + 1) nodes->resize(index + 1); if ((*nodes)[index].node != nullptr) return errors::InvalidArgument(node->type_string(), " node '", node->name(), "' has attribute 'index' ", index, " that conflicts with node '", (*nodes)[index].node->name(), "'"); (*nodes)[index] = {node, 0}; return Status::OK(); }; // Collect arg and ret nodes from graph. for (auto* node : GetOrderedNodes()) if (node->IsArg()) TF_RETURN_IF_ERROR(add_node(node, arg_nodes)); else if (node->IsRetval()) TF_RETURN_IF_ERROR(add_node(node, ret_nodes)); // Collect arg and ret types and create function type. mlir::Builder builder(context); llvm::SmallVector<mlir::Type, 4> arg_types; arg_types.reserve(arg_nodes->size()); for (auto arg_node_and_idx : llvm::enumerate(*arg_nodes)) { auto& arg_node = arg_node_and_idx.value(); if (arg_node.node == nullptr) return errors::InvalidArgument("Graph missing _Arg at index ", arg_node_and_idx.index()); TF_ASSIGN_OR_RETURN(auto type, InferOutputType(*arg_node.node, /*idx=*/0, builder)); arg_types.push_back(type); tensorflow::int64 resource_arg_unique_id; if (TryGetNodeAttr(arg_node.node->attrs(), "_resource_arg_unique_id", &resource_arg_unique_id)) { resource_arg_unique_ids->emplace_back(arg_node_and_idx.index(), resource_arg_unique_id); } } llvm::SmallVector<mlir::Type, 4> ret_types; ret_types.reserve(ret_nodes->size()); for (auto ret_node_and_idx : llvm::enumerate(*ret_nodes)) { auto& ret_node = ret_node_and_idx.value(); if (ret_node.node == nullptr) return errors::InvalidArgument("Graph missing _Retval at index ", ret_node_and_idx.index()); TF_ASSIGN_OR_RETURN(auto type, InferInputType(*ret_node.node, /*idx=*/0, builder)); ret_types.push_back(type); } return builder.getFunctionType(arg_types, ret_types); } Status GraphDefImporter::GetControlRetsFromGraph( llvm::ArrayRef<std::string> control_outputs, absl::InlinedVector<Node*, 4>* control_ret_nodes) { if (control_outputs.empty()) return Status::OK(); llvm::SmallDenseMap<llvm::StringRef, int32_t> controls_to_idx; for (auto control_and_idx : llvm::enumerate(control_outputs)) controls_to_idx.insert({control_and_idx.value(), control_and_idx.index()}); if (controls_to_idx.size() != control_outputs.size()) return errors::InvalidArgument("Control outputs must be unique"); control_ret_nodes->resize(controls_to_idx.size()); for (auto* node : GetOrderedNodes()) { auto it = controls_to_idx.find(node->name()); if (it != controls_to_idx.end()) (*control_ret_nodes)[it->second] = node; } for (auto node_and_name : llvm::zip(*control_ret_nodes, control_outputs)) if (std::get<0>(node_and_name) == nullptr) return errors::InvalidArgument( "Control output '", std::get<1>(node_and_name), "' is missing"); return Status::OK(); } // Stateful helper class to import a TensorFlow model expressed in SavedModel // into an MLIR Module. class SavedModelObjectGraphImporter : public ImporterBase { public: // Main entry point: converts all functions in the given meta graph to an MLIR // Module. static StatusOr<mlir::OwningModuleRef> Convert( SavedModelV2Bundle* saved_model, mlir::MLIRContext* context, absl::Span<std::string> exported_names, bool add_default_attributes); private: explicit SavedModelObjectGraphImporter( const FunctionLibraryDefinition& flib, const GraphDebugInfo& debug_info, const GraphImportConfig& specs, mlir::ModuleOp module, std::unordered_map<std::string, std::string>* tf_name_to_mlir_name, NameUniquifier* function_name_uniquifier) : ImporterBase(flib, debug_info, specs, module, tf_name_to_mlir_name, function_name_uniquifier) {} }; // Determines the names used to reference objects in the SavedObjectGraph. class ObjectNames { public: explicit ObjectNames(const SavedObjectGraph& object_graph, absl::Span<std::string> exported_names); // Gets the names that external users of the SavedModel can use to refer to // this node. llvm::ArrayRef<llvm::StringRef> GetExportedNames(int node_id) const; // Gets the name in the module symbol table for this node. // This name is only used for internal IR references. llvm::StringRef GetSymbolTableName(int node_id) const; private: // In the absence of any other information, use this name as the symbol table // name for this node. std::string GetDefaultSymbolTableName(int node_id) const; // Determines if a name is exported. bool IsExported(const std::string& name); // Main object graph traversal function. void RecursivelyVisitObjectGraph(int node_id); // Gets a stable StringRef from a std::string. llvm::StringRef SaveString(const std::string& s) const; // The object graph we are traversing. const SavedObjectGraph& object_graph_; // The set of names to export. Empty means "export all". std::unordered_set<std::string> names_to_export_; // When we recursively follow the object graph tree structure from the root, // we track its path in the object graph by pushing and popping from here // during traversal. llvm::SmallVector<std::string, 8> path_segments_; // The set of node_id's that are on the current DFS stack. // For cyclic object graphs, this prevents infinite recursion. std::unordered_set<int> on_stack_nodes_; // Key: node_id. // Value: all object names that node_id appears as. // Each object name corresponds to a unique path from the root of the object // graph. // The common intuitive case is when there is only one name for a given // object, which corresponds to the object graph being a tree. // // But, there cases where the object graph is a general graph. For // example, this happens commonly in Keras models, where `foo.bar` is // also reachable via the name `keras_api.foo.bar`. // Cycles are possible too. absl::flat_hash_map<int, std::vector<std::string>> object_names_; // Key: node_id // Value: all names that this object is exported as absl::flat_hash_map<int, llvm::SmallVector<llvm::StringRef, 1>> exported_names_; // Key: node_id // Value: pretty symbol table name to use for internal references to this // object. absl::flat_hash_map<int, llvm::StringRef> pretty_symbol_table_name_; // Stable strings we can take StringRef's into. Used only by the SaveString // method. mutable std::unordered_set<std::string> saved_strings_; }; ObjectNames::ObjectNames(const SavedObjectGraph& object_graph, absl::Span<std::string> exported_names) : object_graph_(object_graph), names_to_export_(exported_names.begin(), exported_names.end()) { // Visit all reachable nodes from the root of the object graph. // This builds up object_names_ to contain all names like `foo.bar` that a // particular node in the graph can be reached from. RecursivelyVisitObjectGraph(/*node_id=*/0); // Populate the exported_names_ map. // TODO(silvasean): Diagnose typos in exported names? for (auto& kv : object_names_) { // Make object names map independent of our particular choice of object // graph traversal. std::sort(kv.second.begin(), kv.second.end(), [](absl::string_view a, absl::string_view b) { // The sort order here influences the "pretty name" we assign // below. We want the most debuggable name to be first. // // Debuggability heuristics: // 1. Names that end in digits are likely to be internal aliases // to the "real" names. // 2. Longer names are more likely to be internal aliases. // // Example set of object names created by Keras for the weight // matrix of a fully connected layer on a trivial FC mnist // model: // - `model.layer-1.kernel` (this is the "best" name) // - `model.keras_api.layers.1.kernel` // - `model.variables.0` // - `model.keras_api.layers.1.keras_api.trainable_variables.0` // - ... 10 more long aliases ending in digits ... return std::make_tuple(isdigit(a.back()), a.size(), a) < std::make_tuple(isdigit(b.back()), b.size(), b); }); for (const std::string& name : kv.second) { if (IsExported(name)) { exported_names_[kv.first].push_back(SaveString(name)); } } } // Create "pretty" symbol table names for nodes where that is applicable. // We could make all symbol table names use the default, which is basically // just the node id. But for debugging purposes, it's nicer if we can mix in // a recognizable object name if we have the information to do so. for (auto& kv : object_names_) { int node_id = kv.first; std::string internal_name = absl::StrCat(GetDefaultSymbolTableName(node_id), "__"); // If the object has an exported name, we prefer that since it is probably // the most recognizable. Otherwise, we grab some non-exported name of the // object. if (exported_names_.find(node_id) != exported_names_.end()) { internal_name += exported_names_[node_id][0].str(); } else { internal_name += object_names_[node_id][0]; } pretty_symbol_table_name_[node_id] = SaveString(internal_name); } } llvm::ArrayRef<llvm::StringRef> ObjectNames::GetExportedNames( int node_id) const { auto it = exported_names_.find(node_id); if (it != exported_names_.end()) { return it->second; } return {}; } llvm::StringRef ObjectNames::GetSymbolTableName(int node_id) const { auto it = pretty_symbol_table_name_.find(node_id); if (it != pretty_symbol_table_name_.end()) { return it->second; } return SaveString(GetDefaultSymbolTableName(node_id)); } std::string ObjectNames::GetDefaultSymbolTableName(int node_id) const { return absl::StrCat("__sm_node", node_id); } bool ObjectNames::IsExported(const std::string& name) { if (names_to_export_.empty()) { return true; } return names_to_export_.find(name) != names_to_export_.end(); } void ObjectNames::RecursivelyVisitObjectGraph(int node_id) { const SavedObject& object = object_graph_.nodes(node_id); switch (object.kind_case()) { case SavedObject::kConstant: case SavedObject::kFunction: case SavedObject::kVariable: { object_names_[node_id].push_back(absl::StrJoin(path_segments_, ".")); break; } default: break; } for (const auto& child_ref : object.children()) { bool on_stack = !on_stack_nodes_.insert(child_ref.node_id()).second; if (on_stack) { // This is a backedge. Don't traverse it. continue; } path_segments_.push_back(child_ref.local_name()); RecursivelyVisitObjectGraph(child_ref.node_id()); path_segments_.pop_back(); on_stack_nodes_.erase(child_ref.node_id()); } } llvm::StringRef ObjectNames::SaveString(const std::string& s) const { return llvm::StringRef(*saved_strings_.insert(s).first); } // Extracts a TensorProto for a Const op from a GraphDef, given an op_name. // Returns nullptr on not found or other mismatch. // This returns a pointer to the actual node within the graph_def so as to // avoid expensive copies. const TensorProto* ExtractConstTensorFromGraph(const GraphDef& graph_def, const std::string& op_name) { const NodeDef* match_node = nullptr; for (const auto& node : graph_def.node()) { if (node.name() == op_name) { match_node = &node; } } if (!match_node) { return nullptr; } auto value_it = match_node->attr().find("value"); if (value_it == match_node->attr().end()) { return nullptr; } if (!value_it->second.has_tensor()) { return nullptr; } return &value_it->second.tensor(); } const TrackableObjectGraph::TrackableObject::SerializedTensor* FindSerializedTensorInTrackable( const TrackableObjectGraph::TrackableObject& trackable_object, StringPiece name) { for (const auto& maybe_serialized_tensor : trackable_object.attributes()) { if (maybe_serialized_tensor.name() == name) { return &maybe_serialized_tensor; } } return nullptr; } Status DiagnoseMultipleConcreteFunctions(const SavedObjectGraph& object_graph, const ObjectNames& object_names) { for (int node_id = 0; node_id < object_graph.nodes_size(); node_id++) { const SavedObject& object = object_graph.nodes(node_id); if (object_names.GetExportedNames(node_id).empty()) { continue; } if (object.kind_case() == SavedObject::kFunction) { // We only allow a single input signature to each SavedFunction. // This assumption means we have a 1:1 correspondence between // tf.function <=> SavedFunction <=> SavedConcreteFunction <=> FunctionDef // This makes defining the ABI easier (or even well-defined at all). // TODO(silvasean): How to detect a function that doesn't have an // explicitly user-provided input signature, but happens to have been // traced exactly once? if (object.function().concrete_functions_size() != 1) { llvm::SmallVector<std::string, 4> names; for (llvm::StringRef s : object_names.GetExportedNames(node_id)) { names.push_back("'" + s.str() + "'"); } return errors::InvalidArgument( "Exported function with exported name(s) ", absl::StrJoin(names, ", "), " with multiple concrete functions. Add " "@tf.function(input_signature=[...]) on this function, or use a " "narrower list of exported names that excludes this function."); } } } return Status::OK(); } // Recursively traverses a StructuredValue, linearizing all the leaves. // // This currently only handles the subset of StructuredValue that is needed for // signatures. // // Given a StructuredValue with structure [{"x": leaf0}], the "index path" // needed to reach leaf0 is `[0, "x"]`, as it would be if you were operating on // a Python object (`obj[0]["x"] is leaf0`). Each leaf corresponds to a // linearized function argument or return on a FunctionDef, and hence to an // mlir::FuncOp argument / return. // // This must match the linearization that happens in `tf.nest.flatten`. // In particular, dict values should be linearized in sorted key order. // // The linearized index paths can be returned back to a structured // representation (e.g. to emit C structs matching a signature) with a simple // algorithm that recurses on each run of index paths with identical first // elements. class StructuredValueLinearizer { public: StructuredValueLinearizer(const StructuredValue& value, mlir::MLIRContext* context); // Returns the list of index paths to each leaf of the StructuredValue, // in a linearized order matching `tf.nest.flatten`. // // If an error occurred during the linearization process, an error message // with `error_context` prepended will be included in the returned status. StatusOr<llvm::ArrayRef<mlir::ArrayAttr>> GetLeafIndexPaths( llvm::StringRef error_context) const; private: // Main function that recursively traverses the StructuredValue. void RecursivelyFindLeaves(const StructuredValue& value); mlir::Builder builder_; // The current index path. We push/pop this during recursive traversal of the // StructuredValue. llvm::SmallVector<mlir::Attribute, 4> current_index_path_; // The list of leaf index paths we have discovered so far. llvm::SmallVector<mlir::ArrayAttr, 4> leaf_index_paths_; // If non-empty, an error message to report. std::string error_message_; }; StructuredValueLinearizer::StructuredValueLinearizer( const StructuredValue& value, mlir::MLIRContext* context) : builder_(context) { RecursivelyFindLeaves(value); } StatusOr<llvm::ArrayRef<mlir::ArrayAttr>> StructuredValueLinearizer::GetLeafIndexPaths( llvm::StringRef error_context) const { if (error_message_.empty()) { return llvm::makeArrayRef(leaf_index_paths_); } return errors::InvalidArgument( error_context.str(), error_message_, "This likely means that you have @tf.function " "on an exported function instead of " "@tf.function(input_signature=[...]). Consider annotating an " "input_signature or narrowing your set of " "exported names to not include this function."); } void StructuredValueLinearizer::RecursivelyFindLeaves( const StructuredValue& value) { switch (value.kind_case()) { case StructuredValue::kDictValue: { // Dict values must be linearized in sorted order of keys. const DictValue& dict = value.dict_value(); using FieldTy = protobuf::MapPair<std::string, StructuredValue>; llvm::SmallVector<const FieldTy*, 4> fields; for (auto& field : dict.fields()) { fields.push_back(&field); } llvm::sort(fields, [](const FieldTy* a, const FieldTy* b) { return a->first < b->first; }); for (auto& field : fields) { current_index_path_.push_back(builder_.getStringAttr(field->first)); RecursivelyFindLeaves(field->second); current_index_path_.pop_back(); } return; } case StructuredValue::kTupleValue: { const TupleValue& tuple = value.tuple_value(); for (int i = 0, e = tuple.values_size(); i < e; i++) { current_index_path_.push_back(builder_.getI64IntegerAttr(i)); RecursivelyFindLeaves(tuple.values(i)); current_index_path_.pop_back(); } return; } // We don't differentiate between tuples and lists. case StructuredValue::kListValue: { const ListValue& list = value.list_value(); for (int i = 0, e = list.values_size(); i < e; i++) { current_index_path_.push_back(builder_.getI64IntegerAttr(i)); RecursivelyFindLeaves(list.values(i)); current_index_path_.pop_back(); } return; } case StructuredValue::kTensorSpecValue: { // Base case: record the current path stack as the index path needed to // get to this leaf. leaf_index_paths_.push_back(builder_.getArrayAttr(current_index_path_)); return; } case StructuredValue::kNoneValue: { // Base case: do nothing. // This arises, for example, as the top-level object of an output // signature when there are no return values. return; } default: { llvm::raw_string_ostream os(error_message_); // TODO(silvasean): Use an enumerant name string instead of a number. os << "Unhandled structured value kind " << value.kind_case() << " at index path: <value>"; for (auto path_element : current_index_path_) { os << "."; if (auto integer = path_element.dyn_cast<mlir::IntegerAttr>()) { os << integer.getValue(); } else { auto str = path_element.cast<mlir::StringAttr>(); os << str.getValue(); } } os << "\n"; } } } // For exported functions with bound inputs, rewrite the function // signature to match the requirements of tf_saved_model bound input args. // // The raw imported functions have `tensor<*x!tf.resource>` as the type for // mutable bound inputs and `tensor<...>` as the type for immutable // bound inputs. Here we canonicalize both of them into // `tensor<!tf.resource<tensor<...>>>`. void AdjustBoundInputArgTypes(mlir::ModuleOp module) { mlir::SymbolTable symbol_table(module); for (auto func : module.getOps<mlir::FuncOp>()) { if (!mlir::tf_saved_model::IsExported(func)) continue; mlir::OpBuilder builder(func.getBody()); llvm::SmallVector<mlir::Type, 4> new_input_types; for (int i = 0, e = func.getNumArguments(); i < e; i++) { auto arg = func.front().getArgument(i); auto global_tensor = mlir::tf_saved_model::LookupBoundInput(func, i, symbol_table); if (global_tensor) { auto old_type = arg.getType(); auto new_type = mlir::tf_saved_model::GetBoundInputArgTypeFor(global_tensor); arg.setType(new_type); if (global_tensor.is_mutable()) { auto arg_with_original_type = builder.create<mlir::TF::CastOp>( global_tensor.getLoc(), old_type, arg, /*Truncate=*/builder.getBoolAttr(false)); arg.replaceAllUsesWith(arg_with_original_type); // The RAUW replaces the arg with itself, so we need to set it back. arg_with_original_type.setOperand(arg); } else { auto arg_with_original_type = builder.create<mlir::TF::ReadVariableOp>(global_tensor.getLoc(), old_type, arg); arg.replaceAllUsesWith(arg_with_original_type); // The RAUW replaces the arg with itself, so we need to set it back. arg_with_original_type.setOperand(arg); } } new_input_types.push_back(arg.getType()); } func.setType(mlir::FunctionType::get( new_input_types, func.getType().getResults(), module.getContext())); } } // Reorder the ops in the module to make testing easier and less dependent // on implementation details such as the order of functions in the // FunctionDefLibrary. // // The order this ensures is: // 1. GlobalTensorOp's // 2. FuncOps's. // // Within each of 1. and 2., ops are sorted by exported name (if // available, and only the first exported name is considered), followed by // non-exported ops. void SortSavedModelModule(mlir::ModuleOp module) { struct NamedGlobalTensor { llvm::StringRef name; mlir::tf_saved_model::GlobalTensorOp global_tensor; }; llvm::SmallVector<NamedGlobalTensor, 8> named_global_tensors; for (auto global_tensor : module.getOps<mlir::tf_saved_model::GlobalTensorOp>()) { auto exported_names = mlir::tf_saved_model::GetExportedNames(global_tensor); // We use stable_sort, so duplicate empty names are fine here. named_global_tensors.push_back( {exported_names.empty() ? "" : exported_names.front(), global_tensor}); } llvm::stable_sort(named_global_tensors, [](const NamedGlobalTensor& a, const NamedGlobalTensor& b) { return std::make_tuple(a.name.empty(), a.name) < std::make_tuple(b.name.empty(), b.name); }); struct NamedFunc { llvm::StringRef name; mlir::FuncOp func; }; llvm::SmallVector<NamedFunc, 8> named_funcs; for (auto func : module.getOps<mlir::FuncOp>()) { auto exported_names = mlir::tf_saved_model::GetExportedNames(func); named_funcs.push_back( {exported_names.empty() ? "" : exported_names.front(), func}); } llvm::stable_sort(named_funcs, [](const NamedFunc& a, const NamedFunc& b) { return std::make_tuple(a.name.empty(), a.name) < std::make_tuple(b.name.empty(), b.name); }); // Move onto the front of the module in reverse of the final desired order. for (auto named_func : llvm::reverse(named_funcs)) { named_func.func.getOperation()->moveBefore(&module.getBody()->front()); } for (auto named_global_tensor : llvm::reverse(named_global_tensors)) { named_global_tensor.global_tensor.getOperation()->moveBefore( &module.getBody()->front()); } } Status CreateSavedModelIR( const ObjectNames& object_names, mlir::ModuleOp module, const SavedObjectGraph& object_graph, const std::unordered_map<std::string, std::string>& tf_name_to_mlir_name, SavedModelV2Bundle* saved_model) { mlir::OpBuilder builder(module.getBodyRegion()); mlir::SymbolTable symbol_table(module); // Create a side data-structure, indexed by the object_graph node_id to // a TrackableObject that is restorable. absl::flat_hash_map<int, const TrackableObjectGraph::TrackableObject*> restored_objects; TF_RETURN_IF_ERROR(saved_model->VisitObjectsToRestore( [&](int saved_node_id, const TrackableObjectGraph::TrackableObject& trackable_object) { restored_objects.insert( std::make_pair(saved_node_id, &trackable_object)); return Status::OK(); })); for (int node_id = 0; node_id < object_graph.nodes_size(); node_id++) { const SavedObject& object = object_graph.nodes(node_id); // For correctness, we cannot import functions that don't have exported // names, since they don't necessarily have a well-defined ABI (diagnosed // earlier). // // For variables/constants, pruning them is purely an optimization, // and more complicated since it requires use-def analysis of which // functions use which variables/constants, so we don't do anything // special for them here as part of our initial IR construction. if (object.kind_case() == SavedObject::kFunction) { if (object_names.GetExportedNames(node_id).empty()) { continue; } std::string error_context = "While importing SavedModel function '" + object_names.GetExportedNames(node_id)[0].str() + "': "; const SavedFunction& function = object.function(); auto orig_func = symbol_table.lookup<mlir::FuncOp>( tf_name_to_mlir_name.find(function.concrete_functions(0))->second); mlir::FuncOp func = orig_func; // If there are potentially references to this func from within the // module, create a wrapper around it and decorate the wrapper with the // tf_saved_model attributes instead. if (!mlir::SymbolTable::symbolKnownUseEmpty(orig_func.getName(), &module.getBodyRegion())) { func = orig_func.cloneWithoutRegions(); module.insert(module.getBody()->begin(), func); func.addEntryBlock(); func.setName("__sm_exported_" + orig_func.getName().str()); llvm::SmallVector<mlir::Value, 4> args_as_values; for (auto block_argument : func.getArguments()) { args_as_values.push_back(block_argument); } mlir::OpBuilder body_builder(&func.getBody()); auto call = body_builder.create<mlir::TF::StatefulPartitionedCallOp>( func.getLoc(), orig_func.getType().getResults(), args_as_values, builder.getSymbolRefAttr(orig_func.getName()), /*config=*/builder.getStringAttr(""), /*config_proto=*/builder.getStringAttr(""), /*executor_type=*/builder.getStringAttr("")); body_builder.create<mlir::ReturnOp>(func.getLoc(), call.getResults()); } func.setAttr( "tf_saved_model.exported_names", builder.getStrArrayAttr(object_names.GetExportedNames(node_id))); const SavedConcreteFunction& concrete_function = object_graph.concrete_functions().at(function.concrete_functions(0)); // We do not handle the other element of this tuple, which corresponds to // Python kwonlyargs, since currently TensorFlow prohibits this in // combination with input_signature: // https://github.com/tensorflow/tensorflow/blob/8cb8627abb5ef83a6fba34f8fd0e4ee430562eb1/tensorflow/python/eager/function.py#L2027-L2030 // Our SavedModel import requires input_signature on the tf.function, so // we never need to handle the kwonlyargs. auto positional_arg_structure = concrete_function.canonicalized_input_signature() .tuple_value() .values(0); StructuredValueLinearizer input_linearizer(positional_arg_structure, builder.getContext()); int bound_input_base = func.getNumArguments() - concrete_function.bound_inputs_size(); TF_ASSIGN_OR_RETURN(auto input_index_paths, input_linearizer.GetLeafIndexPaths( error_context + "in input signature: ")); if (bound_input_base != input_index_paths.size()) { return errors::InvalidArgument( error_context, "Argument mismatch between concrete function input signature " "vs underlying FunctionDef for concrete function '", function.concrete_functions(0), "' (", input_index_paths.size(), " vs ", bound_input_base, ")"); } for (auto index_path : llvm::enumerate(input_index_paths)) { func.setArgAttr(index_path.index(), "tf_saved_model.index_path", index_path.value()); } for (auto& bound_input : llvm::enumerate(concrete_function.bound_inputs())) { int arg_index = bound_input_base + bound_input.index(); auto symbol_ref = builder.getSymbolRefAttr( object_names.GetSymbolTableName(bound_input.value())); func.setArgAttr(arg_index, "tf_saved_model.bound_input", symbol_ref); } StructuredValueLinearizer output_linearizer( concrete_function.output_signature(), builder.getContext()); TF_ASSIGN_OR_RETURN(auto output_index_paths, output_linearizer.GetLeafIndexPaths( error_context + "in output signature: ")); if (func.getNumResults() != output_index_paths.size()) { return errors::InvalidArgument( error_context, "Result mismatch between concrete function output signature " "vs underlying FunctionDef for concrete function '", function.concrete_functions(0), "' (", output_index_paths.size(), " vs ", func.getNumResults(), ")"); } for (auto index_path : llvm::enumerate(output_index_paths)) { func.setResultAttr(index_path.index(), "tf_saved_model.index_path", index_path.value()); } } else if (object.kind_case() == SavedObject::kVariable) { const SavedVariable& variable = object.variable(); // Find the trackable in the side data structure. auto variable_trackable_it = restored_objects.find(node_id); if (variable_trackable_it == restored_objects.end()) { return errors::FailedPrecondition("Could not restore saved variable: ", variable.name()); } const auto* serialized_tensor_attr = FindSerializedTensorInTrackable( *variable_trackable_it->second, "VARIABLE_VALUE"); if (!serialized_tensor_attr) { return errors::FailedPrecondition( "Could not find serialized tensor for saved variable: ", variable.name()); } const auto& checkpoint_key = serialized_tensor_attr->checkpoint_key(); // Load it from the reader. Tensor value; TF_RETURN_WITH_CONTEXT_IF_ERROR( saved_model->variable_reader()->Lookup(checkpoint_key, &value), "Could not read checkpoint key from variables bundle: ", checkpoint_key); TF_ASSIGN_OR_RETURN(auto value_attr, ConvertTensor(value, &builder)); // A variable can have a partially known type, such as tensor<?x27x?xf32>, // even if the initializer is a specific static shape. TF_ASSIGN_OR_RETURN( auto type, ConvertToMlirTensorType(variable.shape(), variable.dtype(), &builder)); auto op = builder.create<mlir::tf_saved_model::GlobalTensorOp>( builder.getUnknownLoc(), builder.getStringAttr(object_names.GetSymbolTableName(node_id)), value_attr, /*type=*/mlir::TypeAttr::get(type), /*is_mutable=*/builder.getUnitAttr()); op.setAttr( "tf_saved_model.exported_names", builder.getStrArrayAttr(object_names.GetExportedNames(node_id))); } else if (object.kind_case() == SavedObject::kConstant) { const SavedConstant& constant = object.constant(); const TensorProto* value = ExtractConstTensorFromGraph( saved_model->meta_graph_def().graph_def(), constant.operation()); if (!value) { return errors::FailedPrecondition( "Unable to find const node referenced in object graph: ", constant.operation()); } TF_ASSIGN_OR_RETURN(auto value_attr, ConvertTensorProto(*value, &builder)); auto op = builder.create<mlir::tf_saved_model::GlobalTensorOp>( builder.getUnknownLoc(), builder.getStringAttr(object_names.GetSymbolTableName(node_id)), value_attr, /*type=*/mlir::TypeAttr::get(value_attr.Attribute::getType()), /*is_mutable=*/nullptr); op.setAttr( "tf_saved_model.exported_names", builder.getStrArrayAttr(object_names.GetExportedNames(node_id))); } } AdjustBoundInputArgTypes(module); module.setAttr("tf_saved_model.semantics", builder.getUnitAttr()); SortSavedModelModule(module); return Status::OK(); } StatusOr<mlir::OwningModuleRef> SavedModelObjectGraphImporter::Convert( SavedModelV2Bundle* saved_model, mlir::MLIRContext* context, absl::Span<std::string> exported_names, bool add_default_attributes) { GraphDebugInfo dummy_debug_info; const GraphDebugInfo& debug_info = saved_model->debug_info() ? *saved_model->debug_info() : dummy_debug_info; GraphImportConfig specs; specs.prune_unused_nodes = true; mlir::OwningModuleRef module = mlir::ModuleOp::create(mlir::UnknownLoc::get(context)); std::unordered_map<std::string, std::string> tf_name_to_mlir_name; const auto& graphdef = saved_model->meta_graph_def().graph_def(); PopulateTfVersions(module.get(), graphdef.versions()); GraphConstructorOptions options; options.allow_internal_ops = true; options.add_default_attributes = add_default_attributes; Graph graph(OpRegistry::Global()); GraphDef preprocessed_graphdef(graphdef); if (add_default_attributes) { TF_RETURN_IF_ERROR(PreprocessGraphDef(nullptr, &preprocessed_graphdef)); } TF_RETURN_IF_ERROR( ConvertGraphDefToGraph(options, preprocessed_graphdef, &graph)); NameUniquifier function_name_uniquifier(graph.flib_def()); SavedModelObjectGraphImporter importer(graph.flib_def(), debug_info, specs, module.get(), &tf_name_to_mlir_name, &function_name_uniquifier); TF_RETURN_IF_ERROR(importer.PrepareConvert(graph)); auto fn_names = graph.flib_def().ListFunctionNames(); for (const auto& fn_name : fn_names) { TF_RETURN_IF_ERROR(importer.ConvertLibFunction(fn_name)); } if (!saved_model->meta_graph_def().has_object_graph_def()) { return errors::InvalidArgument( "SavedModel does not have an object graph. Please use TF2."); } auto& object_graph = saved_model->meta_graph_def().object_graph_def(); ObjectNames object_names(object_graph, exported_names); // Clean up a couple func's that always seem to be present when importing a // SavedModel. This is not strictly needed, as there is a separate pass that // will clean them up, but this makes staring at the raw IR of minimal // examples quite a bit nicer. for (auto func : llvm::make_early_inc_range(module->getOps<mlir::FuncOp>())) { if (func.getName().startswith("__inference__traced_save_") || func.getName().startswith("__inference__traced_restore_") || func.getName().startswith("__inference_signature_wrapper_")) { func.erase(); } } // Diagnose SavedFunction's with multiple input signatures. TF_RETURN_IF_ERROR( DiagnoseMultipleConcreteFunctions(object_graph, object_names)); // Construct the SavedModel IR. TF_RETURN_IF_ERROR(CreateSavedModelIR(object_names, module.get(), object_graph, tf_name_to_mlir_name, saved_model)); assert(mlir::succeeded(mlir::verify(module.get()))); return module; } // A helper class to import a TensorFlow model expressed in SavedModel V1 into // an MLIR Module in SavedModel dialect. class SavedModelSignatureDefImporter { public: // Main entry point: converts all functions (specified by SignatureDefs) in // the given meta graph to an MLIR Module. static StatusOr<mlir::OwningModuleRef> Convert(const SavedModelBundle& bundle, mlir::MLIRContext* context) { SavedModelSignatureDefImporter importer(bundle, context); return importer.ConvertSignatures(); } private: SavedModelSignatureDefImporter(const SavedModelBundle& bundle, mlir::MLIRContext* context) : bundle_(bundle), module_(mlir::ModuleOp::create(mlir::UnknownLoc::get(context))) {} // Converts the SavedModel to the SavedModel dialect. Creates an MLIR function // for each signature. StatusOr<mlir::OwningModuleRef> ConvertSignatures(); Status ConvertSignature(const GraphDef& graphdef, const std::string& sig_def_key, const SignatureDef& signature_def, const GraphDebugInfo& debug_info, const FunctionLibraryDefinition& flib_def); // Creates GlobalTensorOp for each variable and moves each VarHandle op to // the enclosing function's arguments. Status LiftVariables(); // Moves the result of the VarHandleOp to the enclosing function's argument // list and erases this VarHandleOp. void LiftVariable(mlir::TF::VarHandleOp op); // Reads all variables from the SavedModel through session and creates // GlobalTensorOp for these variables. Status ReadVariablesFromSession( const llvm::SmallVectorImpl<mlir::TF::VarHandleOp>& ops); GraphImportConfig::InputArrays ParseInputArrays( const std::vector<std::pair<std::string, TensorInfo>>& inputs); const SavedModelBundle& bundle_; mlir::OwningModuleRef module_; }; StatusOr<mlir::OwningModuleRef> SavedModelSignatureDefImporter::ConvertSignatures() { const auto& signatures = bundle_.GetSignatures(); const auto& graphdef = bundle_.meta_graph_def.graph_def(); PopulateTfVersions(module_.get(), graphdef.versions()); FunctionLibraryDefinition flib_def(OpRegistry::Global(), graphdef.library()); // debug_info might not be loaded with loader_lite. GraphDebugInfo debug_info; if (bundle_.debug_info != nullptr) debug_info = *bundle_.debug_info; for (const auto& key_and_signature_def : signatures) { const std::string& sig_def_key = key_and_signature_def.first; const SignatureDef& signature_def = key_and_signature_def.second; // It is safe to skip "__saved_model_init_op" since it is an internal // signature that is not user-accessible. if (sig_def_key == "__saved_model_init_op") { continue; } TF_RETURN_IF_ERROR(ConvertSignature(graphdef, sig_def_key, signature_def, debug_info, flib_def)); } TF_RETURN_IF_ERROR(LiftVariables()); mlir::OpBuilder builder(module_->getBodyRegion()); module_->setAttr("tf_saved_model.semantics", builder.getUnitAttr()); SortSavedModelModule(*module_); return std::move(module_); } Status SavedModelSignatureDefImporter::ConvertSignature( const GraphDef& graphdef, const std::string& sig_def_key, const SignatureDef& signature_def, const GraphDebugInfo& debug_info, const FunctionLibraryDefinition& flib_def) { // Create local vectors for the input and output and sort them to be // deterministic. We don't want anyone to really depend on the order, client // should lookup argument/result mapping by attribute name. // To avoid accidentally depending on the order we use an unintuitive sorting. std::vector<std::pair<std::string, TensorInfo>> inputs( signature_def.inputs().begin(), signature_def.inputs().end()); llvm::sort(inputs, [](const auto& lhs, const auto& rhs) { return lhs.first.size() < rhs.first.size() || lhs.first > rhs.first; }); std::vector<std::pair<std::string, TensorInfo>> outputs( signature_def.outputs().begin(), signature_def.outputs().end()); llvm::sort(outputs, [](const auto& lhs, const auto& rhs) { return lhs.first.size() < rhs.first.size() || lhs.first > rhs.first; }); GraphImportConfig specs; specs.prune_unused_nodes = true; specs.inputs = ParseInputArrays(inputs); for (auto& output : outputs) specs.outputs.push_back(output.second.name()); // Remove unused nodes and create sub-graphdef. GraphDef sub_graph_def; TF_RETURN_IF_ERROR(tensorflow::grappler::SetTransitiveFaninGraph( graphdef, &sub_graph_def, /*terminal_nodes=*/{specs.outputs.begin(), specs.outputs.end()})); // Convert sub-graphdef to sub-graph. GraphConstructorOptions options; options.allow_internal_ops = true; options.add_default_attributes = true; Graph sub_graph(OpRegistry::Global()); TF_RETURN_IF_ERROR( ConvertGraphDefToGraph(options, sub_graph_def, &sub_graph)); // Convert sub-graph to MLIR module. TF_ASSIGN_OR_RETURN( auto sub_module, GraphDefImporter::Convert(module_->getContext(), sub_graph, debug_info, flib_def, specs, sig_def_key)); mlir::OpBuilder builder(sub_module->getBodyRegion()); // Find the FuncOp which corresponds to current SignatureDef. mlir::SymbolTable symbol_table(*sub_module); auto func_op = symbol_table.lookup<mlir::FuncOp>(sig_def_key); TF_RET_CHECK(func_op) << "Graphdef importer should have created a function named " << sig_def_key << "."; // Use unique SignatureDef key as exported name. func_op.setAttr("tf_saved_model.exported_names", builder.getStrArrayAttr({sig_def_key})); // Transfer input and output parameter names to index_path attributes. for (auto input_and_idx : llvm::enumerate(inputs)) { func_op.setArgAttr(input_and_idx.index(), "tf_saved_model.index_path", builder.getStrArrayAttr({input_and_idx.value().first})); } for (auto output_and_idx : llvm::enumerate(outputs)) { func_op.setResultAttr( output_and_idx.index(), "tf_saved_model.index_path", builder.getStrArrayAttr({output_and_idx.value().first})); } // Move the converted functions to top level MLIR module. auto* block = module_->getBody(); auto* sub_block = sub_module->getBody(); block->getOperations().splice( mlir::Block::iterator(block->getTerminator()), sub_block->getOperations(), sub_block->begin(), mlir::Block::iterator(sub_block->getTerminator())); return Status::OK(); } Status SavedModelSignatureDefImporter::LiftVariables() { llvm::SmallVector<mlir::TF::VarHandleOp, 4> ops; bool contains_ref_variable = false; module_->walk([&ops, &contains_ref_variable](mlir::Operation* op) { if (auto var_handle_op = llvm::dyn_cast<mlir::TF::VarHandleOp>(op)) ops.push_back(var_handle_op); else if (op->getName().getStringRef() == "tf.VariableV2") contains_ref_variable = true; }); if (contains_ref_variable) return errors::InvalidArgument( "Ref variable created by VariableV2 is not supported."); if (ops.empty()) return Status::OK(); TF_RETURN_IF_ERROR(ReadVariablesFromSession(ops)); for (auto op : ops) LiftVariable(op); return Status::OK(); } void SavedModelSignatureDefImporter::LiftVariable(mlir::TF::VarHandleOp op) { mlir::OpBuilder builder(&module_->getBodyRegion()); auto func_op = op.getParentOfType<mlir::FuncOp>(); builder.setInsertionPoint(func_op); auto func_type = func_op.getType(); // Create the new function type by adding variable type to the arguments. llvm::SmallVector<mlir::Type, 4> new_input_types( func_type.getInputs().begin(), func_type.getInputs().end()); new_input_types.push_back(op.resource().getType()); auto new_func_type = builder.getFunctionType(new_input_types, func_type.getResults()); func_op.setType(new_func_type); // Bind the argument to the corresponding global tensor op. func_op.setArgAttr(func_op.getNumArguments() - 1, "tf_saved_model.bound_input", builder.getSymbolRefAttr(op.shared_name())); // Add the newly added function param to entry block's arguments. auto new_value = func_op.front().addArgument(op.resource().getType()); // Remove the VarHandleOp. op.getOperation()->replaceAllUsesWith(llvm::ArrayRef<mlir::Value>(new_value)); op.getOperation()->erase(); } Status SavedModelSignatureDefImporter::ReadVariablesFromSession( const llvm::SmallVectorImpl<mlir::TF::VarHandleOp>& ops) { mlir::OpBuilder builder(&module_->getBodyRegion()); // Find all variables and their corresponding read ops. llvm::MapVector<llvm::StringRef, mlir::TF::VarHandleOp> variable_names_and_ops; for (auto op : ops) { variable_names_and_ops[op.shared_name()] = op; } // Read all resource variables from the session. std::vector<std::string> variable_names; variable_names.reserve(variable_names_and_ops.size()); for (const auto& name_and_location : variable_names_and_ops) variable_names.push_back(std::string(name_and_location.first)); std::vector<Tensor> resource_tensors; TF_RETURN_IF_ERROR(bundle_.GetSession()->Run( /*inputs=*/{}, variable_names, /*target_node_names=*/{}, &resource_tensors)); const DeviceMgr* device_manager; TF_RETURN_IF_ERROR(bundle_.GetSession()->LocalDeviceManager(&device_manager)); // Read all underlying tensors of the variables from the session. std::vector<Tensor> tensors; tensors.reserve(resource_tensors.size()); for (const auto& resource_tensor : resource_tensors) { const auto& resource_handle = resource_tensor.scalar<ResourceHandle>()(); Device* device; TF_RETURN_IF_ERROR( device_manager->LookupDevice(resource_handle.device(), &device)); Var* var_ptr; TF_RETURN_IF_ERROR(device->resource_manager()->Lookup( resource_handle.container(), resource_handle.name(), &var_ptr)); core::RefCountPtr<Var> var(var_ptr); // The variable tensor is already loaded into corresponding device's // resource manager when we load the saved model using LoadSavedModel(). // Here we just read its value. mutex_lock ml(*var->mu()); tensors.push_back(*var->tensor()); } for (const auto iter : llvm::zip(variable_names_and_ops, tensors)) { const auto& name = std::get<0>(iter).first; auto location = std::get<0>(iter).second.getLoc(); const auto& tensor = std::get<1>(iter); // Create tensor attribute for this variable. TF_ASSIGN_OR_RETURN(auto tensor_attr, ConvertTensor(tensor, &builder)); builder.create<mlir::tf_saved_model::GlobalTensorOp>( location, builder.getStringAttr(name), tensor_attr, mlir::TypeAttr::get(tensor_attr.getType()), builder.getUnitAttr()); } return Status::OK(); } GraphImportConfig::InputArrays SavedModelSignatureDefImporter::ParseInputArrays( const std::vector<std::pair<std::string, TensorInfo>>& inputs) { GraphImportConfig::InputArrays results; for (const auto& iter : inputs) { const auto& tensor_info = iter.second; // Only dense tensor is supported. DCHECK_EQ(tensor_info.encoding_case(), tensorflow::TensorInfo::kName); ArrayInfo array_info; array_info.imported_dtype = tensor_info.dtype(); array_info.shape = tensor_info.tensor_shape(); results.insert(std::pair<std::string, ArrayInfo>(tensor_info.name(), std::move(array_info))); } return results; } } // namespace Status UpgradeLegacyGraph(Graph* graph, FunctionLibraryDefinition* flib_def) { return FunctionalizeControlFlow(graph, flib_def); } StatusOr<mlir::OwningModuleRef> ConvertGraphdefToMlir( const GraphDef& graphdef, const GraphDebugInfo& debug_info, const GraphImportConfig& specs, mlir::MLIRContext* context, bool add_default_attributes) { GraphConstructorOptions options; options.allow_internal_ops = true; options.add_default_attributes = add_default_attributes; Graph graph(OpRegistry::Global()); GraphDef preprocessed_graphdef(graphdef); if (add_default_attributes) { TF_RETURN_IF_ERROR(PreprocessGraphDef(&specs, &preprocessed_graphdef)); } TF_RETURN_IF_ERROR(ConvertGraphDefToGraph( options, std::move(preprocessed_graphdef), &graph)); return ConvertGraphToMlir(graph, debug_info, graph.flib_def(), specs, context); } StatusOr<mlir::OwningModuleRef> ConvertGraphToMlir( const Graph& graph, const GraphDebugInfo& debug_info, const FunctionLibraryDefinition& flib_def, const GraphImportConfig& specs, mlir::MLIRContext* context) { // TODO(jpienaar): Remove need to const_cast. if (specs.upgrade_legacy) { TF_RETURN_IF_ERROR( UpgradeLegacyGraph(const_cast<Graph*>(&graph), const_cast<FunctionLibraryDefinition*>(&flib_def))); } return GraphDefImporter::Convert(context, graph, debug_info, flib_def, specs, /*func_name=*/"main"); } StatusOr<mlir::OwningModuleRef> ConvertSavedModelToMlir( SavedModelV2Bundle* saved_model, mlir::MLIRContext* context, absl::Span<std::string> exported_names, bool add_default_attributes) { return SavedModelObjectGraphImporter::Convert( saved_model, context, exported_names, add_default_attributes); } StatusOr<mlir::OwningModuleRef> ConvertSavedModelV1ToMlir( const SavedModelBundle& saved_model, mlir::MLIRContext* context) { return SavedModelSignatureDefImporter::Convert(saved_model, context); } std::string MlirModuleToString(mlir::ModuleOp module, bool show_debug_info) { std::string txt_module; { mlir::OpPrintingFlags flags; if (show_debug_info) flags.enableDebugInfo(); llvm::raw_string_ostream os{txt_module}; module.print(os, flags); } return txt_module; } } // namespace tensorflow
42.399313
143
0.684426
joshz123
4f41e682eb49c0dfed37f086bc2498247cab8872
1,521
hpp
C++
src/gmatutil/util/FileTypes.hpp
saichikine/GMAT
80bde040e12946a61dae90d9fc3538f16df34190
[ "Apache-2.0" ]
null
null
null
src/gmatutil/util/FileTypes.hpp
saichikine/GMAT
80bde040e12946a61dae90d9fc3538f16df34190
[ "Apache-2.0" ]
null
null
null
src/gmatutil/util/FileTypes.hpp
saichikine/GMAT
80bde040e12946a61dae90d9fc3538f16df34190
[ "Apache-2.0" ]
1
2021-12-05T05:40:15.000Z
2021-12-05T05:40:15.000Z
//$Id$ //------------------------------------------------------------------------------ // FileTypes //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002 - 2018 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other 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. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number S-67573-G // // Author: Linda Jun (GSFC) // Created: 2007/05/15 // /** * Provides constants for file types. */ //------------------------------------------------------------------------------ #ifndef FileTypes_hpp #define FileTypes_hpp #include "utildefs.hpp" namespace GmatFile { static const Integer MAX_PATH_LEN = 232; static const Integer MAX_FILE_LEN = 232; static const Integer MAX_LINE_LEN = 512; } #endif // FileTypes_hpp
34.568182
80
0.605523
saichikine
4f42eb9b1307d853bc9238a25990ad05ea937dc1
66,540
cpp
C++
source/vulkan/vulkan_impl_type_convert.cpp
Meme-sys/reshade
93380452fc6eb647a4cc5400ac1e81355ab91513
[ "BSD-3-Clause" ]
null
null
null
source/vulkan/vulkan_impl_type_convert.cpp
Meme-sys/reshade
93380452fc6eb647a4cc5400ac1e81355ab91513
[ "BSD-3-Clause" ]
null
null
null
source/vulkan/vulkan_impl_type_convert.cpp
Meme-sys/reshade
93380452fc6eb647a4cc5400ac1e81355ab91513
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2021 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license */ #include "vulkan_hooks.hpp" #include "vulkan_impl_device.hpp" #include "vulkan_impl_type_convert.hpp" auto reshade::vulkan::convert_format(api::format format) -> VkFormat { switch (format) { default: case api::format::unknown: break; case api::format::r1_unorm: break; // Unsupported case api::format::r8_uint: return VK_FORMAT_R8_UINT; case api::format::r8_sint: return VK_FORMAT_R8_SINT; case api::format::r8_typeless: case api::format::r8_unorm: case api::format::l8_unorm: // { VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_ONE } case api::format::a8_unorm: // { VK_COMPONENT_SWIZZLE_ZERO, VK_COMPONENT_SWIZZLE_ZERO, VK_COMPONENT_SWIZZLE_ZERO, VK_COMPONENT_SWIZZLE_R } return VK_FORMAT_R8_UNORM; case api::format::r8_snorm: return VK_FORMAT_R8_SNORM; case api::format::r8g8_uint: return VK_FORMAT_R8G8_UINT; case api::format::r8g8_sint: return VK_FORMAT_R8G8_SINT; case api::format::r8g8_typeless: case api::format::l8a8_unorm: // { VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G } case api::format::r8g8_unorm: return VK_FORMAT_R8G8_UNORM; case api::format::r8g8_snorm: return VK_FORMAT_R8G8_SNORM; case api::format::r8g8b8a8_uint: return VK_FORMAT_R8G8B8A8_UINT; case api::format::r8g8b8a8_sint: return VK_FORMAT_R8G8B8A8_SINT; case api::format::r8g8b8a8_typeless: case api::format::r8g8b8a8_unorm: case api::format::r8g8b8x8_typeless: case api::format::r8g8b8x8_unorm: return VK_FORMAT_R8G8B8A8_UNORM; case api::format::r8g8b8a8_unorm_srgb: case api::format::r8g8b8x8_unorm_srgb: return VK_FORMAT_R8G8B8A8_SRGB; case api::format::r8g8b8a8_snorm: return VK_FORMAT_R8G8B8A8_SNORM; case api::format::b8g8r8a8_typeless: case api::format::b8g8r8a8_unorm: case api::format::b8g8r8x8_typeless: // { VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_ONE } case api::format::b8g8r8x8_unorm: return VK_FORMAT_B8G8R8A8_UNORM; case api::format::b8g8r8a8_unorm_srgb: case api::format::b8g8r8x8_unorm_srgb: return VK_FORMAT_B8G8R8A8_SRGB; case api::format::r10g10b10a2_uint: return VK_FORMAT_A2B10G10R10_UINT_PACK32; case api::format::r10g10b10a2_typeless: case api::format::r10g10b10a2_unorm: return VK_FORMAT_A2B10G10R10_UNORM_PACK32; case api::format::r10g10b10a2_xr_bias: break; // Unsupported case api::format::b10g10r10a2_uint: return VK_FORMAT_A2R10G10B10_UINT_PACK32; case api::format::b10g10r10a2_typeless: case api::format::b10g10r10a2_unorm: return VK_FORMAT_A2R10G10B10_UNORM_PACK32; case api::format::r16_sint: return VK_FORMAT_R16_SINT; case api::format::r16_uint: return VK_FORMAT_R16_UINT; case api::format::r16_typeless: case api::format::r16_float: return VK_FORMAT_R16_SFLOAT; case api::format::r16_unorm: case api::format::l16_unorm: // { VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_ONE } return VK_FORMAT_R16_UNORM; case api::format::r16_snorm: return VK_FORMAT_R16_SNORM; case api::format::r16g16_uint: return VK_FORMAT_R16G16_UINT; case api::format::r16g16_sint: return VK_FORMAT_R16G16_SINT; case api::format::r16g16_typeless: case api::format::r16g16_float: return VK_FORMAT_R16G16_SFLOAT; case api::format::l16a16_unorm: // { VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G } case api::format::r16g16_unorm: return VK_FORMAT_R16G16_UNORM; case api::format::r16g16_snorm: return VK_FORMAT_R16G16_SNORM; case api::format::r16g16b16a16_uint: return VK_FORMAT_R16G16B16A16_UINT; case api::format::r16g16b16a16_sint: return VK_FORMAT_R16G16B16A16_SINT; case api::format::r16g16b16a16_typeless: case api::format::r16g16b16a16_float: return VK_FORMAT_R16G16B16A16_SFLOAT; case api::format::r16g16b16a16_unorm: return VK_FORMAT_R16G16B16A16_UNORM; case api::format::r16g16b16a16_snorm: return VK_FORMAT_R16G16B16A16_SNORM; case api::format::r32_uint: return VK_FORMAT_R32_UINT; case api::format::r32_sint: return VK_FORMAT_R32_SINT; case api::format::r32_typeless: case api::format::r32_float: return VK_FORMAT_R32_SFLOAT; case api::format::r32g32_uint: return VK_FORMAT_R32G32_UINT; case api::format::r32g32_sint: return VK_FORMAT_R32G32_SINT; case api::format::r32g32_typeless: case api::format::r32g32_float: return VK_FORMAT_R32G32_SFLOAT; case api::format::r32g32b32_uint: return VK_FORMAT_R32G32B32_UINT; case api::format::r32g32b32_sint: return VK_FORMAT_R32G32B32_SINT; case api::format::r32g32b32_typeless: case api::format::r32g32b32_float: return VK_FORMAT_R32G32B32_SFLOAT; case api::format::r32g32b32a32_uint: return VK_FORMAT_R32G32B32A32_UINT; case api::format::r32g32b32a32_sint: return VK_FORMAT_R32G32B32A32_SINT; case api::format::r32g32b32a32_typeless: case api::format::r32g32b32a32_float: return VK_FORMAT_R32G32B32A32_SFLOAT; case api::format::r9g9b9e5: return VK_FORMAT_E5B9G9R9_UFLOAT_PACK32; case api::format::r11g11b10_float: return VK_FORMAT_B10G11R11_UFLOAT_PACK32; case api::format::b5g6r5_unorm: return VK_FORMAT_R5G6B5_UNORM_PACK16; case api::format::b5g5r5a1_unorm: case api::format::b5g5r5x1_unorm: return VK_FORMAT_A1R5G5B5_UNORM_PACK16; #if 0 case api::format::b4g4r4a4_unorm: return VK_FORMAT_A4R4G4B4_UNORM_PACK16_EXT; #endif case api::format::s8_uint: return VK_FORMAT_S8_UINT; case api::format::d16_unorm: return VK_FORMAT_D16_UNORM; case api::format::d16_unorm_s8_uint: return VK_FORMAT_D16_UNORM_S8_UINT; case api::format::r24_g8_typeless: case api::format::r24_unorm_x8_uint: case api::format::x24_unorm_g8_uint: case api::format::d24_unorm_s8_uint: return VK_FORMAT_D24_UNORM_S8_UINT; case api::format::d32_float: return VK_FORMAT_D32_SFLOAT; case api::format::r32_g8_typeless: case api::format::r32_float_x8_uint: case api::format::x32_float_g8_uint: case api::format::d32_float_s8_uint: return VK_FORMAT_D32_SFLOAT_S8_UINT; case api::format::bc1_typeless: case api::format::bc1_unorm: return VK_FORMAT_BC1_RGBA_UNORM_BLOCK; case api::format::bc1_unorm_srgb: return VK_FORMAT_BC1_RGBA_SRGB_BLOCK; case api::format::bc2_typeless: case api::format::bc2_unorm: return VK_FORMAT_BC2_UNORM_BLOCK; case api::format::bc2_unorm_srgb: return VK_FORMAT_BC2_SRGB_BLOCK; case api::format::bc3_typeless: case api::format::bc3_unorm: return VK_FORMAT_BC3_UNORM_BLOCK; case api::format::bc3_unorm_srgb: return VK_FORMAT_BC3_SRGB_BLOCK; case api::format::bc4_typeless: case api::format::bc4_unorm: return VK_FORMAT_BC4_UNORM_BLOCK; case api::format::bc4_snorm: return VK_FORMAT_BC4_SNORM_BLOCK; case api::format::bc5_typeless: case api::format::bc5_unorm: return VK_FORMAT_BC5_UNORM_BLOCK; case api::format::bc5_snorm: return VK_FORMAT_BC5_SNORM_BLOCK; case api::format::bc6h_typeless: case api::format::bc6h_ufloat: return VK_FORMAT_BC6H_UFLOAT_BLOCK; case api::format::bc6h_sfloat: return VK_FORMAT_BC6H_SFLOAT_BLOCK; case api::format::bc7_typeless: case api::format::bc7_unorm: return VK_FORMAT_BC7_UNORM_BLOCK; case api::format::bc7_unorm_srgb: return VK_FORMAT_BC7_SRGB_BLOCK; case api::format::r8g8_b8g8_unorm: return VK_FORMAT_B8G8R8G8_422_UNORM; case api::format::g8r8_g8b8_unorm: return VK_FORMAT_G8B8G8R8_422_UNORM; } return VK_FORMAT_UNDEFINED; } auto reshade::vulkan::convert_format(VkFormat vk_format) -> api::format { switch (vk_format) { default: case VK_FORMAT_UNDEFINED: return api::format::unknown; #if 0 case VK_FORMAT_A4R4G4B4_UNORM_PACK16_EXT: return api::format::b4g4r4a4_unorm; #endif case VK_FORMAT_R5G6B5_UNORM_PACK16: return api::format::b5g6r5_unorm; case VK_FORMAT_A1R5G5B5_UNORM_PACK16: return api::format::b5g5r5a1_unorm; case VK_FORMAT_R8_UNORM: return api::format::r8_unorm; case VK_FORMAT_R8_SNORM: return api::format::r8_snorm; case VK_FORMAT_R8_UINT: return api::format::r8_uint; case VK_FORMAT_R8_SINT: return api::format::r8_sint; case VK_FORMAT_R8G8_UNORM: return api::format::r8g8_unorm; case VK_FORMAT_R8G8_SNORM: return api::format::r8g8_snorm; case VK_FORMAT_R8G8_UINT: return api::format::r8g8_uint; case VK_FORMAT_R8G8_SINT: return api::format::r8g8_sint; case VK_FORMAT_R8G8B8A8_UNORM: return api::format::r8g8b8a8_unorm; case VK_FORMAT_R8G8B8A8_SNORM: return api::format::r8g8b8a8_snorm; case VK_FORMAT_R8G8B8A8_UINT: return api::format::r8g8b8a8_uint; case VK_FORMAT_R8G8B8A8_SINT: return api::format::r8g8b8a8_sint; case VK_FORMAT_R8G8B8A8_SRGB: return api::format::r8g8b8a8_unorm_srgb; case VK_FORMAT_B8G8R8A8_UNORM: return api::format::b8g8r8a8_unorm; case VK_FORMAT_B8G8R8A8_SRGB: return api::format::b8g8r8a8_unorm_srgb; case VK_FORMAT_A2B10G10R10_UNORM_PACK32: return api::format::r10g10b10a2_unorm; case VK_FORMAT_A2B10G10R10_UINT_PACK32: return api::format::r10g10b10a2_uint; case VK_FORMAT_A2R10G10B10_UNORM_PACK32: return api::format::b10g10r10a2_unorm; case VK_FORMAT_A2R10G10B10_UINT_PACK32: return api::format::b10g10r10a2_uint; case VK_FORMAT_R16_UNORM: return api::format::r16_unorm; case VK_FORMAT_R16_SNORM: return api::format::r16_snorm; case VK_FORMAT_R16_UINT: return api::format::r16_uint; case VK_FORMAT_R16_SINT: return api::format::r16_sint; case VK_FORMAT_R16_SFLOAT: return api::format::r16_float; case VK_FORMAT_R16G16_UNORM: return api::format::r16g16_unorm; case VK_FORMAT_R16G16_SNORM: return api::format::r16g16_snorm; case VK_FORMAT_R16G16_UINT: return api::format::r16g16_uint; case VK_FORMAT_R16G16_SINT: return api::format::r16g16_sint; case VK_FORMAT_R16G16_SFLOAT: return api::format::r16g16_float; case VK_FORMAT_R16G16B16A16_UNORM: return api::format::r16g16b16a16_unorm; case VK_FORMAT_R16G16B16A16_SNORM: return api::format::r16g16b16a16_snorm; case VK_FORMAT_R16G16B16A16_UINT: return api::format::r16g16b16a16_uint; case VK_FORMAT_R16G16B16A16_SINT: return api::format::r16g16b16a16_sint; case VK_FORMAT_R16G16B16A16_SFLOAT: return api::format::r16g16b16a16_float; case VK_FORMAT_R32_UINT: return api::format::r32_uint; case VK_FORMAT_R32_SINT: return api::format::r32_sint; case VK_FORMAT_R32_SFLOAT: return api::format::r32_float; case VK_FORMAT_R32G32_UINT: return api::format::r32g32_uint; case VK_FORMAT_R32G32_SINT: return api::format::r32g32_sint; case VK_FORMAT_R32G32_SFLOAT: return api::format::r32g32_float; case VK_FORMAT_R32G32B32_UINT: return api::format::r32g32b32_uint; case VK_FORMAT_R32G32B32_SINT: return api::format::r32g32b32_sint; case VK_FORMAT_R32G32B32_SFLOAT: return api::format::r32g32b32_float; case VK_FORMAT_R32G32B32A32_UINT: return api::format::r32g32b32a32_uint; case VK_FORMAT_R32G32B32A32_SINT: return api::format::r32g32b32a32_sint; case VK_FORMAT_R32G32B32A32_SFLOAT: return api::format::r32g32b32a32_float; case VK_FORMAT_B10G11R11_UFLOAT_PACK32: return api::format::r11g11b10_float; case VK_FORMAT_E5B9G9R9_UFLOAT_PACK32: return api::format::r9g9b9e5; case VK_FORMAT_D16_UNORM: return api::format::d16_unorm; case VK_FORMAT_D32_SFLOAT: return api::format::d32_float; case VK_FORMAT_S8_UINT: return api::format::s8_uint; case VK_FORMAT_D24_UNORM_S8_UINT: return api::format::d24_unorm_s8_uint; case VK_FORMAT_D32_SFLOAT_S8_UINT: return api::format::d32_float_s8_uint; case VK_FORMAT_BC1_RGBA_UNORM_BLOCK: return api::format::bc1_unorm; case VK_FORMAT_BC1_RGBA_SRGB_BLOCK: return api::format::bc1_unorm_srgb; case VK_FORMAT_BC2_UNORM_BLOCK: return api::format::bc2_unorm; case VK_FORMAT_BC2_SRGB_BLOCK: return api::format::bc2_unorm_srgb; case VK_FORMAT_BC3_UNORM_BLOCK: return api::format::bc3_unorm; case VK_FORMAT_BC3_SRGB_BLOCK: return api::format::bc3_unorm_srgb; case VK_FORMAT_BC4_UNORM_BLOCK: return api::format::bc4_unorm; case VK_FORMAT_BC4_SNORM_BLOCK: return api::format::bc4_snorm; case VK_FORMAT_BC5_UNORM_BLOCK: return api::format::bc5_unorm; case VK_FORMAT_BC5_SNORM_BLOCK: return api::format::bc5_snorm; case VK_FORMAT_BC6H_UFLOAT_BLOCK: return api::format::bc6h_ufloat; case VK_FORMAT_BC6H_SFLOAT_BLOCK: return api::format::bc6h_sfloat; case VK_FORMAT_BC7_UNORM_BLOCK: return api::format::bc7_unorm; case VK_FORMAT_BC7_SRGB_BLOCK: return api::format::bc7_unorm_srgb; case VK_FORMAT_G8B8G8R8_422_UNORM: return api::format::g8r8_g8b8_unorm; case VK_FORMAT_B8G8R8G8_422_UNORM: return api::format::r8g8_b8g8_unorm; } } auto reshade::vulkan::convert_access_to_usage(VkAccessFlags flags) -> api::resource_usage { api::resource_usage result = api::resource_usage::undefined; if ((flags & VK_ACCESS_SHADER_READ_BIT) != 0) result |= api::resource_usage::shader_resource; if ((flags & VK_ACCESS_SHADER_WRITE_BIT) != 0) result |= api::resource_usage::unordered_access; if ((flags & VK_ACCESS_TRANSFER_WRITE_BIT) != 0) result |= api::resource_usage::copy_dest; if ((flags & VK_ACCESS_TRANSFER_READ_BIT) != 0) result |= api::resource_usage::copy_source; if ((flags & VK_ACCESS_INDEX_READ_BIT) != 0) result |= api::resource_usage::index_buffer; if ((flags & VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT) != 0) result |= api::resource_usage::vertex_buffer; if ((flags & VK_ACCESS_UNIFORM_READ_BIT) != 0) result |= api::resource_usage::constant_buffer; return result; } auto reshade::vulkan::convert_image_layout_to_usage(VkImageLayout layout) -> api::resource_usage { switch (layout) { case VK_IMAGE_LAYOUT_UNDEFINED: return api::resource_usage::undefined; default: case VK_IMAGE_LAYOUT_GENERAL: return api::resource_usage::general; case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL: return api::resource_usage::render_target; case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL: case VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL: case VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL: case VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL: case VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL: return api::resource_usage::depth_stencil; case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL: case VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL: case VK_IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL: return api::resource_usage::depth_stencil_read; case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL: return api::resource_usage::shader_resource; case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL: return api::resource_usage::copy_source; case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL: return api::resource_usage::copy_dest; case VK_IMAGE_LAYOUT_PREINITIALIZED: return api::resource_usage::cpu_access; case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR: case VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR: return api::resource_usage::present; } } auto reshade::vulkan::convert_usage_to_access(api::resource_usage state) -> VkAccessFlags { if (state == api::resource_usage::present) return 0; if (state == api::resource_usage::cpu_access) return VK_ACCESS_HOST_READ_BIT | VK_ACCESS_HOST_WRITE_BIT; VkAccessFlags result = 0; if ((state & api::resource_usage::depth_stencil_read) != api::resource_usage::undefined) result |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT; if ((state & api::resource_usage::depth_stencil_write) != api::resource_usage::undefined) result |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; if ((state & api::resource_usage::render_target) != api::resource_usage::undefined) result |= VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; if ((state & api::resource_usage::shader_resource) != api::resource_usage::undefined) result |= VK_ACCESS_SHADER_READ_BIT; if ((state & api::resource_usage::unordered_access) != api::resource_usage::undefined) result |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; if ((state & (api::resource_usage::copy_dest | api::resource_usage::resolve_dest)) != api::resource_usage::undefined) result |= VK_ACCESS_TRANSFER_WRITE_BIT; if ((state & (api::resource_usage::copy_source | api::resource_usage::resolve_source)) != api::resource_usage::undefined) result |= VK_ACCESS_TRANSFER_READ_BIT; if ((state & api::resource_usage::index_buffer) != api::resource_usage::undefined) result |= VK_ACCESS_INDEX_READ_BIT; if ((state & api::resource_usage::vertex_buffer) != api::resource_usage::undefined) result |= VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT; if ((state & api::resource_usage::constant_buffer) != api::resource_usage::undefined) result |= VK_ACCESS_UNIFORM_READ_BIT; return result; } auto reshade::vulkan::convert_usage_to_image_layout(api::resource_usage state) -> VkImageLayout { switch (state) { case api::resource_usage::undefined: return VK_IMAGE_LAYOUT_UNDEFINED; case api::resource_usage::depth_stencil: case api::resource_usage::depth_stencil_write: return VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; case api::resource_usage::depth_stencil_read: return VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL; case api::resource_usage::render_target: return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; case api::resource_usage::shader_resource: case api::resource_usage::shader_resource_pixel: case api::resource_usage::shader_resource_non_pixel: return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; default: // Default to general layout if multiple usage flags are specified case api::resource_usage::general: case api::resource_usage::unordered_access: return VK_IMAGE_LAYOUT_GENERAL; case api::resource_usage::copy_dest: case api::resource_usage::resolve_dest: return VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; case api::resource_usage::copy_source: case api::resource_usage::resolve_source: return VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; case api::resource_usage::present: return VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; } } auto reshade::vulkan::convert_usage_to_pipeline_stage(api::resource_usage state, bool src_stage, const VkPhysicalDeviceFeatures &enabled_features) -> VkPipelineStageFlags { if (state == api::resource_usage::general) return VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; if (state == api::resource_usage::present || state == api::resource_usage::undefined) // Do not introduce a execution dependency return src_stage ? VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT : VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; if (state == api::resource_usage::cpu_access) return VK_PIPELINE_STAGE_HOST_BIT; VkPipelineStageFlags result = 0; if ((state & api::resource_usage::depth_stencil_read) != api::resource_usage::undefined) result |= VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT; if ((state & api::resource_usage::depth_stencil_write) != api::resource_usage::undefined) result |= VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; if ((state & api::resource_usage::render_target) != api::resource_usage::undefined) result |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; if ((state & (api::resource_usage::shader_resource_pixel | api::resource_usage::constant_buffer)) != api::resource_usage::undefined) result |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; if ((state & (api::resource_usage::shader_resource_non_pixel | api::resource_usage::constant_buffer)) != api::resource_usage::undefined) result |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | (enabled_features.tessellationShader ? VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT : 0) | (enabled_features.geometryShader ? VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT : 0) | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; if ((state & api::resource_usage::unordered_access) != api::resource_usage::undefined) result |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; if ((state & (api::resource_usage::copy_dest | api::resource_usage::copy_source | api::resource_usage::resolve_dest | api::resource_usage::resolve_source)) != api::resource_usage::undefined) result |= VK_PIPELINE_STAGE_TRANSFER_BIT; if ((state & (api::resource_usage::index_buffer | api::resource_usage::vertex_buffer)) != api::resource_usage::undefined) result |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT; return result; } void reshade::vulkan::convert_usage_to_image_usage_flags(api::resource_usage usage, VkImageUsageFlags &image_flags) { if ((usage & (api::resource_usage::copy_dest | api::resource_usage::resolve_dest)) != api::resource_usage::undefined) image_flags |= VK_IMAGE_USAGE_TRANSFER_DST_BIT; else image_flags &= ~VK_IMAGE_USAGE_TRANSFER_DST_BIT; if ((usage & (api::resource_usage::copy_source | api::resource_usage::resolve_source)) != api::resource_usage::undefined) image_flags |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; else image_flags &= ~VK_IMAGE_USAGE_TRANSFER_SRC_BIT; if ((usage & api::resource_usage::depth_stencil) != api::resource_usage::undefined) // Add transfer destination usage as well to support clearing via 'vkCmdClearDepthStencilImage' image_flags |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; else image_flags &= ~VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; if ((usage & api::resource_usage::render_target) != api::resource_usage::undefined) // Add transfer destination usage as well to support clearing via 'vkCmdClearColorImage' image_flags |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; else image_flags &= ~VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; if ((usage & api::resource_usage::shader_resource) != api::resource_usage::undefined) image_flags |= VK_IMAGE_USAGE_SAMPLED_BIT; else image_flags &= ~VK_IMAGE_USAGE_SAMPLED_BIT; if ((usage & api::resource_usage::unordered_access) != api::resource_usage::undefined) image_flags |= VK_IMAGE_USAGE_STORAGE_BIT; else image_flags &= ~VK_IMAGE_USAGE_STORAGE_BIT; } void reshade::vulkan::convert_image_usage_flags_to_usage(const VkImageUsageFlags image_flags, api::resource_usage &usage) { using namespace reshade; if ((image_flags & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) != 0) usage |= api::resource_usage::depth_stencil; if ((image_flags & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) != 0) usage |= api::resource_usage::render_target; if ((image_flags & VK_IMAGE_USAGE_SAMPLED_BIT) != 0) usage |= api::resource_usage::shader_resource; if ((image_flags & VK_IMAGE_USAGE_STORAGE_BIT) != 0) usage |= api::resource_usage::unordered_access; if ((image_flags & VK_IMAGE_USAGE_TRANSFER_DST_BIT) != 0) usage |= api::resource_usage::copy_dest; if ((image_flags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) != 0) usage |= api::resource_usage::copy_source; } void reshade::vulkan::convert_usage_to_buffer_usage_flags(api::resource_usage usage, VkBufferUsageFlags &buffer_flags) { if ((usage & api::resource_usage::index_buffer) != api::resource_usage::undefined) buffer_flags |= VK_BUFFER_USAGE_INDEX_BUFFER_BIT; else buffer_flags &= ~VK_BUFFER_USAGE_INDEX_BUFFER_BIT; if ((usage & api::resource_usage::vertex_buffer) != api::resource_usage::undefined) buffer_flags |= VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; else buffer_flags &= ~VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; if ((usage & api::resource_usage::constant_buffer) != api::resource_usage::undefined) buffer_flags |= VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; else buffer_flags &= ~VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; if ((usage & api::resource_usage::shader_resource) != api::resource_usage::undefined) buffer_flags |= VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT; else buffer_flags &= ~VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT; if ((usage & api::resource_usage::unordered_access) != api::resource_usage::undefined) buffer_flags |= VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; else buffer_flags &= ~(VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); if ((usage & api::resource_usage::copy_dest) != api::resource_usage::undefined) buffer_flags |= VK_BUFFER_USAGE_TRANSFER_DST_BIT; else buffer_flags &= ~VK_BUFFER_USAGE_TRANSFER_DST_BIT; if ((usage & api::resource_usage::copy_source) != api::resource_usage::undefined) buffer_flags |= VK_BUFFER_USAGE_TRANSFER_SRC_BIT; else buffer_flags &= ~VK_BUFFER_USAGE_TRANSFER_SRC_BIT; } void reshade::vulkan::convert_buffer_usage_flags_to_usage(const VkBufferUsageFlags buffer_flags, api::resource_usage &usage) { using namespace reshade; if ((buffer_flags & VK_BUFFER_USAGE_INDEX_BUFFER_BIT) != 0) usage |= api::resource_usage::index_buffer; if ((buffer_flags & VK_BUFFER_USAGE_VERTEX_BUFFER_BIT) != 0) usage |= api::resource_usage::vertex_buffer; if ((buffer_flags & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT) != 0) usage |= api::resource_usage::constant_buffer; if ((buffer_flags & VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT) != 0) usage |= api::resource_usage::shader_resource; if ((buffer_flags & VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT) != 0) usage |= api::resource_usage::unordered_access; if ((buffer_flags & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT) != 0) usage |= api::resource_usage::unordered_access; if ((buffer_flags & VK_BUFFER_USAGE_TRANSFER_DST_BIT) != 0) usage |= api::resource_usage::copy_dest; if ((buffer_flags & VK_BUFFER_USAGE_TRANSFER_SRC_BIT) != 0) usage |= api::resource_usage::copy_source; } void reshade::vulkan::convert_sampler_desc(const api::sampler_desc &desc, VkSamplerCreateInfo &create_info) { create_info.compareEnable = VK_FALSE; switch (desc.filter) { case api::filter_mode::compare_min_mag_mip_point: create_info.compareEnable = VK_TRUE; [[fallthrough]]; case api::filter_mode::min_mag_mip_point: create_info.minFilter = VK_FILTER_NEAREST; create_info.magFilter = VK_FILTER_NEAREST; create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; create_info.anisotropyEnable = VK_FALSE; break; case api::filter_mode::compare_min_mag_point_mip_linear: create_info.compareEnable = VK_TRUE; [[fallthrough]]; case api::filter_mode::min_mag_point_mip_linear: create_info.magFilter = VK_FILTER_NEAREST; create_info.minFilter = VK_FILTER_NEAREST; create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; create_info.anisotropyEnable = VK_FALSE; break; case api::filter_mode::compare_min_point_mag_linear_mip_point: create_info.compareEnable = VK_TRUE; [[fallthrough]]; case api::filter_mode::min_point_mag_linear_mip_point: create_info.magFilter = VK_FILTER_LINEAR; create_info.minFilter = VK_FILTER_NEAREST; create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; create_info.anisotropyEnable = VK_FALSE; break; case api::filter_mode::compare_min_point_mag_mip_linear: create_info.compareEnable = VK_TRUE; [[fallthrough]]; case api::filter_mode::min_point_mag_mip_linear: create_info.magFilter = VK_FILTER_LINEAR; create_info.minFilter = VK_FILTER_NEAREST; create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; create_info.anisotropyEnable = VK_FALSE; break; case api::filter_mode::compare_min_linear_mag_mip_point: create_info.compareEnable = VK_TRUE; [[fallthrough]]; case api::filter_mode::min_linear_mag_mip_point: create_info.magFilter = VK_FILTER_NEAREST; create_info.minFilter = VK_FILTER_LINEAR; create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; create_info.anisotropyEnable = VK_FALSE; break; case api::filter_mode::compare_min_linear_mag_point_mip_linear: create_info.compareEnable = VK_TRUE; [[fallthrough]]; case api::filter_mode::min_linear_mag_point_mip_linear: create_info.magFilter = VK_FILTER_NEAREST; create_info.minFilter = VK_FILTER_LINEAR; create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; create_info.anisotropyEnable = VK_FALSE; break; case api::filter_mode::compare_min_mag_linear_mip_point: create_info.compareEnable = VK_TRUE; [[fallthrough]]; case api::filter_mode::min_mag_linear_mip_point: create_info.magFilter = VK_FILTER_LINEAR; create_info.minFilter = VK_FILTER_LINEAR; create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; create_info.anisotropyEnable = VK_FALSE; break; case api::filter_mode::compare_min_mag_mip_linear: create_info.compareEnable = VK_TRUE; [[fallthrough]]; case api::filter_mode::min_mag_mip_linear: create_info.magFilter = VK_FILTER_LINEAR; create_info.minFilter = VK_FILTER_LINEAR; create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; create_info.anisotropyEnable = VK_FALSE; break; case api::filter_mode::compare_anisotropic: create_info.compareEnable = VK_TRUE; [[fallthrough]]; case api::filter_mode::anisotropic: create_info.magFilter = VK_FILTER_LINEAR; create_info.minFilter = VK_FILTER_LINEAR; create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; create_info.anisotropyEnable = VK_TRUE; break; } const auto convert_address_mode = [](api::texture_address_mode mode) { switch (mode) { default: assert(false); [[fallthrough]]; case api::texture_address_mode::wrap: return VK_SAMPLER_ADDRESS_MODE_REPEAT; case api::texture_address_mode::mirror: return VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT; case api::texture_address_mode::clamp: return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; case api::texture_address_mode::border: return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER; case api::texture_address_mode::mirror_once: return VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE; } }; create_info.addressModeU = convert_address_mode(desc.address_u); create_info.addressModeV = convert_address_mode(desc.address_v); create_info.addressModeW = convert_address_mode(desc.address_w); create_info.mipLodBias = desc.mip_lod_bias; create_info.maxAnisotropy = desc.max_anisotropy; create_info.compareOp = convert_compare_op(desc.compare_op); create_info.minLod = desc.min_lod; create_info.maxLod = desc.max_lod; const auto border_color_info = const_cast<VkSamplerCustomBorderColorCreateInfoEXT *>(find_in_structure_chain<VkSamplerCustomBorderColorCreateInfoEXT>( create_info.pNext, VK_STRUCTURE_TYPE_SAMPLER_CUSTOM_BORDER_COLOR_CREATE_INFO_EXT)); if (border_color_info != nullptr && create_info.borderColor == VK_BORDER_COLOR_FLOAT_CUSTOM_EXT) { std::copy_n(desc.border_color, 4, border_color_info->customBorderColor.float32); } } reshade::api::sampler_desc reshade::vulkan::convert_sampler_desc(const VkSamplerCreateInfo &create_info) { api::sampler_desc desc = {}; if (create_info.anisotropyEnable) { desc.filter = api::filter_mode::anisotropic; } else { switch (create_info.minFilter) { case VK_FILTER_NEAREST: switch (create_info.magFilter) { case VK_FILTER_NEAREST: switch (create_info.mipmapMode) { case VK_SAMPLER_MIPMAP_MODE_NEAREST: desc.filter = create_info.compareEnable ? api::filter_mode::compare_min_mag_mip_point : api::filter_mode::min_mag_mip_point; break; case VK_SAMPLER_MIPMAP_MODE_LINEAR: desc.filter = create_info.compareEnable ? api::filter_mode::compare_min_mag_point_mip_linear : api::filter_mode::min_mag_point_mip_linear; break; } break; case VK_FILTER_LINEAR: switch (create_info.mipmapMode) { case VK_SAMPLER_MIPMAP_MODE_NEAREST: desc.filter = create_info.compareEnable ? api::filter_mode::compare_min_point_mag_linear_mip_point : api::filter_mode::min_point_mag_linear_mip_point; break; case VK_SAMPLER_MIPMAP_MODE_LINEAR: desc.filter = create_info.compareEnable ? api::filter_mode::compare_min_point_mag_mip_linear : api::filter_mode::min_point_mag_mip_linear; break; } break; } break; case VK_FILTER_LINEAR: switch (create_info.magFilter) { case VK_FILTER_NEAREST: switch (create_info.mipmapMode) { case VK_SAMPLER_MIPMAP_MODE_NEAREST: desc.filter = create_info.compareEnable ? api::filter_mode::compare_min_linear_mag_mip_point : api::filter_mode::min_linear_mag_mip_point; break; case VK_SAMPLER_MIPMAP_MODE_LINEAR: desc.filter = create_info.compareEnable ? api::filter_mode::compare_min_linear_mag_point_mip_linear : api::filter_mode::min_linear_mag_point_mip_linear; break; } break; case VK_FILTER_LINEAR: switch (create_info.mipmapMode) { case VK_SAMPLER_MIPMAP_MODE_NEAREST: desc.filter = create_info.compareEnable ? api::filter_mode::compare_min_mag_linear_mip_point : api::filter_mode::min_mag_linear_mip_point; break; case VK_SAMPLER_MIPMAP_MODE_LINEAR: desc.filter = create_info.compareEnable ? api::filter_mode::compare_min_mag_mip_linear : api::filter_mode::min_mag_mip_linear; break; } break; } break; } } const auto convert_address_mode = [](VkSamplerAddressMode mode) { switch (mode) { default: assert(false); [[fallthrough]]; case VK_SAMPLER_ADDRESS_MODE_REPEAT: return api::texture_address_mode::wrap; case VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT: return api::texture_address_mode::mirror; case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE: return api::texture_address_mode::clamp; case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER: return api::texture_address_mode::border; case VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE: return api::texture_address_mode::mirror_once; } }; desc.address_u = convert_address_mode(create_info.addressModeU); desc.address_v = convert_address_mode(create_info.addressModeV); desc.address_w = convert_address_mode(create_info.addressModeW); desc.mip_lod_bias = create_info.mipLodBias; desc.max_anisotropy = create_info.maxAnisotropy; desc.compare_op = convert_compare_op(create_info.compareOp); desc.min_lod = create_info.minLod; desc.max_lod = create_info.maxLod; const auto border_color_info = find_in_structure_chain<VkSamplerCustomBorderColorCreateInfoEXT>( create_info.pNext, VK_STRUCTURE_TYPE_SAMPLER_CUSTOM_BORDER_COLOR_CREATE_INFO_EXT); switch (create_info.borderColor) { case VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK: case VK_BORDER_COLOR_INT_TRANSPARENT_BLACK: break; case VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK: case VK_BORDER_COLOR_INT_OPAQUE_BLACK: desc.border_color[3] = 1.0f; break; case VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE: case VK_BORDER_COLOR_INT_OPAQUE_WHITE: std::fill_n(desc.border_color, 4, 1.0f); break; case VK_BORDER_COLOR_FLOAT_CUSTOM_EXT: assert(border_color_info != nullptr); std::copy_n(border_color_info->customBorderColor.float32, 4, desc.border_color); break; case VK_BORDER_COLOR_INT_CUSTOM_EXT: assert(border_color_info != nullptr); for (int i = 0; i < 4; ++i) desc.border_color[i] = border_color_info->customBorderColor.int32[i] / 255.0f; break; } return desc; } void reshade::vulkan::convert_resource_desc(const api::resource_desc &desc, VkImageCreateInfo &create_info) { switch (desc.type) { default: assert(false); break; case api::resource_type::texture_1d: create_info.imageType = VK_IMAGE_TYPE_1D; create_info.extent = { desc.texture.width, 1u, 1u }; create_info.arrayLayers = desc.texture.depth_or_layers; break; case api::resource_type::texture_2d: create_info.imageType = VK_IMAGE_TYPE_2D; create_info.extent = { desc.texture.width, desc.texture.height, 1u }; create_info.arrayLayers = desc.texture.depth_or_layers; break; case api::resource_type::texture_3d: create_info.imageType = VK_IMAGE_TYPE_3D; create_info.extent = { desc.texture.width, desc.texture.height, desc.texture.depth_or_layers }; create_info.arrayLayers = 1u; break; } if (const VkFormat format = convert_format(desc.texture.format); format != VK_FORMAT_UNDEFINED) create_info.format = format; create_info.mipLevels = desc.texture.levels; create_info.samples = static_cast<VkSampleCountFlagBits>(desc.texture.samples); convert_usage_to_image_usage_flags(desc.usage, create_info.usage); // A typeless format indicates that views with different typed formats can be created, so set mutable flag if (desc.texture.format == api::format_to_typeless(desc.texture.format) && desc.texture.format != api::format_to_default_typed(desc.texture.format)) create_info.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT; if ((desc.flags & api::resource_flags::sparse_binding) == api::resource_flags::sparse_binding) create_info.flags |= VK_IMAGE_CREATE_SPARSE_BINDING_BIT | VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT; else create_info.flags &= ~(VK_IMAGE_CREATE_SPARSE_BINDING_BIT | VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT); if ((desc.flags & api::resource_flags::cube_compatible) == api::resource_flags::cube_compatible) create_info.flags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT; else create_info.flags &= ~VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT; // Mipmap generation is using 'vkCmdBlitImage' and therefore needs transfer usage flags (see 'command_list_impl::generate_mipmaps') if ((desc.flags & api::resource_flags::generate_mipmaps) == api::resource_flags::generate_mipmaps) create_info.usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; // Dynamic resources do not exist in Vulkan assert((desc.flags & api::resource_flags::dynamic) != api::resource_flags::dynamic); } void reshade::vulkan::convert_resource_desc(const api::resource_desc &desc, VkBufferCreateInfo &create_info) { assert(desc.type == api::resource_type::buffer); create_info.size = desc.buffer.size; convert_usage_to_buffer_usage_flags(desc.usage, create_info.usage); // Dynamic resources do not exist in Vulkan assert((desc.flags & api::resource_flags::dynamic) != api::resource_flags::dynamic); } reshade::api::resource_desc reshade::vulkan::convert_resource_desc(const VkImageCreateInfo &create_info) { api::resource_desc desc = {}; switch (create_info.imageType) { default: assert(false); desc.type = api::resource_type::unknown; break; case VK_IMAGE_TYPE_1D: desc.type = api::resource_type::texture_1d; desc.texture.width = create_info.extent.width; assert(create_info.extent.height == 1 && create_info.extent.depth == 1); desc.texture.height = 1; assert(create_info.arrayLayers <= std::numeric_limits<uint16_t>::max()); desc.texture.depth_or_layers = static_cast<uint16_t>(create_info.arrayLayers); break; case VK_IMAGE_TYPE_2D: desc.type = api::resource_type::texture_2d; desc.texture.width = create_info.extent.width; desc.texture.height = create_info.extent.height; assert(create_info.extent.depth == 1); assert(create_info.arrayLayers <= std::numeric_limits<uint16_t>::max()); desc.texture.depth_or_layers = static_cast<uint16_t>(create_info.arrayLayers); break; case VK_IMAGE_TYPE_3D: desc.type = api::resource_type::texture_3d; desc.texture.width = create_info.extent.width; desc.texture.height = create_info.extent.height; assert(create_info.extent.depth <= std::numeric_limits<uint16_t>::max()); desc.texture.depth_or_layers = static_cast<uint16_t>(create_info.extent.depth); assert(create_info.arrayLayers == 1); break; } assert(create_info.mipLevels <= std::numeric_limits<uint16_t>::max()); desc.texture.levels = static_cast<uint16_t>(create_info.mipLevels); desc.texture.format = convert_format(create_info.format); desc.texture.samples = static_cast<uint16_t>(create_info.samples); convert_image_usage_flags_to_usage(create_info.usage, desc.usage); if (desc.type == api::resource_type::texture_2d && ( create_info.usage & (desc.texture.samples > 1 ? VK_IMAGE_USAGE_TRANSFER_SRC_BIT : VK_IMAGE_USAGE_TRANSFER_DST_BIT)) != 0) desc.usage |= desc.texture.samples > 1 ? api::resource_usage::resolve_source : api::resource_usage::resolve_dest; if ((create_info.flags & VK_IMAGE_CREATE_SPARSE_BINDING_BIT) != 0) desc.flags |= api::resource_flags::sparse_binding; if ((create_info.flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT) != 0) desc.texture.format = api::format_to_typeless(desc.texture.format); if ((create_info.flags & VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT) != 0) desc.flags |= api::resource_flags::cube_compatible; // Images that have both transfer usage flags are usable with the 'generate_mipmaps' function if (create_info.mipLevels > 1 && (create_info.usage & (VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT)) == (VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT)) desc.flags |= api::resource_flags::generate_mipmaps; return desc; } reshade::api::resource_desc reshade::vulkan::convert_resource_desc(const VkBufferCreateInfo &create_info) { api::resource_desc desc = {}; desc.type = api::resource_type::buffer; desc.buffer.size = create_info.size; convert_buffer_usage_flags_to_usage(create_info.usage, desc.usage); return desc; } void reshade::vulkan::convert_resource_view_desc(const api::resource_view_desc &desc, VkImageViewCreateInfo &create_info) { switch (desc.type) { default: assert(false); break; case api::resource_view_type::texture_1d: create_info.viewType = VK_IMAGE_VIEW_TYPE_1D; break; case api::resource_view_type::texture_1d_array: create_info.viewType = VK_IMAGE_VIEW_TYPE_1D_ARRAY; break; case api::resource_view_type::texture_2d: create_info.viewType = VK_IMAGE_VIEW_TYPE_2D; break; case api::resource_view_type::texture_2d_array: create_info.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY; break; case api::resource_view_type::texture_3d: create_info.viewType = VK_IMAGE_VIEW_TYPE_3D; break; case api::resource_view_type::texture_cube: create_info.viewType = VK_IMAGE_VIEW_TYPE_CUBE; break; case api::resource_view_type::texture_cube_array: create_info.viewType = VK_IMAGE_VIEW_TYPE_CUBE_ARRAY; break; } if (const VkFormat format = convert_format(desc.format); format != VK_FORMAT_UNDEFINED) create_info.format = format; create_info.subresourceRange.baseMipLevel = desc.texture.first_level; create_info.subresourceRange.levelCount = desc.texture.level_count; create_info.subresourceRange.baseArrayLayer = desc.texture.first_layer; create_info.subresourceRange.layerCount = desc.texture.layer_count; } void reshade::vulkan::convert_resource_view_desc(const api::resource_view_desc &desc, VkBufferViewCreateInfo &create_info) { assert(desc.type == api::resource_view_type::buffer); if (const VkFormat format = convert_format(desc.format); format != VK_FORMAT_UNDEFINED) create_info.format = format; create_info.offset = desc.buffer.offset; create_info.range = desc.buffer.size; } reshade::api::resource_view_desc reshade::vulkan::convert_resource_view_desc(const VkImageViewCreateInfo &create_info) { api::resource_view_desc desc = {}; switch (create_info.viewType) { default: assert(false); desc.type = api::resource_view_type::unknown; break; case VK_IMAGE_VIEW_TYPE_1D: desc.type = api::resource_view_type::texture_1d; break; case VK_IMAGE_VIEW_TYPE_1D_ARRAY: desc.type = api::resource_view_type::texture_1d_array; break; case VK_IMAGE_VIEW_TYPE_2D: desc.type = api::resource_view_type::texture_2d; break; case VK_IMAGE_VIEW_TYPE_2D_ARRAY: desc.type = api::resource_view_type::texture_2d_array; break; case VK_IMAGE_VIEW_TYPE_3D: desc.type = api::resource_view_type::texture_3d; break; case VK_IMAGE_VIEW_TYPE_CUBE: desc.type = api::resource_view_type::texture_cube; break; case VK_IMAGE_VIEW_TYPE_CUBE_ARRAY: desc.type = api::resource_view_type::texture_cube_array; break; } desc.format = convert_format(create_info.format); desc.texture.first_level = create_info.subresourceRange.baseMipLevel; desc.texture.level_count = create_info.subresourceRange.levelCount; desc.texture.first_layer = create_info.subresourceRange.baseArrayLayer; desc.texture.layer_count = create_info.subresourceRange.layerCount; return desc; } reshade::api::resource_view_desc reshade::vulkan::convert_resource_view_desc(const VkBufferViewCreateInfo &create_info) { api::resource_view_desc desc = {}; desc.type = api::resource_view_type::buffer; desc.format = convert_format(create_info.format); desc.buffer.offset = create_info.offset; desc.buffer.size = create_info.sType; return desc; } reshade::api::pipeline_desc reshade::vulkan::device_impl::convert_pipeline_desc(const VkComputePipelineCreateInfo &create_info) const { api::pipeline_desc desc = { api::pipeline_stage::all_compute }; desc.layout = { (uint64_t)create_info.layout }; const auto module_data = get_user_data_for_object<VK_OBJECT_TYPE_SHADER_MODULE>(create_info.stage.module); assert(create_info.stage.stage == VK_SHADER_STAGE_COMPUTE_BIT); desc.compute.shader.code = module_data->spirv.data(); desc.compute.shader.code_size = module_data->spirv.size(); desc.compute.shader.entry_point = create_info.stage.pName; return desc; } reshade::api::pipeline_desc reshade::vulkan::device_impl::convert_pipeline_desc(const VkGraphicsPipelineCreateInfo &create_info) const { bool has_tessellation_shader_stage = false; api::pipeline_desc desc = { api::pipeline_stage::all_graphics }; desc.layout = { (uint64_t)create_info.layout }; for (uint32_t i = 0; i < create_info.stageCount; ++i) { const VkPipelineShaderStageCreateInfo &stage = create_info.pStages[i]; const auto module_data = get_user_data_for_object<VK_OBJECT_TYPE_SHADER_MODULE>(stage.module); switch (stage.stage) { case VK_SHADER_STAGE_VERTEX_BIT: desc.graphics.vertex_shader.code = module_data->spirv.data(); desc.graphics.vertex_shader.code_size = module_data->spirv.size(); desc.graphics.vertex_shader.entry_point = stage.pName; break; case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT: has_tessellation_shader_stage = true; desc.graphics.hull_shader.code = module_data->spirv.data(); desc.graphics.hull_shader.code_size = module_data->spirv.size(); desc.graphics.hull_shader.entry_point = stage.pName; break; case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT: has_tessellation_shader_stage = true; desc.graphics.domain_shader.code = module_data->spirv.data(); desc.graphics.domain_shader.code_size = module_data->spirv.size(); desc.graphics.domain_shader.entry_point = stage.pName; break; case VK_SHADER_STAGE_GEOMETRY_BIT: desc.graphics.geometry_shader.code = module_data->spirv.data(); desc.graphics.geometry_shader.code_size = module_data->spirv.size(); desc.graphics.geometry_shader.entry_point = stage.pName; break; case VK_SHADER_STAGE_FRAGMENT_BIT: desc.graphics.pixel_shader.code = module_data->spirv.data(); desc.graphics.pixel_shader.code_size = module_data->spirv.size(); desc.graphics.pixel_shader.entry_point = stage.pName; break; } } if (create_info.pVertexInputState != nullptr) { const VkPipelineVertexInputStateCreateInfo &vertex_input_state_info = *create_info.pVertexInputState; for (uint32_t a = 0; a < vertex_input_state_info.vertexAttributeDescriptionCount; ++a) { const VkVertexInputAttributeDescription &attribute = vertex_input_state_info.pVertexAttributeDescriptions[a]; desc.graphics.input_layout[a].location = attribute.location; desc.graphics.input_layout[a].format = convert_format(attribute.format); desc.graphics.input_layout[a].buffer_binding = attribute.binding; desc.graphics.input_layout[a].offset = attribute.offset; for (uint32_t b = 0; b < vertex_input_state_info.vertexBindingDescriptionCount; ++b) { const VkVertexInputBindingDescription &binding = vertex_input_state_info.pVertexBindingDescriptions[b]; if (binding.binding == attribute.binding) { desc.graphics.input_layout[a].stride = binding.stride; desc.graphics.input_layout[a].instance_step_rate = binding.inputRate != VK_VERTEX_INPUT_RATE_VERTEX ? 1 : 0; break; } } } } if (create_info.pInputAssemblyState != nullptr) { const VkPipelineInputAssemblyStateCreateInfo &input_assembly_state_info = *create_info.pInputAssemblyState; desc.graphics.topology = convert_primitive_topology(input_assembly_state_info.topology); } if (has_tessellation_shader_stage && create_info.pTessellationState != nullptr) { const VkPipelineTessellationStateCreateInfo &tessellation_state_info = *create_info.pTessellationState; assert(desc.graphics.topology == api::primitive_topology::patch_list_01_cp); desc.graphics.topology = static_cast<api::primitive_topology>(static_cast<uint32_t>(api::primitive_topology::patch_list_01_cp) + tessellation_state_info.patchControlPoints - 1); } if (create_info.pViewportState != nullptr) { const VkPipelineViewportStateCreateInfo &viewport_state_info = *create_info.pViewportState; desc.graphics.viewport_count = viewport_state_info.viewportCount; } if (create_info.pRasterizationState != nullptr) { const VkPipelineRasterizationStateCreateInfo &rasterization_state_info = *create_info.pRasterizationState; desc.graphics.rasterizer_state.fill_mode = convert_fill_mode(rasterization_state_info.polygonMode); desc.graphics.rasterizer_state.cull_mode = convert_cull_mode(rasterization_state_info.cullMode); desc.graphics.rasterizer_state.front_counter_clockwise = rasterization_state_info.frontFace == VK_FRONT_FACE_COUNTER_CLOCKWISE; desc.graphics.rasterizer_state.depth_bias = rasterization_state_info.depthBiasConstantFactor; desc.graphics.rasterizer_state.depth_bias_clamp = rasterization_state_info.depthBiasClamp; desc.graphics.rasterizer_state.slope_scaled_depth_bias = rasterization_state_info.depthBiasSlopeFactor; desc.graphics.rasterizer_state.depth_clip_enable = !rasterization_state_info.depthClampEnable; desc.graphics.rasterizer_state.scissor_enable = true; const auto conservative_rasterization_info = find_in_structure_chain<VkPipelineRasterizationConservativeStateCreateInfoEXT>( rasterization_state_info.pNext, VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_CONSERVATIVE_STATE_CREATE_INFO_EXT); if (conservative_rasterization_info != nullptr) { desc.graphics.rasterizer_state.conservative_rasterization = static_cast<uint32_t>(conservative_rasterization_info->conservativeRasterizationMode); } } if (create_info.pMultisampleState != nullptr) { const VkPipelineMultisampleStateCreateInfo &multisample_state_info = *create_info.pMultisampleState; desc.graphics.blend_state.alpha_to_coverage_enable = multisample_state_info.alphaToCoverageEnable; desc.graphics.rasterizer_state.multisample_enable = multisample_state_info.rasterizationSamples != VK_SAMPLE_COUNT_1_BIT; if (multisample_state_info.pSampleMask != nullptr) desc.graphics.sample_mask = *multisample_state_info.pSampleMask; else desc.graphics.sample_mask = std::numeric_limits<uint32_t>::max(); } if (create_info.pDepthStencilState != nullptr) { const VkPipelineDepthStencilStateCreateInfo &depth_stencil_state_info = *create_info.pDepthStencilState; desc.graphics.depth_stencil_state.depth_enable = depth_stencil_state_info.depthTestEnable; desc.graphics.depth_stencil_state.depth_write_mask = depth_stencil_state_info.depthWriteEnable; desc.graphics.depth_stencil_state.depth_func = convert_compare_op(depth_stencil_state_info.depthCompareOp); desc.graphics.depth_stencil_state.stencil_enable = depth_stencil_state_info.stencilTestEnable; desc.graphics.depth_stencil_state.stencil_read_mask = depth_stencil_state_info.back.compareMask & 0xFF; desc.graphics.depth_stencil_state.stencil_write_mask = depth_stencil_state_info.back.writeMask & 0xFF; desc.graphics.depth_stencil_state.stencil_reference_value = depth_stencil_state_info.back.reference & 0xFF; desc.graphics.depth_stencil_state.back_stencil_fail_op = convert_stencil_op(depth_stencil_state_info.back.failOp); desc.graphics.depth_stencil_state.back_stencil_pass_op = convert_stencil_op(depth_stencil_state_info.back.passOp); desc.graphics.depth_stencil_state.back_stencil_depth_fail_op = convert_stencil_op(depth_stencil_state_info.back.depthFailOp); desc.graphics.depth_stencil_state.back_stencil_func = convert_compare_op(depth_stencil_state_info.back.compareOp); desc.graphics.depth_stencil_state.front_stencil_fail_op = convert_stencil_op(depth_stencil_state_info.front.failOp); desc.graphics.depth_stencil_state.front_stencil_pass_op = convert_stencil_op(depth_stencil_state_info.front.passOp); desc.graphics.depth_stencil_state.front_stencil_depth_fail_op = convert_stencil_op(depth_stencil_state_info.front.depthFailOp); desc.graphics.depth_stencil_state.front_stencil_func = convert_compare_op(depth_stencil_state_info.front.compareOp); } if (create_info.pColorBlendState != nullptr) { const VkPipelineColorBlendStateCreateInfo &color_blend_state_info = *create_info.pColorBlendState; std::copy_n(color_blend_state_info.blendConstants, 4, desc.graphics.blend_state.blend_constant); for (uint32_t a = 0; a < color_blend_state_info.attachmentCount; ++a) { const VkPipelineColorBlendAttachmentState &attachment = color_blend_state_info.pAttachments[a]; desc.graphics.blend_state.blend_enable[a] = attachment.blendEnable; desc.graphics.blend_state.logic_op_enable[a] = color_blend_state_info.logicOpEnable; desc.graphics.blend_state.color_blend_op[a] = convert_blend_op(attachment.colorBlendOp); desc.graphics.blend_state.source_color_blend_factor[a] = convert_blend_factor(attachment.srcColorBlendFactor); desc.graphics.blend_state.dest_color_blend_factor[a] = convert_blend_factor(attachment.dstColorBlendFactor); desc.graphics.blend_state.alpha_blend_op[a] = convert_blend_op(attachment.alphaBlendOp); desc.graphics.blend_state.source_alpha_blend_factor[a] = convert_blend_factor(attachment.srcAlphaBlendFactor); desc.graphics.blend_state.dest_alpha_blend_factor[a] = convert_blend_factor(attachment.dstAlphaBlendFactor); desc.graphics.blend_state.logic_op[a] = convert_logic_op(color_blend_state_info.logicOp); desc.graphics.blend_state.render_target_write_mask[a] = static_cast<uint8_t>(attachment.colorWriteMask); } } return desc; } void reshade::vulkan::convert_dynamic_states(const VkPipelineDynamicStateCreateInfo &create_info, std::vector<reshade::api::dynamic_state> &states) { states.reserve(create_info.dynamicStateCount); for (uint32_t i = 0; i < create_info.dynamicStateCount; ++i) { switch (create_info.pDynamicStates[i]) { case VK_DYNAMIC_STATE_DEPTH_BIAS: states.push_back(api::dynamic_state::depth_bias); states.push_back(api::dynamic_state::depth_bias_clamp); states.push_back(api::dynamic_state::depth_bias_slope_scaled); break; case VK_DYNAMIC_STATE_BLEND_CONSTANTS: states.push_back(api::dynamic_state::blend_constant); break; case VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK: states.push_back(api::dynamic_state::stencil_read_mask); break; case VK_DYNAMIC_STATE_STENCIL_WRITE_MASK: states.push_back(api::dynamic_state::stencil_write_mask); break; case VK_DYNAMIC_STATE_STENCIL_REFERENCE: states.push_back(api::dynamic_state::stencil_reference_value); break; case VK_DYNAMIC_STATE_CULL_MODE_EXT: states.push_back(api::dynamic_state::cull_mode); break; case VK_DYNAMIC_STATE_FRONT_FACE_EXT: states.push_back(api::dynamic_state::front_counter_clockwise); break; case VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY_EXT: states.push_back(api::dynamic_state::primitive_topology); break; case VK_DYNAMIC_STATE_DEPTH_TEST_ENABLE_EXT: states.push_back(api::dynamic_state::depth_enable); break; case VK_DYNAMIC_STATE_DEPTH_WRITE_ENABLE_EXT: states.push_back(api::dynamic_state::depth_write_mask); break; case VK_DYNAMIC_STATE_DEPTH_COMPARE_OP_EXT: states.push_back(api::dynamic_state::depth_func); break; case VK_DYNAMIC_STATE_DEPTH_BOUNDS_TEST_ENABLE_EXT: states.push_back(api::dynamic_state::depth_clip_enable); break; case VK_DYNAMIC_STATE_STENCIL_TEST_ENABLE_EXT: states.push_back(api::dynamic_state::stencil_enable); break; case VK_DYNAMIC_STATE_STENCIL_OP_EXT: states.push_back(api::dynamic_state::back_stencil_func); states.push_back(api::dynamic_state::front_stencil_func); break; case VK_DYNAMIC_STATE_LOGIC_OP_EXT: states.push_back(api::dynamic_state::logic_op); break; case VK_DYNAMIC_STATE_COLOR_WRITE_ENABLE_EXT: states.push_back(api::dynamic_state::render_target_write_mask); break; } } } auto reshade::vulkan::convert_logic_op(api::logic_op value) -> VkLogicOp { return static_cast<VkLogicOp>(value); } auto reshade::vulkan::convert_logic_op(VkLogicOp value) -> api::logic_op { return static_cast<api::logic_op>(value); } auto reshade::vulkan::convert_blend_op(api::blend_op value) -> VkBlendOp { return static_cast<VkBlendOp>(value); } auto reshade::vulkan::convert_blend_op(VkBlendOp value) -> api::blend_op { return static_cast<api::blend_op>(value); } auto reshade::vulkan::convert_blend_factor(api::blend_factor value) -> VkBlendFactor { return static_cast<VkBlendFactor>(value); } auto reshade::vulkan::convert_blend_factor(VkBlendFactor value) -> api::blend_factor { return static_cast<api::blend_factor>(value); } auto reshade::vulkan::convert_fill_mode(api::fill_mode value) -> VkPolygonMode { switch (value) { case api::fill_mode::point: return VK_POLYGON_MODE_POINT; case api::fill_mode::wireframe: return VK_POLYGON_MODE_LINE; default: assert(false); [[fallthrough]]; case api::fill_mode::solid: return VK_POLYGON_MODE_FILL; } } auto reshade::vulkan::convert_fill_mode(VkPolygonMode value) -> api::fill_mode { switch (value) { default: assert(false); [[fallthrough]]; case VK_POLYGON_MODE_FILL: return api::fill_mode::solid; case VK_POLYGON_MODE_LINE: return api::fill_mode::wireframe; case VK_POLYGON_MODE_POINT: return api::fill_mode::point; } } auto reshade::vulkan::convert_cull_mode(api::cull_mode value) -> VkCullModeFlags { return static_cast<VkCullModeFlags>(value); } auto reshade::vulkan::convert_cull_mode(VkCullModeFlags value) -> api::cull_mode { return static_cast<api::cull_mode>(value); } auto reshade::vulkan::convert_compare_op(api::compare_op value) -> VkCompareOp { return static_cast<VkCompareOp>(value); } auto reshade::vulkan::convert_compare_op(VkCompareOp value) -> api::compare_op { return static_cast<api::compare_op>(value); } auto reshade::vulkan::convert_stencil_op(api::stencil_op value) -> VkStencilOp { return static_cast<VkStencilOp>(value); } auto reshade::vulkan::convert_stencil_op(VkStencilOp value) -> api::stencil_op { return static_cast<api::stencil_op>(value); } auto reshade::vulkan::convert_primitive_topology(api::primitive_topology value) -> VkPrimitiveTopology { switch (value) { default: case api::primitive_topology::undefined: assert(false); return VK_PRIMITIVE_TOPOLOGY_MAX_ENUM; case api::primitive_topology::point_list: return VK_PRIMITIVE_TOPOLOGY_POINT_LIST; case api::primitive_topology::line_list: return VK_PRIMITIVE_TOPOLOGY_LINE_LIST; case api::primitive_topology::line_strip: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP; case api::primitive_topology::triangle_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; case api::primitive_topology::triangle_strip: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; case api::primitive_topology::triangle_fan: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN; case api::primitive_topology::line_list_adj: return VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY; case api::primitive_topology::line_strip_adj: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY; case api::primitive_topology::triangle_list_adj: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY; case api::primitive_topology::triangle_strip_adj: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY; case api::primitive_topology::patch_list_01_cp: case api::primitive_topology::patch_list_02_cp: case api::primitive_topology::patch_list_03_cp: case api::primitive_topology::patch_list_04_cp: case api::primitive_topology::patch_list_05_cp: case api::primitive_topology::patch_list_06_cp: case api::primitive_topology::patch_list_07_cp: case api::primitive_topology::patch_list_08_cp: case api::primitive_topology::patch_list_09_cp: case api::primitive_topology::patch_list_10_cp: case api::primitive_topology::patch_list_11_cp: case api::primitive_topology::patch_list_12_cp: case api::primitive_topology::patch_list_13_cp: case api::primitive_topology::patch_list_14_cp: case api::primitive_topology::patch_list_15_cp: case api::primitive_topology::patch_list_16_cp: case api::primitive_topology::patch_list_17_cp: case api::primitive_topology::patch_list_18_cp: case api::primitive_topology::patch_list_19_cp: case api::primitive_topology::patch_list_20_cp: case api::primitive_topology::patch_list_21_cp: case api::primitive_topology::patch_list_22_cp: case api::primitive_topology::patch_list_23_cp: case api::primitive_topology::patch_list_24_cp: case api::primitive_topology::patch_list_25_cp: case api::primitive_topology::patch_list_26_cp: case api::primitive_topology::patch_list_27_cp: case api::primitive_topology::patch_list_28_cp: case api::primitive_topology::patch_list_29_cp: case api::primitive_topology::patch_list_30_cp: case api::primitive_topology::patch_list_31_cp: case api::primitive_topology::patch_list_32_cp: return VK_PRIMITIVE_TOPOLOGY_PATCH_LIST; } } auto reshade::vulkan::convert_primitive_topology(VkPrimitiveTopology value) -> api::primitive_topology { switch (value) { default: case VK_PRIMITIVE_TOPOLOGY_MAX_ENUM: assert(false); return api::primitive_topology::undefined; case VK_PRIMITIVE_TOPOLOGY_POINT_LIST: return api::primitive_topology::point_list; case VK_PRIMITIVE_TOPOLOGY_LINE_LIST: return api::primitive_topology::line_list; case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP: return api::primitive_topology::line_strip; case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST: return api::primitive_topology::triangle_list; case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP: return api::primitive_topology::triangle_strip; case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN: return api::primitive_topology::triangle_fan; case VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY: return api::primitive_topology::line_list_adj; case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY: return api::primitive_topology::line_strip_adj; case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY: return api::primitive_topology::triangle_list_adj; case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY: return api::primitive_topology::triangle_strip_adj; case VK_PRIMITIVE_TOPOLOGY_PATCH_LIST: return api::primitive_topology::patch_list_01_cp; } } auto reshade::vulkan::convert_query_type(api::query_type type) -> VkQueryType { switch (type) { case api::query_type::occlusion: case api::query_type::binary_occlusion: return VK_QUERY_TYPE_OCCLUSION; case api::query_type::timestamp: return VK_QUERY_TYPE_TIMESTAMP; case api::query_type::pipeline_statistics: return VK_QUERY_TYPE_PIPELINE_STATISTICS; default: assert(false); return VK_QUERY_TYPE_MAX_ENUM; } } auto reshade::vulkan::convert_descriptor_type(api::descriptor_type value, bool is_image) -> VkDescriptorType { switch (value) { case api::descriptor_type::sampler: return VK_DESCRIPTOR_TYPE_SAMPLER; case api::descriptor_type::sampler_with_resource_view: assert(is_image); return VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; case api::descriptor_type::shader_resource_view: return is_image ? VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE : VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER; case api::descriptor_type::unordered_access_view: return is_image ? VK_DESCRIPTOR_TYPE_STORAGE_IMAGE : VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER; case api::descriptor_type::constant_buffer: return VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; case api::descriptor_type::shader_storage_buffer: return VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; default: assert(false); return static_cast<VkDescriptorType>(value); } } auto reshade::vulkan::convert_descriptor_type(VkDescriptorType value) -> api::descriptor_type { switch (value) { case VK_DESCRIPTOR_TYPE_SAMPLER: return api::descriptor_type::sampler; case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: return api::descriptor_type::sampler_with_resource_view; case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE: case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: return api::descriptor_type::shader_resource_view; case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: return api::descriptor_type::unordered_access_view; case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER: case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC: return api::descriptor_type::constant_buffer; case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER: case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: return api::descriptor_type::shader_storage_buffer; default: assert(false); return static_cast<api::descriptor_type>(value); } } auto reshade::vulkan::convert_attachment_type(api::attachment_type value) -> VkImageAspectFlags { VkImageAspectFlags flags = 0; if ((value & api::attachment_type::color) == api::attachment_type::color) flags |= VK_IMAGE_ASPECT_COLOR_BIT; if ((value & api::attachment_type::depth) == api::attachment_type::depth) flags |= VK_IMAGE_ASPECT_DEPTH_BIT; if ((value & api::attachment_type::stencil) == api::attachment_type::stencil) flags |= VK_IMAGE_ASPECT_STENCIL_BIT; return flags; } auto reshade::vulkan::convert_attachment_load_op(api::attachment_load_op value) -> VkAttachmentLoadOp { switch (value) { case api::attachment_load_op::load: return VK_ATTACHMENT_LOAD_OP_LOAD; case api::attachment_load_op::clear: return VK_ATTACHMENT_LOAD_OP_CLEAR; default: assert(false); [[fallthrough]]; case api::attachment_load_op::discard: case api::attachment_load_op::dont_care: return VK_ATTACHMENT_LOAD_OP_DONT_CARE; } } auto reshade::vulkan::convert_attachment_load_op(VkAttachmentLoadOp value) -> api::attachment_load_op { switch (value) { case VK_ATTACHMENT_LOAD_OP_LOAD: return api::attachment_load_op::load; case VK_ATTACHMENT_LOAD_OP_CLEAR: return api::attachment_load_op::clear; default: assert(false); [[fallthrough]]; case VK_ATTACHMENT_LOAD_OP_DONT_CARE: return api::attachment_load_op::dont_care; } } auto reshade::vulkan::convert_attachment_store_op(api::attachment_store_op value) -> VkAttachmentStoreOp { switch (value) { case api::attachment_store_op::store: return VK_ATTACHMENT_STORE_OP_STORE; default: assert(false); [[fallthrough]]; case api::attachment_store_op::discard: case api::attachment_store_op::dont_care: return VK_ATTACHMENT_STORE_OP_DONT_CARE; } } auto reshade::vulkan::convert_attachment_store_op(VkAttachmentStoreOp value) -> api::attachment_store_op { switch (value) { case VK_ATTACHMENT_STORE_OP_STORE: return api::attachment_store_op::store; default: assert(false); [[fallthrough]]; case VK_ATTACHMENT_STORE_OP_DONT_CARE: return api::attachment_store_op::dont_care; } }
39.963964
318
0.803817
Meme-sys
4f450e4aa328322bb4d00a8d0d61f8b7d33f6405
1,298
hpp
C++
drape/vulkan/vulkan_staging_buffer.hpp
kudlav/organicmaps
390236365749e0525b9229684132c2888d11369d
[ "Apache-2.0" ]
4,879
2015-09-30T10:56:36.000Z
2022-03-31T18:43:03.000Z
drape/vulkan/vulkan_staging_buffer.hpp
mbrukman/omim
d22fe2b6e0beee697f096e931df97a64f9db9dc1
[ "Apache-2.0" ]
7,549
2015-09-30T10:52:53.000Z
2022-03-31T22:04:22.000Z
drape/vulkan/vulkan_staging_buffer.hpp
mbrukman/omim
d22fe2b6e0beee697f096e931df97a64f9db9dc1
[ "Apache-2.0" ]
1,493
2015-09-30T10:43:06.000Z
2022-03-21T09:16:49.000Z
#pragma once #include "drape/pointers.hpp" #include "drape/vulkan/vulkan_object_manager.hpp" #include "base/thread_checker.hpp" #include <vulkan_wrapper.h> #include <vulkan/vulkan.h> #include <cstdint> #include <string> #include <vector> namespace dp { namespace vulkan { class VulkanStagingBuffer { public: VulkanStagingBuffer(ref_ptr<VulkanObjectManager> objectManager, uint32_t sizeInBytes); ~VulkanStagingBuffer(); struct StagingData { VkBuffer m_stagingBuffer = {}; uint8_t * m_pointer = nullptr; uint32_t m_offset = 0; uint32_t m_size = 0; operator bool() const { return m_stagingBuffer != 0 && m_pointer != nullptr; } }; bool HasEnoughSpace(uint32_t sizeInBytes) const; StagingData Reserve(uint32_t sizeInBytes); uint32_t ReserveWithId(uint32_t sizeInBytes, StagingData & data); StagingData const & GetReservationById(uint32_t id) const; void Flush(); void Reset(); private: ref_ptr<VulkanObjectManager> m_objectManager; uint32_t m_sizeInBytes; VulkanObject m_object; uint32_t m_offsetAlignment = 0; uint32_t m_sizeAlignment = 0; uint8_t * m_pointer = nullptr; uint32_t m_offset = 0; std::vector<StagingData> m_reservation; ThreadChecker m_threadChecker; }; } // namespace vulkan } // namespace dp
23.178571
82
0.734977
kudlav
4f466eef0ecf08c25cce8d23e0725fcae85b11ae
25,666
cpp
C++
src/slg/shapes/strands.cpp
tschw/LuxCore
111009811c31a74595e25c290bfaa7d715db4192
[ "Apache-2.0" ]
null
null
null
src/slg/shapes/strands.cpp
tschw/LuxCore
111009811c31a74595e25c290bfaa7d715db4192
[ "Apache-2.0" ]
null
null
null
src/slg/shapes/strands.cpp
tschw/LuxCore
111009811c31a74595e25c290bfaa7d715db4192
[ "Apache-2.0" ]
null
null
null
/*************************************************************************** * Copyright 1998-2018 by authors (see AUTHORS.txt) * * * * This file is part of LuxCoreRender. * * * * 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 "slg/shapes/strands.h" #include "slg/scene/scene.h" #include "slg/cameras/perspective.h" using namespace std; using namespace luxrays; using namespace slg; //------------------------------------------------------------------------------ // CatmullRomCurve class definition //------------------------------------------------------------------------------ class CatmullRomCurve { public: CatmullRomCurve() { } ~CatmullRomCurve() { } void AddPoint(const Point &p, const float size, const Spectrum &col, const float transp, const UV &uv) { points.push_back(p); sizes.push_back(size); cols.push_back(col); transps.push_back(transp); uvs.push_back(uv); } void AdaptiveTessellate(const u_int maxDepth, const float error, vector<float> &values) { values.push_back(0.f); AdaptiveTessellate(0, maxDepth, error, values, 0.f, 1.f); values.push_back(1.f); sort(values.begin(), values.end()); } Point EvaluatePoint(const float t) { const int count = (int)points.size(); if (count > 2) { int segment = Floor2Int((count - 1) * t); segment = max(segment, 0); segment = min(segment, count - 2); const float ct = t * (count - 1) - segment; if (segment == 0) return CatmullRomSpline(points[0], points[0], points[1], points[2], ct); if (segment == count - 2) return CatmullRomSpline(points[count - 3], points[count - 2], points[count - 1], points[count - 1], ct); return CatmullRomSpline(points[segment - 1], points[segment], points[segment + 1], points[segment + 2], ct); } else if (count == 2) return (1.f - t) * points[0] + t * points[1]; else if (count == 1) return points[0]; else throw runtime_error("Internal error in CatmullRomCurve::EvaluatePoint()"); } float EvaluateSize(const float t) { int count = (int)sizes.size(); if (count > 2) { int segment = Floor2Int((count - 1) * t); segment = max(segment, 0); segment = min(segment, count - 2); const float ct = t * (count - 1) - segment; if (segment == 0) return CatmullRomSpline(sizes[0], sizes[0], sizes[1], sizes[2], ct); if (segment == count - 2) return CatmullRomSpline(sizes[count - 3], sizes[count - 2], sizes[count - 1], sizes[count - 1], ct); return CatmullRomSpline(sizes[segment - 1], sizes[segment], sizes[segment + 1], sizes[segment + 2], ct); } else if (count == 2) return (1.f - t) * sizes[0] + t * sizes[1]; else if (count == 1) return sizes[0]; else throw runtime_error("Internal error in CatmullRomCurve::EvaluateSize()"); } Spectrum EvaluateColor(const float t) { int count = (int)cols.size(); if (count > 2) { int segment = Floor2Int((count - 1) * t); segment = max(segment, 0); segment = min(segment, count - 2); const float ct = t * (count - 1) - segment; if (segment == 0) return CatmullRomSpline(cols[0], cols[0], cols[1], cols[2], ct); if (segment == count - 2) return CatmullRomSpline(cols[count - 3], cols[count - 2], cols[count - 1], cols[count - 1], ct); return CatmullRomSpline(cols[segment - 1], cols[segment], cols[segment + 1], cols[segment + 2], ct); } else if (count == 2) return (1.f - t) * cols[0] + t * cols[1]; else if (count == 1) return cols[0]; else throw runtime_error("Internal error in CatmullRomCurve::EvaluateColor()"); } float EvaluateTransparency(const float t) { int count = (int)transps.size(); if (count > 2) { int segment = Floor2Int((count - 1) * t); segment = max(segment, 0); segment = min(segment, count - 2); const float ct = t * (count - 1) - segment; if (segment == 0) return CatmullRomSpline(transps[0], transps[0], transps[1], transps[2], ct); if (segment == count - 2) return CatmullRomSpline(transps[count - 3], transps[count - 2], transps[count - 1], transps[count - 1], ct); return CatmullRomSpline(transps[segment - 1], transps[segment], transps[segment + 1], transps[segment + 2], ct); } else if (count == 2) return (1.f - t) * transps[0] + t * transps[1]; else if (count == 1) return transps[0]; else throw runtime_error("Internal error in CatmullRomCurve::EvaluateTransparency()"); } UV EvaluateUV(const float t) { int count = (int)uvs.size(); if (count > 2) { int segment = Floor2Int((count - 1) * t); segment = max(segment, 0); segment = min(segment, count - 2); const float ct = t * (count - 1) - segment; if (segment == 0) return CatmullRomSpline(uvs[0], uvs[0], uvs[1], uvs[2], ct); if (segment == count - 2) return CatmullRomSpline(uvs[count - 3], uvs[count - 2], uvs[count - 1], uvs[count - 1], ct); return CatmullRomSpline(uvs[segment - 1], uvs[segment], uvs[segment + 1], uvs[segment + 2], ct); } else if (count == 2) return (1.f - t) * uvs[0] + t * uvs[1]; else if (count == 1) return uvs[0]; else throw runtime_error("Internal error in CatmullRomCurve::EvaluateUV()"); } private: bool AdaptiveTessellate(const u_int depth, const u_int maxDepth, const float error, vector<float> &values, const float t0, const float t1) { if (depth >= maxDepth) return false; const float tmid = (t0 + t1) * .5f; const Point p0 = EvaluatePoint(t0); const Point pmid = EvaluatePoint(tmid); const Point p1 = EvaluatePoint(t1); const Vector vmid = pmid - p0; const Vector v = p1 - p0; // Check if the vectors are nearly parallel if (AbsDot(Normalize(vmid), Normalize(v)) < 1.f - .05f) { // Tessellate left side too const bool leftSide = AdaptiveTessellate(depth + 1, maxDepth, error, values, t0, tmid); const bool rightSide = AdaptiveTessellate(depth + 1, maxDepth, error, values, tmid, t1); if (leftSide || rightSide) values.push_back(tmid); return false; } //---------------------------------------------------------------------- // Curve flatness check //---------------------------------------------------------------------- // Calculate the distance between vmid and the segment const float distance = Cross(v, vmid).Length() / vmid.Length(); // Check if the distance normalized with the segment length is // over the required error const float segmentLength = v.Length(); if (distance / segmentLength > error) { // Tessellate left side too AdaptiveTessellate(depth + 1, maxDepth, error, values, t0, tmid); values.push_back(tmid); // Tessellate right side too AdaptiveTessellate(depth + 1, maxDepth, error, values, tmid, t1); return true; } //---------------------------------------------------------------------- // Curve size check //---------------------------------------------------------------------- const float s0 = EvaluateSize(t0); const float smid = EvaluateSize(tmid); const float s1 = EvaluateSize(t1); const float expectedSize = (s0 + s1) * .5f; if (fabsf(expectedSize - smid) > error) { // Tessellate left side too AdaptiveTessellate(depth + 1, maxDepth, error, values, t0, tmid); values.push_back(tmid); // Tessellate right side too AdaptiveTessellate(depth + 1, maxDepth, error, values, tmid, t1); return true; } return false; } float CatmullRomSpline(const float a, const float b, const float c, const float d, const float t) { const float t1 = (c - a) * .5f; const float t2 = (d - b) * .5f; const float h1 = +2 * t * t * t - 3 * t * t + 1; const float h2 = -2 * t * t * t + 3 * t * t; const float h3 = t * t * t - 2 * t * t + t; const float h4 = t * t * t - t * t; return b * h1 + c * h2 + t1 * h3 + t2 * h4; } Point CatmullRomSpline(const Point a, const Point b, const Point c, const Point d, const float t) { return Point( CatmullRomSpline(a.x, b.x, c.x, d.x, t), CatmullRomSpline(a.y, b.y, c.y, d.y, t), CatmullRomSpline(a.z, b.z, c.z, d.z, t)); } Spectrum CatmullRomSpline(const Spectrum a, const Spectrum b, const Spectrum c, const Spectrum d, const float t) { return Spectrum( Clamp(CatmullRomSpline(a.c[0], b.c[0], c.c[0], d.c[0], t), 0.f, 1.f), Clamp(CatmullRomSpline(a.c[1], b.c[1], c.c[1], d.c[1], t), 0.f, 1.f), Clamp(CatmullRomSpline(a.c[2], b.c[2], c.c[2], d.c[2], t), 0.f, 1.f)); } UV CatmullRomSpline(const UV a, const UV b, const UV c, const UV d, const float t) { return UV( Clamp(CatmullRomSpline(a.u, b.u, c.u, d.u, t), 0.f, 1.f), Clamp(CatmullRomSpline(a.v, b.v, c.v, d.v, t), 0.f, 1.f)); } vector<Point> points; vector<float> sizes; vector<Spectrum> cols; vector<float> transps; vector<UV> uvs; }; //------------------------------------------------------------------------------ // StrendsShape methods //------------------------------------------------------------------------------ StrendsShape::StrendsShape(const Scene *scene, const cyHairFile *hairFile, const TessellationType tesselType, const u_int aMaxDepth, const float aError, const u_int sSideCount, const bool sCapBottom, const bool sCapTop, const bool useCamPos) : Shape(), mesh(NULL) { adaptiveMaxDepth = aMaxDepth; adaptiveError = aError; solidSideCount = sSideCount; solidCapBottom = sCapBottom; solidCapTop = sCapTop; useCameraPosition = useCamPos; const cyHairFileHeader &header = hairFile->GetHeader(); if (header.hair_count == 0) throw runtime_error("Empty strands shape are not supported"); if (useCameraPosition && !scene->camera) throw runtime_error("The scene camera must be defined in order to enable strands useCameraPosition flag"); SLG_LOG("Refining " << header.hair_count << " strands"); const double start = WallClockTime(); const float *points = hairFile->GetPointsArray(); const float *thickness = hairFile->GetThicknessArray(); const u_short *segments = hairFile->GetSegmentsArray(); const float *colors = hairFile->GetColorsArray(); const float *transparency = hairFile->GetTransparencyArray(); const float *uvs = hairFile->GetUVsArray(); if (segments || (header.d_segments > 0)) { u_int pointIndex = 0; vector<Point> hairPoints; vector<float> hairSizes; vector<Spectrum> hairCols; vector<float> hairTransps; vector<UV> hairUVs; vector<Point> meshVerts; vector<Normal> meshNorms; vector<Triangle> meshTris; vector<UV> meshUVs; vector<Spectrum> meshCols; vector<float> meshTransps; for (u_int i = 0; i < header.hair_count; ++i) { // segmentSize must be signed const int segmentSize = segments ? segments[i] : header.d_segments; if (segmentSize == 0) continue; // Collect the segment points and size hairPoints.clear(); hairSizes.clear(); hairCols.clear(); hairTransps.clear(); hairUVs.clear(); for (int j = 0; j <= segmentSize; ++j) { hairPoints.push_back(Point(points[pointIndex * 3], points[pointIndex * 3 + 1], points[pointIndex * 3 + 2])); hairSizes.push_back(((thickness) ? thickness[pointIndex] : header.d_thickness) * .5f); if (colors) hairCols.push_back(Spectrum(colors[pointIndex * 3], colors[pointIndex * 3 + 1], colors[pointIndex * 3 + 2])); else hairCols.push_back(Spectrum(header.d_color[0], header.d_color[1], header.d_color[2])); if (transparency) hairTransps.push_back(1.f - transparency[pointIndex]); else hairTransps.push_back(1.f - header.d_transparency); if (uvs) hairUVs.push_back(UV(uvs[pointIndex * 2], uvs[pointIndex * 2 + 1])); else hairUVs.push_back(UV(0.f, j / (float)segmentSize)); ++pointIndex; } switch (tesselType) { case TESSEL_RIBBON: TessellateRibbon(scene, hairPoints, hairSizes, hairCols, hairUVs, hairTransps, meshVerts, meshNorms, meshTris, meshUVs, meshCols, meshTransps); break; case TESSEL_RIBBON_ADAPTIVE: TessellateAdaptive(scene, false, hairPoints, hairSizes, hairCols, hairUVs, hairTransps, meshVerts, meshNorms, meshTris, meshUVs, meshCols, meshTransps); break; case TESSEL_SOLID: TessellateSolid(scene, hairPoints, hairSizes, hairCols, hairUVs, hairTransps, meshVerts, meshNorms, meshTris, meshUVs, meshCols, meshTransps); break; case TESSEL_SOLID_ADAPTIVE: TessellateAdaptive(scene, true, hairPoints, hairSizes, hairCols, hairUVs, hairTransps, meshVerts, meshNorms, meshTris, meshUVs, meshCols, meshTransps); break; default: SLG_LOG("Unknown tessellation type in an Strands Shape: " + ToString(tesselType)); } } // Normalize normals for (u_int i = 0; i < meshNorms.size(); ++i) meshNorms[i] = Normalize(meshNorms[i]); SLG_LOG("Strands mesh: " << meshTris.size() / 3 << " triangles"); // Create the mesh Point *newMeshVerts = TriangleMesh::AllocVerticesBuffer(meshVerts.size()); copy(meshVerts.begin(), meshVerts.end(), newMeshVerts); Triangle *newMeshTris = TriangleMesh::AllocTrianglesBuffer(meshTris.size()); copy(meshTris.begin(), meshTris.end(), newMeshTris); Normal *newMeshNorms = new Normal[meshNorms.size()]; copy(meshNorms.begin(), meshNorms.end(), newMeshNorms); UV *newMeshUVs = new UV[meshUVs.size()]; copy(meshUVs.begin(), meshUVs.end(), newMeshUVs); // Check if I have to include vertex colors too Spectrum *newMeshCols = NULL; BOOST_FOREACH(const Spectrum &c, meshCols) { if (c != Spectrum(1.f)) { // The mesh uses vertex colors SLG_LOG("Strands shape uses colors"); newMeshCols = new Spectrum[meshUVs.size()]; copy(meshCols.begin(), meshCols.end(), newMeshCols); break; } } // Check if I have to include vertex alpha too float *newMeshTransps = NULL; BOOST_FOREACH(const float &a, meshTransps) { if (a != 1.f) { // The mesh uses vertex alphas SLG_LOG("Strands shape uses alphas"); newMeshTransps = new float[meshTransps.size()]; copy(meshTransps.begin(), meshTransps.end(), newMeshTransps); break; } } mesh = new ExtTriangleMesh(meshVerts.size(), meshTris.size(), newMeshVerts, newMeshTris, newMeshNorms, newMeshUVs, newMeshCols, newMeshTransps); } else throw runtime_error("Strands shape without segments are not supported"); const float dt = WallClockTime() - start; SLG_LOG("Refining time: " << std::setprecision(3) << dt << " secs"); } void StrendsShape::TessellateRibbon(const Scene *scene, const vector<Point> &hairPoints, const vector<float> &hairSizes, const vector<Spectrum> &hairCols, const vector<UV> &hairUVs, const vector<float> &hairTransps, vector<Point> &meshVerts, vector<Normal> &meshNorms, vector<Triangle> &meshTris, vector<UV> &meshUVs, vector<Spectrum> &meshCols, vector<float> &meshTransps) const { // Create the mesh vertices const u_int baseOffset = meshVerts.size(); const Point cameraPosition = (useCameraPosition && (scene->camera->GetType() == Camera::PERSPECTIVE)) ? ((PerspectiveCamera *)scene->camera)->orig : Point(); Vector previousDir; Vector previousX; // I'm using quaternion here in order to avoid Gimbal lock problem Quaternion trans; for (int i = 0; i < (int)hairPoints.size(); ++i) { Vector dir; // I need a special case for the very last point if (i == (int)hairPoints.size() - 1) dir = Normalize(hairPoints[i] - hairPoints[i - 1]); else dir = Normalize(hairPoints[i + 1] - hairPoints[i]); if (i == 0) { // Build the initial quaternion by establishing an initial (arbitrary) // frame // Check if I have to face the ribbon in a specific direction Vector up; if (useCameraPosition) up = Normalize(cameraPosition - hairPoints[i]); else up = Vector(1.f, 0.f, 0.f); if (AbsDot(dir, up) > 1.f - .05f) { up = Vector(0.f, 1.f, 0.f); if (AbsDot(dir, up) > 1.f - .05f) up = Vector(0.f, 0.f, 1.f); } const Transform dirTrans = LookAt(hairPoints[0], hairPoints[1], up); trans = Quaternion(dirTrans.m); } else { // Compose the new delta transformation with all old one trans = GetRotationBetween(previousDir, dir) * trans; } previousDir = dir; const Vector newPreviousX = trans.RotateVector(Vector(1.f, 0.f, 0.f)); // Using this trick to have a section half way between previous and new one const Vector x = (i == 0) ? newPreviousX : (previousX + newPreviousX) * .5; previousX = newPreviousX; const Point p0 = hairPoints[i] + hairSizes[i] * x; const Point p1 = hairPoints[i] - hairSizes[i] * x; meshVerts.push_back(p0); meshNorms.push_back(Normal()); meshVerts.push_back(p1); meshNorms.push_back(Normal()); meshUVs.push_back(hairUVs[i]); meshUVs.push_back(hairUVs[i]); meshCols.push_back(hairCols[i]); meshCols.push_back(hairCols[i]); meshTransps.push_back(hairTransps[i]); meshTransps.push_back(hairTransps[i]); } // Triangulate the vertex mesh for (int i = 0; i < (int)hairPoints.size() - 1; ++i) { const u_int index = baseOffset + i * 2; const u_int i0 = index; const u_int i1 = index + 1; const u_int i2 = index + 2; const u_int i3 = index + 3; // First triangle meshTris.push_back(Triangle(i0, i1, i2)); // First triangle normal const Normal n0 = Normal(Cross(meshVerts[i2] - meshVerts[i0], meshVerts[i1] - meshVerts[i0])); meshNorms[i0] += n0; meshNorms[i1] += n0; meshNorms[i2] += n0; // Second triangle meshTris.push_back(Triangle(i1, i3, i2)); // Second triangle normal const Normal n1 = Normal(Cross(meshVerts[i2] - meshVerts[i1], meshVerts[i3] - meshVerts[i1])); meshNorms[i1] += n1; meshNorms[i2] += n1; meshNorms[i3] += n1; } } void StrendsShape::TessellateAdaptive(const Scene *scene, const bool solid, const vector<Point> &hairPoints, const vector<float> &hairSizes, const vector<Spectrum> &hairCols, const vector<UV> &hairUVs, const vector<float> &hairTransps, vector<Point> &meshVerts, vector<Normal> &meshNorms, vector<Triangle> &meshTris, vector<UV> &meshUVs, vector<Spectrum> &meshCols, vector<float> &meshTransps) const { // Interpolate the hair segments CatmullRomCurve curve; for (int i = 0; i < (int)hairPoints.size(); ++i) curve.AddPoint(hairPoints[i], hairSizes[i], hairCols[i], hairTransps[i], hairUVs[i]); // Tessellate the curve vector<float> values; curve.AdaptiveTessellate(adaptiveMaxDepth, adaptiveError, values); // Create the ribbon vector<Point> tesselPoints; vector<float> tesselSizes; vector<Spectrum> tesselCols; vector<float> tesselTransps; vector<UV> tesselUVs; for (u_int i = 0; i < values.size(); ++i) { tesselPoints.push_back(curve.EvaluatePoint(values[i])); tesselSizes.push_back(curve.EvaluateSize(values[i])); tesselCols.push_back(curve.EvaluateColor(values[i])); tesselTransps.push_back(curve.EvaluateTransparency(values[i])); tesselUVs.push_back(curve.EvaluateUV(values[i])); } if (solid) TessellateSolid(scene, tesselPoints, tesselSizes, tesselCols, tesselUVs, tesselTransps, meshVerts, meshNorms, meshTris, meshUVs, meshCols, meshTransps); else TessellateRibbon(scene, tesselPoints, tesselSizes, tesselCols, tesselUVs, tesselTransps, meshVerts, meshNorms, meshTris, meshUVs, meshCols, meshTransps); } void StrendsShape::TessellateSolid(const Scene *scene, const vector<Point> &hairPoints, const vector<float> &hairSizes, const vector<Spectrum> &hairCols, const vector<UV> &hairUVs, const vector<float> &hairTransps, vector<Point> &meshVerts, vector<Normal> &meshNorms, vector<Triangle> &meshTris, vector<UV> &meshUVs, vector<Spectrum> &meshCols, vector<float> &meshTransps) const { // Create the mesh vertices const u_int baseOffset = meshVerts.size(); const float angleStep = Radians(360.f / solidSideCount); Vector previousDir; Vector previousX, previousY, previousZ; // I'm using quaternion here in order to avoid Gimbal lock problem Quaternion trans; for (int i = 0; i < (int)hairPoints.size(); ++i) { Vector dir; // I need a special case for the very last point if (i == (int)hairPoints.size() - 1) dir = Normalize(hairPoints[i] - hairPoints[i - 1]); else dir = Normalize(hairPoints[i + 1] - hairPoints[i]); if (i == 0) { // Build the initial quaternion by establishing an initial (arbitrary) // frame Vector up(0.f, 0.f, 1.f); if (AbsDot(dir, up) > 1.f - .05f) up = Vector(1.f, 0.f, 0.f); const Transform dirTrans = LookAt(hairPoints[0], hairPoints[1], up); trans = Quaternion(dirTrans.m); } else { // Compose the new delta transformation with all old one trans = GetRotationBetween(previousDir, dir) * trans; } previousDir = dir; const Vector newPreviousX = trans.RotateVector(Vector(1.f, 0.f, 0.f)); const Vector newPreviousY = trans.RotateVector(Vector(0.f, 1.f, 0.f)); const Vector newPreviousZ = trans.RotateVector(Vector(0.f, 0.f, 1.f)); // Using this trick to have a section half way between previous and new one const Vector x = (i == 0) ? newPreviousX : (previousX + newPreviousX) * .5; const Vector y = (i == 0) ? newPreviousY : (previousY + newPreviousY) * .5; const Vector z = (i == 0) ? newPreviousZ : (previousZ + newPreviousZ) * .5; previousX = newPreviousX; previousY = newPreviousY; previousZ = newPreviousZ; float angle = 0.f; for (u_int j = 0; j < solidSideCount; ++j) { const Point lp(hairSizes[i] * cosf(angle), hairSizes[i] * sinf(angle), 0.f); const Point p( x.x * lp.x + y.x * lp.y + z.x * lp.z + hairPoints[i].x, x.y * lp.x + y.y * lp.y + z.y * lp.z + hairPoints[i].y, x.z * lp.x + y.z * lp.y + z.z * lp.z + hairPoints[i].z); meshVerts.push_back(p); meshNorms.push_back(Normal()); meshUVs.push_back(hairUVs[i]); meshCols.push_back(hairCols[i]); meshTransps.push_back(hairTransps[i]); angle += angleStep; } } // Triangulate the vertex mesh for (int i = 0; i < (int)hairPoints.size() - 1; ++i) { const u_int index = baseOffset + i * solidSideCount; for (u_int j = 0; j < solidSideCount; ++j) { // Side face const u_int i0 = index + j; const u_int i1 = (j == solidSideCount - 1) ? index : (index + j + 1); const u_int i2 = index + j + solidSideCount; const u_int i3 = (j == solidSideCount - 1) ? (index + solidSideCount) : (index + j + solidSideCount + 1); // First triangle meshTris.push_back(Triangle(i0, i2, i1)); const Normal n0 = Normal(Cross(meshVerts[i2] - meshVerts[i0], meshVerts[i1] - meshVerts[i0])); meshNorms[i0] += n0; meshNorms[i1] += n0; meshNorms[i2] += n0; // Second triangle meshTris.push_back(Triangle(i1, i2, i3)); const Normal n1 = Normal(Cross(meshVerts[i2] - meshVerts[i0], meshVerts[i3] - meshVerts[i0])); meshNorms[i1] += n1; meshNorms[i3] += n1; meshNorms[i2] += n1; } } if (solidCapTop) { // Add a top fan cap const u_int offset = meshVerts.size(); const Normal n = Normal(Normalize(hairPoints[hairPoints.size() - 1] - hairPoints[hairPoints.size() - 2])); for (u_int j = 0; j < solidSideCount; ++j) { meshVerts.push_back(meshVerts[offset - solidSideCount + j]); meshNorms.push_back(n); meshUVs.push_back(hairUVs.back()); meshCols.push_back(hairCols.back()); meshTransps.push_back(hairTransps.back()); } // Add the fan center meshVerts.push_back(hairPoints.back()); meshNorms.push_back(n); meshUVs.push_back(hairUVs.back()); meshCols.push_back(hairCols.back()); meshTransps.push_back(hairTransps.back()); const u_int i3 = meshVerts.size() - 1; for (u_int j = 0; j < solidSideCount; ++j) { const u_int i0 = offset + j; const u_int i1 = (j == solidSideCount - 1) ? offset : (offset + j + 1); meshTris.push_back(Triangle(i1, i0, i3)); } } if (solidCapBottom) { // Add a bottom fan cap const u_int offset = meshVerts.size(); const Normal n = Normal(Normalize(hairPoints[0] - hairPoints[1])); for (u_int j = 0; j < solidSideCount; ++j) { meshVerts.push_back(meshVerts[baseOffset + j]); meshNorms.push_back(n); meshUVs.push_back(hairUVs[0]); meshCols.push_back(hairCols[0]); meshTransps.push_back(hairTransps[0]); } // Add the fan center meshVerts.push_back(hairPoints[0]); meshNorms.push_back(n); meshUVs.push_back(hairUVs[0]); meshCols.push_back(hairCols[0]); meshTransps.push_back(hairTransps[0]); const u_int i3 = meshVerts.size() - 1; for (u_int j = 0; j < solidSideCount; ++j) { const u_int i0 = offset + j; const u_int i1 = (j == solidSideCount - 1) ? offset : (offset + j + 1); meshTris.push_back(Triangle(i0, i1, i3)); } } } StrendsShape::~StrendsShape() { if (!refined) delete mesh; } ExtTriangleMesh *StrendsShape::RefineImpl(const Scene *scene) { return mesh; }
34.497312
115
0.636328
tschw
4f482d4179751351680ece9bcc3f10de2882292a
43,981
cc
C++
packager/media/codecs/nal_unit_to_byte_stream_converter_unittest.cc
koln67/shaka-packager
5b9fd409a5de502e8af2e46ee12840bd2226874d
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1,288
2016-05-25T01:20:31.000Z
2022-03-02T23:56:56.000Z
packager/media/codecs/nal_unit_to_byte_stream_converter_unittest.cc
koln67/shaka-packager
5b9fd409a5de502e8af2e46ee12840bd2226874d
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
894
2016-05-17T00:39:30.000Z
2022-03-02T18:46:21.000Z
packager/media/codecs/nal_unit_to_byte_stream_converter_unittest.cc
koln67/shaka-packager
5b9fd409a5de502e8af2e46ee12840bd2226874d
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
400
2016-05-25T01:20:35.000Z
2022-03-03T02:12:00.000Z
// Copyright 2016 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd #include <gmock/gmock.h> #include <gtest/gtest.h> #include "packager/media/base/media_sample.h" #include "packager/media/codecs/nal_unit_to_byte_stream_converter.h" #include "packager/media/formats/mp4/box_definitions_comparison.h" namespace shaka { namespace media { namespace { // This should be valud AVCDecoderConfigurationRecord that can be parsed by // NalUnitToByteStreamConverter. const uint8_t kTestAVCDecoderConfigurationRecord[] = { 0x01, // configuration version (must be 1) 0x00, // AVCProfileIndication (bogus) 0x00, // profile_compatibility (bogus) 0x00, // AVCLevelIndication (bogus) 0xFF, // Length size minus 1 == 3 0xE1, // 1 sps. 0x00, 0x1D, // SPS length == 29 // Some valid SPS data. 0x67, 0x64, 0x00, 0x1E, 0xAC, 0xD9, 0x40, 0xB4, 0x2F, 0xF9, 0x7F, 0xF0, 0x00, 0x80, 0x00, 0x91, 0x00, 0x00, 0x03, 0x03, 0xE9, 0x00, 0x00, 0xEA, 0x60, 0x0F, 0x16, 0x2D, 0x96, 0x01, // 1 pps. 0x00, 0x0A, // PPS length == 10 0x68, 0xFE, 0xFD, 0xFC, 0xFB, 0x11, 0x12, 0x13, 0x14, 0x15, }; const uint8_t kTestAVCDecoderConfigurationRecordNaluLengthSize2[] = { 0x01, // configuration version (must be 1) 0x00, // AVCProfileIndication (bogus) 0x00, // profile_compatibility (bogus) 0x00, // AVCLevelIndication (bogus) 0xFD, // Length size minus 1 == 1 0xE1, // 1 sps. 0x00, 0x1D, // SPS length == 29 // Some valid SPS data. 0x67, 0x64, 0x00, 0x1E, 0xAC, 0xD9, 0x40, 0xB4, 0x2F, 0xF9, 0x7F, 0xF0, 0x00, 0x80, 0x00, 0x91, 0x00, 0x00, 0x03, 0x03, 0xE9, 0x00, 0x00, 0xEA, 0x60, 0x0F, 0x16, 0x2D, 0x96, 0x01, // 1 pps. 0x00, 0x0A, // PPS length == 10 0x68, 0xFE, 0xFD, 0xFC, 0xFB, 0x11, 0x12, 0x13, 0x14, 0x15, }; const bool kIsKeyFrame = true; const bool kEscapeEncryptedNalu = true; } // namespace class NalUnitToByteStreamConverterTest : public ::testing::Test { public: NalUnitToByteStreamConverter converter_; }; // Expect a valid AVCDecoderConfigurationRecord to pass. TEST(NalUnitToByteStreamConverterTest, ParseAVCDecoderConfigurationRecord) { NalUnitToByteStreamConverter converter; EXPECT_TRUE( converter.Initialize(kTestAVCDecoderConfigurationRecord, arraysize(kTestAVCDecoderConfigurationRecord))); EXPECT_TRUE( converter.Initialize(kTestAVCDecoderConfigurationRecord, arraysize(kTestAVCDecoderConfigurationRecord))); } // Empty AVCDecoderConfigurationRecord should return false. TEST(NalUnitToByteStreamConverterTest, EmptyAVCDecoderConfigurationRecord) { NalUnitToByteStreamConverter converter; EXPECT_FALSE(converter.Initialize(nullptr, 102)); EXPECT_FALSE(converter.Initialize(kTestAVCDecoderConfigurationRecord, 0)); } // If there is no SPS, Initialize() should fail. TEST(NalUnitToByteStreamConverterTest, NoSps) { NalUnitToByteStreamConverter converter; const uint8_t kNoSps[] = { 0x01, // configuration version (must be 1) 0x00, // AVCProfileIndication (bogus) 0x00, // profile_compatibility (bogus) 0x00, // AVCLevelIndication (bogus) 0xFF, // Length size minus 1 == 3 0xE0, // 0 sps. // The rest doesn't really matter, Initialize() should fail. 0x01, // 1 pps. 0x00, 0x0A, // PPS length == 10 0x68, 0xFE, 0xFD, 0xFC, 0xFB, 0x11, 0x12, 0x13, 0x14, 0x15, }; EXPECT_FALSE(converter.Initialize(kNoSps, arraysize(kNoSps))); } // If there is no PPS, Initialize() should fail. TEST(NalUnitToByteStreamConverterTest, NoPps) { NalUnitToByteStreamConverter converter; const uint8_t kNoPps[] = { 0x01, // configuration version (must be 1) 0x00, // AVCProfileIndication (bogus) 0x00, // profile_compatibility (bogus) 0x00, // AVCLevelIndication (bogus) 0xFF, // Length size minus 1 == 3 0xE1, // 1 sps. 0x00, 0x1D, // SPS length == 29 // Some valid SPS data. 0x67, 0x64, 0x00, 0x1E, 0xAC, 0xD9, 0x40, 0xB4, 0x2F, 0xF9, 0x7F, 0xF0, 0x00, 0x80, 0x00, 0x91, 0x00, 0x00, 0x03, 0x03, 0xE9, 0x00, 0x00, 0xEA, 0x60, 0x0F, 0x16, 0x2D, 0x96, 0x00, // 0 pps. }; EXPECT_FALSE(converter.Initialize(kNoPps, arraysize(kNoPps))); } // If the length of SPS is 0 then Initialize() should fail. TEST(NalUnitToByteStreamConverterTest, ZeroLengthSps) { NalUnitToByteStreamConverter converter; const uint8_t kZeroLengthSps[] = { 0x01, // configuration version (must be 1) 0x00, // AVCProfileIndication (bogus) 0x00, // profile_compatibility (bogus) 0x00, // AVCLevelIndication (bogus) 0xFF, // Length size minus 1 == 3 0xE1, // 1 sps. 0x00, 0x00, // SPS length == 0 0x01, // 1 pps. 0x00, 0x0A, // PPS length == 10 0x68, 0xFE, 0xFD, 0xFC, 0xFB, 0x11, 0x12, 0x13, 0x14, 0x15, }; EXPECT_FALSE(converter.Initialize(kZeroLengthSps, arraysize(kZeroLengthSps))); } // If the length of PPS is 0 then Initialize() should fail. TEST(NalUnitToByteStreamConverterTest, ZeroLengthPps) { NalUnitToByteStreamConverter converter; const uint8_t kZeroLengthPps[] = { 0x01, // configuration version (must be 1) 0x00, // AVCProfileIndication (bogus) 0x00, // profile_compatibility (bogus) 0x00, // AVCLevelIndication (bogus) 0xFF, // Length size minus 1 == 3 0xE1, // 1 sps. 0x00, 0x05, // SPS length == 5 0x00, 0x00, 0x00, 0x01, 0x02, 0x01, // 1 pps. 0x00, 0x00, // PPS length == 0 }; EXPECT_FALSE(converter.Initialize(kZeroLengthPps, arraysize(kZeroLengthPps))); } TEST(NalUnitToByteStreamConverterTest, ConvertUnitToByteStream) { // Only the type of the NAL units are checked. // This does not contain AUD, SPS, nor PPS. const uint8_t kUnitStreamLikeMediaSample[] = { 0x00, 0x00, 0x00, 0x0A, // Size 10 NALU. 0x06, // NAL unit type. 0xFD, 0x78, 0xA4, 0xC3, 0x82, 0x62, 0x11, 0x29, 0x77, }; NalUnitToByteStreamConverter converter; EXPECT_TRUE( converter.Initialize(kTestAVCDecoderConfigurationRecord, arraysize(kTestAVCDecoderConfigurationRecord))); std::vector<uint8_t> output; EXPECT_TRUE(converter.ConvertUnitToByteStream( kUnitStreamLikeMediaSample, arraysize(kUnitStreamLikeMediaSample), kIsKeyFrame, &output)); const uint8_t kExpectedOutput[] = { 0x00, 0x00, 0x00, 0x01, // Start code. 0x09, // AUD type. 0xF0, // primary pic type is anything. 0x00, 0x00, 0x00, 0x01, // Start code. // Some valid SPS data. 0x67, 0x64, 0x00, 0x1E, 0xAC, 0xD9, 0x40, 0xB4, 0x2F, 0xF9, 0x7F, 0xF0, 0x00, 0x80, 0x00, 0x91, 0x00, 0x00, 0x03, 0x03, 0xE9, 0x00, 0x00, 0xEA, 0x60, 0x0F, 0x16, 0x2D, 0x96, 0x00, 0x00, 0x00, 0x01, // Start code. 0x68, 0xFE, 0xFD, 0xFC, 0xFB, 0x11, 0x12, 0x13, 0x14, 0x15, // PPS. 0x00, 0x00, 0x00, 0x01, // Start code. // The input NALU. 0x06, // NALU type. 0xFD, 0x78, 0xA4, 0xC3, 0x82, 0x62, 0x11, 0x29, 0x77, }; EXPECT_EQ(std::vector<uint8_t>(kExpectedOutput, kExpectedOutput + arraysize(kExpectedOutput)), output); } // Expect a valid AVCDecoderConfigurationRecord with SPSExtension to pass. TEST(NalUnitToByteStreamConverterTest, ConvertUnitToByteStreamWithSPSExtension) { NalUnitToByteStreamConverter converter; const uint8_t kDecoderConfigWithSpsExt[] = { 0x01, // configuration version (must be 1) 0x64, // AVCProfileIndication (100: sps special case) 0x00, // profile_compatibility (bogus) 0x00, // AVCLevelIndication (bogus) 0xFF, // Length size minus 1 == 3 0xE1, // 1 sps. 0x00, 0x1D, // SPS length == 29 // Some valid SPS data. 0x67, 0x64, 0x00, 0x1E, 0xAC, 0xD9, 0x40, 0xB4, 0x2F, 0xF9, 0x7F, 0xF0, 0x00, 0x80, 0x00, 0x91, 0x00, 0x00, 0x03, 0x03, 0xE9, 0x00, 0x00, 0xEA, 0x60, 0x0F, 0x16, 0x2D, 0x96, 0x01, // 1 pps. 0x00, 0x0A, // PPS length == 10 0x68, 0xFE, 0xFD, 0xFC, 0xFB, 0x11, 0x12, 0x13, 0x14, 0x15, 0xFC, // chroma_format == 0 0xF9, // bit_depth_luma_minus8 == 1 0xFF, // bit_depth_chroma_minus8 == 7 0x01, // 1 SPS Extension 0x00, 0x05, // SPSExtension length = 5 0x6D, 0x33, 0x01, 0x57, 0x78 }; // Only the type of the NAL units are checked. // This does not contain AUD, SPS, nor PPS. const uint8_t kUnitStreamLikeMediaSample[] = { 0x00, 0x00, 0x00, 0x0A, // Size 10 NALU. 0x06, // NAL unit type. 0xFD, 0x78, 0xA4, 0xC3, 0x82, 0x62, 0x11, 0x29, 0x77 }; const uint8_t kByteStreamWithSpsExtension[] = { 0x00, 0x00, 0x00, 0x01, // Start code 0x09, // AUD Type 0xF0, // Primary pic type 0x00, 0x00, 0x00, 0x01, // Start code // Some SPS Data 0x67, 0x64, 0x00, 0x1E, 0xAC, 0xD9, 0x40, 0xB4, 0x2F, 0xF9, 0x7F, 0xF0, 0x00, 0x80, 0x00, 0x91, 0x00, 0x00, 0x03, 0x03, 0xE9, 0x00, 0x00, 0xEA, 0x60, 0x0F, 0x16, 0x2D, 0x96, 0x00, 0x00, 0x00, 0x01, // Start code // Some PPS Data 0x68, 0xFE, 0xFD, 0xFC, 0xFB, 0x11, 0x12, 0x13, 0x14, 0x15, 0x00, 0x00, 0x00, 0x01, // Start code // Some SPS Extension data 0x6D, 0x33, 0x01, 0x57, 0x78, 0x00, 0x00, 0x00, 0x01, // Start code // The input NALU 0x06, // NALU type 0xFD, 0x78, 0xA4, 0xC3, 0x82, 0x62, 0x11, 0x29, 0x77, }; EXPECT_TRUE(converter.Initialize(kDecoderConfigWithSpsExt, arraysize(kDecoderConfigWithSpsExt))); std::vector<uint8_t> output; EXPECT_TRUE(converter.ConvertUnitToByteStream( kUnitStreamLikeMediaSample, arraysize(kUnitStreamLikeMediaSample), kIsKeyFrame, &output)); EXPECT_EQ(std::vector<uint8_t>(std::begin(kByteStreamWithSpsExtension), std::end(kByteStreamWithSpsExtension)), output); } // Verify that if it is not a key frame then SPS and PPS from decoder // configuration is not used. TEST(NalUnitToByteStreamConverterTest, NonKeyFrameSample) { const uint8_t kNonKeyFrameStream[] = { 0x00, 0x00, 0x00, 0x03, // Size 3 NALU. 0x06, // NAL unit type. 0x33, 0x88, }; NalUnitToByteStreamConverter converter; EXPECT_TRUE( converter.Initialize(kTestAVCDecoderConfigurationRecord, arraysize(kTestAVCDecoderConfigurationRecord))); std::vector<uint8_t> output; EXPECT_TRUE(converter.ConvertUnitToByteStream(kNonKeyFrameStream, arraysize(kNonKeyFrameStream), !kIsKeyFrame, &output)); const uint8_t kExpectedOutput[] = { 0x00, 0x00, 0x00, 0x01, // Start code. 0x09, // AUD type. 0xF0, // Anything. 0x00, 0x00, 0x00, 0x01, // Start code. // The input NALU. 0x06, // NALU type. 0x33, 0x88, }; EXPECT_EQ(std::vector<uint8_t>(kExpectedOutput, kExpectedOutput + arraysize(kExpectedOutput)), output); } // Bug found during unit testing. // The zeros aren't contiguous but the escape byte was inserted. TEST(NalUnitToByteStreamConverterTest, DispersedZeros) { const uint8_t kDispersedZeros[] = { 0x00, 0x00, 0x00, 0x08, // Size 8 NALU. 0x06, // NAL unit type. // After 2 zeros (including the first byte of the NALU followed by 0, 1, // 2, or 3 caused it to insert the escape byte. 0x11, 0x00, 0x01, 0x00, 0x02, 0x00, 0x44, }; NalUnitToByteStreamConverter converter; EXPECT_TRUE( converter.Initialize(kTestAVCDecoderConfigurationRecord, arraysize(kTestAVCDecoderConfigurationRecord))); std::vector<uint8_t> output; EXPECT_TRUE(converter.ConvertUnitToByteStream( kDispersedZeros, arraysize(kDispersedZeros), !kIsKeyFrame, &output)); const uint8_t kExpectedOutput[] = { 0x00, 0x00, 0x00, 0x01, // Start code. 0x09, // AUD type. 0xF0, // Anything. 0x00, 0x00, 0x00, 0x01, // Start code. // The input NALU. 0x06, // NAL unit type. 0x11, 0x00, 0x01, 0x00, 0x02, 0x00, 0x44, }; EXPECT_EQ(std::vector<uint8_t>(kExpectedOutput, kExpectedOutput + arraysize(kExpectedOutput)), output); } // Verify that ConvertUnitToByteStream() with escape_data = false works. TEST(NalUnitToByteStreamConverterTest, DoNotEscape) { // This has sequences that should be escaped if escape_data = true. const uint8_t kNotEscaped[] = { 0x00, 0x00, 0x00, 0x0C, // Size 12 NALU. 0x06, // NAL unit type. 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x02, 0x00, 0x00, 0x03, }; NalUnitToByteStreamConverter converter; EXPECT_TRUE( converter.Initialize(kTestAVCDecoderConfigurationRecord, arraysize(kTestAVCDecoderConfigurationRecord))); std::vector<uint8_t> output; EXPECT_TRUE(converter.ConvertUnitToByteStream( kNotEscaped, arraysize(kNotEscaped), !kIsKeyFrame, &output)); const uint8_t kExpectedOutput[] = { 0x00, 0x00, 0x00, 0x01, // Start code. 0x09, // AUD type. 0xF0, // Anything. 0x00, 0x00, 0x00, 0x01, // Start code. // Should be the same as the input. 0x06, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x02, 0x00, 0x00, 0x03, }; EXPECT_EQ(std::vector<uint8_t>(kExpectedOutput, kExpectedOutput + arraysize(kExpectedOutput)), output); } // All NAL units have both clear and ciper text TEST(NalUnitToByteStreamConverterTest, NoClearNAL) { // Only the type of the NAL units are checked. // This does not contain AUD, SPS, nor PPS. const uint8_t kUnitStreamLikeMediaSample[] = { 0x00, 0x00, 0x00, 0x0A, // Size 10 NALU. 0x02, // NAL unit type. 0xFD, 0x78, 0xA4, 0xC3, 0x82, 0x62, 0x11, 0x29, 0x77, // Slice data 0x00, 0x00, 0x00, 0x08, // Size 8 NALU. 0x02, // NAL unit type. 0xFD, 0x78, 0xA4, 0x82, 0x62, 0x29, 0x77, // Slice data }; std::vector<SubsampleEntry> subsamples{SubsampleEntry(5, 9), SubsampleEntry(5, 7)}; NalUnitToByteStreamConverter converter; EXPECT_TRUE( converter.Initialize(kTestAVCDecoderConfigurationRecord, arraysize(kTestAVCDecoderConfigurationRecord))); std::vector<uint8_t> output; EXPECT_TRUE(converter.ConvertUnitToByteStreamWithSubsamples( kUnitStreamLikeMediaSample, arraysize(kUnitStreamLikeMediaSample), kIsKeyFrame, !kEscapeEncryptedNalu, &output, &subsamples)); const uint8_t kExpectedOutput[] = { 0x00, 0x00, 0x00, 0x01, // Start code. 0x09, // AUD type. 0xF0, // primary pic type is anything. 0x00, 0x00, 0x00, 0x01, // Start code. // Some valid SPS data. 0x67, 0x64, 0x00, 0x1E, 0xAC, 0xD9, 0x40, 0xB4, 0x2F, 0xF9, 0x7F, 0xF0, 0x00, 0x80, 0x00, 0x91, 0x00, 0x00, 0x03, 0x03, 0xE9, 0x00, 0x00, 0xEA, 0x60, 0x0F, 0x16, 0x2D, 0x96, 0x00, 0x00, 0x00, 0x01, // Start code. 0x68, 0xFE, 0xFD, 0xFC, 0xFB, 0x11, 0x12, 0x13, 0x14, 0x15, // PPS. 0x00, 0x00, 0x00, 0x01, // Start code. // The input NALU 1. 0x02, // NALU type. 0xFD, 0x78, 0xA4, 0xC3, 0x82, 0x62, 0x11, 0x29, 0x77, 0x00, 0x00, 0x00, 0x01, // Start code. // The input NALU 2. 0x02, // NALU type. 0xFD, 0x78, 0xA4, 0x82, 0x62, 0x29, 0x77, }; const std::vector<SubsampleEntry> kExpectedOutputSubsamples{ SubsampleEntry(58, 9), SubsampleEntry(5, 7)}; EXPECT_EQ(std::vector<uint8_t>(kExpectedOutput, kExpectedOutput + arraysize(kExpectedOutput)), output); EXPECT_EQ(kExpectedOutputSubsamples, subsamples); } // Some NAL units have all clear text TEST(NalUnitToByteStreamConverterTest, WithSomeClearNAL) { // Only the type of the NAL units are checked. // This does not contain AUD, SPS, nor PPS. const uint8_t kUnitStreamLikeMediaSample[] = { 0x00, 0x00, 0x00, 0x0A, // Size 10 NALU. 0x06, // NAL unit type. 0xFD, 0x78, 0xA4, 0xC3, 0x82, 0x62, 0x11, 0x29, 0x77, 0x00, 0x00, 0x00, 0x08, // Size 8 NALU. 0x02, // NAL unit type. 0xFD, 0x78, 0xA4, 0x82, 0x62, 0x29, 0x77, // Slice data }; std::vector<SubsampleEntry> subsamples{SubsampleEntry(19, 7)}; NalUnitToByteStreamConverter converter; EXPECT_TRUE( converter.Initialize(kTestAVCDecoderConfigurationRecord, arraysize(kTestAVCDecoderConfigurationRecord))); std::vector<uint8_t> output; EXPECT_TRUE(converter.ConvertUnitToByteStreamWithSubsamples( kUnitStreamLikeMediaSample, arraysize(kUnitStreamLikeMediaSample), kIsKeyFrame, !kEscapeEncryptedNalu, &output, &subsamples)); const uint8_t kExpectedOutput[] = { 0x00, 0x00, 0x00, 0x01, // Start code. 0x09, // AUD type. 0xF0, // primary pic type is anything. 0x00, 0x00, 0x00, 0x01, // Start code. // Some valid SPS data. 0x67, 0x64, 0x00, 0x1E, 0xAC, 0xD9, 0x40, 0xB4, 0x2F, 0xF9, 0x7F, 0xF0, 0x00, 0x80, 0x00, 0x91, 0x00, 0x00, 0x03, 0x03, 0xE9, 0x00, 0x00, 0xEA, 0x60, 0x0F, 0x16, 0x2D, 0x96, 0x00, 0x00, 0x00, 0x01, // Start code. 0x68, 0xFE, 0xFD, 0xFC, 0xFB, 0x11, 0x12, 0x13, 0x14, 0x15, // PPS. 0x00, 0x00, 0x00, 0x01, // Start code. // The input NALU 1. 0x06, // NALU type. 0xFD, 0x78, 0xA4, 0xC3, 0x82, 0x62, 0x11, 0x29, 0x77, 0x00, 0x00, 0x00, 0x01, // Start code. // The input NALU 2. 0x02, // NALU type. 0xFD, 0x78, 0xA4, 0x82, 0x62, 0x29, 0x77, }; const std::vector<SubsampleEntry> kExpectedOutputSubsamples{ SubsampleEntry(72, 7)}; EXPECT_EQ(std::vector<uint8_t>(kExpectedOutput, kExpectedOutput + arraysize(kExpectedOutput)), output); EXPECT_EQ(kExpectedOutputSubsamples, subsamples); } TEST(NalUnitToByteStreamConverterTest, WithSomeClearNALAndNaluLengthSize2) { // Only the type of the NAL units are checked. // This does not contain AUD, SPS, nor PPS. const uint8_t kUnitStreamLikeMediaSample[] = { 0x00, 0x0A, // Size 10 NALU. 0x06, // NAL unit type. 0xFD, 0x78, 0xA4, 0xC3, 0x82, 0x62, 0x11, 0x29, 0x77, 0x00, 0x08, // Size 8 NALU. 0x02, // NAL unit type. 0xFD, 0x78, 0xA4, 0x82, 0x62, 0x29, 0x77, // Slice data }; std::vector<SubsampleEntry> subsamples{SubsampleEntry(15, 7)}; NalUnitToByteStreamConverter converter; EXPECT_TRUE(converter.Initialize( kTestAVCDecoderConfigurationRecordNaluLengthSize2, arraysize(kTestAVCDecoderConfigurationRecordNaluLengthSize2))); std::vector<uint8_t> output; EXPECT_TRUE(converter.ConvertUnitToByteStreamWithSubsamples( kUnitStreamLikeMediaSample, arraysize(kUnitStreamLikeMediaSample), kIsKeyFrame, !kEscapeEncryptedNalu, &output, &subsamples)); const uint8_t kExpectedOutput[] = { 0x00, 0x00, 0x00, 0x01, // Start code. 0x09, // AUD type. 0xF0, // primary pic type is anything. 0x00, 0x00, 0x00, 0x01, // Start code. // Some valid SPS data. 0x67, 0x64, 0x00, 0x1E, 0xAC, 0xD9, 0x40, 0xB4, 0x2F, 0xF9, 0x7F, 0xF0, 0x00, 0x80, 0x00, 0x91, 0x00, 0x00, 0x03, 0x03, 0xE9, 0x00, 0x00, 0xEA, 0x60, 0x0F, 0x16, 0x2D, 0x96, 0x00, 0x00, 0x00, 0x01, // Start code. 0x68, 0xFE, 0xFD, 0xFC, 0xFB, 0x11, 0x12, 0x13, 0x14, 0x15, // PPS. 0x00, 0x00, 0x00, 0x01, // Start code. // The input NALU 1. 0x06, // NALU type. 0xFD, 0x78, 0xA4, 0xC3, 0x82, 0x62, 0x11, 0x29, 0x77, 0x00, 0x00, 0x00, 0x01, // Start code. // The input NALU 2. 0x02, // NALU type. 0xFD, 0x78, 0xA4, 0x82, 0x62, 0x29, 0x77, }; const std::vector<SubsampleEntry> kExpectedOutputSubsamples{ SubsampleEntry(72, 7)}; EXPECT_EQ(std::vector<uint8_t>(kExpectedOutput, kExpectedOutput + arraysize(kExpectedOutput)), output); EXPECT_EQ(kExpectedOutputSubsamples, subsamples); } TEST(NalUnitToByteStreamConverterTest, EscapeEncryptedNalu) { // Only the type of the NAL units are checked. // This does not contain AUD, SPS, nor PPS. const uint8_t kUnitStreamLikeMediaSample[] = { 0x00, 0x00, 0x00, 0x0A, // Size 10 NALU. 0x06, // NAL unit type. // Unencrypted NALU with 0x000000 pattern (no need to escaped). 0xFD, 0x00, 0x00, 0x00, 0x82, 0x62, 0x11, 0x29, 0x77, 0x00, 0x00, 0x00, 0x08, // Size 8 NALU. 0x02, // NAL unit type. // Encrypted NALU with 0x000000 pattern (need to escape). 0xFD, 0x00, 0x00, 0x00, 0x62, 0x29, 0x77, 0x00, 0x00, 0x00, 0x09, // Size 9 NALU. 0x01, // NAL unit types. // Partially encrypted NALU with 0x000000 pattern at the boundary (need to // escape). 0xFD, 0x01, 0x02, 0x00, 0x00, 0x01, 0x02, 0x03, }; std::vector<SubsampleEntry> subsamples{SubsampleEntry(19, 7), SubsampleEntry(9, 4)}; NalUnitToByteStreamConverter converter; EXPECT_TRUE( converter.Initialize(kTestAVCDecoderConfigurationRecord, arraysize(kTestAVCDecoderConfigurationRecord))); std::vector<uint8_t> output; ASSERT_TRUE(converter.ConvertUnitToByteStreamWithSubsamples( kUnitStreamLikeMediaSample, arraysize(kUnitStreamLikeMediaSample), !kIsKeyFrame, kEscapeEncryptedNalu, &output, &subsamples)); const uint8_t kExpectedOutput[] = { 0x00, 0x00, 0x00, 0x01, // Start code. 0x09, // AUD type. 0xF0, // primary pic type is anything. // The input NALU 1. 0x00, 0x00, 0x00, 0x01, // Start code. 0x06, // NALU type. 0xFD, 0x00, 0x00, 0x00, 0x82, 0x62, 0x11, 0x29, 0x77, 0x00, 0x00, 0x00, 0x01, // Start code. // The input NALU 2. 0x02, // NALU type. 0xFD, 0x00, 0x00, 0x03, 0x00, 0x62, 0x29, 0x77, // The input NALU 3. 0x00, 0x00, 0x00, 0x01, // Start code. 0x01, // NAL unit types. 0xFD, 0x01, 0x02, 0x00, 0x00, 0x03, 0x01, 0x02, 0x03, }; EXPECT_EQ(std::vector<uint8_t>(std::begin(kExpectedOutput), std::end(kExpectedOutput)), output); // The result subsample does not include emulation prevention bytes. EXPECT_THAT(subsamples, ::testing::ElementsAre(SubsampleEntry(25, 7), SubsampleEntry(9, 4))); } TEST(NalUnitToByteStreamConverterTest, EncryptedNaluEndingWithZero) { // Only the type of the NAL units are checked. // This does not contain AUD, SPS, nor PPS. const uint8_t kUnitStreamLikeMediaSample[] = { 0x00, 0x00, 0x00, 0x06, // Size 6 NALU. 0x01, // NALU unit types. // Encrypted NALU with 0x0003 pattern in the end (need to escape). 0xFD, 0x00, 0x01, 0x02, 0x00, }; std::vector<SubsampleEntry> subsamples{SubsampleEntry(7, 3)}; NalUnitToByteStreamConverter converter; EXPECT_TRUE( converter.Initialize(kTestAVCDecoderConfigurationRecord, arraysize(kTestAVCDecoderConfigurationRecord))); std::vector<uint8_t> output; ASSERT_TRUE(converter.ConvertUnitToByteStreamWithSubsamples( kUnitStreamLikeMediaSample, arraysize(kUnitStreamLikeMediaSample), !kIsKeyFrame, kEscapeEncryptedNalu, &output, &subsamples)); const uint8_t kExpectedOutput[] = { 0x00, 0x00, 0x00, 0x01, // Start code. 0x09, // AUD type. 0xF0, // primary pic type is anything. 0x00, 0x00, 0x00, 0x01, // Start code. 0x01, // NALU unit types. // Encrypted NALU with 0x0003 pattern in the end (need to escape). 0xFD, 0x00, 0x01, 0x02, 0x00, 0x03, }; EXPECT_EQ(std::vector<uint8_t>(std::begin(kExpectedOutput), std::end(kExpectedOutput)), output); // The result subsample does not include emulation prevention bytes. EXPECT_THAT(subsamples, ::testing::ElementsAre(SubsampleEntry(13, 3))); } // Not supposed to happen, just in case, make sure it is properly supported. TEST(NalUnitToByteStreamConverterTest, EncryptedPps) { // Only the type of the NAL units are checked. // This does not contain AUD, SPS, nor PPS. const uint8_t kUnitStreamLikeMediaSample[] = { 0x00, 0x00, 0x00, 0x0A, // Size 10 NALU. 0x06, // NAL unit type. 0xFD, 0x78, 0xA4, 0xC3, 0x82, 0x62, 0x11, 0x29, 0x77, // clear 0x00, 0x00, 0x00, 0x0B, // Size 11 NALU. 0x68, // PPS, will remain as it is different to the one in decoder // configuration. 0x68, 0xFE, 0xFD, 0xFC, 0xFB, 0x12, 0x12, 0x13, 0x14, 0x15, // cipher 0x00, 0x00, 0x00, 0x08, // Size 8 NALU. 0x02, // NAL unit type. 0xFD, 0x78, 0xA4, 0x82, 0x62, 0x29, 0x77, // Slice data, cipher }; std::vector<SubsampleEntry> subsamples{SubsampleEntry(19, 10), SubsampleEntry(5, 7)}; NalUnitToByteStreamConverter converter; EXPECT_TRUE( converter.Initialize(kTestAVCDecoderConfigurationRecord, arraysize(kTestAVCDecoderConfigurationRecord))); std::vector<uint8_t> output; EXPECT_TRUE(converter.ConvertUnitToByteStreamWithSubsamples( kUnitStreamLikeMediaSample, arraysize(kUnitStreamLikeMediaSample), kIsKeyFrame, !kEscapeEncryptedNalu, &output, &subsamples)); // clang-format off const uint8_t kExpectedOutput[] = { 0x00, 0x00, 0x00, 0x01, // Start code. 0x09, // AUD type. 0xF0, // primary pic type is anything. 0x00, 0x00, 0x00, 0x01, // Start code. // Some valid SPS data. 0x67, 0x64, 0x00, 0x1E, 0xAC, 0xD9, 0x40, 0xB4, 0x2F, 0xF9, 0x7F, 0xF0, 0x00, 0x80, 0x00, 0x91, 0x00, 0x00, 0x03, 0x03, 0xE9, 0x00, 0x00, 0xEA, 0x60, 0x0F, 0x16, 0x2D, 0x96, 0x00, 0x00, 0x00, 0x01, // Start code. 0x68, 0xFE, 0xFD, 0xFC, 0xFB, 0x11, 0x12, 0x13, 0x14, 0x15, // PPS. 0x00, 0x00, 0x00, 0x01, // Start code. // The input NALU 1. 0x06, // NALU type. 0xFD, 0x78, 0xA4, 0xC3, 0x82, 0x62, 0x11, 0x29, 0x77, 0x00, 0x00, 0x00, 0x01, // Start code. // PPS from sample. 0x68, 0x68, 0xFE, 0xFD, 0xFC, 0xFB, 0x12, 0x12, 0x13, 0x14, 0x15, // cipher 0x00, 0x00, 0x00, 0x01, // Start code. // The input NALU 2. 0x02, // NALU type. 0xFD, 0x78, 0xA4, 0x82, 0x62, 0x29, 0x77, }; // clang-format on const std::vector<SubsampleEntry> kExpectedOutputSubsamples{ SubsampleEntry(72, 10), SubsampleEntry(5, 7)}; EXPECT_EQ(std::vector<uint8_t>(kExpectedOutput, kExpectedOutput + arraysize(kExpectedOutput)), output); EXPECT_THAT(kExpectedOutputSubsamples, subsamples); } // A clear PPS NALU follows a clear NALU, the PPS in the sample is the same as // the PPS in decoder configuration, the PPS is dropped and subsample size is // adjusted. TEST(NalUnitToByteStreamConverterTest, ClearPpsSame) { // Only the type of the NAL units are checked. // This does not contain AUD, SPS, nor PPS. const uint8_t kUnitStreamLikeMediaSample[] = { 0x00, 0x00, 0x00, 0x0B, // Size 11 NALU. 0x06, // NAL unit type. 0xFD, 0x78, 0xA4, 0xC3, 0x82, 0x62, 0x11, 0x29, 0x77, 0x88, // clear 0x00, 0x00, 0x00, 0x0A, // Size 10 NALU. 0x68, // PPS, same as in decoder configuration, so is // removed. 0xFE, 0xFD, 0xFC, 0xFB, 0x11, 0x12, 0x13, 0x14, 0x15, // PPS. 0x00, 0x00, 0x00, 0x08, // Size 8 NALU. 0x02, // NAL unit type. 0xFD, 0x78, 0xA4, 0x82, 0x62, 0x29, 0x77, // Slice data, cipher }; std::vector<SubsampleEntry> subsamples{SubsampleEntry(34, 7)}; NalUnitToByteStreamConverter converter; EXPECT_TRUE( converter.Initialize(kTestAVCDecoderConfigurationRecord, arraysize(kTestAVCDecoderConfigurationRecord))); std::vector<uint8_t> output; EXPECT_TRUE(converter.ConvertUnitToByteStreamWithSubsamples( kUnitStreamLikeMediaSample, arraysize(kUnitStreamLikeMediaSample), kIsKeyFrame, !kEscapeEncryptedNalu, &output, &subsamples)); // clang-format off const uint8_t kExpectedOutput[] = { 0x00, 0x00, 0x00, 0x01, // Start code. 0x09, // AUD type. 0xF0, // primary pic type is anything. 0x00, 0x00, 0x00, 0x01, // Start code. // Some valid SPS data. 0x67, 0x64, 0x00, 0x1E, 0xAC, 0xD9, 0x40, 0xB4, 0x2F, 0xF9, 0x7F, 0xF0, 0x00, 0x80, 0x00, 0x91, 0x00, 0x00, 0x03, 0x03, 0xE9, 0x00, 0x00, 0xEA, 0x60, 0x0F, 0x16, 0x2D, 0x96, 0x00, 0x00, 0x00, 0x01, // Start code. 0x68, 0xFE, 0xFD, 0xFC, 0xFB, 0x11, 0x12, 0x13, 0x14, 0x15, // PPS. 0x00, 0x00, 0x00, 0x01, // Start code. // The input NALU 1. 0x06, // NALU type. 0xFD, 0x78, 0xA4, 0xC3, 0x82, 0x62, 0x11, 0x29, 0x77, 0x88, 0x00, 0x00, 0x00, 0x01, // Start code. // The input NALU 2. 0x02, // NALU type. 0xFD, 0x78, 0xA4, 0x82, 0x62, 0x29, 0x77, }; // clang-format on const std::vector<SubsampleEntry> kExpectedOutputSubsamples{ SubsampleEntry(73, 7)}; EXPECT_EQ(std::vector<uint8_t>(kExpectedOutput, kExpectedOutput + arraysize(kExpectedOutput)), output); EXPECT_EQ(kExpectedOutputSubsamples, subsamples); } // A clear PPS NALU follows a clear NALU, the PPS in the sample is different to // the PPS in decoder configuration, so both the PPS in the sample and the PPS // in decoder configuration are written to output. TEST(NalUnitToByteStreamConverterTest, ClearPpsDifferent) { // Only the type of the NAL units are checked. const uint8_t kUnitStreamLikeMediaSample[] = { 0x00, 0x00, 0x00, 0x0B, // Size 11 NALU. 0x06, // NAL unit type. 0xFD, 0x78, 0xA4, 0xC3, 0x82, 0x62, 0x11, 0x29, 0x77, 0x88, // clear 0x00, 0x00, 0x00, 0x0A, // Size 10 NALU. 0x68, // PPS, different to the PPS in the decoder // configuration, is also written to output. 0xFE, 0xFD, 0xFC, 0xFB, 0x12, 0x12, 0x13, 0x14, 0x15, // clear 0x00, 0x00, 0x00, 0x08, // Size 8 NALU. 0x02, // NAL unit type. 0xFD, 0x78, 0xA4, 0x82, 0x62, 0x29, 0x77, // Slice data, cipher }; std::vector<SubsampleEntry> subsamples{SubsampleEntry(34, 7)}; NalUnitToByteStreamConverter converter; EXPECT_TRUE( converter.Initialize(kTestAVCDecoderConfigurationRecord, arraysize(kTestAVCDecoderConfigurationRecord))); std::vector<uint8_t> output; EXPECT_TRUE(converter.ConvertUnitToByteStreamWithSubsamples( kUnitStreamLikeMediaSample, arraysize(kUnitStreamLikeMediaSample), kIsKeyFrame, !kEscapeEncryptedNalu, &output, &subsamples)); // clang-format off const uint8_t kExpectedOutput[] = { 0x00, 0x00, 0x00, 0x01, // Start code. 0x09, // AUD type. 0xF0, // primary pic type is anything. 0x00, 0x00, 0x00, 0x01, // Start code. // Some valid SPS data. 0x67, 0x64, 0x00, 0x1E, 0xAC, 0xD9, 0x40, 0xB4, 0x2F, 0xF9, 0x7F, 0xF0, 0x00, 0x80, 0x00, 0x91, 0x00, 0x00, 0x03, 0x03, 0xE9, 0x00, 0x00, 0xEA, 0x60, 0x0F, 0x16, 0x2D, 0x96, 0x00, 0x00, 0x00, 0x01, // Start code. 0x68, 0xFE, 0xFD, 0xFC, 0xFB, 0x11, 0x12, 0x13, 0x14, 0x15, // PPS. 0x00, 0x00, 0x00, 0x01, // Start code. // The input NALU 1. 0x06, // NALU type. 0xFD, 0x78, 0xA4, 0xC3, 0x82, 0x62, 0x11, 0x29, 0x77, 0x88, 0x00, 0x00, 0x00, 0x01, // Start code. // PPS should match the PPS above. 0x68, 0xFE, 0xFD, 0xFC, 0xFB, 0x12, 0x12, 0x13, 0x14, 0x15, 0x00, 0x00, 0x00, 0x01, // Start code. // The input NALU 2. 0x02, // NALU type. 0xFD, 0x78, 0xA4, 0x82, 0x62, 0x29, 0x77, }; // clang-format on const std::vector<SubsampleEntry> kExpectedOutputSubsamples{ SubsampleEntry(87, 7)}; EXPECT_EQ(std::vector<uint8_t>(kExpectedOutput, kExpectedOutput + arraysize(kExpectedOutput)), output); EXPECT_EQ(kExpectedOutputSubsamples, subsamples); } // One NAL unit has more than one subsamples. All subsample except the last // be all-clear subsamples. This case is possible when the clear part is // larger than 16-bit (64Kb), so that the clear part is split into two // subsamples. TEST(NalUnitToByteStreamConverterTest, MultipleSubsamplesInSingleNaluOnlyLastEncrypted) { // Only the type of the NAL units are checked. // This does not contain AUD, SPS, nor PPS. const uint8_t kUnitStreamLikeMediaSample[] = { 0x00, 0x00, 0x00, 0x0A, // Size 10 NALU. 0x06, // NAL unit type. 0xFD, 0x78, 0xA4, 0xC3, 0x82, 0x62, 0x11, 0x29, 0x77, 0x00, 0x00, 0x00, 0x08, // Size 8 NALU. 0x02, // NAL unit type. 0xFD, 0x78, 0xA4, 0x82, 0x62, 0x29, 0x77, // Slice data }; std::vector<SubsampleEntry> subsamples{ SubsampleEntry(6, 0), SubsampleEntry(8, 0), SubsampleEntry(5, 7)}; NalUnitToByteStreamConverter converter; EXPECT_TRUE( converter.Initialize(kTestAVCDecoderConfigurationRecord, arraysize(kTestAVCDecoderConfigurationRecord))); std::vector<uint8_t> output; EXPECT_TRUE(converter.ConvertUnitToByteStreamWithSubsamples( kUnitStreamLikeMediaSample, arraysize(kUnitStreamLikeMediaSample), kIsKeyFrame, !kEscapeEncryptedNalu, &output, &subsamples)); const uint8_t kExpectedOutput[] = { 0x00, 0x00, 0x00, 0x01, // Start code. 0x09, // AUD type. 0xF0, // primary pic type is anything. 0x00, 0x00, 0x00, 0x01, // Start code. // Some valid SPS data. 0x67, 0x64, 0x00, 0x1E, 0xAC, 0xD9, 0x40, 0xB4, 0x2F, 0xF9, 0x7F, 0xF0, 0x00, 0x80, 0x00, 0x91, 0x00, 0x00, 0x03, 0x03, 0xE9, 0x00, 0x00, 0xEA, 0x60, 0x0F, 0x16, 0x2D, 0x96, 0x00, 0x00, 0x00, 0x01, // Start code. 0x68, 0xFE, 0xFD, 0xFC, 0xFB, 0x11, 0x12, 0x13, 0x14, 0x15, // PPS. 0x00, 0x00, 0x00, 0x01, // Start code. // The input NALU 1. 0x06, // NALU type. 0xFD, 0x78, 0xA4, 0xC3, 0x82, 0x62, 0x11, 0x29, 0x77, 0x00, 0x00, 0x00, 0x01, // Start code. // The input NALU 2. 0x02, // NALU type. 0xFD, 0x78, 0xA4, 0x82, 0x62, 0x29, 0x77, }; const std::vector<SubsampleEntry> kExpectedOutputSubsamples{ SubsampleEntry(72, 7)}; EXPECT_EQ(std::vector<uint8_t>(kExpectedOutput, kExpectedOutput + arraysize(kExpectedOutput)), output); EXPECT_EQ(kExpectedOutputSubsamples, subsamples); } // One NAL unit has more than one subsamples. All subsamples have cipher // texts. TEST(NalUnitToByteStreamConverterTest, MultipleSubsamplesInSingleNaluAllEncrypted) { // Only the type of the NAL units are checked. // This does not contain AUD, SPS, nor PPS. const uint8_t kUnitStreamLikeMediaSample[] = { 0x00, 0x00, 0x00, 0x0A, // Size 10 NALU. 0x06, // NAL unit type. 0xFD, 0x78, 0xA4, 0xC3, 0x82, 0x62, 0x11, 0x29, 0x77, 0x00, 0x00, 0x00, 0x10, // Size 16 NALU. 0x02, // NAL unit type. // Slices data. 0xFD, 0x78, 0xA4, 0x82, 0x62, // Encrypted. 0x29, 0x77, 0x27, 0xFD, 0x78, 0xA4, // Clear. 0xC3, 0x82, 0x62, 0x11, // Encrypted. }; // The 2nd (partially) and 3rd subsamples belong to the 2nd input NALU. std::vector<SubsampleEntry> subsamples{ SubsampleEntry(6, 0), SubsampleEntry(13, 5), SubsampleEntry(6, 4)}; NalUnitToByteStreamConverter converter; EXPECT_TRUE( converter.Initialize(kTestAVCDecoderConfigurationRecord, arraysize(kTestAVCDecoderConfigurationRecord))); std::vector<uint8_t> output; EXPECT_TRUE(converter.ConvertUnitToByteStreamWithSubsamples( kUnitStreamLikeMediaSample, arraysize(kUnitStreamLikeMediaSample), kIsKeyFrame, !kEscapeEncryptedNalu, &output, &subsamples)); const uint8_t kExpectedOutput[] = { 0x00, 0x00, 0x00, 0x01, // Start code. 0x09, // AUD type. 0xF0, // primary pic type is anything. 0x00, 0x00, 0x00, 0x01, // Start code. // Some valid SPS data. 0x67, 0x64, 0x00, 0x1E, 0xAC, 0xD9, 0x40, 0xB4, 0x2F, 0xF9, 0x7F, 0xF0, 0x00, 0x80, 0x00, 0x91, 0x00, 0x00, 0x03, 0x03, 0xE9, 0x00, 0x00, 0xEA, 0x60, 0x0F, 0x16, 0x2D, 0x96, 0x00, 0x00, 0x00, 0x01, // Start code. 0x68, 0xFE, 0xFD, 0xFC, 0xFB, 0x11, 0x12, 0x13, 0x14, 0x15, // PPS. 0x00, 0x00, 0x00, 0x01, // Start code. // The input NALU 1. 0x06, // NALU type. 0xFD, 0x78, 0xA4, 0xC3, 0x82, 0x62, 0x11, 0x29, 0x77, 0x00, 0x00, 0x00, 0x01, // Start code. // The input NALU 2. 0x02, // NALU type. // Slices data. 0xFD, 0x78, 0xA4, 0x82, 0x62, // Encrypted. 0x29, 0x77, 0x27, 0xFD, 0x78, 0xA4, // Clear. 0xC3, 0x82, 0x62, 0x11, // Encrypted. }; const std::vector<SubsampleEntry> kExpectedOutputSubsamples{ SubsampleEntry(72, 5), SubsampleEntry(6, 4)}; EXPECT_EQ(std::vector<uint8_t>(kExpectedOutput, kExpectedOutput + arraysize(kExpectedOutput)), output); EXPECT_EQ(kExpectedOutputSubsamples, subsamples); } // One NAL unit is larger than 2^16 bytes and the corresponding subsamples is // split into small subsamples. All subsamples have cipher texts. TEST(NalUnitToByteStreamConverterTest, LargeNaluWithMultipleSubsamples) { // Only the type of the NAL units are checked. // This does not contain AUD, SPS, nor PPS. const uint8_t kUnitStreamLikeMediaSamplePart1[] = { 0x00, 0x00, 0x00, 0x0A, // Size 10 NALU. 0x06, // NAL unit type. 0xFD, 0x78, 0xA4, 0xC3, 0x82, 0x62, 0x11, 0x29, 0x77, // Encrypted. 0x00, 0x01, 0x00, 0x0f, // Size 65551 NALU. 0x02, // NAL unit type. }; const std::vector<uint8_t> kUnitStreamLikeMediaSamplePart2(65535, 0x01); const uint8_t kUnitStreamLikeMediaSamplePart3[] = { // Slices data. 0xFD, 0x78, 0xA4, 0x82, 0x62, // Encrypted. 0x29, 0x77, 0x27, 0xFD, 0x78, 0xA4, // Clear. 0xC3, 0x82, 0x62, 0x11, // Encrypted. }; std::vector<uint8_t> unit_stream_like_media_sample( std::begin(kUnitStreamLikeMediaSamplePart1), std::end(kUnitStreamLikeMediaSamplePart1)); unit_stream_like_media_sample.insert( unit_stream_like_media_sample.end(), std::begin(kUnitStreamLikeMediaSamplePart2), std::end(kUnitStreamLikeMediaSamplePart2)); unit_stream_like_media_sample.insert( unit_stream_like_media_sample.end(), std::begin(kUnitStreamLikeMediaSamplePart3), std::end(kUnitStreamLikeMediaSamplePart3)); std::vector<SubsampleEntry> subsamples{ SubsampleEntry(5, 9), SubsampleEntry(65535, 0), SubsampleEntry(5, 5), SubsampleEntry(6, 4)}; NalUnitToByteStreamConverter converter; EXPECT_TRUE( converter.Initialize(kTestAVCDecoderConfigurationRecord, arraysize(kTestAVCDecoderConfigurationRecord))); std::vector<uint8_t> output; EXPECT_TRUE(converter.ConvertUnitToByteStreamWithSubsamples( unit_stream_like_media_sample.data(), unit_stream_like_media_sample.size(), kIsKeyFrame, !kEscapeEncryptedNalu, &output, &subsamples)); const uint8_t kExpectedOutputPart1[] = { 0x00, 0x00, 0x00, 0x01, // Start code. 0x09, // AUD type. 0xF0, // primary pic type is anything. 0x00, 0x00, 0x00, 0x01, // Start code. // Some valid SPS data. 0x67, 0x64, 0x00, 0x1E, 0xAC, 0xD9, 0x40, 0xB4, 0x2F, 0xF9, 0x7F, 0xF0, 0x00, 0x80, 0x00, 0x91, 0x00, 0x00, 0x03, 0x03, 0xE9, 0x00, 0x00, 0xEA, 0x60, 0x0F, 0x16, 0x2D, 0x96, 0x00, 0x00, 0x00, 0x01, // Start code. 0x68, 0xFE, 0xFD, 0xFC, 0xFB, 0x11, 0x12, 0x13, 0x14, 0x15, // PPS. 0x00, 0x00, 0x00, 0x01, // Start code. // The input NALU 1. 0x06, // NALU type. 0xFD, 0x78, 0xA4, 0xC3, 0x82, 0x62, 0x11, 0x29, 0x77, 0x00, 0x00, 0x00, 0x01, // Start code. // The input NALU 2. 0x02, // NALU type. }; const std::vector<uint8_t> kExpectedOutputPart2 = kUnitStreamLikeMediaSamplePart2; const uint8_t kExpectedOutputPart3[] = { // Slices data. 0xFD, 0x78, 0xA4, 0x82, 0x62, // Encrypted. 0x29, 0x77, 0x27, 0xFD, 0x78, 0xA4, // Clear. 0xC3, 0x82, 0x62, 0x11, // Encrypted. }; std::vector<uint8_t> expected_output(std::begin(kExpectedOutputPart1), std::end(kExpectedOutputPart1)); expected_output.insert(expected_output.end(), std::begin(kExpectedOutputPart2), std::end(kExpectedOutputPart2)); expected_output.insert(expected_output.end(), std::begin(kExpectedOutputPart3), std::end(kExpectedOutputPart3)); const std::vector<SubsampleEntry> kExpectedOutputSubsamples{ SubsampleEntry(58, 9), SubsampleEntry(65535, 0), SubsampleEntry(5, 5), SubsampleEntry(6, 4)}; EXPECT_EQ(expected_output, output); EXPECT_EQ(kExpectedOutputSubsamples, subsamples); } } // namespace media } // namespace shaka
41.569943
82
0.607649
koln67
4f48a1510b2bfc30e11db64af0c28ab3fc1ddf1d
4,237
cpp
C++
dbi_clients_src/pin/pin-3.6-97554-g31f0a167d-gcc-linux/source/tools/ToolUnitTests/attach_app.cpp
DigitalAlchemist/fuzzwatch
32517e7b80b680dd658e833ed2dfdd88744e6694
[ "Apache-2.0" ]
326
2019-08-10T21:17:22.000Z
2022-03-22T08:40:47.000Z
dbi_clients_src/pin/pin-3.6-97554-g31f0a167d-gcc-linux/source/tools/ToolUnitTests/attach_app.cpp
DigitalAlchemist/fuzzwatch
32517e7b80b680dd658e833ed2dfdd88744e6694
[ "Apache-2.0" ]
42
2019-08-13T12:48:19.000Z
2021-11-03T12:57:59.000Z
dbi_clients_src/pin/pin-3.6-97554-g31f0a167d-gcc-linux/source/tools/ToolUnitTests/attach_app.cpp
DigitalAlchemist/fuzzwatch
32517e7b80b680dd658e833ed2dfdd88744e6694
[ "Apache-2.0" ]
66
2019-08-10T21:41:38.000Z
2022-03-17T13:03:42.000Z
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2017 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR ITS 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. END_LEGAL */ /* ===================================================================== */ /*! @file * * A test for attach to single threaded application. * The application launches Pin and waits until Pin attaches */ #include <stdio.h> #include <unistd.h> #include <sched.h> #include <signal.h> #include <stdlib.h> #include <string> #include <list> #include <assert.h> using namespace std; /* Pin doesn't kill the process if if failed to attach, exit on SIGALRM */ void ExitOnAlarm(int sig) { fprintf(stderr, "Pin is not attached, exit on SIGALRM\n"); exit(0); } extern "C" int PinAttached() { return 0; } void PrintArguments(char **inArgv) { fprintf(stderr, "Going to run: "); for(unsigned int i=0; inArgv[i] != 0; ++i) { fprintf(stderr, "%s ", inArgv[i]); } fprintf(stderr, "\n"); } /* * Expected command line: <this exe> [-th_num NUM] -pin $PIN -pinarg <pin args > -t tool <tool args> */ void ParseCommandLine(int argc, char *argv[], list < string>* pinArgs) { string pinBinary; for (int i=1; i<argc; i++) { string arg = string(argv[i]); if (arg == "-pin") { pinBinary = argv[++i]; } else if (arg == "-pinarg") { for (int parg = ++i; parg < argc; parg++) { pinArgs->push_back(string(argv[parg])); ++i; } } } assert(!pinBinary.empty()); pinArgs->push_front(pinBinary); } void StartPin(list <string>* pinArgs) { pid_t appPid = getpid(); pid_t child = fork(); if (child) return; // start Pin from child char **inArgv = new char*[pinArgs->size()+10]; // Pin binary in the first list <string>::iterator pinArgIt = pinArgs->begin(); string pinBinary = *pinArgIt; pinArgIt++; // build pin arguments: // pin -pid appPid -mt 0 [pinarg] unsigned int idx = 0; inArgv[idx++] = (char *)pinBinary.c_str(); inArgv[idx++] = (char*)"-pid"; inArgv[idx] = (char *)malloc(10); sprintf(inArgv[idx++], "%d", appPid); inArgv[idx++] = (char*)"-mt"; inArgv[idx++] = (char*)"0"; for (; pinArgIt != pinArgs->end(); pinArgIt++) { inArgv[idx++]= (char *)pinArgIt->c_str(); } inArgv[idx] = 0; PrintArguments(inArgv); execvp(inArgv[0], inArgv); fprintf(stderr, "ERROR: execv %s failed\n", inArgv[0]); exit(1); } int main(int argc, char * argv[]) { int i; list <string> pinArgs; ParseCommandLine(argc, argv, &pinArgs); StartPin(&pinArgs); /* Exit in 20 sec */ signal(SIGALRM, ExitOnAlarm); alarm(20); printf("Before pause\n"); while (!PinAttached()) { sched_yield(); printf("."); sleep(2); } printf("After pause\n"); return 0; }
26.154321
100
0.654709
DigitalAlchemist
4f48f7862b54048fe8dc674f2f57c108c154ea49
22,080
cpp
C++
externals/skia/src/core/SkSpecialImage.cpp
terrajobst/linux-packaging-skiasharp
47dbb2ff9ae01305b190f409ccea00b3b4f0bc79
[ "MIT" ]
1
2019-10-29T14:36:32.000Z
2019-10-29T14:36:32.000Z
externals/skia/src/core/SkSpecialImage.cpp
terrajobst/linux-packaging-skiasharp
47dbb2ff9ae01305b190f409ccea00b3b4f0bc79
[ "MIT" ]
1
2017-06-18T00:25:03.000Z
2017-11-29T16:01:48.000Z
externals/skia/src/core/SkSpecialImage.cpp
terrajobst/linux-packaging-skiasharp
47dbb2ff9ae01305b190f409ccea00b3b4f0bc79
[ "MIT" ]
5
2017-11-30T06:06:50.000Z
2022-03-31T21:48:49.000Z
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file */ #include "SkSpecialImage.h" #include "SkBitmap.h" #include "SkImage.h" #include "SkBitmapCache.h" #include "SkCanvas.h" #include "SkImage_Base.h" #include "SkSpecialSurface.h" #include "SkSurfacePriv.h" #include "SkPixelRef.h" #if SK_SUPPORT_GPU #include "GrContext.h" #include "GrSurfaceContext.h" #include "GrTexture.h" #include "GrSamplerParams.h" #include "GrTextureProxy.h" #include "SkGr.h" #include "SkGrPriv.h" #endif // Currently the raster imagefilters can only handle certain imageinfos. Call this to know if // a given info is supported. static bool valid_for_imagefilters(const SkImageInfo& info) { // no support for other swizzles/depths yet return info.colorType() == kN32_SkColorType; } /////////////////////////////////////////////////////////////////////////////// class SkSpecialImage_Base : public SkSpecialImage { public: SkSpecialImage_Base(const SkIRect& subset, uint32_t uniqueID, const SkSurfaceProps* props) : INHERITED(subset, uniqueID, props) { } ~SkSpecialImage_Base() override { } virtual void onDraw(SkCanvas*, SkScalar x, SkScalar y, const SkPaint*) const = 0; virtual bool onGetROPixels(SkBitmap*) const = 0; virtual GrContext* onGetContext() const { return nullptr; } virtual SkColorSpace* onGetColorSpace() const = 0; #if SK_SUPPORT_GPU virtual sk_sp<GrTexture> onAsTextureRef(GrContext* context) const = 0; virtual sk_sp<GrTextureProxy> onAsTextureProxy(GrContext* context) const = 0; #endif virtual sk_sp<SkSpecialImage> onMakeSubset(const SkIRect& subset) const = 0; virtual sk_sp<SkSpecialSurface> onMakeSurface(const SkImageFilter::OutputProperties& outProps, const SkISize& size, SkAlphaType at) const = 0; virtual sk_sp<SkImage> onMakeTightSubset(const SkIRect& subset) const = 0; virtual sk_sp<SkSurface> onMakeTightSurface(const SkImageFilter::OutputProperties& outProps, const SkISize& size, SkAlphaType at) const = 0; private: typedef SkSpecialImage INHERITED; }; /////////////////////////////////////////////////////////////////////////////// static inline const SkSpecialImage_Base* as_SIB(const SkSpecialImage* image) { return static_cast<const SkSpecialImage_Base*>(image); } SkSpecialImage::SkSpecialImage(const SkIRect& subset, uint32_t uniqueID, const SkSurfaceProps* props) : fProps(SkSurfacePropsCopyOrDefault(props)) , fSubset(subset) , fUniqueID(kNeedNewImageUniqueID_SpecialImage == uniqueID ? SkNextID::ImageID() : uniqueID) { } sk_sp<SkSpecialImage> SkSpecialImage::makeTextureImage(GrContext* context) { #if SK_SUPPORT_GPU if (!context) { return nullptr; } if (GrContext* curContext = as_SIB(this)->onGetContext()) { return curContext == context ? sk_sp<SkSpecialImage>(SkRef(this)) : nullptr; } SkBitmap bmp; // At this point, we are definitely not texture-backed, so we must be raster or generator // backed. If we remove the special-wrapping-an-image subclass, we may be able to assert that // we are strictly raster-backed (i.e. generator images become raster when they are specialized) // in which case getROPixels could turn into peekPixels... if (!this->getROPixels(&bmp)) { return nullptr; } if (bmp.empty()) { return SkSpecialImage::MakeFromRaster(SkIRect::MakeEmpty(), bmp, &this->props()); } sk_sp<GrTexture> resultTex( GrRefCachedBitmapTexture(context, bmp, GrSamplerParams::ClampNoFilter())); if (!resultTex) { return nullptr; } return SkSpecialImage::MakeFromGpu(SkIRect::MakeWH(resultTex->width(), resultTex->height()), this->uniqueID(), resultTex, sk_ref_sp(this->getColorSpace()), &this->props(), this->alphaType()); #else return nullptr; #endif } void SkSpecialImage::draw(SkCanvas* canvas, SkScalar x, SkScalar y, const SkPaint* paint) const { return as_SIB(this)->onDraw(canvas, x, y, paint); } bool SkSpecialImage::getROPixels(SkBitmap* bm) const { return as_SIB(this)->onGetROPixels(bm); } bool SkSpecialImage::isTextureBacked() const { return SkToBool(as_SIB(this)->onGetContext()); } GrContext* SkSpecialImage::getContext() const { return as_SIB(this)->onGetContext(); } SkColorSpace* SkSpecialImage::getColorSpace() const { return as_SIB(this)->onGetColorSpace(); } #if SK_SUPPORT_GPU sk_sp<GrTexture> SkSpecialImage::asTextureRef(GrContext* context) const { return as_SIB(this)->onAsTextureRef(context); } sk_sp<GrTextureProxy> SkSpecialImage::asTextureProxy(GrContext* context) const { return as_SIB(this)->onAsTextureProxy(context); } #endif sk_sp<SkSpecialSurface> SkSpecialImage::makeSurface(const SkImageFilter::OutputProperties& outProps, const SkISize& size, SkAlphaType at) const { return as_SIB(this)->onMakeSurface(outProps, size, at); } sk_sp<SkSurface> SkSpecialImage::makeTightSurface(const SkImageFilter::OutputProperties& outProps, const SkISize& size, SkAlphaType at) const { return as_SIB(this)->onMakeTightSurface(outProps, size, at); } sk_sp<SkSpecialImage> SkSpecialImage::makeSubset(const SkIRect& subset) const { return as_SIB(this)->onMakeSubset(subset); } sk_sp<SkImage> SkSpecialImage::makeTightSubset(const SkIRect& subset) const { return as_SIB(this)->onMakeTightSubset(subset); } #ifdef SK_DEBUG static bool rect_fits(const SkIRect& rect, int width, int height) { if (0 == width && 0 == height) { SkASSERT(0 == rect.fLeft && 0 == rect.fRight && 0 == rect.fTop && 0 == rect.fBottom); return true; } return rect.fLeft >= 0 && rect.fLeft < width && rect.fLeft < rect.fRight && rect.fRight >= 0 && rect.fRight <= width && rect.fTop >= 0 && rect.fTop < height && rect.fTop < rect.fBottom && rect.fBottom >= 0 && rect.fBottom <= height; } #endif sk_sp<SkSpecialImage> SkSpecialImage::MakeFromImage(const SkIRect& subset, sk_sp<SkImage> image, SkColorSpace* dstColorSpace, const SkSurfaceProps* props) { SkASSERT(rect_fits(subset, image->width(), image->height())); #if SK_SUPPORT_GPU if (GrTexture* texture = as_IB(image)->peekTexture()) { return MakeFromGpu(subset, image->uniqueID(), sk_ref_sp(texture), sk_ref_sp(as_IB(image)->onImageInfo().colorSpace()), props); } else #endif { SkBitmap bm; if (as_IB(image)->getROPixels(&bm, dstColorSpace)) { return MakeFromRaster(subset, bm, props); } } return nullptr; } /////////////////////////////////////////////////////////////////////////////// class SkSpecialImage_Raster : public SkSpecialImage_Base { public: SkSpecialImage_Raster(const SkIRect& subset, const SkBitmap& bm, const SkSurfaceProps* props) : INHERITED(subset, bm.getGenerationID(), props) , fBitmap(bm) { SkASSERT(bm.pixelRef()); // We have to lock now, while bm is still in scope, since it may have come from our // cache, which means we need to keep it locked until we (the special) are done, since // we cannot re-generate the cache entry (if bm came from a generator). fBitmap.lockPixels(); SkASSERT(fBitmap.getPixels()); } SkAlphaType alphaType() const override { return fBitmap.alphaType(); } size_t getSize() const override { return fBitmap.getSize(); } void onDraw(SkCanvas* canvas, SkScalar x, SkScalar y, const SkPaint* paint) const override { SkRect dst = SkRect::MakeXYWH(x, y, this->subset().width(), this->subset().height()); canvas->drawBitmapRect(fBitmap, this->subset(), dst, paint, SkCanvas::kStrict_SrcRectConstraint); } bool onGetROPixels(SkBitmap* bm) const override { *bm = fBitmap; return true; } SkColorSpace* onGetColorSpace() const override { return fBitmap.colorSpace(); } #if SK_SUPPORT_GPU sk_sp<GrTexture> onAsTextureRef(GrContext* context) const override { if (context) { return sk_ref_sp( GrRefCachedBitmapTexture(context, fBitmap, GrSamplerParams::ClampNoFilter())); } return nullptr; } sk_sp<GrTextureProxy> onAsTextureProxy(GrContext* context) const override { if (context) { sk_sp<GrTexture> tex(sk_ref_sp(GrRefCachedBitmapTexture( context, fBitmap, GrSamplerParams::ClampNoFilter()))); sk_sp<GrSurfaceProxy> sProxy = GrSurfaceProxy::MakeWrapped(std::move(tex)); return sk_ref_sp(sProxy->asTextureProxy()); } return nullptr; } #endif // TODO: The raster implementations of image filters all currently assume that the pixels are // legacy N32. Until they actually check the format and operate on sRGB or F16 data appropriately, // we can't enable this. (They will continue to produce incorrect results, but less-so). #define RASTER_IMAGE_FILTERS_SUPPORT_SRGB_AND_F16 0 sk_sp<SkSpecialSurface> onMakeSurface(const SkImageFilter::OutputProperties& outProps, const SkISize& size, SkAlphaType at) const override { #if RASTER_IMAGE_FILTERS_SUPPORT_SRGB_AND_F16 SkColorSpace* colorSpace = outProps.colorSpace(); #else SkColorSpace* colorSpace = nullptr; #endif SkColorType colorType = colorSpace && colorSpace->gammaIsLinear() ? kRGBA_F16_SkColorType : kN32_SkColorType; SkImageInfo info = SkImageInfo::Make(size.width(), size.height(), colorType, at, sk_ref_sp(colorSpace)); return SkSpecialSurface::MakeRaster(info, nullptr); } sk_sp<SkSpecialImage> onMakeSubset(const SkIRect& subset) const override { SkBitmap subsetBM; if (!fBitmap.extractSubset(&subsetBM, subset)) { return nullptr; } return SkSpecialImage::MakeFromRaster(SkIRect::MakeWH(subset.width(), subset.height()), subsetBM, &this->props()); } sk_sp<SkImage> onMakeTightSubset(const SkIRect& subset) const override { SkBitmap subsetBM; if (!fBitmap.extractSubset(&subsetBM, subset)) { return nullptr; } return SkImage::MakeFromBitmap(subsetBM); } sk_sp<SkSurface> onMakeTightSurface(const SkImageFilter::OutputProperties& outProps, const SkISize& size, SkAlphaType at) const override { #if RASTER_IMAGE_FILTERS_SUPPORT_SRGB_AND_F16 SkColorSpace* colorSpace = outProps.colorSpace(); #else SkColorSpace* colorSpace = nullptr; #endif SkColorType colorType = colorSpace && colorSpace->gammaIsLinear() ? kRGBA_F16_SkColorType : kN32_SkColorType; SkImageInfo info = SkImageInfo::Make(size.width(), size.height(), colorType, at, sk_ref_sp(colorSpace)); return SkSurface::MakeRaster(info); } private: SkBitmap fBitmap; typedef SkSpecialImage_Base INHERITED; }; sk_sp<SkSpecialImage> SkSpecialImage::MakeFromRaster(const SkIRect& subset, const SkBitmap& bm, const SkSurfaceProps* props) { SkASSERT(rect_fits(subset, bm.width(), bm.height())); if (!bm.pixelRef()) { return nullptr; } const SkBitmap* srcBM = &bm; SkBitmap tmpStorage; // ImageFilters only handle N32 at the moment, so force our src to be that if (!valid_for_imagefilters(bm.info())) { if (!bm.copyTo(&tmpStorage, kN32_SkColorType)) { return nullptr; } srcBM = &tmpStorage; } return sk_make_sp<SkSpecialImage_Raster>(subset, *srcBM, props); } #if SK_SUPPORT_GPU /////////////////////////////////////////////////////////////////////////////// #include "GrTexture.h" #include "SkImage_Gpu.h" static sk_sp<SkImage> wrap_proxy_in_image(GrContext* context, GrSurfaceProxy* proxy, SkAlphaType alphaType, sk_sp<SkColorSpace> colorSpace) { // TODO: add GrTextureProxy-backed SkImage_Gpus GrSurface* surf = proxy->instantiate(context->textureProvider()); if (!surf) { return nullptr; } return sk_make_sp<SkImage_Gpu>(proxy->width(), proxy->height(), kNeedNewImageUniqueID, alphaType, sk_ref_sp(surf->asTexture()), std::move(colorSpace), SkBudgeted::kYes); } class SkSpecialImage_Gpu : public SkSpecialImage_Base { public: SkSpecialImage_Gpu(const SkIRect& subset, uint32_t uniqueID, sk_sp<GrTexture> tex, SkAlphaType at, sk_sp<SkColorSpace> colorSpace, const SkSurfaceProps* props) : INHERITED(subset, uniqueID, props) , fContext(tex->getContext()) , fAlphaType(at) , fColorSpace(std::move(colorSpace)) , fAddedRasterVersionToCache(false) { fSurfaceProxy = GrSurfaceProxy::MakeWrapped(std::move(tex)); } SkSpecialImage_Gpu(GrContext* context, const SkIRect& subset, uint32_t uniqueID, sk_sp<GrSurfaceProxy> proxy, SkAlphaType at, sk_sp<SkColorSpace> colorSpace, const SkSurfaceProps* props) : INHERITED(subset, uniqueID, props) , fContext(context) , fSurfaceProxy(std::move(proxy)) , fAlphaType(at) , fColorSpace(std::move(colorSpace)) , fAddedRasterVersionToCache(false) { } ~SkSpecialImage_Gpu() override { if (fAddedRasterVersionToCache.load()) { SkNotifyBitmapGenIDIsStale(this->uniqueID()); } } SkAlphaType alphaType() const override { return fAlphaType; } size_t getSize() const override { return fSurfaceProxy->gpuMemorySize(); } void onDraw(SkCanvas* canvas, SkScalar x, SkScalar y, const SkPaint* paint) const override { SkRect dst = SkRect::MakeXYWH(x, y, this->subset().width(), this->subset().height()); // TODO: add GrTextureProxy-backed SkImage_Gpus GrSurface* surf = fSurfaceProxy->instantiate(fContext->textureProvider()); if (!surf) { return; } // TODO: In this instance we know we're going to draw a sub-portion of the backing // texture into the canvas so it is okay to wrap it in an SkImage. This poses // some problems for full deferral however in that when the deferred SkImage_Gpu // instantiates itself it is going to have to either be okay with having a larger // than expected backing texture (unlikely) or the 'fit' of the SurfaceProxy needs // to be tightened (if it is deferred). auto img = sk_sp<SkImage>(new SkImage_Gpu(surf->width(), surf->height(), this->uniqueID(), fAlphaType, sk_ref_sp(surf->asTexture()), fColorSpace, SkBudgeted::kNo)); canvas->drawImageRect(img, this->subset(), dst, paint, SkCanvas::kStrict_SrcRectConstraint); } GrContext* onGetContext() const override { return fContext; } // This entry point should go away in favor of asTextureProxy sk_sp<GrTexture> onAsTextureRef(GrContext* context) const override { GrSurface* surf = fSurfaceProxy->instantiate(context->textureProvider()); if (!surf) { return nullptr; } return sk_ref_sp(surf->asTexture()); } sk_sp<GrTextureProxy> onAsTextureProxy(GrContext*) const override { return sk_ref_sp(fSurfaceProxy->asTextureProxy()); } bool onGetROPixels(SkBitmap* dst) const override { if (SkBitmapCache::Find(this->uniqueID(), dst)) { SkASSERT(dst->getGenerationID() == this->uniqueID()); SkASSERT(dst->isImmutable()); SkASSERT(dst->getPixels()); return true; } SkImageInfo info = SkImageInfo::MakeN32(this->width(), this->height(), this->alphaType(), fColorSpace); if (!dst->tryAllocPixels(info)) { return false; } // Reading back to an SkBitmap ends deferral GrSurface* surface = fSurfaceProxy->instantiate(fContext->textureProvider()); if (!surface) { return false; } if (!surface->readPixels(0, 0, dst->width(), dst->height(), kSkia8888_GrPixelConfig, dst->getPixels(), dst->rowBytes())) { return false; } dst->pixelRef()->setImmutableWithID(this->uniqueID()); SkBitmapCache::Add(this->uniqueID(), *dst); fAddedRasterVersionToCache.store(true); return true; } SkColorSpace* onGetColorSpace() const override { return fColorSpace.get(); } sk_sp<SkSpecialSurface> onMakeSurface(const SkImageFilter::OutputProperties& outProps, const SkISize& size, SkAlphaType at) const override { if (!fContext) { return nullptr; } SkColorSpace* colorSpace = outProps.colorSpace(); return SkSpecialSurface::MakeRenderTarget( fContext, size.width(), size.height(), GrRenderableConfigForColorSpace(colorSpace), sk_ref_sp(colorSpace)); } sk_sp<SkSpecialImage> onMakeSubset(const SkIRect& subset) const override { return SkSpecialImage::MakeDeferredFromGpu(fContext, subset, this->uniqueID(), fSurfaceProxy, fColorSpace, &this->props(), fAlphaType); } // TODO: move all the logic here into the subset-flavor GrSurfaceProxy::copy? sk_sp<SkImage> onMakeTightSubset(const SkIRect& subset) const override { // TODO: this is problematic since the surfaceProxy could be loose if (0 == subset.fLeft && 0 == subset.fTop && fSurfaceProxy->width() == subset.width() && fSurfaceProxy->height() == subset.height()) { // The existing GrTexture is already tight so reuse it in the SkImage return wrap_proxy_in_image(fContext, fSurfaceProxy.get(), fAlphaType, fColorSpace); } sk_sp<GrSurfaceProxy> subsetProxy(GrSurfaceProxy::Copy(fContext, fSurfaceProxy.get(), subset, SkBudgeted::kYes)); return wrap_proxy_in_image(fContext, subsetProxy.get(), fAlphaType, fColorSpace); } sk_sp<SkSurface> onMakeTightSurface(const SkImageFilter::OutputProperties& outProps, const SkISize& size, SkAlphaType at) const override { SkColorSpace* colorSpace = outProps.colorSpace(); SkColorType colorType = colorSpace && colorSpace->gammaIsLinear() ? kRGBA_F16_SkColorType : kRGBA_8888_SkColorType; SkImageInfo info = SkImageInfo::Make(size.width(), size.height(), colorType, at, sk_ref_sp(colorSpace)); return SkSurface::MakeRenderTarget(fContext, SkBudgeted::kYes, info); } private: GrContext* fContext; sk_sp<GrSurfaceProxy> fSurfaceProxy; const SkAlphaType fAlphaType; sk_sp<SkColorSpace> fColorSpace; mutable SkAtomic<bool> fAddedRasterVersionToCache; typedef SkSpecialImage_Base INHERITED; }; sk_sp<SkSpecialImage> SkSpecialImage::MakeFromGpu(const SkIRect& subset, uint32_t uniqueID, sk_sp<GrTexture> tex, sk_sp<SkColorSpace> colorSpace, const SkSurfaceProps* props, SkAlphaType at) { SkASSERT(rect_fits(subset, tex->width(), tex->height())); return sk_make_sp<SkSpecialImage_Gpu>(subset, uniqueID, std::move(tex), at, std::move(colorSpace), props); } sk_sp<SkSpecialImage> SkSpecialImage::MakeDeferredFromGpu(GrContext* context, const SkIRect& subset, uint32_t uniqueID, sk_sp<GrSurfaceProxy> proxy, sk_sp<SkColorSpace> colorSpace, const SkSurfaceProps* props, SkAlphaType at) { SkASSERT(rect_fits(subset, proxy->width(), proxy->height())); return sk_make_sp<SkSpecialImage_Gpu>(context, subset, uniqueID, std::move(proxy), at, std::move(colorSpace), props); } #endif
39.71223
100
0.596422
terrajobst
4f4bba1c4730ddcfad9104e4a9e7a97cf0f765c5
13,958
cpp
C++
software/arduino/libraries/OLED12864/OLED12864.cpp
ericyangs/5dof_arm
21eb5db6642a602984b8c04a7d3fd6d0b3b37688
[ "MIT" ]
null
null
null
software/arduino/libraries/OLED12864/OLED12864.cpp
ericyangs/5dof_arm
21eb5db6642a602984b8c04a7d3fd6d0b3b37688
[ "MIT" ]
null
null
null
software/arduino/libraries/OLED12864/OLED12864.cpp
ericyangs/5dof_arm
21eb5db6642a602984b8c04a7d3fd6d0b3b37688
[ "MIT" ]
null
null
null
#include <Wire.h> #if defined( ESP8266 ) #include <pgmspace.h> #else #include <avr/pgmspace.h> #endif #include "OLED12864.h" #include "oled12864font.c" // Change font file name to prevent overwrite from previous version /* Pending Issues - Option for directDraw - Public function for line drawing (already done in plotter, try to publish the function) - Split library by chipset inherit from OLED12864, some function may duplicated - Draw Text ... allow mix the text with backgroup drawing */ void OLED12864::setInverse(boolean inverseMode) { _inverseMode = inverseMode; } void OLED12864::setFont(uint8_t fontCode) { switch (fontCode) { case OLED_font6x8: _font.fontData = font6x8; break; case OLED_font8x16: _font.fontData = font8x16; break; case OLED_fontNum: _font.fontData = fontNum; break; case OLED_fontBigNum: _font.fontData = fontBigNum; break; default: return; } _font.code = fontCode; _font.sram = false; _font.width = pgm_read_byte(&_font.fontData[0]); _font.height = pgm_read_byte(&_font.fontData[1]); _font.lines = (_font.height + 7) / 8; _font.offset = pgm_read_byte(&_font.fontData[2]); _font.numChars = pgm_read_byte(&_font.fontData[3]); _font.bytePerChar = pgm_read_byte(&_font.fontData[4]); #ifdef _OLED12864_DEBUG_ Serial.print("setFont: >> "); Serial.print(_font.code); Serial.print(" : "); Serial.print(_font.width); Serial.print(" : "); Serial.print(_font.height); Serial.print(" : "); Serial.print(_font.lines); Serial.print(" : "); Serial.print(_font.offset); Serial.print(" : "); Serial.print(_font.bytePerChar); Serial.println(); #endif return; } void OLED12864::setFont(const char *font, boolean sram) { _font.code = OLED_fontUDF; _font.sram = sram; _font.fontData = font; if (sram) { _font.width = _font.fontData[0]; _font.height = _font.fontData[1]; _font.lines = (_font.height + 7) / 8; _font.offset = _font.fontData[2]; _font.numChars = _font.fontData[3]; _font.bytePerChar = _font.width * _font.height / 8; } else { _font.width = pgm_read_byte(&_font.fontData[0]); _font.height = pgm_read_byte(&_font.fontData[1]); _font.lines = (_font.height + 7) / 8; _font.offset = pgm_read_byte(&_font.fontData[2]); _font.numChars = pgm_read_byte(&_font.fontData[3]); _font.bytePerChar = _font.width * _font.height / 8; } #ifdef _OLED12864_DEBUG_ Serial.print("setFont: >> "); Serial.print(_font.code); Serial.print((_font.sram ? " : SRAM : " : " : PROGMEM : ")); Serial.print(_font.width); Serial.print(" : "); Serial.print(_font.height); Serial.print(" : "); Serial.print(_font.lines); Serial.print(" : "); Serial.print(_font.offset); Serial.print(" : "); Serial.print(_font.bytePerChar); Serial.println(); #endif } void OLED12864::setPrintPos(uint8_t x, uint8_t line) { if (invalidXL(x, line)) return; setDisplayPos(x, line); _cursor.x = x; _cursor.y = OLED_LINE_HEIGHT * line; } void OLED12864::println() { uint8_t lineScroll = 0; _cursor.x = 0; if (_cursor.y + 2 * _font.height > OLED_HEIGHT) { scrollLine(OLED_SCROLL_UP, _font.lines); } else { _cursor.y += _font.height; } } void OLED12864::printError(uint8_t x, uint8_t line, uint8_t width, char errCode) { char buf[width + 1]; for (int i = 0; i < width; i++) buf[i] = errCode; buf[width] = '\0'; print(x,line,buf); } // Use long for maximum size void OLED12864::printNum(uint8_t x, uint8_t line, long n, uint8_t base, uint8_t width, boolean fillZero) { #ifdef _OLED12864_DEBUG_ Serial.print("OLED12864::printNumber>> "); Serial.print(x); Serial.print(" : "); Serial.print(line); Serial.print(" : "); Serial.print(n); Serial.print(" : "); Serial.print(base); Serial.print(" : "); Serial.print(width); Serial.print(" : "); Serial.print(fillZero); Serial.println(); #endif char buf[8 * sizeof(long) + 1]; // Assumes 8-bit chars plus zero byte. char *str = &buf[sizeof(buf) - 1]; if (isnan(n)) return printError(x, line, width, 'N'); if (isinf(n)) return printError(x, line, width, 'I'); // Invalid width if (width > sizeof(buf)) { printError(x,line,sizeof(buf)); return; } boolean nve = (n < 0); if (nve) n = -n; if (width < 1) width = 0; int w = 0; *str = '\0'; // prevent crash if called with base == 1 if (base < 2) base = 10; do { unsigned long m = n; n /= base; char c = m - base * n; *--str = c < 10 ? c + '0' : c + 'A' - 10; // Continue to build the string // if (++w == width) break ; w++; } while(n); if (width && ((w > width) || (nve && (w == width)))) { if (nve) *--str = '-'; #ifdef _OLED12864_DEBUG_ Serial.print(" : Over width : "); Serial.println(str); #endif return printError(x, line, width, '*'); } // Different cases // - : fill zero after '-', fill space before '-' // + : simple, just add leading characters if (nve) { if (fillZero) { while (w < width - 1) { *--str = '0'; w++; } *--str = '-'; w++; } else { *--str = '-'; w++; while (w < width) { *--str = ' '; w++; } } } else { while (w < width) { *--str = ((fillZero && !nve) ? '0' : ' '); w++; } } #ifdef _OLED12864_DEBUG_ Serial.print(" : normal >> "); Serial.println(str); #endif print(x, line, str); } // For floating number, leading zero is not supported, overall width is used void OLED12864::printFloat(uint8_t x, uint8_t line, double n, uint8_t decimal, uint8_t width) { #ifdef _OLED12864_DEBUG_ Serial.print("OLED12864::printFloat>> "); Serial.print(n); Serial.print(" : "); Serial.print(decimal); Serial.print(" : "); Serial.print(width); Serial.println(); #endif char buf[21]; // Enforce to max. 20 characters, which should be good enough char *str = &buf[sizeof(buf) - 1]; if (isnan(n)) return printError(x, line, width, 'N'); if (isinf(n)) return printError(x, line, width, 'I'); if (n > 4294967040.0) return printError(x, line, width, '^'); if (n < -4294967040.0) return printError(x, line, width, 'v'); // Invalid width if (width > sizeof(buf)) { printError(x,line,sizeof(buf)); return; } // Display as integer if decimal <= 0 if (decimal <= 0) return printNum(x, line, (int) n, 10, width, false); if (width < 0) width = 0; if (width > 20) width = 20; if (width && (decimal > width - 1)) { printError(x, line, width); return; } boolean nve = (n < 0); if (nve) n = -n; long int_part1 = (long) n; double reminder = n - int_part1; for (int i = 0; i < decimal; i++) reminder *= 10; long int_part2 = (long) reminder; reminder -= int_part2; if (reminder > 0.5) int_part2 += 1; #ifdef _OLED12864_DEBUG_ Serial.print(" : "); Serial.print(int_part1); Serial.print(" : "); Serial.print(reminder); Serial.print(" : "); Serial.print(int_part2); #endif *str = '\0'; int w = 0; for (int i = 0; i < decimal; i++) { unsigned long m = int_part2; int_part2 /= 10; char c = m - int_part2 * 10; *--str = c + '0'; w++; } *--str = '.'; w++; // Special handle for 0.X which can be displayed as .XX only if ((!nve) && (w == width) && (int_part1 == 0)) { #ifdef _OLED12864_DEBUG_ Serial.println(" : 0.X"); #endif return print(x, line, str); } do { unsigned long m = int_part1; int_part1 /= 10; char c = m - 10 * int_part1; *--str = c + '0'; // Continue to build the string // if (++w == width) break ; w++; } while(int_part1); if (nve) { *--str = '-'; w++; } if ((width > 0) && (w > width)) { #ifdef _OLED12864_DEBUG_ Serial.print(" : Over width > "); Serial.println(str); #endif return printError(x, line, width, '*'); } while (w < width) { *--str = ' '; w++; } #ifdef _OLED12864_DEBUG_ Serial.print(" : normal >> "); Serial.println(str); #endif return print(x,line,str); } // --------------------------------------------------------------------------------------------------- void OLED12864::adjCursor() { #ifdef _OLED12864_DEBUG_ Serial.print("adjCursor: scroll >> "); Serial.print(_cursor.x); Serial.print(" : "); Serial.print(_cursor.y); #endif if (_cursor.x + _font.width > OLED_WIDTH) { // No more character can be printed _cursor.x = 0; _cursor.y += _font.height; } if (_cursor.y + _font.height > OLED_HEIGHT) { int minLineScroll = (_cursor.y + _font.height - OLED_HEIGHT - 1) / OLED_LINE_HEIGHT + 1; scrollLine(OLED_SCROLL_UP, minLineScroll); _cursor.y -= (minLineScroll * OLED_LINE_HEIGHT); #ifdef _OLED12864_DEBUG_ Serial.print(" : "); Serial.print(minLineScroll); Serial.print(" : "); Serial.print(_cursor.y); #endif show(); // MUST update the display after scroll if (_scrollDelay) delay(_scrollDelay); } #ifdef _OLED12864_DEBUG_ Serial.println(); #endif } void OLED12864::print(uint8_t x, uint8_t line, const char ch) { // Use string mode for printing char printStr[] = " "; printStr[0] = ch; print(x, line, printStr); } void OLED12864::print(uint8_t x, uint8_t line, const char ch[]) { // simplified for testing only // if (invalidXL(x, line)) return; // -- This will introduce a bug if last printing stopped at last position which will not advance the line until next print. // Try just valid the line only if (invalidLine(line)) return; uint8_t j; uint16_t c; uint16_t bPos; uint8_t data; _cursor.x = x; _cursor.y = line * OLED_LINE_HEIGHT; int maxChars, charsWrite; j = 0; while (ch[j] != '\0') { adjCursor(); maxChars = ((OLED_WIDTH - _cursor.x) / _font.width); // number of characters can be printed in this line. charsWrite = 0; if (maxChars > 0) { line = (_cursor.y / OLED_LINE_HEIGHT); for (int k = 0; k < _font.lines; k++) { setDisplayPos(_cursor.x, line + k); bPos = posXL(_cursor.x, line + k); for (int l = 0; (( l < maxChars) && (ch[j + l] != '\0')) ; l++) { c =ch[j+l] - _font.offset; if (_font.width <= 24) { if (_directDraw) Wire.beginTransmission(_i2cAddress); if (_directDraw) Wire.write(0x40); for (uint8_t i=0; i < _font.width; i++) { data = getFontData(c, 5 + c * _font.bytePerChar + k * _font.width + i); if (_directDraw) Wire.write(data); if (_enableBuffer) _buffer[bPos++] = data; } if (_directDraw) Wire.endTransmission(); } else { for (uint8_t i=0; i < _font.width; i += 8) { if (_directDraw) Wire.beginTransmission(_i2cAddress); if (_directDraw) Wire.write(0x40); uint8_t maxX = min(8, _font.width - i); for (uint8_t x=0; x < maxX; x++) { data = getFontData(c, 5 + c * _font.bytePerChar + k * _font.width + i + x); if (_directDraw) Wire.write(data); if (_enableBuffer) _buffer[bPos++] = data; } if (_directDraw) Wire.endTransmission(); } } if (k == 0) charsWrite++; // only count on first row of chars; it may use l as charsWrite, but will need to check stop condition } } } j += charsWrite; _cursor.x += charsWrite * _font.width; if (ch[j] != '\0') { // advance to next line _cursor.x = 0; _cursor.y += _font.height; } } } void OLED12864::printFlashMsg(uint8_t x, uint8_t line, const char* msgptr) { #ifdef _OLED12864_DEBUG_ Serial.println("printFlashMsg"); #endif _cursor.x = x; _cursor.y = line * OLED_LINE_HEIGHT; // print at most 8 characters at a time (take the balance between buffer size and speed) char prtBuffer[9]; uint8_t idx = 0; uint16_t ptr = 0; boolean goPrint = true; memset(prtBuffer, 0x00, 9); do { // Serial.print(ptr); // Serial.print(" : "); // Serial.println(pgm_read_byte(&msgptr[ptr])); goPrint = (prtBuffer[idx++] = pgm_read_byte(&msgptr[ptr++])); if (goPrint) { if (idx == 8) { print(prtBuffer); #ifdef _OLED12864_DEBUG_ Serial.print(prtBuffer); #endif memset(prtBuffer, 0x00, 8); idx = 0; } } else { if (idx > 1) print(prtBuffer); } } while (goPrint); #ifdef _OLED12864_DEBUG_ Serial.println(); #endif } /* void OLED12864::printFlashMsgArr(uint8_t x, uint8_t line, const char** msg) { Serial.println("printFlashMsgArr"); Serial.print(x); Serial.print(" ,"); Serial.print(line); Serial.println(); printFlashMsg(x, line, (char *)pgm_read_word(msg)); char* msgptr = (char *)pgm_read_word(msg); _cursor.x = x; _cursor.y = line * OLED_LINE_HEIGHT; // print at most 8 characters at a time (take the balance between buffer size and speed) char prtBuffer[9]; uint8_t idx = 0; uint16_t ptr = 0; boolean goPrint = true; memset(prtBuffer, 0x00, 9); do { Serial.print(ptr); Serial.print(" : "); Serial.println(pgm_read_byte(&msgptr[ptr])); goPrint = (prtBuffer[idx++] = pgm_read_byte(&msgptr[ptr++])); if (goPrint) { if (idx == 8) { print(prtBuffer); memset(prtBuffer, 0x00, 8); idx = 0; } } else { if (idx > 1) print(prtBuffer); } } while (goPrint); } */ uint8_t OLED12864::getFontData(uint16_t c, uint16_t address) { uint8_t data; if ((c < 0) or (c >= _font.numChars)) return _invalidChar; if (_font.sram) data = _font.fontData[address]; else data = pgm_read_byte(&_font.fontData[address]); if (_inverseMode) data = ~data; return data; }
23.819113
135
0.586904
ericyangs
4f4d47a102ddbcc0d4c60f8b5c3eaad9469b900b
7,134
hpp
C++
public/inc/audio/smartx/rtprocessingfwx/IasSimpleAudioStream.hpp
juimonen/SmartXbar
033f521a5dba5bce5e097df9c98af5b2cc2636dd
[ "BSD-3-Clause" ]
5
2018-11-05T07:37:58.000Z
2022-03-04T06:40:09.000Z
public/inc/audio/smartx/rtprocessingfwx/IasSimpleAudioStream.hpp
juimonen/SmartXbar
033f521a5dba5bce5e097df9c98af5b2cc2636dd
[ "BSD-3-Clause" ]
null
null
null
public/inc/audio/smartx/rtprocessingfwx/IasSimpleAudioStream.hpp
juimonen/SmartXbar
033f521a5dba5bce5e097df9c98af5b2cc2636dd
[ "BSD-3-Clause" ]
7
2018-12-04T07:32:19.000Z
2021-02-17T11:28:28.000Z
/* * Copyright (C) 2018 Intel Corporation.All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ /** * @file IasSimpleAudioStream.hpp * @date 2013 * @brief The definition of the IasSimpleAudioStream class. */ #ifndef IASSIMPLEAUDIOSTREAM_HPP_ #define IASSIMPLEAUDIOSTREAM_HPP_ #include "audio/smartx/rtprocessingfwx/IasBaseAudioStream.hpp" #include "audio/smartx/rtprocessingfwx/IasProcessingTypes.hpp" namespace IasAudio { class IasSimpleAudioStream; class IasAudioBuffer; /** * @class IasSimpleAudioStream * * This class defines an audio stream. An audio stream is a combination of several * mono audio channels. Audio streams are used to route the data through the audio chain. A vector * of audio streams is provided to each audio processing component to process the data belonging to * an audio stream. */ class IAS_AUDIO_PUBLIC IasSimpleAudioStream : public IasBaseAudioStream { public: /** * @brief Constructor. */ IasSimpleAudioStream(); /** * @brief Destructor, virtual by default. */ virtual ~IasSimpleAudioStream(); /* * @brief Set the properties of this audio stream. * * @param[in] name The name of the audio stream. * @param[in] id The ID of the audio stream. * @param[in] numberChannels The number of channels of the audio stream. * @param[in] sampleLayout The layout of the samples in the buffer. See #IasSampleLayout. * @param[in] frameLength The number of frames of one buffer. */ IasAudioProcessingResult setProperties(const std::string &name, int32_t id, uint32_t numberChannels, IasSampleLayout sampleLayout, uint32_t frameLength, IasAudioStreamTypes type, bool sidAvailable); /** * @brief Return all buffers back to pool */ void cleanup(); /** * @brief Get a reference to a vector with pointers to all single audio channels. * * @returns A vector with pointers to all single audio channels. */ const IasAudioFrame& getAudioBuffers() const { return mAudioFrame; } /** * @brief Write (copy) data into the stream channel buffers. * * The audio frame given as parameter contains pointers to channels with non-interleaved audio samples. * @note: This method may only be called the first time each processing cycle when the data is copied initially * to the stream buffer. * * @param[in] audioFrame A vector with pointers to the audio channels to be copied into the streams memory buffer. * * @returns The result indicating success (eIasAudioProcOK) or failure. */ IasAudioProcessingResult writeFromNonInterleaved(const IasAudioFrame &audioFrame); /** * @brief Write (copy) data into the stream channel buffers. * * The audio frame given as parameter contains pointers to channels with bundled audio samples. * * @param[in] audioFrame A vector with pointers to the audio channels to be copied into the streams memory buffer. * * @returns The result indicating success (eIasAudioProcOK) or failure. */ IasAudioProcessingResult writeFromBundled(const IasAudioFrame &audioFrame); /** * @brief Provide non-interleaved representation of stream. * * This method will convert the current representation of the stream into the * requested one or does nothing if the current representation matches the * requested representation. The given pointer has to point to an existing valid * IasSimpleAudioStream instance which will be filled with the samples of * the current representation. * * @param[in,out] nonInterleaved Pointer to non-interleaved representation */ virtual void asNonInterleavedStream(IasSimpleAudioStream *nonInterleaved); /** * @brief Provide interleaved representation of stream. * * This method will convert the current representation of the stream into the * requested one or does nothing if the current representation matches the * requested representation. The given pointer has to point to an existing valid * IasSimpleAudioStream instance which will be filled with the samples of * the current representation. * * @param[in,out] interleaved Pointer to interleaved representation */ virtual void asInterleavedStream(IasSimpleAudioStream *interleaved); /** * @brief Provide bundled representation of stream. * * This method will convert the current representation of the stream into the * requested one or does nothing if the current representation matches the * requested representation. The given pointer has to point to an existing valid * IasSimpleAudioStream instance which will be filled with the samples of * the current representation. * * @param[in,out] bundled Pointer to bundled representation */ virtual void asBundledStream(IasBundledAudioStream *bundled); /** * @brief Copy the samples to the location referenced by outAudioFrame. * * This method copies the audio samples of the stream to the location referenced * by outAudioFrame. outAudioFrame has to contain valid pointers to non-interleaved * audio buffers, one buffer for each channel. * * @param[in,out] outAudioFrame Audio frame containing pointers to the destination of the audio samples. */ virtual void copyToOutputAudioChannels(const IasAudioFrame &outAudioFrame) const; /** * @brief Get access to the internal channel buffers of the audio stream. * * @param[out] audioFrame Frame of pointers that shall be set to the channel buffers (one pointer for each channel). * When calling this function, the audioFrame must already have the correct size * (according to the number of channels). * @param[out] stride Stride between two samples, expressed in samples. */ virtual IasAudioProcessingResult getAudioDataPointers(IasAudioFrame &audioFrame, uint32_t *stride) const; protected: // Member variables IasAudioFrame mAudioFrame; //!< A vector with pointers to every single audio channel. uint32_t mFrameLength; //!< The frame length for one audio channel buffer in number of samples. IasAudioBuffer *mBuffer; //!< A pointer to the used audio buffer from the buffer pool. private: /** * @brief Copy constructor, private unimplemented to prevent misuse. */ IasSimpleAudioStream(IasSimpleAudioStream const &other); /** * @brief Assignment operator, private unimplemented to prevent misuse. */ IasSimpleAudioStream& operator=(IasSimpleAudioStream const &other); }; } //namespace IasAudio #endif /* IASSIMPLEAUDIOSTREAM_HPP_ */
39.414365
127
0.679563
juimonen
4f4d7ec0cc920886ccf808cfb8d7a52e327eee14
41,269
cpp
C++
misc/repoconv/svn2git/svn-fast-export/svn.cpp
earl-ducaine/brlcad-mirror
402bd3542a10618d1f749b264cadf9b0bd723546
[ "BSD-4-Clause", "BSD-3-Clause" ]
1
2019-10-23T16:17:49.000Z
2019-10-23T16:17:49.000Z
misc/repoconv/svn2git/svn-fast-export/svn.cpp
pombredanne/sf.net-brlcad
fb56f37c201b51241e8f3aa7b979436856f43b8c
[ "BSD-4-Clause", "BSD-3-Clause" ]
null
null
null
misc/repoconv/svn2git/svn-fast-export/svn.cpp
pombredanne/sf.net-brlcad
fb56f37c201b51241e8f3aa7b979436856f43b8c
[ "BSD-4-Clause", "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2007 Thiago Macieira <thiago@kde.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Based on svn-fast-export by Chris Lee <clee@kde.org> * License: MIT <http://www.opensource.org/licenses/mit-license.php> * URL: git://repo.or.cz/fast-import.git http://repo.or.cz/w/fast-export.git */ #define _XOPEN_SOURCE #define _LARGEFILE_SUPPORT #define _LARGEFILE64_SUPPORT #include <iostream> #include <fstream> #include <sys/stat.h> #include "svn.h" #include "CommandLineParser.h" #include <unistd.h> #include <string.h> #include <stdio.h> #include <time.h> #include <unistd.h> #include <apr_lib.h> #include <apr_getopt.h> #include <apr_general.h> #include <svn_fs.h> #include <svn_pools.h> #include <svn_repos.h> #include <svn_types.h> #include <svn_version.h> #include <QFile> #include <QDebug> #include "repository.h" #undef SVN_ERR #define SVN_ERR(expr) SVN_INT_ERR(expr) #if SVN_VER_MAJOR == 1 && SVN_VER_MINOR < 9 #define svn_stream_read_full svn_stream_read #endif typedef QList<Rules::Match> MatchRuleList; typedef QHash<QString, Repository *> RepositoryHash; typedef QHash<QByteArray, QByteArray> IdentityHash; class AprAutoPool { apr_pool_t *pool; AprAutoPool(const AprAutoPool &); AprAutoPool &operator=(const AprAutoPool &); public: inline AprAutoPool(apr_pool_t *parent = NULL) { pool = svn_pool_create(parent); } inline ~AprAutoPool() { svn_pool_destroy(pool); } inline void clear() { svn_pool_clear(pool); } inline apr_pool_t *data() const { return pool; } inline operator apr_pool_t *() const { return pool; } }; class SvnPrivate { public: QList<MatchRuleList> allMatchRules; RepositoryHash repositories; IdentityHash identities; QString userdomain; SvnPrivate(const QString &pathToRepository); ~SvnPrivate(); int youngestRevision(); int exportRevision(int revnum); int openRepository(const QString &pathToRepository); private: AprAutoPool global_pool; AprAutoPool scratch_pool; svn_fs_t *fs; svn_revnum_t youngest_rev; }; void Svn::initialize() { // initialize APR or exit if (apr_initialize() != APR_SUCCESS) { fprintf(stderr, "You lose at apr_initialize().\n"); exit(1); } // static destructor static struct Destructor { ~Destructor() { apr_terminate(); } } destructor; } Svn::Svn(const QString &pathToRepository) : d(new SvnPrivate(pathToRepository)) { } Svn::~Svn() { delete d; } void Svn::setMatchRules(const QList<MatchRuleList> &allMatchRules) { d->allMatchRules = allMatchRules; } void Svn::setRepositories(const RepositoryHash &repositories) { d->repositories = repositories; } void Svn::setIdentityMap(const IdentityHash &identityMap) { d->identities = identityMap; } void Svn::setIdentityDomain(const QString &identityDomain) { d->userdomain = identityDomain; } int Svn::youngestRevision() { return d->youngestRevision(); } bool Svn::exportRevision(int revnum) { return d->exportRevision(revnum) == EXIT_SUCCESS; } SvnPrivate::SvnPrivate(const QString &pathToRepository) : global_pool(NULL) , scratch_pool(NULL) { if( openRepository(pathToRepository) != EXIT_SUCCESS) { qCritical() << "Failed to open repository"; exit(1); } // get the youngest revision svn_fs_youngest_rev(&youngest_rev, fs, global_pool); } SvnPrivate::~SvnPrivate() {} int SvnPrivate::youngestRevision() { return youngest_rev; } int SvnPrivate::openRepository(const QString &pathToRepository) { svn_repos_t *repos; QString path = pathToRepository; while (path.endsWith('/')) // no trailing slash allowed path = path.mid(0, path.length()-1); #if SVN_VER_MAJOR == 1 && SVN_VER_MINOR < 9 SVN_ERR(svn_repos_open2(&repos, QFile::encodeName(path), NULL, global_pool)); #else SVN_ERR(svn_repos_open3(&repos, QFile::encodeName(path), NULL, global_pool, scratch_pool)); #endif fs = svn_repos_fs(repos); return EXIT_SUCCESS; } enum RuleType { AnyRule = 0, NoIgnoreRule = 0x01, NoRecurseRule = 0x02 }; static MatchRuleList::ConstIterator findMatchRule(const MatchRuleList &matchRules, int revnum, const QString &current, int ruleMask = AnyRule) { MatchRuleList::ConstIterator it = matchRules.constBegin(), end = matchRules.constEnd(); for ( ; it != end; ++it) { if (it->minRevision > revnum) continue; if (it->maxRevision != -1 && it->maxRevision < revnum) continue; if (it->action == Rules::Match::Ignore && ruleMask & NoIgnoreRule) continue; if (it->action == Rules::Match::Recurse && ruleMask & NoRecurseRule) continue; if (it->rx.indexIn(current) == 0) { Stats::instance()->ruleMatched(*it, revnum); return it; } } // no match return end; } static int pathMode(svn_fs_root_t *fs_root, const char *pathname, apr_pool_t *pool) { svn_string_t *propvalue; SVN_ERR(svn_fs_node_prop(&propvalue, fs_root, pathname, "svn:executable", pool)); int mode = 0100644; if (propvalue) mode = 0100755; return mode; } svn_error_t *QIODevice_write(void *baton, const char *data, apr_size_t *len) { QIODevice *device = reinterpret_cast<QIODevice *>(baton); device->write(data, *len); while (device->bytesToWrite() > 32*1024) { if (!device->waitForBytesWritten(-1)) { qFatal("Failed to write to process: %s", qPrintable(device->errorString())); return svn_error_createf(APR_EOF, SVN_NO_ERROR, "Failed to write to process: %s", qPrintable(device->errorString())); } } return SVN_NO_ERROR; } static svn_stream_t *streamForDevice(QIODevice *device, apr_pool_t *pool) { svn_stream_t *stream = svn_stream_create(device, pool); svn_stream_set_write(stream, QIODevice_write); return stream; } static int dumpBlob(Repository::Transaction *txn, svn_fs_root_t *fs_root, const char *pathname, const QString &finalPathName, apr_pool_t *pool) { AprAutoPool dumppool(pool); // what type is it? int mode = pathMode(fs_root, pathname, dumppool); svn_filesize_t stream_length; SVN_ERR(svn_fs_file_length(&stream_length, fs_root, pathname, dumppool)); svn_stream_t *in_stream, *out_stream; if (!CommandLineParser::instance()->contains("dry-run")) { // open the file SVN_ERR(svn_fs_file_contents(&in_stream, fs_root, pathname, dumppool)); } // maybe it's a symlink? svn_string_t *propvalue; SVN_ERR(svn_fs_node_prop(&propvalue, fs_root, pathname, "svn:special", dumppool)); if (propvalue) { apr_size_t len = strlen("link "); if (!CommandLineParser::instance()->contains("dry-run")) { QByteArray buf; buf.reserve(len); SVN_ERR(svn_stream_read_full(in_stream, buf.data(), &len)); if (len == strlen("link ") && strncmp(buf, "link ", len) == 0) { mode = 0120000; stream_length -= len; } else { //this can happen if a link changed into a file in one commit qWarning("file %s is svn:special but not a symlink", pathname); // re-open the file as we tried to read "link " svn_stream_close(in_stream); SVN_ERR(svn_fs_file_contents(&in_stream, fs_root, pathname, dumppool)); } } } QIODevice *io = txn->addFile(finalPathName, mode, stream_length); if (!CommandLineParser::instance()->contains("dry-run")) { // open a generic svn_stream_t for the QIODevice out_stream = streamForDevice(io, dumppool); SVN_ERR(svn_stream_copy3(in_stream, out_stream, NULL, NULL, dumppool)); // print an ending newline io->putChar('\n'); } return EXIT_SUCCESS; } static int recursiveDumpDir(Repository::Transaction *txn, svn_fs_root_t *fs_root, const QByteArray &pathname, const QString &finalPathName, apr_pool_t *pool, svn_revnum_t revnum, const Rules::Match &rule, const MatchRuleList &matchRules, bool ruledebug) { // get the dir listing apr_hash_t *entries; SVN_ERR(svn_fs_dir_entries(&entries, fs_root, pathname, pool)); AprAutoPool dirpool(pool); // While we get a hash, put it in a map for sorted lookup, so we can // repeat the conversions and get the same git commit hashes. QMap<QByteArray, svn_node_kind_t> map; for (apr_hash_index_t *i = apr_hash_first(pool, entries); i; i = apr_hash_next(i)) { const void *vkey; void *value; apr_hash_this(i, &vkey, NULL, &value); svn_fs_dirent_t *dirent = reinterpret_cast<svn_fs_dirent_t *>(value); map.insertMulti(QByteArray(dirent->name), dirent->kind); } QMapIterator<QByteArray, svn_node_kind_t> i(map); while (i.hasNext()) { dirpool.clear(); i.next(); QByteArray entryName = pathname + '/' + i.key(); QString entryFinalName = finalPathName + QString::fromUtf8(i.key()); if (i.value() == svn_node_dir) { entryFinalName += '/'; QString entryNameQString = entryName + '/'; MatchRuleList::ConstIterator match = findMatchRule(matchRules, revnum, entryNameQString); if (match == matchRules.constEnd()) continue; // no match of parent repo? (should not happen) const Rules::Match &matchedRule = *match; if (matchedRule.action != Rules::Match::Export || matchedRule.repository != rule.repository) { if (ruledebug) qDebug() << "recursiveDumpDir:" << entryNameQString << "skip entry for different/ignored repository"; continue; } if (recursiveDumpDir(txn, fs_root, entryName, entryFinalName, dirpool, revnum, rule, matchRules, ruledebug) == EXIT_FAILURE) return EXIT_FAILURE; } else if (i.value() == svn_node_file) { printf("+"); fflush(stdout); if (dumpBlob(txn, fs_root, entryName, entryFinalName, dirpool) == EXIT_FAILURE) return EXIT_FAILURE; } } return EXIT_SUCCESS; } static bool wasDir(svn_fs_t *fs, int revnum, const char *pathname, apr_pool_t *pool) { AprAutoPool subpool(pool); svn_fs_root_t *fs_root; if (svn_fs_revision_root(&fs_root, fs, revnum, subpool) != SVN_NO_ERROR) return false; svn_boolean_t is_dir; if (svn_fs_is_dir(&is_dir, fs_root, pathname, subpool) != SVN_NO_ERROR) return false; return is_dir; } time_t get_epoch(const char* svn_date) { struct tm tm; memset(&tm, 0, sizeof tm); QByteArray date(svn_date, strlen(svn_date) - 8); strptime(date, "%Y-%m-%dT%H:%M:%S", &tm); return timegm(&tm); } class SvnRevision { public: AprAutoPool pool; QHash<QString, Repository::Transaction *> transactions; QList<MatchRuleList> allMatchRules; RepositoryHash repositories; IdentityHash identities; QString userdomain; svn_fs_t *fs; svn_fs_root_t *fs_root; int revnum; // must call fetchRevProps first: QByteArray authorident; QByteArray log; uint epoch; bool ruledebug; bool propsFetched; bool needCommit; SvnRevision(int revision, svn_fs_t *f, apr_pool_t *parent_pool) : pool(parent_pool), fs(f), fs_root(0), revnum(revision), propsFetched(false) { ruledebug = CommandLineParser::instance()->contains( QLatin1String("debug-rules")); } int open() { SVN_ERR(svn_fs_revision_root(&fs_root, fs, revnum, pool)); return EXIT_SUCCESS; } int prepareTransactions(); int fetchRevProps(); int commit(); int exportEntry(const char *path, const svn_fs_path_change2_t *change, apr_hash_t *changes); int exportDispatch(const char *path, const svn_fs_path_change2_t *change, const char *path_from, svn_revnum_t rev_from, apr_hash_t *changes, const QString &current, const Rules::Match &rule, const MatchRuleList &matchRules, apr_pool_t *pool); int exportInternal(const char *path, const svn_fs_path_change2_t *change, const char *path_from, svn_revnum_t rev_from, const QString &current, const Rules::Match &rule, const MatchRuleList &matchRules); int recurse(const char *path, const svn_fs_path_change2_t *change, const char *path_from, const MatchRuleList &matchRules, svn_revnum_t rev_from, apr_hash_t *changes, apr_pool_t *pool); int addGitIgnore(apr_pool_t *pool, const char *key, QString path, svn_fs_root_t *fs_root, Repository::Transaction *txn, const char *content = NULL); int fetchIgnoreProps(QString *ignore, apr_pool_t *pool, const char *key, svn_fs_root_t *fs_root); int fetchUnknownProps(apr_pool_t *pool, const char *key, svn_fs_root_t *fs_root); private: void splitPathName(const Rules::Match &rule, const QString &pathName, QString *svnprefix_p, QString *repository_p, QString *effectiveRepository_p, QString *branch_p, QString *path_p); }; int SvnPrivate::exportRevision(int revnum) { SvnRevision rev(revnum, fs, global_pool); rev.allMatchRules = allMatchRules; rev.repositories = repositories; rev.identities = identities; rev.userdomain = userdomain; // open this revision: printf("Exporting revision %d ", revnum); fflush(stdout); if (rev.open() == EXIT_FAILURE) return EXIT_FAILURE; if (rev.prepareTransactions() == EXIT_FAILURE) return EXIT_FAILURE; if (!rev.needCommit) { printf(" nothing to do\n"); return EXIT_SUCCESS; // no changes? } if (rev.commit() == EXIT_FAILURE) return EXIT_FAILURE; printf(" done\n"); return EXIT_SUCCESS; } void SvnRevision::splitPathName(const Rules::Match &rule, const QString &pathName, QString *svnprefix_p, QString *repository_p, QString *effectiveRepository_p, QString *branch_p, QString *path_p) { QString svnprefix = pathName; svnprefix.truncate(rule.rx.matchedLength()); if (svnprefix_p) { *svnprefix_p = svnprefix; } if (repository_p) { *repository_p = svnprefix; repository_p->replace(rule.rx, rule.repository); foreach (Rules::Match::Substitution subst, rule.repo_substs) { subst.apply(*repository_p); } } if (effectiveRepository_p) { *effectiveRepository_p = svnprefix; effectiveRepository_p->replace(rule.rx, rule.repository); foreach (Rules::Match::Substitution subst, rule.repo_substs) { subst.apply(*effectiveRepository_p); } Repository *repository = repositories.value(*effectiveRepository_p, 0); if (repository) { *effectiveRepository_p = repository->getEffectiveRepository()->getName(); } } if (branch_p) { *branch_p = svnprefix; branch_p->replace(rule.rx, rule.branch); foreach (Rules::Match::Substitution subst, rule.branch_substs) { subst.apply(*branch_p); } } if (path_p) { QString prefix = svnprefix; prefix.replace(rule.rx, rule.prefix); *path_p = prefix + pathName.mid(svnprefix.length()); } } int SvnRevision::prepareTransactions() { // find out what was changed in this revision: apr_hash_t *changes; SVN_ERR(svn_fs_paths_changed2(&changes, fs_root, pool)); QMap<QByteArray, svn_fs_path_change2_t*> map; for (apr_hash_index_t *i = apr_hash_first(pool, changes); i; i = apr_hash_next(i)) { const void *vkey; void *value; apr_hash_this(i, &vkey, NULL, &value); const char *key = reinterpret_cast<const char *>(vkey); svn_fs_path_change2_t *change = reinterpret_cast<svn_fs_path_change2_t *>(value); // If we mix path deletions with path adds/replaces we might erase a // branch after that it has been reset -> history truncated if (map.contains(QByteArray(key))) { // If the same path is deleted and added, we need to put the // deletions into the map first, then the addition. if (change->change_kind == svn_fs_path_change_delete) { // XXX } fprintf(stderr, "\nDuplicate key found in rev %d: %s\n", revnum, key); fprintf(stderr, "This needs more code to be handled, file a bug report\n"); fflush(stderr); exit(1); } map.insertMulti(QByteArray(key), change); } QMapIterator<QByteArray, svn_fs_path_change2_t*> i(map); while (i.hasNext()) { i.next(); if (exportEntry(i.key(), i.value(), changes) == EXIT_FAILURE) return EXIT_FAILURE; } return EXIT_SUCCESS; } int SvnRevision::fetchRevProps() { if( propsFetched ) return EXIT_SUCCESS; apr_hash_t *revprops; SVN_ERR(svn_fs_revision_proplist(&revprops, fs, revnum, pool)); svn_string_t *svnauthor = (svn_string_t*)apr_hash_get(revprops, "svn:author", APR_HASH_KEY_STRING); svn_string_t *svndate = (svn_string_t*)apr_hash_get(revprops, "svn:date", APR_HASH_KEY_STRING); svn_string_t *svnlog = (svn_string_t*)apr_hash_get(revprops, "svn:log", APR_HASH_KEY_STRING); if (svnlog) log = svnlog->data; else log.clear(); authorident = svnauthor ? identities.value(svnauthor->data) : QByteArray(); epoch = svndate ? get_epoch(svndate->data) : 0; if (authorident.isEmpty()) { if (!svnauthor || svn_string_isempty(svnauthor)) authorident = "nobody <nobody@localhost>"; else authorident = svnauthor->data + QByteArray(" <") + svnauthor->data + QByteArray("@") + userdomain.toUtf8() + QByteArray(">"); } propsFetched = true; return EXIT_SUCCESS; } int SvnRevision::commit() { // now create the commit if (fetchRevProps() != EXIT_SUCCESS) return EXIT_FAILURE; foreach (Repository *repo, repositories.values()) { repo->commit(); } foreach (Repository::Transaction *txn, transactions) { txn->setAuthor(authorident); txn->setDateTime(epoch); txn->setLog(log); txn->commit(); delete txn; } return EXIT_SUCCESS; } int SvnRevision::exportEntry(const char *key, const svn_fs_path_change2_t *change, apr_hash_t *changes) { AprAutoPool revpool(pool.data()); QString current = QString::fromUtf8(key); // was this copied from somewhere? svn_revnum_t rev_from = SVN_INVALID_REVNUM; const char *path_from = NULL; if (change->change_kind != svn_fs_path_change_delete) { // svn_fs_copied_from would fail on deleted paths, because the path // obviously no longer exists in the current revision SVN_ERR(svn_fs_copied_from(&rev_from, &path_from, fs_root, key, revpool)); } // is this a directory? svn_boolean_t is_dir; SVN_ERR(svn_fs_is_dir(&is_dir, fs_root, key, revpool)); // Adding newly created directories if (is_dir && change->change_kind == svn_fs_path_change_add && path_from == NULL && CommandLineParser::instance()->contains("empty-dirs")) { QString keyQString = key; // Skipping SVN-directory-layout if (keyQString.endsWith("/trunk") || keyQString.endsWith("/branches") || keyQString.endsWith("/tags")) { //qDebug() << "Skipping SVN-directory-layout:" << keyQString; return EXIT_SUCCESS; } needCommit = true; //qDebug() << "Adding directory:" << key; } // svn:ignore-properties else if (is_dir && (change->change_kind == svn_fs_path_change_add || change->change_kind == svn_fs_path_change_modify) && path_from == NULL && CommandLineParser::instance()->contains("svn-ignore")) { needCommit = true; } else if (is_dir) { if (change->change_kind == svn_fs_path_change_modify || change->change_kind == svn_fs_path_change_add) { if (path_from == NULL) { // freshly added directory, or modified properties // Git doesn't handle directories, so we don't either //qDebug() << " mkdir ignored:" << key; return EXIT_SUCCESS; } qDebug() << " " << key << "was copied from" << path_from << "rev" << rev_from; } else if (change->change_kind == svn_fs_path_change_replace) { if (path_from == NULL) qDebug() << " " << key << "was replaced"; else qDebug() << " " << key << "was replaced from" << path_from << "rev" << rev_from; } else if (change->change_kind == svn_fs_path_change_reset) { qCritical() << " " << key << "was reset, panic!"; return EXIT_FAILURE; } else { // if change_kind == delete, it shouldn't come into this arm of the 'is_dir' test qCritical() << " " << key << "has unhandled change kind " << change->change_kind << ", panic!"; return EXIT_FAILURE; } } else if (change->change_kind == svn_fs_path_change_delete) { is_dir = wasDir(fs, revnum - 1, key, revpool); } if (is_dir) current += '/'; //MultiRule: loop start //Replace all returns with continue, bool isHandled = false; foreach ( const MatchRuleList matchRules, allMatchRules ) { // find the first rule that matches this pathname MatchRuleList::ConstIterator match = findMatchRule(matchRules, revnum, current); if (match != matchRules.constEnd()) { const Rules::Match &rule = *match; if ( exportDispatch(key, change, path_from, rev_from, changes, current, rule, matchRules, revpool) == EXIT_FAILURE ) return EXIT_FAILURE; isHandled = true; } else if (is_dir && path_from != NULL) { qDebug() << current << "is a copy-with-history, auto-recursing"; if ( recurse(key, change, path_from, matchRules, rev_from, changes, revpool) == EXIT_FAILURE ) return EXIT_FAILURE; isHandled = true; } else if (is_dir && change->change_kind == svn_fs_path_change_delete) { qDebug() << current << "deleted, auto-recursing"; if ( recurse(key, change, path_from, matchRules, rev_from, changes, revpool) == EXIT_FAILURE ) return EXIT_FAILURE; isHandled = true; } } if ( isHandled ) { return EXIT_SUCCESS; } if (wasDir(fs, revnum - 1, key, revpool)) { qDebug() << current << "was a directory; ignoring"; } else if (change->change_kind == svn_fs_path_change_delete) { qDebug() << current << "is being deleted but I don't know anything about it; ignoring"; } else { qCritical() << current << "did not match any rules; cannot continue"; return EXIT_FAILURE; } return EXIT_SUCCESS; } int SvnRevision::exportDispatch(const char *key, const svn_fs_path_change2_t *change, const char *path_from, svn_revnum_t rev_from, apr_hash_t *changes, const QString &current, const Rules::Match &rule, const MatchRuleList &matchRules, apr_pool_t *pool) { //if(ruledebug) // qDebug() << "rev" << revnum << qPrintable(current) << "matched rule:" << rule.lineNumber << "(" << rule.rx.pattern() << ")"; switch (rule.action) { case Rules::Match::Ignore: //if(ruledebug) // qDebug() << " " << "ignoring."; return EXIT_SUCCESS; case Rules::Match::Recurse: if(ruledebug) qDebug() << "rev" << revnum << qPrintable(current) << "matched rule:" << rule.info() << " " << "recursing."; return recurse(key, change, path_from, matchRules, rev_from, changes, pool); case Rules::Match::Export: if(ruledebug) qDebug() << "rev" << revnum << qPrintable(current) << "matched rule:" << rule.info() << " " << "exporting."; if (exportInternal(key, change, path_from, rev_from, current, rule, matchRules) == EXIT_SUCCESS) return EXIT_SUCCESS; if (change->change_kind != svn_fs_path_change_delete) { if(ruledebug) qDebug() << "rev" << revnum << qPrintable(current) << "matched rule:" << rule.info() << " " << "Unable to export non path removal."; return EXIT_FAILURE; } // we know that the default action inside recurse is to recurse further or to ignore, // either of which is reasonably safe for deletion qWarning() << "WARN: deleting unknown path" << current << "; auto-recursing"; return recurse(key, change, path_from, matchRules, rev_from, changes, pool); } // never reached return EXIT_FAILURE; } int SvnRevision::exportInternal(const char *key, const svn_fs_path_change2_t *change, const char *path_from, svn_revnum_t rev_from, const QString &current, const Rules::Match &rule, const MatchRuleList &matchRules) { needCommit = true; QString svnprefix, repository, effectiveRepository, branch, path; splitPathName(rule, current, &svnprefix, &repository, &effectiveRepository, &branch, &path); Repository *repo = repositories.value(repository, 0); if (!repo) { if (change->change_kind != svn_fs_path_change_delete) qCritical() << "Rule" << rule << "references unknown repository" << repository; return EXIT_FAILURE; } printf("."); fflush(stdout); // qDebug() << " " << qPrintable(current) << "rev" << revnum << "->" // << qPrintable(repository) << qPrintable(branch) << qPrintable(path); if (change->change_kind == svn_fs_path_change_delete && current == svnprefix && path.isEmpty() && !repo->hasPrefix()) { if(ruledebug) qDebug() << "repository" << repository << "branch" << branch << "deleted"; return repo->deleteBranch(branch, revnum); } QString previous; QString prevsvnprefix, prevrepository, preveffectiverepository, prevbranch, prevpath; if (path_from != NULL) { previous = QString::fromUtf8(path_from); if (wasDir(fs, rev_from, path_from, pool.data())) { previous += '/'; } MatchRuleList::ConstIterator prevmatch = findMatchRule(matchRules, rev_from, previous, NoIgnoreRule); if (prevmatch != matchRules.constEnd()) { splitPathName(*prevmatch, previous, &prevsvnprefix, &prevrepository, &preveffectiverepository, &prevbranch, &prevpath); } else { qWarning() << "WARN: SVN reports a \"copy from\" @" << revnum << "from" << path_from << "@" << rev_from << "but no matching rules found! Ignoring copy, treating as a modification"; path_from = NULL; } } // current == svnprefix => we're dealing with the contents of the whole branch here if (path_from != NULL && current == svnprefix && path.isEmpty()) { if (previous != prevsvnprefix) { // source is not the whole of its branch qDebug() << qPrintable(current) << "is a partial branch of repository" << qPrintable(prevrepository) << "branch" << qPrintable(prevbranch) << "subdir" << qPrintable(prevpath); } else if (preveffectiverepository != effectiveRepository) { qWarning() << "WARN:" << qPrintable(current) << "rev" << revnum << "is a cross-repository copy (from repository" << qPrintable(prevrepository) << "branch" << qPrintable(prevbranch) << "path" << qPrintable(prevpath) << "rev" << rev_from << ")"; } else if (path != prevpath) { qDebug() << qPrintable(current) << "is a branch copy which renames base directory of all contents" << qPrintable(prevpath) << "to" << qPrintable(path); // FIXME: Handle with fast-import 'file rename' facility // ??? Might need special handling when path == / or prevpath == / } else { if (prevbranch == branch) { // same branch and same repository qDebug() << qPrintable(current) << "rev" << revnum << "is reseating branch" << qPrintable(branch) << "to an earlier revision" << qPrintable(previous) << "rev" << rev_from; } else { // same repository but not same branch // this means this is a plain branch qDebug() << qPrintable(repository) << ": branch" << qPrintable(branch) << "is branching from" << qPrintable(prevbranch); } if (repo->createBranch(branch, revnum, prevbranch, rev_from) == EXIT_FAILURE) return EXIT_FAILURE; if(CommandLineParser::instance()->contains("svn-branches")) { Repository::Transaction *txn = transactions.value(repository + branch, 0); if (!txn) { txn = repo->newTransaction(branch, svnprefix, revnum); if (!txn) return EXIT_FAILURE; transactions.insert(repository + branch, txn); } if(ruledebug) qDebug() << "Create a true SVN copy of branch (" << key << "->" << branch << path << ")"; txn->deleteFile(path); recursiveDumpDir(txn, fs_root, key, path, pool, revnum, rule, matchRules, ruledebug); } if (rule.annotate) { // create an annotated tag fetchRevProps(); repo->createAnnotatedTag(branch, svnprefix, revnum, authorident, epoch, log); } return EXIT_SUCCESS; } } Repository::Transaction *txn = transactions.value(repository + branch, 0); if (!txn) { txn = repo->newTransaction(branch, svnprefix, revnum); if (!txn) return EXIT_FAILURE; transactions.insert(repository + branch, txn); } // // If this path was copied from elsewhere, use it to infer _some_ // merge points. This heuristic is fairly useful for tracking // changes across directory re-organizations and wholesale branch // imports. // if (path_from != NULL && preveffectiverepository == effectiveRepository && prevbranch != branch) { if(ruledebug) qDebug() << "copy from branch" << prevbranch << "to branch" << branch << "@rev" << rev_from; txn->noteCopyFromBranch (prevbranch, rev_from); } if (change->change_kind == svn_fs_path_change_replace && path_from == NULL) { if(ruledebug) qDebug() << "replaced with empty path (" << branch << path << ")"; txn->deleteFile(path); } if (change->change_kind == svn_fs_path_change_delete) { if(ruledebug) qDebug() << "delete (" << branch << path << ")"; txn->deleteFile(path); } else if (!current.endsWith('/')) { if(ruledebug) qDebug() << "add/change file (" << key << "->" << branch << path << ")"; dumpBlob(txn, fs_root, key, path, pool); } else { if(ruledebug) qDebug() << "add/change dir (" << key << "->" << branch << path << ")"; // Check unknown svn-properties if (((path_from == NULL && change->prop_mod==1) || (path_from != NULL && change->change_kind == svn_fs_path_change_add)) && CommandLineParser::instance()->contains("propcheck")) { if (fetchUnknownProps(pool, key, fs_root) != EXIT_SUCCESS) { qWarning() << "Error checking svn-properties (" << key << ")"; } } int ignoreSet = false; // Add GitIgnore with svn:ignore if (((path_from == NULL && change->prop_mod==1) || (path_from != NULL && change->change_kind == svn_fs_path_change_add)) && CommandLineParser::instance()->contains("svn-ignore")) { QString svnignore; // TODO: Check if svn:ignore or other property was changed, but always set on copy/rename (path_from != NULL) if (fetchIgnoreProps(&svnignore, pool, key, fs_root) != EXIT_SUCCESS) { qWarning() << "Error fetching svn-properties (" << key << ")"; } else if (!svnignore.isNull()) { addGitIgnore(pool, key, path, fs_root, txn, svnignore.toStdString().c_str()); ignoreSet = true; std::string ignorefile = std::to_string(revnum) + std::string(".gitignore"); struct stat buffer; int fexists = (stat(ignorefile.c_str(), &buffer) == 0); std::ofstream outfile(ignorefile, std::ios::out | std::ios::binary | std::fstream::app); if (!fexists) { std::cout << revnum << ": creating gitignore\n\n"; } else { std::cout << revnum << ": appending to gitignore\n\n"; } outfile << svnignore.toStdString(); outfile.close(); } } // Add GitIgnore for empty directories (if GitIgnore was not set previously) if (CommandLineParser::instance()->contains("empty-dirs") && ignoreSet == false) { if (addGitIgnore(pool, key, path, fs_root, txn) == EXIT_SUCCESS) { return EXIT_SUCCESS; } else { ignoreSet = true; } } if (ignoreSet == false) { txn->deleteFile(path); } recursiveDumpDir(txn, fs_root, key, path, pool, revnum, rule, matchRules, ruledebug); } return EXIT_SUCCESS; } int SvnRevision::recurse(const char *path, const svn_fs_path_change2_t *change, const char *path_from, const MatchRuleList &matchRules, svn_revnum_t rev_from, apr_hash_t *changes, apr_pool_t *pool) { svn_fs_root_t *fs_root = this->fs_root; if (change->change_kind == svn_fs_path_change_delete) SVN_ERR(svn_fs_revision_root(&fs_root, fs, revnum - 1, pool)); // get the dir listing svn_node_kind_t kind; SVN_ERR(svn_fs_check_path(&kind, fs_root, path, pool)); if(kind == svn_node_none) { qWarning() << "WARN: Trying to recurse using a nonexistant path" << path << ", ignoring"; return EXIT_SUCCESS; } else if(kind != svn_node_dir) { qWarning() << "WARN: Trying to recurse using a non-directory path" << path << ", ignoring"; return EXIT_SUCCESS; } apr_hash_t *entries; SVN_ERR(svn_fs_dir_entries(&entries, fs_root, path, pool)); AprAutoPool dirpool(pool); // While we get a hash, put it in a map for sorted lookup, so we can // repeat the conversions and get the same git commit hashes. QMap<QByteArray, svn_node_kind_t> map; for (apr_hash_index_t *i = apr_hash_first(pool, entries); i; i = apr_hash_next(i)) { dirpool.clear(); const void *vkey; void *value; apr_hash_this(i, &vkey, NULL, &value); svn_fs_dirent_t *dirent = reinterpret_cast<svn_fs_dirent_t *>(value); map.insertMulti(QByteArray(dirent->name), dirent->kind); } QMapIterator<QByteArray, svn_node_kind_t> i(map); while (i.hasNext()) { dirpool.clear(); i.next(); QByteArray entry = path + QByteArray("/") + i.key(); QByteArray entryFrom; if (path_from) entryFrom = path_from + QByteArray("/") + i.key(); // check if this entry is in the changelist for this revision already svn_fs_path_change2_t *otherchange = (svn_fs_path_change2_t*)apr_hash_get(changes, entry.constData(), APR_HASH_KEY_STRING); if (otherchange && otherchange->change_kind == svn_fs_path_change_add) { qDebug() << entry << "rev" << revnum << "is in the change-list, deferring to that one"; continue; } QString current = QString::fromUtf8(entry); if (i.value() == svn_node_dir) current += '/'; // find the first rule that matches this pathname MatchRuleList::ConstIterator match = findMatchRule(matchRules, revnum, current); if (match != matchRules.constEnd()) { if (exportDispatch(entry, change, entryFrom.isNull() ? 0 : entryFrom.constData(), rev_from, changes, current, *match, matchRules, dirpool) == EXIT_FAILURE) return EXIT_FAILURE; } else { if (i.value() == svn_node_dir) { qDebug() << current << "rev" << revnum << "did not match any rules; auto-recursing"; if (recurse(entry, change, entryFrom.isNull() ? 0 : entryFrom.constData(), matchRules, rev_from, changes, dirpool) == EXIT_FAILURE) return EXIT_FAILURE; } } } return EXIT_SUCCESS; } int SvnRevision::addGitIgnore(apr_pool_t *pool, const char *key, QString path, svn_fs_root_t *fs_root, Repository::Transaction *txn, const char *content) { // Check for number of subfiles if no content if (!content) { apr_hash_t *entries; SVN_ERR(svn_fs_dir_entries(&entries, fs_root, key, pool)); // Return if any subfiles if (apr_hash_count(entries)!=0) { return EXIT_FAILURE; } } // Add gitignore-File QString gitIgnorePath = path + ".gitignore"; if (content) { QIODevice *io = txn->addFile(gitIgnorePath, 33188, strlen(content)); io->write(content); io->putChar('\n'); } else { QIODevice *io = txn->addFile(gitIgnorePath, 33188, 0); io->putChar('\n'); } return EXIT_SUCCESS; } int SvnRevision::fetchIgnoreProps(QString *ignore, apr_pool_t *pool, const char *key, svn_fs_root_t *fs_root) { // Get svn:ignore svn_string_t *prop = NULL; SVN_ERR(svn_fs_node_prop(&prop, fs_root, key, "svn:ignore", pool)); if (prop) { *ignore = QString(prop->data); // remove patterns with slashes or backslashes, // they didn't match anything in Subversion but would in Git eventually ignore->remove(QRegExp("^[^\\r\\n]*[\\\\/][^\\r\\n]*(?:[\\r\\n]|$)|[\\r\\n][^\\r\\n]*[\\\\/][^\\r\\n]*(?=[\\r\\n]|$)")); // add a slash in front to have the same meaning in Git of only working on the direct children ignore->replace(QRegExp("(^|[\\r\\n])\\s*(?![\\r\\n]|$)"), "\\1/"); } else { *ignore = QString(); } // Get svn:global-ignores prop = NULL; SVN_ERR(svn_fs_node_prop(&prop, fs_root, key, "svn:global-ignores", pool)); if (prop) { QString global_ignore = QString(prop->data); // remove patterns with slashes or backslashes, // they didn't match anything in Subversion but would in Git eventually global_ignore.remove(QRegExp("^[^\\r\\n]*[\\\\/][^\\r\\n]*(?:[\\r\\n]|$)|[\\r\\n][^\\r\\n]*[\\\\/][^\\r\\n]*(?=[\\r\\n]|$)")); ignore->append(global_ignore); } // replace multiple asterisks Subversion meaning by Git meaning ignore->replace(QRegExp("\\*+"), "*"); return EXIT_SUCCESS; } int SvnRevision::fetchUnknownProps(apr_pool_t *pool, const char *key, svn_fs_root_t *fs_root) { // Check all properties apr_hash_t *table; SVN_ERR(svn_fs_node_proplist(&table, fs_root, key, pool)); apr_hash_index_t *hi; void *propVal; const void *propKey; for (hi = apr_hash_first(pool, table); hi; hi = apr_hash_next(hi)) { apr_hash_this(hi, &propKey, NULL, &propVal); if (strcmp((char*)propKey, "svn:ignore")!=0) { qWarning() << "WARN: Unknown svn-property" << (char*)propKey << "set to" << ((svn_string_t*)propVal)->data << "for" << key; } } return EXIT_SUCCESS; }
37.381341
192
0.608108
earl-ducaine
4f502396625432e8879c2f137301e2334a37bea6
14,541
hpp
C++
AirLib/include/physics/FastPhysicsEngine.hpp
1508189250/AirSim
edf186f31cf4f5fc2085ecfbccd71041aab908ad
[ "MIT" ]
null
null
null
AirLib/include/physics/FastPhysicsEngine.hpp
1508189250/AirSim
edf186f31cf4f5fc2085ecfbccd71041aab908ad
[ "MIT" ]
null
null
null
AirLib/include/physics/FastPhysicsEngine.hpp
1508189250/AirSim
edf186f31cf4f5fc2085ecfbccd71041aab908ad
[ "MIT" ]
3
2018-01-26T17:48:22.000Z
2021-05-03T23:52:56.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef airsim_core_FastPhysicsEngine_hpp #define airsim_core_FastPhysicsEngine_hpp #include "common/Common.hpp" #include "physics/PhysicsEngineBase.hpp" #include <iostream> #include <sstream> #include <fstream> #include "common/LogFileWriter.hpp" #include "common/CommonStructs.hpp" namespace msr { namespace airlib { class FastPhysicsEngine : public PhysicsEngineBase { public: FastPhysicsEngine() { FastPhysicsEngine::reset(); logger_.open("c:\\temp\\FastPhysicsEngine.tsv", false); } ~FastPhysicsEngine() { //log_file_.close(); } //*** Start: UpdatableState implementation ***// virtual void reset() override { } virtual void update(real_T dt) override { for (PhysicsBody* body_ptr : *this) { updatePhysics(dt, *body_ptr); } } virtual void reportState(StateReporter& reporter) override { for (PhysicsBody* body_ptr : *this) { reporter.writeValue("Phys", debug_string_.str()); reporter.writeValue("Is Gounded", grounded_); reporter.writeValue("Force (world)", body_ptr->getWrench().force); reporter.writeValue("Torque (body)", body_ptr->getWrench().torque); } //call base UpdatableObject::reportState(reporter); } //*** End: UpdatableState implementation ***// private: void updatePhysics(real_T dt, PhysicsBody& body) { //get current kinematics state of the body - this state existed since last dt seconds const Kinematics::State& current = body.getKinematics(); Kinematics::State next; Wrench next_wrench; getNextKinematicsNoCollison(dt, body, current, next, next_wrench); if (!getNextKinematicsOnCollison(dt, body, current, next, next_wrench)) getNextKinematicsOnGround(dt, body, current, next, next_wrench); body.setKinematics(next); body.setWrench(next_wrench); body.kinematicsUpdated(dt); } bool getNextKinematicsOnCollison(real_T dt, const PhysicsBody& body, const Kinematics::State& current, Kinematics::State& next, Wrench& next_wrench) { static constexpr uint kCollisionResponseCycles = 1; /************************* Collison response ************************/ const CollisionInfo collison_info = body.getCollisionInfo(); //if there is collison if (collison_info.has_collided) { //are we going away from collison? real_T vnext_normal_mag = -collison_info.normal.dot(next.twist.linear + next.accelerations.linear *dt); //if not then we need collison response if (Utils::isDefinitelyGreaterThan(vnext_normal_mag, 0.0f)) { //get current velocity's reflection Vector3r vcur_avg = current.twist.linear + current.accelerations.linear * dt; real_T vcur_normal_mag = -collison_info.normal.dot(vcur_avg); //if current velocity is going away from collison then don't reflect it if (Utils::isDefinitelyGreaterThan(vcur_normal_mag, 0.0f)) { /********** Core collison response ***********/ //get average angular velocity Vector3r angular_avg = current.twist.angular + current.accelerations.angular * dt; //contact point vector Vector3r r = collison_info.impact_point - collison_info.position; //velocity at contact point Vector3r contact_vel = vcur_avg + angular_avg.cross(r); /* GafferOnGames - Collison response with columb friction http://gafferongames.com/virtual-go/collision-response-and-coulomb-friction/ Assuming collison is with static fixed body, impulse magnitude = j = -(1 + R)V.N / (1/m + (I'(r X N) X r).N) Physics Part 3, Collison Response, Chris Hecker, eq 4(a) http://chrishecker.com/images/e/e7/Gdmphys3.pdf V(t+1) = V(t) + j*N / m */ real_T impulse_mag_denom = 1.0f / body.getMass() + (body.getInertiaInv() * r.cross(collison_info.normal)) .cross(r) .dot(collison_info.normal); real_T impulse_mag = -contact_vel.dot(collison_info.normal) * (1 + body.getRestitution()) / impulse_mag_denom; next.twist.linear = vcur_avg + collison_info.normal * (impulse_mag / body.getMass()); next.twist.angular = angular_avg + r.cross(collison_info.normal) * impulse_mag; //above would modify component in direction of normal //we will use friction to modify component in direction of tangent Vector3r contact_tang = contact_vel - collison_info.normal * collison_info.normal.dot(contact_vel); Vector3r contact_tang_unit = contact_tang.normalized(); real_T friction_mag_denom = 1.0f / body.getMass() + (body.getInertiaInv() * r.cross(contact_tang_unit)) .cross(r) .dot(contact_tang_unit); real_T friction_mag = -contact_tang.norm() * body.getFriction() / friction_mag_denom; next.twist.linear += contact_tang_unit * friction_mag; next.twist.angular += r.cross(contact_tang_unit) * (friction_mag / body.getMass()); } else next.twist.linear = vcur_avg; //there is no acceleration during collison response next.accelerations.linear = Vector3r::Zero(); next.accelerations.angular = Vector3r::Zero(); //do not use current.pose because it might be invalid next.pose.position = collison_info.position + (collison_info.normal * collison_info.penetration_depth) + next.twist.linear * (dt * kCollisionResponseCycles); next_wrench = Wrench::zero(); return true; } } return false; } bool getNextKinematicsOnGround(real_T dt, const PhysicsBody& body, const Kinematics::State& current, Kinematics::State& next, Wrench& next_wrench) { /************************* reset state if we have hit the ground ************************/ real_T min_z_over_ground = body.getEnvironment().getState().min_z_over_ground; grounded_ = 0; if (min_z_over_ground <= next.pose.position.z()) { grounded_ = 1; next.pose.position.z() = min_z_over_ground; if (Utils::isDefinitelyLessThan(0.0f, next.twist.linear.z() + next.accelerations.linear.z() *dt)) { grounded_ = 2; next.twist = Twist::zero(); next.accelerations.linear = Vector3r::Zero(); next.accelerations.angular = Vector3r::Zero(); //reset roll/pitch - px4 seems to have issue with this real_T r, p, y; VectorMath::toEulerianAngle(current.pose.orientation, p, r, y); next.pose.orientation = VectorMath::toQuaternion(0, 0, y); next_wrench = Wrench::zero(); } } return grounded_ != 0; } void getNextKinematicsNoCollison(real_T dt, const PhysicsBody& body, const Kinematics::State& current, Kinematics::State& next, Wrench& next_wrench) { /************************* Get force and torque acting on body ************************/ //set wrench sum to zero Wrench wrench = Wrench::zero(); Vector3r cog = Vector3r::Zero(); const CollisionInfo collison_info = body.getCollisionInfo(); //if there is collison we will apply force around contact point to generate torque if (collison_info.has_collided) { cog = VectorMath::transformToBodyFrame(collison_info.impact_point - collison_info.position, current.pose.orientation, true); } //calculate total force on rigid body's center of gravity for (uint i = 0; i < body.vertexCount(); ++i) { //aggregate total const PhysicsBodyVertex& vertex = body.getVertex(i); const auto& vertex_wrench = vertex.getWrench(); wrench += vertex_wrench; //add additional torque due to force applies farther than COG // tau = r X F wrench.torque += (vertex.getPosition() - cog).cross(vertex_wrench.force); } //transoform force to world frame Vector3r force_world_generated = VectorMath::transformToWorldFrame(wrench.force, current.pose.orientation, true); //add linear drag due to velocity we had since last dt seconds //drag vector magnitude is proportional to v^2, direction opposite of velocity //total drag is b*v + c*v*v but we ignore the first term as b << c (pg 44, Classical Mechanics, John Taylor) //To find the drag force, we find the magnitude in the body frame and unit vector direction in world frame Vector3r avg_velocity = current.twist.linear + current.accelerations.linear * (0.5f * dt); Vector3r avg_velocity_body = VectorMath::transformToBodyFrame(avg_velocity, current.pose.orientation, true); real_T avg_velocity_body_norm = avg_velocity_body.norm(); Vector3r drag_force_world = Vector3r::Zero(); if (!Utils::isApproximatelyZero(avg_velocity_body_norm, 1E-1f)) { Vector3r drag_force_body = body.getLinearDragFactor() .cwiseProduct(avg_velocity_body) .cwiseProduct(avg_velocity_body); drag_force_world = -avg_velocity / avg_velocity_body_norm * drag_force_body.norm(); } Vector3r force_net_world = force_world_generated + drag_force_world; //similarly calculate angular drag //note that angular velocity, acceleration, torque are already in body frame //http://physics.stackexchange.com/questions/304742/angular-drag-on-body Vector3r avg_angular = current.twist.angular + current.accelerations.angular * (0.5f * dt); real_T avg_angular_norm = avg_angular.norm(); Vector3r angular_drag = Vector3r::Zero(); //if angular velocity is too low (for example, random noise), 1/norm can get randomly big and generate huge drag if (!Utils::isApproximatelyZero(avg_angular_norm, 1E-1f)) { Vector3r angular_drag_mag = body.getAngularDragFactor() .cwiseProduct(avg_angular) .cwiseProduct(avg_angular); angular_drag = -avg_angular / avg_angular_norm * angular_drag_mag.norm(); } Vector3r torque_net = wrench.torque + angular_drag; /************************* Update accelerations due to force and torque ************************/ //get new acceleration due to force - we'll use this acceleration in next time step next.accelerations.linear = (force_net_world / body.getMass()) + body.getEnvironment().getState().gravity; //get new angular acceleration //Euler's rotation equation: https://en.wikipedia.org/wiki/Euler's_equations_(body_dynamics) //we will use torque to find out the angular acceleration //angular momentum L = I * omega Vector3r angular_momentum = body.getInertia() * avg_angular; Vector3r angular_momentum_rate = torque_net - avg_angular.cross(angular_momentum); //new angular acceleration - we'll use this acceleration in next time step next.accelerations.angular = body.getInertiaInv() * angular_momentum_rate; /************************* Update pose and twist after dt ************************/ //Verlet integration: http://www.physics.udel.edu/~bnikolic/teaching/phys660/numerical_ode/node5.html next.pose.position = current.pose.position + avg_velocity * dt; next.twist.linear = current.twist.linear + (current.accelerations.linear + next.accelerations.linear) * (0.5f * dt); //use angular velocty in body frame to calculate angular displacement in last dt seconds real_T angle_per_unit = avg_angular.norm(); if (Utils::isDefinitelyGreaterThan(angle_per_unit, 0.0f)) { //convert change in angle to unit quaternion AngleAxisr angle_dt_aa = AngleAxisr(angle_per_unit * dt, avg_angular / angle_per_unit); Quaternionr angle_dt_q = Quaternionr(angle_dt_aa); /* Add change in angle to previous orientation. Proof that this is q0 * q1: If rotated vector is qx*v*qx' then qx is attitude Initially we have q0*v*q0' Lets transform this to body coordinates to get q0'*(q0*v*q0')*q0 Then apply q1 rotation on it to get q1(q0'*(q0*v*q0')*q0)q1' Then transform back to world coordinate q0(q1(q0'*(q0*v*q0')*q0)q1')q0' which simplifies to q0(q1(v)q1')q0' Thus new attitude is q0q1 */ next.pose.orientation = current.pose.orientation * angle_dt_q; if (VectorMath::hasNan(next.pose.orientation)) Utils::DebugBreak(); //re-normalize quaternion to avoid accumulating error next.pose.orientation.normalize(); } else //no change in angle, because angular velocity is zero (normalized vector is undefined) next.pose.orientation = current.pose.orientation; next.twist.angular = current.twist.angular + (current.accelerations.angular + next.accelerations.angular) * (0.5f * dt); next_wrench = Wrench(force_net_world, torque_net); } private: LogFileWriter logger_; std::stringstream debug_string_; int grounded_; }; }} //namespace #endif
48.30897
174
0.598996
1508189250
4f506afcffadaf9162659db4ebaee3abce615de7
3,178
cpp
C++
lib/ofdirent.cpp
timmyw/ofsystem
6f955d53dc3025148763333bea0a11d0bce28c06
[ "MIT" ]
null
null
null
lib/ofdirent.cpp
timmyw/ofsystem
6f955d53dc3025148763333bea0a11d0bce28c06
[ "MIT" ]
null
null
null
lib/ofdirent.cpp
timmyw/ofsystem
6f955d53dc3025148763333bea0a11d0bce28c06
[ "MIT" ]
null
null
null
/* Copyright (C) 1997-2011 by Suntail.com AS, Tim Whelan 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 <ofsys.h> #include <ofdirent.h> #include <ofplatform.h> #include <ofos.h> OFDirent::OFDirent( const char *path ) { OFOS::strncpy2( m_path, path, OF_MAX_PATH_LEN ); OFPlatform::fixPath( m_path ); #if defined(OFOPSYS_WIN32) char realpath[OF_MAX_PATH_LEN+1]; OFOS::snprintf( realpath, OF_MAX_PATH_LEN, "%s\\*.*", m_path ); m_dir = FindFirstFile( realpath, &m_data ); if (m_dir == INVALID_HANDLE_VALUE) m_dir = 0; m_first = 1; #elif defined(OFOPSYS_LINUX) || defined(OFOPSYS_SOLARIS) || defined(OFOPSYS_FREEBSD) || defined(OFOPSYS_DARWIN) m_dir = opendir( m_path ); #endif } OFDirent::~OFDirent( ) { #if defined(OFOPSYS_WIN32) FindClose( m_dir ); #elif defined(OFOPSYS_LINUX) || defined(OFOPSYS_SOLARIS) || defined(OFOPSYS_FREEBSD) || defined(OFOPSYS_DARWIN) closedir (m_dir); #endif } ofuint32 OFDirent::read( OFDIRENT *direntry ) { if (!m_dir) return 0; memset( direntry, 0, sizeof(OFDIRENT) ); #if defined(OFOPSYS_WIN32) if ( m_first ) m_first = 0; else { if ( !FindNextFile( m_dir, &m_data ) ) return 0; } OFOS::strncpy2( direntry->name, m_data.cFileName, OF_MAX_PATH_LEN ); direntry->type = (m_data.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)?OFDIR_TYPE_DIR:OFDIR_TYPE_FILE; #elif defined(OFOPSYS_LINUX) || defined(OFOPSYS_SOLARIS) || defined(OFOPSYS_FREEBSD) || defined(OFOPSYS_DARWIN) struct dirent *de = readdir( m_dir ); if ( de ) { #if defined(OFOPSYS_SOLARIS) direntry->type = 0; #endif #if defined(OFOPSYS_LINUX) || defined(OFOPSYS_FREEBSD) OFOS::strncpy2( direntry->name, de->d_name, OF_MAX_PATH_LEN ); // struct stat* buf; // OFFile::getExtFileInfo( fullpath, buf ); if ( de->d_type == DT_REG || de->d_type == DT_LNK ) direntry->type = OFDIR_TYPE_FILE; if ( de->d_type == DT_DIR ) direntry->type = OFDIR_TYPE_DIR; #endif } else return 0; #else #error Undefined platform #endif return 1; }
32.428571
111
0.690686
timmyw
4f581df610b298c767fd144bcc475bcb8549326e
2,549
cpp
C++
src/systemc/tests/systemc/kernel/dynamic_processes/test06/test06.cpp
hyu-iot/gem5
aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5
[ "BSD-3-Clause" ]
765
2015-01-14T16:17:04.000Z
2022-03-28T07:46:28.000Z
src/systemc/tests/systemc/kernel/dynamic_processes/test06/test06.cpp
hyu-iot/gem5
aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5
[ "BSD-3-Clause" ]
148
2018-07-20T00:58:36.000Z
2021-11-16T01:52:33.000Z
src/systemc/tests/systemc/kernel/dynamic_processes/test06/test06.cpp
hyu-iot/gem5
aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5
[ "BSD-3-Clause" ]
807
2015-01-06T09:55:38.000Z
2022-03-30T10:23:36.000Z
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** Original Author: Bishnupriya Bhattacharya, Cadence Design Systems, Inc., 2004-03-10 *****************************************************************************/ // tests parent spawning process dying before child spawned process. /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ // $Log: test06.cpp,v $ // Revision 1.2 2011/02/01 17:17:40 acg // Andy Goodrich: update of copyright notice, added visible CVS logging. // #define SC_INCLUDE_DYNAMIC_PROCESSES #include <systemc.h> void p3() { cerr << sc_time_stamp() << ":entering p3" << endl; wait(30, SC_NS); cerr << sc_time_stamp() << ":exiting p3" << endl; } void p2() { cerr << sc_time_stamp() << ":entering p2, spawning p3" << endl; sc_spawn(sc_bind(&p3)); wait(20, SC_NS); cerr << sc_time_stamp() << ":exiting p2" << endl; } void p1() { cerr << sc_time_stamp() << ":entering p1, spawning p2" << endl; sc_spawn(sc_bind(&p2)); wait(10, SC_NS); cerr << sc_time_stamp() << ":exiting p1" << endl; } void p0() { cerr << sc_time_stamp() << ":entering p0, spawning p1" << endl; sc_spawn(sc_bind(&p1)); cerr << sc_time_stamp() << ":exiting p0" << endl; } int sc_main(int, char**) { sc_start(10, SC_NS); p0(); sc_start(50, SC_NS); return 0; }
32.265823
85
0.568066
hyu-iot
4f591b53aaa6e7137f11c6f18f8840fd0ff19793
56,692
cpp
C++
lldb/source/Commands/CommandObjectProcess.cpp
tiwaria1/llvm
616a396db0610ae0c1992361af005a869ef81897
[ "Apache-2.0" ]
1
2020-09-10T01:00:18.000Z
2020-09-10T01:00:18.000Z
lldb/source/Commands/CommandObjectProcess.cpp
coolstar/llvm-project
e21ccdd5b5667de50de65ee8903a89a21020e89a
[ "Apache-2.0" ]
null
null
null
lldb/source/Commands/CommandObjectProcess.cpp
coolstar/llvm-project
e21ccdd5b5667de50de65ee8903a89a21020e89a
[ "Apache-2.0" ]
null
null
null
//===-- CommandObjectProcess.cpp ------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "CommandObjectProcess.h" #include "lldb/Breakpoint/Breakpoint.h" #include "lldb/Breakpoint/BreakpointLocation.h" #include "lldb/Breakpoint/BreakpointSite.h" #include "lldb/Core/Module.h" #include "lldb/Core/PluginManager.h" #include "lldb/Host/OptionParser.h" #include "lldb/Host/StringConvert.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Interpreter/OptionArgParser.h" #include "lldb/Interpreter/Options.h" #include "lldb/Target/Platform.h" #include "lldb/Target/Process.h" #include "lldb/Target/StopInfo.h" #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Target/UnixSignals.h" #include "lldb/Utility/Args.h" #include "lldb/Utility/State.h" using namespace lldb; using namespace lldb_private; class CommandObjectProcessLaunchOrAttach : public CommandObjectParsed { public: CommandObjectProcessLaunchOrAttach(CommandInterpreter &interpreter, const char *name, const char *help, const char *syntax, uint32_t flags, const char *new_process_action) : CommandObjectParsed(interpreter, name, help, syntax, flags), m_new_process_action(new_process_action) {} ~CommandObjectProcessLaunchOrAttach() override = default; protected: bool StopProcessIfNecessary(Process *process, StateType &state, CommandReturnObject &result) { state = eStateInvalid; if (process) { state = process->GetState(); if (process->IsAlive() && state != eStateConnected) { char message[1024]; if (process->GetState() == eStateAttaching) ::snprintf(message, sizeof(message), "There is a pending attach, abort it and %s?", m_new_process_action.c_str()); else if (process->GetShouldDetach()) ::snprintf(message, sizeof(message), "There is a running process, detach from it and %s?", m_new_process_action.c_str()); else ::snprintf(message, sizeof(message), "There is a running process, kill it and %s?", m_new_process_action.c_str()); if (!m_interpreter.Confirm(message, true)) { result.SetStatus(eReturnStatusFailed); return false; } else { if (process->GetShouldDetach()) { bool keep_stopped = false; Status detach_error(process->Detach(keep_stopped)); if (detach_error.Success()) { result.SetStatus(eReturnStatusSuccessFinishResult); process = nullptr; } else { result.AppendErrorWithFormat( "Failed to detach from process: %s\n", detach_error.AsCString()); result.SetStatus(eReturnStatusFailed); } } else { Status destroy_error(process->Destroy(false)); if (destroy_error.Success()) { result.SetStatus(eReturnStatusSuccessFinishResult); process = nullptr; } else { result.AppendErrorWithFormat("Failed to kill process: %s\n", destroy_error.AsCString()); result.SetStatus(eReturnStatusFailed); } } } } } return result.Succeeded(); } std::string m_new_process_action; }; // CommandObjectProcessLaunch #pragma mark CommandObjectProcessLaunch class CommandObjectProcessLaunch : public CommandObjectProcessLaunchOrAttach { public: CommandObjectProcessLaunch(CommandInterpreter &interpreter) : CommandObjectProcessLaunchOrAttach( interpreter, "process launch", "Launch the executable in the debugger.", nullptr, eCommandRequiresTarget, "restart"), m_options() { CommandArgumentEntry arg; CommandArgumentData run_args_arg; // Define the first (and only) variant of this arg. run_args_arg.arg_type = eArgTypeRunArgs; run_args_arg.arg_repetition = eArgRepeatOptional; // There is only one variant this argument could be; put it into the // argument entry. arg.push_back(run_args_arg); // Push the data for the first argument into the m_arguments vector. m_arguments.push_back(arg); } ~CommandObjectProcessLaunch() override = default; void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override { CommandCompletions::InvokeCommonCompletionCallbacks( GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion, request, nullptr); } Options *GetOptions() override { return &m_options; } const char *GetRepeatCommand(Args &current_command_args, uint32_t index) override { // No repeat for "process launch"... return ""; } protected: bool DoExecute(Args &launch_args, CommandReturnObject &result) override { Debugger &debugger = GetDebugger(); Target *target = debugger.GetSelectedTarget().get(); // If our listener is nullptr, users aren't allows to launch ModuleSP exe_module_sp = target->GetExecutableModule(); if (exe_module_sp == nullptr) { result.AppendError("no file in target, create a debug target using the " "'target create' command"); result.SetStatus(eReturnStatusFailed); return false; } StateType state = eStateInvalid; if (!StopProcessIfNecessary(m_exe_ctx.GetProcessPtr(), state, result)) return false; llvm::StringRef target_settings_argv0 = target->GetArg0(); // Determine whether we will disable ASLR or leave it in the default state // (i.e. enabled if the platform supports it). First check if the process // launch options explicitly turn on/off // disabling ASLR. If so, use that setting; // otherwise, use the 'settings target.disable-aslr' setting. bool disable_aslr = false; if (m_options.disable_aslr != eLazyBoolCalculate) { // The user specified an explicit setting on the process launch line. // Use it. disable_aslr = (m_options.disable_aslr == eLazyBoolYes); } else { // The user did not explicitly specify whether to disable ASLR. Fall // back to the target.disable-aslr setting. disable_aslr = target->GetDisableASLR(); } if (disable_aslr) m_options.launch_info.GetFlags().Set(eLaunchFlagDisableASLR); else m_options.launch_info.GetFlags().Clear(eLaunchFlagDisableASLR); if (target->GetDetachOnError()) m_options.launch_info.GetFlags().Set(eLaunchFlagDetachOnError); if (target->GetDisableSTDIO()) m_options.launch_info.GetFlags().Set(eLaunchFlagDisableSTDIO); // Merge the launch info environment with the target environment. Environment target_env = target->GetEnvironment(); m_options.launch_info.GetEnvironment().insert(target_env.begin(), target_env.end()); if (!target_settings_argv0.empty()) { m_options.launch_info.GetArguments().AppendArgument( target_settings_argv0); m_options.launch_info.SetExecutableFile( exe_module_sp->GetPlatformFileSpec(), false); } else { m_options.launch_info.SetExecutableFile( exe_module_sp->GetPlatformFileSpec(), true); } if (launch_args.GetArgumentCount() == 0) { m_options.launch_info.GetArguments().AppendArguments( target->GetProcessLaunchInfo().GetArguments()); } else { m_options.launch_info.GetArguments().AppendArguments(launch_args); // Save the arguments for subsequent runs in the current target. target->SetRunArguments(launch_args); } StreamString stream; Status error = target->Launch(m_options.launch_info, &stream); if (error.Success()) { ProcessSP process_sp(target->GetProcessSP()); if (process_sp) { // There is a race condition where this thread will return up the call // stack to the main command handler and show an (lldb) prompt before // HandlePrivateEvent (from PrivateStateThread) has a chance to call // PushProcessIOHandler(). process_sp->SyncIOHandler(0, std::chrono::seconds(2)); llvm::StringRef data = stream.GetString(); if (!data.empty()) result.AppendMessage(data); const char *archname = exe_module_sp->GetArchitecture().GetArchitectureName(); result.AppendMessageWithFormat( "Process %" PRIu64 " launched: '%s' (%s)\n", process_sp->GetID(), exe_module_sp->GetFileSpec().GetPath().c_str(), archname); result.SetStatus(eReturnStatusSuccessFinishResult); result.SetDidChangeProcessState(true); } else { result.AppendError( "no error returned from Target::Launch, and target has no process"); result.SetStatus(eReturnStatusFailed); } } else { result.AppendError(error.AsCString()); result.SetStatus(eReturnStatusFailed); } return result.Succeeded(); } protected: ProcessLaunchCommandOptions m_options; }; #define LLDB_OPTIONS_process_attach #include "CommandOptions.inc" #pragma mark CommandObjectProcessAttach class CommandObjectProcessAttach : public CommandObjectProcessLaunchOrAttach { public: class CommandOptions : public Options { public: CommandOptions() : Options() { // Keep default values of all options in one place: OptionParsingStarting // () OptionParsingStarting(nullptr); } ~CommandOptions() override = default; Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override { Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { case 'c': attach_info.SetContinueOnceAttached(true); break; case 'p': { lldb::pid_t pid; if (option_arg.getAsInteger(0, pid)) { error.SetErrorStringWithFormat("invalid process ID '%s'", option_arg.str().c_str()); } else { attach_info.SetProcessID(pid); } } break; case 'P': attach_info.SetProcessPluginName(option_arg); break; case 'n': attach_info.GetExecutableFile().SetFile(option_arg, FileSpec::Style::native); break; case 'w': attach_info.SetWaitForLaunch(true); break; case 'i': attach_info.SetIgnoreExisting(false); break; default: llvm_unreachable("Unimplemented option"); } return error; } void OptionParsingStarting(ExecutionContext *execution_context) override { attach_info.Clear(); } llvm::ArrayRef<OptionDefinition> GetDefinitions() override { return llvm::makeArrayRef(g_process_attach_options); } void HandleOptionArgumentCompletion( CompletionRequest &request, OptionElementVector &opt_element_vector, int opt_element_index, CommandInterpreter &interpreter) override { int opt_arg_pos = opt_element_vector[opt_element_index].opt_arg_pos; int opt_defs_index = opt_element_vector[opt_element_index].opt_defs_index; switch (GetDefinitions()[opt_defs_index].short_option) { case 'n': { // Look to see if there is a -P argument provided, and if so use that // plugin, otherwise use the default plugin. const char *partial_name = nullptr; partial_name = request.GetParsedLine().GetArgumentAtIndex(opt_arg_pos); PlatformSP platform_sp(interpreter.GetPlatform(true)); if (!platform_sp) return; ProcessInstanceInfoList process_infos; ProcessInstanceInfoMatch match_info; if (partial_name) { match_info.GetProcessInfo().GetExecutableFile().SetFile( partial_name, FileSpec::Style::native); match_info.SetNameMatchType(NameMatch::StartsWith); } platform_sp->FindProcesses(match_info, process_infos); const size_t num_matches = process_infos.size(); if (num_matches == 0) return; for (size_t i = 0; i < num_matches; ++i) { request.AddCompletion(process_infos[i].GetNameAsStringRef()); } } break; case 'P': CommandCompletions::InvokeCommonCompletionCallbacks( interpreter, CommandCompletions::eProcessPluginCompletion, request, nullptr); break; } } // Instance variables to hold the values for command options. ProcessAttachInfo attach_info; }; CommandObjectProcessAttach(CommandInterpreter &interpreter) : CommandObjectProcessLaunchOrAttach( interpreter, "process attach", "Attach to a process.", "process attach <cmd-options>", 0, "attach"), m_options() {} ~CommandObjectProcessAttach() override = default; Options *GetOptions() override { return &m_options; } protected: bool DoExecute(Args &command, CommandReturnObject &result) override { PlatformSP platform_sp( GetDebugger().GetPlatformList().GetSelectedPlatform()); Target *target = GetDebugger().GetSelectedTarget().get(); // N.B. The attach should be synchronous. It doesn't help much to get the // prompt back between initiating the attach and the target actually // stopping. So even if the interpreter is set to be asynchronous, we wait // for the stop ourselves here. StateType state = eStateInvalid; Process *process = m_exe_ctx.GetProcessPtr(); if (!StopProcessIfNecessary(process, state, result)) return false; if (target == nullptr) { // If there isn't a current target create one. TargetSP new_target_sp; Status error; error = GetDebugger().GetTargetList().CreateTarget( GetDebugger(), "", "", eLoadDependentsNo, nullptr, // No platform options new_target_sp); target = new_target_sp.get(); if (target == nullptr || error.Fail()) { result.AppendError(error.AsCString("Error creating target")); return false; } GetDebugger().GetTargetList().SetSelectedTarget(target); } // Record the old executable module, we want to issue a warning if the // process of attaching changed the current executable (like somebody said // "file foo" then attached to a PID whose executable was bar.) ModuleSP old_exec_module_sp = target->GetExecutableModule(); ArchSpec old_arch_spec = target->GetArchitecture(); if (command.GetArgumentCount()) { result.AppendErrorWithFormat("Invalid arguments for '%s'.\nUsage: %s\n", m_cmd_name.c_str(), m_cmd_syntax.c_str()); result.SetStatus(eReturnStatusFailed); return false; } m_interpreter.UpdateExecutionContext(nullptr); StreamString stream; const auto error = target->Attach(m_options.attach_info, &stream); if (error.Success()) { ProcessSP process_sp(target->GetProcessSP()); if (process_sp) { result.AppendMessage(stream.GetString()); result.SetStatus(eReturnStatusSuccessFinishNoResult); result.SetDidChangeProcessState(true); } else { result.AppendError( "no error returned from Target::Attach, and target has no process"); result.SetStatus(eReturnStatusFailed); } } else { result.AppendErrorWithFormat("attach failed: %s\n", error.AsCString()); result.SetStatus(eReturnStatusFailed); } if (!result.Succeeded()) return false; // Okay, we're done. Last step is to warn if the executable module has // changed: char new_path[PATH_MAX]; ModuleSP new_exec_module_sp(target->GetExecutableModule()); if (!old_exec_module_sp) { // We might not have a module if we attached to a raw pid... if (new_exec_module_sp) { new_exec_module_sp->GetFileSpec().GetPath(new_path, PATH_MAX); result.AppendMessageWithFormat("Executable module set to \"%s\".\n", new_path); } } else if (old_exec_module_sp->GetFileSpec() != new_exec_module_sp->GetFileSpec()) { char old_path[PATH_MAX]; old_exec_module_sp->GetFileSpec().GetPath(old_path, PATH_MAX); new_exec_module_sp->GetFileSpec().GetPath(new_path, PATH_MAX); result.AppendWarningWithFormat( "Executable module changed from \"%s\" to \"%s\".\n", old_path, new_path); } if (!old_arch_spec.IsValid()) { result.AppendMessageWithFormat( "Architecture set to: %s.\n", target->GetArchitecture().GetTriple().getTriple().c_str()); } else if (!old_arch_spec.IsExactMatch(target->GetArchitecture())) { result.AppendWarningWithFormat( "Architecture changed from %s to %s.\n", old_arch_spec.GetTriple().getTriple().c_str(), target->GetArchitecture().GetTriple().getTriple().c_str()); } // This supports the use-case scenario of immediately continuing the // process once attached. if (m_options.attach_info.GetContinueOnceAttached()) m_interpreter.HandleCommand("process continue", eLazyBoolNo, result); return result.Succeeded(); } CommandOptions m_options; }; // CommandObjectProcessContinue #define LLDB_OPTIONS_process_continue #include "CommandOptions.inc" #pragma mark CommandObjectProcessContinue class CommandObjectProcessContinue : public CommandObjectParsed { public: CommandObjectProcessContinue(CommandInterpreter &interpreter) : CommandObjectParsed( interpreter, "process continue", "Continue execution of all threads in the current process.", "process continue", eCommandRequiresProcess | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), m_options() {} ~CommandObjectProcessContinue() override = default; protected: class CommandOptions : public Options { public: CommandOptions() : Options() { // Keep default values of all options in one place: OptionParsingStarting // () OptionParsingStarting(nullptr); } ~CommandOptions() override = default; Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override { Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { case 'i': if (option_arg.getAsInteger(0, m_ignore)) error.SetErrorStringWithFormat( "invalid value for ignore option: \"%s\", should be a number.", option_arg.str().c_str()); break; default: llvm_unreachable("Unimplemented option"); } return error; } void OptionParsingStarting(ExecutionContext *execution_context) override { m_ignore = 0; } llvm::ArrayRef<OptionDefinition> GetDefinitions() override { return llvm::makeArrayRef(g_process_continue_options); } uint32_t m_ignore; }; bool DoExecute(Args &command, CommandReturnObject &result) override { Process *process = m_exe_ctx.GetProcessPtr(); bool synchronous_execution = m_interpreter.GetSynchronous(); StateType state = process->GetState(); if (state == eStateStopped) { if (command.GetArgumentCount() != 0) { result.AppendErrorWithFormat( "The '%s' command does not take any arguments.\n", m_cmd_name.c_str()); result.SetStatus(eReturnStatusFailed); return false; } if (m_options.m_ignore > 0) { ThreadSP sel_thread_sp(GetDefaultThread()->shared_from_this()); if (sel_thread_sp) { StopInfoSP stop_info_sp = sel_thread_sp->GetStopInfo(); if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint) { lldb::break_id_t bp_site_id = (lldb::break_id_t)stop_info_sp->GetValue(); BreakpointSiteSP bp_site_sp( process->GetBreakpointSiteList().FindByID(bp_site_id)); if (bp_site_sp) { const size_t num_owners = bp_site_sp->GetNumberOfOwners(); for (size_t i = 0; i < num_owners; i++) { Breakpoint &bp_ref = bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint(); if (!bp_ref.IsInternal()) { bp_ref.SetIgnoreCount(m_options.m_ignore); } } } } } } { // Scope for thread list mutex: std::lock_guard<std::recursive_mutex> guard( process->GetThreadList().GetMutex()); const uint32_t num_threads = process->GetThreadList().GetSize(); // Set the actions that the threads should each take when resuming for (uint32_t idx = 0; idx < num_threads; ++idx) { const bool override_suspend = false; process->GetThreadList().GetThreadAtIndex(idx)->SetResumeState( eStateRunning, override_suspend); } } const uint32_t iohandler_id = process->GetIOHandlerID(); StreamString stream; Status error; if (synchronous_execution) error = process->ResumeSynchronous(&stream); else error = process->Resume(); if (error.Success()) { // There is a race condition where this thread will return up the call // stack to the main command handler and show an (lldb) prompt before // HandlePrivateEvent (from PrivateStateThread) has a chance to call // PushProcessIOHandler(). process->SyncIOHandler(iohandler_id, std::chrono::seconds(2)); result.AppendMessageWithFormat("Process %" PRIu64 " resuming\n", process->GetID()); if (synchronous_execution) { // If any state changed events had anything to say, add that to the // result result.AppendMessage(stream.GetString()); result.SetDidChangeProcessState(true); result.SetStatus(eReturnStatusSuccessFinishNoResult); } else { result.SetStatus(eReturnStatusSuccessContinuingNoResult); } } else { result.AppendErrorWithFormat("Failed to resume process: %s.\n", error.AsCString()); result.SetStatus(eReturnStatusFailed); } } else { result.AppendErrorWithFormat( "Process cannot be continued from its current state (%s).\n", StateAsCString(state)); result.SetStatus(eReturnStatusFailed); } return result.Succeeded(); } Options *GetOptions() override { return &m_options; } CommandOptions m_options; }; // CommandObjectProcessDetach #define LLDB_OPTIONS_process_detach #include "CommandOptions.inc" #pragma mark CommandObjectProcessDetach class CommandObjectProcessDetach : public CommandObjectParsed { public: class CommandOptions : public Options { public: CommandOptions() : Options() { OptionParsingStarting(nullptr); } ~CommandOptions() override = default; Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override { Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { case 's': bool tmp_result; bool success; tmp_result = OptionArgParser::ToBoolean(option_arg, false, &success); if (!success) error.SetErrorStringWithFormat("invalid boolean option: \"%s\"", option_arg.str().c_str()); else { if (tmp_result) m_keep_stopped = eLazyBoolYes; else m_keep_stopped = eLazyBoolNo; } break; default: llvm_unreachable("Unimplemented option"); } return error; } void OptionParsingStarting(ExecutionContext *execution_context) override { m_keep_stopped = eLazyBoolCalculate; } llvm::ArrayRef<OptionDefinition> GetDefinitions() override { return llvm::makeArrayRef(g_process_detach_options); } // Instance variables to hold the values for command options. LazyBool m_keep_stopped; }; CommandObjectProcessDetach(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "process detach", "Detach from the current target process.", "process detach", eCommandRequiresProcess | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched), m_options() {} ~CommandObjectProcessDetach() override = default; Options *GetOptions() override { return &m_options; } protected: bool DoExecute(Args &command, CommandReturnObject &result) override { Process *process = m_exe_ctx.GetProcessPtr(); // FIXME: This will be a Command Option: bool keep_stopped; if (m_options.m_keep_stopped == eLazyBoolCalculate) { // Check the process default: keep_stopped = process->GetDetachKeepsStopped(); } else if (m_options.m_keep_stopped == eLazyBoolYes) keep_stopped = true; else keep_stopped = false; Status error(process->Detach(keep_stopped)); if (error.Success()) { result.SetStatus(eReturnStatusSuccessFinishResult); } else { result.AppendErrorWithFormat("Detach failed: %s\n", error.AsCString()); result.SetStatus(eReturnStatusFailed); return false; } return result.Succeeded(); } CommandOptions m_options; }; // CommandObjectProcessConnect #define LLDB_OPTIONS_process_connect #include "CommandOptions.inc" #pragma mark CommandObjectProcessConnect class CommandObjectProcessConnect : public CommandObjectParsed { public: class CommandOptions : public Options { public: CommandOptions() : Options() { // Keep default values of all options in one place: OptionParsingStarting // () OptionParsingStarting(nullptr); } ~CommandOptions() override = default; Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override { Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { case 'p': plugin_name.assign(std::string(option_arg)); break; default: llvm_unreachable("Unimplemented option"); } return error; } void OptionParsingStarting(ExecutionContext *execution_context) override { plugin_name.clear(); } llvm::ArrayRef<OptionDefinition> GetDefinitions() override { return llvm::makeArrayRef(g_process_connect_options); } // Instance variables to hold the values for command options. std::string plugin_name; }; CommandObjectProcessConnect(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "process connect", "Connect to a remote debug service.", "process connect <remote-url>", 0), m_options() {} ~CommandObjectProcessConnect() override = default; Options *GetOptions() override { return &m_options; } protected: bool DoExecute(Args &command, CommandReturnObject &result) override { if (command.GetArgumentCount() != 1) { result.AppendErrorWithFormat( "'%s' takes exactly one argument:\nUsage: %s\n", m_cmd_name.c_str(), m_cmd_syntax.c_str()); result.SetStatus(eReturnStatusFailed); return false; } Process *process = m_exe_ctx.GetProcessPtr(); if (process && process->IsAlive()) { result.AppendErrorWithFormat( "Process %" PRIu64 " is currently being debugged, kill the process before connecting.\n", process->GetID()); result.SetStatus(eReturnStatusFailed); return false; } const char *plugin_name = nullptr; if (!m_options.plugin_name.empty()) plugin_name = m_options.plugin_name.c_str(); Status error; Debugger &debugger = GetDebugger(); PlatformSP platform_sp = m_interpreter.GetPlatform(true); ProcessSP process_sp = platform_sp->ConnectProcess( command.GetArgumentAtIndex(0), plugin_name, debugger, debugger.GetSelectedTarget().get(), error); if (error.Fail() || process_sp == nullptr) { result.AppendError(error.AsCString("Error connecting to the process")); result.SetStatus(eReturnStatusFailed); return false; } return true; } CommandOptions m_options; }; // CommandObjectProcessPlugin #pragma mark CommandObjectProcessPlugin class CommandObjectProcessPlugin : public CommandObjectProxy { public: CommandObjectProcessPlugin(CommandInterpreter &interpreter) : CommandObjectProxy( interpreter, "process plugin", "Send a custom command to the current target process plug-in.", "process plugin <args>", 0) {} ~CommandObjectProcessPlugin() override = default; CommandObject *GetProxyCommandObject() override { Process *process = m_interpreter.GetExecutionContext().GetProcessPtr(); if (process) return process->GetPluginCommandObject(); return nullptr; } }; // CommandObjectProcessLoad #define LLDB_OPTIONS_process_load #include "CommandOptions.inc" #pragma mark CommandObjectProcessLoad class CommandObjectProcessLoad : public CommandObjectParsed { public: class CommandOptions : public Options { public: CommandOptions() : Options() { // Keep default values of all options in one place: OptionParsingStarting // () OptionParsingStarting(nullptr); } ~CommandOptions() override = default; Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override { Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { case 'i': do_install = true; if (!option_arg.empty()) install_path.SetFile(option_arg, FileSpec::Style::native); break; default: llvm_unreachable("Unimplemented option"); } return error; } void OptionParsingStarting(ExecutionContext *execution_context) override { do_install = false; install_path.Clear(); } llvm::ArrayRef<OptionDefinition> GetDefinitions() override { return llvm::makeArrayRef(g_process_load_options); } // Instance variables to hold the values for command options. bool do_install; FileSpec install_path; }; CommandObjectProcessLoad(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "process load", "Load a shared library into the current process.", "process load <filename> [<filename> ...]", eCommandRequiresProcess | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), m_options() {} ~CommandObjectProcessLoad() override = default; Options *GetOptions() override { return &m_options; } protected: bool DoExecute(Args &command, CommandReturnObject &result) override { Process *process = m_exe_ctx.GetProcessPtr(); for (auto &entry : command.entries()) { Status error; PlatformSP platform = process->GetTarget().GetPlatform(); llvm::StringRef image_path = entry.ref(); uint32_t image_token = LLDB_INVALID_IMAGE_TOKEN; if (!m_options.do_install) { FileSpec image_spec(image_path); platform->ResolveRemotePath(image_spec, image_spec); image_token = platform->LoadImage(process, FileSpec(), image_spec, error); } else if (m_options.install_path) { FileSpec image_spec(image_path); FileSystem::Instance().Resolve(image_spec); platform->ResolveRemotePath(m_options.install_path, m_options.install_path); image_token = platform->LoadImage(process, image_spec, m_options.install_path, error); } else { FileSpec image_spec(image_path); FileSystem::Instance().Resolve(image_spec); image_token = platform->LoadImage(process, image_spec, FileSpec(), error); } if (image_token != LLDB_INVALID_IMAGE_TOKEN) { result.AppendMessageWithFormat( "Loading \"%s\"...ok\nImage %u loaded.\n", image_path.str().c_str(), image_token); result.SetStatus(eReturnStatusSuccessFinishResult); } else { result.AppendErrorWithFormat("failed to load '%s': %s", image_path.str().c_str(), error.AsCString()); result.SetStatus(eReturnStatusFailed); } } return result.Succeeded(); } CommandOptions m_options; }; // CommandObjectProcessUnload #pragma mark CommandObjectProcessUnload class CommandObjectProcessUnload : public CommandObjectParsed { public: CommandObjectProcessUnload(CommandInterpreter &interpreter) : CommandObjectParsed( interpreter, "process unload", "Unload a shared library from the current process using the index " "returned by a previous call to \"process load\".", "process unload <index>", eCommandRequiresProcess | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {} ~CommandObjectProcessUnload() override = default; protected: bool DoExecute(Args &command, CommandReturnObject &result) override { Process *process = m_exe_ctx.GetProcessPtr(); for (auto &entry : command.entries()) { uint32_t image_token; if (entry.ref().getAsInteger(0, image_token)) { result.AppendErrorWithFormat("invalid image index argument '%s'", entry.ref().str().c_str()); result.SetStatus(eReturnStatusFailed); break; } else { Status error(process->GetTarget().GetPlatform()->UnloadImage( process, image_token)); if (error.Success()) { result.AppendMessageWithFormat( "Unloading shared library with index %u...ok\n", image_token); result.SetStatus(eReturnStatusSuccessFinishResult); } else { result.AppendErrorWithFormat("failed to unload image: %s", error.AsCString()); result.SetStatus(eReturnStatusFailed); break; } } } return result.Succeeded(); } }; // CommandObjectProcessSignal #pragma mark CommandObjectProcessSignal class CommandObjectProcessSignal : public CommandObjectParsed { public: CommandObjectProcessSignal(CommandInterpreter &interpreter) : CommandObjectParsed( interpreter, "process signal", "Send a UNIX signal to the current target process.", nullptr, eCommandRequiresProcess | eCommandTryTargetAPILock) { CommandArgumentEntry arg; CommandArgumentData signal_arg; // Define the first (and only) variant of this arg. signal_arg.arg_type = eArgTypeUnixSignal; signal_arg.arg_repetition = eArgRepeatPlain; // There is only one variant this argument could be; put it into the // argument entry. arg.push_back(signal_arg); // Push the data for the first argument into the m_arguments vector. m_arguments.push_back(arg); } ~CommandObjectProcessSignal() override = default; void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override { if (!m_exe_ctx.HasProcessScope() || request.GetCursorIndex() != 0) return; UnixSignalsSP signals = m_exe_ctx.GetProcessPtr()->GetUnixSignals(); int signo = signals->GetFirstSignalNumber(); while (signo != LLDB_INVALID_SIGNAL_NUMBER) { request.AddCompletion(signals->GetSignalAsCString(signo), ""); signo = signals->GetNextSignalNumber(signo); } } protected: bool DoExecute(Args &command, CommandReturnObject &result) override { Process *process = m_exe_ctx.GetProcessPtr(); if (command.GetArgumentCount() == 1) { int signo = LLDB_INVALID_SIGNAL_NUMBER; const char *signal_name = command.GetArgumentAtIndex(0); if (::isxdigit(signal_name[0])) signo = StringConvert::ToSInt32(signal_name, LLDB_INVALID_SIGNAL_NUMBER, 0); else signo = process->GetUnixSignals()->GetSignalNumberFromName(signal_name); if (signo == LLDB_INVALID_SIGNAL_NUMBER) { result.AppendErrorWithFormat("Invalid signal argument '%s'.\n", command.GetArgumentAtIndex(0)); result.SetStatus(eReturnStatusFailed); } else { Status error(process->Signal(signo)); if (error.Success()) { result.SetStatus(eReturnStatusSuccessFinishResult); } else { result.AppendErrorWithFormat("Failed to send signal %i: %s\n", signo, error.AsCString()); result.SetStatus(eReturnStatusFailed); } } } else { result.AppendErrorWithFormat( "'%s' takes exactly one signal number argument:\nUsage: %s\n", m_cmd_name.c_str(), m_cmd_syntax.c_str()); result.SetStatus(eReturnStatusFailed); } return result.Succeeded(); } }; // CommandObjectProcessInterrupt #pragma mark CommandObjectProcessInterrupt class CommandObjectProcessInterrupt : public CommandObjectParsed { public: CommandObjectProcessInterrupt(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "process interrupt", "Interrupt the current target process.", "process interrupt", eCommandRequiresProcess | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched) {} ~CommandObjectProcessInterrupt() override = default; protected: bool DoExecute(Args &command, CommandReturnObject &result) override { Process *process = m_exe_ctx.GetProcessPtr(); if (process == nullptr) { result.AppendError("no process to halt"); result.SetStatus(eReturnStatusFailed); return false; } if (command.GetArgumentCount() == 0) { bool clear_thread_plans = true; Status error(process->Halt(clear_thread_plans)); if (error.Success()) { result.SetStatus(eReturnStatusSuccessFinishResult); } else { result.AppendErrorWithFormat("Failed to halt process: %s\n", error.AsCString()); result.SetStatus(eReturnStatusFailed); } } else { result.AppendErrorWithFormat("'%s' takes no arguments:\nUsage: %s\n", m_cmd_name.c_str(), m_cmd_syntax.c_str()); result.SetStatus(eReturnStatusFailed); } return result.Succeeded(); } }; // CommandObjectProcessKill #pragma mark CommandObjectProcessKill class CommandObjectProcessKill : public CommandObjectParsed { public: CommandObjectProcessKill(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "process kill", "Terminate the current target process.", "process kill", eCommandRequiresProcess | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched) {} ~CommandObjectProcessKill() override = default; protected: bool DoExecute(Args &command, CommandReturnObject &result) override { Process *process = m_exe_ctx.GetProcessPtr(); if (process == nullptr) { result.AppendError("no process to kill"); result.SetStatus(eReturnStatusFailed); return false; } if (command.GetArgumentCount() == 0) { Status error(process->Destroy(true)); if (error.Success()) { result.SetStatus(eReturnStatusSuccessFinishResult); } else { result.AppendErrorWithFormat("Failed to kill process: %s\n", error.AsCString()); result.SetStatus(eReturnStatusFailed); } } else { result.AppendErrorWithFormat("'%s' takes no arguments:\nUsage: %s\n", m_cmd_name.c_str(), m_cmd_syntax.c_str()); result.SetStatus(eReturnStatusFailed); } return result.Succeeded(); } }; // CommandObjectProcessSaveCore #pragma mark CommandObjectProcessSaveCore class CommandObjectProcessSaveCore : public CommandObjectParsed { public: CommandObjectProcessSaveCore(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "process save-core", "Save the current process as a core file using an " "appropriate file type.", "process save-core FILE", eCommandRequiresProcess | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched) {} ~CommandObjectProcessSaveCore() override = default; protected: bool DoExecute(Args &command, CommandReturnObject &result) override { ProcessSP process_sp = m_exe_ctx.GetProcessSP(); if (process_sp) { if (command.GetArgumentCount() == 1) { FileSpec output_file(command.GetArgumentAtIndex(0)); Status error = PluginManager::SaveCore(process_sp, output_file); if (error.Success()) { result.SetStatus(eReturnStatusSuccessFinishResult); } else { result.AppendErrorWithFormat( "Failed to save core file for process: %s\n", error.AsCString()); result.SetStatus(eReturnStatusFailed); } } else { result.AppendErrorWithFormat("'%s' takes one arguments:\nUsage: %s\n", m_cmd_name.c_str(), m_cmd_syntax.c_str()); result.SetStatus(eReturnStatusFailed); } } else { result.AppendError("invalid process"); result.SetStatus(eReturnStatusFailed); return false; } return result.Succeeded(); } }; // CommandObjectProcessStatus #pragma mark CommandObjectProcessStatus #define LLDB_OPTIONS_process_status #include "CommandOptions.inc" class CommandObjectProcessStatus : public CommandObjectParsed { public: CommandObjectProcessStatus(CommandInterpreter &interpreter) : CommandObjectParsed( interpreter, "process status", "Show status and stop location for the current target process.", "process status", eCommandRequiresProcess | eCommandTryTargetAPILock), m_options() {} ~CommandObjectProcessStatus() override = default; Options *GetOptions() override { return &m_options; } class CommandOptions : public Options { public: CommandOptions() : Options(), m_verbose(false) {} ~CommandOptions() override = default; Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override { const int short_option = m_getopt_table[option_idx].val; switch (short_option) { case 'v': m_verbose = true; break; default: llvm_unreachable("Unimplemented option"); } return {}; } void OptionParsingStarting(ExecutionContext *execution_context) override { m_verbose = false; } llvm::ArrayRef<OptionDefinition> GetDefinitions() override { return llvm::makeArrayRef(g_process_status_options); } // Instance variables to hold the values for command options. bool m_verbose; }; protected: bool DoExecute(Args &command, CommandReturnObject &result) override { Stream &strm = result.GetOutputStream(); result.SetStatus(eReturnStatusSuccessFinishNoResult); if (command.GetArgumentCount()) { result.AppendError("'process status' takes no arguments"); result.SetStatus(eReturnStatusFailed); return result.Succeeded(); } // No need to check "process" for validity as eCommandRequiresProcess // ensures it is valid Process *process = m_exe_ctx.GetProcessPtr(); const bool only_threads_with_stop_reason = true; const uint32_t start_frame = 0; const uint32_t num_frames = 1; const uint32_t num_frames_with_source = 1; const bool stop_format = true; process->GetStatus(strm); process->GetThreadStatus(strm, only_threads_with_stop_reason, start_frame, num_frames, num_frames_with_source, stop_format); if (m_options.m_verbose) { PlatformSP platform_sp = process->GetTarget().GetPlatform(); if (!platform_sp) { result.AppendError("Couldn'retrieve the target's platform"); result.SetStatus(eReturnStatusFailed); return result.Succeeded(); } auto expected_crash_info = platform_sp->FetchExtendedCrashInformation(*process); if (!expected_crash_info) { result.AppendError(llvm::toString(expected_crash_info.takeError())); result.SetStatus(eReturnStatusFailed); return result.Succeeded(); } StructuredData::DictionarySP crash_info_sp = *expected_crash_info; if (crash_info_sp) { strm.PutCString("Extended Crash Information:\n"); crash_info_sp->Dump(strm); } } return result.Succeeded(); } private: CommandOptions m_options; }; // CommandObjectProcessHandle #define LLDB_OPTIONS_process_handle #include "CommandOptions.inc" #pragma mark CommandObjectProcessHandle class CommandObjectProcessHandle : public CommandObjectParsed { public: class CommandOptions : public Options { public: CommandOptions() : Options() { OptionParsingStarting(nullptr); } ~CommandOptions() override = default; Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override { Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { case 's': stop = std::string(option_arg); break; case 'n': notify = std::string(option_arg); break; case 'p': pass = std::string(option_arg); break; default: llvm_unreachable("Unimplemented option"); } return error; } void OptionParsingStarting(ExecutionContext *execution_context) override { stop.clear(); notify.clear(); pass.clear(); } llvm::ArrayRef<OptionDefinition> GetDefinitions() override { return llvm::makeArrayRef(g_process_handle_options); } // Instance variables to hold the values for command options. std::string stop; std::string notify; std::string pass; }; CommandObjectProcessHandle(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "process handle", "Manage LLDB handling of OS signals for the " "current target process. Defaults to showing " "current policy.", nullptr, eCommandRequiresTarget), m_options() { SetHelpLong("\nIf no signals are specified, update them all. If no update " "option is specified, list the current values."); CommandArgumentEntry arg; CommandArgumentData signal_arg; signal_arg.arg_type = eArgTypeUnixSignal; signal_arg.arg_repetition = eArgRepeatStar; arg.push_back(signal_arg); m_arguments.push_back(arg); } ~CommandObjectProcessHandle() override = default; Options *GetOptions() override { return &m_options; } bool VerifyCommandOptionValue(const std::string &option, int &real_value) { bool okay = true; bool success = false; bool tmp_value = OptionArgParser::ToBoolean(option, false, &success); if (success && tmp_value) real_value = 1; else if (success && !tmp_value) real_value = 0; else { // If the value isn't 'true' or 'false', it had better be 0 or 1. real_value = StringConvert::ToUInt32(option.c_str(), 3); if (real_value != 0 && real_value != 1) okay = false; } return okay; } void PrintSignalHeader(Stream &str) { str.Printf("NAME PASS STOP NOTIFY\n"); str.Printf("=========== ===== ===== ======\n"); } void PrintSignal(Stream &str, int32_t signo, const char *sig_name, const UnixSignalsSP &signals_sp) { bool stop; bool suppress; bool notify; str.Printf("%-11s ", sig_name); if (signals_sp->GetSignalInfo(signo, suppress, stop, notify)) { bool pass = !suppress; str.Printf("%s %s %s", (pass ? "true " : "false"), (stop ? "true " : "false"), (notify ? "true " : "false")); } str.Printf("\n"); } void PrintSignalInformation(Stream &str, Args &signal_args, int num_valid_signals, const UnixSignalsSP &signals_sp) { PrintSignalHeader(str); if (num_valid_signals > 0) { size_t num_args = signal_args.GetArgumentCount(); for (size_t i = 0; i < num_args; ++i) { int32_t signo = signals_sp->GetSignalNumberFromName( signal_args.GetArgumentAtIndex(i)); if (signo != LLDB_INVALID_SIGNAL_NUMBER) PrintSignal(str, signo, signal_args.GetArgumentAtIndex(i), signals_sp); } } else // Print info for ALL signals { int32_t signo = signals_sp->GetFirstSignalNumber(); while (signo != LLDB_INVALID_SIGNAL_NUMBER) { PrintSignal(str, signo, signals_sp->GetSignalAsCString(signo), signals_sp); signo = signals_sp->GetNextSignalNumber(signo); } } } protected: bool DoExecute(Args &signal_args, CommandReturnObject &result) override { Target *target_sp = &GetSelectedTarget(); ProcessSP process_sp = target_sp->GetProcessSP(); if (!process_sp) { result.AppendError("No current process; cannot handle signals until you " "have a valid process.\n"); result.SetStatus(eReturnStatusFailed); return false; } int stop_action = -1; // -1 means leave the current setting alone int pass_action = -1; // -1 means leave the current setting alone int notify_action = -1; // -1 means leave the current setting alone if (!m_options.stop.empty() && !VerifyCommandOptionValue(m_options.stop, stop_action)) { result.AppendError("Invalid argument for command option --stop; must be " "true or false.\n"); result.SetStatus(eReturnStatusFailed); return false; } if (!m_options.notify.empty() && !VerifyCommandOptionValue(m_options.notify, notify_action)) { result.AppendError("Invalid argument for command option --notify; must " "be true or false.\n"); result.SetStatus(eReturnStatusFailed); return false; } if (!m_options.pass.empty() && !VerifyCommandOptionValue(m_options.pass, pass_action)) { result.AppendError("Invalid argument for command option --pass; must be " "true or false.\n"); result.SetStatus(eReturnStatusFailed); return false; } size_t num_args = signal_args.GetArgumentCount(); UnixSignalsSP signals_sp = process_sp->GetUnixSignals(); int num_signals_set = 0; if (num_args > 0) { for (const auto &arg : signal_args) { int32_t signo = signals_sp->GetSignalNumberFromName(arg.c_str()); if (signo != LLDB_INVALID_SIGNAL_NUMBER) { // Casting the actions as bools here should be okay, because // VerifyCommandOptionValue guarantees the value is either 0 or 1. if (stop_action != -1) signals_sp->SetShouldStop(signo, stop_action); if (pass_action != -1) { bool suppress = !pass_action; signals_sp->SetShouldSuppress(signo, suppress); } if (notify_action != -1) signals_sp->SetShouldNotify(signo, notify_action); ++num_signals_set; } else { result.AppendErrorWithFormat("Invalid signal name '%s'\n", arg.c_str()); } } } else { // No signal specified, if any command options were specified, update ALL // signals. if ((notify_action != -1) || (stop_action != -1) || (pass_action != -1)) { if (m_interpreter.Confirm( "Do you really want to update all the signals?", false)) { int32_t signo = signals_sp->GetFirstSignalNumber(); while (signo != LLDB_INVALID_SIGNAL_NUMBER) { if (notify_action != -1) signals_sp->SetShouldNotify(signo, notify_action); if (stop_action != -1) signals_sp->SetShouldStop(signo, stop_action); if (pass_action != -1) { bool suppress = !pass_action; signals_sp->SetShouldSuppress(signo, suppress); } signo = signals_sp->GetNextSignalNumber(signo); } } } } PrintSignalInformation(result.GetOutputStream(), signal_args, num_signals_set, signals_sp); if (num_signals_set > 0) result.SetStatus(eReturnStatusSuccessFinishNoResult); else result.SetStatus(eReturnStatusFailed); return result.Succeeded(); } CommandOptions m_options; }; // CommandObjectMultiwordProcess CommandObjectMultiwordProcess::CommandObjectMultiwordProcess( CommandInterpreter &interpreter) : CommandObjectMultiword( interpreter, "process", "Commands for interacting with processes on the current platform.", "process <subcommand> [<subcommand-options>]") { LoadSubCommand("attach", CommandObjectSP(new CommandObjectProcessAttach(interpreter))); LoadSubCommand("launch", CommandObjectSP(new CommandObjectProcessLaunch(interpreter))); LoadSubCommand("continue", CommandObjectSP(new CommandObjectProcessContinue( interpreter))); LoadSubCommand("connect", CommandObjectSP(new CommandObjectProcessConnect(interpreter))); LoadSubCommand("detach", CommandObjectSP(new CommandObjectProcessDetach(interpreter))); LoadSubCommand("load", CommandObjectSP(new CommandObjectProcessLoad(interpreter))); LoadSubCommand("unload", CommandObjectSP(new CommandObjectProcessUnload(interpreter))); LoadSubCommand("signal", CommandObjectSP(new CommandObjectProcessSignal(interpreter))); LoadSubCommand("handle", CommandObjectSP(new CommandObjectProcessHandle(interpreter))); LoadSubCommand("status", CommandObjectSP(new CommandObjectProcessStatus(interpreter))); LoadSubCommand("interrupt", CommandObjectSP(new CommandObjectProcessInterrupt( interpreter))); LoadSubCommand("kill", CommandObjectSP(new CommandObjectProcessKill(interpreter))); LoadSubCommand("plugin", CommandObjectSP(new CommandObjectProcessPlugin(interpreter))); LoadSubCommand("save-core", CommandObjectSP(new CommandObjectProcessSaveCore( interpreter))); } CommandObjectMultiwordProcess::~CommandObjectMultiwordProcess() = default;
35.278158
80
0.646582
tiwaria1
4f5a1e82254a216b948d13df57a75f6d2c6d8613
5,515
cc
C++
vendor/github.com/cockroachdb/c-rocksdb/internal_db_db_impl_experimental.cc
Matthewbalala/FabricSharp
a3000826dbcf70f9d8dc6a678d8d01e3a4eee3ba
[ "Apache-2.0" ]
3
2021-05-25T03:12:11.000Z
2021-09-29T01:29:10.000Z
vendor/github.com/cockroachdb/c-rocksdb/internal_db_db_impl_experimental.cc
Matthewbalala/FabricSharp
a3000826dbcf70f9d8dc6a678d8d01e3a4eee3ba
[ "Apache-2.0" ]
null
null
null
vendor/github.com/cockroachdb/c-rocksdb/internal_db_db_impl_experimental.cc
Matthewbalala/FabricSharp
a3000826dbcf70f9d8dc6a678d8d01e3a4eee3ba
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // // Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "db/db_impl.h" #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include <inttypes.h> #include <vector> #include "db/column_family.h" #include "db/job_context.h" #include "db/version_set.h" #include "rocksdb/status.h" namespace rocksdb { #ifndef ROCKSDB_LITE Status DBImpl::SuggestCompactRange(ColumnFamilyHandle* column_family, const Slice* begin, const Slice* end) { auto cfh = reinterpret_cast<ColumnFamilyHandleImpl*>(column_family); auto cfd = cfh->cfd(); InternalKey start_key, end_key; if (begin != nullptr) { start_key.SetMaxPossibleForUserKey(*begin); } if (end != nullptr) { end_key.SetMinPossibleForUserKey(*end); } { InstrumentedMutexLock l(&mutex_); auto vstorage = cfd->current()->storage_info(); for (int level = 0; level < vstorage->num_non_empty_levels() - 1; ++level) { std::vector<FileMetaData*> inputs; vstorage->GetOverlappingInputs( level, begin == nullptr ? nullptr : &start_key, end == nullptr ? nullptr : &end_key, &inputs); for (auto f : inputs) { f->marked_for_compaction = true; } } // Since we have some more files to compact, we should also recompute // compaction score vstorage->ComputeCompactionScore(*cfd->ioptions(), *cfd->GetLatestMutableCFOptions()); SchedulePendingCompaction(cfd); MaybeScheduleFlushOrCompaction(); } return Status::OK(); } Status DBImpl::PromoteL0(ColumnFamilyHandle* column_family, int target_level) { assert(column_family); if (target_level < 1) { Log(InfoLogLevel::INFO_LEVEL, immutable_db_options_.info_log, "PromoteL0 FAILED. Invalid target level %d\n", target_level); return Status::InvalidArgument("Invalid target level"); } Status status; VersionEdit edit; JobContext job_context(next_job_id_.fetch_add(1), true); { InstrumentedMutexLock l(&mutex_); auto* cfd = static_cast<ColumnFamilyHandleImpl*>(column_family)->cfd(); const auto* vstorage = cfd->current()->storage_info(); if (target_level >= vstorage->num_levels()) { Log(InfoLogLevel::INFO_LEVEL, immutable_db_options_.info_log, "PromoteL0 FAILED. Target level %d does not exist\n", target_level); job_context.Clean(); return Status::InvalidArgument("Target level does not exist"); } // Sort L0 files by range. const InternalKeyComparator* icmp = &cfd->internal_comparator(); auto l0_files = vstorage->LevelFiles(0); std::sort(l0_files.begin(), l0_files.end(), [icmp](FileMetaData* f1, FileMetaData* f2) { return icmp->Compare(f1->largest, f2->largest) < 0; }); // Check that no L0 file is being compacted and that they have // non-overlapping ranges. for (size_t i = 0; i < l0_files.size(); ++i) { auto f = l0_files[i]; if (f->being_compacted) { Log(InfoLogLevel::INFO_LEVEL, immutable_db_options_.info_log, "PromoteL0 FAILED. File %" PRIu64 " being compacted\n", f->fd.GetNumber()); job_context.Clean(); return Status::InvalidArgument("PromoteL0 called during L0 compaction"); } if (i == 0) continue; auto prev_f = l0_files[i - 1]; if (icmp->Compare(prev_f->largest, f->smallest) >= 0) { Log(InfoLogLevel::INFO_LEVEL, immutable_db_options_.info_log, "PromoteL0 FAILED. Files %" PRIu64 " and %" PRIu64 " have overlapping ranges\n", prev_f->fd.GetNumber(), f->fd.GetNumber()); job_context.Clean(); return Status::InvalidArgument("L0 has overlapping files"); } } // Check that all levels up to target_level are empty. for (int level = 1; level <= target_level; ++level) { if (vstorage->NumLevelFiles(level) > 0) { Log(InfoLogLevel::INFO_LEVEL, immutable_db_options_.info_log, "PromoteL0 FAILED. Level %d not empty\n", level); job_context.Clean(); return Status::InvalidArgument( "All levels up to target_level " "must be empty"); } } edit.SetColumnFamily(cfd->GetID()); for (const auto& f : l0_files) { edit.DeleteFile(0, f->fd.GetNumber()); edit.AddFile(target_level, f->fd.GetNumber(), f->fd.GetPathId(), f->fd.GetFileSize(), f->smallest, f->largest, f->smallest_seqno, f->largest_seqno, f->marked_for_compaction); } status = versions_->LogAndApply(cfd, *cfd->GetLatestMutableCFOptions(), &edit, &mutex_, directories_.GetDbDir()); if (status.ok()) { InstallSuperVersionAndScheduleWorkWrapper( cfd, &job_context, *cfd->GetLatestMutableCFOptions()); } } // lock released here LogFlush(immutable_db_options_.info_log); job_context.Clean(); return status; } #endif // ROCKSDB_LITE } // namespace rocksdb
36.282895
80
0.648776
Matthewbalala
4f5b076939ee5448da1311527d9402230a84e45d
25,674
hpp
C++
src/data/vector.hpp
Harrand/Engine-A
995fff8a7a07ac496c368a235659e72107b6b6cb
[ "Apache-2.0" ]
null
null
null
src/data/vector.hpp
Harrand/Engine-A
995fff8a7a07ac496c368a235659e72107b6b6cb
[ "Apache-2.0" ]
null
null
null
src/data/vector.hpp
Harrand/Engine-A
995fff8a7a07ac496c368a235659e72107b6b6cb
[ "Apache-2.0" ]
null
null
null
#ifndef VECTOR_HPP #define VECTOR_HPP #include <array> #include <functional> #include <cmath> /** * Vector to hold a quantity of some value. It's a glorified array. * @tparam N - Number of elements * @tparam T - Type of element */ template<unsigned int N, typename T> class Vector { public: /** * Construct a Vector directly from an array. * @param data - The data to be copied into the vector. */ constexpr Vector(std::array<T, N> underlying_data); /** * Return magnitude of the Vector. * @param sqrt_function - The function to use to perform a square-root on the type T. If none is provided, the default std::sqrt will be used. * @return - Magnitude of the Vector. */ T length(std::function<T(T)> sqrt_function = std::sqrt) const; const std::array<T, N>& data() const; Vector<N, T> lerp(const Vector<N, T>& rhs, double proportion) const; /** * Explicitly convert to a string. * @return String in the following format: "[d0, d1, ...]" */ explicit operator std::string() const; bool operator==(const Vector<N, T>& rhs) const; bool operator!=(const Vector<N, T>& rhs) const; /// Array representing the underlying data. std::array<T, N> underlying_data; }; template<unsigned int N, typename T> std::ostream& operator<<(std::ostream& os, const Vector<N, T>& vector); /** * Spatial 2-dimensional Vector. * Subclass of a partial specialisation of Vector. * @tparam T - Type of element */ template<typename T> class Vector2 : public Vector<2, T> { public: /** * Construct a 2-dimensional Vector directly from arguments. * @param x - Representation of the x-coordinate. * @param y - Representation of the y-coordinate. */ constexpr Vector2<T>(T x = T(), T y = T()); /** * Construct a 2-dimensional vector from an existing array. * @param data - The array to be copied. */ constexpr Vector2<T>(const std::array<T, 2>& data); /** * Construct a 2-dimensional Vector, copying attributes from an existing 2-dimensional Vector. * @param copy - The existing 2-dimensional Vector to copy attributes from */ Vector2<T>(const Vector2<T>& copy); /** * Construct a 2-dimensional Vector, moving attributes from an existing 2-dimensional Vector. * @param move - The existing 2-dimensional Vector to move attributes from */ Vector2<T>(Vector2<T>&& move); /** * Assign the data members of this 2-dimensional Vector to be equal to another. * @param rhs - The 2-dimensional Vector to copy from * @return - This, after assignment */ Vector2<T>& operator=(const Vector2<T>& rhs); /** * Assign the data members of this 3-dimensional Vector to be equal to an existing base-vector. * @param rhs - The 3-dimensional Vector to copy from * @return - This, after assignment */ Vector2<T>& operator=(const Vector<2, T>& rhs); /** * Find the magnitude of the 2-dimensional Vector. * @return - Magnitude of the 2-dimensional Vector. */ T length() const; /** * Perform a 2-dimensional dot-product. * @param rhs - The other 2-dimensional Vector to compute the dot-product from. * @return - Dot product of this and the parameter. */ T dot(const Vector2<T>& rhs) const; /** * Divide all data members by the magnitude, and return the copy. * @return - Normalised version of this 2-dimensional Vector. */ Vector2<T> normalised() const; /** * Add a pair of 2-dimensional Vectors. * @param rhs - The other 2-dimensional Vector to perform the addition with. * @return - this + the parameter. */ Vector2<T> operator+(const Vector2<T>& rhs) const; /** * Subtract a pair of 2-dimensional Vectors. * @param rhs - The other 2-dimensional Vector to perform the subtraction with. * @return - this - the parameter. */ Vector2<T> operator-(const Vector2<T>& rhs) const; /** * Multiply this 2-dimensional Vector by a scalar of the same underlying type. Return a copy of the result. * @param scalar - The scalar to multiply this Vector by. * @return - this * the scalar. */ Vector2<T> operator*(const T& scalar) const; /** * Divide this 2-dimensional Vector by a scalar of the same underlying type. Return a copy of the result. * @param scalar - The scalar to divide this Vector by. * @return - this ÷ the parameter. */ Vector2<T> operator/(const T& scalar) const; /** * Assign this 2-dimensional Vector to the addition of this and another 2-dimensional Vector. * @param rhs - The other 2-dimensional Vector to perform the addition with. * @return - this, where 'this = this + the parameter'. */ Vector2<T>& operator+=(const Vector2<T>& rhs); /** * Assign this 2-dimensional Vector to the subtraction of this and another 2-dimensional Vector. * @param rhs - The other 2-dimensional Vector to perform the subtraction with. * @return - this, where 'this = this - the parameter'. */ Vector2<T>& operator-=(const Vector2<T>& rhs); /** * Assign this 2-dimensional Vector to the multiplication of this and a scalar with the same underlying type. * @param scalar - The scalar to perform the multiplication with. * @return - this, where 'this = this * the parameter'. */ Vector2<T>& operator*=(const T& scalar); /** * Assign this 2-dimensional Vector to the division of this and a scalar with the same underlying type. * @param scalar - The scalar to perform the division with. * @return - this, where 'this = this ÷ the parameter'. */ Vector2<T>& operator/=(const T& scalar); /** * Compare this to another 2-dimensional Vector. * @param rhs - The other 2-dimensional Vector to compare this to. * @return - True if all data members of this are lesser than the data members of the parameter. */ bool operator<(const Vector2<T>& rhs) const; /** * Compare this to another 2-dimensional Vector. * @param rhs - The other 2-dimensional Vector to compare this to. * @return - True if all data members of this are greater than the data members of the parameter. */ bool operator>(const Vector2<T>& rhs) const; /** * Compare this to another 2-dimensional Vector. * @param rhs - The other 2-dimensional Vector to compare this to. * @return - True if all data members of this are lesser than or equal to the data members of the parameter. */ bool operator<=(const Vector2<T>& rhs) const; /** * Compare this to another 2-dimensional Vector. * @param rhs - The other 2-dimensional Vector to compare this to. * @return - True if all data members of this are greater than or equal to the data members of the parameter. */ bool operator>=(const Vector2<T>& rhs) const; /** * Equate this with another 2-dimensional Vector. * @param rhs - The other 2-dimensional Vector to compare this to. * @return - True if all data members of this are equal to the data members of the parameter. */ bool operator==(const Vector2<T>& rhs) const; /** * Swizzle operator xy. * @return - The 2-dimensional Vector [x, y] */ Vector2<T> xy() const; /** * Swizzle operator yx. * @return - The 2-dimensional Vector [y, x] */ Vector2<T> yx() const; /// References the first element in the data array. T& x; /// References the second element in the data array. T& y; private: using Vector<2, T>::underlying_data; }; /** * Spatial 3-dimensional Vector. * Subclass of a partial specialisation of Vector. * @tparam T - Type of element */ template<typename T> class Vector3: public Vector<3, T> { public: /** * Construct a 3-dimensional Vector directly from arguments. * @param x - Representation of the x-coordinate. * @param y - Representation of the y-coordinate. * @param z - Representation of the z-coordinate. */ constexpr Vector3<T>(T x = T(), T y = T(), T z = T()); /** * Construct a 3-dimensional Vector via concatenation of a 2-dimensional Vector and a scalar. * @param xy - Beginning 2-dimensional Vector component. * @param z - Ending scalar component. */ constexpr Vector3<T>(Vector2<T> xy, T z); /** * Construct a 3-dimensional Vector via concatenation of a scalar and a 2-dimensional Vector. * @param x - Beginning scalar component. * @param yz - Ending 2-dimensional Vector component. */ constexpr Vector3<T>(T x, Vector2<T> yz); /** * Construct a 3-dimensional vector from an existing array. * @param data - The array to be copied. */ constexpr Vector3<T>(const std::array<T, 3>& data); /** * Construct a 3-dimensional Vector, copying attributes from an existing 3-dimensional Vector. * @param copy - The existing 3-dimensional Vector to copy attributes from */ Vector3<T>(const Vector3<T>& copy); /** * Construct a 3-dimensional Vector, moving attributes from an existing 3-dimensional Vector. * @param move - The existing 3-dimensional Vector to move attributes from */ Vector3<T>(Vector3<T>&& move); /** * Assign the data members of this 3-dimensional Vector to be equal to another. * @param rhs - The 3-dimensional Vector to copy from * @return - This, after assignment */ Vector3<T>& operator=(const Vector3<T>& rhs); /** * Assign the data members of this 3-dimensional Vector to be equal to an existing base-vector. * @param rhs - The 3-dimensional Vector to copy from * @return - This, after assignment */ Vector3<T>& operator=(const Vector<3, T>& rhs); /** * Find the magnitude of the 3-dimensional Vector. * @return - Magnitude of the 3-dimensional Vector. */ T length() const; /** * Perform a 3-dimensional dot-product. * @param rhs - The other 3-dimensional Vector to compute the dot-product from. * @return - Dot product of this and the parameter. */ T dot(const Vector3<T>& rhs) const; /** * Perform a 3-dimensional cross-product. * @param rhs - The other 3-dimensional Vector to compute the cross-product from. * @return - Cross product of this and the parameter. */ Vector3<T> cross(const Vector3<T>& rhs) const; Vector3<T> reflect(const Vector3<T>& rhs) const; /** * Divide all data members by the magnitude, and return the copy. * @return - Normalised version of this 3-dimensional Vector. */ Vector3<T> normalised() const; /** * Add a pair of 3-dimensional Vectors. * @param rhs - The other 3-dimensional Vector to perform the addition with. * @return - this + the parameter. */ Vector3<T> operator+(const Vector3<T>& rhs) const; /** * Subtract a pair of 3-dimensional Vectors. * @param rhs - The other 3-dimensional Vector to perform the subtraction with. * @return - this - the parameter. */ Vector3<T> operator-(const Vector3<T>& rhs) const; /** * Multiply this 3-dimensional Vector by a scalar of the same underlying type. Return a copy of the result. * @param scalar - The scalar to multiply this Vector by. * @return - this * the scalar. */ Vector3<T> operator*(const T& scalar) const; /** * Divide this 3-dimensional Vector by a scalar of the same underlying type. Return a copy of the result. * @param scalar - The scalar to divide this Vector by. * @return - this ÷ the parameter. */ Vector3<T> operator/(const T& scalar) const; /** * Assign this 3-dimensional Vector to the addition of this and another 3-dimensional Vector. * @param rhs - The other 3-dimensional Vector to perform the addition with. * @return - this, where 'this = this + the parameter'. */ Vector3<T>& operator+=(const Vector3<T>& rhs); /** * Assign this 3-dimensional Vector to the subtraction of this and another 3-dimensional Vector. * @param rhs - The other 3-dimensional Vector to perform the subtraction with. * @return - this, where 'this = this - the parameter'. */ Vector3<T>& operator-=(const Vector3<T>& rhs); /** * Assign this 3-dimensional Vector to the multiplication of this and a scalar with the same underlying type. * @param scalar - The scalar to perform the multiplication with. * @return - this, where 'this = this * the parameter'. */ Vector3<T>& operator*=(const T& scalar); /** * Assign this 3-dimensional Vector to the division of this and a scalar with the same underlying type. * @param scalar - The scalar to perform the division with. * @return - this, where 'this = this ÷ the parameter'. */ Vector3<T>& operator/=(const T& scalar); /** * Compare this to another 3-dimensional Vector. * @param rhs - The other 3-dimensional Vector to compare this to. * @return - True if all data members of this are lesser than the data members of the parameter. */ bool operator<(const Vector3<T>& rhs) const; /** * Compare this to another 3-dimensional Vector. * @param rhs - The other 3-dimensional Vector to compare this to. * @return - True if all data members of this are greater than the data members of the parameter. */ bool operator>(const Vector3<T>& rhs) const; /** * Compare this to another 3-dimensional Vector. * @param rhs - The other 3-dimensional Vector to compare this to. * @return - True if all data members of this are lesser than or equal to the data members of the parameter. */ bool operator<=(const Vector3<T>& rhs) const; /** * Compare this to another 3-dimensional Vector. * @param rhs - The other 3-dimensional Vector to compare this to. * @return - True if all data members of this are greater than or equal to the data members of the parameter. */ bool operator>=(const Vector3<T>& rhs) const; /** * Equate this with another 3-dimensional Vector. * @param rhs - The other 3-dimensional Vector to compare this to. * @return - True if all data members of this are equal to the data members of the parameter. */ bool operator==(const Vector3<T>& rhs) const; /** * Swizzle operator xy. * @return - The 2-dimensional Vector [x, y] */ Vector2<T> xy() const; /** * Swizzle operator yx. * @return - The 2-dimensional Vector [y, x] */ Vector2<T> yx() const; /** * Swizzle operator xyz. * @return - The 3-dimensional Vector {x, y, z} */ Vector3<T> xyz() const; /** * Swizzle operator xzy. * @return - The 3-dimensional Vector {x, z, y} */ Vector3<T> xzy() const; /** * Swizzle operator yxz. * @return - The 3-dimensional Vector {y, x, z} */ Vector3<T> yxz() const; /** * Swizzle operator yzx. * @return - The 3-dimensional Vector {y, z, x} */ Vector3<T> yzx() const; /** * Swizzle operator zxy. * @return - The 3-dimensional Vector {z, x, y} */ Vector3<T> zxy() const; /** * Swizzle operator zyx. * @return - The 3-dimensional Vector {z, y, x} */ Vector3<T> zyx() const; /// References the first element in the data array. T& x; /// References the second element in the data array. T& y; /// References the third element in the data array. T& z; private: using Vector<3, T>::underlying_data; }; /** * Spatial 4-dimensional Vector. * Subclass of a partial specialisation of Vector. * @tparam T - Type of element */ template<typename T> class Vector4: public Vector<4, T> { public: /** * Construct a 4-dimensional Vector directly from arguments. * @param x - Representation of the x-coordinate. * @param y - Representation of the y-coordinate. * @param z - Representation of the z-coordinate. * @param w - Representation of the w-coordinate. */ constexpr Vector4<T>(T x = T(), T y = T(), T z = T(), T w = T()); /** * Construct a 4-dimensional Vector via concatenation of a 3-dimensional Vector and a scalar. * @param xyz - Beginning 3-dimensional Vector component. * @param w - Ending scalar component. */ constexpr Vector4<T>(Vector3<T> xyz, T w); /** * Construct a 4-dimensional Vector via concatenation of a scalar and a 3-dimensional Vector. * @param x - Beginning scalar component. * @param yzw - Ending 3-dimensional Vector component. */ constexpr Vector4<T>(T x, Vector3<T> yzw); /** * Construct a 4-dimensional Vector via concatenation of a pair of 2-dimensional Vectors. * @param xy - Beginning 2-dimensional Vector component. * @param zw - Ending 2-dimensional Vector component. */ constexpr Vector4<T>(Vector2<T> xy, Vector2<T> zw); /** * Construct a 4-dimensional vector from an existing array. * @param data - The array to be copied. */ constexpr Vector4<T>(const std::array<T, 4>& data); /** * Construct a 4-dimensional Vector, copying attributes from an existing 4-dimensional Vector. * @param copy - The existing 4-dimensional Vector to copy attributes from */ Vector4<T>(const Vector4<T>& copy); /** * Construct a 4-dimensional Vector, moving attributes from an existing 4-dimensional Vector. * @param move - The existing 4-dimensional Vector to move attributes from */ Vector4<T>(Vector4<T>&& move); /** * Assign the data members of this 4-dimensional Vector to be equal to another. * @param rhs - The 4-dimensional Vector to copy from * @return - This, after assignment */ Vector4<T>& operator=(const Vector4<T>& rhs); /** * Assign the data members of this 3-dimensional Vector to be equal to an existing base-vector. * @param rhs - The 3-dimensional Vector to copy from * @return - This, after assignment */ Vector4<T>& operator=(const Vector<4, T>& rhs); /** * Find the magnitude of the 4-dimensional Vector. * @return - Magnitude of the 4-dimensional Vector. */ T length() const; /** * Perform a 4-dimensional dot-product. * @param rhs - The other 4-dimensional Vector to compute the dot-product from. * @return - Dot product of this and the parameter. */ T dot(Vector4<T> rhs) const; /** * Divide all data members by the magnitude, and return the copy. * @return - Normalised version of this 4-dimensional Vector. */ Vector4<T> normalised() const; /** * Add a pair of 4-dimensional Vectors. * @param rhs - The other 4-dimensional Vector to perform the addition with. * @return - this + the parameter. */ Vector4<T> operator+(const Vector4<T>& rhs) const; /** * Subtract a pair of 4-dimensional Vectors. * @param rhs - The other 4-dimensional Vector to perform the subtraction with. * @return - this - the parameter. */ Vector4<T> operator-(const Vector4<T>& rhs) const; /** * Assign this 4-dimensional Vector to the multiplication of this and a scalar with the same underlying type. * @param scalar - The scalar to perform the multiplication with. * @return - this, where 'this = this * the parameter'. */ Vector4<T> operator*(const T& scalar) const; /** * Assign this 4-dimensional Vector to the division of this and a scalar with the same underlying type. * @param scalar - The scalar to perform the division with. * @return - this, where 'this = this ÷ the parameter'. */ Vector4<T> operator/(const T& scalar) const; /** * Assign this 4-dimensional Vector to the addition of this and another 4-dimensional Vector. * @param rhs - The other 4-dimensional Vector to perform the addition with. * @return - this, where 'this = this + the parameter'. */ Vector4<T>& operator+=(const Vector4<T>& rhs); /** * Assign this 4-dimensional Vector to the subtraction of this and another 4-dimensional Vector. * @param rhs - The other 4-dimensional Vector to perform the subtraction with. * @return - this, where 'this = this - the parameter'. */ Vector4<T>& operator-=(const Vector4<T>& rhs); /** * Assign this 4-dimensional Vector to the multiplication of this and a scalar with the same underlying type. * @param scalar - The scalar to perform the multiplication with. * @return - this, where 'this = this * the parameter'. */ Vector4<T>& operator*=(const T& scalar); /** * Assign this 4-dimensional Vector to the division of this and a scalar with the same underlying type. * @param scalar - The scalar to perform the division with. * @return - this, where 'this = this ÷ the parameter'. */ Vector4<T>& operator/=(const T& scalar); /** * Compare this to another 4-dimensional Vector. * @param rhs - The other 4-dimensional Vector to compare this to. * @return - True if all data members of this are lesser than the data members of the parameter. */ bool operator<(const Vector4<T>& rhs) const; /** * Compare this to another 4-dimensional Vector. * @param rhs - The other 4-dimensional Vector to compare this to. * @return - True if all data members of this are greater than the data members of the parameter. */ bool operator>(const Vector4<T>& rhs) const; /** * Compare this to another 4-dimensional Vector. * @param rhs - The other 4-dimensional Vector to compare this to. * @return - True if all data members of this are lesser than or equal to the data members of the parameter. */ bool operator<=(const Vector4<T>& rhs) const; /** * Compare this to another 4-dimensional Vector. * @param rhs - The other 4-dimensional Vector to compare this to. * @return - True if all data members of this are greater than or equal to the data members of the parameter. */ bool operator>=(const Vector4<T>& rhs) const; /** * Equate this with another 4-dimensional Vector. * @param rhs - The other 4-dimensional Vector to compare this to. * @return - True if all data members of this are equal to the data members of the parameter. */ bool operator==(const Vector4<T>& rhs) const; /** * Swizzle operator xy. * @return - The 2-dimensional Vector [x, y] */ Vector2<T> xy() const; /** * Swizzle operator yx. * @return - The 2-dimensional Vector [y, x] */ Vector2<T> yx() const; /** * Swizzle operator xyz. * @return - The 3-dimensional Vector {x, y, z} */ Vector3<T> xyz() const; /** * Swizzle operator xzy. * @return - The 3-dimensional Vector {x, z, y} */ Vector3<T> xzy() const; /** * Swizzle operator yxz. * @return - The 3-dimensional Vector {y, x, z} */ Vector3<T> yxz() const; /** * Swizzle operator yzx. * @return - The 3-dimensional Vector {y, z, x} */ Vector3<T> yzx() const; /** * Swizzle operator zxy. * @return - The 3-dimensional Vector {z, x, y} */ Vector3<T> zxy() const; /** * Swizzle operator zyx. * @return - The 3-dimensional Vector {z, y, x} */ Vector3<T> zyx() const; /** * Swizzle operator xyzw. * @return - The 4-dimensional Vector {x, y, z, w} */ Vector4<T> xyzw() const; /** * Swizzle operator xywz. * @return - The 4-dimensional Vector {x, y, w, z} */ Vector4<T> xywz() const; /** * Swizzle operator xzyw. * @return - The 4-dimensional Vector {x, z, y, w} */ Vector4<T> xzyw() const; /** * Swizzle operator xzwy. * @return - The 4-dimensional Vector {x, z, w, y} */ Vector4<T> xzwy() const; /** * Swizzle operator xwyz. * @return - The 4-dimensional Vector {x, w, y, z} */ Vector4<T> xwyz() const; /** * Swizzle operator xwzy. * @return - The 4-dimensional Vector {x, w, z, y} */ Vector4<T> xwzy() const; /** * Swizzle operator yxzw. * @return - The 4-dimensional Vector {y, x, z, w} */ Vector4<T> yxzw() const; /** * Swizzle operator yxwz. * @return - The 4-dimensional Vector {y, x, w, z} */ Vector4<T> yxwz() const; /** * Swizzle operator yzxw. * @return - The 4-dimensional Vector {y, z, x, w} */ Vector4<T> yzxw() const; /** * Swizzle operator yzwx. * @return - The 4-dimensional Vector {y, z, w, x} */ Vector4<T> yzwx() const; /** * Swizzle operator ywxz. * @return - The 4-dimensional Vector {y, w, x, z} */ Vector4<T> ywxz() const; /** * Swizzle operator ywzx. * @return - The 4-dimensional Vector {y, w, z, x} */ Vector4<T> ywzx() const; /** * Swizzle operator zxyw. * @return - The 4-dimensional Vector {z, x, y, w} */ Vector4<T> zxyw() const; /** * Swizzle operator zxwy. * @return - The 4-dimensional Vector {zxwy} */ Vector4<T> zxwy() const; /** * Swizzle operator zyxw. * @return - The 4-dimensional Vector {z, y, x, w} */ Vector4<T> zyxw() const; /** * Swizzle operator zywx. * @return - The 4-dimensional Vector {z, y, w, x} */ Vector4<T> zywx() const; /** * Swizzle operator zwxy. * @return - The 4-dimensional Vector {z, w, x, y} */ Vector4<T> zwxy() const; /** * Swizzle operator zwyx. * @return - The 4-dimensional Vector {z, w, y, x} */ Vector4<T> zwyx() const; /** * Swizzle operator wxyz. * @return - The 4-dimensional Vector {w, x, y, z} */ Vector4<T> wxyz() const; /** * Swizzle operator wxzy. * @return - The 4-dimensional Vector {w, x, z, y} */ Vector4<T> wxzy() const; /** * Swizzle operator wyxz. * @return - The 4-dimensional Vector {w, y, x, z} */ Vector4<T> wyxz() const; /** * Swizzle operator wyzx. * @return - The 4-dimensional Vector {w, y, z, x} */ Vector4<T> wyzx() const; /** * Swizzle operator wzxy. * @return - The 4-dimensional Vector {w, z, x, y} */ Vector4<T> wzxy() const; /** * Swizzle operator wzyx. * @return - The 4-dimensional Vector {w, z, y, x} */ Vector4<T> wzyx() const; /// References the first element in the data array. T& x; /// References the second element in the data array. T& y; /// References the third element in the data array. T& z; /// References the fourth element in the data array. T& w; private: using Vector<4, T>::underlying_data; }; #include "vector.inl" /** * Represents a 2-dimensional Vector of ints. */ using Vector2I = Vector2<int>; /** * Represents a 3-dimensional Vector of ints. */ using Vector3I = Vector3<int>; /** * Represents a 4-dimensional Vector of ints. */ using Vector4I = Vector4<int>; /** * Represents a 2-dimensional Vector of ints. */ using Vector2F = Vector2<float>; /** * Represents a 3-dimensional Vector of floats. */ using Vector3F = Vector3<float>; /** * Represents a 4-dimensional Vector of floats. */ using Vector4F = Vector4<float>; #endif
33.692913
143
0.67099
Harrand
4f5c3023213f415f908d09fa80964d974b471659
7,522
cpp
C++
src/size.cpp
nstrayer/lobstr
df3b36eea420d8735c67e1d038c33d9f5bd9cd2d
[ "MIT" ]
null
null
null
src/size.cpp
nstrayer/lobstr
df3b36eea420d8735c67e1d038c33d9f5bd9cd2d
[ "MIT" ]
null
null
null
src/size.cpp
nstrayer/lobstr
df3b36eea420d8735c67e1d038c33d9f5bd9cd2d
[ "MIT" ]
null
null
null
#include <cpp11/environment.hpp> #include <cpp11/doubles.hpp> #include <cpp11/list.hpp> #include <Rversion.h> #include <set> [[cpp11::register]] double v_size(double n, int element_size) { if (n == 0) return 0; double vec_size = std::max(sizeof(SEXP), sizeof(double)); double elements_per_byte = vec_size / element_size; double n_bytes = ceil(n / elements_per_byte); // Rcout << n << " elements, each of " << elements_per_byte << " = " << // n_bytes << "\n"; double size = 0; // Big vectors always allocated in 8 byte chunks if (n_bytes > 16) size = n_bytes * 8; // For small vectors, round to sizes allocated in small vector pool else if (n_bytes > 8) size = 128; else if (n_bytes > 6) size = 64; else if (n_bytes > 4) size = 48; else if (n_bytes > 2) size = 32; else if (n_bytes > 1) size = 16; else if (n_bytes > 0) size = 8; // Size is pointer to struct + struct size return size; } bool is_namespace(cpp11::environment env) { return Rf_findVarInFrame3(env, Rf_install(".__NAMESPACE__."), FALSE) != R_UnboundValue; } // R equivalent // https://github.com/wch/r-source/blob/master/src/library/utils/src/size.c#L41 double obj_size_tree(SEXP x, cpp11::environment base_env, int sizeof_node, int sizeof_vector, std::set<SEXP>& seen, int depth) { // NILSXP is a singleton, so occupies no space. Similarly SPECIAL and // BUILTIN are fixed and unchanging if (TYPEOF(x) == NILSXP || TYPEOF(x) == SPECIALSXP || TYPEOF(x) == BUILTINSXP) return 0; // Don't count objects that we've seen before if (!seen.insert(x).second) return 0; // Rcout << "\n" << std::string(depth * 2, ' '); // Rprintf("type: %s", Rf_type2char(TYPEOF(x))); // Use sizeof(SEXPREC) and sizeof(VECTOR_SEXPREC) computed in R. // CHARSXP are treated as vectors for this purpose double size = (Rf_isVector(x) || TYPEOF(x) == CHARSXP) ? sizeof_vector : sizeof_node; #if defined(R_VERSION) && R_VERSION >= R_Version(3, 5, 0) // Handle ALTREP objects if (ALTREP(x)) { SEXP klass = ALTREP_CLASS(x); SEXP classname = CAR(ATTRIB(klass)); size += 3 * sizeof(SEXP); size += obj_size_tree(klass, base_env, sizeof_node, sizeof_vector, seen, depth + 1); if (classname == Rf_install("deferred_string")) { // Deferred string ALTREP uses an pairlist, but stores data in the CDR SEXP data1 = R_altrep_data1(x); size += obj_size_tree(CAR(data1), base_env, sizeof_node, sizeof_vector, seen, depth + 1); size += obj_size_tree(CDR(data1), base_env, sizeof_node, sizeof_vector, seen, depth + 1); } else { size += obj_size_tree(R_altrep_data1(x), base_env, sizeof_node, sizeof_vector, seen, depth + 1); } size += obj_size_tree(R_altrep_data2(x), base_env, sizeof_node, sizeof_vector, seen, depth + 1); return size; } #endif // CHARSXPs have fake attributes if (TYPEOF(x) != CHARSXP ) size += obj_size_tree(ATTRIB(x), base_env, sizeof_node, sizeof_vector, seen, depth + 1); switch (TYPEOF(x)) { // Vectors ------------------------------------------------------------------- // See details in v_size() // Simple vectors case LGLSXP: case INTSXP: size += v_size(XLENGTH(x), sizeof(int)); break; case REALSXP: size += v_size(XLENGTH(x), sizeof(double)); break; case CPLXSXP: size += v_size(XLENGTH(x), sizeof(Rcomplex)); break; case RAWSXP: size += v_size(XLENGTH(x), 1); break; // Strings case STRSXP: size += v_size(XLENGTH(x), sizeof(SEXP)); for (R_xlen_t i = 0; i < XLENGTH(x); i++) { size += obj_size_tree(STRING_ELT(x, i), base_env, sizeof_node, sizeof_vector, seen, depth + 1); } break; case CHARSXP: size += v_size(LENGTH(x) + 1, 1); break; // Generic vectors case VECSXP: case EXPRSXP: case WEAKREFSXP: size += v_size(XLENGTH(x), sizeof(SEXP)); for (R_xlen_t i = 0; i < XLENGTH(x); ++i) { size += obj_size_tree(VECTOR_ELT(x, i), base_env, sizeof_node, sizeof_vector, seen, depth + 1); } break; // Nodes --------------------------------------------------------------------- // https://github.com/wch/r-source/blob/master/src/include/Rinternals.h#L237-L249 // All have enough space for three SEXP pointers // Linked lists case DOTSXP: case LISTSXP: case LANGSXP: if (x == R_MissingArg) // Needed for DOTSXP break; for(SEXP cons = x; cons != R_NilValue; cons = CDR(cons)) { if (cons != x) size += sizeof_node; size += obj_size_tree(TAG(cons), base_env, sizeof_node, sizeof_vector, seen, depth + 1); size += obj_size_tree(CAR(cons), base_env, sizeof_node, sizeof_vector, seen, depth + 1); } break; case BCODESXP: size += obj_size_tree(TAG(x), base_env, sizeof_node, sizeof_vector, seen, depth + 1); size += obj_size_tree(CAR(x), base_env, sizeof_node, sizeof_vector, seen, depth + 1); size += obj_size_tree(CDR(x), base_env, sizeof_node, sizeof_vector, seen, depth + 1); break; // Environments case ENVSXP: if (x == R_BaseEnv || x == R_GlobalEnv || x == R_EmptyEnv || x == base_env || is_namespace(x)) return 0; size += obj_size_tree(FRAME(x), base_env, sizeof_node, sizeof_vector, seen, depth + 1); size += obj_size_tree(ENCLOS(x), base_env, sizeof_node, sizeof_vector, seen, depth + 1); size += obj_size_tree(HASHTAB(x), base_env, sizeof_node, sizeof_vector, seen, depth + 1); break; // Functions case CLOSXP: size += obj_size_tree(FORMALS(x), base_env, sizeof_node, sizeof_vector, seen, depth + 1); // BODY is either an expression or byte code size += obj_size_tree(BODY(x), base_env, sizeof_node, sizeof_vector, seen, depth + 1); size += obj_size_tree(CLOENV(x), base_env, sizeof_node, sizeof_vector, seen, depth + 1); break; case PROMSXP: size += obj_size_tree(PRVALUE(x), base_env, sizeof_node, sizeof_vector, seen, depth + 1); size += obj_size_tree(PRCODE(x), base_env, sizeof_node, sizeof_vector, seen, depth + 1); size += obj_size_tree(PRENV(x), base_env, sizeof_node, sizeof_vector, seen, depth + 1); break; case EXTPTRSXP: size += sizeof(void *); // the actual pointer size += obj_size_tree(EXTPTR_PROT(x), base_env, sizeof_node, sizeof_vector, seen, depth + 1); size += obj_size_tree(EXTPTR_TAG(x), base_env, sizeof_node, sizeof_vector, seen, depth + 1); break; case S4SXP: size += obj_size_tree(TAG(x), base_env, sizeof_node, sizeof_vector, seen, depth + 1); break; case SYMSXP: break; default: cpp11::stop("Can't compute size of %s", Rf_type2char(TYPEOF(x))); } // Rprintf("type: %-10s size: %6.0f\n", Rf_type2char(TYPEOF(x)), size); return size; } [[cpp11::register]] double obj_size_(cpp11::list objects, cpp11::environment base_env, int sizeof_node, int sizeof_vector) { std::set<SEXP> seen; double size = 0; int n = objects.size(); for (int i = 0; i < n; ++i) { size += obj_size_tree(objects[i], base_env, sizeof_node, sizeof_vector, seen, 0); } return size; } [[cpp11::register]] cpp11::doubles obj_csize_(cpp11::list objects, cpp11::environment base_env, int sizeof_node, int sizeof_vector) { std::set<SEXP> seen; int n = objects.size(); cpp11::writable::doubles out(n); for (int i = 0; i < n; ++i) { out[i] = out[i] + obj_size_tree(objects[i], base_env, sizeof_node, sizeof_vector, seen, 0); } return out; }
33.431111
113
0.635469
nstrayer
4f5c8ae0c1a1052e426b99bd39e7e7266899ea52
97,258
cpp
C++
Plugins/org.mitk.lancet.nodeeditor/src/internal/NodeEditor.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
null
null
null
Plugins/org.mitk.lancet.nodeeditor/src/internal/NodeEditor.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2021-12-22T10:19:02.000Z
2021-12-22T10:19:02.000Z
Plugins/org.mitk.lancet.nodeeditor/src/internal/NodeEditor.cpp
zhaomengxiao/MITK_lancet
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
null
null
null
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ /*============================================================= Below are Headers for the Node Editor plugin ==============================================================*/ #include <sstream> #include <cmath> // Blueberry #include <berryISelectionService.h> #include <berryIWorkbenchWindow.h> // Qmitk #include "NodeEditor.h" // Qt #include <QDoubleSpinBox> #include <QPushButton> // mitk image #include "basic.h" #include "mitkImagePixelReadAccessor.h" #include "mitkImagePixelWriteAccessor.h" #include "mitkNodePredicateAnd.h" #include "mitkNodePredicateDataType.h" #include "mitkNodePredicateNot.h" #include "mitkNodePredicateOr.h" #include "mitkNodePredicateProperty.h" #include "mitkSurfaceOperation.h" #include "physioModelFactory.h" #include "vtkPlaneSource.h" #include "vtkSphereSource.h" #include <QComboBox> #include <itkBSplineInterpolateImageFunction.h> #include <itkResampleImageFilter.h> #include <mitkApplyTransformMatrixOperation.h> #include <mitkBoundingShapeCropper.h> #include <mitkImage.h> #include <mitkInteractionConst.h> #include <mitkPadImageFilter.h> #include <mitkPointOperation.h> #include <mitkPointSet.h> #include <mitkPointSetShapeProperty.h> #include <mitkRotationOperation.h> #include <mitkSurface.h> #include <mitkSurfaceToImageFilter.h> #include <mitkVector.h> #include <vtkClipPolyData.h> #include <vtkImageStencil.h> #include <vtkLandmarkTransform.h> #include <vtkMatrix4x4.h> #include <vtkPlane.h> #include <vtkSTLReader.h> #include <vtkPolyLine.h> #include "drrGenerator.h" #include <drr.h> #include <drrsidonjacobsraytracing.h> #include <eigen3/Eigen/Eigen> #include <mitkPadImageFilter.h> #include <nodebinder.h> #include <surfaceregistraion.h> // registration header #include "volumeRegistrator.h" #include <twoprojectionregistration.h> #include <setuptcpcalibrator.h> /*============================================================= Above are Headers for the Node Editor plugin ==============================================================*/ /*============================================================= Below are Headers for DRR testing ==============================================================*/ #include "itkImage.h" // #include "itkImageFileReader.h" #include "itkCenteredEuler3DTransform.h" #include "itkImageFileWriter.h" #include "itkImageRegionIteratorWithIndex.h" #include "itkNearestNeighborInterpolateImageFunction.h" #include "itkResampleImageFilter.h" #include "itkRescaleIntensityImageFilter.h" //--- #include "itkRayCastInterpolateImageFunction.h" #include "mitkImageCast.h" #include <boost/numeric/conversion/bounds.hpp> #include <vtkImageData.h> #include <vtkNew.h> #include <vtkPointData.h> #include <vtkPolyData.h> #include <iostream> inline void NodeEditor::DrrCtImageChanged(QmitkSingleNodeSelectionWidget::NodeList /*nodes*/) { m_DrrCtImageDataNode = m_Controls.drrCtImageSingleNodeSelectionWidget->GetSelectedNode(); } inline void NodeEditor::NewDrrCtImageChanged(QmitkSingleNodeSelectionWidget::NodeList /*nodes*/) { m_NewDrrCtImageDataNode = m_Controls.newDrrCtImageSingleNodeSelectionWidget->GetSelectedNode(); } inline void NodeEditor::RegistrationCtImageChanged(QmitkSingleNodeSelectionWidget::NodeList /*nodes*/) { m_RegistrationCtImageDataNode = m_Controls.registrationCtSingleNodeSelectionWidget->GetSelectedNode(); } inline void NodeEditor::InputDrrImageChanged_1(QmitkSingleNodeSelectionWidget::NodeList /*nodes*/) { m_InputDrrImageDataNode_1 = m_Controls.registrationDrr1SingleNodeSelectionWidget->GetSelectedNode(); } inline void NodeEditor::InputDrrImageChanged_2(QmitkSingleNodeSelectionWidget::NodeList /*nodes*/) { m_InputDrrImageDataNode_2 = m_Controls.registrationDrr2SingleNodeSelectionWidget->GetSelectedNode(); } inline void NodeEditor::InputImageToCropChanged(QmitkSingleNodeSelectionWidget::NodeList /*nodes*/) { m_InputImageToCropDataNode = m_Controls.widget_CropImage->GetSelectedNode(); } inline void NodeEditor::InputSurfaceChanged(QmitkSingleNodeSelectionWidget::NodeList /*nodes*/) { m_InputSurfaceDataNode = m_Controls.widget_Poly->GetSelectedNode(); } void NodeEditor::RawCtImageChanged(QmitkSingleNodeSelectionWidget::NodeList /*nodes*/) { m_RawCtImageDataNode = m_Controls.rawCtImageSingleNodeSelectionWidget->GetSelectedNode(); } void NodeEditor::EvaluationPointsChanged(QmitkSingleNodeSelectionWidget::NodeList /*nodes*/) { m_EvaluationPointsDataNode = m_Controls.evaluationPointsSingleNodeSelectionWidget->GetSelectedNode(); } void NodeEditor::NewRegistrationCtChanged(QmitkSingleNodeSelectionWidget::NodeList /*nodes*/) { m_NewRegistrationCtDataNode = m_Controls.newRegistrationCtSingleNodeSelectionWidget->GetSelectedNode(); } void NodeEditor::RegDrr1Changed(QmitkSingleNodeSelectionWidget::NodeList /*nodes*/) { m_RegDrr1DataNode = m_Controls.regDrr1SingleNodeSelectionWidget->GetSelectedNode(); } void NodeEditor::RegDrr2Changed(QmitkSingleNodeSelectionWidget::NodeList /*nodes*/) { m_RegDrr2DataNode = m_Controls.regDrr2SingleNodeSelectionWidget->GetSelectedNode(); } void NodeEditor::EvaluateRegistration() { auto image_original_ct = dynamic_cast<mitk::Image *>(m_RawCtImageDataNode->GetData()); auto pointset_register_points = dynamic_cast<mitk::PointSet *>(m_EvaluationPointsDataNode->GetData()); auto pointset_real_points = mitk::PointSet::New(); for (unsigned n = 0; n < pointset_register_points->GetSize(); n++) { pointset_real_points->InsertPoint(pointset_register_points->GetPoint(n)); } mitk::Point3D ct_center = image_original_ct->GetGeometry()->GetCenter(); double x_axis[3] = {1, 0, 0}; double y_axis[3] = {0, 1, 0}; double z_axis[3] = {0, 0, 1}; mitk::Vector3D axis_z{z_axis}; mitk::Vector3D axis_y{y_axis}; mitk::Vector3D axis_x{x_axis}; mitk::Point3D rotateCenter{ct_center}; double rotation_x_real = (m_Controls.sampleRotationXLineEdit->text()).toDouble(); double rotation_y_real = (m_Controls.sampleRotationYLineEdit->text()).toDouble(); double rotation_z_real = (m_Controls.sampleRotationZLineEdit->text()).toDouble(); double translation_x_real = (m_Controls.sampleTranslationXLineEdit->text()).toDouble(); double translation_y_real = (m_Controls.sampleTranslationYLineEdit->text()).toDouble(); double translation_z_real = (m_Controls.sampleTranslationZLineEdit->text()).toDouble(); // ZYX double rotation_x_register = (m_Controls.registrationRotationXLineEdit->text()).toDouble(); double rotation_y_register = (m_Controls.registrationRotationYLineEdit->text()).toDouble(); double rotation_z_register = (m_Controls.registrationRotationZLineEdit->text()).toDouble(); double translation_x_register = (m_Controls.registrationTranslationXLineEdit->text()).toDouble(); double translation_y_register = (m_Controls.registrationTranslationYLineEdit->text()).toDouble(); double translation_z_register = (m_Controls.registrationTranslationZLineEdit->text()).toDouble(); // ZYX auto *rotate_operation_real_z = new mitk::RotationOperation(mitk::OpROTATE, rotateCenter, axis_z, rotation_z_real); pointset_real_points->GetGeometry()->ExecuteOperation(rotate_operation_real_z); auto *rotate_operation_real_y = new mitk::RotationOperation(mitk::OpROTATE, rotateCenter, axis_y, rotation_y_real); pointset_real_points->GetGeometry()->ExecuteOperation(rotate_operation_real_y); auto *rotate_operation_real_x = new mitk::RotationOperation(mitk::OpROTATE, rotateCenter, axis_x, rotation_x_real); pointset_real_points->GetGeometry()->ExecuteOperation(rotate_operation_real_x); delete rotate_operation_real_z; delete rotate_operation_real_y; delete rotate_operation_real_x; auto *rotate_operation_register_z = new mitk::RotationOperation(mitk::OpROTATE, rotateCenter, axis_z, rotation_z_register); pointset_register_points->GetGeometry()->ExecuteOperation(rotate_operation_register_z); auto *rotate_operation_register_y = new mitk::RotationOperation(mitk::OpROTATE, rotateCenter, axis_y, rotation_y_register); pointset_register_points->GetGeometry()->ExecuteOperation(rotate_operation_register_y); auto *rotate_operation_register_x = new mitk::RotationOperation(mitk::OpROTATE, rotateCenter, axis_x, rotation_x_register); pointset_register_points->GetGeometry()->ExecuteOperation(rotate_operation_register_x); delete rotate_operation_register_z; delete rotate_operation_register_y; delete rotate_operation_register_x; double direction_real[3] = {translation_x_real, translation_y_real, translation_z_real}; mitk::Point3D translation_dir_real{direction_real}; auto *translation_real = new mitk::PointOperation(mitk::OpMOVE, 0, translation_dir_real, 0); pointset_real_points->GetGeometry()->ExecuteOperation(translation_real); delete translation_real; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); double direction_register[3] = {translation_x_register, translation_y_register, translation_z_register}; mitk::Point3D translation_dir_register{direction_register}; auto *translation_register = new mitk::PointOperation(mitk::OpMOVE, 0, translation_dir_register, 0); pointset_register_points->GetGeometry()->ExecuteOperation(translation_register); delete translation_register; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); for (unsigned n = 0; n < pointset_register_points->GetSize(); n++) { mitk::Point3D points_register = pointset_register_points->GetPoint(n); mitk::Point3D point_real = pointset_real_points->GetPoint(n); double p1[3]{points_register[0], points_register[1], points_register[2]}; double p2[3]{point_real[0], point_real[1], point_real[2]}; double distance = lancetAlgorithm::DistanceOfTwoPoints(p1, p2); m_Controls.evaluationTextBrowser->append("Deviation of point " + QString::number(n) + " is " + QString::number(distance)); } } void NodeEditor::ConvertPolyDataToImage() { auto imageToCrop = dynamic_cast<mitk::Image *>(m_InputImageToCropDataNode->GetData()); auto objectSurface = dynamic_cast<mitk::Surface *>(m_InputSurfaceDataNode->GetData()); // imageToCrop->GetPixelType() mitk::Point3D imageCenter = imageToCrop->GetGeometry()->GetCenter(); mitk::Point3D surfaceCenter = objectSurface->GetGeometry()->GetOrigin(); double direction[3]{ surfaceCenter[0] - imageCenter[0], surfaceCenter[1] - imageCenter[1], surfaceCenter[2] - imageCenter[2]}; TranslateImage(direction, imageToCrop); mitk::Image::Pointer convertedImage = mitk::Image::New(); // stencil mitk::SurfaceToImageFilter::Pointer surfaceToImageFilter = mitk::SurfaceToImageFilter::New(); surfaceToImageFilter->SetImage(imageToCrop); surfaceToImageFilter->SetInput(objectSurface); surfaceToImageFilter->SetReverseStencil(true); surfaceToImageFilter->SetBackgroundValue(1000.0); // surfaceToImageFilter->SetMakeOutputBinary(true); surfaceToImageFilter->Update(); // boundingBox auto boundingBox = mitk::GeometryData::New(); // InitializeWithSurfaceGeometry auto boundingGeometry = mitk::Geometry3D::New(); auto geometry = objectSurface->GetGeometry(); boundingGeometry->SetBounds(geometry->GetBounds()); boundingGeometry->SetOrigin(geometry->GetOrigin()); boundingGeometry->SetSpacing(geometry->GetSpacing()); boundingGeometry->SetIndexToWorldTransform(geometry->GetIndexToWorldTransform()->Clone()); boundingGeometry->Modified(); boundingBox->SetGeometry(boundingGeometry); auto cutter = mitk::BoundingShapeCropper::New(); cutter->SetGeometry(boundingBox); cutter->SetInput(surfaceToImageFilter->GetOutput()); cutter->Update(); convertedImage = cutter->GetOutput()->Clone(); QString renameSuffix = "_converted"; QString outputFilename = m_Controls.drrOutputFilenameLineEdit->text(); auto existingNode = GetDataStorage()->GetNamedNode((outputFilename).toLocal8Bit().data()); auto newNode = mitk::DataNode::New(); // in case the output name already exists if (existingNode == nullptr) { newNode->SetName(outputFilename.toLocal8Bit().data()); } else { newNode->SetName(outputFilename.append(renameSuffix).toLocal8Bit().data()); m_Controls.drrOutputFilenameLineEdit->setText(outputFilename); } // add new node newNode->SetData(convertedImage); GetDataStorage()->Add(newNode); } void NodeEditor::PolyDataToImageWithWhiteBackGround() { // auto imageToCrop = dynamic_cast<mitk::Image *>(m_InputImageToCropDataNode->GetData()); auto objectSurface = dynamic_cast<mitk::Surface *>(m_InputSurfaceDataNode->GetData()); vtkNew<vtkImageData> whiteImage; double imageBounds[6]{0}; double imageSpacing[3]{1, 1, 1}; whiteImage->SetSpacing(imageSpacing); auto geometry = objectSurface->GetGeometry(); auto surfaceBounds = geometry->GetBounds(); for (int n = 0; n < 6; n++) { imageBounds[n] = surfaceBounds[n]; } int dim[3]; for (int i = 0; i < 3; i++) { dim[i] = static_cast<int>(ceil((imageBounds[i * 2 + 1] - imageBounds[i * 2]) / imageSpacing[i])); } whiteImage->SetDimensions(dim); whiteImage->SetExtent(0, dim[0] - 1, 0, dim[1] - 1, 0, dim[2] - 1); double origin[3]; origin[0] = imageBounds[0] + imageSpacing[0] / 2; origin[1] = imageBounds[2] + imageSpacing[1] / 2; origin[2] = imageBounds[4] + imageSpacing[2] / 2; whiteImage->SetOrigin(origin); whiteImage->AllocateScalars(VTK_SHORT, 1); // fill the image with foreground voxels: short inval = 1024; short outval = 0; vtkIdType count = whiteImage->GetNumberOfPoints(); for (vtkIdType i = 0; i < count; ++i) { whiteImage->GetPointData()->GetScalars()->SetTuple1(i, inval); } auto imageToCrop = mitk::Image::New(); imageToCrop->Initialize(whiteImage); imageToCrop->SetVolume(whiteImage->GetScalarPointer()); // imageToCrop->GetPixelType() // mitk::Point3D imageCenter = imageToCrop->GetGeometry()->GetCenter(); // mitk::Point3D surfaceCenter = objectSurface->GetGeometry()->GetOrigin(); // double direction[3]{ // surfaceCenter[0] - imageCenter[0], surfaceCenter[1] - imageCenter[1], surfaceCenter[2] - imageCenter[2]}; // TranslateImage(direction, imageToCrop); // mitk::Image::Pointer convertedImage = mitk::Image::New(); // stencil mitk::SurfaceToImageFilter::Pointer surfaceToImageFilter = mitk::SurfaceToImageFilter::New(); surfaceToImageFilter->SetImage(imageToCrop); surfaceToImageFilter->SetInput(objectSurface); surfaceToImageFilter->SetReverseStencil(false); // surfaceToImageFilter->SetMakeOutputBinary(true); surfaceToImageFilter->Update(); // // boundingBox // auto boundingBox = mitk::GeometryData::New(); // // InitializeWithSurfaceGeometry // auto boundingGeometry = mitk::Geometry3D::New(); // auto geometry = objectSurface->GetGeometry(); // boundingGeometry->SetBounds(geometry->GetBounds()); // boundingGeometry->SetOrigin(geometry->GetOrigin()); // boundingGeometry->SetSpacing(geometry->GetSpacing()); // boundingGeometry->SetIndexToWorldTransform(geometry->GetIndexToWorldTransform()->Clone()); // boundingGeometry->Modified(); // boundingBox->SetGeometry(boundingGeometry); // // auto cutter = mitk::BoundingShapeCropper::New(); // cutter->SetGeometry(boundingBox); // cutter->SetInput(surfaceToImageFilter->GetOutput()); // cutter->Update(); // convertedImage = cutter->GetOutput()->Clone(); QString renameSuffix = "_converted"; QString outputFilename = m_Controls.drrOutputFilenameLineEdit->text(); auto existingNode = GetDataStorage()->GetNamedNode((outputFilename).toLocal8Bit().data()); auto newNode = mitk::DataNode::New(); // in case the output name already exists if (existingNode == nullptr) { newNode->SetName(outputFilename.toLocal8Bit().data()); } else { newNode->SetName(outputFilename.append(renameSuffix).toLocal8Bit().data()); m_Controls.drrOutputFilenameLineEdit->setText(outputFilename); } // add new node newNode->SetData(surfaceToImageFilter->GetOutput()); GetDataStorage()->Add(newNode); }; void NodeEditor::GenerateWhiteImage() { auto objectSurface = dynamic_cast<mitk::Surface *>(m_InputSurfaceDataNode->GetData()); vtkNew<vtkImageData> whiteImage; double imageBounds[6]{0}; double imageSpacing[3]{1, 1, 1}; whiteImage->SetSpacing(imageSpacing); auto geometry = objectSurface->GetGeometry(); auto surfaceBounds = geometry->GetBounds(); for (int n = 0; n < 6; n++) { imageBounds[n] = surfaceBounds[n]; } int dim[3]; for (int i = 0; i < 3; i++) { dim[i] = static_cast<int>(ceil((imageBounds[i * 2 + 1] - imageBounds[i * 2]) / imageSpacing[i])); } whiteImage->SetDimensions(dim); whiteImage->SetExtent(0, dim[0] - 1, 0, dim[1] - 1, 0, dim[2] - 1); double origin[3]; origin[0] = imageBounds[0] + imageSpacing[0] / 2; origin[1] = imageBounds[2] + imageSpacing[1] / 2; origin[2] = imageBounds[4] + imageSpacing[2] / 2; whiteImage->SetOrigin(origin); whiteImage->AllocateScalars(VTK_SHORT, 1); // fill the image with foreground voxels: short insideValue = 1024; short outsideValue = 0; vtkIdType count = whiteImage->GetNumberOfPoints(); for (vtkIdType i = 0; i < count; ++i) { whiteImage->GetPointData()->GetScalars()->SetTuple1(i, insideValue); } auto imageToCrop = mitk::Image::New(); imageToCrop->Initialize(whiteImage); imageToCrop->SetVolume(whiteImage->GetScalarPointer()); // add a new node for the white image auto newNode = mitk::DataNode::New(); newNode->SetName("White Image"); newNode->SetData(imageToCrop); GetDataStorage()->Add(newNode); } void NodeEditor::PolyDataToImageData() { auto imageToCrop = dynamic_cast<mitk::Image *>(m_InputImageToCropDataNode->GetData()); auto objectSurface = dynamic_cast<mitk::Surface *>(m_InputSurfaceDataNode->GetData()); mitk::Image::Pointer convertedImage = mitk::Image::New(); // stencil mitk::SurfaceToImageFilter::Pointer surfaceToImageFilter = mitk::SurfaceToImageFilter::New(); surfaceToImageFilter->SetImage(imageToCrop); surfaceToImageFilter->SetInput(objectSurface); surfaceToImageFilter->SetReverseStencil(false); surfaceToImageFilter->Update(); convertedImage = surfaceToImageFilter->GetOutput(); auto newNode = mitk::DataNode::New(); newNode->SetName("Generated CT image"); // add new node newNode->SetData(convertedImage); GetDataStorage()->Add(newNode); } void NodeEditor::SetUiDefault() { m_Controls.gantryRotationLineEdit->setText("0.0"); m_Controls.sampleTranslationXLineEdit->setText("0.0"); m_Controls.sampleTranslationYLineEdit->setText("0.0"); m_Controls.sampleTranslationZLineEdit->setText("0.0"); m_Controls.sampleRotationXLineEdit->setText("0"); m_Controls.sampleRotationYLineEdit->setText("0.0"); m_Controls.sampleRotationZLineEdit->setText("0.0"); m_Controls.isocenterOffsetXLineEdit->setText("0.0"); m_Controls.isocenterOffsetYLineEdit->setText("0.0"); m_Controls.isocenterOffsetZLineEdit->setText("0.0"); m_Controls.drrThresholdLineEdit->setText("0.0"); m_Controls.drrSourceToIsoDistanceLineEdit->setText("607"); m_Controls.drrOutputResolutionXLineEdit->setText("1.0"); m_Controls.drrOutputResolutionYLineEdit->setText("1.0"); m_Controls.centralAxisOffsetXLineEdit->setText("0.0"); m_Controls.centralAxisOffsetYLineEdit->setText("0.0"); m_Controls.drrOutputSizeXLineEdit->setText("512"); m_Controls.drrOutputSizeYLineEdit->setText("512"); } void NodeEditor::Drr() { DrrVisualization(); DrrGenerateData(); } void NodeEditor::DrrGenerateData() { if (m_DrrCtImageDataNode == nullptr) { MITK_ERROR << "m_DrrCtImageDataNode null"; return; } // the original input image node will be named "unnamed", and you have to rename it because it really does not have a // name!! // auto image = // GetDataStorage()->GetNamedObject<mitk::Image>((m_Controls.inputFilename->text()).toLocal8Bit().data()); auto image = dynamic_cast<mitk::Image *>(m_DrrCtImageDataNode->GetData()); // auto sliced = dynamic_cast<mitk::SlicedData *>(m_DrrCtImageDataNode->GetData()); // auto image = dynamic_cast<mitk::Image *>(sliced); // the original input image node will be named "unnamed", and you have to rename it because it really does not have a // name!! if (image == nullptr) { MITK_ERROR << "Can't Run DRR: Image null"; m_Controls.drrTextBrowser->append("Error: Input image node is empty"); return; } itk::SmartPointer<DRRSidonJacobsRayTracingFilter> drrFilter = DRRSidonJacobsRayTracingFilter::New(); drrFilter->SetInput(image); double rprojection = (m_Controls.gantryRotationLineEdit->text()).toDouble(); double tx = (m_Controls.sampleTranslationXLineEdit->text()).toDouble(); double ty = (m_Controls.sampleTranslationYLineEdit->text()).toDouble(); double tz = (m_Controls.sampleTranslationZLineEdit->text()).toDouble(); double rx = (m_Controls.sampleRotationXLineEdit->text()).toDouble(); double ry = (m_Controls.sampleRotationYLineEdit->text()).toDouble(); double rz = (m_Controls.sampleRotationZLineEdit->text()).toDouble(); double cx = (m_Controls.isocenterOffsetXLineEdit->text()).toDouble(); double cy = (m_Controls.isocenterOffsetYLineEdit->text()).toDouble(); double cz = (m_Controls.isocenterOffsetZLineEdit->text()).toDouble(); double threshold = (m_Controls.drrThresholdLineEdit->text()).toDouble(); double scd = (m_Controls.drrSourceToIsoDistanceLineEdit->text()).toDouble(); double sx = (m_Controls.drrOutputResolutionXLineEdit->text()).toDouble(); double sy = (m_Controls.drrOutputResolutionYLineEdit->text()).toDouble(); double o2Dx = (m_Controls.centralAxisOffsetXLineEdit->text()).toDouble(); double o2Dy = (m_Controls.centralAxisOffsetYLineEdit->text()).toDouble(); int dx = (m_Controls.drrOutputSizeXLineEdit->text()).toInt(); int dy = (m_Controls.drrOutputSizeYLineEdit->text()).toInt(); drrFilter->Setrprojection(rprojection); drrFilter->SetObjTranslate(tx, ty, tz); drrFilter->SetObjRotate(rx, ry, rz); drrFilter->Setcx(cx); drrFilter->Setcy(cy); drrFilter->Setcz(cz); drrFilter->Setthreshold(threshold); drrFilter->Setscd(scd); drrFilter->Setim_sx(sx); drrFilter->Setim_sy(sy); drrFilter->Setdx(dx); drrFilter->Setdy(dy); drrFilter->Seto2Dx(o2Dx); drrFilter->Seto2Dy(o2Dy); drrFilter->Update(); QString renameSuffix = "_new"; QString outputFilename = m_Controls.drrOutputFilenameLineEdit->text(); auto node = GetDataStorage()->GetNamedNode(outputFilename.toLocal8Bit().data()); auto newnode = mitk::DataNode::New(); // in case the output name already exists if (node == nullptr) { newnode->SetName(outputFilename.toLocal8Bit().data()); } else { newnode->SetName(outputFilename.append(renameSuffix).toLocal8Bit().data()); m_Controls.drrOutputFilenameLineEdit->setText(outputFilename); } // add new node newnode->SetData(drrFilter->GetOutput()); GetDataStorage()->Add(newnode); } void NodeEditor::DrrVisualization() { if (m_DrrCtImageDataNode == nullptr) { MITK_ERROR << "m_DrrCtImageDataNode null"; return; } // the original input image node will be named "unnamed", and you have to rename it because it really does not have a // name!! // auto image = // GetDataStorage()->GetNamedObject<mitk::Image>((m_Controls.inputFilename->text()).toLocal8Bit().data()); auto image = dynamic_cast<mitk::Image *>(m_DrrCtImageDataNode->GetData()); // auto sliced = dynamic_cast<mitk::SlicedData *>(m_DrrCtImageDataNode->GetData()); // auto image = dynamic_cast<mitk::Image *>(sliced); // the original input image node will be named "unnamed", and you have to rename it because it really does not have a // name!! if (image == nullptr) { MITK_ERROR << "Can't Run DRR: Image null"; m_Controls.drrTextBrowser->append("Error: Input image node is empty"); return; } itk::SmartPointer<DRRSidonJacobsRayTracingFilter> drrFilter = DRRSidonJacobsRayTracingFilter::New(); drrFilter->SetInput(image); double rprojection = (m_Controls.gantryRotationLineEdit->text()).toDouble(); double tx = (m_Controls.sampleTranslationXLineEdit->text()).toDouble(); double ty = (m_Controls.sampleTranslationYLineEdit->text()).toDouble(); double tz = (m_Controls.sampleTranslationZLineEdit->text()).toDouble(); double rx = (m_Controls.sampleRotationXLineEdit->text()).toDouble(); double ry = (m_Controls.sampleRotationYLineEdit->text()).toDouble(); double rz = (m_Controls.sampleRotationZLineEdit->text()).toDouble(); double cx = (m_Controls.isocenterOffsetXLineEdit->text()).toDouble(); double cy = (m_Controls.isocenterOffsetYLineEdit->text()).toDouble(); double cz = (m_Controls.isocenterOffsetZLineEdit->text()).toDouble(); double threshold = (m_Controls.drrThresholdLineEdit->text()).toDouble(); double scd = (m_Controls.drrSourceToIsoDistanceLineEdit->text()).toDouble(); double sx = (m_Controls.drrOutputResolutionXLineEdit->text()).toDouble(); double sy = (m_Controls.drrOutputResolutionYLineEdit->text()).toDouble(); double o2Dx = (m_Controls.centralAxisOffsetXLineEdit->text()).toDouble(); double o2Dy = (m_Controls.centralAxisOffsetYLineEdit->text()).toDouble(); int dx = (m_Controls.drrOutputSizeXLineEdit->text()).toInt(); int dy = (m_Controls.drrOutputSizeYLineEdit->text()).toInt(); drrFilter->Setrprojection(rprojection); drrFilter->SetObjTranslate(tx, ty, tz); drrFilter->SetObjRotate(rx, ry, rz); drrFilter->Setcx(cx); drrFilter->Setcy(cy); drrFilter->Setcz(cz); drrFilter->Setthreshold(threshold); drrFilter->Setscd(scd); drrFilter->Setim_sx(sx); drrFilter->Setim_sy(sy); drrFilter->Setdx(dx); drrFilter->Setdy(dy); drrFilter->Seto2Dx(o2Dx); drrFilter->Seto2Dy(o2Dy); drrFilter->Update(); QString renameSuffix = "_new"; QString outputFilename = m_Controls.drrOutputFilenameLineEdit->text(); auto node = GetDataStorage()->GetNamedNode(outputFilename.toLocal8Bit().data()); auto newnode = mitk::DataNode::New(); // in case the output name already exists if (node == nullptr) { newnode->SetName(outputFilename.toLocal8Bit().data()); } else { newnode->SetName(outputFilename.append(renameSuffix).toLocal8Bit().data()); m_Controls.drrOutputFilenameLineEdit->setText(outputFilename); } // add new node for DRR geometry visualization mitk::Image::Pointer image_trans = drrFilter->GetOutput(); mitk::Point3D c_k = m_DrrCtImageDataNode->GetData()->GetGeometry()->GetCenter(); double c_v[3]{c_k[0], c_k[1], c_k[2]}; // rotate 90 degrees to fit the DRR geometry double x_axis[3]{1, 0, 0}; double isoc[3]{0, 0, -scd}; RotateImage(isoc, x_axis, -90, image_trans); // move the center of the image to the isocenter in the sample coordinates double p[3]{c_v[0] + cx, c_v[1] + cy, c_v[2] + cy + scd}; // translation vector // mitk::Point3D direciton{p}; TranslateImage(p, image_trans); double isocw[3]{c_v[0] + cx, c_v[1] + cy, c_v[2] + cz}; m_Controls.isocenterXLineEdit->setText(QString::number(isocw[0])); m_Controls.isocenterYLineEdit->setText(QString::number(isocw[1])); m_Controls.isocenterZLineEdit->setText(QString::number(isocw[2])); // move the image by some -y for better visualization double p_1[3]{0, scd, 0}; TranslateImage(p_1, image_trans); // gantry rotation offset double z_axis[3]{0, 0, 1}; RotateImage(isocw, z_axis, rprojection, image_trans); // mitk::RenderingManager::GetInstance()->RequestUpdateAll(); auto geo_node = mitk::DataNode::New(); QString geo_Suffix = "_visual"; geo_node->SetName(outputFilename.append(geo_Suffix).toLocal8Bit().data()); geo_node->SetData(image_trans); GetDataStorage()->Add(geo_node); if (m_Controls.generateMovedCtCheckBox->isChecked()) { // add a node that contains the moved CT image itk::Image<short, 3>::Pointer m_movedCTimage; mitk::Image::Pointer image_tmp; mitk::CastToItkImage(image, m_movedCTimage); mitk::CastToMitkImage(m_movedCTimage, image_tmp); double Z_axis[3]{0, 0, 1}; RotateImage(isocw, Z_axis, rz, image_tmp); double Y_axis[3]{0, 1, 0}; RotateImage(isocw, Y_axis, ry, image_tmp); double X_axis[3]{1, 0, 0}; RotateImage(isocw, X_axis, rz, image_tmp); double p_tmp[3]{tx, ty, tz}; TranslateImage(p_tmp, image_tmp); auto movedCT_node = mitk::DataNode::New(); QString movedCT_Suffix = "_sample"; movedCT_node->SetName(outputFilename.append(movedCT_Suffix).toLocal8Bit().data()); movedCT_node->SetData(image_tmp); GetDataStorage()->Add(movedCT_node); } c_v[0] = (c_v[0] + cx) + scd * sin(rprojection * 3.1415926 / 180); c_v[1] = (c_v[1] + cy) - scd * cos(rprojection * 3.1415926 / 180); c_v[2] = c_v[2] + cz; // double xsourcew[3]{c_v[0] + cx, c_v[1] + cy - scd, c_v[2] + cz}; m_Controls.raySourceXLineEdit->setText(QString::number(c_v[0])); m_Controls.raySourceYLineEdit->setText(QString::number(c_v[1])); m_Controls.raySourceZLineEdit->setText(QString::number(c_v[2])); if (m_Controls.generateRaySourceCheckBox->isChecked()) { mitk::Point3D point3D_raySource; point3D_raySource[0] = c_v[0]; point3D_raySource[1] = c_v[1]; point3D_raySource[2] = c_v[2]; mitk::Point3D point3D_isocenter; point3D_isocenter[0] = isocw[0]; point3D_isocenter[1] = isocw[1]; point3D_isocenter[2] = isocw[2]; auto pointSet_raySource = mitk::PointSet::New(); pointSet_raySource->InsertPoint(point3D_raySource); pointSet_raySource->InsertPoint(point3D_isocenter); auto raySourceDataNode = mitk::DataNode::New(); QString movedCT_Suffix = "_raySource"; raySourceDataNode->SetName((outputFilename + movedCT_Suffix).toLocal8Bit().data()); raySourceDataNode->SetData(pointSet_raySource); GetDataStorage()->Add(raySourceDataNode); } } void NodeEditor::V1DrrGenerateData() // this method incorporates the MITK coordinate system which can be regarded as the // NDI coordinate system later { if (m_NewDrrCtImageDataNode == nullptr) { MITK_ERROR << "m_NewDrrCtImageDataNode null"; return; } //-------------Below: Get the size and spacing of the input image----------- auto image = dynamic_cast<mitk::Image *>(m_NewDrrCtImageDataNode->GetData()); typedef itk::Image<float, 3> TempImageType; TempImageType::Pointer image_tmp; mitk::CastToItkImage(image, image_tmp); const typename TempImageType::SpacingType spacing_temp = image_tmp->GetSpacing(); typedef typename TempImageType::RegionType TempRegionType; typename TempRegionType region = image_tmp->GetBufferedRegion(); typename TempRegionType::SizeType size_temp = region.GetSize(); int dx = (m_Controls.imagerPixelNumXLineEdit->text()).toInt(); int dy = (m_Controls.imagerPixelNumYLineEdit->text()).toInt(); double sx = (m_Controls.imagerPixelSizeXLineEdit->text()).toDouble(); double sy = (m_Controls.imagerPixelSizeYLineEdit->text()).toDouble(); //-------------Above: Get the size and spacing of the input image----------- //-------------Below: Construct the Affine transform between coordinate systems: MITK scene, CT volume, c-arm imager, //c-arm internal CT volume------------------------- // Axes transform from "MITK frame" to "imager frame" auto transMitk2Imager = vtkSmartPointer<vtkTransform>::New(); vtkSmartPointer<vtkMatrix4x4> matrixMitk2Imager = vtkSmartPointer<vtkMatrix4x4>::New(); transMitk2Imager->Identity(); transMitk2Imager->PostMultiply(); transMitk2Imager->RotateZ(m_Controls.imagerRzLineEdit->text().toDouble()); transMitk2Imager->RotateY(m_Controls.imagerRyLineEdit->text().toDouble()); transMitk2Imager->RotateX(m_Controls.imagerRxLineEdit->text().toDouble()); double translationMitk2Imager[3] = {m_Controls.imagerTxLineEdit->text().toDouble(), m_Controls.imagerTyLineEdit->text().toDouble(), m_Controls.imagerTzLineEdit->text().toDouble()}; transMitk2Imager->Translate(translationMitk2Imager); transMitk2Imager->Update(); transMitk2Imager->GetMatrix(matrixMitk2Imager); // Axes transform from "MITK frame" to "CT image frame" auto transMitk2Ct = vtkSmartPointer<vtkTransform>::New(); vtkSmartPointer<vtkMatrix4x4> matrixMitk2Ct = vtkSmartPointer<vtkMatrix4x4>::New(); // auto transCt2Mitk = vtkSmartPointer<vtkTransform>::New(); vtkSmartPointer<vtkMatrix4x4> matrixCt2Mitk = vtkSmartPointer<vtkMatrix4x4>::New(); transMitk2Ct->Identity(); transMitk2Ct->PostMultiply(); transMitk2Ct->RotateZ(m_Controls.ctRzLineEdit->text().toDouble()); transMitk2Ct->RotateY(m_Controls.ctRyLineEdit->text().toDouble()); transMitk2Ct->RotateX(m_Controls.ctRxLineEdit->text().toDouble()); double translationMitk2Ct[3] = {m_Controls.ctTxLineEdit->text().toDouble(), m_Controls.ctTyLineEdit->text().toDouble(), m_Controls.ctTzLineEdit->text().toDouble()}; transMitk2Ct->Translate(translationMitk2Ct); transMitk2Ct->Update(); transMitk2Ct->GetMatrix(matrixMitk2Ct); transMitk2Ct->GetInverse(matrixCt2Mitk); // Axes transform from "imager frame" to "original C-arm internal CT image frame" auto transImager2InternalCt = vtkSmartPointer<vtkTransform>::New(); vtkSmartPointer<vtkMatrix4x4> matrixImager2InternalCt = vtkSmartPointer<vtkMatrix4x4>::New(); transImager2InternalCt->Identity(); transImager2InternalCt->PostMultiply(); transImager2InternalCt->RotateX(-90); double translationImager2InternalCt[3] = { m_Controls.sourceXLineEdit->text().toDouble() - spacing_temp[0] * double(size_temp[0]) / 2.0, m_Controls.sourceYLineEdit->text().toDouble() - spacing_temp[2] * double(size_temp[2]) / 2.0, spacing_temp[1] * double(size_temp[1]) / 2.0}; transImager2InternalCt->Translate(translationImager2InternalCt); transImager2InternalCt->Update(); transImager2InternalCt->GetMatrix(matrixImager2InternalCt); // Axes transform from "original C-arm internal CT image frame" to "CT image frame" auto transCt2InternalCt = vtkSmartPointer<vtkTransform>::New(); vtkSmartPointer<vtkMatrix4x4> matrixInternalCt2Ct = vtkSmartPointer<vtkMatrix4x4>::New(); transCt2InternalCt->Identity(); transCt2InternalCt->PostMultiply(); transCt2InternalCt->Concatenate(matrixImager2InternalCt); transCt2InternalCt->Concatenate(matrixMitk2Imager); transCt2InternalCt->Concatenate(matrixCt2Mitk); transCt2InternalCt->Update(); transCt2InternalCt->GetInverse(matrixInternalCt2Ct); //-------------Above: Construct the Affine transform between coordinate systems------------------------- //----------Below: Extract ZYX angles from the affine transform matrix---------- double rx, ry, rz; double piParameter = 180 / 3.1415926; if (matrixInternalCt2Ct->GetElement(0, 2) < 1) { if (matrixInternalCt2Ct->GetElement(0, 2) > -1) { ry = asin(matrixInternalCt2Ct->GetElement(0, 2)); rx = atan2(-matrixInternalCt2Ct->GetElement(1, 2), matrixInternalCt2Ct->GetElement(2, 2)); rz = atan2(-matrixInternalCt2Ct->GetElement(0, 1), matrixInternalCt2Ct->GetElement(0, 0)); } else { ry = -3.1415926 / 2; rx = -atan2(matrixInternalCt2Ct->GetElement(1, 0), matrixInternalCt2Ct->GetElement(1, 1)); rz = 0; } } else { ry = 3.1415926 / 2; rx = atan2(matrixInternalCt2Ct->GetElement(1, 0), matrixInternalCt2Ct->GetElement(1, 1)); rz = 0; } rx = rx * piParameter; ry = ry * piParameter; rz = rz * piParameter; //----------Above: Extract ZYX angles from the affine transform matrix---------- //----------Below: Construct a filter and feed in the image and the parameters generated above-------------- itk::SmartPointer<DRRSidonJacobsRayTracingFilter> drrFilter = DRRSidonJacobsRayTracingFilter::New(); drrFilter->SetInput(image); // The volume center of the internal Ct volume under the internal Ct coordinate system Eigen::Vector4d internalCtCenter{spacing_temp[0] * double(size_temp[0]) / 2.0, spacing_temp[1] * double(size_temp[1]) / 2.0, spacing_temp[2] * double(size_temp[2]) / 2.0, 1}; // The center of the real Ct volume under the real Ct coordinate system Eigen::Vector4d ctCenter{spacing_temp[0] * double(size_temp[0]) / 2.0, spacing_temp[1] * double(size_temp[1]) / 2.0, spacing_temp[2] * double(size_temp[2]) / 2.0, 1}; Eigen::Matrix4d eigenMatrixInternalCt2Ct{matrixInternalCt2Ct->GetData()}; eigenMatrixInternalCt2Ct.transposeInPlace(); // The volume center of the real Ct volume under the internal Ct coordinate system Eigen::Vector4d targetCenterPoint = eigenMatrixInternalCt2Ct * ctCenter; double tx = targetCenterPoint[0] - internalCtCenter[0]; double ty = targetCenterPoint[1] - internalCtCenter[1]; double tz = targetCenterPoint[2] - internalCtCenter[2]; double cx = 0; double cy = 0; double cz = 0; double threshold = (m_Controls.newDrrthresLineEdit->text()).toDouble(); double scd = (m_Controls.sourceZLineEdit->text()).toDouble(); double o2Dx = -((m_Controls.sourceXLineEdit->text()).toDouble() - sx * (dx - 1) / 2); double o2Dy = -((m_Controls.sourceYLineEdit->text()).toDouble() - sy * (dy - 1) / 2); drrFilter->Setrprojection(0); drrFilter->SetObjTranslate(tx, ty, tz); drrFilter->SetObjRotate(rx, ry, rz); drrFilter->Setcx(cx); drrFilter->Setcy(cy); drrFilter->Setcz(cz); drrFilter->Setthreshold(threshold); drrFilter->Setscd(scd); drrFilter->Setim_sx(sx); drrFilter->Setim_sy(sy); drrFilter->Setdx(dx); drrFilter->Setdy(dy); drrFilter->Seto2Dx(o2Dx); drrFilter->Seto2Dy(o2Dy); drrFilter->Update(); //-----------Below: add the datanode containing the DRR-------------- QString renameSuffix = "_new"; QString outputFilename = m_Controls.drrNameLineEdit->text(); auto node = GetDataStorage()->GetNamedNode(outputFilename.toLocal8Bit().data()); auto newnode = mitk::DataNode::New(); // in case the output name already exists if (node == nullptr) { newnode->SetName(outputFilename.toLocal8Bit().data()); } else { newnode->SetName(outputFilename.append(renameSuffix).toLocal8Bit().data()); m_Controls.drrNameLineEdit->setText(outputFilename); } // add new node newnode->SetData(drrFilter->GetOutput()); GetDataStorage()->Add(newnode); //-----------Above: add the datanode containing the DRR-------------- //-----------------Below: generate a image on the virtual monitor screen------------------ QString pseudoImageSuffix = "_visual"; outputFilename = m_Controls.drrNameLineEdit->text(); auto visualnewnode = mitk::DataNode::New(); // in case the output name already exists visualnewnode->SetName(outputFilename.append(pseudoImageSuffix).toLocal8Bit().data()); // add new node auto pseudoImage = drrFilter->GetOutput()->Clone(); mitk::Point3D pseudoImageOrigin; pseudoImageOrigin[0] = 300 - sx * (dx - 1) / 2; pseudoImageOrigin[1] = 300 - sy * (dy - 1) / 2; pseudoImageOrigin[2] = 1; pseudoImage->GetGeometry()->SetOrigin(pseudoImageOrigin); visualnewnode->SetData(pseudoImage); GetDataStorage()->Add(visualnewnode); //-----------------Above: generate a image on the virtual monitor screen------------------ //------------Below: Print out the real parameters used for DRR generation ---------------- m_Controls.newDrrTextBrowser->append("rprojection: " + QString::number(0)); m_Controls.newDrrTextBrowser->append("tx: " + QString::number(tx)); m_Controls.newDrrTextBrowser->append("ty: " + QString::number(ty)); m_Controls.newDrrTextBrowser->append("tz: " + QString::number(tz)); m_Controls.newDrrTextBrowser->append("rx: " + QString::number(rx)); m_Controls.newDrrTextBrowser->append("ry: " + QString::number(ry)); m_Controls.newDrrTextBrowser->append("rz: " + QString::number(rz)); m_Controls.newDrrTextBrowser->append("scd: " + QString::number(scd)); m_Controls.newDrrTextBrowser->append("sx: " + QString::number(sx)); m_Controls.newDrrTextBrowser->append("sy: " + QString::number(sy)); m_Controls.newDrrTextBrowser->append("dx: " + QString::number(dx)); m_Controls.newDrrTextBrowser->append("dy: " + QString::number(dy)); m_Controls.newDrrTextBrowser->append("o2Dx: " + QString::number(o2Dx)); m_Controls.newDrrTextBrowser->append("o2Dy: " + QString::number(o2Dy)); //------------Above: Print out the real parameters used for DRR generation ---------------- // double m_ArrayMatrixWorldToImager[16] // { // 1,0,0,2, // 0,1,0,3, // 0,0,1,4, // 0,0,0,5 // }; // Eigen::Matrix4d matrixTest{m_ArrayMatrixWorldToImager}; // m_Controls.newDrrTextBrowser->append("Element 8" + QString::number(matrixTest(7))); // itk::SmartPointer<SetUpTcpCalibrator> tcpCorrector = SetUpTcpCalibrator::New(); // double pointD[3]{8, 9, 10}; // double pointP[3]{1, 4, 4}; // double pointQ[3]{0.292993,4.707106,4}; // double pointS[3]{1, 4, 3}; // double arrayMatrix[16]{1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 2, 3, 1}; // // tcpCorrector->calibrateGooseSaw(arrayMatrix,pointD,pointP,pointQ,pointS); // m_Controls.newDrrTextBrowser->append("Rx: " + QString::number(tcpCorrector->GetRx())); // m_Controls.newDrrTextBrowser->append("Ry: " + QString::number(tcpCorrector->GetRy())); // m_Controls.newDrrTextBrowser->append("Rz: " + QString::number(tcpCorrector->GetRz())); // m_Controls.newDrrTextBrowser->append("Tx: " + QString::number(tcpCorrector->GetTx())); // m_Controls.newDrrTextBrowser->append("Ty: " + QString::number(tcpCorrector->GetTy())); // m_Controls.newDrrTextBrowser->append("Tz: " + QString::number(tcpCorrector->GetTz())); // // Eigen::Vector3d X(0.204007,-0.177015,0.494579); // Eigen::Vector3d x(0.356809,0.0814958,0.930616); // // m_Controls.newDrrTextBrowser->append("The initial result is " + QString::number(X.dot(x))); // m_Controls.newDrrTextBrowser->append("The fixed result is " + QString::number(X(0)*x(0)+X(1)*x(1)+X(2)*x(2))); } void NodeEditor::V2DrrGenerateData() { if (m_NewDrrCtImageDataNode == nullptr) { MITK_ERROR << "m_NewDrrCtImageDataNode null"; return; } //-------------Below: Get the size and spacing of the input image----------- auto image = dynamic_cast<mitk::Image *>(m_NewDrrCtImageDataNode->GetData()); typedef itk::Image<float, 3> TempImageType; TempImageType::Pointer image_tmp; mitk::CastToItkImage(image, image_tmp); const typename TempImageType::SpacingType spacing_temp = image_tmp->GetSpacing(); typedef typename TempImageType::RegionType TempRegionType; typename TempRegionType region = image_tmp->GetBufferedRegion(); typename TempRegionType::SizeType size_temp = region.GetSize(); int dx = (m_Controls.imagerPixelNumXLineEdit->text()).toInt(); int dy = (m_Controls.imagerPixelNumYLineEdit->text()).toInt(); double sx = (m_Controls.imagerPixelSizeXLineEdit->text()).toDouble(); double sy = (m_Controls.imagerPixelSizeYLineEdit->text()).toDouble(); //-------------Above: Get the size and spacing of the input image----------- //-------------Below: Construct the Affine transform between coordinate systems: MITK scene, CT volume, c-arm imager, // and c-arm internal CT volume------------------------- // Axes transform from "MITK frame" to "imager frame" auto transMitk2Imager = vtkSmartPointer<vtkTransform>::New(); vtkSmartPointer<vtkMatrix4x4> matrixMitk2Imager = vtkSmartPointer<vtkMatrix4x4>::New(); transMitk2Imager->Identity(); transMitk2Imager->PostMultiply(); transMitk2Imager->RotateZ(m_Controls.imagerRzLineEdit->text().toDouble()); transMitk2Imager->RotateY(m_Controls.imagerRyLineEdit->text().toDouble()); transMitk2Imager->RotateX(m_Controls.imagerRxLineEdit->text().toDouble()); double translationMitk2Imager[3] = {m_Controls.imagerTxLineEdit->text().toDouble(), m_Controls.imagerTyLineEdit->text().toDouble(), m_Controls.imagerTzLineEdit->text().toDouble()}; transMitk2Imager->Translate(translationMitk2Imager); transMitk2Imager->Update(); transMitk2Imager->GetMatrix(matrixMitk2Imager); // Axes transform from "MITK frame" to "CT image frame" auto transMitk2Ct = vtkSmartPointer<vtkTransform>::New(); vtkSmartPointer<vtkMatrix4x4> matrixMitk2Ct = vtkSmartPointer<vtkMatrix4x4>::New(); // auto transCt2Mitk = vtkSmartPointer<vtkTransform>::New(); vtkSmartPointer<vtkMatrix4x4> matrixCt2Mitk = vtkSmartPointer<vtkMatrix4x4>::New(); transMitk2Ct->Identity(); transMitk2Ct->PostMultiply(); transMitk2Ct->RotateZ(m_Controls.ctRzLineEdit->text().toDouble()); transMitk2Ct->RotateY(m_Controls.ctRyLineEdit->text().toDouble()); transMitk2Ct->RotateX(m_Controls.ctRxLineEdit->text().toDouble()); double translationMitk2Ct[3] = {m_Controls.ctTxLineEdit->text().toDouble(), m_Controls.ctTyLineEdit->text().toDouble(), m_Controls.ctTzLineEdit->text().toDouble()}; transMitk2Ct->Translate(translationMitk2Ct); transMitk2Ct->Update(); transMitk2Ct->GetMatrix(matrixMitk2Ct); //----------Below: Construct a filter and feed in the image and the parameters generated above-------------- itk::SmartPointer<DrrGenerator> drrFilter = DrrGenerator::New(); // The volume center of the internal Ct volume under the internal Ct coordinate system // Eigen::Vector4d internalCtCenter{spacing_temp[0] * double(size_temp[0]) / 2.0, // spacing_temp[1] * double(size_temp[1]) / 2.0, // spacing_temp[2] * double(size_temp[2]) / 2.0, // 1}; // The center of the real Ct volume under the real Ct coordinate system // Eigen::Vector4d ctCenter{spacing_temp[0] * double(size_temp[0]) / 2.0, // spacing_temp[1] * double(size_temp[1]) / 2.0, // spacing_temp[2] * double(size_temp[2]) / 2.0, // 1}; // Eigen::Matrix4d eigenMatrixInternalCt2Ct{matrixInternalCt2Ct->GetData()}; // eigenMatrixInternalCt2Ct.transposeInPlace(); // // The volume center of the real Ct volume under the internal Ct coordinate system // Eigen::Vector4d targetCenterPoint = eigenMatrixInternalCt2Ct * ctCenter; // // double tx = targetCenterPoint[0] - internalCtCenter[0]; // double ty = targetCenterPoint[1] - internalCtCenter[1]; // double tz = targetCenterPoint[2] - internalCtCenter[2]; double threshold = (m_Controls.newDrrthresLineEdit->text()).toDouble(); // double scd = (m_Controls.sourceZLineEdit->text()).toDouble(); // double o2Dx = -((m_Controls.sourceXLineEdit->text()).toDouble() - sx * (dx - 1) / 2); // double o2Dy = -((m_Controls.sourceYLineEdit->text()).toDouble() - sy * (dy - 1) / 2); // drrFilter->Setrprojection(0); // drrFilter->SetObjTranslate(tx, ty, tz); // drrFilter->SetObjRotate(rx, ry, rz); // drrFilter->Setcx(0); // drrFilter->Setcy(0); // drrFilter->Setcz(0); drrFilter->SetInput(image); drrFilter->SetArrayMatrixWorldToCt(matrixMitk2Ct->GetData()); drrFilter->SetArrayMatrixWorldToImager(matrixMitk2Imager->GetData()); drrFilter->Setthreshold(threshold); double arraySource[3]{m_Controls.sourceXLineEdit->text().toDouble(), m_Controls.sourceYLineEdit->text().toDouble(), m_Controls.sourceZLineEdit->text().toDouble()}; drrFilter->SetRaySource(arraySource); // source xyz drrFilter->Setim_sx(sx); drrFilter->Setim_sy(sy); drrFilter->Setdx(dx); drrFilter->Setdy(dy); // drrFilter->Seto2Dx(o2Dx); // drrFilter->Seto2Dy(o2Dy); drrFilter->Update(); //-----------Below: add the datanode containing the DRR-------------- QString renameSuffix = "_new"; QString outputFilename = m_Controls.drrNameLineEdit->text(); auto node = GetDataStorage()->GetNamedNode(outputFilename.toLocal8Bit().data()); auto newnode = mitk::DataNode::New(); // in case the output name already exists if (node == nullptr) { newnode->SetName(outputFilename.toLocal8Bit().data()); } else { newnode->SetName(outputFilename.append(renameSuffix).toLocal8Bit().data()); m_Controls.drrNameLineEdit->setText(outputFilename); } // add new node newnode->SetData(drrFilter->GetOutput()); GetDataStorage()->Add(newnode); //-----------Above: add the datanode containing the DRR-------------- //-----------------Below: generate a image on the virtual monitor screen------------------ QString pseudoImageSuffix = "_visual"; outputFilename = m_Controls.drrNameLineEdit->text(); auto visualnewnode = mitk::DataNode::New(); // in case the output name already exists visualnewnode->SetName(outputFilename.append(pseudoImageSuffix).toLocal8Bit().data()); // add new node auto pseudoImage = drrFilter->GetOutput()->Clone(); mitk::Point3D pseudoImageOrigin; pseudoImageOrigin[0] = 300 - sx * (dx - 1) / 2; pseudoImageOrigin[1] = 300 - sy * (dy - 1) / 2; pseudoImageOrigin[2] = 1; pseudoImage->GetGeometry()->SetOrigin(pseudoImageOrigin); visualnewnode->SetData(pseudoImage); GetDataStorage()->Add(visualnewnode); } void NodeEditor::VisualizeDrrProjectionModel() { //-------------Below: Visualize the real CT volume in MITK scene coordinate system ----------- auto image = dynamic_cast<mitk::Image *>(m_NewDrrCtImageDataNode->GetData())->Clone(); auto origin = image->GetGeometry()->GetOrigin(); double rz = m_Controls.ctRzLineEdit->text().toDouble(); double ry = m_Controls.ctRyLineEdit->text().toDouble(); double rx = m_Controls.ctRxLineEdit->text().toDouble(); double tz = m_Controls.ctTzLineEdit->text().toDouble(); double ty = m_Controls.ctTyLineEdit->text().toDouble(); double tx = m_Controls.ctTxLineEdit->text().toDouble(); double translate2MITKorigin[3] = {-origin[0], -origin[1], -origin[2]}; TranslateImage(translate2MITKorigin, image); double center[3] = {0, 0, 0}; double z_axis[3]{0, 0, 1}; RotateImage(center, z_axis, rz, image); double y_axis[3]{0, 1, 0}; RotateImage(center, y_axis, ry, image); double x_axis[3]{1, 0, 0}; RotateImage(center, x_axis, rx, image); double MITKorigin2CT[3] = {tx, ty, tz}; TranslateImage(MITKorigin2CT, image); QString renameSuffix = "_CT_visual"; QString outputFilename = m_Controls.drrNameLineEdit->text(); auto newnode = mitk::DataNode::New(); newnode->SetName(outputFilename.append(renameSuffix).toLocal8Bit().data()); // add new node newnode->SetData(image); GetDataStorage()->Add(newnode); //-------------Above: Visualize the real CT volume in MITK scene coordinate system ----------- //------------Below: Visualize the ray source--------------- double source_x = m_Controls.sourceXLineEdit->text().toDouble(); double source_y = m_Controls.sourceYLineEdit->text().toDouble(); double source_z = m_Controls.sourceZLineEdit->text().toDouble(); auto transMitk2Imager = vtkSmartPointer<vtkTransform>::New(); vtkSmartPointer<vtkMatrix4x4> matrixMitk2Imager = vtkSmartPointer<vtkMatrix4x4>::New(); transMitk2Imager->Identity(); transMitk2Imager->PostMultiply(); transMitk2Imager->RotateZ(m_Controls.imagerRzLineEdit->text().toDouble()); transMitk2Imager->RotateY(m_Controls.imagerRyLineEdit->text().toDouble()); transMitk2Imager->RotateX(m_Controls.imagerRxLineEdit->text().toDouble()); double translationMitk2Imager[3] = {m_Controls.imagerTxLineEdit->text().toDouble(), m_Controls.imagerTyLineEdit->text().toDouble(), m_Controls.imagerTzLineEdit->text().toDouble()}; transMitk2Imager->Translate(translationMitk2Imager); transMitk2Imager->GetMatrix(matrixMitk2Imager); Eigen::Matrix4d eigenMatrixMitk2Imager{matrixMitk2Imager->GetData()}; eigenMatrixMitk2Imager.transposeInPlace(); Eigen::Vector4d sourcePointUnderImager{source_x, source_y, source_z, 1}; Eigen::Vector4d sourcePointUnderMitk = eigenMatrixMitk2Imager * sourcePointUnderImager; auto raySource = vtkSmartPointer<vtkSphereSource>::New(); raySource->SetCenter(sourcePointUnderMitk[0], sourcePointUnderMitk[1], sourcePointUnderMitk[2]); raySource->SetRadius(17); raySource->Update(); auto raySourceNode = mitk::DataNode::New(); auto raySourceSurface = mitk::Surface::New(); raySourceSurface->SetVtkPolyData(raySource->GetOutput()); raySourceNode->SetData(raySourceSurface); outputFilename = m_Controls.drrNameLineEdit->text(); raySourceNode->SetName(outputFilename.append("_raySource_visual").toLocal8Bit().data()); raySourceNode->SetColor(1.0, 0.0, 0.0); raySourceNode->SetVisibility(true); raySourceNode->SetOpacity(0.7); GetDataStorage()->Add(raySourceNode); //------------Above: Visualize the ray source--------------- //-----------Below: Visualize the imager plane---------- int dx = (m_Controls.imagerPixelNumXLineEdit->text()).toInt(); int dy = (m_Controls.imagerPixelNumYLineEdit->text()).toInt(); double sx = (m_Controls.imagerPixelSizeXLineEdit->text()).toDouble(); double sy = (m_Controls.imagerPixelSizeYLineEdit->text()).toDouble(); Eigen::Vector4d imagerOriginUnderImager{0, 0, 0, 1}; Eigen::Vector4d imagerP1UnderImager{sx * double(dx - 1), 0, 0, 1}; Eigen::Vector4d imagerP2UnderImager{0, sy * double(dy - 1), 0, 1}; Eigen::Vector4d imagerOriginUnderMitk = eigenMatrixMitk2Imager * imagerOriginUnderImager; Eigen::Vector4d imagerP1UnderMitk = eigenMatrixMitk2Imager * imagerP1UnderImager; Eigen::Vector4d imagerP2UnderMitk = eigenMatrixMitk2Imager * imagerP2UnderImager; auto imagerPlaneSource = vtkSmartPointer<vtkPlaneSource>::New(); imagerPlaneSource->SetOrigin(imagerOriginUnderMitk[0], imagerOriginUnderMitk[1], imagerOriginUnderMitk[2]); imagerPlaneSource->SetPoint1(imagerP1UnderMitk[0], imagerP1UnderMitk[1], imagerP1UnderMitk[2]); imagerPlaneSource->SetPoint2(imagerP2UnderMitk[0], imagerP2UnderMitk[1], imagerP2UnderMitk[2]); imagerPlaneSource->Update(); auto imagerPlaneNode = mitk::DataNode::New(); auto imagerPlaneSurface = mitk::Surface::New(); imagerPlaneSurface->SetVtkPolyData(imagerPlaneSource->GetOutput()); imagerPlaneNode->SetData(imagerPlaneSurface); outputFilename = m_Controls.drrNameLineEdit->text(); imagerPlaneNode->SetName(outputFilename.append("_imagerPlane_visual").toLocal8Bit().data()); imagerPlaneNode->SetColor(0.0, 0.0, 1); imagerPlaneNode->SetVisibility(true); imagerPlaneNode->SetOpacity(0.5); GetDataStorage()->Add(imagerPlaneNode); //-----------Above: Visualize the imager plane---------- } void NodeEditor::TranslateImage(double direction[3], mitk::Image *mitkImage) { if (mitkImage != nullptr) { mitk::Point3D translationDir{direction}; auto *pointOperation = new mitk::PointOperation(mitk::OpMOVE, 0, translationDir, 0); // execute the Operation // here no undo is stored, because the movement-steps aren't interesting. // only the start and the end is of interest to be stored for undo. mitkImage->GetGeometry()->ExecuteOperation(pointOperation); delete pointOperation; // updateStemCenter(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void NodeEditor::RotateImage(double center[3], double axis[3], double degree, mitk::Image *mitkImage) { if (mitkImage != nullptr) { mitk::Point3D rotateCenter{center}; mitk::Vector3D rotateAxis{axis}; auto *rotateOperation = new mitk::RotationOperation(mitk::OpROTATE, rotateCenter, rotateAxis, degree); // execute the Operation // here no undo is stored, because the movement-steps aren't interesting. // only the start and the end is of interest to be stored for undo. mitkImage->GetGeometry()->ExecuteOperation(rotateOperation); delete rotateOperation; // updateStemCenter(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } /*============================================================= Above is the Code for DRR ==============================================================*/ //-------------------------------- ↓ registration part ↓--------------------------------------- void NodeEditor::Register() { if (m_RegistrationCtImageDataNode == nullptr || m_InputDrrImageDataNode_1 == nullptr || m_InputDrrImageDataNode_2 == nullptr) { MITK_ERROR << "Input nodes are not ready"; return; } auto ctimage = dynamic_cast<mitk::Image *>(m_RegistrationCtImageDataNode->GetData()); auto DRR1 = dynamic_cast<mitk::Image *>(m_InputDrrImageDataNode_1->GetData()); auto DRR2 = dynamic_cast<mitk::Image *>(m_InputDrrImageDataNode_2->GetData()); if (ctimage == nullptr || DRR1 == nullptr || DRR2 == nullptr) { MITK_ERROR << "Can't Run twoProjectionRegistration: Input images are empty"; m_Controls.registerTextBrowser->append("Error: Input image node is empty"); return; } itk::SmartPointer<TwoProjectionRegistration> registrator = TwoProjectionRegistration::New(); registrator->SetswitchOffOptimizer(false); registrator->link_drr1_cast(DRR1); registrator->link_drr2_cast(DRR2); registrator->link_3d_cast(ctimage); double angleDRR1 = (m_Controls.angleDrr1LineEdit->text()).toDouble(); double angleDRR2 = (m_Controls.angleDrr2LineEdit->text()).toDouble(); double tx = (m_Controls.initialTranslationXLineEdit->text()).toDouble(); double ty = (m_Controls.initialTranslationYLineEdit->text()).toDouble(); double tz = (m_Controls.initialTranslationZLineEdit->text()).toDouble(); double cx = (m_Controls.registrationIsoOffsetXLineEdit->text()).toDouble(); double cy = (m_Controls.registrationIsoOffsetYLineEdit->text()).toDouble(); double cz = (m_Controls.registrationIsoOffsetZLineEdit->text()).toDouble(); double rx = (m_Controls.initialRotationXLineEdit->text()).toDouble(); double ry = (m_Controls.initialRotationYLineEdit->text()).toDouble(); double rz = (m_Controls.initialRotationZLineEdit->text()).toDouble(); double threshold = (m_Controls.registrationThresholdLineEdit->text()).toDouble(); double scd = (m_Controls.registrationSourceToIsoDistanceLineEdit->text()).toDouble(); double sx_1 = (m_Controls.drr1ResolutionXLineEdit->text()).toDouble(); double sy_1 = (m_Controls.drr1ResolutionYLineEdit->text()).toDouble(); double sx_2 = (m_Controls.drr2ResolutionXLineEdit->text()).toDouble(); double sy_2 = (m_Controls.drr2ResolutionYLineEdit->text()).toDouble(); double o2Dx_1 = (m_Controls.drr1CentralAxisOffsetXLineEdit->text()).toDouble(); double o2Dy_1 = (m_Controls.drr1CentralAxisOffsetYLineEdit->text()).toDouble(); double o2Dx_2 = (m_Controls.drr2CentralAxisOffsetXLineEdit->text()).toDouble(); double o2Dy_2 = (m_Controls.drr2CentralAxisOffsetYLineEdit->text()).toDouble(); if (sx_1 == 0 || sy_1 || sx_2 == 0 || sy_2 == 0) { std::cout << "FLAG!" << std::endl; } registrator->SetangleDRR1(angleDRR1); registrator->SetangleDRR2(angleDRR2); registrator->Settx(tx); registrator->Setty(ty); registrator->Settz(tz); registrator->Setcx(cx); registrator->Setcy(cy); registrator->Setcz(cz); registrator->Setrx(rx); registrator->Setry(ry); registrator->Setrz(rz); registrator->Setthreshold(threshold); registrator->Setscd(scd); registrator->Setsx_1(sx_1); registrator->Setsy_1(sy_1); registrator->Setsx_2(sx_2); registrator->Setsy_2(sy_2); registrator->Seto2Dx_1(o2Dx_1); registrator->Seto2Dy_1(o2Dy_1); registrator->Seto2Dx_2(o2Dx_2); registrator->Seto2Dy_2(o2Dy_2); registrator->twoprojection_registration(); m_Controls.registrationRotationXLineEdit->setText(QString::number(registrator->GetRX())); m_Controls.registrationRotationYLineEdit->setText(QString::number(registrator->GetRY())); m_Controls.registrationRotationZLineEdit->setText(QString::number(registrator->GetRZ())); m_Controls.registrationTranslationXLineEdit->setText(QString::number(registrator->GetTX())); m_Controls.registrationTranslationYLineEdit->setText(QString::number(registrator->GetTY())); m_Controls.registrationTranslationZLineEdit->setText(QString::number(registrator->GetTZ())); m_Controls.registerTextBrowser->append("The metric is:"); m_Controls.registerTextBrowser->append(QString::number(registrator->Getmetric())); m_Controls.registerTextBrowser->append("(The closer to -1 the better)"); // add a node containing the registration result mitk::Point3D c_v = m_RegistrationCtImageDataNode->GetData()->GetGeometry()->GetCenter(); double isocw[3]{c_v[0] + cx, c_v[1] + cy, c_v[2] + cz}; itk::Image<short, 3>::Pointer m_movedCTimage; mitk::Image::Pointer image_tmp; mitk::CastToItkImage(ctimage, m_movedCTimage); mitk::CastToMitkImage(m_movedCTimage, image_tmp); double Z_axis[3]{0, 0, 1}; RotateImage(isocw, Z_axis, registrator->GetRZ(), image_tmp); double Y_axis[3]{0, 1, 0}; RotateImage(isocw, Y_axis, registrator->GetRY(), image_tmp); double X_axis[3]{1, 0, 0}; RotateImage(isocw, X_axis, registrator->GetRX(), image_tmp); double p_tmp[3]{registrator->GetTX(), registrator->GetTY(), registrator->GetTZ()}; TranslateImage(p_tmp, image_tmp); // QString outputFilename = m_Controls.drrOutputFilenameLineEdit->text(); auto movedCT_node = mitk::DataNode::New(); // QString movedCT_Suffix = "_register"; // movedCT_node->SetName(outputFilename.append(movedCT_Suffix).toLocal8Bit().data()); movedCT_node->SetName("Registered image"); movedCT_node->SetData(image_tmp); GetDataStorage()->Add(movedCT_node); } void NodeEditor::NewRegister() { if (m_NewRegistrationCtDataNode == nullptr || m_RegDrr1DataNode == nullptr || m_RegDrr2DataNode == nullptr) { MITK_ERROR << "Input nodes are not ready"; return; } auto ctimage = dynamic_cast<mitk::Image *>(m_NewRegistrationCtDataNode->GetData()); auto DRR1 = dynamic_cast<mitk::Image *>(m_RegDrr1DataNode->GetData()); auto DRR2 = dynamic_cast<mitk::Image *>(m_RegDrr2DataNode->GetData()); if (ctimage == nullptr || DRR1 == nullptr || DRR2 == nullptr) { MITK_ERROR << "Can't Run twoProjectionRegistration: Input images are empty"; m_Controls.newRegTextBrowser->append("Error: Input image node is empty"); return; } itk::SmartPointer<VolumeRegistrator> registrator = VolumeRegistrator::New(); registrator->link_drr1_cast(DRR1); registrator->link_drr2_cast(DRR2); registrator->link_3d_cast(ctimage); double threshold = (m_Controls.regThresholdLineEdit->text()).toDouble(); double sx_1 = (m_Controls.dr1SpacingXLineEdit->text()).toDouble(); double sy_1 = (m_Controls.dr1SpacingYLineEdit->text()).toDouble(); double sx_2 = (m_Controls.dr2SpacingXLineEdit->text()).toDouble(); double sy_2 = (m_Controls.dr2SpacingYLineEdit->text()).toDouble(); // Axes transform from "MITK frame" to "CT image frame" (world to Ct) auto transMitk2Ct = vtkSmartPointer<vtkTransform>::New(); vtkSmartPointer<vtkMatrix4x4> matrixMitk2Ct = vtkSmartPointer<vtkMatrix4x4>::New(); // auto transCt2Mitk = vtkSmartPointer<vtkTransform>::New(); vtkSmartPointer<vtkMatrix4x4> matrixCt2Mitk = vtkSmartPointer<vtkMatrix4x4>::New(); transMitk2Ct->Identity(); transMitk2Ct->PostMultiply(); transMitk2Ct->RotateZ(m_Controls.regCtRzLineEdit->text().toDouble()); transMitk2Ct->RotateY(m_Controls.regCtRyLineEdit->text().toDouble()); transMitk2Ct->RotateX(m_Controls.regCtRxLineEdit->text().toDouble()); double translationMitk2Ct[3] = {m_Controls.regCtTxLineEdit->text().toDouble(), m_Controls.regCtTyLineEdit->text().toDouble(), m_Controls.regCtTzLineEdit->text().toDouble()}; transMitk2Ct->Translate(translationMitk2Ct); transMitk2Ct->Update(); transMitk2Ct->GetMatrix(matrixMitk2Ct); // Axes transform from "MITK frame" to "imager1 frame" (world to imager1) auto transMitk2Imager1 = vtkSmartPointer<vtkTransform>::New(); vtkSmartPointer<vtkMatrix4x4> matrixMitk2Imager1 = vtkSmartPointer<vtkMatrix4x4>::New(); transMitk2Imager1->Identity(); transMitk2Imager1->PostMultiply(); transMitk2Imager1->RotateZ(m_Controls.imager1RzLineEdit->text().toDouble()); transMitk2Imager1->RotateY(m_Controls.imager1RyLineEdit->text().toDouble()); transMitk2Imager1->RotateX(m_Controls.imager1RxLineEdit->text().toDouble()); double translationMitk2Imager1[3] = {m_Controls.imager1TxLineEdit->text().toDouble(), m_Controls.imager1TyLineEdit->text().toDouble(), m_Controls.imager1TzLineEdit->text().toDouble()}; transMitk2Imager1->Translate(translationMitk2Imager1); transMitk2Imager1->Update(); transMitk2Imager1->GetMatrix(matrixMitk2Imager1); // Axes transform from "MITK frame" to "imager1 frame" (world to imager2) auto transMitk2Imager2 = vtkSmartPointer<vtkTransform>::New(); vtkSmartPointer<vtkMatrix4x4> matrixMitk2Imager2 = vtkSmartPointer<vtkMatrix4x4>::New(); transMitk2Imager2->Identity(); transMitk2Imager2->PostMultiply(); transMitk2Imager2->RotateZ(m_Controls.imager2RzLineEdit->text().toDouble()); transMitk2Imager2->RotateY(m_Controls.imager2RyLineEdit->text().toDouble()); transMitk2Imager2->RotateX(m_Controls.imager2RxLineEdit->text().toDouble()); double translationMitk2Imager2[3] = {m_Controls.imager2TxLineEdit->text().toDouble(), m_Controls.imager2TyLineEdit->text().toDouble(), m_Controls.imager2TzLineEdit->text().toDouble()}; transMitk2Imager2->Translate(translationMitk2Imager2); transMitk2Imager2->Update(); transMitk2Imager2->GetMatrix(matrixMitk2Imager2); // obtain the 2 raySources double arraySource1[3]{m_Controls.source1XLineEdit->text().toDouble(), m_Controls.source1YLineEdit->text().toDouble(), m_Controls.source1ZLineEdit->text().toDouble()}; double arraySource2[3]{m_Controls.source2XLineEdit->text().toDouble(), m_Controls.source2YLineEdit->text().toDouble(), m_Controls.source2ZLineEdit->text().toDouble()}; registrator->SetArrayMatrixWorldToCt(matrixMitk2Ct->GetData()); registrator->SetArrayMatrixWorldToImager1(matrixMitk2Imager1->GetData()); registrator->SetArrayMatrixWorldToImager2(matrixMitk2Imager2->GetData()); registrator->Setthreshold(threshold); registrator->SetRaySource1(arraySource1); registrator->SetRaySource2(arraySource2); registrator->Setsx_1(sx_1); registrator->Setsy_1(sy_1); registrator->Setsx_2(sx_2); registrator->Setsy_2(sy_2); registrator->SetswitchOffOptimizer(false); registrator->registration(); m_Controls.regResultCtTxLineEdit->setText(QString::number(registrator->GetTX())); m_Controls.regResultCtTyLineEdit->setText(QString::number(registrator->GetTY())); m_Controls.regResultCtTzLineEdit->setText(QString::number(registrator->GetTZ())); m_Controls.regResultCtRxLineEdit->setText(QString::number(registrator->GetRX())); m_Controls.regResultCtRyLineEdit->setText(QString::number(registrator->GetRY())); m_Controls.regResultCtRzLineEdit->setText(QString::number(registrator->GetRZ())); m_Controls.newRegTextBrowser->append("The metric is:"); m_Controls.newRegTextBrowser->append(QString::number(registrator->Getmetric())); m_Controls.newRegTextBrowser->append("(The closer to -1 the better)"); } void NodeEditor::Visualize2ProjectionModel() { //-------------Below: Visualize the real CT volume in MITK scene coordinate system ----------- auto image = dynamic_cast<mitk::Image *>(m_NewDrrCtImageDataNode->GetData())->Clone(); auto origin = image->GetGeometry()->GetOrigin(); double rz = m_Controls.regResultCtRzLineEdit->text().toDouble(); double ry = m_Controls.regResultCtRyLineEdit->text().toDouble(); double rx = m_Controls.regResultCtRxLineEdit->text().toDouble(); double tz = m_Controls.regResultCtTzLineEdit->text().toDouble(); double ty = m_Controls.regResultCtTyLineEdit->text().toDouble(); double tx = m_Controls.regResultCtTxLineEdit->text().toDouble(); double translate2MITKorigin[3] = {-origin[0], -origin[1], -origin[2]}; TranslateImage(translate2MITKorigin, image); double center[3] = {0, 0, 0}; double z_axis[3]{0, 0, 1}; RotateImage(center, z_axis, rz, image); double y_axis[3]{0, 1, 0}; RotateImage(center, y_axis, ry, image); double x_axis[3]{1, 0, 0}; RotateImage(center, x_axis, rx, image); double MITKorigin2CT[3] = {tx, ty, tz}; TranslateImage(MITKorigin2CT, image); QString renameSuffix = "_CT_visual"; QString outputFilename = "TwoProjection"; auto newnode = mitk::DataNode::New(); newnode->SetName(outputFilename.append(renameSuffix).toLocal8Bit().data()); // add new node newnode->SetData(image); GetDataStorage()->Add(newnode); //-------------Above: Visualize the real CT volume in MITK scene coordinate system ----------- //------------Below: Visualize the ray source1--------------- double source_x1 = m_Controls.source1XLineEdit->text().toDouble(); double source_y1 = m_Controls.source1YLineEdit->text().toDouble(); double source_z1 = m_Controls.source1ZLineEdit->text().toDouble(); auto transMitk2Imager1 = vtkSmartPointer<vtkTransform>::New(); vtkSmartPointer<vtkMatrix4x4> matrixMitk2Imager1 = vtkSmartPointer<vtkMatrix4x4>::New(); transMitk2Imager1->Identity(); transMitk2Imager1->PostMultiply(); transMitk2Imager1->RotateZ(m_Controls.imager1RzLineEdit->text().toDouble()); transMitk2Imager1->RotateY(m_Controls.imager1RyLineEdit->text().toDouble()); transMitk2Imager1->RotateX(m_Controls.imager1RxLineEdit->text().toDouble()); double translationMitk2Imager1[3] = {m_Controls.imager1TxLineEdit->text().toDouble(), m_Controls.imager1TyLineEdit->text().toDouble(), m_Controls.imager1TzLineEdit->text().toDouble()}; transMitk2Imager1->Translate(translationMitk2Imager1); transMitk2Imager1->GetMatrix(matrixMitk2Imager1); Eigen::Matrix4d eigenMatrixMitk2Imager1{matrixMitk2Imager1->GetData()}; eigenMatrixMitk2Imager1.transposeInPlace(); Eigen::Vector4d sourcePointUnderImager1{source_x1, source_y1, source_z1, 1}; Eigen::Vector4d sourcePointUnderMitk1 = eigenMatrixMitk2Imager1 * sourcePointUnderImager1; auto raySource1 = vtkSmartPointer<vtkSphereSource>::New(); raySource1->SetCenter(sourcePointUnderMitk1[0], sourcePointUnderMitk1[1], sourcePointUnderMitk1[2]); raySource1->SetRadius(17); raySource1->Update(); auto raySourceNode1 = mitk::DataNode::New(); auto raySourceSurface1 = mitk::Surface::New(); raySourceSurface1->SetVtkPolyData(raySource1->GetOutput()); raySourceNode1->SetData(raySourceSurface1); outputFilename = "TwoProjection"; raySourceNode1->SetName(outputFilename.append("_raySource1_visual").toLocal8Bit().data()); raySourceNode1->SetColor(1.0, 0.0, 0.0); raySourceNode1->SetVisibility(true); raySourceNode1->SetOpacity(0.7); GetDataStorage()->Add(raySourceNode1); //------------Above: Visualize the ray source1--------------- //------------Below: Visualize the ray source2--------------- double source_x2 = m_Controls.source2XLineEdit->text().toDouble(); double source_y2 = m_Controls.source2YLineEdit->text().toDouble(); double source_z2 = m_Controls.source2ZLineEdit->text().toDouble(); auto transMitk2Imager2 = vtkSmartPointer<vtkTransform>::New(); vtkSmartPointer<vtkMatrix4x4> matrixMitk2Imager2 = vtkSmartPointer<vtkMatrix4x4>::New(); transMitk2Imager2->Identity(); transMitk2Imager2->PostMultiply(); transMitk2Imager2->RotateZ(m_Controls.imager2RzLineEdit->text().toDouble()); transMitk2Imager2->RotateY(m_Controls.imager2RyLineEdit->text().toDouble()); transMitk2Imager2->RotateX(m_Controls.imager2RxLineEdit->text().toDouble()); double translationMitk2Imager2[3] = {m_Controls.imager2TxLineEdit->text().toDouble(), m_Controls.imager2TyLineEdit->text().toDouble(), m_Controls.imager2TzLineEdit->text().toDouble()}; transMitk2Imager2->Translate(translationMitk2Imager2); transMitk2Imager2->GetMatrix(matrixMitk2Imager2); Eigen::Matrix4d eigenMatrixMitk2Imager2{matrixMitk2Imager2->GetData()}; eigenMatrixMitk2Imager2.transposeInPlace(); Eigen::Vector4d sourcePointUnderImager2{source_x2, source_y2, source_z2, 1}; Eigen::Vector4d sourcePointUnderMitk2 = eigenMatrixMitk2Imager2 * sourcePointUnderImager2; auto raySource2 = vtkSmartPointer<vtkSphereSource>::New(); raySource2->SetCenter(sourcePointUnderMitk2[0], sourcePointUnderMitk2[1], sourcePointUnderMitk2[2]); raySource2->SetRadius(17); raySource2->Update(); auto raySourceNode2 = mitk::DataNode::New(); auto raySourceSurface2 = mitk::Surface::New(); raySourceSurface2->SetVtkPolyData(raySource2->GetOutput()); raySourceNode2->SetData(raySourceSurface2); outputFilename = "TwoProjection"; raySourceNode2->SetName(outputFilename.append("_raySource2_visual").toLocal8Bit().data()); raySourceNode2->SetColor(0.0, 0.0, 1); raySourceNode2->SetVisibility(true); raySourceNode2->SetOpacity(0.7); GetDataStorage()->Add(raySourceNode2); //------------Above: Visualize the ray source2--------------- //-----------Below: Visualize the imager planes---------- int dx = 512; int dy = 512; double sx1 = (m_Controls.dr2SpacingXLineEdit->text()).toDouble(); double sy1 = (m_Controls.dr2SpacingYLineEdit->text()).toDouble(); Eigen::Vector4d imagerOriginUnderImager{0, 0, 0, 1}; Eigen::Vector4d imagerP1UnderImager{sx1 * double(dx - 1), 0, 0, 1}; Eigen::Vector4d imagerP2UnderImager{0, sy1 * double(dy - 1), 0, 1}; Eigen::Vector4d imagerOriginUnderMitk1 = eigenMatrixMitk2Imager1 * imagerOriginUnderImager; Eigen::Vector4d imagerP1UnderMitk1 = eigenMatrixMitk2Imager1 * imagerP1UnderImager; Eigen::Vector4d imagerP2UnderMitk1 = eigenMatrixMitk2Imager1 * imagerP2UnderImager; auto imagerPlaneSource1 = vtkSmartPointer<vtkPlaneSource>::New(); imagerPlaneSource1->SetOrigin(imagerOriginUnderMitk1[0], imagerOriginUnderMitk1[1], imagerOriginUnderMitk1[2]); imagerPlaneSource1->SetPoint1(imagerP1UnderMitk1[0], imagerP1UnderMitk1[1], imagerP1UnderMitk1[2]); imagerPlaneSource1->SetPoint2(imagerP2UnderMitk1[0], imagerP2UnderMitk1[1], imagerP2UnderMitk1[2]); imagerPlaneSource1->Update(); auto imagerPlaneNode1 = mitk::DataNode::New(); auto imagerPlaneSurface1 = mitk::Surface::New(); imagerPlaneSurface1->SetVtkPolyData(imagerPlaneSource1->GetOutput()); imagerPlaneNode1->SetData(imagerPlaneSurface1); outputFilename = "TwoProjection"; imagerPlaneNode1->SetName(outputFilename.append("_imagerPlane1_visual").toLocal8Bit().data()); imagerPlaneNode1->SetColor(1.0, 0.0, 0.0); imagerPlaneNode1->SetVisibility(true); imagerPlaneNode1->SetOpacity(0.5); GetDataStorage()->Add(imagerPlaneNode1); Eigen::Vector4d imagerOriginUnderMitk2 = eigenMatrixMitk2Imager2 * imagerOriginUnderImager; Eigen::Vector4d imagerP1UnderMitk2 = eigenMatrixMitk2Imager2 * imagerP1UnderImager; Eigen::Vector4d imagerP2UnderMitk2 = eigenMatrixMitk2Imager2 * imagerP2UnderImager; auto imagerPlaneSource2 = vtkSmartPointer<vtkPlaneSource>::New(); imagerPlaneSource2->SetOrigin(imagerOriginUnderMitk2[0], imagerOriginUnderMitk2[1], imagerOriginUnderMitk2[2]); imagerPlaneSource2->SetPoint1(imagerP1UnderMitk2[0], imagerP1UnderMitk2[1], imagerP1UnderMitk2[2]); imagerPlaneSource2->SetPoint2(imagerP2UnderMitk2[0], imagerP2UnderMitk2[1], imagerP2UnderMitk2[2]); imagerPlaneSource2->Update(); auto imagerPlaneNode2 = mitk::DataNode::New(); auto imagerPlaneSurface2 = mitk::Surface::New(); imagerPlaneSurface2->SetVtkPolyData(imagerPlaneSource2->GetOutput()); imagerPlaneNode2->SetData(imagerPlaneSurface2); outputFilename = "TwoProjection"; imagerPlaneNode2->SetName(outputFilename.append("_imagerPlane2_visual").toLocal8Bit().data()); imagerPlaneNode2->SetColor(0.0, 0.0, 1.0); imagerPlaneNode2->SetVisibility(true); imagerPlaneNode2->SetOpacity(0.5); GetDataStorage()->Add(imagerPlaneNode2); //-----------Above: Visualize the imager planes---------- } // --------------------Below: test the line intersection function ------------------------- void NodeEditor::GetIntersection() { unsigned int lineNumber = 3; double line0StartX = m_Controls.line0StartXLineEdit->text().toDouble(); double line0StartY = m_Controls.line0StartYLineEdit->text().toDouble(); double line0StartZ = m_Controls.line0StartZLineEdit->text().toDouble(); double line0EndX = m_Controls.line0EndXLineEdit->text().toDouble(); double line0EndY = m_Controls.line0EndYLineEdit->text().toDouble(); double line0EndZ = m_Controls.line0EndZLineEdit->text().toDouble(); double line1StartX = m_Controls.line1StartXLineEdit->text().toDouble(); double line1StartY = m_Controls.line1StartYLineEdit->text().toDouble(); double line1StartZ = m_Controls.line1StartZLineEdit->text().toDouble(); double line1EndX = m_Controls.line1EndXLineEdit->text().toDouble(); double line1EndY = m_Controls.line1EndYLineEdit->text().toDouble(); double line1EndZ = m_Controls.line1EndZLineEdit->text().toDouble(); double line2StartX = m_Controls.line2StartXLineEdit->text().toDouble(); double line2StartY = m_Controls.line2StartYLineEdit->text().toDouble(); double line2StartZ = m_Controls.line2StartZLineEdit->text().toDouble(); double line2EndX = m_Controls.line2EndXLineEdit->text().toDouble(); double line2EndY = m_Controls.line2EndYLineEdit->text().toDouble(); double line2EndZ = m_Controls.line2EndZLineEdit->text().toDouble(); Eigen::VectorXd d(9); d << line0StartX, line0StartY, line0StartZ, line1StartX, line1StartY, line1StartZ, line2StartX, line2StartY, line2StartZ; Eigen::VectorXd d_End(9); d_End << line0EndX, line0EndY, line0EndZ, line1EndX, line1EndY, line1EndZ, line2EndX, line2EndY, line2EndZ; Eigen::VectorXd d_Substraction(9); d_Substraction = d_End - d; Eigen::MatrixXd G(3 * lineNumber, lineNumber + 3); // G.Zero(); for (int i = 0; i < 3 * lineNumber; i = i + 1) { for (int j = 0; j < 3 + lineNumber; j = j + 1) { G(i, j) = 0; if (i % 3 == 0 && j == 0) { G(i, j) = 1; } if (i % 3 == 1 && j == 1) { G(i, j) = 1; } if (i % 3 == 2 && j == 2) { G(i, j) = 1; } if ( j - 2 > 0 ) { for (int q = 0; q < 3; q = q + 1) { G(q + 3 * (j - 3), j) = - d_Substraction[q + 3 * (j - 3)]; } } } } Eigen::VectorXd m(3 + lineNumber); Eigen::MatrixXd G_Transpose(3 * lineNumber, lineNumber + 3); G_Transpose = G.transpose(); m = (G_Transpose * G).inverse() * G_Transpose * d; m_Controls.lineIntersectionTextBrowser->append(QString::number(m[0])); m_Controls.lineIntersectionTextBrowser->append(QString::number(m[1])); m_Controls.lineIntersectionTextBrowser->append(QString::number(m[2])); // visualize the scene // Line 0 double startLine0[3]{line0StartX, line0StartY, line0StartZ}; double endLine0[3]{line0EndX, line0EndY, line0EndZ}; vtkNew<vtkPoints> points_Line0; points_Line0->InsertNextPoint(startLine0); points_Line0->InsertNextPoint(endLine0); vtkNew<vtkPolyLine> polyLine0; polyLine0->GetPointIds()->SetNumberOfIds(2); for (unsigned int i = 0; i < 2; i++) { polyLine0->GetPointIds()->SetId(i, i); } vtkNew<vtkCellArray> cells0; cells0->InsertNextCell(polyLine0); vtkNew<vtkPolyData> polyData0; polyData0->SetPoints(points_Line0); polyData0->SetLines(cells0); auto linesNode0 = mitk::DataNode::New(); auto linesSurface0 = mitk::Surface::New(); linesSurface0->SetVtkPolyData(polyData0); linesNode0->SetData(linesSurface0); linesNode0->SetName("Lines"); linesNode0->SetColor(0.7, 0, 0.0); linesNode0->SetVisibility(true); linesNode0->SetOpacity(0.7); GetDataStorage()->Add(linesNode0); double startLine1[3]{line1StartX, line1StartY, line1StartZ}; double endLine1[3]{line1EndX, line1EndY, line1EndZ}; vtkNew<vtkPoints> points_Line1; points_Line1->InsertNextPoint(startLine1); points_Line1->InsertNextPoint(endLine1); vtkNew<vtkPolyLine> polyLine1; polyLine1->GetPointIds()->SetNumberOfIds(2); for (unsigned int i = 0; i < 2; i++) { polyLine1->GetPointIds()->SetId(i, i); } vtkNew<vtkCellArray> cells1; cells1->InsertNextCell(polyLine1); vtkNew<vtkPolyData> polyData1; polyData1->SetPoints(points_Line1); polyData1->SetLines(cells1); auto linesNode1 = mitk::DataNode::New(); auto linesSurface1 = mitk::Surface::New(); linesSurface1->SetVtkPolyData(polyData1); linesNode1->SetData(linesSurface1); linesNode1->SetName("Lines"); linesNode1->SetColor(0.0, 0.7, 0.0); linesNode1->SetVisibility(true); linesNode1->SetOpacity(0.7); GetDataStorage()->Add(linesNode1); double startLine2[3]{line2StartX, line2StartY, line2StartZ}; double endLine2[3]{line2EndX, line2EndY, line2EndZ}; vtkNew<vtkPoints> points_Line2; points_Line2->InsertNextPoint(startLine2); points_Line2->InsertNextPoint(endLine2); vtkNew<vtkPolyLine> polyLine2; polyLine2->GetPointIds()->SetNumberOfIds(2); for (unsigned int i = 0; i < 2; i++) { polyLine2->GetPointIds()->SetId(i, i); } vtkNew<vtkCellArray> cells2; cells2->InsertNextCell(polyLine2); vtkNew<vtkPolyData> polyData2; polyData2->SetPoints(points_Line2); polyData2->SetLines(cells2); auto linesNode2 = mitk::DataNode::New(); auto linesSurface2 = mitk::Surface::New(); linesSurface2->SetVtkPolyData(polyData2); linesNode2->SetData(linesSurface2); linesNode2->SetName("Lines"); linesNode2->SetColor(0.0, 0, 0.7); linesNode2->SetVisibility(true); linesNode2->SetOpacity(0.7); GetDataStorage()->Add(linesNode2); auto raySource2 = vtkSmartPointer<vtkSphereSource>::New(); raySource2->SetCenter(m[0], m[1], m[2]); raySource2->SetRadius(7); raySource2->Update(); auto raySourceNode2 = mitk::DataNode::New(); auto raySourceSurface2 = mitk::Surface::New(); raySourceSurface2->SetVtkPolyData(raySource2->GetOutput()); raySourceNode2->SetData(raySourceSurface2); raySourceNode2->SetName("Intersection"); raySourceNode2->SetColor(0.5, 0.0, 0.5); raySourceNode2->SetVisibility(true); raySourceNode2->SetOpacity(0.7); GetDataStorage()->Add(raySourceNode2); } // --------------------Above: test the line intersection function ------------------------- void NodeEditor::InitialMetric() { if (m_RegistrationCtImageDataNode == nullptr || m_InputDrrImageDataNode_1 == nullptr || m_InputDrrImageDataNode_2 == nullptr) { MITK_ERROR << "Input nodes are not ready"; return; } auto ctimage = dynamic_cast<mitk::Image *>(m_RegistrationCtImageDataNode->GetData()); auto DRR1 = dynamic_cast<mitk::Image *>(m_InputDrrImageDataNode_1->GetData()); auto DRR2 = dynamic_cast<mitk::Image *>(m_InputDrrImageDataNode_2->GetData()); if (ctimage == nullptr || DRR1 == nullptr || DRR2 == nullptr) { MITK_ERROR << "Can't Run twoProjectionRegistration: Input images are empty"; m_Controls.registerTextBrowser->append("Error: Input image node is empty"); return; } itk::SmartPointer<TwoProjectionRegistration> metricCalculator = TwoProjectionRegistration::New(); metricCalculator->SetswitchOffOptimizer(true); metricCalculator->link_drr1_cast(DRR1); metricCalculator->link_drr2_cast(DRR2); metricCalculator->link_3d_cast(ctimage); double angleDRR1 = (m_Controls.angleDrr1LineEdit->text()).toDouble(); double angleDRR2 = (m_Controls.angleDrr2LineEdit->text()).toDouble(); double tx = (m_Controls.initialTranslationXLineEdit->text()).toDouble(); double ty = (m_Controls.initialTranslationYLineEdit->text()).toDouble(); double tz = (m_Controls.initialTranslationZLineEdit->text()).toDouble(); double cx = (m_Controls.registrationIsoOffsetXLineEdit->text()).toDouble(); double cy = (m_Controls.registrationIsoOffsetYLineEdit->text()).toDouble(); double cz = (m_Controls.registrationIsoOffsetZLineEdit->text()).toDouble(); double rx = (m_Controls.initialRotationXLineEdit->text()).toDouble(); double ry = (m_Controls.initialRotationYLineEdit->text()).toDouble(); double rz = (m_Controls.initialRotationZLineEdit->text()).toDouble(); double threshold = (m_Controls.registrationThresholdLineEdit->text()).toDouble(); double scd = (m_Controls.registrationSourceToIsoDistanceLineEdit->text()).toDouble(); double sx_1 = (m_Controls.drr1ResolutionXLineEdit->text()).toDouble(); double sy_1 = (m_Controls.drr1ResolutionYLineEdit->text()).toDouble(); double sx_2 = (m_Controls.drr2ResolutionXLineEdit->text()).toDouble(); double sy_2 = (m_Controls.drr2ResolutionYLineEdit->text()).toDouble(); double o2Dx_1 = (m_Controls.drr1CentralAxisOffsetXLineEdit->text()).toDouble(); double o2Dy_1 = (m_Controls.drr1CentralAxisOffsetYLineEdit->text()).toDouble(); double o2Dx_2 = (m_Controls.drr2CentralAxisOffsetXLineEdit->text()).toDouble(); double o2Dy_2 = (m_Controls.drr2CentralAxisOffsetYLineEdit->text()).toDouble(); if (sx_1 == 0 || sy_1 || sx_2 == 0 || sy_2 == 0) { std::cout << "FLAG!" << std::endl; } metricCalculator->SetangleDRR1(angleDRR1); metricCalculator->SetangleDRR2(angleDRR2); metricCalculator->Settx(tx); metricCalculator->Setty(ty); metricCalculator->Settz(tz); metricCalculator->Setcx(cx); metricCalculator->Setcy(cy); metricCalculator->Setcz(cz); metricCalculator->Setrx(rx); metricCalculator->Setry(ry); metricCalculator->Setrz(rz); metricCalculator->Setthreshold(threshold); metricCalculator->Setscd(scd); metricCalculator->Setsx_1(sx_1); metricCalculator->Setsy_1(sy_1); metricCalculator->Setsx_2(sx_2); metricCalculator->Setsy_2(sy_2); metricCalculator->Seto2Dx_1(o2Dx_1); metricCalculator->Seto2Dy_1(o2Dy_1); metricCalculator->Seto2Dx_2(o2Dx_2); metricCalculator->Seto2Dy_2(o2Dy_2); metricCalculator->twoprojection_registration(); m_Controls.registerTextBrowser->append("The metric is:"); m_Controls.registerTextBrowser->append(QString::number(metricCalculator->Getmetric())); m_Controls.registerTextBrowser->append("(The closer to -1 the better)"); // add a node containing the registration result mitk::Point3D c_v = m_RegistrationCtImageDataNode->GetData()->GetGeometry()->GetCenter(); double isocw[3]{c_v[0] + cx, c_v[1] + cy, c_v[2] + cz}; itk::Image<short, 3>::Pointer m_movedCTimage; mitk::Image::Pointer image_tmp; mitk::CastToItkImage(ctimage, m_movedCTimage); mitk::CastToMitkImage(m_movedCTimage, image_tmp); double Z_axis[3]{0, 0, 1}; RotateImage(isocw, Z_axis, (m_Controls.initialRotationZLineEdit->text()).toDouble(), image_tmp); double Y_axis[3]{0, 1, 0}; RotateImage(isocw, Y_axis, (m_Controls.initialRotationYLineEdit->text()).toDouble(), image_tmp); double X_axis[3]{1, 0, 0}; RotateImage(isocw, X_axis, (m_Controls.initialRotationXLineEdit->text()).toDouble(), image_tmp); double p_tmp[3]{(m_Controls.initialTranslationXLineEdit->text()).toDouble(), (m_Controls.initialTranslationYLineEdit->text()).toDouble(), (m_Controls.initialTranslationZLineEdit->text()).toDouble()}; TranslateImage(p_tmp, image_tmp); // QString outputFilename = m_Controls.drrOutputFilenameLineEdit->text(); auto movedCT_node = mitk::DataNode::New(); // QString movedCT_Suffix = "_register"; // movedCT_node->SetName(outputFilename.append(movedCT_Suffix).toLocal8Bit().data()); movedCT_node->SetName("Initial image"); movedCT_node->SetData(image_tmp); GetDataStorage()->Add(movedCT_node); } //-------------------------------- ↑ registration part ↑--------------------------------------- // void NodeEditor::SetUpTcpCalibrator(double toolPointA[3], // double toolPointB[3], // double toolPointC[3], // double sawPointD[3], // double sawPlanePointP[3], // double sawPlanePointQ[3], // double sawPlanePointS[3]) // { // Eigen::Vector3d AC(toolPointC[0] - toolPointA[0], toolPointC[1] - toolPointA[1], toolPointC[2] - toolPointA[2]); // double normAC = AC.norm(); // // Eigen::Vector3d AB(toolPointB[0] - toolPointA[0], toolPointB[1] - toolPointA[1], toolPointB[2] - toolPointA[2]); // double normAB = AB.norm(); // // Eigen::Vector3d AD(sawPointD[0] - toolPointA[0], sawPointD[1] - toolPointA[1], sawPointD[2] - toolPointA[2]); // double normAD = AD.norm(); // // Eigen::Vector3d PQ(sawPlanePointQ[0] - sawPlanePointP[0], // sawPlanePointQ[1] - sawPlanePointP[1], // sawPlanePointQ[2] - sawPlanePointP[2]); // double normPQ = PQ.norm(); // // Eigen::Vector3d PS(sawPlanePointS[0] - sawPlanePointP[0], // sawPlanePointS[1] - sawPlanePointP[1], // sawPlanePointS[2] - sawPlanePointP[2]); // double normPS = PS.norm(); // // // 3 unit vectors of the coordinate system at Point A // Eigen::Vector3d y; // y = AC / normAC; // // Eigen::Vector3d z; // z = (AB.cross(AC)) / (normAB * normAC); // // Eigen::Vector3d x; // x = y.cross(z); // // Eigen::Matrix3d matrixA; // matrixA.col(0) = x; // matrixA.col(1) = y; // matrixA.col(2) = z; // Eigen::Matrix3d inverseMatrixA = matrixA.inverse(); // // // 3 unit vectors of the coordinate system at Point D // Eigen::Vector3d X; // X = PQ.cross(PS) / (normPQ * normPS); // if (X.dot(x)<0) // { // X = - X; // } // // // Eigen::Vector3d Y; // Y = y - X * (y.dot(X)); // Y = Y / Y.norm(); // // Eigen::Vector3d Z; // Z = X.cross(Y); // // Eigen::Matrix3d matrixD; // matrixD.col(0) = X; // matrixD.col(1) = Y; // matrixD.col(2) = Z; // // // Obtain the rotation angles // Eigen::Matrix3d matrixR; // matrixR = matrixD * inverseMatrixA; // Eigen::Vector3d eulerAngles = matrixR.eulerAngles(2, 1, 0); // // double r_x = eulerAngles[2]; // double r_y = eulerAngles[1]; // double r_z = eulerAngles[0]; // // // Obtain the translation (D's position under A's coordinate system) // double x_d = AD.dot(x); // double y_d = AD.dot(y); // double z_d = AD.dot(z); // // // print out // std::cout << "r_z: " << r_z << std::endl; // std::cout << "r_y: " << r_y << std::endl; // std::cout << "r_x: " << r_x << std::endl; // // std::cout << "x: " << x_d << std::endl; // std::cout << "y: " << y_d << std::endl; // std::cout << "z: " << z_d << std::endl; // } //-------------------------------- ↓ QT part ↓--------------------------------------- #define PI acos(-1) const std::string NodeEditor::VIEW_ID = "org.mitk.views.nodeeditor"; void NodeEditor::SetFocus() { // m_Controls.pushButton_applyLandMark->setFocus(); } void NodeEditor::InitPointSetSelector(QmitkSingleNodeSelectionWidget *widget) { widget->SetDataStorage(GetDataStorage()); widget->SetNodePredicate(mitk::NodePredicateAnd::New( mitk::TNodePredicateDataType<mitk::PointSet>::New(), mitk::NodePredicateNot::New(mitk::NodePredicateOr::New(mitk::NodePredicateProperty::New("helper object"), mitk::NodePredicateProperty::New("hidden object"))))); widget->SetSelectionIsOptional(true); widget->SetAutoSelectNewNodes(true); widget->SetEmptyInfo(QString("Please select a point set")); widget->SetPopUpTitel(QString("Select point set")); } void NodeEditor::InitNodeSelector(QmitkSingleNodeSelectionWidget *widget) { widget->SetDataStorage(GetDataStorage()); widget->SetNodePredicate(mitk::NodePredicateNot::New(mitk::NodePredicateOr::New( mitk::NodePredicateProperty::New("helper object"), mitk::NodePredicateProperty::New("hidden object")))); widget->SetSelectionIsOptional(true); widget->SetAutoSelectNewNodes(true); widget->SetEmptyInfo(QString("Please select a node")); widget->SetPopUpTitel(QString("Select node")); } void NodeEditor::CreateQtPartControl(QWidget *parent) { // create GUI widgets from the Qt Designer's .ui file m_Controls.setupUi(parent); // connect(m_Controls.buttonPerformImageProcessing, &QPushButton::clicked, this, &NodeEditor::DoImageProcessing); // Set Node Selection Widget InitNodeSelector(m_Controls.drrCtImageSingleNodeSelectionWidget); InitNodeSelector(m_Controls.newDrrCtImageSingleNodeSelectionWidget); InitNodeSelector(m_Controls.widget_Poly); InitNodeSelector(m_Controls.widget_CropImage); InitNodeSelector(m_Controls.registrationCtSingleNodeSelectionWidget); InitNodeSelector(m_Controls.registrationDrr1SingleNodeSelectionWidget); InitNodeSelector(m_Controls.registrationDrr2SingleNodeSelectionWidget); InitNodeSelector(m_Controls.rawCtImageSingleNodeSelectionWidget); InitNodeSelector(m_Controls.evaluationPointsSingleNodeSelectionWidget); InitNodeSelector(m_Controls.newRegistrationCtSingleNodeSelectionWidget); InitNodeSelector(m_Controls.regDrr1SingleNodeSelectionWidget); InitNodeSelector(m_Controls.regDrr2SingleNodeSelectionWidget); connect(m_Controls.newRegistrationCtSingleNodeSelectionWidget, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged, this, &NodeEditor::NewRegistrationCtChanged); connect(m_Controls.regDrr1SingleNodeSelectionWidget, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged, this, &NodeEditor::RegDrr1Changed); connect(m_Controls.regDrr2SingleNodeSelectionWidget, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged, this, &NodeEditor::RegDrr2Changed); connect(m_Controls.getIntersectionPushButton, &QPushButton::clicked, this, &NodeEditor::GetIntersection); connect(m_Controls.newRegPushButton, &QPushButton::clicked, this, &NodeEditor::NewRegister); connect(m_Controls.newRegVisualPushButton, &QPushButton::clicked, this, &NodeEditor::Visualize2ProjectionModel); connect(m_Controls.rawCtImageSingleNodeSelectionWidget, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged, this, &NodeEditor::RawCtImageChanged); connect(m_Controls.evaluationPointsSingleNodeSelectionWidget, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged, this, &NodeEditor::EvaluationPointsChanged); connect(m_Controls.evaluateRegisterPushButton, &QPushButton::clicked, this, &NodeEditor::EvaluateRegistration); connect(m_Controls.v1GenerateDrrPushButton, &QPushButton::clicked, this, &NodeEditor::V1DrrGenerateData); connect(m_Controls.v2GenerateDrrPushButton, &QPushButton::clicked, this, &NodeEditor::V2DrrGenerateData); connect(m_Controls.drrModelVisualPushButton, &QPushButton::clicked, this, &NodeEditor::VisualizeDrrProjectionModel); // drr connect(m_Controls.recoverDefaultValuesPushButton, &QPushButton::clicked, this, &NodeEditor::SetUiDefault); connect(m_Controls.generateDrrPushButton, &QPushButton::clicked, this, &NodeEditor::Drr); connect(m_Controls.drrCtImageSingleNodeSelectionWidget, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged, this, &NodeEditor::DrrCtImageChanged); connect(m_Controls.newDrrCtImageSingleNodeSelectionWidget, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged, this, &NodeEditor::NewDrrCtImageChanged); connect(m_Controls.widget_CropImage, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged, this, &NodeEditor::InputImageToCropChanged); connect(m_Controls.widget_Poly, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged, this, &NodeEditor::InputSurfaceChanged); // twoProjectionRegistration connect(m_Controls.registerPushButton, &QPushButton::clicked, this, &NodeEditor::Register); connect(m_Controls.initialMetricPushButton, &QPushButton::clicked, this, &NodeEditor::InitialMetric); connect(m_Controls.registrationCtSingleNodeSelectionWidget, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged, this, &NodeEditor::RegistrationCtImageChanged); connect(m_Controls.registrationDrr1SingleNodeSelectionWidget, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged, this, &NodeEditor::InputDrrImageChanged_1); connect(m_Controls.registrationDrr2SingleNodeSelectionWidget, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged, this, &NodeEditor::InputDrrImageChanged_2); // stl polydata to imagedata connect(m_Controls.surfaceToImagePushButton, &QPushButton::clicked, this, &NodeEditor::PolyDataToImageData); connect(m_Controls.generateWhiteImagePushButton, &QPushButton::clicked, this, &NodeEditor::GenerateWhiteImage); } //-------------------------------- ↑ QT part ↑---------------------------------------
44.008145
120
0.714327
zhaomengxiao
4f5e170f033b10eac7e869f8859c00580c9777ee
526
cpp
C++
Assignment2/Motorcycle.cpp
JaeSungPak/Pocu_Test
9f606e88236ef59bba1baea7a0199fd6c49fe478
[ "MIT" ]
null
null
null
Assignment2/Motorcycle.cpp
JaeSungPak/Pocu_Test
9f606e88236ef59bba1baea7a0199fd6c49fe478
[ "MIT" ]
null
null
null
Assignment2/Motorcycle.cpp
JaeSungPak/Pocu_Test
9f606e88236ef59bba1baea7a0199fd6c49fe478
[ "MIT" ]
null
null
null
#include "Motorcycle.h" namespace assignment2 { Motorcycle::Motorcycle() : Vehicle(2) { SetTravelAndRestTime(eTravelInfo::MOTORCYCLE_TRAVEL, eRestInfo::MOTORCYCLE_REST); } Motorcycle::~Motorcycle() { } unsigned int Motorcycle::GetMaxSpeed() const { return GetDriveSpeed(); } unsigned int Motorcycle::GetDriveSpeed() const { double x = static_cast<double>(GetPassengersWeight()); return (-pow(x / 15, 3) + (x * 2) + 400 > 0) ? static_cast<unsigned int>(-pow(x / 15, 3) + (x * 2) + 400 + 0.5f) : 0; } }
21.04
119
0.671103
JaeSungPak
4f615c956f3ade2815e7404d63a2a4ef531b817b
2,542
cpp
C++
tests/unit/parallel/executors/timed_parallel_executor.cpp
brycelelbach/hpx
94582f5dc26e889cdcf80913975ff33b7f975285
[ "BSL-1.0" ]
3
2017-04-06T16:36:38.000Z
2018-05-19T11:28:54.000Z
tests/unit/parallel/executors/timed_parallel_executor.cpp
brycelelbach/hpx
94582f5dc26e889cdcf80913975ff33b7f975285
[ "BSL-1.0" ]
1
2018-08-13T17:42:55.000Z
2018-08-13T18:20:23.000Z
tests/unit/parallel/executors/timed_parallel_executor.cpp
brycelelbach/hpx
94582f5dc26e889cdcf80913975ff33b7f975285
[ "BSL-1.0" ]
2
2018-05-25T06:33:50.000Z
2019-02-25T20:09:13.000Z
// Copyright (c) 2007-2016 Hartmut Kaiser // // 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 <hpx/hpx_init.hpp> #include <hpx/hpx.hpp> #include <hpx/include/parallel_executors.hpp> #include <hpx/util/lightweight_test.hpp> #include <boost/range/functions.hpp> #include <algorithm> #include <chrono> #include <cstdlib> #include <string> #include <vector> using namespace std::chrono; /////////////////////////////////////////////////////////////////////////////// hpx::thread::id test(int passed_through) { HPX_TEST_EQ(passed_through, 42); return hpx::this_thread::get_id(); } void test_timed_sync() { typedef hpx::parallel::parallel_executor executor; typedef hpx::parallel::timed_executor_traits<executor> traits; executor exec; HPX_TEST( traits::execute_after( exec, milliseconds(1), &test, 42 ) != hpx::this_thread::get_id()); HPX_TEST( traits::execute_at( exec, steady_clock::now() + milliseconds(1), &test, 42 ) != hpx::this_thread::get_id()); } void test_timed_async() { typedef hpx::parallel::parallel_executor executor; typedef hpx::parallel::timed_executor_traits<executor> traits; executor exec; HPX_TEST( traits::async_execute_after( exec, milliseconds(1), &test, 42 ).get() != hpx::this_thread::get_id()); HPX_TEST( traits::async_execute_at( exec, steady_clock::now() + milliseconds(1), &test, 42 ).get() != hpx::this_thread::get_id()); } void test_timed_apply() { typedef hpx::parallel::parallel_executor executor; typedef hpx::parallel::timed_executor_traits<executor> traits; executor exec; traits::apply_execute_after(exec, milliseconds(1), &test, 42); traits::apply_execute_at( exec, steady_clock::now() + milliseconds(1), &test, 42); } /////////////////////////////////////////////////////////////////////////////// int hpx_main(int argc, char* argv[]) { test_timed_sync(); test_timed_async(); test_timed_apply(); return hpx::finalize(); } int main(int argc, char* argv[]) { // By default this test should run on all available cores std::vector<std::string> const cfg = { "hpx.os_threads=all" }; // Initialize and run HPX HPX_TEST_EQ_MSG(hpx::init(argc, argv, cfg), 0, "HPX main exited with non-zero status"); return hpx::util::report_errors(); }
26.757895
80
0.623131
brycelelbach
4f64557c2369e155a3f92bc5f822ad51a39c2461
2,112
cpp
C++
src/game/sys/combat/comp/health_comp.cpp
lowkey42/MagnumOpus
87897b16192323b40064119402c74e014a48caf3
[ "MIT" ]
5
2020-03-13T23:16:33.000Z
2022-03-20T19:16:46.000Z
src/game/sys/combat/comp/health_comp.cpp
lowkey42/MagnumOpus
87897b16192323b40064119402c74e014a48caf3
[ "MIT" ]
24
2015-04-20T20:26:23.000Z
2015-11-20T22:39:38.000Z
src/game/sys/combat/comp/health_comp.cpp
lowkey42/medienprojekt
87897b16192323b40064119402c74e014a48caf3
[ "MIT" ]
1
2022-03-08T03:11:21.000Z
2022-03-08T03:11:21.000Z
#define MO_BUILD_SERIALIZER #include "health_comp.hpp" #include "../../../level/elements.hpp" namespace mo { namespace sys { namespace combat { void Health_comp::load(sf2::JsonDeserializer& state, asset::Asset_manager&) { std::vector<level::Element> resistences; std::vector<level::Element> vulnerabilities; for(auto e : _resistences) resistences.push_back(e); for(auto e : _vulnerabilities) vulnerabilities.push_back(e); state.read_virtual( sf2::vmember("auto_heal_max", _auto_heal_max), sf2::vmember("auto_heal", _auto_heal), sf2::vmember("max_hp", _max_hp), sf2::vmember("current_hp", _current_hp), sf2::vmember("physical_resistence", _physical_resistence), sf2::vmember("resistences", resistences), sf2::vmember("vulnerabilities", vulnerabilities), sf2::vmember("death_effect", _death_effect), sf2::vmember("death_force_feedback", _death_force_feedback) ); if(_current_hp==0) _current_hp = _max_hp; _resistences = level::Elements{resistences}; _vulnerabilities = level::Elements{vulnerabilities}; } void Health_comp::save(sf2::JsonSerializer& state)const { std::vector<level::Element> resistences; std::vector<level::Element> vulnerabilities; for(auto e : _resistences) resistences.push_back(e); for(auto e : _vulnerabilities) vulnerabilities.push_back(e); state.write_virtual( sf2::vmember("auto_heal_max", _auto_heal_max), sf2::vmember("auto_heal", _auto_heal), sf2::vmember("max_hp", _max_hp), sf2::vmember("current_hp", _current_hp), sf2::vmember("physical_resistence", _physical_resistence), sf2::vmember("resistences", resistences), sf2::vmember("vulnerabilities", vulnerabilities), sf2::vmember("death_effect", _death_effect), sf2::vmember("death_force_feedback", _death_force_feedback) ); } void Health_comp::damage(float hp, level::Element type)noexcept{ if(type==level::Element::neutral) hp *= (1.f - _physical_resistence); else if(_resistences | type) hp *= 0.25f; else if(_vulnerabilities | type) hp *= 4.f; _damage+=hp; } } } }
25.445783
65
0.709754
lowkey42
4f65916fd29efbd8aacecc1433c59d9c5f4c651c
2,337
cc
C++
vod/src/model/DeleteAIImageInfosRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
null
null
null
vod/src/model/DeleteAIImageInfosRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
null
null
null
vod/src/model/DeleteAIImageInfosRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
1
2020-11-27T09:13:12.000Z
2020-11-27T09:13:12.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/vod/model/DeleteAIImageInfosRequest.h> using AlibabaCloud::Vod::Model::DeleteAIImageInfosRequest; DeleteAIImageInfosRequest::DeleteAIImageInfosRequest() : RpcServiceRequest("vod", "2017-03-21", "DeleteAIImageInfos") { setMethod(HttpRequest::Method::Post); } DeleteAIImageInfosRequest::~DeleteAIImageInfosRequest() {} long DeleteAIImageInfosRequest::getResourceOwnerId()const { return resourceOwnerId_; } void DeleteAIImageInfosRequest::setResourceOwnerId(long resourceOwnerId) { resourceOwnerId_ = resourceOwnerId; setParameter("ResourceOwnerId", std::to_string(resourceOwnerId)); } std::string DeleteAIImageInfosRequest::getResourceOwnerAccount()const { return resourceOwnerAccount_; } void DeleteAIImageInfosRequest::setResourceOwnerAccount(const std::string& resourceOwnerAccount) { resourceOwnerAccount_ = resourceOwnerAccount; setParameter("ResourceOwnerAccount", resourceOwnerAccount); } long DeleteAIImageInfosRequest::getOwnerId()const { return ownerId_; } void DeleteAIImageInfosRequest::setOwnerId(long ownerId) { ownerId_ = ownerId; setParameter("OwnerId", std::to_string(ownerId)); } std::string DeleteAIImageInfosRequest::getAccessKeyId()const { return accessKeyId_; } void DeleteAIImageInfosRequest::setAccessKeyId(const std::string& accessKeyId) { accessKeyId_ = accessKeyId; setParameter("AccessKeyId", accessKeyId); } std::string DeleteAIImageInfosRequest::getAIImageInfoIds()const { return aIImageInfoIds_; } void DeleteAIImageInfosRequest::setAIImageInfoIds(const std::string& aIImageInfoIds) { aIImageInfoIds_ = aIImageInfoIds; setParameter("AIImageInfoIds", aIImageInfoIds); }
27.494118
97
0.774925
iamzken
4f673d576213f5ae9a9097133faae1684512ba02
2,545
cpp
C++
qwt/examples/radio/tunerfrm.cpp
iti-luebeck/HANSE2011
0bd5b3f1e0bc5a02516e7514b2241897337334c2
[ "BSD-3-Clause" ]
null
null
null
qwt/examples/radio/tunerfrm.cpp
iti-luebeck/HANSE2011
0bd5b3f1e0bc5a02516e7514b2241897337334c2
[ "BSD-3-Clause" ]
null
null
null
qwt/examples/radio/tunerfrm.cpp
iti-luebeck/HANSE2011
0bd5b3f1e0bc5a02516e7514b2241897337334c2
[ "BSD-3-Clause" ]
null
null
null
#include <qlayout.h> #include <qlabel.h> #include <qwt_wheel.h> #include <qwt_slider.h> #include <qwt_thermo.h> #include <qwt_math.h> #include "tunerfrm.h" class TuningThermo: public QWidget { public: TuningThermo(QWidget *parent): QWidget(parent) { d_thermo = new QwtThermo(this); d_thermo->setOrientation(Qt::Horizontal, QwtThermo::NoScale); d_thermo->setRange(0.0, 1.0); d_thermo->setFillColor(Qt::green); QLabel *label = new QLabel("Tuning", this); label->setAlignment(Qt::AlignCenter); QVBoxLayout *layout = new QVBoxLayout(this); layout->setMargin(0); layout->addWidget(d_thermo); layout->addWidget(label); setFixedWidth(3 * label->sizeHint().width()); } void setValue(double value) { d_thermo->setValue(value); } private: QwtThermo *d_thermo; }; TunerFrame::TunerFrame(QWidget *parent): QFrame(parent) { d_sldFreq = new QwtSlider(this, Qt::Horizontal, QwtSlider::TopScale); d_sldFreq->setRange(87.5, 108, 0.01, 10); d_sldFreq->setScaleMaxMinor(5); d_sldFreq->setScaleMaxMajor(12); d_sldFreq->setThumbLength(80); d_sldFreq->setBorderWidth(1); d_thmTune = new TuningThermo(this); d_whlFreq = new QwtWheel(this); d_whlFreq->setMass(0.5); d_whlFreq->setRange(87.5, 108, 0.01); d_whlFreq->setTotalAngle(3600.0); d_whlFreq->setFixedHeight(30); connect(d_whlFreq, SIGNAL(valueChanged(double)), SLOT(adjustFreq(double))); connect(d_sldFreq, SIGNAL(valueChanged(double)), SLOT(adjustFreq(double))); QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->setMargin(10); mainLayout->setSpacing(5); mainLayout->addWidget(d_sldFreq); QHBoxLayout *hLayout = new QHBoxLayout; hLayout->setMargin(0); hLayout->addWidget(d_thmTune, 0); hLayout->addStretch(5); hLayout->addWidget(d_whlFreq, 2); mainLayout->addLayout(hLayout); } void TunerFrame::adjustFreq(double frq) { const double factor = 13.0 / (108 - 87.5); const double x = (frq - 87.5) * factor; const double field = qwtSqr(sin(x) * cos(4.0 * x)); d_thmTune->setValue(field); if (d_sldFreq->value() != frq) d_sldFreq->setValue(frq); if (d_whlFreq->value() != frq) d_whlFreq->setValue(frq); emit fieldChanged(field); } void TunerFrame::setFreq(double frq) { d_whlFreq->setValue(frq); }
26.237113
80
0.628684
iti-luebeck
4f682d2c088bf9f8823befdef4ebcf31c214b746
2,951
cpp
C++
examples/Qt/common/VVGLRenderQThread.cpp
mrRay/VVISF-GL
96b00da11e4497da304041ea2a5ffc6e3a8c9454
[ "BSD-3-Clause" ]
24
2019-01-17T17:56:18.000Z
2022-02-27T19:57:13.000Z
examples/Qt/common/VVGLRenderQThread.cpp
mrRay/VVISF-GL
96b00da11e4497da304041ea2a5ffc6e3a8c9454
[ "BSD-3-Clause" ]
6
2019-01-17T17:17:12.000Z
2020-06-19T11:27:50.000Z
examples/Qt/common/VVGLRenderQThread.cpp
mrRay/VVISF-GL
96b00da11e4497da304041ea2a5ffc6e3a8c9454
[ "BSD-3-Clause" ]
2
2020-12-25T04:57:31.000Z
2021-03-02T22:05:31.000Z
#include "VVGLRenderQThread.h" #include <QMutexLocker> #include <QAbstractEventDispatcher> #include <QDebug> using namespace std; using namespace VVGL; VVGLRenderQThread::VVGLRenderQThread(const VVGL::GLContextRef & ctxToUse, QObject * parent) : QThread(parent), _ctx(ctxToUse) { //_ctx->moveToThread(this); _bp = make_shared<GLBufferPool>(ctxToUse); _tc = CreateGLTexToTexCopierRefUsing(_ctx); _tc->setPrivatePool(_bp); connect(this, &QThread::finished, [&]() { // move the contexts back to the main thread before we exit QThread *mainThread = qApp->thread(); if (mainThread != nullptr) { if (_ctx != nullptr) _ctx->moveToThread(mainThread); if (_bp != nullptr) _bp->context()->moveToThread(mainThread); if (_tc != nullptr) _tc->context()->moveToThread(mainThread); } }); } void VVGLRenderQThread::performRender() { _cond.wakeOne(); } void VVGLRenderQThread::setRenderCallback(const RenderCallback & n) { QMutexLocker tmpLock(&_condLock); _renderCallback = n; } VVGL::GLContextRef VVGLRenderQThread::renderContext() { return _ctx; } VVGL::GLBufferPoolRef VVGLRenderQThread::bufferPool() { return _bp; } VVGL::GLTexToTexCopierRef VVGLRenderQThread::texCopier() { return _tc; } void VVGLRenderQThread::start(QThread::Priority inPriority) { //qDebug() << __PRETTY_FUNCTION__; if (_ctx != nullptr) _ctx->moveToThread(this); if (_bp != nullptr) _bp->context()->moveToThread(this); if (_tc != nullptr) _tc->context()->moveToThread(this); QThread::start(inPriority); } void VVGLRenderQThread::run() { //qDebug() << __PRETTY_FUNCTION__; while (1) { //qDebug() << "\tentering wait loop..."; _condLock.lock(); if (!_cond.wait(&_condLock, 17)) { //qDebug() << "\twait loop timed out..."; _condLock.unlock(); // if i'm here, then the wait timed out- check to see if the thread should still be running, run another loop if it's clear if (isFinished() || isInterruptionRequested() || !isRunning()) { //qDebug() << "\tfinished or requested interrupt or not running- bailing"; break; } else { continue; } } //else //qDebug() << "\texited wait loop!"; // ...if i'm here then the wait didn't time out- something signaled the condition // check to see if the thread should still be running if (isFinished() || isInterruptionRequested() || !isRunning()) { //qDebug() << "\tfinished or requested interrupt or not running- bailing"; break; } // perform the render callback if (_renderCallback != nullptr) { _ctx->makeCurrentIfNotCurrent(); _renderCallback(this); } // do housekeeping on the buffer pool if (_bp != nullptr) _bp->housekeeping(); _condLock.unlock(); // process some events QAbstractEventDispatcher *ed = eventDispatcher(); if (ed != nullptr) { ed->processEvents(QEventLoop::AllEvents); } } //qDebug() << "\t" << __PRETTY_FUNCTION__ << "- FINISHED"; }
23.420635
126
0.675364
mrRay
4f6b9f44636f66e94d6a514cc10f3915c0e601c6
567
cpp
C++
lab2021-2022f/lab02/protection_levels_example_sol.cpp
chgogos/oop
3b0e6bbd29a76f863611e18d082913f080b1b571
[ "MIT" ]
14
2019-04-23T13:45:10.000Z
2022-03-12T18:26:47.000Z
lab2021-2022f/lab02/protection_levels_example_sol.cpp
chgogos/oop
3b0e6bbd29a76f863611e18d082913f080b1b571
[ "MIT" ]
null
null
null
lab2021-2022f/lab02/protection_levels_example_sol.cpp
chgogos/oop
3b0e6bbd29a76f863611e18d082913f080b1b571
[ "MIT" ]
9
2019-09-01T15:17:45.000Z
2020-11-13T20:31:36.000Z
// Γράψτε ένα πρόγραμμα που να ορίζει μια κλάση Α με ένα ακέραιο ιδιωτικό μέλος δεδομένων x και ένα ακέραιο δημόσιο μέλος δεδομένων y. // Συμπληρώστε τον απαιτούμενο κώδικα έτσι ώστε για ένα αντικείμενο που δημιουργείται στη main να εμφανίζεται τόσο η τιμή του x όσο και η τιμή του y. #include <iostream> using namespace std; class A { private: int x; public: int y; A(int x, int y) : x(x), y(y) {} int get_x() { return x; } }; int main() { A obj(1, 2); cout << obj.get_x() << endl; cout << obj.y << endl; } /* 1 2 */
17.71875
149
0.631393
chgogos
4f6d6af7bb76469c81d269a977c926fc17470f82
5,091
cc
C++
chromium/chrome/installer/util/copy_tree_work_item.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/chrome/installer/util/copy_tree_work_item.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/chrome/installer/util/copy_tree_work_item.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/installer/util/copy_tree_work_item.h" #include <shlwapi.h> #include "base/files/file_util.h" #include "base/logging.h" #include "chrome/installer/util/logging_installer.h" CopyTreeWorkItem::~CopyTreeWorkItem() { } CopyTreeWorkItem::CopyTreeWorkItem(const base::FilePath& source_path, const base::FilePath& dest_path, const base::FilePath& temp_dir, CopyOverWriteOption overwrite_option, const base::FilePath& alternative_path) : source_path_(source_path), dest_path_(dest_path), temp_dir_(temp_dir), overwrite_option_(overwrite_option), alternative_path_(alternative_path), copied_to_dest_path_(false), moved_to_backup_(false), copied_to_alternate_path_(false) { } bool CopyTreeWorkItem::Do() { if (!base::PathExists(source_path_)) { LOG(ERROR) << source_path_.value() << " does not exist"; return false; } bool dest_exist = base::PathExists(dest_path_); // handle overwrite_option_ = IF_DIFFERENT case. if ((dest_exist) && (overwrite_option_ == WorkItem::IF_DIFFERENT) && // only for single file (!base::DirectoryExists(source_path_)) && (!base::DirectoryExists(dest_path_)) && (base::ContentsEqual(source_path_, dest_path_))) { VLOG(1) << "Source file " << source_path_.value() << " and destination file " << dest_path_.value() << " are exactly same. Returning true."; return true; } else if ((dest_exist) && (overwrite_option_ == WorkItem::NEW_NAME_IF_IN_USE) && (!base::DirectoryExists(source_path_)) && (!base::DirectoryExists(dest_path_)) && (IsFileInUse(dest_path_))) { // handle overwrite_option_ = NEW_NAME_IF_IN_USE case. if (alternative_path_.empty() || base::PathExists(alternative_path_) || !base::CopyFile(source_path_, alternative_path_)) { LOG(ERROR) << "failed to copy " << source_path_.value() << " to " << alternative_path_.value(); return false; } else { copied_to_alternate_path_ = true; VLOG(1) << "Copied source file " << source_path_.value() << " to alternative path " << alternative_path_.value(); return true; } } else if ((dest_exist) && (overwrite_option_ == WorkItem::IF_NOT_PRESENT)) { // handle overwrite_option_ = IF_NOT_PRESENT case. return true; } // In all cases that reach here, move dest to a backup path. if (dest_exist) { if (!backup_path_.CreateUniqueTempDirUnderPath(temp_dir_)) { PLOG(ERROR) << "Failed to get backup path in folder " << temp_dir_.value(); return false; } base::FilePath backup = backup_path_.path().Append(dest_path_.BaseName()); if (base::Move(dest_path_, backup)) { moved_to_backup_ = true; VLOG(1) << "Moved destination " << dest_path_.value() << " to backup path " << backup.value(); } else { PLOG(ERROR) << "failed moving " << dest_path_.value() << " to " << backup.value(); return false; } } // In all cases that reach here, copy source to destination. if (base::CopyDirectory(source_path_, dest_path_, true)) { copied_to_dest_path_ = true; VLOG(1) << "Copied source " << source_path_.value() << " to destination " << dest_path_.value(); } else { LOG(ERROR) << "failed copy " << source_path_.value() << " to " << dest_path_.value(); return false; } return true; } void CopyTreeWorkItem::Rollback() { // Normally the delete operations below should not fail unless some // programs like anti-virus are inspecting the files we just copied. // If this does happen sometimes, we may consider using Move instead of // Delete here. For now we just log the error and continue with the // rest of rollback operation. if (copied_to_dest_path_ && !base::DeleteFile(dest_path_, true)) { LOG(ERROR) << "Can not delete " << dest_path_.value(); } if (moved_to_backup_) { base::FilePath backup(backup_path_.path().Append(dest_path_.BaseName())); if (!base::Move(backup, dest_path_)) { PLOG(ERROR) << "failed move " << backup.value() << " to " << dest_path_.value(); } } if (copied_to_alternate_path_ && !base::DeleteFile(alternative_path_, true)) { LOG(ERROR) << "Can not delete " << alternative_path_.value(); } } bool CopyTreeWorkItem::IsFileInUse(const base::FilePath& path) { if (!base::PathExists(path)) return false; HANDLE handle = ::CreateFile(path.value().c_str(), GENERIC_WRITE, NULL, NULL, OPEN_EXISTING, NULL, NULL); if (handle == INVALID_HANDLE_VALUE) return true; CloseHandle(handle); return false; }
36.364286
79
0.626989
wedataintelligence
4f7021d4a1d75b40579e980220bb355917ad16a1
5,058
cpp
C++
Tejas-Simulator/PIN/pin-2.14/source/tools/ManualExamples/malloc_mt.cpp
markoshorro/tejas_knl
5e772aef46362d8bec8ad6d5427b9bcff9be5cfe
[ "Apache-2.0" ]
1
2021-04-22T05:27:08.000Z
2021-04-22T05:27:08.000Z
pin_kit/source/tools/ManualExamples/malloc_mt.cpp
sawansib/SNIPER
45ec1eeb09b81a7250bc1a1aaa452f16b2b7f497
[ "MIT" ]
null
null
null
pin_kit/source/tools/ManualExamples/malloc_mt.cpp
sawansib/SNIPER
45ec1eeb09b81a7250bc1a1aaa452f16b2b7f497
[ "MIT" ]
null
null
null
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2014 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR ITS 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. END_LEGAL */ #include <stdio.h> #include "pin.H" KNOB<string> KnobOutputFile(KNOB_MODE_WRITEONCE, "pintool", "o", "malloc_mt.out", "specify output file name"); //============================================================== // Analysis Routines //============================================================== // Note: threadid+1 is used as an argument to the PIN_GetLock() // routine as a debugging aid. This is the value that // the lock is set to, so it must be non-zero. // lock serializes access to the output file. FILE * out; PIN_LOCK lock; // Note that opening a file in a callback is only supported on Linux systems. // See buffer-win.cpp for how to work around this issue on Windows. // // This routine is executed every time a thread is created. VOID ThreadStart(THREADID threadid, CONTEXT *ctxt, INT32 flags, VOID *v) { PIN_GetLock(&lock, threadid+1); fprintf(out, "thread begin %d\n",threadid); fflush(out); PIN_ReleaseLock(&lock); } // This routine is executed every time a thread is destroyed. VOID ThreadFini(THREADID threadid, const CONTEXT *ctxt, INT32 code, VOID *v) { PIN_GetLock(&lock, threadid+1); fprintf(out, "thread end %d code %d\n",threadid, code); fflush(out); PIN_ReleaseLock(&lock); } // This routine is executed each time malloc is called. VOID BeforeMalloc( int size, THREADID threadid ) { PIN_GetLock(&lock, threadid+1); fprintf(out, "thread %d entered malloc(%d)\n", threadid, size); fflush(out); PIN_ReleaseLock(&lock); } //==================================================================== // Instrumentation Routines //==================================================================== // This routine is executed for each image. VOID ImageLoad(IMG img, VOID *) { RTN rtn = RTN_FindByName(img, "malloc"); if ( RTN_Valid( rtn )) { RTN_Open(rtn); RTN_InsertCall(rtn, IPOINT_BEFORE, AFUNPTR(BeforeMalloc), IARG_FUNCARG_ENTRYPOINT_VALUE, 0, IARG_THREAD_ID, IARG_END); RTN_Close(rtn); } } // This routine is executed once at the end. VOID Fini(INT32 code, VOID *v) { fclose(out); } /* ===================================================================== */ /* Print Help Message */ /* ===================================================================== */ INT32 Usage() { PIN_ERROR("This Pintool prints a trace of malloc calls in the guest application\n" + KNOB_BASE::StringKnobSummary() + "\n"); return -1; } /* ===================================================================== */ /* Main */ /* ===================================================================== */ int main(INT32 argc, CHAR **argv) { // Initialize the pin lock PIN_InitLock(&lock); // Initialize pin if (PIN_Init(argc, argv)) return Usage(); PIN_InitSymbols(); out = fopen(KnobOutputFile.Value().c_str(), "w"); // Register ImageLoad to be called when each image is loaded. IMG_AddInstrumentFunction(ImageLoad, 0); // Register Analysis routines to be called when a thread begins/ends PIN_AddThreadStartFunction(ThreadStart, 0); PIN_AddThreadFiniFunction(ThreadFini, 0); // Register Fini to be called when the application exits PIN_AddFiniFunction(Fini, 0); // Never returns PIN_StartProgram(); return 0; }
34.408163
86
0.618822
markoshorro
4f73c2c6265861405facac96a5c6ced99988e079
12,762
cpp
C++
src/ESocketAcceptor.cpp
cxxjava/CxxConet
43a617636ab437616c15c20f9826247cb17a66f0
[ "Apache-2.0" ]
23
2017-05-11T01:42:15.000Z
2021-11-24T06:50:51.000Z
src/ESocketAcceptor.cpp
cxxjava/CxxConet
43a617636ab437616c15c20f9826247cb17a66f0
[ "Apache-2.0" ]
null
null
null
src/ESocketAcceptor.cpp
cxxjava/CxxConet
43a617636ab437616c15c20f9826247cb17a66f0
[ "Apache-2.0" ]
8
2017-05-11T07:55:22.000Z
2022-01-14T09:14:09.000Z
/* * ESocketAcceptor.cpp * * Created on: 2017-3-16 * Author: cxxjava@163.com */ #include "../inc/ESocketAcceptor.hh" #include "./EManagedSession.hh" namespace efc { namespace naf { #define SOCKET_BACKLOG_MIN 512 sp<ELogger> ESocketAcceptor::logger = ELoggerManager::getLogger("ESocketAcceptor"); ESocketAcceptor::~ESocketAcceptor() { delete managedSessions_; } ESocketAcceptor::ESocketAcceptor() : status_(INITED), reuseAddress_(false), backlog_(SOCKET_BACKLOG_MIN), timeout_(0), bufsize_(-1), maxConns_(-1), workThreads_(EOS::active_processor_count()), stats_(this) { managedSessions_ = new EManagedSession(this); } EFiberScheduler& ESocketAcceptor::getFiberScheduler() { return scheduler; } boolean ESocketAcceptor::isReuseAddress() { return reuseAddress_; } void ESocketAcceptor::setReuseAddress(boolean on) { reuseAddress_ = on; } int ESocketAcceptor::getBacklog() { return backlog_; } void ESocketAcceptor::setBacklog(int backlog) { backlog_ = ES_MAX(backlog, backlog_); } void ESocketAcceptor::setSoTimeout(int timeout) { timeout_ = timeout; } int ESocketAcceptor::getSoTimeout() { return timeout_; } void ESocketAcceptor::setReceiveBufferSize (int size) { bufsize_ = size; } int ESocketAcceptor::getReceiveBufferSize () { return bufsize_; } void ESocketAcceptor::setMaxConnections(int connections) { maxConns_ = connections; } int ESocketAcceptor::getMaxConnections() { return maxConns_.value(); } void ESocketAcceptor::setSessionIdleTime(EIdleStatus status, int seconds) { if (seconds < 0) { throw EIllegalArgumentException(__FILE__, __LINE__, EString::formatOf("Illegal idle time: %d", seconds).c_str()); } if ((status & READER_IDLE) == READER_IDLE) { idleTimeForRead_ = seconds; } if ((status & WRITER_IDLE) == WRITER_IDLE) { idleTimeForWrite_ = seconds; } } int ESocketAcceptor::getSessionIdleTime(EIdleStatus status) { if ((status & READER_IDLE) == READER_IDLE) { return idleTimeForRead_.value(); } if ((status & WRITER_IDLE) == WRITER_IDLE) { return idleTimeForWrite_.value(); } throw EIllegalArgumentException(__FILE__, __LINE__, EString::formatOf("Unknown idle status: %d", status).c_str()); } int ESocketAcceptor::getWorkThreads() { return workThreads_; } int ESocketAcceptor::getManagedSessionCount() { return managedSessions_->getManagedSessionCount(); } EIoFilterChainBuilder* ESocketAcceptor::getFilterChainBuilder() { return &defaultFilterChain; } EIoServiceStatistics* ESocketAcceptor::getStatistics() { return &stats_; } void ESocketAcceptor::setListeningHandler(std::function<void(ESocketAcceptor* acceptor)> handler) { listeningCallback_ = handler; } void ESocketAcceptor::setConnectionHandler(std::function<void(sp<ESocketSession>& session, Service* service)> handler) { connectionCallback_ = handler; } void ESocketAcceptor::bind(int port, boolean ssl, const char* name, std::function<void(Service& service)> listener) { Service* svc = new Service(name, ssl, "127.0.0.1", port); Services_.add(svc); if (listener != null) { listener(*svc); } } void ESocketAcceptor::bind(const char* hostname, int port, boolean ssl, const char* name, std::function<void(Service& service)> listener) { Service* svc = new Service(name, ssl, hostname, port); Services_.add(svc); if (listener != null) { listener(*svc); } } void ESocketAcceptor::bind(EInetSocketAddress* localAddress, boolean ssl, const char* name, std::function<void(Service& service)> listener) { if (!localAddress) { throw ENullPointerException(__FILE__, __LINE__, "localAddress"); } Service* svc = new Service(name, ssl, localAddress); Services_.add(svc); if (listener != null) { listener(*svc); } } void ESocketAcceptor::bind(EIterable<EInetSocketAddress*>* localAddresses, boolean ssl, const char* name, std::function<void(Service& service)> listener) { if (!localAddresses) { throw ENullPointerException(__FILE__, __LINE__, "localAddresses"); } sp < EIterator<EInetSocketAddress*> > iter = localAddresses->iterator(); while (iter->hasNext()) { Service* svc = new Service(name, ssl, iter->next()); Services_.add(svc); if (listener != null) { listener(*svc); } } } void ESocketAcceptor::listen() { try { // fibers balance scheduler.setBalanceCallback([](EFiber* fiber, int threadNums){ long tag = fiber->getTag(); if (tag == 0) { return 0; // accept fibers } else if (tag > 0) { return (int)tag; // clean fibers } else { int fid = fiber->getId(); return fid % (threadNums - 1) + 1; // balance to other's threads. } }); status_ = RUNNING; // create clean idle socket fibers for per-conn-thread. if (idleTimeForRead_.value() > 0 || idleTimeForWrite_.value() > 0) { for (int i=1; i<workThreads_; i++) { this->startClean(scheduler, i); } } // accept loop sp<EIterator<Service*> > iter = Services_.iterator(); while (iter->hasNext()) { this->startAccept(scheduler, iter->next()); } // start statistics this->startStatistics(scheduler); // on listening callback this->onListeningHandle(); // wait for fibers work done. scheduler.join(EOS::active_processor_count()); } catch (EInterruptedException& e) { logger->info__(__FILE__, __LINE__, "interrupted"); } catch (EException& e) { logger->error__(__FILE__, __LINE__, e.toString().c_str()); } } void ESocketAcceptor::signalAccept() { sp<EIterator<Service*> > iter = Services_.iterator(); while (iter->hasNext()) { Service* sv = iter->next(); if (sv->ss != null) { //FIXME: http://bbs.chinaunix.net/forum.php?mod=viewthread&action=printable&tid=1844321 //sv->ss->close(); ESocket s("127.0.0.1", sv->ss->getLocalPort()); } } } void ESocketAcceptor::dispose() { // set dispose flag status_ = DISPOSED; // fibier interrupt scheduler.interrupt(); // accept notify signalAccept(); } void ESocketAcceptor::shutdown() { // set dispose flag status_ = DISPOSING; // accept notify signalAccept(); } boolean ESocketAcceptor::isDisposed() { return status_ >= DISPOSING; } //============================================================================= void ESocketAcceptor::startAccept(EFiberScheduler& scheduler, Service* service) { EInetSocketAddress& socketAddress = service->boundAddress; sp<EFiber> acceptFiber = new EFiberTarget([&,service,this](){ service->ss->setReuseAddress(reuseAddress_); if (timeout_ > 0) { service->ss->setSoTimeout(timeout_); } if (bufsize_ > 0) { service->ss->setReceiveBufferSize(bufsize_); } service->ss->bind(&socketAddress, backlog_); while (status_ == RUNNING) { try { // accept sp<ESocket> socket = service->ss->accept(); if (socket != null) { try { sp<ESocketSession> session = newSession(this, socket); session->init(); // enable shared from this. // reach the max connections. int maxconns = maxConns_.value(); if (isDisposed() || (maxconns > 0 && connections_.value() >= maxconns)) { socket->close(); EThread::yield(); //? continue; } connections_++; // statistics stats_.cumulativeManagedSessionCount.incrementAndGet(); if (connections_.value() > stats_.largestManagedSessionCount.get()) { stats_.largestManagedSessionCount.set(connections_.value()); } scheduler.schedule([session,service,this](){ ON_SCOPE_EXIT( connections_--; // remove from session manager. managedSessions_->removeSession(session->getSocket()->getFD()); session->close(); ); try { // add to session manager. managedSessions_->addSession(session->getSocket()->getFD(), session.get()); // set so_timeout option. if (timeout_ > 0) { session->getSocket()->setSoTimeout(timeout_); } // on session create. boolean created = session->getFilterChain()->fireSessionCreated(); if (!created) { return; } // on connection. sp<ESocketSession> noconstss = session; this->onConnectionHandle(noconstss, service); } catch (EThrowable& t) { logger->error__(__FILE__, __LINE__, t.toString().c_str()); } catch (...) { logger->error__(__FILE__, __LINE__, "error"); } }); } catch (EThrowable& t) { logger->error__(__FILE__, __LINE__, t.toString().c_str()); } catch (...) { logger->error__(__FILE__, __LINE__, "error"); } } } catch (EInterruptedException& e) { logger->info__(__FILE__, __LINE__, "interrupted"); break; } catch (ESocketTimeoutException& e) { // nothing to do. } catch (EThrowable& t) { logger->error__(__FILE__, __LINE__, t.toString().c_str()); break; } } logger->info__(__FILE__, __LINE__, "accept closed."); service->ss->close(); }); acceptFiber->setTag(0); //tag: 0 scheduler.schedule(acceptFiber); } void ESocketAcceptor::startClean(EFiberScheduler& scheduler, int tag) { sp<EFiber> cleanFiber = new EFiberTarget([&,this](){ logger->debug__(__FILE__, __LINE__, "I'm clean fiber, thread id=%ld", EThread::currentThread()->getId()); try { EHashMap<int, EIoSession*>* threadManagedSessions = managedSessions_->getCurrentThreadManagedSessions(); while (status_ == RUNNING || (connections_.value() > 0)) { int maxsecs = 3; // sleep for 1s-10s second. int idleread = idleTimeForRead_.value(); int idlewrite = idleTimeForWrite_.value(); int idlesecs = EInteger::MAX_VALUE; int status = 0; if (idleread > 0) { status |= READER_IDLE; maxsecs = ES_MIN(idleread, maxsecs); idlesecs = ES_MIN(idlesecs, idleread); } if (idlewrite > 0) { status |= WRITER_IDLE; maxsecs = ES_MIN(idlewrite, maxsecs); idlesecs = ES_MIN(idlesecs, idlewrite); } int seconds = ES_MAX(maxsecs, 1); sleep(seconds); //! llong currTime = ESystem::currentTimeMillis(); sp<EIterator<EIoSession*> > iter = threadManagedSessions->values()->iterator(); while (iter->hasNext()) { ESocketSession* session = dynamic_cast<ESocketSession*>(iter->next()); llong lastIoTime = ELLong::MAX_VALUE; if ((status & READER_IDLE) == READER_IDLE) { lastIoTime = ES_MIN(session->getLastReadTime(), lastIoTime); } if ((status & WRITER_IDLE) == WRITER_IDLE) { lastIoTime = ES_MIN(session->getLastWriteTime(), lastIoTime); } if (currTime - lastIoTime > (idlesecs * 1000)) { //shutdown socket by server. session->getSocket()->shutdownInput(); } } if (status_ == DISPOSED) { logger->info__(__FILE__, __LINE__, "disposed"); break; //! } } } catch (EInterruptedException& e) { logger->info__(__FILE__, __LINE__, "interrupted"); } catch (EThrowable& t) { logger->error__(__FILE__, __LINE__, t.toString().c_str()); } logger->info__(__FILE__, __LINE__, "exit clean fiber."); }); cleanFiber->setTag(tag); //tag: 1-N scheduler.schedule(cleanFiber); } void ESocketAcceptor::startStatistics(EFiberScheduler& scheduler) { sp<EFiber> statisticsFiber = new EFiberTarget([this](){ try { llong currentTime = ESystem::currentTimeMillis(); int count = 0; while (status_ == RUNNING || (connections_.value() > 0)) { int seconds = this->getStatistics()->getThroughputCalculationInterval(); sleep(seconds); //! currentTime += seconds * 1000; // do time rectification if (count > 100) { //100? currentTime = ESystem::currentTimeMillis(); count = 0; } this->getStatistics()->updateThroughput(currentTime); if (status_ == DISPOSED) { logger->info__(__FILE__, __LINE__, "disposed"); break; //! } } } catch (EInterruptedException& e) { logger->info__(__FILE__, __LINE__, "interrupted"); } catch (EThrowable& t) { logger->error__(__FILE__, __LINE__, t.toString().c_str()); } logger->info__(__FILE__, __LINE__, "exit statistics fiber."); }); statisticsFiber->setTag(0); //tag: 0 scheduler.schedule(statisticsFiber); } sp<ESocketSession> ESocketAcceptor::newSession(EIoService *service, sp<ESocket>& socket) { return new ESocketSession(this, socket); } void ESocketAcceptor::onListeningHandle() { if (listeningCallback_ != null) { scheduler.schedule([this](){ listeningCallback_(this); }); } } void ESocketAcceptor::onConnectionHandle(sp<ESocketSession>& session, Service* service) { if (connectionCallback_ != null) { try { connectionCallback_(session, service); } catch (EIOException& e) { logger->error__(__FILE__, __LINE__, e.toString().c_str()); } catch (...) { logger->error__(__FILE__, __LINE__, "error"); } } } } /* namespace naf */ } /* namespace efc */
27.563715
155
0.667294
cxxjava
4f7572f25a24783ea1d0458c363a9eafe796b0d3
513
cpp
C++
rpkg_src/gpudevice.cpp
RDIL/RPKG-Tool
fc516bf34dd994d2df58f0a405c292624ab421f1
[ "BSD-2-Clause" ]
9
2021-06-01T00:58:46.000Z
2022-02-16T12:44:15.000Z
rpkg_src/gpudevice.cpp
RDIL/RPKG-Tool
fc516bf34dd994d2df58f0a405c292624ab421f1
[ "BSD-2-Clause" ]
33
2021-06-02T17:55:16.000Z
2022-02-27T15:03:06.000Z
rpkg_src/gpudevice.cpp
RDIL/RPKG-Tool
fc516bf34dd994d2df58f0a405c292624ab421f1
[ "BSD-2-Clause" ]
17
2021-06-01T01:05:45.000Z
2022-01-30T12:19:53.000Z
#include "gpudevice.h" #include <iostream> gpudevice::gpudevice() { } ID3D11Device* gpudevice::get_device_d3d11() { if (!device) { D3D_FEATURE_LEVEL d3d_feature_level = D3D_FEATURE_LEVEL_11_0; HRESULT hresult = D3D11CreateDevice(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, NULL, &d3d_feature_level, 1, D3D11_SDK_VERSION, &device, NULL, &context); if (FAILED(hresult)) { LOG("Error: Failed to initialize DirectX 11 GPU Device."); } } return device; }
22.304348
155
0.664717
RDIL
4f75d7424357df50e8a3364b41f20430342655ea
9,762
cc
C++
chrome_frame/crash_reporting/nt_loader_unittest.cc
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
1
2015-10-12T09:14:22.000Z
2015-10-12T09:14:22.000Z
chrome_frame/crash_reporting/nt_loader_unittest.cc
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
null
null
null
chrome_frame/crash_reporting/nt_loader_unittest.cc
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
1
2020-11-04T07:22:28.000Z
2020-11-04T07:22:28.000Z
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome_frame/crash_reporting/nt_loader.h" #include <tlhelp32.h> #include <winnt.h> #include "base/at_exit.h" #include "base/environment.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop.h" #include "base/string_util.h" #include "base/sys_info.h" #include "base/threading/thread.h" #include "base/utf_string_conversions.h" #include "base/win/scoped_handle.h" #include "chrome_frame/crash_reporting/crash_dll.h" #include "gtest/gtest.h" namespace { void AssertIsCriticalSection(CRITICAL_SECTION* critsec) { // Assert on some of the internals of the debug info if it has one. RTL_CRITICAL_SECTION_DEBUG* debug = critsec->DebugInfo; if (debug) { ASSERT_EQ(RTL_CRITSECT_TYPE, debug->Type); ASSERT_EQ(critsec, debug->CriticalSection); } // TODO(siggi): assert on the semaphore handle & object type? } class ScopedEnterCriticalSection { public: explicit ScopedEnterCriticalSection(CRITICAL_SECTION* critsec) : critsec_(critsec) { ::EnterCriticalSection(critsec_); } ~ScopedEnterCriticalSection() { ::LeaveCriticalSection(critsec_); } private: CRITICAL_SECTION* critsec_; }; std::wstring FromUnicodeString(const UNICODE_STRING& str) { return std::wstring(str.Buffer, str.Length / sizeof(str.Buffer[0])); } } // namespace using namespace nt_loader; TEST(NtLoader, OwnsCriticalSection) { // Use of Thread requires an atexit manager. base::AtExitManager at_exit; CRITICAL_SECTION cs = {}; ::InitializeCriticalSection(&cs); EXPECT_FALSE(OwnsCriticalSection(&cs)); // Enter the critsec and assert we own it. { ScopedEnterCriticalSection lock1(&cs); EXPECT_TRUE(OwnsCriticalSection(&cs)); // Re-enter the critsec and assert we own it. ScopedEnterCriticalSection lock2(&cs); EXPECT_TRUE(OwnsCriticalSection(&cs)); } // Should no longer own it. EXPECT_FALSE(OwnsCriticalSection(&cs)); // Make another thread grab it. base::Thread other("Other threads"); ASSERT_TRUE(other.Start()); other.message_loop()->PostTask( FROM_HERE, NewRunnableFunction(::EnterCriticalSection, &cs)); base::win::ScopedHandle event(::CreateEvent(NULL, FALSE, FALSE, NULL)); other.message_loop()->PostTask( FROM_HERE, NewRunnableFunction(::SetEvent, event.Get())); ASSERT_EQ(WAIT_OBJECT_0, ::WaitForSingleObject(event.Get(), INFINITE)); // We still shouldn't own it - the other thread does. EXPECT_FALSE(OwnsCriticalSection(&cs)); // And we shouldn't be able to enter it. EXPECT_EQ(0, ::TryEnterCriticalSection(&cs)); // Make the other thread release it. other.message_loop()->PostTask( FROM_HERE, NewRunnableFunction(::LeaveCriticalSection, &cs)); other.Stop(); ::DeleteCriticalSection(&cs); } TEST(NtLoader, GetLoaderLock) { CRITICAL_SECTION* loader_lock = GetLoaderLock(); AssertIsCriticalSection(loader_lock); // We should be able to enter and leave the loader's lock without trouble. EnterCriticalSection(loader_lock); LeaveCriticalSection(loader_lock); } TEST(NtLoader, OwnsLoaderLock) { CRITICAL_SECTION* loader_lock = GetLoaderLock(); EXPECT_FALSE(OwnsLoaderLock()); EnterCriticalSection(loader_lock); EXPECT_TRUE(OwnsLoaderLock()); LeaveCriticalSection(loader_lock); EXPECT_FALSE(OwnsLoaderLock()); } TEST(NtLoader, GetLoaderEntry) { // Get all modules in the current process. base::win::ScopedHandle snap( ::CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, ::GetCurrentProcessId())); EXPECT_TRUE(snap.Get() != NULL); // Walk them, while checking we get an entry for each, and that it // contains sane information. MODULEENTRY32 module = { sizeof(module) }; ASSERT_TRUE(::Module32First(snap.Get(), &module)); do { ScopedEnterCriticalSection lock(GetLoaderLock()); nt_loader::LDR_DATA_TABLE_ENTRY* entry = nt_loader::GetLoaderEntry(module.hModule); ASSERT_TRUE(entry != NULL); EXPECT_EQ(module.hModule, reinterpret_cast<HMODULE>(entry->DllBase)); EXPECT_STREQ(module.szModule, FromUnicodeString(entry->BaseDllName).c_str()); EXPECT_STREQ(module.szExePath, FromUnicodeString(entry->FullDllName).c_str()); ULONG flags = entry->Flags; // All entries should have this flag set. EXPECT_TRUE(flags & LDRP_ENTRY_PROCESSED); if (0 == (flags & LDRP_IMAGE_DLL)) { // TODO(siggi): write a test to assert this holds true for loading // non-DLL, e.g. exe image files. // Dlls have the LDRP_IMAGE_DLL flag set, any module that doesn't // have that flag has to be the main executable. EXPECT_TRUE(module.hModule == ::GetModuleHandle(NULL)); } else { // Since we're not currently loading any modules, all loaded // modules should either have the LDRP_PROCESS_ATTACH_CALLED, // or a NULL entrypoint. if (entry->EntryPoint == NULL) { EXPECT_FALSE(flags & LDRP_PROCESS_ATTACH_CALLED); } else { // Shimeng.dll is an exception to the above, it's loaded // in a special way, see e.g. http://www.alex-ionescu.com/?p=41 // for details. bool is_shimeng = LowerCaseEqualsASCII( FromUnicodeString(entry->BaseDllName), "shimeng.dll"); EXPECT_TRUE(is_shimeng || (flags & LDRP_PROCESS_ATTACH_CALLED)); } } } while (::Module32Next(snap.Get(), &module)); } namespace { typedef void (*ExceptionFunction)(EXCEPTION_POINTERS* ex_ptrs); class NtLoaderTest: public testing::Test { public: NtLoaderTest() : veh_id_(NULL), exception_function_(NULL) { EXPECT_EQ(NULL, current_); current_ = this; } ~NtLoaderTest() { EXPECT_TRUE(this == current_); current_ = NULL; } void SetUp() { veh_id_ = ::AddVectoredExceptionHandler(FALSE, &ExceptionHandler); EXPECT_TRUE(veh_id_ != NULL); // Clear the crash DLL environment. scoped_ptr<base::Environment> env(base::Environment::Create()); env->UnSetVar(WideToASCII(kCrashOnLoadMode).c_str()); env->UnSetVar(WideToASCII(kCrashOnUnloadMode).c_str()); } void TearDown() { if (veh_id_ != NULL) EXPECT_NE(0, ::RemoveVectoredExceptionHandler(veh_id_)); // Clear the crash DLL environment. scoped_ptr<base::Environment> env(base::Environment::Create()); env->UnSetVar(WideToASCII(kCrashOnLoadMode).c_str()); env->UnSetVar(WideToASCII(kCrashOnUnloadMode).c_str()); } void set_exception_function(ExceptionFunction func) { exception_function_ = func; } private: static LONG NTAPI ExceptionHandler(EXCEPTION_POINTERS* ex_ptrs){ // Dispatch the exception to any exception function, // but only on the main thread. if (main_thread_ == ::GetCurrentThreadId() && current_ != NULL && current_->exception_function_ != NULL) current_->exception_function_(ex_ptrs); return ExceptionContinueSearch; } void* veh_id_; ExceptionFunction exception_function_; static NtLoaderTest* current_; static DWORD main_thread_; }; NtLoaderTest* NtLoaderTest::current_ = NULL; DWORD NtLoaderTest::main_thread_ = ::GetCurrentThreadId(); } // namespace static int exceptions_handled = 0; static void OnCrashDuringLoadLibrary(EXCEPTION_POINTERS* ex_ptrs) { ASSERT_EQ(STATUS_ACCESS_VIOLATION, ex_ptrs->ExceptionRecord->ExceptionCode); ASSERT_EQ(2, ex_ptrs->ExceptionRecord->NumberParameters); ASSERT_EQ(EXCEPTION_WRITE_FAULT, ex_ptrs->ExceptionRecord->ExceptionInformation[0]); ASSERT_EQ(kCrashAddress, ex_ptrs->ExceptionRecord->ExceptionInformation[1]); // Bump the exceptions count. exceptions_handled++; EXPECT_TRUE(OwnsLoaderLock()); HMODULE crash_dll = ::GetModuleHandle(kCrashDllName); ASSERT_TRUE(crash_dll != NULL); nt_loader::LDR_DATA_TABLE_ENTRY* entry = GetLoaderEntry(crash_dll); ASSERT_TRUE(entry != NULL); ASSERT_EQ(0, entry->Flags & LDRP_PROCESS_ATTACH_CALLED); } TEST_F(NtLoaderTest, CrashOnLoadLibrary) { exceptions_handled = 0; set_exception_function(OnCrashDuringLoadLibrary); // Setup to crash on load. scoped_ptr<base::Environment> env(base::Environment::Create()); env->SetVar(WideToASCII(kCrashOnLoadMode).c_str(), "1"); // And load it. HMODULE module = ::LoadLibrary(kCrashDllName); DWORD err = ::GetLastError(); EXPECT_EQ(NULL, module); EXPECT_EQ(ERROR_NOACCESS, err); EXPECT_EQ(1, exceptions_handled); if (module != NULL) ::FreeLibrary(module); } static void OnCrashDuringUnloadLibrary(EXCEPTION_POINTERS* ex_ptrs) { ASSERT_EQ(STATUS_ACCESS_VIOLATION, ex_ptrs->ExceptionRecord->ExceptionCode); ASSERT_EQ(2, ex_ptrs->ExceptionRecord->NumberParameters); ASSERT_EQ(EXCEPTION_WRITE_FAULT, ex_ptrs->ExceptionRecord->ExceptionInformation[0]); ASSERT_EQ(kCrashAddress, ex_ptrs->ExceptionRecord->ExceptionInformation[1]); // Bump the exceptions count. exceptions_handled++; EXPECT_TRUE(OwnsLoaderLock()); HMODULE crash_dll = ::GetModuleHandle(kCrashDllName); ASSERT_TRUE(crash_dll == NULL); nt_loader::LDR_DATA_TABLE_ENTRY* entry = GetLoaderEntry(crash_dll); ASSERT_TRUE(entry == NULL); } TEST_F(NtLoaderTest, CrashOnUnloadLibrary) { // Setup to crash on unload. scoped_ptr<base::Environment> env(base::Environment::Create()); env->SetVar(WideToASCII(kCrashOnUnloadMode).c_str(), "1"); // And load it. HMODULE module = ::LoadLibrary(kCrashDllName); EXPECT_TRUE(module != NULL); exceptions_handled = 0; set_exception_function(OnCrashDuringUnloadLibrary); // We should crash during unload. if (module != NULL) ::FreeLibrary(module); EXPECT_EQ(1, exceptions_handled); }
30.411215
78
0.719627
meego-tablet-ux
4f7751b309428a7d57d198ddb755ac7795b35fcc
12,895
hxx
C++
Base/Numerics/itktubeImageRegionMomentsCalculator.hxx
cdeepakroy/TubeTK
c39d1065bf10736a36a845cbd68749ff363f733f
[ "Apache-2.0" ]
1
2016-09-08T21:34:25.000Z
2016-09-08T21:34:25.000Z
Base/Numerics/itktubeImageRegionMomentsCalculator.hxx
cdeepakroy/TubeTK
c39d1065bf10736a36a845cbd68749ff363f733f
[ "Apache-2.0" ]
null
null
null
Base/Numerics/itktubeImageRegionMomentsCalculator.hxx
cdeepakroy/TubeTK
c39d1065bf10736a36a845cbd68749ff363f733f
[ "Apache-2.0" ]
null
null
null
/*========================================================================= Library: TubeTK Copyright 2010 Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. 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. =========================================================================*/ #ifndef __itktubeImageRegionMomentsCalculator_hxx #define __itktubeImageRegionMomentsCalculator_hxx #include "itktubeImageRegionMomentsCalculator.h" #include <itkImageRegionConstIteratorWithIndex.h> #include <vnl/algo/vnl_real_eigensystem.h> #include <vnl/algo/vnl_symmetric_eigensystem.h> namespace itk { namespace tube { class InvalidImageRegionMomentsError : public ExceptionObject { public: /* * Constructor. Needed to ensure the exception object can be copied. */ InvalidImageRegionMomentsError( const char *file, unsigned int lineNumber ) :ExceptionObject( file, lineNumber ) { this->SetDescription( "No valid image moments are availble." );} /* * Constructor. Needed to ensure the exception object can be copied. */ InvalidImageRegionMomentsError( const std::string& file, unsigned int lineNumber ) :ExceptionObject( file, lineNumber ) { this->SetDescription( "No valid image moments are availble." );} itkTypeMacro( InvalidImageRegionMomentsError, ExceptionObject ); }; // End class InvalidImageRegionMomentsError //---------------------------------------------------------------------- // Construct without computing moments template< class TImage > ImageRegionMomentsCalculator<TImage>::ImageRegionMomentsCalculator( void ) { m_Valid = false; m_Image = NULL; m_SpatialObjectMask = NULL; m_M0 = NumericTraits<ScalarType>::Zero; m_M1.Fill( NumericTraits<typename VectorType::ValueType>::Zero ); m_M2.Fill( NumericTraits<typename MatrixType::ValueType>::Zero ); m_Cg.Fill( NumericTraits<typename VectorType::ValueType>::Zero ); m_Cm.Fill( NumericTraits<typename MatrixType::ValueType>::Zero ); m_Pm.Fill( NumericTraits<typename VectorType::ValueType>::Zero ); m_Pa.Fill( NumericTraits<typename MatrixType::ValueType>::Zero ); m_UseRegionOfInterest = false; m_RegionOfInterestPoint1.Fill( 0 ); m_RegionOfInterestPoint2.Fill( 0 ); } //---------------------------------------------------------------------- // Destructor template< class TImage > ImageRegionMomentsCalculator<TImage>:: ~ImageRegionMomentsCalculator( void ) { } template< class TInputImage > void ImageRegionMomentsCalculator<TInputImage> ::PrintSelf( std::ostream& os, Indent indent ) const { Superclass::PrintSelf( os,indent ); os << indent << "Image: " << m_Image.GetPointer() << std::endl; os << indent << "Valid: " << m_Valid << std::endl; os << indent << "Zeroth Moment about origin: " << m_M0 << std::endl; os << indent << "First Moment about origin: " << m_M1 << std::endl; os << indent << "Second Moment about origin: " << m_M2 << std::endl; os << indent << "Center of Gravity: " << m_Cg << std::endl; os << indent << "Second central moments: " << m_Cm << std::endl; os << indent << "Principal Moments: " << m_Pm << std::endl; os << indent << "Principal axes: " << m_Pa << std::endl; os << indent << "Use RegionOfInterest : " << m_UseRegionOfInterest << std::endl; os << indent << "RegionOfInterest Point1: " << m_RegionOfInterestPoint1 << std::endl; os << indent << "RegionOfInterest Point2: " << m_RegionOfInterestPoint2 << std::endl; } //---------------------------------------------------------------------- // Compute moments for a new or modified image template< class TImage > void ImageRegionMomentsCalculator<TImage>:: Compute( void ) { m_M0 = NumericTraits<ScalarType>::Zero; m_M1.Fill( NumericTraits<typename VectorType::ValueType>::Zero ); m_M2.Fill( NumericTraits<typename MatrixType::ValueType>::Zero ); m_Cg.Fill( NumericTraits<typename VectorType::ValueType>::Zero ); m_Cm.Fill( NumericTraits<typename MatrixType::ValueType>::Zero ); typedef typename ImageType::IndexType IndexType; if( !m_Image ) { return; } ImageRegionConstIteratorWithIndex< ImageType > it( m_Image, m_Image->GetRequestedRegion() ); while( !it.IsAtEnd() ) { double value = it.Value(); IndexType indexPosition = it.GetIndex(); Point<double, ImageDimension> physicalPosition; m_Image->TransformIndexToPhysicalPoint( indexPosition, physicalPosition ); bool isInsideRegionOfInterest = true; if( m_UseRegionOfInterest ) { for( unsigned int i=0; i<ImageDimension; i++ ) { if( !( ( physicalPosition[i]<=m_RegionOfInterestPoint1[i] && physicalPosition[i]>=m_RegionOfInterestPoint2[i] ) || ( physicalPosition[i]<=m_RegionOfInterestPoint2[i] && physicalPosition[i]>=m_RegionOfInterestPoint1[i] ) ) ) { isInsideRegionOfInterest = false; break; } } } if( isInsideRegionOfInterest && ( m_SpatialObjectMask.IsNull() || m_SpatialObjectMask->IsInside( physicalPosition ) ) ) { m_M0 += value; for( unsigned int i=0; i<ImageDimension; i++ ) { m_M1[i] += static_cast<double>( indexPosition[i] ) * value; for( unsigned int j=0; j<ImageDimension; j++ ) { double weight = value * static_cast<double>( indexPosition[i] ) * static_cast<double>( indexPosition[j] ); m_M2[i][j] += weight; } } for( unsigned int i=0; i<ImageDimension; i++ ) { m_Cg[i] += physicalPosition[i] * value; for( unsigned int j=0; j<ImageDimension; j++ ) { double weight = value * physicalPosition[i] * physicalPosition[j]; m_Cm[i][j] += weight; } } } ++it; } // Throw an error if the total mass is zero if( m_M0 == 0.0 ) { itkExceptionMacro( << "Compute(): Total Mass of the image was zero. Aborting here to " << "prevent division by zero later on. " ); } // Normalize using the total mass for( unsigned int i=0; i<ImageDimension; i++ ) { m_Cg[i] /= m_M0; m_M1[i] /= m_M0; for( unsigned int j=0; j<ImageDimension; j++ ) { m_M2[i][j] /= m_M0; m_Cm[i][j] /= m_M0; } } // Center the second order moments for( unsigned int i=0; i<ImageDimension; i++ ) { for( unsigned int j=0; j<ImageDimension; j++ ) { m_M2[i][j] -= m_M1[i] * m_M1[j]; m_Cm[i][j] -= m_Cg[i] * m_Cg[j]; } } // Compute principal moments and axes vnl_symmetric_eigensystem<double> eigen( m_Cm.GetVnlMatrix() ); vnl_diag_matrix<double> pm = eigen.D; for( unsigned int i=0; i<ImageDimension; i++ ) { m_Pm[i] = pm( i,i ) * m_M0; } m_Pa = eigen.V.transpose(); // Add a final reflection if needed for a proper rotation, // by multiplying the last row by the determinant vnl_real_eigensystem eigenrot( m_Pa.GetVnlMatrix() ); vnl_diag_matrix< std::complex<double> > eigenval = eigenrot.D; std::complex<double> det( 1.0, 0.0 ); for( unsigned int i=0; i<ImageDimension; i++ ) { det *= eigenval( i, i ); } for( unsigned int i=0; i<ImageDimension; i++ ) { m_Pa[ ImageDimension-1 ][i] *= std::real( det ); } /* Remember that the moments are valid */ m_Valid = 1; } //--------------------------------------------------------------------- // Get sum of intensities template< class TImage > typename ImageRegionMomentsCalculator<TImage>::ScalarType ImageRegionMomentsCalculator<TImage>:: GetTotalMass( void ) const { if( !m_Valid ) { itkExceptionMacro( << "GetTotalMass() invoked, but the moments have not been computed." << " Call Compute() first." ); } return m_M0; } //-------------------------------------------------------------------- // Get first moments about origin, in index coordinates template< class TImage > typename ImageRegionMomentsCalculator<TImage>::VectorType ImageRegionMomentsCalculator<TImage>:: GetFirstMoments( void ) const { if( !m_Valid ) { itkExceptionMacro( << "GetFirstMoments() invoked, but the moments have not been computed. " << "Call Compute() first." ); } return m_M1; } //-------------------------------------------------------------------- // Get second moments about origin, in index coordinates template< class TImage > typename ImageRegionMomentsCalculator<TImage>::MatrixType ImageRegionMomentsCalculator<TImage>:: GetSecondMoments( void ) const { if( !m_Valid ) { itkExceptionMacro( << "GetSecondMoments() invoked, but the moments have not been computed. " << "Call Compute() first." ); } return m_M2; } //-------------------------------------------------------------------- // Get center of gravity, in physical coordinates template< class TImage > typename ImageRegionMomentsCalculator<TImage>::VectorType ImageRegionMomentsCalculator<TImage>:: GetCenterOfGravity( void ) const { if( !m_Valid ) { itkExceptionMacro( << "GetCenterOfGravity() invoked, but the moments have not been " << "computed. Call Compute() first." ); } return m_Cg; } //-------------------------------------------------------------------- // Get second central moments, in physical coordinates template< class TImage > typename ImageRegionMomentsCalculator<TImage>::MatrixType ImageRegionMomentsCalculator<TImage>:: GetCentralMoments( void ) const { if( !m_Valid ) { itkExceptionMacro( << "GetCentralMoments() invoked, but the moments have not been " << "computed. Call Compute() first." ); } return m_Cm; } //-------------------------------------------------------------------- // Get principal moments, in physical coordinates template< class TImage > typename ImageRegionMomentsCalculator<TImage>::VectorType ImageRegionMomentsCalculator<TImage>:: GetPrincipalMoments( void ) const { if( !m_Valid ) { itkExceptionMacro( << "GetPrincipalMoments() invoked, but the moments have not been " << "computed. Call Compute() first." ); } return m_Pm; } //-------------------------------------------------------------------- // Get principal axes, in physical coordinates template< class TImage > typename ImageRegionMomentsCalculator<TImage>::MatrixType ImageRegionMomentsCalculator<TImage>:: GetPrincipalAxes( void ) const { if( !m_Valid ) { itkExceptionMacro( << "GetPrincipalAxes() invoked, but the moments have not been computed." << " Call Compute() first." ); } return m_Pa; } //-------------------------------------------------------------------- // Get principal axes to physical axes transform template< class TImage > typename ImageRegionMomentsCalculator<TImage>::AffineTransformPointer ImageRegionMomentsCalculator<TImage>:: GetPrincipalAxesToPhysicalAxesTransform( void ) const { typename AffineTransformType::MatrixType matrix; typename AffineTransformType::OffsetType offset; for( unsigned int i = 0; i < ImageDimension; i++ ) { offset[i] = m_Cg [i]; for( unsigned int j = 0; j < ImageDimension; j++ ) { matrix[j][i] = m_Pa[i][j]; // Note the transposition } } AffineTransformPointer result = AffineTransformType::New(); result->SetMatrix( matrix ); result->SetOffset( offset ); return result; } //-------------------------------------------------------------------- // Get physical axes to principal axes transform template< class TImage > typename ImageRegionMomentsCalculator<TImage>::AffineTransformPointer ImageRegionMomentsCalculator<TImage>:: GetPhysicalAxesToPrincipalAxesTransform( void ) const { typename AffineTransformType::MatrixType matrix; typename AffineTransformType::OffsetType offset; for( unsigned int i = 0; i < ImageDimension; i++ ) { offset[i] = m_Cg [i]; for( unsigned int j = 0; j < ImageDimension; j++ ) { matrix[j][i] = m_Pa[i][j]; // Note the transposition } } AffineTransformPointer result = AffineTransformType::New(); result->SetMatrix( matrix ); result->SetOffset( offset ); AffineTransformPointer inverse = AffineTransformType::New(); result->GetInverse( inverse ); return inverse; } } // End namespace tube } // End namespace itk #endif // End !defined(__itktubeImageRegionMomentsCalculator_hxx)
30.412736
87
0.624661
cdeepakroy
4f78354412d0eba8e90e7628781c680e3a628d14
1,631
cpp
C++
LibCarla/source/test/client/test_rpc.cpp
simon0628/carla
b49664f94f87291be36805315593571678c8da28
[ "MIT" ]
12
2019-04-24T16:58:52.000Z
2022-01-22T07:48:55.000Z
LibCarla/source/test/client/test_rpc.cpp
simon0628/carla
b49664f94f87291be36805315593571678c8da28
[ "MIT" ]
1
2019-03-16T07:42:18.000Z
2019-03-16T10:10:52.000Z
LibCarla/source/test/client/test_rpc.cpp
simon0628/carla
b49664f94f87291be36805315593571678c8da28
[ "MIT" ]
11
2018-09-28T16:18:37.000Z
2022-01-04T06:02:05.000Z
// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma // de Barcelona (UAB). // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #include "test.h" #include <carla/MsgPackAdaptors.h> #include <carla/ThreadGroup.h> #include <carla/rpc/Actor.h> #include <carla/rpc/Client.h> #include <carla/rpc/Response.h> #include <carla/rpc/Server.h> #include <thread> using namespace carla::rpc; TEST(rpc, compilation_tests) { Server server(TESTING_PORT); server.BindSync("bind00", []() { return 2.0f; }); server.BindSync("bind01", [](int x) { return x; }); server.BindSync("bind02", [](int, float) { return 0.0; }); server.BindSync("bind03", [](int, float, double, char) {}); } TEST(rpc, server_bind_sync_run_on_game_thread) { const auto main_thread_id = std::this_thread::get_id(); const auto port = (TESTING_PORT != 0u ? TESTING_PORT : 2017u); Server server(port); server.BindSync("do_the_thing", [=](int x, int y) -> int { EXPECT_EQ(std::this_thread::get_id(), main_thread_id); return x + y; }); server.AsyncRun(1u); std::atomic_bool done{false}; carla::ThreadGroup threads; threads.CreateThread([&]() { Client client("localhost", port); for (auto i = 0; i < 300; ++i) { auto result = client.call("do_the_thing", i, 1).as<int>(); EXPECT_EQ(result, i + 1); } done = true; }); auto i = 0u; for (; i < 1'000'000u; ++i) { server.SyncRunFor(2ms); if (done) { break; } } std::cout << "game thread: run " << i << " slices.\n"; ASSERT_TRUE(done); }
25.484375
78
0.638259
simon0628
4f78fcbdbcfecf3b88c31ed3ff0fbf9f121bd590
1,592
hpp
C++
libraries/chain/include/dfcio/chain/reversible_block_object.hpp
DFChainLab/DFChain
cc85da9f3efb0dd56e9bb5ce5f08e1c7a217e0a6
[ "MIT" ]
null
null
null
libraries/chain/include/dfcio/chain/reversible_block_object.hpp
DFChainLab/DFChain
cc85da9f3efb0dd56e9bb5ce5f08e1c7a217e0a6
[ "MIT" ]
null
null
null
libraries/chain/include/dfcio/chain/reversible_block_object.hpp
DFChainLab/DFChain
cc85da9f3efb0dd56e9bb5ce5f08e1c7a217e0a6
[ "MIT" ]
null
null
null
/** * @file * @copyright defined in dfc/LICENSE */ #pragma once #include <dfcio/chain/types.hpp> #include <dfcio/chain/authority.hpp> #include <dfcio/chain/block_timestamp.hpp> #include <dfcio/chain/contract_types.hpp> #include "multi_index_includes.hpp" namespace dfcio { namespace chain { class reversible_block_object : public chainbase::object<reversible_block_object_type, reversible_block_object> { OBJECT_CTOR(reversible_block_object,(packedblock) ) id_type id; uint32_t blocknum = 0; shared_string packedblock; void set_block( const signed_block_ptr& b ) { packedblock.resize( fc::raw::pack_size( *b ) ); fc::datastream<char*> ds( packedblock.data(), packedblock.size() ); fc::raw::pack( ds, *b ); } signed_block_ptr get_block()const { fc::datastream<const char*> ds( packedblock.data(), packedblock.size() ); auto result = std::make_shared<signed_block>(); fc::raw::unpack( ds, *result ); return result; } }; struct by_num; using reversible_block_index = chainbase::shared_multi_index_container< reversible_block_object, indexed_by< ordered_unique<tag<by_id>, member<reversible_block_object, reversible_block_object::id_type, &reversible_block_object::id>>, ordered_unique<tag<by_num>, member<reversible_block_object, uint32_t, &reversible_block_object::blocknum>> > >; } } // dfcio::chain CHAINBASE_SET_INDEX_TYPE(dfcio::chain::reversible_block_object, dfcio::chain::reversible_block_index)
32.489796
133
0.690955
DFChainLab
4f79be36252f52468a78bbd3196652d3f94d5331
1,842
cxx
C++
test/run_html_escape.cxx
CM4all/beng-proxy
ce5a81f7969bc5cb6c5985cdc98f61ef8b5c6159
[ "BSD-2-Clause" ]
35
2017-08-16T06:52:26.000Z
2022-03-27T21:49:01.000Z
test/run_html_escape.cxx
nn6n/beng-proxy
2cf351da656de6fbace3048ee90a8a6a72f6165c
[ "BSD-2-Clause" ]
2
2017-12-22T15:34:23.000Z
2022-03-08T04:15:23.000Z
test/run_html_escape.cxx
nn6n/beng-proxy
2cf351da656de6fbace3048ee90a8a6a72f6165c
[ "BSD-2-Clause" ]
8
2017-12-22T15:11:47.000Z
2022-03-15T22:54:04.000Z
/* * Copyright 2007-2021 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "escape/HTML.hxx" #include "escape/Static.hxx" #include "util/StringView.hxx" #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char **argv) { if (argc != 2) exit(1); const char *p = argv[1]; const char *q = escape_static(&html_escape_class, p); if (q == NULL) { fprintf(stderr, "too long\n"); return EXIT_FAILURE; } printf("%s\n", q); }
34.111111
70
0.722584
CM4all
4f7b4d313256e34b165512de6dfba9427285ef06
297
cpp
C++
XYCodeScan/Classes/Tool/CodeGenerator/OCCodeGen/GPropInfo.cpp
shaktim888/obfTools
770a1177e0778c46ceab438719dc43594e618e22
[ "MIT" ]
null
null
null
XYCodeScan/Classes/Tool/CodeGenerator/OCCodeGen/GPropInfo.cpp
shaktim888/obfTools
770a1177e0778c46ceab438719dc43594e618e22
[ "MIT" ]
null
null
null
XYCodeScan/Classes/Tool/CodeGenerator/OCCodeGen/GPropInfo.cpp
shaktim888/obfTools
770a1177e0778c46ceab438719dc43594e618e22
[ "MIT" ]
null
null
null
// // GCPropInfo.cpp // HYCodeScan // // Created by admin on 2020/7/28. // #include "GPropInfo.hpp" namespace ocgen { PropInfo * PropInfo::copy() { auto p = new PropInfo(); p->name = name; p->ret = ret; p->readonly = readonly; p->writeonly = writeonly; return p; } }
14.142857
34
0.585859
shaktim888
4f7c4a7f2359b0b3ea9048eca441e32c093656b6
1,443
hpp
C++
sprout/type_traits/is_move_constructible.hpp
kevcadieux/Sprout
6b5addba9face0a6403e66e7db2aa94d87387f61
[ "BSL-1.0" ]
691
2015-01-15T18:52:23.000Z
2022-03-15T23:39:39.000Z
sprout/type_traits/is_move_constructible.hpp
kevcadieux/Sprout
6b5addba9face0a6403e66e7db2aa94d87387f61
[ "BSL-1.0" ]
22
2015-03-11T01:22:56.000Z
2021-03-29T01:51:45.000Z
sprout/type_traits/is_move_constructible.hpp
kevcadieux/Sprout
6b5addba9face0a6403e66e7db2aa94d87387f61
[ "BSL-1.0" ]
57
2015-03-11T07:52:29.000Z
2021-12-16T09:15:33.000Z
/*============================================================================= Copyright (c) 2011-2019 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout 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) =============================================================================*/ #ifndef SPROUT_TYPE_TRAITS_IS_MOVE_CONSTRUCTIBLE_HPP #define SPROUT_TYPE_TRAITS_IS_MOVE_CONSTRUCTIBLE_HPP #include <type_traits> #include <sprout/config.hpp> #include <sprout/type_traits/integral_constant.hpp> #include <sprout/type_traits/is_constructible.hpp> namespace sprout { // // is_move_constructible // namespace detail { template<typename T, bool = std::is_void<T>::value> struct is_move_constructible_impl : public sprout::false_type {}; template<typename T> struct is_move_constructible_impl<T, false> : public sprout::is_constructible<T, T&&> {}; } // namespace detail template<typename T> struct is_move_constructible : public sprout::detail::is_move_constructible_impl<T> {}; #if SPROUT_USE_VARIABLE_TEMPLATES template<typename T> SPROUT_STATIC_CONSTEXPR bool is_move_constructible_v = sprout::is_move_constructible<T>::value; #endif // #if SPROUT_USE_VARIABLE_TEMPLATES } // namespace sprout #endif // #ifndef SPROUT_TYPE_TRAITS_IS_MOVE_CONSTRUCTIBLE_HPP
34.357143
97
0.678448
kevcadieux
4f7c6b27475d593b448289c46b1ebeb3b35fade2
6,185
cpp
C++
bbs/valscan.cpp
k5jat/wwiv
b390e476c75f68e0f4f28c66d4a2eecd74753b7c
[ "Apache-2.0" ]
null
null
null
bbs/valscan.cpp
k5jat/wwiv
b390e476c75f68e0f4f28c66d4a2eecd74753b7c
[ "Apache-2.0" ]
null
null
null
bbs/valscan.cpp
k5jat/wwiv
b390e476c75f68e0f4f28c66d4a2eecd74753b7c
[ "Apache-2.0" ]
null
null
null
/**************************************************************************/ /* */ /* WWIV Version 5.x */ /* Copyright (C)1998-2017, WWIV Software Services */ /* */ /* 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 "bbs/valscan.h" #include <algorithm> #include "bbs/bbs.h" #include "bbs/com.h" #include "bbs/conf.h" #include "bbs/datetime.h" #include "bbs/bbsutl.h" #include "bbs/utility.h" #include "bbs/subacc.h" #include "bbs/input.h" #include "bbs/msgbase1.h" #include "bbs/read_message.h" #include "core/strings.h" #include "sdk/subxtr.h" #include "sdk/user.h" using namespace wwiv::core; using namespace wwiv::sdk; using namespace wwiv::strings; void valscan() { // Must be local cosysop or better if (!lcs()) { return; } int ac = 0; auto os = a()->current_user_sub_num(); if (a()->uconfsub[1].confnum != -1 && okconf(a()->user())) { ac = 1; tmp_disable_conf(true); } bool done = false; for (size_t sn = 0; sn < a()->subs().subs().size() && !a()->hangup_ && !done; sn++) { if (!iscan(sn)) { continue; } if (a()->GetCurrentReadMessageArea() < 0) { return; } uint32_t sq = a()->context().qsc_p[sn]; // Must be sub with validation "on" if (a()->current_sub().nets.empty() || !(a()->current_sub().anony & anony_val_net)) { continue; } bout.nl(); bout.Color(2); bout.clreol(); bout << "{{ ValScanning " << a()->current_sub().name << " }}\r\n"; bout.clear_lines_listed(); bout.clreol(); bout.move_up_if_newline(2); for (int i = 1; i <= a()->GetNumMessagesInCurrentMessageArea() && !a()->hangup_ && !done; i++) { // was i = 0 if (get_post(i)->status & status_pending_net) { CheckForHangup(); a()->tleft(true); if (i > 0 && i <= a()->GetNumMessagesInCurrentMessageArea()) { bool next; int val; read_post(i, &next, &val); bout << "|#4[|#4Subboard: " << a()->current_sub().name << "|#1]\r\n"; bout << "|#1D|#9)elete, |#1R|#9)eread |#1V|#9)alidate, |#1M|#9)ark Validated, |#1Q|#9)uit: |#2"; char ch = onek("QDVMR"); switch (ch) { case 'Q': done = true; break; case 'R': i--; continue; case 'V': { open_sub(true); resynch(&i, nullptr); postrec *p1 = get_post(i); p1->status &= ~status_pending_net; write_post(i, p1); close_sub(); send_net_post(p1, a()->current_sub()); bout.nl(); bout << "|#7Message sent.\r\n\n"; } break; case 'M': if (lcs() && i > 0 && i <= a()->GetNumMessagesInCurrentMessageArea() && a()->current_sub().anony & anony_val_net && !a()->current_sub().nets.empty()) { wwiv::bbs::OpenSub opened_sub(true); resynch(&i, nullptr); postrec *p1 = get_post(i); p1->status &= ~status_pending_net; write_post(i, p1); bout.nl(); bout << "|#9Not set for net pending now.\r\n\n"; } break; case 'D': if (lcs()) { if (i > 0) { open_sub(true); resynch(&i, nullptr); postrec p2 = *get_post(i); delete_message(i); close_sub(); if (p2.ownersys == 0) { User tu; a()->users()->readuser(&tu, p2.owneruser); if (!tu.IsUserDeleted()) { if (date_to_daten(tu.GetFirstOn()) < p2.daten) { bout.nl(); bout << "|#2Remove how many posts credit? "; char szNumCredits[ 11 ]; input(szNumCredits, 3, true); int num_post_credits = 1; if (szNumCredits[0]) { num_post_credits = to_number<int>(szNumCredits); } num_post_credits = std::min<int>(tu.GetNumMessagesPosted(), num_post_credits); if (num_post_credits) { tu.SetNumMessagesPosted(tu.GetNumMessagesPosted() - static_cast<uint16_t>(num_post_credits)); } bout.nl(); bout << "|#3Post credit removed = " << num_post_credits << wwiv::endl; tu.SetNumDeletedPosts(tu.GetNumDeletedPosts() + 1); a()->users()->writeuser(&tu, p2.owneruser); a()->UpdateTopScreen(); } } } resynch(&i, &p2); } } break; } } } } a()->context().qsc_p[sn] = sq; } if (ac) { tmp_disable_conf(false); } a()->set_current_user_sub_num(os); bout.nl(2); }
35.342857
117
0.437025
k5jat
4f7c6da74782243aa2b25067279d78cf0e531ab6
1,606
hpp
C++
llvm/tools/clang/test/CodeGen/tvm/SMVStats.hpp
VasiliyKuznetsov/TON-Compiler
0573a06d03a2ee5618ff5f9be69738f17103db3d
[ "Apache-2.0" ]
null
null
null
llvm/tools/clang/test/CodeGen/tvm/SMVStats.hpp
VasiliyKuznetsov/TON-Compiler
0573a06d03a2ee5618ff5f9be69738f17103db3d
[ "Apache-2.0" ]
null
null
null
llvm/tools/clang/test/CodeGen/tvm/SMVStats.hpp
VasiliyKuznetsov/TON-Compiler
0573a06d03a2ee5618ff5f9be69738f17103db3d
[ "Apache-2.0" ]
null
null
null
#pragma once #include <tvm/schema/message.hpp> #include <tvm/dict_array.hpp> #include <tvm/log_sequence.hpp> #include <tvm/replay_attack_protection/timestamp.hpp> #include <tvm/smart_switcher.hpp> namespace tvm { namespace schema { // For internal purposes (fixed-size address) struct TransferRecord { uint256 proposalId; addr_std_fixed contestAddr; uint256 requestValue; }; // For getter (reconstructed address) struct Transfer { uint256 proposalId; address contestAddr; uint256 requestValue; }; __interface [[no_pubkey]] ISMVStats { [[internal, external, dyn_chain_parse]] void constructor(address SMV_root); [[internal, noaccept, answer_id]] bool_t registerTransfer(uint256 proposalId, address contestAddr, uint256 requestValue); // ============== getters ============== [[getter]] dict_array<Transfer> getTransfers(); }; struct DSMVStats { address SMV_root_; log_sequence<TransferRecord> transfers_; Grams start_balance_; }; struct ESMVStats {}; static constexpr unsigned STATS_TIMESTAMP_DELAY = 1800; using stats_replay_protection_t = replay_attack_protection::timestamp<STATS_TIMESTAMP_DELAY>; inline std::pair<StateInit, uint256> prepare_stats_state_init_and_addr(DSMVStats data, cell code) { cell data_cl = prepare_persistent_data<ISMVStats, stats_replay_protection_t, DSMVStats>( { stats_replay_protection_t::init() }, data); StateInit init { /*split_depth*/{}, /*special*/{}, code, data_cl, /*library*/{} }; cell init_cl = build(init).make_cell(); return { init, uint256(tvm_hash(init_cl)) }; } }} // namespace tvm::schema
25.492063
93
0.737858
VasiliyKuznetsov
4f7fd670857b4e95754cec14106377024843362b
9,263
cc
C++
ccc/src/model/ListJobStatusResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
null
null
null
ccc/src/model/ListJobStatusResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
null
null
null
ccc/src/model/ListJobStatusResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
1
2020-11-27T09:13:12.000Z
2020-11-27T09:13:12.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/ccc/model/ListJobStatusResult.h> #include <json/json.h> using namespace AlibabaCloud::CCC; using namespace AlibabaCloud::CCC::Model; ListJobStatusResult::ListJobStatusResult() : ServiceResult() {} ListJobStatusResult::ListJobStatusResult(const std::string &payload) : ServiceResult() { parse(payload); } ListJobStatusResult::~ListJobStatusResult() {} void ListJobStatusResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto jobsNode = value["Jobs"]; if(!jobsNode["TotalCount"].isNull()) jobs_.totalCount = std::stoi(jobsNode["TotalCount"].asString()); if(!jobsNode["PageNumber"].isNull()) jobs_.pageNumber = std::stoi(jobsNode["PageNumber"].asString()); if(!jobsNode["PageSize"].isNull()) jobs_.pageSize = std::stoi(jobsNode["PageSize"].asString()); auto allListNode = jobsNode["List"]["Job"]; for (auto jobsNodeListJob : allListNode) { Jobs::Job jobObject; if(!jobsNodeListJob["JobId"].isNull()) jobObject.jobId = jobsNodeListJob["JobId"].asString(); if(!jobsNodeListJob["GroupId"].isNull()) jobObject.groupId = jobsNodeListJob["GroupId"].asString(); if(!jobsNodeListJob["ScenarioId"].isNull()) jobObject.scenarioId = jobsNodeListJob["ScenarioId"].asString(); if(!jobsNodeListJob["StrategyId"].isNull()) jobObject.strategyId = jobsNodeListJob["StrategyId"].asString(); if(!jobsNodeListJob["Priority"].isNull()) jobObject.priority = std::stoi(jobsNodeListJob["Priority"].asString()); if(!jobsNodeListJob["Status"].isNull()) jobObject.status = jobsNodeListJob["Status"].asString(); if(!jobsNodeListJob["ReferenceId"].isNull()) jobObject.referenceId = jobsNodeListJob["ReferenceId"].asString(); if(!jobsNodeListJob["FailureReason"].isNull()) jobObject.failureReason = jobsNodeListJob["FailureReason"].asString(); auto allContactsNode = allListNode["Contacts"]["Contact"]; for (auto allListNodeContactsContact : allContactsNode) { Jobs::Job::Contact contactsObject; if(!allListNodeContactsContact["ContactId"].isNull()) contactsObject.contactId = allListNodeContactsContact["ContactId"].asString(); if(!allListNodeContactsContact["ContactName"].isNull()) contactsObject.contactName = allListNodeContactsContact["ContactName"].asString(); if(!allListNodeContactsContact["Honorific"].isNull()) contactsObject.honorific = allListNodeContactsContact["Honorific"].asString(); if(!allListNodeContactsContact["Role"].isNull()) contactsObject.role = allListNodeContactsContact["Role"].asString(); if(!allListNodeContactsContact["PhoneNumber"].isNull()) contactsObject.phoneNumber = allListNodeContactsContact["PhoneNumber"].asString(); if(!allListNodeContactsContact["State"].isNull()) contactsObject.state = allListNodeContactsContact["State"].asString(); if(!allListNodeContactsContact["ReferenceId"].isNull()) contactsObject.referenceId = allListNodeContactsContact["ReferenceId"].asString(); if(!allListNodeContactsContact["JobId"].isNull()) contactsObject.jobId = allListNodeContactsContact["JobId"].asString(); jobObject.contacts.push_back(contactsObject); } auto allExtrasNode = allListNode["Extras"]["KeyValuePair"]; for (auto allListNodeExtrasKeyValuePair : allExtrasNode) { Jobs::Job::KeyValuePair extrasObject; if(!allListNodeExtrasKeyValuePair["Key"].isNull()) extrasObject.key = allListNodeExtrasKeyValuePair["Key"].asString(); if(!allListNodeExtrasKeyValuePair["Value"].isNull()) extrasObject.value = allListNodeExtrasKeyValuePair["Value"].asString(); jobObject.extras.push_back(extrasObject); } auto allTasksNode = allListNode["Tasks"]["Task"]; for (auto allListNodeTasksTask : allTasksNode) { Jobs::Job::Task tasksObject; if(!allListNodeTasksTask["TaskId"].isNull()) tasksObject.taskId = allListNodeTasksTask["TaskId"].asString(); if(!allListNodeTasksTask["JobId"].isNull()) tasksObject.jobId = allListNodeTasksTask["JobId"].asString(); if(!allListNodeTasksTask["ScenarioId"].isNull()) tasksObject.scenarioId = allListNodeTasksTask["ScenarioId"].asString(); if(!allListNodeTasksTask["ChatbotId"].isNull()) tasksObject.chatbotId = allListNodeTasksTask["ChatbotId"].asString(); if(!allListNodeTasksTask["PlanedTime"].isNull()) tasksObject.planedTime = std::stol(allListNodeTasksTask["PlanedTime"].asString()); if(!allListNodeTasksTask["ActualTime"].isNull()) tasksObject.actualTime = std::stol(allListNodeTasksTask["ActualTime"].asString()); if(!allListNodeTasksTask["CallingNumber"].isNull()) tasksObject.callingNumber = allListNodeTasksTask["CallingNumber"].asString(); if(!allListNodeTasksTask["CalledNumber"].isNull()) tasksObject.calledNumber = allListNodeTasksTask["CalledNumber"].asString(); if(!allListNodeTasksTask["CallId"].isNull()) tasksObject.callId = allListNodeTasksTask["CallId"].asString(); if(!allListNodeTasksTask["Status"].isNull()) tasksObject.status = allListNodeTasksTask["Status"].asString(); if(!allListNodeTasksTask["Brief"].isNull()) tasksObject.brief = allListNodeTasksTask["Brief"].asString(); if(!allListNodeTasksTask["Duration"].isNull()) tasksObject.duration = std::stoi(allListNodeTasksTask["Duration"].asString()); auto contact1Node = value["Contact"]; if(!contact1Node["ContactId"].isNull()) tasksObject.contact1.contactId = contact1Node["ContactId"].asString(); if(!contact1Node["ContactName"].isNull()) tasksObject.contact1.contactName = contact1Node["ContactName"].asString(); if(!contact1Node["Honorific"].isNull()) tasksObject.contact1.honorific = contact1Node["Honorific"].asString(); if(!contact1Node["Role"].isNull()) tasksObject.contact1.role = contact1Node["Role"].asString(); if(!contact1Node["PhoneNumber"].isNull()) tasksObject.contact1.phoneNumber = contact1Node["PhoneNumber"].asString(); if(!contact1Node["State"].isNull()) tasksObject.contact1.state = contact1Node["State"].asString(); if(!contact1Node["ReferenceId"].isNull()) tasksObject.contact1.referenceId = contact1Node["ReferenceId"].asString(); if(!contact1Node["JobId"].isNull()) tasksObject.contact1.jobId = contact1Node["JobId"].asString(); jobObject.tasks.push_back(tasksObject); } auto allSummaryNode = allListNode["Summary"]["SummaryItem"]; for (auto allListNodeSummarySummaryItem : allSummaryNode) { Jobs::Job::SummaryItem summaryObject; if(!allListNodeSummarySummaryItem["SummaryId"].isNull()) summaryObject.summaryId = allListNodeSummarySummaryItem["SummaryId"].asString(); if(!allListNodeSummarySummaryItem["GroupId"].isNull()) summaryObject.groupId = allListNodeSummarySummaryItem["GroupId"].asString(); if(!allListNodeSummarySummaryItem["JobId"].isNull()) summaryObject.jobId = allListNodeSummarySummaryItem["JobId"].asString(); if(!allListNodeSummarySummaryItem["TaskId"].isNull()) summaryObject.taskId = allListNodeSummarySummaryItem["TaskId"].asString(); if(!allListNodeSummarySummaryItem["ConversationDetailId"].isNull()) summaryObject.conversationDetailId = allListNodeSummarySummaryItem["ConversationDetailId"].asString(); if(!allListNodeSummarySummaryItem["Category"].isNull()) summaryObject.category = allListNodeSummarySummaryItem["Category"].asString(); if(!allListNodeSummarySummaryItem["SummaryName"].isNull()) summaryObject.summaryName = allListNodeSummarySummaryItem["SummaryName"].asString(); if(!allListNodeSummarySummaryItem["Content"].isNull()) summaryObject.content = allListNodeSummarySummaryItem["Content"].asString(); jobObject.summary.push_back(summaryObject); } auto allCallingNumbers = value["CallingNumbers"]["String"]; for (auto value : allCallingNumbers) jobObject.callingNumbers.push_back(value.asString()); jobs_.list.push_back(jobObject); } if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; if(!value["Code"].isNull()) code_ = value["Code"].asString(); if(!value["Message"].isNull()) message_ = value["Message"].asString(); if(!value["HttpStatusCode"].isNull()) httpStatusCode_ = std::stoi(value["HttpStatusCode"].asString()); } std::string ListJobStatusResult::getMessage()const { return message_; } ListJobStatusResult::Jobs ListJobStatusResult::getJobs()const { return jobs_; } int ListJobStatusResult::getHttpStatusCode()const { return httpStatusCode_; } std::string ListJobStatusResult::getCode()const { return code_; } bool ListJobStatusResult::getSuccess()const { return success_; }
43.900474
106
0.74749
iamzken
4f80888d2bd2db3fc8cb7731943e5bb37f289548
3,853
cpp
C++
liero/replay_to_video.cpp
lauri-kaariainen/emscripten_openliero
ab3268237c7084e00f3bccb4442f0ad7762d8419
[ "BSD-2-Clause" ]
null
null
null
liero/replay_to_video.cpp
lauri-kaariainen/emscripten_openliero
ab3268237c7084e00f3bccb4442f0ad7762d8419
[ "BSD-2-Clause" ]
2
2015-02-11T09:43:33.000Z
2015-02-11T17:57:58.000Z
liero/replay_to_video.cpp
lauri-kaariainen/emscripten_openliero
ab3268237c7084e00f3bccb4442f0ad7762d8419
[ "BSD-2-Clause" ]
null
null
null
#include "replay_to_video.hpp" #include <string> #include "replay.hpp" #include "filesystem.hpp" #include "reader.hpp" #include "mixer/player.hpp" #include "game.hpp" #include "gfx/renderer.hpp" #include "text.hpp" //#include <gvl/io/fstream.hpp> #include <gvl/io2/fstream.hpp> #include <memory> extern "C" { #include "video_recorder.h" #include "tl/vector.h" #include "mixer/mixer.h" } void replayToVideo( gvl::shared_ptr<Common> const& common, std::string const& fullPath, std::string const& replayVideoName) { auto replay( gvl::to_source(new gvl::file_bucket_source(fullPath.c_str(), "rb"))); ReplayReader replayReader(replay); Renderer renderer; renderer.init(); renderer.loadPalette(*common); std::string fullVideoPath = joinPath(lieroEXERoot, replayVideoName); sfx_mixer* mixer = sfx_mixer_create(); std::auto_ptr<Game> game( replayReader.beginPlayback(common, gvl::shared_ptr<SoundPlayer>(new RecordSoundPlayer(*common, mixer)))); //game->soundPlayer.reset(new RecordSoundPlayer(*common, mixer)); game->startGame(); game->focus(renderer); int w = 1280, h = 720; AVRational framerate; framerate.num = 1; framerate.den = 30; AVRational nativeFramerate; nativeFramerate.num = 1; nativeFramerate.den = 70; av_register_all(); video_recorder vidrec; vidrec_init(&vidrec, fullVideoPath.c_str(), w, h, framerate); tl_vector soundBuffer; tl_vector_new_empty(soundBuffer); std::size_t audioCodecFrames = 1024; AVRational sampleDebt; sampleDebt.num = 0; sampleDebt.den = 70; AVRational frameDebt; frameDebt.num = 0; frameDebt.den = 1; uint32_t scaleFilter = Settings::SfNearest; int offsetX, offsetY; int mag = fitScreen(w, h, renderer.screenBmp.w, renderer.screenBmp.h, offsetX, offsetY, scaleFilter); printf("\n"); int f = 0; while(replayReader.playbackFrame(renderer)) { game->processFrame(); renderer.clear(); game->draw(renderer, true); ++f; renderer.fadeValue = 33; sampleDebt.num += 44100; // sampleDebt += 44100 / 70 int mixerFrames = sampleDebt.num / sampleDebt.den; // floor(sampleDebt) sampleDebt.num -= mixerFrames * sampleDebt.den; // sampleDebt -= mixerFrames std::size_t mixerStart = soundBuffer.size; tl_vector_reserve(soundBuffer, int16_t, soundBuffer.size + mixerFrames); sfx_mixer_mix(mixer, tl_vector_idx(soundBuffer, int16_t, mixerStart), mixerFrames); tl_vector_post_enlarge(soundBuffer, int16_t, mixerFrames); { int16_t* audioSamples = tl_vector_idx(soundBuffer, int16_t, 0); std::size_t samplesLeft = soundBuffer.size; while (samplesLeft > audioCodecFrames) { vidrec_write_audio_frame(&vidrec, audioSamples, audioCodecFrames); audioSamples += audioCodecFrames; samplesLeft -= audioCodecFrames; } frameDebt = av_add_q(frameDebt, nativeFramerate); if (av_cmp_q(frameDebt, framerate) > 0) { frameDebt = av_sub_q(frameDebt, framerate); Color realPal[256]; renderer.pal.activate(realPal); PalIdx* src = renderer.screenBmp.pixels; std::size_t destPitch = vidrec.tmp_picture->linesize[0]; uint8_t* dest = vidrec.tmp_picture->data[0] + offsetY * destPitch + offsetX * 4; std::size_t srcPitch = renderer.screenBmp.pitch; uint32_t pal32[256]; preparePaletteBgra(realPal, pal32); scaleDraw(src, 320, 200, srcPitch, dest, destPitch, mag, scaleFilter, pal32); vidrec_write_video_frame(&vidrec, vidrec.tmp_picture); } // Move rest to the beginning of the buffer assert(audioSamples + samplesLeft == tl_vector_idx(soundBuffer, int16_t, soundBuffer.size)); memmove(soundBuffer.impl, audioSamples, samplesLeft * sizeof(int16_t)); soundBuffer.size = samplesLeft; } if ((f % (70 * 5)) == 0) { printf("\r%s", timeToStringFrames(f)); } } tl_vector_free(soundBuffer); vidrec_finalize(&vidrec); }
26.390411
102
0.715806
lauri-kaariainen
4f82ae812df5d868f5e74deebea9eb86f9c10fc2
1,010
cxx
C++
Applications/VpView/vpFilterTypeDelegate.cxx
PinkDiamond1/vivia
70f7fbed4b33b14d34de35c69b2b14df3514d720
[ "BSD-3-Clause" ]
14
2016-09-16T12:33:05.000Z
2021-02-14T02:16:33.000Z
Applications/VpView/vpFilterTypeDelegate.cxx
PinkDiamond1/vivia
70f7fbed4b33b14d34de35c69b2b14df3514d720
[ "BSD-3-Clause" ]
44
2016-10-06T22:12:57.000Z
2021-01-07T19:39:07.000Z
Applications/VpView/vpFilterTypeDelegate.cxx
PinkDiamond1/vivia
70f7fbed4b33b14d34de35c69b2b14df3514d720
[ "BSD-3-Clause" ]
17
2015-06-30T13:41:47.000Z
2021-11-22T17:38:48.000Z
// This file is part of ViViA, and is distributed under the // OSI-approved BSD 3-Clause License. See top-level LICENSE file or // https://github.com/Kitware/vivia/blob/master/LICENSE for details. #include "vpFilterTypeDelegate.h" #include "vtkVgTemporalFilters.h" #include <QComboBox> namespace { const vtkVgTemporalFilters::FilterType Types[] = { vtkVgTemporalFilters::FT_Select, vtkVgTemporalFilters::FT_Exclude }; enum { NumTypes = sizeof(Types) / sizeof(Types[0]) }; } // end anonymous namespace //----------------------------------------------------------------------------- vpFilterTypeDelegate::vpFilterTypeDelegate(QObject* parent) : qtComboBoxDelegate(parent) { QVariantList vl; QStringList sl; for (int i = 0; i < NumTypes; ++i) { vl << Types[i]; sl << vtkVgTemporalFilters::StringForType(Types[i]); } this->setMapping(sl, vl); } //----------------------------------------------------------------------------- vpFilterTypeDelegate::~vpFilterTypeDelegate() { }
24.047619
79
0.608911
PinkDiamond1
4f836635c73ec66724b0b1a8cec1c838763acd60
9,357
cpp
C++
openstudiocore/src/model/test/EnergyManagementSystemSensor_GTest.cpp
hellok-coder/OS-Testing
e9e18ad9e99f709a3f992601ed8d2e0662175af4
[ "blessing" ]
1
2019-11-12T02:07:03.000Z
2019-11-12T02:07:03.000Z
openstudiocore/src/model/test/EnergyManagementSystemSensor_GTest.cpp
hellok-coder/OS-Testing
e9e18ad9e99f709a3f992601ed8d2e0662175af4
[ "blessing" ]
1
2019-02-04T23:30:45.000Z
2019-02-04T23:30:45.000Z
openstudiocore/src/model/test/EnergyManagementSystemSensor_GTest.cpp
hellok-coder/OS-Testing
e9e18ad9e99f709a3f992601ed8d2e0662175af4
[ "blessing" ]
null
null
null
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2019, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED * STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 <gtest/gtest.h> #include "ModelFixture.hpp" #include "../Building.hpp" #include "../Building_Impl.hpp" #include "../PlantLoop.hpp" #include "../Node.hpp" #include "../Node_Impl.hpp" #include "../AvailabilityManagerHighTemperatureTurnOff.hpp" #include "../AvailabilityManagerHighTemperatureTurnOff_Impl.hpp" #include "../ThermalZone.hpp" #include "../EnergyManagementSystemSensor.hpp" #include "../EnergyManagementSystemSensor_Impl.hpp" #include "../OutputVariable.hpp" #include "../OutputVariable_Impl.hpp" #include "../OutputMeter.hpp" #include "../OutputMeter_Impl.hpp" #include "../Model.hpp" #include "../Model_Impl.hpp" #include "../../utilities/idd/IddEnums.hpp" #include "../../utilities/idf/ValidityReport.hpp" #include "../../utilities/idf/IdfObject.hpp" #include "../../utilities/data/TimeSeries.hpp" #include "../../utilities/core/Compare.hpp" #include "../../utilities/core/Optional.hpp" using namespace openstudio; using namespace openstudio::model; using std::string; TEST_F(ModelFixture, EMSSensor_EMSSensor) { Model model; Building building = model.getUniqueModelObject<Building>(); ThermalZone zone1(model); ThermalZone zone2(model); // add Site Outdoor Air Drybulb Temperature OutputVariable siteOutdoorAirDrybulbTemperature("Site Outdoor Air Drybulb Temperature", model); EXPECT_EQ("*", siteOutdoorAirDrybulbTemperature.keyValue()); EXPECT_EQ("Site Outdoor Air Drybulb Temperature", siteOutdoorAirDrybulbTemperature.variableName()); // add sensor EnergyManagementSystemSensor OATdbSensor(model, siteOutdoorAirDrybulbTemperature); OATdbSensor.setName("OATdb Sensor"); //OATdbSensor.setOutputVariable(siteOutdoorAirDrybulbTemperature); EXPECT_EQ("OATdb_Sensor", OATdbSensor.nameString()); EXPECT_EQ(siteOutdoorAirDrybulbTemperature.handle(), OATdbSensor.outputVariable().get().handle() ); EXPECT_EQ(siteOutdoorAirDrybulbTemperature, OATdbSensor.outputVariable()); EXPECT_EQ("", OATdbSensor.keyName()); // add zone Temperature OutputVariable zoneTemperature("Zone Air Temperature", model); zoneTemperature.setKeyValue(zone1.nameString()); EXPECT_EQ(zone1.nameString(), zoneTemperature.keyValue()); EXPECT_EQ("Zone Air Temperature", zoneTemperature.variableName()); // add sensor EnergyManagementSystemSensor zoneSensor(model, zoneTemperature); zoneSensor.setName("Zone Sensor"); EXPECT_EQ("Zone_Sensor", zoneSensor.nameString()); EXPECT_EQ(zoneTemperature.handle(), zoneSensor.outputVariable().get().handle()); EXPECT_EQ(zoneTemperature, zoneSensor.outputVariable()); EXPECT_EQ(zone1.nameString(), zoneSensor.keyName()); // add Zone Lights Electric Power to both zones OutputVariable lightsElectricPower("Zone Lights Electric Power", model); EXPECT_EQ("*", lightsElectricPower.keyValue()); EXPECT_EQ("Zone Lights Electric Power", lightsElectricPower.variableName()); // add light sensor on zone1 EnergyManagementSystemSensor lights(model, lightsElectricPower); lights.setName("Light Sensor"); //lights.setOutputVariable(lightsElectricPower); lights.setKeyName(zone1.name().get()); EXPECT_EQ(zone1.name().get(), lights.keyName()); EXPECT_EQ("Light_Sensor", lights.nameString()); // create meter OutputMeter meter(model); meter.setName("test meter"); //add sensor to meter EnergyManagementSystemSensor meter_sensor(model, meter); meter_sensor.setName("meter sensor"); //meter_sensor.setOutputMeter(meter); EXPECT_EQ("meter_sensor", meter_sensor.nameString()); EXPECT_EQ(meter.handle(), meter_sensor.outputMeter().get().handle()); EXPECT_EQ(meter, meter_sensor.outputMeter()); EXPECT_EQ("", meter_sensor.keyName()); ASSERT_TRUE(OATdbSensor.outputVariable()); ASSERT_FALSE(OATdbSensor.outputMeter()); siteOutdoorAirDrybulbTemperature.remove(); boost::optional<ModelObject> object = model.getModelObjectByName<ModelObject>("OATdb_Sensor"); ASSERT_FALSE(object); ASSERT_TRUE(meter_sensor.outputMeter()); ASSERT_FALSE(meter_sensor.outputVariable()); meter.remove(); object = model.getModelObjectByName<ModelObject>("meter sensor"); ASSERT_FALSE(object); // add sensor by string EnergyManagementSystemSensor sensor_string(model, "Sensor String"); sensor_string.setName("Sensor String Name"); EXPECT_EQ("Sensor_String_Name", sensor_string.nameString()); EXPECT_EQ("Sensor String", sensor_string.outputVariableOrMeterName()); } TEST_F(ModelFixture, EMSSensorOutVar) { Model model; Building building = model.getUniqueModelObject<Building>(); // add output variable 1 OutputVariable outvar1("VRF Heat Pump Heating Electric Energy", model); outvar1.setName("residential mini split vrf heat energy output var"); outvar1.setKeyValue(""); //EXPECT_EQ("", outvar1.keyValue()); EXPECT_EQ("VRF Heat Pump Heating Electric Energy", outvar1.variableName()); EXPECT_EQ("residential mini split vrf heat energy output var", outvar1.nameString()); // add sensor 1 EnergyManagementSystemSensor sensor1(model, outvar1); sensor1.setName("residential_mini_split_vrf_energy_sensor"); sensor1.setKeyName("living zone Multi Split Heat Pump"); // add output variable 2 OutputVariable outvar2("VRF Heat Pump Heating Electric Energy", model); outvar2.setName("residential mini split|unit 2 vrf heat energy output var"); outvar2.setKeyValue(""); //EXPECT_EQ("", outvar2.keyValue()); EXPECT_EQ("VRF Heat Pump Heating Electric Energy", outvar2.variableName()); EXPECT_EQ("residential mini split|unit 2 vrf heat energy output var", outvar2.nameString()); // add sensor EnergyManagementSystemSensor sensor2(model, outvar2); sensor2.setName("residential_mini_split_unit_2_vrf_energy_sensor"); sensor2.setKeyName("living zone|unit 2 Multi Split Heat Pump"); model.save(toPath("./EMS_sensortest.osm"), true); outvar1.remove(); EXPECT_EQ(static_cast<unsigned>(1), model.getModelObjects<EnergyManagementSystemSensor>().size()); } TEST_F(ModelFixture, EMSSensorDelete) { Model model; PlantLoop plantLoop(model); AvailabilityManagerHighTemperatureTurnOff avm(model); avm.setSensorNode(model.outdoorAirNode()); plantLoop.addAvailabilityManager(avm); std::vector<std::string> avm_names = avm.outputVariableNames(); // add sensor 1 EnergyManagementSystemSensor sensor(model, avm_names[0]); sensor.setKeyName(toString(avm.handle())); // Sensor attached to AVM std::string key = toString(avm.handle()); EXPECT_EQ(key, sensor.keyName()); // 1 sensor in the model EXPECT_EQ(static_cast<unsigned>(1), model.getModelObjects<EnergyManagementSystemSensor>().size()); // 1 avm in the model EXPECT_EQ(static_cast<unsigned>(1), model.getModelObjects<AvailabilityManagerHighTemperatureTurnOff>().size()); model.save(toPath("./EMS_sensor_delete_test.osm"), true); avm.remove(); // 0 avm in the model EXPECT_EQ(static_cast<unsigned>(0), model.getModelObjects<AvailabilityManagerHighTemperatureTurnOff>().size()); //sensor still has keyName as avm UUID string (will not FT though eventually) EXPECT_EQ(key, sensor.keyName()); }
43.724299
125
0.747782
hellok-coder
4f83a13894406908b50749e7774d201c65e4d3eb
22,539
cpp
C++
cppForSwig/nodeRPC.cpp
BlockSettle/ArmoryDB
7a63e722969b9cab94f25d569aa425c5c5a3db18
[ "MIT" ]
null
null
null
cppForSwig/nodeRPC.cpp
BlockSettle/ArmoryDB
7a63e722969b9cab94f25d569aa425c5c5a3db18
[ "MIT" ]
6
2019-06-07T15:48:56.000Z
2020-03-09T10:30:39.000Z
cppForSwig/nodeRPC.cpp
BlockSettle/ArmoryDB
7a63e722969b9cab94f25d569aa425c5c5a3db18
[ "MIT" ]
2
2019-05-30T12:15:29.000Z
2019-10-27T22:46:49.000Z
//////////////////////////////////////////////////////////////////////////////// // // // Copyright (C) 2017, goatpig // // Distributed under the MIT license // // See LICENSE-MIT or https://opensource.org/licenses/MIT // // // //////////////////////////////////////////////////////////////////////////////// #include "ArmoryErrors.h" #include "nodeRPC.h" #include "DBUtils.h" #include "ArmoryConfig.h" #include "SocketWritePayload.h" #ifdef _WIN32 #include "leveldb_windows_port\win32_posix\dirent_win32.h" #else #include "dirent.h" #endif using namespace std; using namespace CoreRPC; using namespace Armory::Config; //////////////////////////////////////////////////////////////////////////////// // // NodeRPCInterface // //////////////////////////////////////////////////////////////////////////////// NodeRPCInterface::~NodeRPCInterface() {} //////////////////////////////////////////////////////////////////////////////// const NodeChainStatus& NodeRPCInterface::getChainStatus(void) const { ReentrantLock lock(this); return nodeChainStatus_; } //////////////////////////////////////////////////////////////////////////////// map<unsigned, FeeEstimateResult> NodeRPCInterface::getFeeSchedule( const string& strategy) { auto estimateCachePtr = atomic_load(&currentEstimateCache_); if (estimateCachePtr == nullptr) throw RpcError(); auto iterStrat = estimateCachePtr->find(strategy); if (iterStrat == estimateCachePtr->end()) throw RpcError(); return iterStrat->second; } //////////////////////////////////////////////////////////////////////////////// // // NodeRPC // //////////////////////////////////////////////////////////////////////////////// NodeRPC::NodeRPC() { //start fee estimate polling thread auto pollLbd = [this](void)->void { this->pollThread(); }; if (!canPoll()) return; thrVec_.push_back(thread(pollLbd)); } //////////////////////////////////////////////////////////////////////////////// bool NodeRPC::setupConnection(HttpSocket& sock) { ReentrantLock lock(this); //test the socket if(!sock.connectToRemote()) return false; if (basicAuthString64_.size() == 0) { auto&& authString = getAuthString(); if (authString.size() == 0) return false; basicAuthString64_ = move(BtcUtils::base64_encode(authString)); } stringstream auth_header; auth_header << "Authorization: Basic " << basicAuthString64_; auto header_str = auth_header.str(); sock.precacheHttpHeader(header_str); return true; } //////////////////////////////////////////////////////////////////////////////// void NodeRPC::resetAuthString() { ReentrantLock lock(this); basicAuthString64_.clear(); } //////////////////////////////////////////////////////////////////////////////// RpcState NodeRPC::testConnection() { ReentrantLock lock(this); RpcState state = RpcState_Disabled; JSON_object json_obj; json_obj.add_pair("method", "getblockcount"); try { auto&& response = queryRPC(json_obj); auto&& response_obj = JSON_decode(response); if (response_obj.isResponseValid(json_obj.id_)) { state = RpcState_Online; } else { auto error_ptr = response_obj.getValForKey("error"); auto error_obj = dynamic_pointer_cast<JSON_object>(error_ptr); if (error_obj != nullptr) { auto error_code_ptr = error_obj->getValForKey("code"); auto error_code = dynamic_pointer_cast<JSON_number>(error_code_ptr); if (error_code == nullptr) throw JSON_Exception("failed to get error code"); if ((int)error_code->val_ == -28) { state = RpcState_Error_28; } } else { state = RpcState_Disabled; auto error_val = dynamic_pointer_cast<JSON_string>(error_ptr); if (error_val != nullptr) { LOGWARN << "Rpc connection test failed with error: " << error_val->val_; } } } } catch (RpcError&) { state = RpcState_Disabled; } catch (SocketError&) { state = RpcState_Disabled; } catch (JSON_Exception& e) { LOGERR << "RPC connection test error: " << e.what(); state = RpcState_BadAuth; } return state; } //////////////////////////////////////////////////////////////////////////////// string NodeRPC::getDatadir() { string datadir = Pathing::blkFilePath(); auto len = datadir.size(); if (len >= 6) { auto&& term = datadir.substr(len - 6, 6); if (term == "blocks") datadir = datadir.substr(0, len - 6); } return datadir; } //////////////////////////////////////////////////////////////////////////////// string NodeRPC::getAuthString() { auto&& datadir = getDatadir(); auto confPath = datadir; DBUtils::appendPath(confPath, "bitcoin.conf"); auto getAuthStringFromCookieFile = [&datadir](void)->string { DBUtils::appendPath(datadir, ".cookie"); auto&& lines = SettingsUtils::getLines(datadir); if (lines.size() != 1) { throw runtime_error("unexpected cookie file content"); } auto&& keyVals = SettingsUtils::getKeyValsFromLines(lines, ':'); auto keyIter = keyVals.find("__cookie__"); if (keyIter == keyVals.end()) { throw runtime_error("unexpected cookie file content"); } return lines[0]; }; //open and parse .conf file try { auto&& lines = SettingsUtils::getLines(confPath); auto&& keyVals = SettingsUtils::getKeyValsFromLines(lines, '='); //get rpcuser auto userIter = keyVals.find("rpcuser"); if (userIter == keyVals.end()) return getAuthStringFromCookieFile(); string authStr = userIter->second; //get rpcpassword auto passIter = keyVals.find("rpcpassword"); if (passIter == keyVals.end()) return getAuthStringFromCookieFile(); authStr.append(":"); authStr.append(passIter->second); return authStr; } catch (...) { return string(); } } //////////////////////////////////////////////////////////////////////////////// float NodeRPC::queryFeeByte(HttpSocket& sock, unsigned blocksToConfirm) { ReentrantLock lock(this); JSON_object json_obj; json_obj.add_pair("method", "estimatefee"); auto json_array = make_shared<JSON_array>(); json_array->add_value(blocksToConfirm); json_obj.add_pair("params", json_array); auto&& response = queryRPC(sock, json_obj); auto&& response_obj = JSON_decode(response); if (!response_obj.isResponseValid(json_obj.id_)) throw JSON_Exception("invalid response"); auto feeByteObj = response_obj.getValForKey("result"); auto feeBytePtr = dynamic_pointer_cast<JSON_number>(feeByteObj); if (feeBytePtr == nullptr) throw JSON_Exception("invalid response"); return feeBytePtr->val_; } //////////////////////////////////////////////////////////////////////////////// FeeEstimateResult NodeRPC::queryFeeByteSmart(HttpSocket& sock, unsigned& confTarget, string& strategy) { auto fallback = [this, &confTarget, &sock](void)->FeeEstimateResult { FeeEstimateResult fer; fer.smartFee_ = false; auto feeByteSimple = queryFeeByte(sock, confTarget); if (feeByteSimple == -1.0f) fer.error_ = "error"; else fer.feeByte_ = feeByteSimple; return fer; }; FeeEstimateResult fer; ReentrantLock lock(this); JSON_object json_obj; json_obj.add_pair("method", "estimatesmartfee"); auto json_array = make_shared<JSON_array>(); json_array->add_value(confTarget); if(strategy == FEE_STRAT_CONSERVATIVE || strategy == FEE_STRAT_ECONOMICAL) json_array->add_value(strategy); json_obj.add_pair("params", json_array); auto&& response = queryRPC(sock, json_obj); auto&& response_obj = JSON_decode(response); if (!response_obj.isResponseValid(json_obj.id_)) return fallback(); auto resultPairObj = response_obj.getValForKey("result"); auto resultPairPtr = dynamic_pointer_cast<JSON_object>(resultPairObj); if (resultPairPtr != nullptr) { auto feeByteObj = resultPairPtr->getValForKey("feerate"); auto feeBytePtr = dynamic_pointer_cast<JSON_number>(feeByteObj); if (feeBytePtr != nullptr) { fer.feeByte_ = feeBytePtr->val_; fer.smartFee_ = true; auto blocksObj = resultPairPtr->getValForKey("blocks"); auto blocksPtr = dynamic_pointer_cast<JSON_number>(blocksObj); if (blocksPtr != nullptr) if (blocksPtr->val_ != confTarget) confTarget = blocksPtr->val_; } } auto errorObj = response_obj.getValForKey("error"); auto errorPtr = dynamic_pointer_cast<JSON_string>(errorObj); if (errorPtr != nullptr) { if (resultPairPtr == nullptr) { //fallback to the estimatefee if the method is missing return fallback(); } else { //report smartfee error msg fer.error_ = errorPtr->val_; fer.smartFee_ = true; } } return fer; } //////////////////////////////////////////////////////////////////////////////// FeeEstimateResult NodeRPC::getFeeByte( unsigned confTarget, const string& strategy) { auto estimateCachePtr = atomic_load(&currentEstimateCache_); if (estimateCachePtr == nullptr) throw RpcError(); auto iterStrat = estimateCachePtr->find(strategy); if (iterStrat == estimateCachePtr->end()) throw RpcError(); if (iterStrat->second.empty()) throw RpcError(); auto targetIter = iterStrat->second.upper_bound(confTarget); if (targetIter != iterStrat->second.begin()) --targetIter; return targetIter->second; } //////////////////////////////////////////////////////////////////////////////// void NodeRPC::aggregateFeeEstimates() { //get fee/byte on both strategies vector<unsigned> confTargets = { 2, 3, 4, 5, 6, 10, 12, 20, 24, 48, 144 }; static vector<string> strategies = { FEE_STRAT_CONSERVATIVE, FEE_STRAT_ECONOMICAL }; HttpSocket sock("127.0.0.1", NetworkSettings::rpcPort()); if (!setupConnection(sock)) throw RpcError("aggregateFeeEstimates: failed to setup RPC socket"); auto newCache = make_shared<EstimateCache>(); for (auto& strat : strategies) { auto insertIter = newCache->insert( make_pair(strat, map<unsigned, FeeEstimateResult>())); auto& newMap = insertIter.first->second; for (auto& target : confTargets) { try { auto&& result = queryFeeByteSmart(sock, target, strat); newMap.insert(make_pair(target, move(result))); } catch (ConfMismatch&) { break; } } } atomic_store(&currentEstimateCache_, newCache); } //////////////////////////////////////////////////////////////////////////////// bool NodeRPC::updateChainStatus(void) { ReentrantLock lock(this); //get top block header JSON_object json_getblockchaininfo; json_getblockchaininfo.add_pair("method", "getblockchaininfo"); auto&& response = JSON_decode(queryRPC(json_getblockchaininfo)); if (!response.isResponseValid(json_getblockchaininfo.id_)) throw JSON_Exception("invalid response"); auto getblockchaininfo_result = response.getValForKey("result"); auto getblockchaininfo_object = dynamic_pointer_cast<JSON_object>( getblockchaininfo_result); auto hash_obj = getblockchaininfo_object->getValForKey("bestblockhash"); if (hash_obj == nullptr) return false; auto params_obj = make_shared<JSON_array>(); params_obj->add_value(hash_obj); JSON_object json_getheader; json_getheader.add_pair("method", "getblockheader"); json_getheader.add_pair("params", params_obj); auto&& block_header = JSON_decode(queryRPC(json_getheader)); if (!block_header.isResponseValid(json_getheader.id_)) throw JSON_Exception("invalid response"); auto block_header_ptr = block_header.getValForKey("result"); auto block_header_result = dynamic_pointer_cast<JSON_object>(block_header_ptr); if (block_header_result == nullptr) throw JSON_Exception("invalid response"); //append timestamp and height auto height_obj = block_header_result->getValForKey("height"); auto height_val = dynamic_pointer_cast<JSON_number>(height_obj); if (height_val == nullptr) throw JSON_Exception("invalid response"); auto time_obj = block_header_result->getValForKey("time"); auto time_val = dynamic_pointer_cast<JSON_number>(time_obj); if (time_val == nullptr) throw JSON_Exception("invalid response"); nodeChainStatus_.appendHeightAndTime(height_val->val_, time_val->val_); //figure out state return nodeChainStatus_.processState(getblockchaininfo_object); } //////////////////////////////////////////////////////////////////////////////// void NodeRPC::waitOnChainSync(function<void(void)> callbck) { nodeChainStatus_.reset(); callbck(); while (1) { //keep trying as long as the node is initializing auto state = testConnection(); if (state != RpcState_Error_28) { if (state != RpcState_Online) return; break; } //sleep for 1sec this_thread::sleep_for(chrono::seconds(1)); } callbck(); while (1) { float blkSpeed = 0.0f; try { ReentrantLock lock(this); if (updateChainStatus()) callbck(); auto& chainStatus = getChainStatus(); if (chainStatus.state() == ChainState_Ready) break; blkSpeed = chainStatus.getBlockSpeed(); } catch (...) { auto state = testConnection(); if (state == RpcState_Online) throw runtime_error("unsupported RPC method"); } unsigned dur = 1; //sleep delay in seconds if (blkSpeed != 0.0f) { auto singleBlkEta = max(1.0f / blkSpeed, 1.0f); dur = min(unsigned(singleBlkEta), unsigned(5)); //don't sleep for more than 5sec } this_thread::sleep_for(chrono::seconds(dur)); } LOGINFO << "RPC is ready"; } //////////////////////////////////////////////////////////////////////////////// int NodeRPC::broadcastTx(const BinaryDataRef& rawTx, string& verbose) { ReentrantLock lock(this); JSON_object json_obj; json_obj.add_pair("method", "sendrawtransaction"); auto json_array = make_shared<JSON_array>(); string rawTxHex = rawTx.toHexStr(); json_array->add_value(rawTxHex); json_obj.add_pair("params", json_array); string response; try { response = queryRPC(json_obj); auto&& response_obj = JSON_decode(response); if (!response_obj.isResponseValid(json_obj.id_)) { auto error_field = response_obj.getValForKey("error"); auto error_obj = dynamic_pointer_cast<JSON_object>(error_field); if (error_obj == nullptr) throw JSON_Exception("invalid response"); auto msg_field = error_obj->getValForKey("message"); auto msg_val = dynamic_pointer_cast<JSON_string>(msg_field); verbose = msg_val->val_; auto code_field = error_obj->getValForKey("code"); auto code_val = dynamic_pointer_cast<JSON_number>(code_field); return (int)code_val->val_; } return (int)ArmoryErrorCodes::Success; } catch (RpcError& e) { LOGWARN << "RPC internal error: " << e.what(); return (int)ArmoryErrorCodes::RPCFailure_Internal; } catch (JSON_Exception& e) { LOGWARN << "RPC JSON error: " << e.what(); LOGWARN << "Node response was: "; LOGWARN << response; return (int)ArmoryErrorCodes::RPCFailure_JSON; } catch (exception& e) { LOGWARN << "Unkown RPC error: " << e.what(); return (int)ArmoryErrorCodes::RPCFailure_Unknown; } } //////////////////////////////////////////////////////////////////////////////// void NodeRPC::shutdown() { ReentrantLock lock(this); JSON_object json_obj; json_obj.add_pair("method", "stop"); auto&& response = queryRPC(json_obj); auto&& response_obj = JSON_decode(response); if (!response_obj.isResponseValid(json_obj.id_)) throw JSON_Exception("invalid response"); auto responseStr_obj = response_obj.getValForKey("result"); auto responseStr = dynamic_pointer_cast<JSON_string>(responseStr_obj); if (responseStr == nullptr) throw JSON_Exception("invalid response"); LOGINFO << responseStr->val_; } //////////////////////////////////////////////////////////////////////////////// string NodeRPC::queryRPC(JSON_object& request) { HttpSocket sock("127.0.0.1", NetworkSettings::rpcPort()); if (!setupConnection(sock)) throw RpcError("node_down"); return queryRPC(sock, request); } //////////////////////////////////////////////////////////////////////////////// string NodeRPC::queryRPC(HttpSocket& sock, JSON_object& request) { auto write_payload = make_unique<WritePayload_StringPassthrough>(); write_payload->data_ = move(JSON_encode(request)); auto promPtr = make_shared<promise<string>>(); auto fut = promPtr->get_future(); auto callback = [promPtr](string body)->void { promPtr->set_value(move(body)); }; auto read_payload = make_shared<Socket_ReadPayload>(request.id_); read_payload->callbackReturn_ = make_unique<CallbackReturn_HttpBody>(callback); sock.pushPayload(move(write_payload), read_payload); return fut.get(); } //////////////////////////////////////////////////////////////////////////////// void NodeRPC::pollThread() { auto pred = [this](void)->bool { return !run_.load(memory_order_acquire); }; mutex mu; bool status = false; while (true) { if (!status) { //test connection try { resetAuthString(); auto rpcState = testConnection(); bool doCallback = false; if (rpcState != previousState_) doCallback = true; previousState_ = rpcState; if (doCallback) callback(); if (rpcState == RpcState_Online) { LOGINFO << "RPC connection established"; status = true; continue; } } catch (exception& e) { LOGWARN << "fee poll check failed with error: " << e.what(); status = false; } } else { //update fee estimate try { aggregateFeeEstimates(); } catch (exception&) { status = false; continue; } } unique_lock<mutex> lock(mu); if (pollCondVar_.wait_for(lock, chrono::seconds(10), pred)) break; } LOGWARN << "out of rpc poll loop"; } //////////////////////////////////////////////////////////////////////////////// NodeRPC::~NodeRPC() { run_.store(false, memory_order_release); pollCondVar_.notify_all(); for (auto& thr : thrVec_) { if (thr.joinable()) thr.join(); } } //////////////////////////////////////////////////////////////////////////////// // // NodeChainStatus // //////////////////////////////////////////////////////////////////////////////// bool NodeChainStatus::processState( shared_ptr<JSON_object> const getblockchaininfo_obj) { if (state_ == ChainState_Ready) return false; //progress status auto pct_obj = getblockchaininfo_obj->getValForKey("verificationprogress"); auto pct_val = dynamic_pointer_cast<JSON_number>(pct_obj); if (pct_val == nullptr) return false; pct_ = min(pct_val->val_, 1.0); auto pct_int = unsigned(pct_ * 10000.0); if (pct_int != prev_pct_int_) { LOGINFO << "waiting on node sync: " << float(pct_ * 100.0) << "%"; prev_pct_int_ = pct_int; } if (pct_ >= 0.9995) { state_ = ChainState_Ready; return true; } //compare top block timestamp to now if (heightTimeVec_.size() == 0) return false; uint64_t now = time(0); uint64_t diff = 0; auto blocktime = get<1>(heightTimeVec_.back()); if (now > blocktime) diff = now - blocktime; //we got this far, node is still syncing, let's compute progress and eta state_ = ChainState_Syncing; //average amount of blocks left to sync based on timestamp diff auto blocksLeft = diff / 600; //compute block syncing speed based off of the last 20 top blocks auto iterend = heightTimeVec_.rbegin(); auto time_end = get<2>(*iterend); auto iterbegin = heightTimeVec_.begin(); auto time_begin = get<2>(*iterbegin); if (time_end <= time_begin) return false; auto blockdiff = get<0>(*iterend) - get<0>(*iterbegin); if (blockdiff == 0) return false; auto timediff = time_end - time_begin; blockSpeed_ = float(blockdiff) / float(timediff); eta_ = uint64_t(float(blocksLeft) * blockSpeed_); blocksLeft_ = blocksLeft; return true; } //////////////////////////////////////////////////////////////////////////////// unsigned NodeChainStatus::getTopBlock() const { if (heightTimeVec_.size() == 0) throw runtime_error(""); return get<0>(heightTimeVec_.back()); } //////////////////////////////////////////////////////////////////////////////// void NodeChainStatus::appendHeightAndTime(unsigned height, uint64_t timestamp) { try { if (getTopBlock() == height) return; } catch (...) { } heightTimeVec_.push_back(make_tuple(height, timestamp, time(0))); //force the list at 20 max entries while (heightTimeVec_.size() > 20) heightTimeVec_.pop_front(); } //////////////////////////////////////////////////////////////////////////////// void NodeChainStatus::reset() { heightTimeVec_.clear(); state_ = ChainState_Unknown; blockSpeed_ = 0.0f; eta_ = 0; }
27.32
89
0.56258
BlockSettle
4f85c139d06fb186ea38800e14479af8088a1fdd
19,202
cpp
C++
folly/wangle/test/FutureTest.cpp
zunc/folly
4ecd8cdd6396f2f4cbfc17c1063537884e3cd6b9
[ "Apache-2.0" ]
1
2018-01-18T07:35:45.000Z
2018-01-18T07:35:45.000Z
folly/wangle/test/FutureTest.cpp
dario-DI/folly
6e46d468cf2876dd59c7a4dddcb4e37abf070b7a
[ "Apache-2.0" ]
null
null
null
folly/wangle/test/FutureTest.cpp
dario-DI/folly
6e46d468cf2876dd59c7a4dddcb4e37abf070b7a
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2014 Facebook, 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 <algorithm> #include <atomic> #include <folly/small_vector.h> #include <gtest/gtest.h> #include <memory> #include <string> #include <thread> #include <type_traits> #include <unistd.h> #include <folly/wangle/Executor.h> #include <folly/wangle/Future.h> #include <folly/wangle/ManualExecutor.h> using namespace folly::wangle; using std::pair; using std::string; using std::unique_ptr; using std::vector; #define EXPECT_TYPE(x, T) \ EXPECT_TRUE((std::is_same<decltype(x), T>::value)) typedef WangleException eggs_t; static eggs_t eggs("eggs"); // Future TEST(Future, try) { class A { public: A(int x) : x_(x) {} int x() const { return x_; } private: int x_; }; A a(5); Try<A> t_a(std::move(a)); Try<void> t_void; EXPECT_EQ(5, t_a.value().x()); } TEST(Future, special) { EXPECT_FALSE(std::is_copy_constructible<Future<int>>::value); EXPECT_FALSE(std::is_copy_assignable<Future<int>>::value); EXPECT_TRUE(std::is_move_constructible<Future<int>>::value); EXPECT_TRUE(std::is_move_assignable<Future<int>>::value); } TEST(Future, then) { bool flag = false; makeFuture<int>(42).then([&](Try<int>&& t) { flag = true; EXPECT_EQ(42, t.value()); }); EXPECT_TRUE(flag); flag = false; makeFuture<int>(42) .then([](Try<int>&& t) { return t.value(); }) .then([&](Try<int>&& t) { flag = true; EXPECT_EQ(42, t.value()); }); EXPECT_TRUE(flag); flag = false; makeFuture().then([&](Try<void>&& t) { flag = true; t.value(); }); EXPECT_TRUE(flag); flag = false; Promise<void> p; auto f = p.getFuture().then([&](Try<void>&& t) { flag = true; }); EXPECT_FALSE(flag); EXPECT_FALSE(f.isReady()); p.setValue(); EXPECT_TRUE(flag); EXPECT_TRUE(f.isReady()); } static string doWorkStatic(Try<string>&& t) { return t.value() + ";static"; } TEST(Future, thenFunction) { struct Worker { string doWork(Try<string>&& t) { return t.value() + ";class"; } static string doWorkStatic(Try<string>&& t) { return t.value() + ";class-static"; } } w; auto f = makeFuture<string>("start") .then(doWorkStatic) .then(Worker::doWorkStatic) .then(&w, &Worker::doWork); EXPECT_EQ(f.value(), "start;static;class-static;class"); } static Future<string> doWorkStaticFuture(Try<string>&& t) { return makeFuture(t.value() + ";static"); } TEST(Future, thenFunctionFuture) { struct Worker { Future<string> doWorkFuture(Try<string>&& t) { return makeFuture(t.value() + ";class"); } static Future<string> doWorkStaticFuture(Try<string>&& t) { return makeFuture(t.value() + ";class-static"); } } w; auto f = makeFuture<string>("start") .then(doWorkStaticFuture) .then(Worker::doWorkStaticFuture) .then(&w, &Worker::doWorkFuture); EXPECT_EQ(f.value(), "start;static;class-static;class"); } TEST(Future, value) { auto f = makeFuture(unique_ptr<int>(new int(42))); auto up = std::move(f.value()); EXPECT_EQ(42, *up); EXPECT_THROW(makeFuture<int>(eggs).value(), eggs_t); } TEST(Future, isReady) { Promise<int> p; auto f = p.getFuture(); EXPECT_FALSE(f.isReady()); p.setValue(42); EXPECT_TRUE(f.isReady()); } TEST(Future, futureNotReady) { Promise<int> p; Future<int> f = p.getFuture(); EXPECT_THROW(f.value(), eggs_t); } TEST(Future, hasException) { EXPECT_TRUE(makeFuture<int>(eggs).getTry().hasException()); EXPECT_FALSE(makeFuture(42).getTry().hasException()); } TEST(Future, hasValue) { EXPECT_TRUE(makeFuture(42).getTry().hasValue()); EXPECT_FALSE(makeFuture<int>(eggs).getTry().hasValue()); } TEST(Future, makeFuture) { EXPECT_TYPE(makeFuture(42), Future<int>); EXPECT_EQ(42, makeFuture(42).value()); EXPECT_TYPE(makeFuture<float>(42), Future<float>); EXPECT_EQ(42, makeFuture<float>(42).value()); auto fun = [] { return 42; }; EXPECT_TYPE(makeFutureTry(fun), Future<int>); EXPECT_EQ(42, makeFutureTry(fun).value()); auto failfun = []() -> int { throw eggs; }; EXPECT_TYPE(makeFutureTry(failfun), Future<int>); EXPECT_THROW(makeFutureTry(failfun).value(), eggs_t); EXPECT_TYPE(makeFuture(), Future<void>); } // Promise TEST(Promise, special) { EXPECT_FALSE(std::is_copy_constructible<Promise<int>>::value); EXPECT_FALSE(std::is_copy_assignable<Promise<int>>::value); EXPECT_TRUE(std::is_move_constructible<Promise<int>>::value); EXPECT_TRUE(std::is_move_assignable<Promise<int>>::value); } TEST(Promise, getFuture) { Promise<int> p; Future<int> f = p.getFuture(); EXPECT_FALSE(f.isReady()); } TEST(Promise, setValue) { Promise<int> fund; auto ffund = fund.getFuture(); fund.setValue(42); EXPECT_EQ(42, ffund.value()); struct Foo { string name; int value; }; Promise<Foo> pod; auto fpod = pod.getFuture(); Foo f = {"the answer", 42}; pod.setValue(f); Foo f2 = fpod.value(); EXPECT_EQ(f.name, f2.name); EXPECT_EQ(f.value, f2.value); pod = Promise<Foo>(); fpod = pod.getFuture(); pod.setValue(std::move(f2)); Foo f3 = fpod.value(); EXPECT_EQ(f.name, f3.name); EXPECT_EQ(f.value, f3.value); Promise<unique_ptr<int>> mov; auto fmov = mov.getFuture(); mov.setValue(unique_ptr<int>(new int(42))); unique_ptr<int> ptr = std::move(fmov.value()); EXPECT_EQ(42, *ptr); Promise<void> v; auto fv = v.getFuture(); v.setValue(); EXPECT_TRUE(fv.isReady()); } TEST(Promise, setException) { { Promise<void> p; auto f = p.getFuture(); p.setException(eggs); EXPECT_THROW(f.value(), eggs_t); } { Promise<void> p; auto f = p.getFuture(); try { throw eggs; } catch (...) { p.setException(std::current_exception()); } EXPECT_THROW(f.value(), eggs_t); } } TEST(Promise, fulfil) { { Promise<int> p; auto f = p.getFuture(); p.fulfil([] { return 42; }); EXPECT_EQ(42, f.value()); } { Promise<int> p; auto f = p.getFuture(); p.fulfil([]() -> int { throw eggs; }); EXPECT_THROW(f.value(), eggs_t); } } TEST(Future, finish) { auto x = std::make_shared<int>(0); { Promise<int> p; auto f = p.getFuture().then([x](Try<int>&& t) { *x = t.value(); }); // The callback hasn't executed EXPECT_EQ(0, *x); // The callback has a reference to x EXPECT_EQ(2, x.use_count()); p.setValue(42); // the callback has executed EXPECT_EQ(42, *x); } // the callback has been destructed // and has released its reference to x EXPECT_EQ(1, x.use_count()); } TEST(Future, unwrap) { Promise<int> a; Promise<int> b; auto fa = a.getFuture(); auto fb = b.getFuture(); bool flag1 = false; bool flag2 = false; // do a, then do b, and get the result of a + b. Future<int> f = fa.then([&](Try<int>&& ta) { auto va = ta.value(); flag1 = true; return fb.then([va, &flag2](Try<int>&& tb) { flag2 = true; return va + tb.value(); }); }); EXPECT_FALSE(flag1); EXPECT_FALSE(flag2); EXPECT_FALSE(f.isReady()); a.setValue(3); EXPECT_TRUE(flag1); EXPECT_FALSE(flag2); EXPECT_FALSE(f.isReady()); b.setValue(4); EXPECT_TRUE(flag1); EXPECT_TRUE(flag2); EXPECT_EQ(7, f.value()); } TEST(Future, whenAll) { // returns a vector variant { vector<Promise<int>> promises(10); vector<Future<int>> futures; for (auto& p : promises) futures.push_back(p.getFuture()); auto allf = whenAll(futures.begin(), futures.end()); random_shuffle(promises.begin(), promises.end()); for (auto& p : promises) { EXPECT_FALSE(allf.isReady()); p.setValue(42); } EXPECT_TRUE(allf.isReady()); auto& results = allf.value(); for (auto& t : results) { EXPECT_EQ(42, t.value()); } } // check error semantics { vector<Promise<int>> promises(4); vector<Future<int>> futures; for (auto& p : promises) futures.push_back(p.getFuture()); auto allf = whenAll(futures.begin(), futures.end()); promises[0].setValue(42); promises[1].setException(eggs); EXPECT_FALSE(allf.isReady()); promises[2].setValue(42); EXPECT_FALSE(allf.isReady()); promises[3].setException(eggs); EXPECT_TRUE(allf.isReady()); EXPECT_FALSE(allf.getTry().hasException()); auto& results = allf.value(); EXPECT_EQ(42, results[0].value()); EXPECT_TRUE(results[1].hasException()); EXPECT_EQ(42, results[2].value()); EXPECT_TRUE(results[3].hasException()); } // check that futures are ready in then() { vector<Promise<void>> promises(10); vector<Future<void>> futures; for (auto& p : promises) futures.push_back(p.getFuture()); auto allf = whenAll(futures.begin(), futures.end()) .then([](Try<vector<Try<void>>>&& ts) { for (auto& f : ts.value()) f.value(); }); random_shuffle(promises.begin(), promises.end()); for (auto& p : promises) p.setValue(); EXPECT_TRUE(allf.isReady()); } } TEST(Future, whenAny) { { vector<Promise<int>> promises(10); vector<Future<int>> futures; for (auto& p : promises) futures.push_back(p.getFuture()); for (auto& f : futures) { EXPECT_FALSE(f.isReady()); } auto anyf = whenAny(futures.begin(), futures.end()); /* futures were moved in, so these are invalid now */ EXPECT_FALSE(anyf.isReady()); promises[7].setValue(42); EXPECT_TRUE(anyf.isReady()); auto& idx_fut = anyf.value(); auto i = idx_fut.first; EXPECT_EQ(7, i); auto& f = idx_fut.second; EXPECT_EQ(42, f.value()); } // error { vector<Promise<void>> promises(10); vector<Future<void>> futures; for (auto& p : promises) futures.push_back(p.getFuture()); for (auto& f : futures) { EXPECT_FALSE(f.isReady()); } auto anyf = whenAny(futures.begin(), futures.end()); EXPECT_FALSE(anyf.isReady()); promises[3].setException(eggs); EXPECT_TRUE(anyf.isReady()); EXPECT_TRUE(anyf.value().second.hasException()); } // then() { vector<Promise<int>> promises(10); vector<Future<int>> futures; for (auto& p : promises) futures.push_back(p.getFuture()); auto anyf = whenAny(futures.begin(), futures.end()) .then([](Try<pair<size_t, Try<int>>>&& f) { EXPECT_EQ(42, f.value().second.value()); }); promises[3].setValue(42); EXPECT_TRUE(anyf.isReady()); } } TEST(when, already_completed) { { vector<Future<void>> fs; for (int i = 0; i < 10; i++) fs.push_back(makeFuture()); whenAll(fs.begin(), fs.end()) .then([&](Try<vector<Try<void>>>&& t) { EXPECT_EQ(fs.size(), t.value().size()); }); } { vector<Future<int>> fs; for (int i = 0; i < 10; i++) fs.push_back(makeFuture(i)); whenAny(fs.begin(), fs.end()) .then([&](Try<pair<size_t, Try<int>>>&& t) { auto& p = t.value(); EXPECT_EQ(p.first, p.second.value()); }); } } TEST(when, whenN) { vector<Promise<void>> promises(10); vector<Future<void>> futures; for (auto& p : promises) futures.push_back(p.getFuture()); bool flag = false; size_t n = 3; whenN(futures.begin(), futures.end(), n) .then([&](Try<vector<pair<size_t, Try<void>>>>&& t) { flag = true; auto v = t.value(); EXPECT_EQ(n, v.size()); for (auto& tt : v) EXPECT_TRUE(tt.second.hasValue()); }); promises[0].setValue(); EXPECT_FALSE(flag); promises[1].setValue(); EXPECT_FALSE(flag); promises[2].setValue(); EXPECT_TRUE(flag); } /* Ensure that we can compile when_{all,any} with folly::small_vector */ TEST(when, small_vector) { static_assert(!FOLLY_IS_TRIVIALLY_COPYABLE(Future<void>), "Futures should not be trivially copyable"); static_assert(!FOLLY_IS_TRIVIALLY_COPYABLE(Future<int>), "Futures should not be trivially copyable"); using folly::small_vector; { small_vector<Future<void>> futures; for (int i = 0; i < 10; i++) futures.push_back(makeFuture()); auto anyf = whenAny(futures.begin(), futures.end()); } { small_vector<Future<void>> futures; for (int i = 0; i < 10; i++) futures.push_back(makeFuture()); auto allf = whenAll(futures.begin(), futures.end()); } } TEST(Future, whenAllVariadic) { Promise<bool> pb; Promise<int> pi; Future<bool> fb = pb.getFuture(); Future<int> fi = pi.getFuture(); bool flag = false; whenAll(std::move(fb), std::move(fi)) .then([&](Try<std::tuple<Try<bool>, Try<int>>>&& t) { flag = true; EXPECT_TRUE(t.hasValue()); EXPECT_TRUE(std::get<0>(t.value()).hasValue()); EXPECT_EQ(std::get<0>(t.value()).value(), true); EXPECT_TRUE(std::get<1>(t.value()).hasValue()); EXPECT_EQ(std::get<1>(t.value()).value(), 42); }); pb.setValue(true); EXPECT_FALSE(flag); pi.setValue(42); EXPECT_TRUE(flag); } TEST(Future, whenAllVariadicReferences) { Promise<bool> pb; Promise<int> pi; Future<bool> fb = pb.getFuture(); Future<int> fi = pi.getFuture(); bool flag = false; whenAll(fb, fi) .then([&](Try<std::tuple<Try<bool>, Try<int>>>&& t) { flag = true; EXPECT_TRUE(t.hasValue()); EXPECT_TRUE(std::get<0>(t.value()).hasValue()); EXPECT_EQ(std::get<0>(t.value()).value(), true); EXPECT_TRUE(std::get<1>(t.value()).hasValue()); EXPECT_EQ(std::get<1>(t.value()).value(), 42); }); pb.setValue(true); EXPECT_FALSE(flag); pi.setValue(42); EXPECT_TRUE(flag); } TEST(Future, whenAll_none) { vector<Future<int>> fs; auto f = whenAll(fs.begin(), fs.end()); EXPECT_TRUE(f.isReady()); } TEST(Future, throwCaughtInImmediateThen) { // Neither of these should throw "Promise already satisfied" makeFuture().then( [=](Try<void>&&) -> int { throw std::exception(); }); makeFuture().then( [=](Try<void>&&) -> Future<int> { throw std::exception(); }); } TEST(Future, throwIfFailed) { makeFuture<void>(eggs) .then([=](Try<void>&& t) { EXPECT_THROW(t.throwIfFailed(), eggs_t); }); makeFuture() .then([=](Try<void>&& t) { EXPECT_NO_THROW(t.throwIfFailed()); }); makeFuture<int>(eggs) .then([=](Try<int>&& t) { EXPECT_THROW(t.throwIfFailed(), eggs_t); }); makeFuture<int>(42) .then([=](Try<int>&& t) { EXPECT_NO_THROW(t.throwIfFailed()); }); } TEST(Future, waitWithSemaphoreImmediate) { waitWithSemaphore(makeFuture()); auto done = waitWithSemaphore(makeFuture(42)).value(); EXPECT_EQ(42, done); vector<int> v{1,2,3}; auto done_v = waitWithSemaphore(makeFuture(v)).value(); EXPECT_EQ(v.size(), done_v.size()); EXPECT_EQ(v, done_v); vector<Future<void>> v_f; v_f.push_back(makeFuture()); v_f.push_back(makeFuture()); auto done_v_f = waitWithSemaphore(whenAll(v_f.begin(), v_f.end())).value(); EXPECT_EQ(2, done_v_f.size()); vector<Future<bool>> v_fb; v_fb.push_back(makeFuture(true)); v_fb.push_back(makeFuture(false)); auto fut = whenAll(v_fb.begin(), v_fb.end()); auto done_v_fb = std::move(waitWithSemaphore(std::move(fut)).value()); EXPECT_EQ(2, done_v_fb.size()); } TEST(Future, waitWithSemaphore) { Promise<int> p; Future<int> f = p.getFuture(); std::atomic<bool> flag{false}; std::atomic<int> result{1}; std::atomic<std::thread::id> id; std::thread t([&](Future<int>&& tf){ auto n = tf.then([&](Try<int> && t) { id = std::this_thread::get_id(); return t.value(); }); flag = true; result.store(waitWithSemaphore(std::move(n)).value()); LOG(INFO) << result; }, std::move(f) ); while(!flag){} EXPECT_EQ(result.load(), 1); p.setValue(42); t.join(); // validate that the callback ended up executing in this thread, which // is more to ensure that this test actually tests what it should EXPECT_EQ(id, std::this_thread::get_id()); EXPECT_EQ(result.load(), 42); } TEST(Future, waitWithSemaphoreForTime) { { Promise<int> p; Future<int> f = p.getFuture(); auto t = waitWithSemaphore(std::move(f), std::chrono::microseconds(1)); EXPECT_FALSE(t.isReady()); p.setValue(1); EXPECT_TRUE(t.isReady()); } { Promise<int> p; Future<int> f = p.getFuture(); p.setValue(1); auto t = waitWithSemaphore(std::move(f), std::chrono::milliseconds(1)); EXPECT_TRUE(t.isReady()); } { vector<Future<bool>> v_fb; v_fb.push_back(makeFuture(true)); v_fb.push_back(makeFuture(false)); auto f = whenAll(v_fb.begin(), v_fb.end()); auto t = waitWithSemaphore(std::move(f), std::chrono::milliseconds(1)); EXPECT_TRUE(t.isReady()); EXPECT_EQ(2, t.value().size()); } { vector<Future<bool>> v_fb; Promise<bool> p1; Promise<bool> p2; v_fb.push_back(p1.getFuture()); v_fb.push_back(p2.getFuture()); auto f = whenAll(v_fb.begin(), v_fb.end()); auto t = waitWithSemaphore(std::move(f), std::chrono::milliseconds(1)); EXPECT_FALSE(t.isReady()); p1.setValue(true); EXPECT_FALSE(t.isReady()); p2.setValue(true); EXPECT_TRUE(t.isReady()); } { Promise<int> p; Future<int> f = p.getFuture(); auto begin = std::chrono::system_clock::now(); auto t = waitWithSemaphore(std::move(f), std::chrono::milliseconds(1)); auto end = std::chrono::system_clock::now(); EXPECT_TRUE( end - begin < std::chrono::milliseconds(2)); EXPECT_FALSE(t.isReady()); } { auto t = waitWithSemaphore(makeFuture(), std::chrono::milliseconds(1)); EXPECT_TRUE(t.isReady()); } } TEST(Future, callbackAfterActivate) { Promise<void> p; auto f = p.getFuture(); f.deactivate(); size_t count = 0; f.then([&](Try<void>&&) { count++; }); p.setValue(); EXPECT_EQ(0, count); f.activate(); EXPECT_EQ(1, count); } TEST(Future, activateOnDestruct) { Promise<void> p; auto f = p.getFuture(); f.deactivate(); size_t count = 0; f.then([&](Try<void>&&) { count++; }); p.setValue(); EXPECT_EQ(0, count); f = makeFuture(); // force destruction of old f EXPECT_EQ(1, count); } TEST(Future, viaIsCold) { ManualExecutor x; size_t count = 0; auto fv = makeFuture().via(&x); fv.then([&](Try<void>&&) { count++; }); EXPECT_EQ(0, count); fv.activate(); EXPECT_EQ(1, x.run()); EXPECT_EQ(1, count); } TEST(Future, getFuture_after_setValue) { Promise<int> p; p.setValue(42); EXPECT_EQ(42, p.getFuture().value()); } TEST(Future, getFuture_after_setException) { Promise<void> p; p.fulfil([]() -> void { throw std::logic_error("foo"); }); EXPECT_THROW(p.getFuture().value(), std::logic_error); }
23.912827
77
0.621654
zunc
4f88e455f8cada13913b591be3f881a811f9a3f1
4,772
cpp
C++
aws-cpp-sdk-monitoring/source/model/AlarmHistoryItem.cpp
ambasta/aws-sdk-cpp
c81192e00b572b76d175d84dff77185bd17ae1ac
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-monitoring/source/model/AlarmHistoryItem.cpp
ambasta/aws-sdk-cpp
c81192e00b572b76d175d84dff77185bd17ae1ac
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-monitoring/source/model/AlarmHistoryItem.cpp
ambasta/aws-sdk-cpp
c81192e00b572b76d175d84dff77185bd17ae1ac
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/monitoring/model/AlarmHistoryItem.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Utils::Xml; using namespace Aws::Utils; namespace Aws { namespace CloudWatch { namespace Model { AlarmHistoryItem::AlarmHistoryItem() : m_alarmNameHasBeenSet(false), m_timestampHasBeenSet(false), m_historyItemTypeHasBeenSet(false), m_historySummaryHasBeenSet(false), m_historyDataHasBeenSet(false) { } AlarmHistoryItem::AlarmHistoryItem(const XmlNode& xmlNode) : m_alarmNameHasBeenSet(false), m_timestampHasBeenSet(false), m_historyItemTypeHasBeenSet(false), m_historySummaryHasBeenSet(false), m_historyDataHasBeenSet(false) { *this = xmlNode; } AlarmHistoryItem& AlarmHistoryItem::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode alarmNameNode = resultNode.FirstChild("AlarmName"); if(!alarmNameNode.IsNull()) { m_alarmName = StringUtils::Trim(alarmNameNode.GetText().c_str()); m_alarmNameHasBeenSet = true; } XmlNode timestampNode = resultNode.FirstChild("Timestamp"); if(!timestampNode.IsNull()) { m_timestamp = DateTime(StringUtils::Trim(timestampNode.GetText().c_str()).c_str(), DateFormat::ISO_8601); m_timestampHasBeenSet = true; } XmlNode historyItemTypeNode = resultNode.FirstChild("HistoryItemType"); if(!historyItemTypeNode.IsNull()) { m_historyItemType = HistoryItemTypeMapper::GetHistoryItemTypeForName(StringUtils::Trim(historyItemTypeNode.GetText().c_str()).c_str()); m_historyItemTypeHasBeenSet = true; } XmlNode historySummaryNode = resultNode.FirstChild("HistorySummary"); if(!historySummaryNode.IsNull()) { m_historySummary = StringUtils::Trim(historySummaryNode.GetText().c_str()); m_historySummaryHasBeenSet = true; } XmlNode historyDataNode = resultNode.FirstChild("HistoryData"); if(!historyDataNode.IsNull()) { m_historyData = StringUtils::Trim(historyDataNode.GetText().c_str()); m_historyDataHasBeenSet = true; } } return *this; } void AlarmHistoryItem::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const { if(m_alarmNameHasBeenSet) { oStream << location << index << locationValue << ".AlarmName=" << StringUtils::URLEncode(m_alarmName.c_str()) << "&"; } if(m_timestampHasBeenSet) { oStream << location << index << locationValue << ".Timestamp=" << StringUtils::URLEncode(m_timestamp.ToGmtString(DateFormat::ISO_8601).c_str()) << "&"; } if(m_historyItemTypeHasBeenSet) { oStream << location << index << locationValue << ".HistoryItemType=" << HistoryItemTypeMapper::GetNameForHistoryItemType(m_historyItemType) << "&"; } if(m_historySummaryHasBeenSet) { oStream << location << index << locationValue << ".HistorySummary=" << StringUtils::URLEncode(m_historySummary.c_str()) << "&"; } if(m_historyDataHasBeenSet) { oStream << location << index << locationValue << ".HistoryData=" << StringUtils::URLEncode(m_historyData.c_str()) << "&"; } } void AlarmHistoryItem::OutputToStream(Aws::OStream& oStream, const char* location) const { if(m_alarmNameHasBeenSet) { oStream << location << ".AlarmName=" << StringUtils::URLEncode(m_alarmName.c_str()) << "&"; } if(m_timestampHasBeenSet) { oStream << location << ".Timestamp=" << StringUtils::URLEncode(m_timestamp.ToGmtString(DateFormat::ISO_8601).c_str()) << "&"; } if(m_historyItemTypeHasBeenSet) { oStream << location << ".HistoryItemType=" << HistoryItemTypeMapper::GetNameForHistoryItemType(m_historyItemType) << "&"; } if(m_historySummaryHasBeenSet) { oStream << location << ".HistorySummary=" << StringUtils::URLEncode(m_historySummary.c_str()) << "&"; } if(m_historyDataHasBeenSet) { oStream << location << ".HistoryData=" << StringUtils::URLEncode(m_historyData.c_str()) << "&"; } } } // namespace Model } // namespace CloudWatch } // namespace Aws
32.243243
157
0.711023
ambasta
4f8bb9d81616d6ea39d2a2cb1127aac5c93bbe83
2,619
cpp
C++
src/test/cpp/ut/rocketmq/CredentialsProviderTest.cpp
lizhanhui/rocketmq-client-cpp
d2001836e40d4f1da29ae7b2848fdfe0077ed1bf
[ "Apache-2.0" ]
null
null
null
src/test/cpp/ut/rocketmq/CredentialsProviderTest.cpp
lizhanhui/rocketmq-client-cpp
d2001836e40d4f1da29ae7b2848fdfe0077ed1bf
[ "Apache-2.0" ]
null
null
null
src/test/cpp/ut/rocketmq/CredentialsProviderTest.cpp
lizhanhui/rocketmq-client-cpp
d2001836e40d4f1da29ae7b2848fdfe0077ed1bf
[ "Apache-2.0" ]
1
2021-09-16T06:31:07.000Z
2021-09-16T06:31:07.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "rocketmq/CredentialsProvider.h" #include "MixAll.h" #include "ghc/filesystem.hpp" #include "google/protobuf/struct.pb.h" #include "google/protobuf/util/json_util.h" #include "gtest/gtest.h" #include <cstdlib> #include <fstream> #include <iostream> ROCKETMQ_NAMESPACE_BEGIN class CredentialsProviderTest : public testing::Test {}; TEST_F(CredentialsProviderTest, testStaticCredentialsProvider) { std::string access_key("abc"); std::string access_secret("def"); StaticCredentialsProvider credentials_provider(access_key, access_secret); Credentials&& credentials = credentials_provider.getCredentials(); ASSERT_EQ(credentials.accessKey(), access_key); ASSERT_EQ(credentials.accessSecret(), access_secret); } TEST_F(CredentialsProviderTest, testEnvironmentVariable) { const char* access_key = "abc"; const char* access_secret = "def"; #ifdef _WIN32 std::string env_access_key; env_access_key.append(EnvironmentVariablesCredentialsProvider::ENVIRONMENT_ACCESS_KEY); env_access_key.push_back('='); env_access_key.append(access_key); _putenv(env_access_key.c_str()); std::string env_access_secret; env_access_secret.append(EnvironmentVariablesCredentialsProvider::ENVIRONMENT_ACCESS_SECRET); env_access_secret.push_back('='); env_access_secret.append(access_secret); _putenv(env_access_secret.c_str()); #else setenv(EnvironmentVariablesCredentialsProvider::ENVIRONMENT_ACCESS_KEY, access_key, 1); setenv(EnvironmentVariablesCredentialsProvider::ENVIRONMENT_ACCESS_SECRET, access_secret, 1); #endif EnvironmentVariablesCredentialsProvider provider; const Credentials& credentials = provider.getCredentials(); EXPECT_STREQ(access_key, credentials.accessKey().c_str()); EXPECT_STREQ(access_secret, credentials.accessSecret().c_str()); } ROCKETMQ_NAMESPACE_END
38.514706
95
0.791523
lizhanhui
4f8e2db5241737342e203840e3429179e1928b76
3,319
cpp
C++
libs/glm/test/core/core_type_length.cpp
ashishvista/opengl_makeover
80ceef85c7ba6ac43d1895b5a19c5f287b1b4b00
[ "Zlib" ]
89
2020-08-31T02:59:08.000Z
2022-03-17T13:31:22.000Z
test/core/core_type_length.cpp
seraphim0423/glm-deprecated
e1afbc9ceaacbc9aed7bb896d26c0872f8a2bf29
[ "MIT" ]
10
2015-08-09T21:10:55.000Z
2015-08-10T02:50:07.000Z
src/external/glm-0.9.4.0/test/core/core_type_length.cpp
ScottTodd/GraphicsPractice
31691d5fd0b674627e41362772737168c57ec698
[ "MIT" ]
58
2020-09-27T16:52:45.000Z
2022-03-29T09:13:33.000Z
/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2012 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2011-05-25 // Updated : 2011-05-25 // Licence : This source is under MIT License // File : test/core/type_length.cpp /////////////////////////////////////////////////////////////////////////////////////////////////// #include <glm/glm.hpp> #include <glm/gtc/half_float.hpp> int test_length_mat_non_squared() { int Error = 0; Error += glm::mat2x3().length() == 2 ? 0 : 1; Error += glm::mat2x4().length() == 2 ? 0 : 1; Error += glm::mat3x2().length() == 3 ? 0 : 1; Error += glm::mat3x4().length() == 3 ? 0 : 1; Error += glm::mat4x2().length() == 4 ? 0 : 1; Error += glm::mat4x3().length() == 4 ? 0 : 1; Error += glm::dmat2x3().length() == 2 ? 0 : 1; Error += glm::dmat2x4().length() == 2 ? 0 : 1; Error += glm::dmat3x2().length() == 3 ? 0 : 1; Error += glm::dmat3x4().length() == 3 ? 0 : 1; Error += glm::dmat4x2().length() == 4 ? 0 : 1; Error += glm::dmat4x3().length() == 4 ? 0 : 1; Error += glm::hmat2x3().length() == 2 ? 0 : 1; Error += glm::hmat2x4().length() == 2 ? 0 : 1; Error += glm::hmat3x2().length() == 3 ? 0 : 1; Error += glm::hmat3x4().length() == 3 ? 0 : 1; Error += glm::hmat4x2().length() == 4 ? 0 : 1; Error += glm::hmat4x3().length() == 4 ? 0 : 1; return Error; } int test_length_mat() { int Error = 0; Error += glm::mat2().length() == 2 ? 0 : 1; Error += glm::mat3().length() == 3 ? 0 : 1; Error += glm::mat4().length() == 4 ? 0 : 1; Error += glm::mat2x2().length() == 2 ? 0 : 1; Error += glm::mat3x3().length() == 3 ? 0 : 1; Error += glm::mat4x4().length() == 4 ? 0 : 1; Error += glm::dmat2().length() == 2 ? 0 : 1; Error += glm::dmat3().length() == 3 ? 0 : 1; Error += glm::dmat4().length() == 4 ? 0 : 1; Error += glm::dmat2x2().length() == 2 ? 0 : 1; Error += glm::dmat3x3().length() == 3 ? 0 : 1; Error += glm::dmat4x4().length() == 4 ? 0 : 1; Error += glm::hmat2().length() == 2 ? 0 : 1; Error += glm::hmat3().length() == 3 ? 0 : 1; Error += glm::hmat4().length() == 4 ? 0 : 1; Error += glm::hmat2x2().length() == 2 ? 0 : 1; Error += glm::hmat3x3().length() == 3 ? 0 : 1; Error += glm::hmat4x4().length() == 4 ? 0 : 1; return Error; } int test_length_vec() { int Error = 0; Error += glm::vec2().length() == 2 ? 0 : 1; Error += glm::vec3().length() == 3 ? 0 : 1; Error += glm::vec4().length() == 4 ? 0 : 1; Error += glm::ivec2().length() == 2 ? 0 : 1; Error += glm::ivec3().length() == 3 ? 0 : 1; Error += glm::ivec4().length() == 4 ? 0 : 1; Error += glm::uvec2().length() == 2 ? 0 : 1; Error += glm::uvec3().length() == 3 ? 0 : 1; Error += glm::uvec4().length() == 4 ? 0 : 1; Error += glm::hvec2().length() == 2 ? 0 : 1; Error += glm::hvec3().length() == 3 ? 0 : 1; Error += glm::hvec4().length() == 4 ? 0 : 1; Error += glm::dvec2().length() == 2 ? 0 : 1; Error += glm::dvec3().length() == 3 ? 0 : 1; Error += glm::dvec4().length() == 4 ? 0 : 1; return Error; } int main() { int Error = 0; Error += test_length_vec(); Error += test_length_mat(); Error += test_length_mat_non_squared(); return Error; }
30.731481
99
0.475143
ashishvista
4f8ea15991b72ffae8ba7732f5733bd4fbbd8d57
19,941
cpp
C++
mbed-cloud-client/source/ServiceClient.cpp
ghsecuritylab/Pelion
156eab454e87b5f5bbe4a662d7beb1482051a855
[ "Apache-2.0" ]
1
2020-03-13T07:20:09.000Z
2020-03-13T07:20:09.000Z
mbed-cloud-client/source/ServiceClient.cpp
ghsecuritylab/Pelion
156eab454e87b5f5bbe4a662d7beb1482051a855
[ "Apache-2.0" ]
null
null
null
mbed-cloud-client/source/ServiceClient.cpp
ghsecuritylab/Pelion
156eab454e87b5f5bbe4a662d7beb1482051a855
[ "Apache-2.0" ]
2
2020-03-07T20:00:13.000Z
2020-03-13T07:20:10.000Z
// ---------------------------------------------------------------------------- // Copyright 2016-2017 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // // 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. // ---------------------------------------------------------------------------- // Note: this macro is needed on armcc to get the the PRI*32 macros // from inttypes.h in a C++ code. #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include <inttypes.h> #include <string> #include "include/ServiceClient.h" #include "include/CloudClientStorage.h" #include "include/UpdateClientResources.h" #include "include/UpdateClient.h" #include "factory_configurator_client.h" #include "mbed-client/m2mconstants.h" #include "mbed-trace/mbed_trace.h" #include <assert.h> #define TRACE_GROUP "mClt" #define CONNECT 0 #define ERROR_UPDATE "Update has failed, check MbedCloudClient::Error" /* lookup table for printing hexadecimal values */ const uint8_t ServiceClient::hex_table[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; ServiceClient::ServiceClient(ServiceClientCallback& callback) : _service_callback(callback), _service_uri(NULL), _stack(NULL), _client_objs(NULL), _current_state(State_Init), _event_generated(false), _state_engine_running(false), #ifdef MBED_CLOUD_CLIENT_SUPPORT_UPDATE _setup_update_client(false), #endif _connector_client(this) { } ServiceClient::~ServiceClient() { #ifdef MBED_CLOUD_CLIENT_SUPPORT_UPDATE ARM_UC_HUB_Uninitialize(); #endif } void ServiceClient::initialize_and_register(M2MBaseList& reg_objs) { tr_debug("ServiceClient::initialize_and_register"); if(_current_state == State_Init || _current_state == State_Unregister || _current_state == State_Failure) { _client_objs = &reg_objs; #ifdef MBED_CLOUD_CLIENT_SUPPORT_UPDATE tr_debug("ServiceClient::initialize_and_register: update client supported"); if(!_setup_update_client) { _setup_update_client = true; #ifdef MBED_CLOUD_DEV_UPDATE_ID /* Overwrite values stored in KCM. This is for development only since these IDs should be provisioned in the factory. */ tr_debug("ServiceClient::initialize_and_register: update IDs defined"); /* Delete VendorId */ delete_config_parameter("mbed.VendorId"); /* Store Vendor Id to mbed.VendorId. No conversion is performed. */ set_device_resource_value(M2MDevice::Manufacturer, (const char*) arm_uc_vendor_id, arm_uc_vendor_id_size); /* Delete ClassId */ delete_config_parameter("mbed.ClassId"); /* Store Class Id to mbed.ClassId. No conversion is performed. */ set_device_resource_value(M2MDevice::ModelNumber, (const char*) arm_uc_class_id, arm_uc_class_id_size); #endif /* MBED_CLOUD_DEV_UPDATE_ID */ #ifdef ARM_UPDATE_CLIENT_VERSION /* Inject Update Client version number if no other software version is present in the KCM. */ tr_debug("ServiceClient::initialize_and_register: update version defined"); ; const size_t buffer_size = 16; uint8_t buffer[buffer_size]; size_t size = 0; /* check if software version is already set */ ccs_status_e status = get_config_parameter(KEY_DEVICE_SOFTWAREVERSION, buffer, buffer_size, &size); if (status == CCS_STATUS_KEY_DOESNT_EXIST) { tr_debug("ServiceClient::initialize_and_register: insert update version"); /* insert value from Update Client Common */ set_config_parameter(KEY_DEVICE_SOFTWAREVERSION, (const uint8_t*) ARM_UPDATE_CLIENT_VERSION, sizeof(ARM_UPDATE_CLIENT_VERSION)); } #endif /* ARM_UPDATE_CLIENT_VERSION */ /* Update Client adds the OMA LWM2M Firmware Update object */ UpdateClient::populate_object_list(*_client_objs); /* Initialize Update Client */ FP1<void, int32_t> callback(this, &ServiceClient::update_error_callback); UpdateClient::UpdateClient(callback); } #endif /* MBED_CLOUD_CLIENT_SUPPORT_UPDATE */ /* Device Object is mandatory. Get instance and add it to object list */ M2MDevice *device_object = device_object_from_storage(); if (device_object) { M2MObjectInstance* instance = device_object->object_instance(0); if (instance) { M2MResource *res = instance->resource(DEVICE_MANUFACTURER); if (res) { res->publish_value_in_registration_msg(true); } res = instance->resource(DEVICE_MODEL_NUMBER); if (res) { res->publish_value_in_registration_msg(true); } res = instance->resource(DEVICE_SERIAL_NUMBER); if (res) { res->publish_value_in_registration_msg(true); } } /* Publish device object resource to mds */ M2MResourceList list = device_object->object_instance()->resources(); if(!list.empty()) { M2MResourceList::const_iterator it; it = list.begin(); for ( ; it != list.end(); it++ ) { (*it)->set_register_uri(true); } } /* Add Device Object to object list. */ _client_objs->push_back(device_object); } internal_event(State_Bootstrap); } else if (_current_state == State_Success) { state_success(); } } ConnectorClient &ServiceClient::connector_client() { return _connector_client; } const ConnectorClient &ServiceClient::connector_client() const { return _connector_client; } // generates an internal event. called from within a state // function to transition to a new state void ServiceClient::internal_event(StartupMainState new_state) { tr_debug("ServiceClient::internal_event: state: %d -> %d", _current_state, new_state); _event_generated = true; _current_state = new_state; if (!_state_engine_running) { state_engine(); } } // the state engine executes the state machine states void ServiceClient::state_engine(void) { tr_debug("ServiceClient::state_engine"); // this simple flagging gets rid of recursive calls to this method _state_engine_running = true; // while events are being generated keep executing states while (_event_generated) { _event_generated = false; // event used up, reset flag state_function(_current_state); } _state_engine_running = false; } void ServiceClient::state_function(StartupMainState current_state) { switch (current_state) { case State_Init: // -> Goes to bootstrap state case State_Bootstrap: // -> State_Register OR State_Failure state_bootstrap(); break; case State_Register: // -> State_Succes OR State_Failure state_register(); break; case State_Success: // return success to user state_success(); break; case State_Failure: // return error to user state_failure(); break; case State_Unregister: // return error to user state_unregister(); break; } } void ServiceClient::state_bootstrap() { tr_info("ServiceClient::state_bootstrap()"); bool credentials_ready = _connector_client.connector_credentials_available(); bool bootstrap = _connector_client.use_bootstrap(); tr_info("ServiceClient::state_bootstrap() - lwm2m credentials available: %d", credentials_ready); tr_info("ServiceClient::state_bootstrap() - use bootstrap: %d", bootstrap); if (credentials_ready || !bootstrap) { internal_event(State_Register); } else { _connector_client.start_bootstrap(); } } void ServiceClient::state_register() { tr_info("ServiceClient::state_register()"); _connector_client.start_registration(_client_objs); } void ServiceClient::registration_process_result(ConnectorClient::StartupSubStateRegistration status) { tr_debug("ServiceClient::registration_process_result(): status: %d", status); if (status == ConnectorClient::State_Registration_Success) { internal_event(State_Success); } else if(status == ConnectorClient::State_Registration_Failure || status == ConnectorClient::State_Bootstrap_Failure){ internal_event(State_Failure); // XXX: the status should be saved to eg. event object } if(status == ConnectorClient::State_Bootstrap_Success) { internal_event(State_Register); } if(status == ConnectorClient::State_Unregistered) { internal_event(State_Unregister); } if (status == ConnectorClient::State_Registration_Updated) { _service_callback.complete(ServiceClientCallback::Service_Client_Status_Register_Updated); } } void ServiceClient::connector_error(M2MInterface::Error error, const char *reason) { tr_error("ServiceClient::connector_error() error %d", (int)error); if (_current_state == State_Register) { registration_process_result(ConnectorClient::State_Registration_Failure); } else if (_current_state == State_Bootstrap) { registration_process_result(ConnectorClient::State_Bootstrap_Failure); } _service_callback.error(int(error),reason); internal_event(State_Failure); } void ServiceClient::value_updated(M2MBase *base, M2MBase::BaseType type) { tr_debug("ServiceClient::value_updated()"); _service_callback.value_updated(base, type); } void ServiceClient::state_success() { tr_info("ServiceClient::state_success()"); // this is verified already at client API level, but this might still catch some logic failures _service_callback.complete(ServiceClientCallback::Service_Client_Status_Registered); } void ServiceClient::state_failure() { tr_error("ServiceClient::state_failure()"); _service_callback.complete(ServiceClientCallback::Service_Client_Status_Failure); } void ServiceClient::state_unregister() { tr_debug("ServiceClient::state_unregister()"); _service_callback.complete(ServiceClientCallback::Service_Client_Status_Unregistered); } M2MDevice* ServiceClient::device_object_from_storage() { M2MDevice *device_object = M2MInterfaceFactory::create_device(); if (device_object == NULL) { return NULL; } const size_t buffer_size = 128; uint8_t buffer[buffer_size]; size_t size = 0; #ifdef MBED_CLOUD_CLIENT_SUPPORT_UPDATE uint8_t guid[sizeof(arm_uc_guid_t)] = {0}; // Read out the binary Vendor UUID ccs_status_e status = (ccs_status_e)UpdateClient::getVendorId(guid, sizeof(arm_uc_guid_t), &size); // Format the binary Vendor UUID into a hex string if (status == CCS_STATUS_SUCCESS) { size_t j = 0; for(size_t i = 0; i < size; i++) { buffer[j++] = hex_table[(guid[i] >> 4) & 0xF]; buffer[j++] = hex_table[(guid[i] >> 0) & 0xF]; } buffer[j] = '\0'; device_object->create_resource(M2MDevice::Manufacturer, String((char*)buffer, size * 2)); } // Read out the binary Class UUID status = (ccs_status_e)UpdateClient::getClassId(guid, sizeof(arm_uc_guid_t), &size); // Format the binary Class UUID into a hex string if (status == CCS_STATUS_SUCCESS) { size_t j = 0; for(size_t i = 0; i < size; i++) { buffer[j++] = hex_table[(guid[i] >> 4) & 0xF]; buffer[j++] = hex_table[(guid[i] >> 0) & 0xF]; } buffer[j] = '\0'; device_object->create_resource(M2MDevice::ModelNumber, String((char*)buffer, size * 2)); } #else ccs_status_e status = get_config_parameter(g_fcc_manufacturer_parameter_name, buffer, buffer_size, &size); if (status == CCS_STATUS_SUCCESS) { device_object->create_resource(M2MDevice::Manufacturer, String((char*)buffer, size)); } status = get_config_parameter(g_fcc_model_number_parameter_name, buffer, buffer_size, &size); if (status == CCS_STATUS_SUCCESS) { device_object->create_resource(M2MDevice::ModelNumber, String((char*)buffer, size)); } #endif status = get_config_parameter(g_fcc_device_serial_number_parameter_name, buffer, buffer_size, &size); if (status == CCS_STATUS_SUCCESS) { device_object->create_resource(M2MDevice::SerialNumber, String((char*)buffer, size)); } status = get_config_parameter(g_fcc_device_type_parameter_name, buffer, buffer_size, &size); if (status == CCS_STATUS_SUCCESS) { device_object->create_resource(M2MDevice::DeviceType, String((char*)buffer, size)); } status = get_config_parameter(g_fcc_hardware_version_parameter_name, buffer, buffer_size, &size); if (status == CCS_STATUS_SUCCESS) { device_object->create_resource(M2MDevice::HardwareVersion, String((char*)buffer, size)); } status = get_config_parameter(KEY_DEVICE_SOFTWAREVERSION, buffer, buffer_size, &size); if (status == CCS_STATUS_SUCCESS) { device_object->create_resource(M2MDevice::SoftwareVersion, String((char*)buffer, size)); } uint8_t data[4] = {0}; uint32_t value; status = get_config_parameter(g_fcc_memory_size_parameter_name, data, 4, &size); if (status == CCS_STATUS_SUCCESS) { memcpy(&value, data, 4); device_object->create_resource(M2MDevice::MemoryTotal, value); tr_debug("ServiceClient::device_object_from_storage() - setting memory total value %" PRIu32 " (%s)", value, tr_array(data, 4)); } status = get_config_parameter(g_fcc_current_time_parameter_name, data, 4, &size); if (status == CCS_STATUS_SUCCESS) { memcpy(&value, data, 4); device_object->create_resource(M2MDevice::CurrentTime, value); tr_debug("ServiceClient::device_object_from_storage() - setting current time value %" PRIu32 " (%s)", value, tr_array(data, 4)); } status = get_config_parameter(g_fcc_device_time_zone_parameter_name, buffer, buffer_size, &size); if (status == CCS_STATUS_SUCCESS) { device_object->create_resource(M2MDevice::Timezone, String((char*)buffer, size)); } status = get_config_parameter(g_fcc_offset_from_utc_parameter_name, buffer, buffer_size, &size); if (status == CCS_STATUS_SUCCESS) { device_object->create_resource(M2MDevice::UTCOffset, String((char*)buffer, size)); } return device_object; } /** * \brief Set resource value in the Device Object * * \param resource Device enum to have value set. * \param value String object. * \return True if successful, false otherwise. */ bool ServiceClient::set_device_resource_value(M2MDevice::DeviceResource resource, const std::string& value) { return set_device_resource_value(resource, value.c_str(), value.size() - 1); } /** * \brief Set resource value in the Device Object * * \param resource Device enum to have value set. * \param value Byte buffer. * \param length Buffer length. * \return True if successful, false otherwise. */ bool ServiceClient::set_device_resource_value(M2MDevice::DeviceResource resource, const char* value, uint32_t length) { bool retval = false; /* sanity check */ if (value && (length < 256) && (length > 0)) { #ifdef MBED_CLOUD_CLIENT_SUPPORT_UPDATE /* Pass resource value to Update Client. Used for validating the manifest. */ switch (resource) { case M2MDevice::Manufacturer: ARM_UC_SetVendorId((const uint8_t*) value, length); break; case M2MDevice::ModelNumber: ARM_UC_SetClassId((const uint8_t*) value, length); break; default: break; } #endif /* Convert resource to printable string if necessary */ /* Getting object instance from factory */ M2MDevice *device_object = M2MInterfaceFactory::create_device(); /* Check device object and resource both are present */ if (device_object && device_object->is_resource_present(resource)) { /* set counter to not-zero */ uint8_t printable_length = 0xFF; /* set printable_length to 0 if the buffer is not printable */ for (uint8_t index = 0; index < length; index++) { /* break if character is not printable */ if ((value[index] < ' ') || (value[index] > '~')) { printable_length = 0; break; } } /* resource is a string */ if (printable_length != 0) { /* reset counter */ printable_length = 0; /* find actual printable length */ for ( ; printable_length < length; printable_length++) { /* break prematurely if end-of-string character is found */ if (value[printable_length] == '\0') { break; } } /* convert to string and set value in object */ String string_value(value, printable_length); retval = device_object->set_resource_value(resource, string_value); } else { /* resource is a byte array */ char value_buffer[0xFF] = { 0 }; /* count length */ uint8_t index = 0; /* convert byte array to string */ for ( ; (index < length) && ((2*index +1) < 0xFF); index++) { uint8_t byte = value[index]; value_buffer[2 * index] = hex_table[byte >> 4]; value_buffer[2 * index + 1] = hex_table[byte & 0x0F]; } /* convert to string and set value in object */ String string_value(value_buffer, 2 * (index - 1)); retval = device_object->set_resource_value(resource, string_value); } } } return retval; } #ifdef MBED_CLOUD_CLIENT_SUPPORT_UPDATE void ServiceClient::set_update_authorize_handler(void (*handler)(int32_t request)) { UpdateClient::set_update_authorize_handler(handler); } void ServiceClient::update_authorize(int32_t request) { UpdateClient::update_authorize(request); } void ServiceClient::set_update_progress_handler(void (*handler)(uint32_t progress, uint32_t total)) { UpdateClient::set_update_progress_handler(handler); } void ServiceClient::update_error_callback(int32_t error) { _service_callback.error(error, ERROR_UPDATE); } #endif
36.45521
136
0.634873
ghsecuritylab
4f8ed4998c4eca25a989647b646df463b1ed3b44
1,596
cpp
C++
Source/ImGui/Private/ImGuiWidget.cpp
cl4nk/UnrealImGui
b0db66ff36974f4a52e07e094b152cd194e154a4
[ "MIT" ]
null
null
null
Source/ImGui/Private/ImGuiWidget.cpp
cl4nk/UnrealImGui
b0db66ff36974f4a52e07e094b152cd194e154a4
[ "MIT" ]
null
null
null
Source/ImGui/Private/ImGuiWidget.cpp
cl4nk/UnrealImGui
b0db66ff36974f4a52e07e094b152cd194e154a4
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "ImGuiPrivatePCH.h" #include "ImGui.h" #include "ImGuiModuleManager.h" #include "ImGuiWidget.h" #define LOCTEXT_NAMESPACE "UMG" void UImGuiWidget::SetAsCurrent() const { if (MyImGuiWidget.IsValid()) { if (FImGuiContextProxy * ContextProxy = MyImGuiWidget->GetContextProxy()) { ContextProxy->SetAsCurrent(); } } } void UImGuiWidget::SetContextName(FName InContextName) { ContextName = InContextName; if (MyImGuiWidget.IsValid()) { //Module should be loaded, the check is inside the get FImGuiModule& ImGuiModule = FImGuiModule::Get(); FImGuiModuleManager* ImGuiModuleManager = ImGuiModule.GetImGuiModuleManager(); MyImGuiWidget->SetContextProxy(ImGuiModuleManager ? ImGuiModuleManager->GetContextProxy(GetWorld(), ContextName) : nullptr); } } void UImGuiWidget::ReleaseSlateResources(bool bReleaseChildren) { Super::ReleaseSlateResources(bReleaseChildren); MyImGuiWidget.Reset(); } TSharedRef<SWidget> UImGuiWidget::RebuildWidget() { //Module should be loaded, the check is inside the get FImGuiModule& ImGuiModule = FImGuiModule::Get(); FImGuiModuleManager* ImGuiModuleManager = ImGuiModule.GetImGuiModuleManager(); MyImGuiWidget = SNew(SImGuiWidget). IsFocusable(IsFocusable). ContextProxy(ImGuiModuleManager ? ImGuiModuleManager->GetContextProxy(GetWorld(), ContextName) : nullptr); return MyImGuiWidget.ToSharedRef(); } #if WITH_EDITOR const FText UImGuiWidget::GetPaletteCategory() { return LOCTEXT("Misc", "Misc"); } #endif #undef LOCTEXT_NAMESPACE
23.820896
126
0.774436
cl4nk
4f91f944caf2b5460622afaa978b6b27cf7ce393
106,921
cpp
C++
VEngine/VEngine/src/Context.cpp
Hukunaa/VEngine
a5fe1e9ed4b43ba5d2c79bbbb7e0eac07d076f2d
[ "MIT" ]
3
2020-03-18T19:45:18.000Z
2021-05-07T05:23:54.000Z
VEngine/VEngine/src/Context.cpp
Hukunaa/VEngine
a5fe1e9ed4b43ba5d2c79bbbb7e0eac07d076f2d
[ "MIT" ]
null
null
null
VEngine/VEngine/src/Context.cpp
Hukunaa/VEngine
a5fe1e9ed4b43ba5d2c79bbbb7e0eac07d076f2d
[ "MIT" ]
null
null
null
#include <VContext.h> #include <array> #include <set> #include <optix_function_table_definition.h> #ifdef NDEBUG const bool enableValidationLayers = false; #else const bool enableValidationLayers = true; #endif #define WIDTH 1920 #define HEIGHT 1080 #define INDEX_RAYGEN 0 #define INDEX_MISS 1 #define INDEX_SHADOWMISS 2 #define INDEX_SHADOWHIT 4 #define INDEX_CLOSEST_HIT 3 #define NUM_SHADER_GROUPS 5 #pragma region Queues QueueFamilyIndices VContext::FindQueueFamilies(VkPhysicalDevice p_device) { /** A queue family just describes a set of queues with identical properties. The device supports three kinds of queues: One kind can do graphics, compute, transfer, and sparse binding operations */ QueueFamilyIndices indices; //Get QueueFamily size from the GPU uint32_t queueFamilyCount = 0; vkGetPhysicalDeviceQueueFamilyProperties(p_device, &queueFamilyCount, nullptr); //Get actual info of the GPU's QueueFamily device.queueFamilyProperties.resize(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(p_device, &queueFamilyCount, device.queueFamilyProperties.data()); int i = 0; for (const auto& queueFamily : device.queueFamilyProperties) { //Finding support for image rendering (presentation) VkBool32 presentSupport = false; vkGetPhysicalDeviceSurfaceSupportKHR(p_device, i, device.surface, &presentSupport); if (presentSupport) { indices.presentFamily = i; } //GraphicFamily and Present Family might very likely be the same id, but for support compatibility purpose, //we separate them into 2 queue Famlilies if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) indices.graphicsFamily = i; if (indices.isComplete()) break; i++; } return indices; } #pragma endregion #pragma region GPU Selection bool VContext::IsDeviceSuitable(VkPhysicalDevice p_device) { vkGetPhysicalDeviceMemoryProperties(p_device, &device.memoryProperties); queueFamily = FindQueueFamilies(p_device); const bool extensionsSupported = checkDeviceExtensionSupport(p_device); bool swapChainAdequate = false; if (extensionsSupported) { const SwapChainSupportDetails swapChainSupport = querySwapChainSupport(p_device); swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty(); } else { std::cout << "Extension isn't supported by the GPU!\n"; } return queueFamily.isComplete() && extensionsSupported && swapChainAdequate; } bool VContext::checkDeviceExtensionSupport(VkPhysicalDevice device) const { uint32_t extensionCount; vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr); std::vector<VkExtensionProperties> availableExtensions(extensionCount); vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data()); std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end()); for (const auto& extension : availableExtensions) { requiredExtensions.erase(extension.extensionName); } for (auto ext : availableExtensions) std::cout << ext.extensionName << '\n'; return requiredExtensions.empty(); } void VContext::SelectGPU() { device.physicalDevice = nullptr; uint32_t deviceCount = 0; vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr); if (deviceCount == 0) throw std::runtime_error("No GPU support found For the Renderer"); std::vector<VkPhysicalDevice> GPUs(deviceCount); vkEnumeratePhysicalDevices(instance, &deviceCount, GPUs.data()); std::cout << "GPUs available: \n"; for (size_t i = 0; i < GPUs.size(); ++i) { vkGetPhysicalDeviceProperties(GPUs[i], &device.properties); std::cout << i << ": " << device.properties.deviceName << '\n'; } int id; while (true) { std::cin >> id; if (IsDeviceSuitable(GPUs[id])) { device.physicalDevice = GPUs[id]; vkGetPhysicalDeviceMemoryProperties(device.physicalDevice, &device.memoryProperties); break; } std::cout << "Device is not suitable for the Renderer! \n"; } vkGetPhysicalDeviceProperties(device.physicalDevice, &device.properties); std::cout << "Selected GPU: " << device.properties.deviceName << '\n'; if (device.physicalDevice == nullptr) { throw std::runtime_error("failed to find a suitable GPU!"); } } #pragma endregion #pragma region Instance void VContext::CREATETHEFUCKINGWINDOW(int width, int height, const char* name) { window = glfwCreateWindow(width, height, name, nullptr, nullptr); fd = new int(-1); } void VContext::SetupInstance() { if (!CheckValidationLayerSupport()) { throw std::runtime_error("validation layers requested, but not available!"); } VkApplicationInfo appInfo = {}; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pApplicationName = "VEngine"; appInfo.applicationVersion = VK_MAKE_VERSION(0, 0, 1); appInfo.pEngineName = "VRenderer"; appInfo.engineVersion = VK_MAKE_VERSION(0, 0, 1); appInfo.apiVersion = VK_API_VERSION_1_0; std::cout << appInfo.apiVersion << std::endl; VkInstanceCreateInfo createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; createInfo.pApplicationInfo = &appInfo; auto extensions = GetRequieredExtensions(); createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size()); createInfo.ppEnabledExtensionNames = extensions.data(); VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo; if (enableValidationLayers) { createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size()); createInfo.ppEnabledLayerNames = validationLayers.data(); populateDebugMessengerCreateInfo(debugCreateInfo); createInfo.pNext = static_cast<VkDebugUtilsMessengerCreateInfoEXT*>(&debugCreateInfo); } else { createInfo.enabledLayerCount = 0; createInfo.pNext = nullptr; } if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) { throw std::runtime_error("failed to create instance!"); } const VkResult err = glfwCreateWindowSurface(instance, window, nullptr, &device.surface); if (err) throw std::runtime_error("failed to create surface!"); } void VContext::createLogicalDevice() { QueueFamilyIndices indices = FindQueueFamilies(device.physicalDevice); std::vector<VkDeviceQueueCreateInfo> queueCreateInfos; std::set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value() }; float queuePriority = 1.0f; for (uint32_t queueFamily : uniqueQueueFamilies) { VkDeviceQueueCreateInfo queueCreateInfo = {}; queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueCreateInfo.queueFamilyIndex = queueFamily; queueCreateInfo.queueCount = 1; queueCreateInfo.pQueuePriorities = &queuePriority; queueCreateInfos.push_back(queueCreateInfo); } VkDeviceCreateInfo createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size()); createInfo.pQueueCreateInfos = queueCreateInfos.data(); createInfo.pEnabledFeatures = &device.enabledFeatures; createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size()); createInfo.ppEnabledExtensionNames = deviceExtensions.data(); if (enableValidationLayers) { createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size()); createInfo.ppEnabledLayerNames = validationLayers.data(); } else { createInfo.enabledLayerCount = 0; } if (vkCreateDevice(device.physicalDevice, &createInfo, nullptr, &device.logicalDevice) != VK_SUCCESS) { throw std::runtime_error("failed to create logical device!"); } vkGetDeviceQueue(device.logicalDevice, indices.graphicsFamily.value(), 0, &graphicsQueue); vkGetDeviceQueue(device.logicalDevice, indices.presentFamily.value(), 0, &presentQueue); } SwapChainSupportDetails VContext::querySwapChainSupport(VkPhysicalDevice p_device) const { SwapChainSupportDetails details; vkGetPhysicalDeviceSurfaceCapabilitiesKHR(p_device, device.surface, &details.capabilities); uint32_t formatCount; vkGetPhysicalDeviceSurfaceFormatsKHR(p_device, device.surface, &formatCount, nullptr); if (formatCount != 0) { details.formats.resize(formatCount); vkGetPhysicalDeviceSurfaceFormatsKHR(p_device, device.surface, &formatCount, details.formats.data()); } uint32_t presentModeCount; vkGetPhysicalDeviceSurfacePresentModesKHR(p_device, device.surface, &presentModeCount, nullptr); if (presentModeCount != 0) { details.presentModes.resize(presentModeCount); vkGetPhysicalDeviceSurfacePresentModesKHR(p_device, device.surface, &presentModeCount, details.presentModes.data()); } return details; } void VContext::CHECK_ERROR(VkResult result) { if (result != VK_SUCCESS) throw std::runtime_error(("Error with Vulkan function")); } void VContext::setupSwapChain(uint32_t width, uint32_t height, bool vsync) { if (!getSupportedDepthFormat(device.physicalDevice, &depthFormat)) throw std::runtime_error("can't find suitable format"); VkSwapchainKHR oldSwapchain = swapChain.swapChain; // Get physical device surface properties and formats VkSurfaceCapabilitiesKHR surfCaps; CHECK_ERROR(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device.physicalDevice, device.surface, &surfCaps)); minImageCount = surfCaps.minImageCount; // Get available present modes uint32_t presentModeCount; CHECK_ERROR(vkGetPhysicalDeviceSurfacePresentModesKHR(device.physicalDevice, device.surface, &presentModeCount, nullptr)); assert(presentModeCount > 0); std::vector<VkPresentModeKHR> presentModes(presentModeCount); CHECK_ERROR(vkGetPhysicalDeviceSurfacePresentModesKHR(device.physicalDevice, device.surface, &presentModeCount, presentModes.data())); VkExtent2D swapchain_extent = {}; // If width (and height) equals the special value 0xFFFFFFFF, the size of the surface will be set by the swapchain if (surfCaps.currentExtent.width == static_cast<uint32_t>(-1)) { // If the surface size is undefined, the size is set to // the size of the images requested. swapchain_extent.width = width; swapchain_extent.height = height; } else { // If the surface size is defined, the swap chain size must match swapchain_extent = surfCaps.currentExtent; width = surfCaps.currentExtent.width; height = surfCaps.currentExtent.height; } // Select a present mode for the swapchain // The VK_PRESENT_MODE_FIFO_KHR mode must always be present as per spec // This mode waits for the vertical blank ("v-sync") VkPresentModeKHR swapchain_present_mode = VK_PRESENT_MODE_FIFO_KHR; // If v-sync is not requested, try to find a mailbox mode // It's the lowest latency non-tearing present mode available if (!vsync) { for (size_t i = 0; i < presentModeCount; i++) { if (presentModes[i] == VK_PRESENT_MODE_MAILBOX_KHR) { swapchain_present_mode = VK_PRESENT_MODE_MAILBOX_KHR; break; } if ((swapchain_present_mode != VK_PRESENT_MODE_MAILBOX_KHR) && (presentModes[i] == VK_PRESENT_MODE_IMMEDIATE_KHR)) { swapchain_present_mode = VK_PRESENT_MODE_IMMEDIATE_KHR; } } } // Determine the number of images uint32_t desired_swapchain_images = surfCaps.minImageCount + 1; if ((surfCaps.maxImageCount > 0) && (desired_swapchain_images > surfCaps.maxImageCount)) { desired_swapchain_images = surfCaps.maxImageCount; } // Find the transformation of the surface VkSurfaceTransformFlagsKHR preTransform; if (surfCaps.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) { // We prefer a non-rotated transform preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; } else { preTransform = surfCaps.currentTransform; } // Find a supported composite alpha format (not all devices support alpha opaque) VkCompositeAlphaFlagBitsKHR compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; // Simply select the first composite alpha format available std::vector<VkCompositeAlphaFlagBitsKHR> compositeAlphaFlags = { VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR, VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR, VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR, }; for (auto& compositeAlphaFlag : compositeAlphaFlags) { if (surfCaps.supportedCompositeAlpha & compositeAlphaFlag) { compositeAlpha = compositeAlphaFlag; break; } } VkSwapchainCreateInfoKHR swapchain_ci = {}; swapchain_ci.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; swapchain_ci.pNext = nullptr; swapchain_ci.surface = device.surface; swapchain_ci.minImageCount = desired_swapchain_images; swapchain_ci.imageFormat = swapChain.colorFormat; swapchain_ci.imageColorSpace = swapChain.colorSpace; swapchain_ci.imageExtent = { swapchain_extent.width, swapchain_extent.height }; swapchain_ci.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; swapchain_ci.preTransform = static_cast<VkSurfaceTransformFlagBitsKHR>(preTransform); swapchain_ci.imageArrayLayers = 1; swapchain_ci.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; swapchain_ci.queueFamilyIndexCount = 0; swapchain_ci.pQueueFamilyIndices = nullptr; swapchain_ci.presentMode = swapchain_present_mode; swapchain_ci.oldSwapchain = oldSwapchain; // Setting clipped to VK_TRUE allows the implementation to discard rendering outside of the surface area swapchain_ci.clipped = VK_TRUE; swapchain_ci.compositeAlpha = compositeAlpha; // Enable transfer source on swap chain images if supported if (surfCaps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) { swapchain_ci.imageUsage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; } // Enable transfer destination on swap chain images if supported if (surfCaps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT) { swapchain_ci.imageUsage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT; } CHECK_ERROR(vkCreateSwapchainKHR(device.logicalDevice, &swapchain_ci, nullptr, &swapChain.swapChain)); // If an existing swap chain is re-created, destroy the old swap chain // This also cleans up all the presentable images if (oldSwapchain != nullptr) { for (uint32_t i = 0; i < swapChain.imageCount; i++) { vkDestroyImageView(device.logicalDevice, swapChain.buffers[i].view, nullptr); } vkDestroySwapchainKHR(device.logicalDevice, oldSwapchain, nullptr); } CHECK_ERROR(vkGetSwapchainImagesKHR(device.logicalDevice, swapChain.swapChain, &swapChain.imageCount, nullptr)); // Get the swap chain images swapChain.images.resize(swapChain.imageCount); CHECK_ERROR(vkGetSwapchainImagesKHR(device.logicalDevice, swapChain.swapChain, &swapChain.imageCount, swapChain.images.data())); // Get the swap chain buffers containing the image and imageview swapChain.buffers.resize(swapChain.imageCount); for (uint32_t i = 0; i < swapChain.imageCount; i++) { VkImageViewCreateInfo colorAttachmentView = {}; colorAttachmentView.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; colorAttachmentView.pNext = nullptr; colorAttachmentView.format = swapChain.colorFormat; colorAttachmentView.components = { VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A }; colorAttachmentView.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; colorAttachmentView.subresourceRange.baseMipLevel = 0; colorAttachmentView.subresourceRange.levelCount = 1; colorAttachmentView.subresourceRange.baseArrayLayer = 0; colorAttachmentView.subresourceRange.layerCount = 1; colorAttachmentView.viewType = VK_IMAGE_VIEW_TYPE_2D; colorAttachmentView.flags = 0; swapChain.buffers[i].image = swapChain.images[i]; colorAttachmentView.image = swapChain.buffers[i].image; vkCreateImageView(device.logicalDevice, &colorAttachmentView, nullptr, &swapChain.buffers[i].view); } } uint32_t VContext::getMemoryType(uint32_t typeBits, VkMemoryPropertyFlags properties, VkBool32* memTypeFound) const { for (uint32_t i = 0; i < device.memoryProperties.memoryTypeCount; i++) { if ((typeBits & 1) == 1) { if ((device.memoryProperties.memoryTypes[i].propertyFlags & properties) == properties) { if (memTypeFound) { *memTypeFound = true; } return i; } } typeBits >>= 1; } if (memTypeFound) { *memTypeFound = false; return 0; } throw std::runtime_error("Could not find a matching memory type"); } VkCommandBuffer VContext::createCommandBuffer(VkCommandBufferLevel level, bool begin) const { VkCommandBufferAllocateInfo cmdBufAllocateInfo = Initializers::commandBufferAllocateInfo(commandPool, level, 1); VkCommandBuffer cmdBuffer; vkAllocateCommandBuffers(device.logicalDevice, &cmdBufAllocateInfo, &cmdBuffer); // If requested, also start recording for the new command buffer if (begin) { VkCommandBufferBeginInfo cmdBufInfo = Initializers::commandBufferBeginInfo(); vkBeginCommandBuffer(cmdBuffer, &cmdBufInfo); } return cmdBuffer; } bool VContext::CheckValidationLayerSupport() const { uint32_t layerCount; vkEnumerateInstanceLayerProperties(&layerCount, nullptr); std::vector<VkLayerProperties> availableLayers(layerCount); vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data()); for (const char* layerName : validationLayers) { bool layerFound = false; for (const auto& layerProperties : availableLayers) { if (strcmp(layerName, layerProperties.layerName) == 0) { layerFound = true; break; } } if (!layerFound) { return false; } } return true; } void VContext::CleanUp() { m_pixelBufferIn.destroy(m_alloc); // Closing Handle m_pixelBufferOut.destroy(m_alloc); // Closing Handle if (m_dState != 0) { CUDA_CHECK(cudaFree((void*)m_dState)); } if (m_dScratch != 0) { CUDA_CHECK(cudaFree((void*)m_dScratch)); } if (m_dIntensity != 0) { CUDA_CHECK(cudaFree((void*)m_dIntensity)); } if (m_dMinRGB != 0) { CUDA_CHECK(cudaFree((void*)m_dMinRGB)); } if (enableValidationLayers) DestroyDebugUtilsMessengerEXT(instance, debugMessenger, nullptr); vkDestroyCommandPool(device.logicalDevice, commandPool, nullptr); if (swapChain.swapChain != nullptr) { for (uint32_t i = 0; i < swapChain.imageCount; i++) { vkDestroyImageView(device.logicalDevice, swapChain.buffers[i].view, nullptr); } } if (device.surface != nullptr) { vkDestroySwapchainKHR(device.logicalDevice, swapChain.swapChain, nullptr); vkDestroySurfaceKHR(instance, device.surface, nullptr); } device.surface = nullptr; swapChain.swapChain = nullptr; for (auto frame_buffer : swapChainFramebuffers) { vkDestroyFramebuffer(device.logicalDevice, frame_buffer, nullptr); } for (auto& obj : bottomLevelAS) vkFreeMemory(device.logicalDevice, obj.memory, nullptr); vkFreeMemory(device.logicalDevice, topLevelAS.memory, nullptr); vkDestroyPipeline(device.logicalDevice, Rpipeline, nullptr); vkDestroyPipelineLayout(device.logicalDevice, RpipelineLayout, nullptr); vkDestroyRenderPass(device.logicalDevice, renderPass, nullptr); vkDestroySwapchainKHR(device.logicalDevice, swapChain.swapChain, nullptr); for (auto& fence : waitFences) vkDestroyFence(device.logicalDevice, fence, nullptr); vkDestroySemaphore(device.logicalDevice, semaphores.presentComplete, nullptr); vkDestroySemaphore(device.logicalDevice, semaphores.renderComplete, nullptr); dev.destroyBuffer(pixelBufferOut); vkFreeMemory(device.logicalDevice, storageImage.memory, nullptr); vkFreeMemory(device.logicalDevice, accImage.memory, nullptr); vkDestroyDevice(device.logicalDevice, nullptr); vkDestroySurfaceKHR(GetInstance(), device.surface, nullptr); vkDestroyInstance(GetInstance(), nullptr); glfwDestroyWindow(GetWindow()); glfwTerminate(); } void VContext::UpdateObjects(std::vector<VObject>& objects) { const VkCommandBuffer cmdBuffer = createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); //Generate TLAS std::vector<GeometryInstance> instances; for(auto& obj: objects) instances.push_back(obj.m_mesh.meshGeometry); //Get all instances and create a buffer with all of them VBuffer::Buffer instanceBuffer; createBuffer(VK_BUFFER_USAGE_RAY_TRACING_BIT_NV, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &instanceBuffer, sizeof(GeometryInstance) * instances.size(), instances.data()); //Generate TLAS AccelerationStructure newDataAS; CreateTopLevelAccelerationStructure(newDataAS, instances.size()); //Get memory requirements VkMemoryRequirements2 memReqTopLevelAS; VkAccelerationStructureMemoryRequirementsInfoNV memoryRequirementsInfo2{}; memoryRequirementsInfo2.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_MEMORY_REQUIREMENTS_INFO_NV; memoryRequirementsInfo2.type = VK_ACCELERATION_STRUCTURE_MEMORY_REQUIREMENTS_TYPE_BUILD_SCRATCH_NV; memoryRequirementsInfo2.accelerationStructure = newDataAS.accelerationStructure; vkGetAccelerationStructureMemoryRequirementsNV(device.logicalDevice, &memoryRequirementsInfo2, &memReqTopLevelAS); const VkDeviceSize scratchBufferSize = memReqTopLevelAS.memoryRequirements.size; //Generate Scratch buffer VBuffer::Buffer scratchBuffer; createBuffer( VK_BUFFER_USAGE_RAY_TRACING_BIT_NV, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &scratchBuffer, scratchBufferSize); //Generate build info for TLAS VkAccelerationStructureInfoNV buildInfo{}; buildInfo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_INFO_NV; buildInfo.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_NV; buildInfo.flags = /*VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_BUILD_BIT_NV |*/ VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_COMPACTION_BIT_NV; buildInfo.pGeometries = nullptr; buildInfo.geometryCount = 0; buildInfo.instanceCount = instances.size(); //Build Actual TLAS vkCmdBuildAccelerationStructureNV( cmdBuffer, &buildInfo, instanceBuffer.buffer, 0, VK_FALSE, newDataAS.accelerationStructure, nullptr, scratchBuffer.buffer, 0); VkMemoryBarrier memoryBarrier = Initializers::memoryBarrier(); memoryBarrier.srcAccessMask = VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_NV | VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_NV; memoryBarrier.dstAccessMask = VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_NV | VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_NV; vkCmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_NV, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_NV, 0, 1, &memoryBarrier, 0, nullptr, 0, nullptr); vkCmdCopyAccelerationStructureNV(cmdBuffer, topLevelAS.accelerationStructure, newDataAS.accelerationStructure, VK_COPY_ACCELERATION_STRUCTURE_MODE_CLONE_NV); flushCommandBuffer(cmdBuffer, graphicsQueue, true); vkDestroyAccelerationStructureNV(device.logicalDevice, newDataAS.accelerationStructure, nullptr); vkFreeMemory(device.logicalDevice, newDataAS.memory, nullptr); instances.clear(); scratchBuffer.destroy(); instanceBuffer.destroy(); } void VContext::InitOptix() { cudaFree(nullptr); m_alloc.init(device.logicalDevice, device.physicalDevice); CUcontext cuCtx; CUresult cuRes = cuCtxGetCurrent(&cuCtx); if (cuRes != CUDA_SUCCESS) { std::cerr << "Error querying current context: error code " << cuRes << "\n"; } OPTIX_CHECK(optixInit()); OPTIX_CHECK(optixDeviceContextCreate(cuCtx, nullptr, &m_optixDevice)); OPTIX_CHECK(optixDeviceContextSetLogCallback(m_optixDevice, context_log_cb, nullptr, 4)); OptixPixelFormat pixelFormat = OPTIX_PIXEL_FORMAT_FLOAT3; size_t sizeofPixel = sizeof(float3); CUDA_CHECK(cudaStreamCreate(&cudaStream)); m_dOptions.inputKind = OPTIX_DENOISER_INPUT_RGB; m_dOptions.pixelFormat = pixelFormat; OPTIX_CHECK(optixDenoiserCreate(m_optixDevice, &m_dOptions, &m_denoiser)); OPTIX_CHECK(optixDenoiserSetModel(m_denoiser, OPTIX_DENOISER_MODEL_KIND_HDR, nullptr, 0)); AllocateBuffers(); } void VContext::AllocateBuffers() { /*m_pixelBufferIn.destroy(m_alloc); // Closing Handle m_pixelBufferOut.destroy(m_alloc); // Closing Handle if (m_dState != 0) { CUDA_CHECK(cudaFree((void*)m_dState)); } if (m_dScratch != 0) { CUDA_CHECK(cudaFree((void*)m_dScratch)); } if (m_dIntensity != 0) { CUDA_CHECK(cudaFree((void*)m_dIntensity)); } if (m_dMinRGB != 0) { CUDA_CHECK(cudaFree((void*)m_dMinRGB)); } vk::DeviceSize bufferSize = WIDTH * HEIGHT * 3 * sizeof(float); // Using direct method vk::BufferUsageFlags usage{ vk::BufferUsageFlagBits::eUniformBuffer | vk::BufferUsageFlagBits::eTransferDst }; m_pixelBufferIn.bufVk = m_alloc.createBuffer({ {}, bufferSize, usage }); m_pixelBufferOut.bufVk = m_alloc.createBuffer({ {}, bufferSize, usage | vk::BufferUsageFlagBits::eTransferSrc }); exportToCudaPointer(m_pixelBufferIn); exportToCudaPointer(m_pixelBufferOut); // Computing the amount of memory needed to do the denoiser OPTIX_CHECK(optixDenoiserComputeMemoryResources(m_denoiser, WIDTH, HEIGHT, &m_dSizes)); CUDA_CHECK(cudaMalloc((void**)&m_dState, m_dSizes.stateSizeInBytes)); CUDA_CHECK(cudaMalloc((void**)&m_dScratch, m_dSizes.recommendedScratchSizeInBytes)); CUDA_CHECK(cudaMalloc((void**)&m_dIntensity, sizeof(float))); CUDA_CHECK(cudaMalloc((void**)&m_dMinRGB, 4 * sizeof(float))); OPTIX_CHECK(optixDenoiserSetup(m_denoiser, cudaStream, WIDTH, HEIGHT, m_dState, m_dSizes.stateSizeInBytes, m_dScratch, m_dSizes.recommendedScratchSizeInBytes));*/ } void VContext::ConvertVulkan2Optix(VkImage& vkIMG, vk::Buffer& pixelBuffer) { /*nvvkpp::SingleCommandBuffer sc(dev, 0); vk::CommandBuffer cmdBuffer = sc.createCommandBuffer(); vk::DeviceSize bufferSize = WIDTH * HEIGHT * 3 * sizeof(float); vk::ImageSubresourceRange subresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1); //nvvkpp::image::setImageLayout(cmdBuffer, img, vk::ImageLayout::eGeneral, vk::ImageLayout::eTransferSrcOptimal, subresourceRange); setImageLayout(cmdBuffer, vkIMG, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, subresourceRange, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); vk::BufferImageCopy copyRegion; copyRegion.setImageSubresource({ vk::ImageAspectFlagBits::eColor, 0, 0, 1 }); copyRegion.setImageExtent(vk::Extent3D(WIDTH, HEIGHT, 1)); cmdBuffer.copyImageToBuffer(vkIMG, vk::ImageLayout::eTransferSrcOptimal, pixelBuffer, { copyRegion }); //nvvkpp::image::setImageLayout(cmdBuffer, img, vk::ImageLayout::eTransferSrcOptimal, vk::ImageLayout::eGeneral, subresourceRange); setImageLayout(cmdBuffer, vkIMG, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, subresourceRange, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); sc.flushCommandBuffer(cmdBuffer);*/ /*setImageLayout(cmdBuffer, img, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, subresourceRange, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);*/ /*setImageLayout(cmdBuffer, img, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, subresourceRange, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);*/ //nvvkpp::image::setImageLayout(cmdBuffer, img, vk::ImageLayout::eTransferSrcOptimal, vk::ImageLayout::eGeneral, subresourceRange); // Put back the image as it was' /*nvvkpp::image::setImageLayout(cmdBuffer, img, vk::ImageLayout::eTransferSrcOptimal, vk::ImageLayout::eGeneral, subresourceRange);*/ //-------------------------------------------------------------------------------------------------- // Get the Vulkan buffer and create the Cuda equivalent using the memory allocated in Vulkan // /*cudaBuffer.bufVk.allocation = memoryPixelBuffer; cudaBuffer.bufVk.buffer = pixelBufferOut; auto req = dev.getBufferMemoryRequirements(cudaBuffer.bufVk.buffer); cudaExternalMemoryHandleDesc cudaExtMemHandleDesc{}; cudaExtMemHandleDesc.type = cudaExternalMemoryHandleTypeOpaqueWin32; HANDLE handle = reinterpret_cast<HANDLE>(getVulkanMemoryHandle(dev, memoryPixelBuffer)); //int handle = getVulkanMemoryHandle(dev, memoryPixelBuffer); cudaExtMemHandleDesc.handle.win32.handle = handle; cudaExtMemHandleDesc.size = bufferSize; cudaExternalMemory_t cudaExtMemVertexBuffer{}; cudaError_t result; result = cudaImportExternalMemory(&cudaExtMemVertexBuffer, &cudaExtMemHandleDesc); std::cout << result << '\n'; cudaExternalMemoryBufferDesc cudaExtBufferDesc{}; cudaExtBufferDesc.offset = 0; cudaExtBufferDesc.size = req.size; cudaExtBufferDesc.flags = 0; cudaExternalMemoryGetMappedBuffer(&cudaBuffer.cudaPtr, cudaExtMemVertexBuffer, &cudaExtBufferDesc); OptixImage2D inputImage{ (CUdeviceptr)cudaBuffer.cudaPtr, WIDTH, HEIGHT, 0, 0, OPTIX_PIXEL_FORMAT_FLOAT4 };*/ } void VContext::ConvertOptix2Vulkan(VkImage& vkIMG, vk::Buffer& pixelBuffer) { nvvkpp::SingleCommandBuffer sc(dev, 0); vk::CommandBuffer cmdBuffer = sc.createCommandBuffer(); vk::DeviceSize bufferSize = WIDTH * HEIGHT * 4 * sizeof(float); //vk::Image img = vkIMG; vk::ImageSubresourceRange subresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1); //nvvkpp::image::setImageLayout(cmdBuffer, img, vk::ImageLayout::eGeneral, vk::ImageLayout::eTransferSrcOptimal, subresourceRange); /*setImageLayout(cmdBuffer, img, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, subresourceRange, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);*/ vk::BufferImageCopy copyRegion; copyRegion.setImageSubresource({ vk::ImageAspectFlagBits::eColor, 0, 0, 1 }); copyRegion.setImageOffset({ 0, 0, 0 }); copyRegion.setImageExtent(vk::Extent3D(WIDTH, HEIGHT, 1)); cmdBuffer.copyBufferToImage(pixelBuffer, vkIMG, vk::ImageLayout::eTransferSrcOptimal,{ copyRegion }); //nvvkpp::image::setImageLayout(cmdBuffer, img, vk::ImageLayout::eTransferSrcOptimal, vk::ImageLayout::eGeneral, subresourceRange); setImageLayout(cmdBuffer, vkIMG, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, subresourceRange, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); sc.flushCommandBuffer(cmdBuffer); } void VContext::DenoiseImage() { //AllocateBuffers(); //try //{ std::cout << "SIZE BEFORE: " << sizeof(storageImage.image) << "\n"; ConvertVulkan2Optix(storageImage.image, m_pixelBufferIn.bufVk.buffer); OptixPixelFormat pixelFormat = OPTIX_PIXEL_FORMAT_FLOAT3; auto sizeofPixel = static_cast<uint32_t>(sizeof(float3)); OptixImage2D inputLayer{ (CUdeviceptr)m_pixelBufferIn.cudaPtr, WIDTH, HEIGHT, 0, 0, pixelFormat }; OptixImage2D outputLayer = { (CUdeviceptr)m_pixelBufferOut.cudaPtr, WIDTH, HEIGHT, 0, 0, pixelFormat }; OPTIX_CHECK(optixDenoiserComputeIntensity(m_denoiser, cudaStream, &inputLayer, m_dIntensity, m_dScratch, m_dSizes.recommendedScratchSizeInBytes)); int nbChannels{ 3 }; OptixDenoiserParams params{}; params.denoiseAlpha = 1;// (nbChannels == 4 ? 1 : 0); params.hdrIntensity = m_dIntensity; params.blendFactor = 0; //params.hdrMinRGB = d_minRGB; OPTIX_CHECK(optixDenoiserInvoke(m_denoiser, cudaStream, &params, m_dState, m_dSizes.stateSizeInBytes, &inputLayer, 1, 0, 0, &outputLayer, m_dScratch, m_dSizes.recommendedScratchSizeInBytes)); //CUDA_CHECK(cudaDeviceSynchronize()); CUDA_CHECK(cudaStreamSynchronize(cudaStream)); // Making sure the denoiser is done ConvertOptix2Vulkan(storageImage.image, m_pixelBufferOut.bufVk.buffer); std::cout << "SIZE AFTER: " << sizeof(storageImage.image) << "\n\n\n"; //bufferToImage(m_pixelBufferOut.bufVk.buffer, imgOut); //} /*catch (const std::exception & e) { std::cout << e.what() << std::endl; }*/ } HANDLE VContext::getVulkanMemoryHandle(VkDevice device, VkDeviceMemory memory) { // Get handle to memory of the VkImage VkMemoryGetWin32HandleInfoKHR fdInfo = { }; fdInfo.sType = VK_STRUCTURE_TYPE_MEMORY_GET_WIN32_HANDLE_INFO_KHR; fdInfo.memory = memory; fdInfo.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT_KHR; auto func = (PFN_vkGetMemoryWin32HandleKHR)vkGetDeviceProcAddr(device, "vkGetMemoryWin32HandleKHR"); if (!func) { printf("Failed to locate function vkGetMemoryWin32HandleKHR\n"); return nullptr; } VkResult r = func(device, &fdInfo, &fd); if (r != VK_SUCCESS) { printf("Failed executing vkGetMemoryWin32HandleKHR [%d]\n", r); return nullptr; } HANDLE returnHandle = fd; return returnHandle; } void VContext::exportToCudaPointer(BufferCuda& buf) { buf.handle = getVulkanMemoryHandle( dev, buf.bufVk.allocation); auto req = dev.getBufferMemoryRequirements(buf.bufVk.buffer); cudaExternalMemoryHandleDesc cudaExtMemHandleDesc{}; cudaExtMemHandleDesc.type = cudaExternalMemoryHandleTypeOpaqueWin32; cudaExtMemHandleDesc.handle.win32.handle = buf.handle; cudaExtMemHandleDesc.size = req.size; cudaExternalMemory_t cudaExtMemVertexBuffer{}; CUDA_CHECK(cudaImportExternalMemory(&cudaExtMemVertexBuffer, &cudaExtMemHandleDesc)); cudaExternalMemoryBufferDesc cudaExtBufferDesc{}; cudaExtBufferDesc.offset = 0; cudaExtBufferDesc.size = req.size; cudaExtBufferDesc.flags = 0; CUDA_CHECK(cudaExternalMemoryGetMappedBuffer(&buf.cudaPtr, cudaExtMemVertexBuffer, &cudaExtBufferDesc)); } void VContext::CreateImageBuffer(vk::Buffer& buf, vk::MemoryAllocateInfo& bufAlloc, vk::MemoryRequirements& bufReqs, vk::DeviceMemory& bufMemory, vk::BufferUsageFlags usage) { // Copy the image to the buffer vk::BufferCreateInfo createInfo; createInfo.size = WIDTH * HEIGHT * sizeof(float); createInfo.usage = usage; buf = dev.createBuffer(createInfo); bufReqs = dev.getBufferMemoryRequirements(buf); bufAlloc.allocationSize = bufReqs.size; bufAlloc.memoryTypeIndex = getMemoryType(bufReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); VkExportMemoryAllocateInfoKHR exportInfo = {}; exportInfo.sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR; exportInfo.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT_KHR; bufAlloc.pNext = &exportInfo; bufMemory = dev.allocateMemory(bufAlloc); dev.bindBufferMemory(buf, bufMemory, 0); } #pragma endregion #pragma region Extensions std::vector<const char*> VContext::GetRequieredExtensions() { uint32_t extension_count = 0; const char** extensions_name = glfwGetRequiredInstanceExtensions(&extension_count); std::vector<const char*> extensions(extensions_name, extensions_name + extension_count); std::cout << "Extensions Loaded: \n"; for (const char* typo : extensions) std::cout << typo << "\n"; if (enableValidationLayers) { extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); } extensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME); extensions.push_back(VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME); extensions.push_back(VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME); return extensions; } #pragma endregion #pragma region Debug void VContext::populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo) { createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT; createInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; createInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; createInfo.pfnUserCallback = DebugCallback; } VKAPI_ATTR VkBool32 VKAPI_CALL VContext::DebugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT messageType, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData) { std::cerr << "validation layer: " << pCallbackData->pMessage << std::endl; return VK_FALSE; } std::vector<char> VContext::readFile(const std::string& filename) { std::ifstream file(filename, std::ios::ate | std::ios::binary); if (!file.is_open()) { throw std::runtime_error("failed to open file!"); } const size_t fileSize = static_cast<size_t>(file.tellg()); std::vector<char> buffer(fileSize); file.seekg(0); file.read(buffer.data(), fileSize); file.close(); return buffer; } void VContext::SetupDebugMessenger() { if constexpr (!enableValidationLayers) return; VkDebugUtilsMessengerCreateInfoEXT createInfo; populateDebugMessengerCreateInfo(createInfo); if (CreateDebugUtilsMessengerEXT(instance, &createInfo, nullptr, &debugMessenger) != VK_SUCCESS) { throw std::runtime_error("failed to set up debug messenger!"); } } void VContext::DestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT debugMessenger, const VkAllocationCallbacks* pAllocator) { const auto func = PFN_vkDestroyDebugUtilsMessengerEXT(vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT")); if (func != nullptr) { func(instance, debugMessenger, pAllocator); } } VkResult VContext::CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT* pDebugMessenger) { const auto func = PFN_vkCreateDebugUtilsMessengerEXT(vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT")); if (func != nullptr) { return func(instance, pCreateInfo, pAllocator, pDebugMessenger); } return VK_ERROR_EXTENSION_NOT_PRESENT; } #pragma endregion #pragma region RayTracing /** * Acquires the next image in the swap chain * * @param presentCompleteSemaphore (Optional) Semaphore that is signaled when the image is ready for use * @param imageIndex Pointer to the image index that will be increased if the next image could be acquired * * @note The function will always wait until the next image has been acquired by setting timeout to UINT64_MAX * * @return VkResult of the image acquisition */ VkResult VContext::acquireNextImage(VkSemaphore presentCompleteSemaphore, uint32_t* imageIndex) const { // By setting timeout to UINT64_MAX we will always wait until the next image has been acquired or an actual error is thrown // With that we don't have to handle VK_NOT_READY return vkAcquireNextImageKHR(device.logicalDevice, swapChain.swapChain, UINT64_MAX, presentCompleteSemaphore, static_cast<VkFence>(nullptr), imageIndex); } /** * Queue an image for presentation * * @param queue Presentation queue for presenting the image * @param imageIndex Index of the swapchain image to queue for presentation * @param waitSemaphore (Optional) Semaphore that is waited on before the image is presented (only used if != VK_NULL_HANDLE) * * @return VkResult of the queue presentation */ VkResult VContext::queuePresent(VkQueue queue, uint32_t imageIndex, VkSemaphore waitSemaphore = nullptr) const { VkPresentInfoKHR presentInfo = {}; presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; presentInfo.pNext = nullptr; presentInfo.swapchainCount = 1; presentInfo.pSwapchains = &swapChain.swapChain; presentInfo.pImageIndices = &imageIndex; // Check if a wait semaphore has been specified to wait for before presenting the image if (waitSemaphore != nullptr) { presentInfo.pWaitSemaphores = &waitSemaphore; presentInfo.waitSemaphoreCount = 1; } return vkQueuePresentKHR(queue, &presentInfo); } VkShaderModule VContext::createShaderModule(const std::vector<char>& code) const { //Set the shader VkShaderModuleCreateInfo createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; createInfo.codeSize = code.size(); createInfo.pCode = reinterpret_cast<const uint32_t*>(code.data()); //Create the shader VkShaderModule shaderModule; if (vkCreateShaderModule(device.logicalDevice, &createInfo, nullptr, &shaderModule) != VK_SUCCESS) { throw std::runtime_error("failed to create shader module!"); } return shaderModule; } void VContext::initSwapChain() { dev = device.logicalDevice; // Get available queue family properties uint32_t queueCount; vkGetPhysicalDeviceQueueFamilyProperties(device.physicalDevice, &queueCount, nullptr); assert(queueCount >= 1); std::vector<VkQueueFamilyProperties> queueProps(queueCount); vkGetPhysicalDeviceQueueFamilyProperties(device.physicalDevice, &queueCount, queueProps.data()); // Iterate over each queue to learn whether it supports presenting: // Find a queue with present support // Will be used to present the swap chain images to the windowing system std::vector<VkBool32> supportsPresent(queueCount); for (uint32_t i = 0; i < queueCount; i++) { vkGetPhysicalDeviceSurfaceSupportKHR(device.physicalDevice, i, device.surface, &supportsPresent[i]); } // Search for a graphics and a present queue in the array of queue // families, try to find one that supports both uint32_t graphicsQueueNodeIndex = UINT32_MAX; uint32_t presentQueueNodeIndex = UINT32_MAX; for (uint32_t i = 0; i < queueCount; i++) { if ((queueProps[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0) { if (graphicsQueueNodeIndex == UINT32_MAX) { graphicsQueueNodeIndex = i; } if (supportsPresent[i] == VK_TRUE) { graphicsQueueNodeIndex = i; presentQueueNodeIndex = i; break; } } } if (presentQueueNodeIndex == UINT32_MAX) { // If there's no queue that supports both present and graphics // try to find a separate present queue for (uint32_t i = 0; i < queueCount; ++i) { if (supportsPresent[i] == VK_TRUE) { presentQueueNodeIndex = i; break; } } } // Exit if either a graphics or a presenting queue hasn't been found if (graphicsQueueNodeIndex == UINT32_MAX || presentQueueNodeIndex == UINT32_MAX) { throw std::runtime_error("Could not find a graphics and/or presenting queue!"); } // todo : Add support for separate graphics and presenting queue if (graphicsQueueNodeIndex != presentQueueNodeIndex) { throw std::runtime_error("Separate graphics and presenting queues are not supported yet!"); } swapChain.queueNodeIndex = graphicsQueueNodeIndex; // Get list of supported surface formats uint32_t formatCount; vkGetPhysicalDeviceSurfaceFormatsKHR(device.physicalDevice, device.surface, &formatCount, nullptr); assert(formatCount > 0); std::vector<VkSurfaceFormatKHR> surfaceFormats(formatCount); vkGetPhysicalDeviceSurfaceFormatsKHR(device.physicalDevice, device.surface, &formatCount, surfaceFormats.data()); // If the surface format list only includes one entry with VK_FORMAT_UNDEFINED, // there is no preferered format, so we assume VK_FORMAT_B8G8R8A8_UNORM if ((formatCount == 1) && (surfaceFormats[0].format == VK_FORMAT_UNDEFINED)) { swapChain.colorFormat = VK_FORMAT_B8G8R8A8_UNORM; swapChain.colorSpace = surfaceFormats[0].colorSpace; } else { // iterate over the list of available surface format and // check for the presence of VK_FORMAT_B8G8R8A8_UNORM bool found_B8G8R8A8_UNORM = false; for (auto&& surfaceFormat : surfaceFormats) { if (surfaceFormat.format == VK_FORMAT_B8G8R8A8_UNORM) { swapChain.colorFormat = surfaceFormat.format; swapChain.colorSpace = surfaceFormat.colorSpace; found_B8G8R8A8_UNORM = true; break; } } // in case VK_FORMAT_B8G8R8A8_UNORM is not available // select the first available color format if (!found_B8G8R8A8_UNORM) { swapChain.colorFormat = surfaceFormats[0].format; swapChain.colorSpace = surfaceFormats[0].colorSpace; } } } void VContext::CreateCommandPool() { VkCommandPoolCreateInfo cmdPoolInfo = {}; cmdPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; cmdPoolInfo.queueFamilyIndex = swapChain.queueNodeIndex; cmdPoolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; CHECK_ERROR(vkCreateCommandPool(device.logicalDevice, &cmdPoolInfo, nullptr, &commandPool)); } void VContext::CreateCommandBuffers() { // Create one command buffer for each swap chain image and reuse for rendering commandBuffers.resize(swapChain.imageCount); VkCommandBufferAllocateInfo cmdBufAllocateInfo = Initializers::commandBufferAllocateInfo( commandPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, static_cast<uint32_t>(commandBuffers.size())); CHECK_ERROR(vkAllocateCommandBuffers(device.logicalDevice, &cmdBufAllocateInfo, commandBuffers.data())); } void VContext::CreateBottomLevelAccelerationStructure(const VkGeometryNV* geometries) { AccelerationStructure newBottomAS; VkAccelerationStructureInfoNV accelerationStructureInfo{}; accelerationStructureInfo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_INFO_NV; accelerationStructureInfo.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_NV; accelerationStructureInfo.instanceCount = 0; accelerationStructureInfo.geometryCount = 1; accelerationStructureInfo.pGeometries = geometries; VkAccelerationStructureCreateInfoNV accelerationStructureCI{}; accelerationStructureCI.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_NV; accelerationStructureCI.info = accelerationStructureInfo; vkCreateAccelerationStructureNV(device.logicalDevice, &accelerationStructureCI, nullptr, &newBottomAS.accelerationStructure); VkAccelerationStructureMemoryRequirementsInfoNV memoryRequirementsInfo{}; memoryRequirementsInfo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_MEMORY_REQUIREMENTS_INFO_NV; memoryRequirementsInfo.type = VK_ACCELERATION_STRUCTURE_MEMORY_REQUIREMENTS_TYPE_OBJECT_NV; memoryRequirementsInfo.accelerationStructure = newBottomAS.accelerationStructure; VkMemoryRequirements2 memoryRequirements2{}; vkGetAccelerationStructureMemoryRequirementsNV(device.logicalDevice, &memoryRequirementsInfo, &memoryRequirements2); VkMemoryAllocateInfo memoryAllocateInfo = Initializers::memoryAllocateInfo(); memoryAllocateInfo.allocationSize = memoryRequirements2.memoryRequirements.size; memoryAllocateInfo.memoryTypeIndex = getMemoryType(memoryRequirements2.memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); vkAllocateMemory(device.logicalDevice, &memoryAllocateInfo, nullptr, &newBottomAS.memory); VkBindAccelerationStructureMemoryInfoNV accelerationStructureMemoryInfo{}; accelerationStructureMemoryInfo.sType = VK_STRUCTURE_TYPE_BIND_ACCELERATION_STRUCTURE_MEMORY_INFO_NV; accelerationStructureMemoryInfo.accelerationStructure = newBottomAS.accelerationStructure; accelerationStructureMemoryInfo.memory = newBottomAS.memory; vkBindAccelerationStructureMemoryNV(device.logicalDevice, 1, &accelerationStructureMemoryInfo); vkGetAccelerationStructureHandleNV(device.logicalDevice, newBottomAS.accelerationStructure, sizeof(uint64_t), &newBottomAS.handle); bottomLevelAS.push_back(newBottomAS); } //VALID void VContext::CreateTopLevelAccelerationStructure(AccelerationStructure& accelerationStruct, int instanceCount) const { VkAccelerationStructureInfoNV accelerationStructureInfo{}; accelerationStructureInfo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_INFO_NV; accelerationStructureInfo.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_NV; accelerationStructureInfo.flags = /*VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_BUILD_BIT_NV | */VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_COMPACTION_BIT_NV; accelerationStructureInfo.instanceCount = instanceCount; accelerationStructureInfo.geometryCount = 0; VkAccelerationStructureCreateInfoNV accelerationStructureCI{}; accelerationStructureCI.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_NV; accelerationStructureCI.info = accelerationStructureInfo; vkCreateAccelerationStructureNV(device.logicalDevice, &accelerationStructureCI, nullptr, &accelerationStruct.accelerationStructure); VkAccelerationStructureMemoryRequirementsInfoNV memoryRequirementsInfo{}; memoryRequirementsInfo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_MEMORY_REQUIREMENTS_INFO_NV; memoryRequirementsInfo.type = VK_ACCELERATION_STRUCTURE_MEMORY_REQUIREMENTS_TYPE_OBJECT_NV; memoryRequirementsInfo.accelerationStructure = accelerationStruct.accelerationStructure; VkMemoryRequirements2 memoryRequirements2{}; vkGetAccelerationStructureMemoryRequirementsNV(device.logicalDevice, &memoryRequirementsInfo, &memoryRequirements2); VkMemoryAllocateInfo memoryAllocateInfo = Initializers::memoryAllocateInfo(); memoryAllocateInfo.allocationSize = memoryRequirements2.memoryRequirements.size; memoryAllocateInfo.memoryTypeIndex = getMemoryType(memoryRequirements2.memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); vkAllocateMemory(device.logicalDevice, &memoryAllocateInfo, nullptr, &accelerationStruct.memory); VkBindAccelerationStructureMemoryInfoNV accelerationStructureMemoryInfo{}; accelerationStructureMemoryInfo.sType = VK_STRUCTURE_TYPE_BIND_ACCELERATION_STRUCTURE_MEMORY_INFO_NV; accelerationStructureMemoryInfo.accelerationStructure = accelerationStruct.accelerationStructure; accelerationStructureMemoryInfo.memory = accelerationStruct.memory; vkBindAccelerationStructureMemoryNV(device.logicalDevice, 1, &accelerationStructureMemoryInfo); vkGetAccelerationStructureHandleNV(device.logicalDevice, accelerationStruct.accelerationStructure, sizeof(uint64_t), &accelerationStruct.handle); } //VALID void VContext::CreateStorageImage() { VkImageCreateInfo accImageInfo = Initializers::imageCreateInfo(); accImageInfo.imageType = VK_IMAGE_TYPE_2D; accImageInfo.format = VK_FORMAT_R32G32B32A32_SFLOAT; accImageInfo.extent.width = WIDTH; accImageInfo.extent.height = HEIGHT; accImageInfo.extent.depth = 1; accImageInfo.mipLevels = 1; accImageInfo.arrayLayers = 1; accImageInfo.samples = VK_SAMPLE_COUNT_1_BIT; accImageInfo.tiling = VK_IMAGE_TILING_OPTIMAL; accImageInfo.usage = VK_IMAGE_USAGE_STORAGE_BIT; accImageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; vkCreateImage(device.logicalDevice, &accImageInfo, nullptr, &accImage.image); VkImageCreateInfo image = Initializers::imageCreateInfo(); image.imageType = VK_IMAGE_TYPE_2D; image.format = swapChain.colorFormat; image.extent.width = WIDTH; image.extent.height = HEIGHT; image.extent.depth = 1; image.mipLevels = 1; image.arrayLayers = 1; image.samples = VK_SAMPLE_COUNT_1_BIT; image.tiling = VK_IMAGE_TILING_OPTIMAL; image.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_STORAGE_BIT; image.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; vkCreateImage(device.logicalDevice, &image, nullptr, &storageImage.image); //STORAGE IMAGE VkMemoryRequirements memory_requierements; vkGetImageMemoryRequirements(device.logicalDevice, storageImage.image, &memory_requierements); VkMemoryAllocateInfo memoryAllocateInfo = Initializers::memoryAllocateInfo(); memoryAllocateInfo.allocationSize = memory_requierements.size; memoryAllocateInfo.memoryTypeIndex = getMemoryType(memory_requierements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); vkAllocateMemory(device.logicalDevice, &memoryAllocateInfo, nullptr, &storageImage.memory); vkBindImageMemory(device.logicalDevice, storageImage.image, storageImage.memory, 0); VkImageViewCreateInfo colorImageView = Initializers::imageViewCreateInfo(); colorImageView.viewType = VK_IMAGE_VIEW_TYPE_2D; colorImageView.format = swapChain.colorFormat; colorImageView.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; colorImageView.subresourceRange.baseMipLevel = 0; colorImageView.subresourceRange.levelCount = 1; colorImageView.subresourceRange.baseArrayLayer = 0; colorImageView.subresourceRange.layerCount = 1; colorImageView.image = storageImage.image; vkCreateImageView(device.logicalDevice, &colorImageView, nullptr, &storageImage.view); //ACCUMULATION IMAGE VkMemoryRequirements memory_requierementsAcc; vkGetImageMemoryRequirements(device.logicalDevice, accImage.image, &memory_requierementsAcc); VkMemoryAllocateInfo memoryAllocateInfoAcc = Initializers::memoryAllocateInfo(); memoryAllocateInfoAcc.allocationSize = memory_requierementsAcc.size; memoryAllocateInfoAcc.memoryTypeIndex = getMemoryType(memory_requierementsAcc.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); vkAllocateMemory(device.logicalDevice, &memoryAllocateInfoAcc, nullptr, &accImage.memory); vkBindImageMemory(device.logicalDevice, accImage.image, accImage.memory, 0); VkImageViewCreateInfo colorImageViewAcc = Initializers::imageViewCreateInfo(); colorImageViewAcc.viewType = VK_IMAGE_VIEW_TYPE_2D; colorImageViewAcc.format = swapChain.colorFormat; colorImageViewAcc.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; colorImageViewAcc.subresourceRange.baseMipLevel = 0; colorImageViewAcc.subresourceRange.levelCount = 1; colorImageViewAcc.subresourceRange.baseArrayLayer = 0; colorImageViewAcc.subresourceRange.layerCount = 1; colorImageViewAcc.image = accImage.image; vkCreateImageView(device.logicalDevice, &colorImageView, nullptr, &accImage.view); const VkCommandBuffer cmd_buffer = createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); setImageLayout(cmd_buffer, storageImage.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); //setImageLayout(cmd_buffer, accImage.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); flushCommandBuffer(cmd_buffer, graphicsQueue); } //VALID VkResult VContext::createBuffer(VkBufferUsageFlags usageFlags, VkMemoryPropertyFlags memoryPropertyFlags, VkDeviceSize size, VkBuffer* buffer, VkDeviceMemory* memory, void* data) const { // Create the buffer handle VkBufferCreateInfo bufferCreateInfo = Initializers::bufferCreateInfo(usageFlags, size); bufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; vkCreateBuffer(device.logicalDevice, &bufferCreateInfo, nullptr, buffer); // Create the memory backing up the buffer handle VkMemoryRequirements memory_requirements; VkMemoryAllocateInfo memAlloc = Initializers::memoryAllocateInfo(); vkGetBufferMemoryRequirements(device.logicalDevice, *buffer, &memory_requirements); memAlloc.allocationSize = memory_requirements.size; // Find a memory type index that fits the properties of the buffer memAlloc.memoryTypeIndex = getMemoryType(memory_requirements.memoryTypeBits, memoryPropertyFlags); vkAllocateMemory(device.logicalDevice, &memAlloc, nullptr, memory); // If a pointer to the buffer data has been passed, map the buffer and copy over the data if (data != nullptr) { void* mapped; vkMapMemory(device.logicalDevice, *memory, 0, size, 0, &mapped); memcpy(mapped, data, size); // If host coherency hasn't been requested, do a manual flush to make writes visible if ((memoryPropertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == 0) { VkMappedMemoryRange mappedRange = Initializers::mappedMemoryRange(); mappedRange.memory = *memory; mappedRange.offset = 0; mappedRange.size = size; vkFlushMappedMemoryRanges(device.logicalDevice, 1, &mappedRange); } vkUnmapMemory(device.logicalDevice, *memory); } // Attach the memory to the buffer object vkBindBufferMemory(device.logicalDevice, *buffer, *memory, 0); return VK_SUCCESS; } VkBool32 VContext::getSupportedDepthFormat(VkPhysicalDevice physicalDevice, VkFormat* depthFormat) { // Since all depth formats may be optional, we need to find a suitable depth format to use // Start with the highest precision packed format std::vector<VkFormat> depthFormats = { VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D32_SFLOAT, VK_FORMAT_D24_UNORM_S8_UINT, VK_FORMAT_D16_UNORM_S8_UINT, VK_FORMAT_D16_UNORM }; for (auto& format : depthFormats) { VkFormatProperties formatProps; vkGetPhysicalDeviceFormatProperties(physicalDevice, format, &formatProps); // Format must support depth stencil attachment for optimal tiling if (formatProps.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { *depthFormat = format; return true; } } return false; } void VContext::createScene(std::vector<VObject>& objects) { int j = 0; VkCommandBuffer cmdBuffer = createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); for(auto obj : objects) { std::vector<Vertex> vertices; std::vector<uint32_t> indices; for(auto vertex : obj.m_mesh.GetVertices()) { vertices.push_back(vertex); } for(auto index : obj.m_mesh.GetIndices()) { indices.push_back(index); sceneIndices.push_back(index); } indexCount = static_cast<uint32_t>(indices.size()); //Vertex buffer createBuffer( VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &vertexBuffer, vertices.size() * sizeof(Vertex), vertices.data()); // Index buffer createBuffer( VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &indexBuffer, indices.size() * sizeof(uint32_t), indices.data()); //Generate Geometry data VkGeometryNV geometry{}; geometry.sType = VK_STRUCTURE_TYPE_GEOMETRY_NV; geometry.geometryType = VK_GEOMETRY_TYPE_TRIANGLES_NV; geometry.geometry.triangles.sType = VK_STRUCTURE_TYPE_GEOMETRY_TRIANGLES_NV; geometry.geometry.triangles.vertexData = vertexBuffer.buffer; geometry.geometry.triangles.vertexOffset = 0; geometry.geometry.triangles.vertexCount = static_cast<uint32_t>(vertices.size()); geometry.geometry.triangles.vertexStride = sizeof(Vertex); geometry.geometry.triangles.vertexFormat = VK_FORMAT_R32G32B32_SFLOAT; geometry.geometry.triangles.indexData = indexBuffer.buffer; geometry.geometry.triangles.indexOffset = 0; geometry.geometry.triangles.indexCount = indexCount; geometry.geometry.triangles.indexType = VK_INDEX_TYPE_UINT32; geometry.geometry.triangles.transformData = nullptr; geometry.geometry.triangles.transformOffset = 0; geometry.geometry.aabbs = {}; geometry.geometry.aabbs.sType = { VK_STRUCTURE_TYPE_GEOMETRY_AABB_NV }; geometry.flags = VK_GEOMETRY_OPAQUE_BIT_NV; //Create Bottom Level AS for specific geometry CreateBottomLevelAccelerationStructure(&geometry); //Get memory requirements for BLAS VkAccelerationStructureMemoryRequirementsInfoNV memoryRequirementsInfo{}; memoryRequirementsInfo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_MEMORY_REQUIREMENTS_INFO_NV; memoryRequirementsInfo.type = VK_ACCELERATION_STRUCTURE_MEMORY_REQUIREMENTS_TYPE_BUILD_SCRATCH_NV; memoryRequirementsInfo.accelerationStructure = bottomLevelAS[j].accelerationStructure; vkGetAccelerationStructureMemoryRequirementsNV(device.logicalDevice, &memoryRequirementsInfo, &memReqBottomLevelAS); const VkDeviceSize scratchBufferSize = memReqBottomLevelAS.memoryRequirements.size; //Create scratch buffer, because BLAS needs temp memory to be built VBuffer::Buffer scratchBuffer; createBuffer( VK_BUFFER_USAGE_RAY_TRACING_BIT_NV, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &scratchBuffer, scratchBufferSize); //Set build info VkAccelerationStructureInfoNV buildInfo{}; buildInfo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_INFO_NV; buildInfo.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_NV; buildInfo.geometryCount = 1; buildInfo.pGeometries = &geometry; //Build BLAS for specific object vkCmdBuildAccelerationStructureNV( cmdBuffer, &buildInfo, nullptr, 0, VK_FALSE, bottomLevelAS[j].accelerationStructure, nullptr, scratchBuffer.buffer, 0); //Create memory barrier to prevent issues (it creates a command dependency) VkMemoryBarrier memoryBarrier = Initializers::memoryBarrier(); memoryBarrier.srcAccessMask = VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_NV | VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_NV; memoryBarrier.dstAccessMask = VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_NV | VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_NV; vkCmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_NV, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_NV, 0, 1, &memoryBarrier, 0, nullptr, 0, nullptr); //set correct object acceleration structure to the one we just built objects[j].m_mesh.meshGeometry.accelerationStructureHandle = bottomLevelAS[j].handle; objects[j].m_mesh.meshGeometry.instanceId = j; j++; } j = 0; //Generate TLAS std::vector<GeometryInstance> instances; for(auto& obj: objects) instances.push_back(obj.m_mesh.meshGeometry); //Get all instances and create a buffer with all of them VBuffer::Buffer instanceBuffer; createBuffer(VK_BUFFER_USAGE_RAY_TRACING_BIT_NV, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &instanceBuffer, sizeof(GeometryInstance) * instances.size(), instances.data()); //Generate TLAS CreateTopLevelAccelerationStructure(topLevelAS, instances.size()); //Get memory requirements VkMemoryRequirements2 memReqTopLevelAS; VkAccelerationStructureMemoryRequirementsInfoNV memoryRequirementsInfo2{}; memoryRequirementsInfo2.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_MEMORY_REQUIREMENTS_INFO_NV; memoryRequirementsInfo2.type = VK_ACCELERATION_STRUCTURE_MEMORY_REQUIREMENTS_TYPE_BUILD_SCRATCH_NV; memoryRequirementsInfo2.accelerationStructure = topLevelAS.accelerationStructure; vkGetAccelerationStructureMemoryRequirementsNV(device.logicalDevice, &memoryRequirementsInfo2, &memReqTopLevelAS); const VkDeviceSize scratchBufferSize = memReqTopLevelAS.memoryRequirements.size; //Generate Scratch buffer VBuffer::Buffer scratchBuffer; createBuffer( VK_BUFFER_USAGE_RAY_TRACING_BIT_NV, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &scratchBuffer, scratchBufferSize); //Generate build info for TLAS VkAccelerationStructureInfoNV buildInfo{}; buildInfo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_INFO_NV; buildInfo.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_NV; buildInfo.flags = /*VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_BUILD_BIT_NV | */VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_COMPACTION_BIT_NV; buildInfo.pGeometries = nullptr; buildInfo.geometryCount = 0; buildInfo.instanceCount = instances.size(); //Build Actual TLAS vkCmdBuildAccelerationStructureNV( cmdBuffer, &buildInfo, instanceBuffer.buffer, 0, VK_FALSE, topLevelAS.accelerationStructure, nullptr, scratchBuffer.buffer, 0); VkMemoryBarrier memoryBarrier = Initializers::memoryBarrier(); memoryBarrier.srcAccessMask = VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_NV | VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_NV; memoryBarrier.dstAccessMask = VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_NV | VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_NV; vkCmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_NV, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_NV, 0, 1, &memoryBarrier, 0, nullptr, 0, nullptr); flushCommandBuffer(cmdBuffer, graphicsQueue); scratchBuffer.destroy(); instanceBuffer.destroy(); } //VALID void VContext::createRayTracingPipeline() { //Binding Uniforms to specific shader, //here we set the bindings for the RAYGEN shader (VK_SHADER_STAGE_RAYGEN_BIT_NV) VkDescriptorSetLayoutBinding accelerationStructureLayoutBinding{}; accelerationStructureLayoutBinding.binding = 0; accelerationStructureLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV; accelerationStructureLayoutBinding.descriptorCount = 1; accelerationStructureLayoutBinding.stageFlags = VK_SHADER_STAGE_RAYGEN_BIT_NV | VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV; VkDescriptorSetLayoutBinding resultImageLayoutBinding{}; resultImageLayoutBinding.binding = 1; resultImageLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; resultImageLayoutBinding.descriptorCount = 1; resultImageLayoutBinding.stageFlags = VK_SHADER_STAGE_RAYGEN_BIT_NV; VkDescriptorSetLayoutBinding uniformBufferBinding{}; uniformBufferBinding.binding = 2; uniformBufferBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; uniformBufferBinding.descriptorCount = 1; uniformBufferBinding.stageFlags = VK_SHADER_STAGE_RAYGEN_BIT_NV | VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV; VkDescriptorSetLayoutBinding matBufferBinding{}; matBufferBinding.binding = 3; matBufferBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; matBufferBinding.descriptorCount = 1; matBufferBinding.stageFlags = VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV; VkDescriptorSetLayoutBinding vertexBufferBinding{}; vertexBufferBinding.binding = 4; vertexBufferBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; vertexBufferBinding.descriptorCount = 1; vertexBufferBinding.stageFlags = VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV; VkDescriptorSetLayoutBinding timeBufferBinding{}; timeBufferBinding.binding = 5; timeBufferBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; timeBufferBinding.descriptorCount = 1; timeBufferBinding.stageFlags = VK_SHADER_STAGE_RAYGEN_BIT_NV; VkDescriptorSetLayoutBinding TriNumberBinding{}; TriNumberBinding.binding = 6; TriNumberBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; TriNumberBinding.descriptorCount = 1; TriNumberBinding.stageFlags = VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV; VkDescriptorSetLayoutBinding AccImageLayoutBinding{}; AccImageLayoutBinding.binding = 7; AccImageLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; AccImageLayoutBinding.descriptorCount = 1; AccImageLayoutBinding.stageFlags = VK_SHADER_STAGE_RAYGEN_BIT_NV; //create a Binding vector for Uniform bindings std::vector<VkDescriptorSetLayoutBinding> bindings({ accelerationStructureLayoutBinding, resultImageLayoutBinding, uniformBufferBinding, matBufferBinding, vertexBufferBinding, timeBufferBinding, TriNumberBinding, AccImageLayoutBinding }); //Create the buffer that will map the shader uniforms to the actual shader VkDescriptorSetLayoutCreateInfo layoutInfo{}; layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size()); layoutInfo.pBindings = bindings.data(); vkCreateDescriptorSetLayout(device.logicalDevice, &layoutInfo, nullptr, &RdescriptorSetLayout); VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo{}; pipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipelineLayoutCreateInfo.setLayoutCount = 1; pipelineLayoutCreateInfo.pSetLayouts = &RdescriptorSetLayout; vkCreatePipelineLayout(device.logicalDevice, &pipelineLayoutCreateInfo, nullptr, &RpipelineLayout); const uint32_t shader_index_ray = 0; const uint32_t shaderIndexMiss = 1; const uint32_t shaderIndexShadowMiss = 2; const uint32_t shaderIndexClosestHit = 3; std::array<VkPipelineShaderStageCreateInfo, 4> shaderStages{}; shaderStages[shader_index_ray] = loadShader("shaders/bin/ray_gen.spv", VK_SHADER_STAGE_RAYGEN_BIT_NV); shaderStages[shaderIndexMiss] = loadShader("shaders/bin/ray_miss.spv", VK_SHADER_STAGE_MISS_BIT_NV); shaderStages[shaderIndexShadowMiss] = loadShader("shaders/bin/ray_smiss.spv", VK_SHADER_STAGE_MISS_BIT_NV); shaderStages[shaderIndexClosestHit] = loadShader("shaders/bin/ray_chit.spv", VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV); /* Setup ray tracing shader groups */ std::array<VkRayTracingShaderGroupCreateInfoNV, NUM_SHADER_GROUPS> groups{}; for (auto& group : groups) { // Init all groups with some default values group.sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_NV; group.generalShader = VK_SHADER_UNUSED_NV; group.closestHitShader = VK_SHADER_UNUSED_NV; group.anyHitShader = VK_SHADER_UNUSED_NV; group.intersectionShader = VK_SHADER_UNUSED_NV; } // Links shaders and types to ray tracing shader groups groups[INDEX_RAYGEN].type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_NV; groups[INDEX_RAYGEN].generalShader = shader_index_ray; groups[INDEX_MISS].type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_NV; groups[INDEX_MISS].generalShader = shaderIndexMiss; groups[INDEX_SHADOWMISS].type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_NV; groups[INDEX_SHADOWMISS].generalShader = shaderIndexShadowMiss; groups[INDEX_CLOSEST_HIT].type = VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV; groups[INDEX_CLOSEST_HIT].generalShader = VK_SHADER_UNUSED_NV; groups[INDEX_CLOSEST_HIT].closestHitShader = shaderIndexClosestHit; groups[INDEX_SHADOWHIT].type = VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV; groups[INDEX_SHADOWHIT].generalShader = VK_SHADER_UNUSED_NV; // Reuse shadow miss shader groups[INDEX_SHADOWHIT].closestHitShader = shaderIndexShadowMiss; VkRayTracingPipelineCreateInfoNV rayPipelineInfo{}; rayPipelineInfo.sType = VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_NV; rayPipelineInfo.stageCount = static_cast<uint32_t>(shaderStages.size()); rayPipelineInfo.pStages = shaderStages.data(); rayPipelineInfo.groupCount = static_cast<uint32_t>(groups.size()); rayPipelineInfo.pGroups = groups.data(); rayPipelineInfo.maxRecursionDepth = 1; rayPipelineInfo.layout = RpipelineLayout; vkCreateRayTracingPipelinesNV(device.logicalDevice, nullptr, 1, &rayPipelineInfo, nullptr, &Rpipeline); } VkPipelineShaderStageCreateInfo VContext::loadShader(const std::string file_name, VkShaderStageFlagBits stage) { VkPipelineShaderStageCreateInfo shaderStage = {}; shaderStage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; shaderStage.stage = stage; #if defined(VK_USE_PLATFORM_ANDROID_KHR) shaderStage.module = vks::tools::loadShader(androidApp->activity->assetManager, fileName.c_str(), device); #else shaderStage.module = Tools::loadShader(file_name.c_str(), device.logicalDevice); #endif shaderStage.pName = "main"; // todo : make param assert(shaderStage.module != VK_NULL_HANDLE); shaderModules.push_back(shaderStage.module); return shaderStage; } void VContext::createSynchronizationPrimitives() { // Wait fences to sync command buffer access VkFenceCreateInfo fenceCreateInfo = Initializers::fenceCreateInfo(VK_FENCE_CREATE_SIGNALED_BIT); waitFences.resize(commandBuffers.size()); for (auto& fence : waitFences) { vkCreateFence(device.logicalDevice, &fenceCreateInfo, nullptr, &fence); } } void VContext::createPipelineCache() { VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {}; pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; vkCreatePipelineCache(device.logicalDevice, &pipelineCacheCreateInfo, nullptr, &pipelineCache); } void VContext::setupFrameBuffer() { VkImageView attachments[2]; // Depth/Stencil attachment is the same for all frame buffers attachments[1] = depthStencil.view; VkFramebufferCreateInfo frameBufferCreateInfo = {}; frameBufferCreateInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; frameBufferCreateInfo.pNext = nullptr; frameBufferCreateInfo.renderPass = renderPass; frameBufferCreateInfo.attachmentCount = 2; frameBufferCreateInfo.pAttachments = attachments; frameBufferCreateInfo.width = WIDTH; frameBufferCreateInfo.height = HEIGHT; frameBufferCreateInfo.layers = 1; // Create frame buffers for every swap chain image swapChainFramebuffers.resize(swapChain.imageCount); for (uint32_t i = 0; i < swapChainFramebuffers.size(); i++) { attachments[0] = swapChain.buffers[i].view; CHECK_ERROR(vkCreateFramebuffer(device.logicalDevice, &frameBufferCreateInfo, nullptr, &swapChainFramebuffers[i])); } } void VContext::setupDepthstencil() { VkImageCreateInfo imageCI{}; imageCI.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; imageCI.imageType = VK_IMAGE_TYPE_2D; imageCI.format = depthFormat; imageCI.extent = { WIDTH, HEIGHT, 1 }; imageCI.mipLevels = 1; imageCI.arrayLayers = 1; imageCI.samples = VK_SAMPLE_COUNT_1_BIT; imageCI.tiling = VK_IMAGE_TILING_OPTIMAL; imageCI.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; CHECK_ERROR(vkCreateImage(device.logicalDevice, &imageCI, nullptr, &depthStencil.image)); VkMemoryRequirements memory_requierements{}; vkGetImageMemoryRequirements(device.logicalDevice, depthStencil.image, &memory_requierements); VkMemoryAllocateInfo memory_alloc{}; memory_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; memory_alloc.allocationSize = memory_requierements.size; memory_alloc.memoryTypeIndex = getMemoryType(memory_requierements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); CHECK_ERROR(vkAllocateMemory(device.logicalDevice, &memory_alloc, nullptr, &depthStencil.mem)); CHECK_ERROR(vkBindImageMemory(device.logicalDevice, depthStencil.image, depthStencil.mem, 0)); VkImageViewCreateInfo imageViewCI{}; imageViewCI.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; imageViewCI.viewType = VK_IMAGE_VIEW_TYPE_2D; imageViewCI.image = depthStencil.image; imageViewCI.format = depthFormat; imageViewCI.subresourceRange.baseMipLevel = 0; imageViewCI.subresourceRange.levelCount = 1; imageViewCI.subresourceRange.baseArrayLayer = 0; imageViewCI.subresourceRange.layerCount = 1; imageViewCI.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; // Stencil aspect should only be set on depth + stencil formats (VK_FORMAT_D16_UNORM_S8_UINT..VK_FORMAT_D32_SFLOAT_S8_UINT if (depthFormat >= VK_FORMAT_D16_UNORM_S8_UINT) { imageViewCI.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT; } CHECK_ERROR(vkCreateImageView(device.logicalDevice, &imageViewCI, nullptr, &depthStencil.view)); } void VContext::setupRenderPass() { std::array<VkAttachmentDescription, 2> attachments = {}; // Color attachment attachments[0].format = swapChain.colorFormat; attachments[0].samples = VK_SAMPLE_COUNT_1_BIT; attachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; attachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE; attachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; attachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; attachments[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; attachments[0].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; // Depth attachment attachments[1].format = depthFormat; attachments[1].samples = VK_SAMPLE_COUNT_1_BIT; attachments[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; attachments[1].storeOp = VK_ATTACHMENT_STORE_OP_STORE; attachments[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; attachments[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; attachments[1].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; attachments[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; VkAttachmentReference colorReference; colorReference.attachment = 0; colorReference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkAttachmentReference depthReference; depthReference.attachment = 1; depthReference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; VkSubpassDescription subpass_description = {}; subpass_description.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass_description.colorAttachmentCount = 1; subpass_description.pColorAttachments = &colorReference; subpass_description.pDepthStencilAttachment = &depthReference; subpass_description.inputAttachmentCount = 0; subpass_description.pInputAttachments = nullptr; subpass_description.preserveAttachmentCount = 0; subpass_description.pPreserveAttachments = nullptr; subpass_description.pResolveAttachments = nullptr; // Subpass dependencies for layout transitions std::array<VkSubpassDependency, 2> dependencies{}; dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; dependencies[0].dstSubpass = 0; dependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependencies[0].srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; dependencies[1].srcSubpass = 0; dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; dependencies[1].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; VkRenderPassCreateInfo renderPassInfo = {}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size()); renderPassInfo.pAttachments = attachments.data(); renderPassInfo.subpassCount = 1; renderPassInfo.pSubpasses = &subpass_description; renderPassInfo.dependencyCount = static_cast<uint32_t>(dependencies.size()); renderPassInfo.pDependencies = dependencies.data(); CHECK_ERROR(vkCreateRenderPass(device.logicalDevice, &renderPassInfo, nullptr, &renderPass)); } /** * Create a buffer on the device * * @param usageFlags Usage flag bitmask for the buffer (i.e. index, vertex, uniform buffer) * @param memoryPropertyFlags Memory properties for this buffer (i.e. device local, host visible, coherent) * @param buffer Pointer to a vk::Vulkan buffer object * @param size Size of the buffer in byes * @param data Pointer to the data that should be copied to the buffer after creation (optional, if not set, no data is copied over) * * @return VK_SUCCESS if buffer handle and memory have been created and (optionally passed) data has been copied */ VkResult VContext::createBuffer(VkBufferUsageFlags usageFlags, VkMemoryPropertyFlags memoryPropertyFlags, VBuffer::Buffer* buffer, VkDeviceSize size, void* data) const { buffer->device = device.logicalDevice; // Create the buffer handle VkBufferCreateInfo bufferCreateInfo = Initializers::bufferCreateInfo(usageFlags, size); vkCreateBuffer(device.logicalDevice, &bufferCreateInfo, nullptr, &buffer->buffer); // Create the memory backing up the buffer handle VkMemoryRequirements memory_requierements; VkMemoryAllocateInfo memAlloc = Initializers::memoryAllocateInfo(); vkGetBufferMemoryRequirements(device.logicalDevice, buffer->buffer, &memory_requierements); memAlloc.allocationSize = memory_requierements.size; // Find a memory type index that fits the properties of the buffer memAlloc.memoryTypeIndex = getMemoryType(memory_requierements.memoryTypeBits, memoryPropertyFlags); vkAllocateMemory(device.logicalDevice, &memAlloc, nullptr, &buffer->memory); buffer->alignment = memory_requierements.alignment; buffer->size = memAlloc.allocationSize; buffer->usageFlags = usageFlags; buffer->memoryPropertyFlags = memoryPropertyFlags; // If a pointer to the buffer data has been passed, map the buffer and copy over the data if (data != nullptr) { buffer->map(); memcpy(buffer->mapped, data, size); if ((memoryPropertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == 0) CHECK_ERROR(buffer->flush()); buffer->unmap(); } // Initialize a default descriptor that covers the whole buffer size buffer->setupDescriptor(); // Attach the memory to the buffer object return buffer->bind(); } void VContext::setImageLayout(const VkCommandBuffer cmd_buffer, VkImage image, VkImageLayout oldImageLayout, VkImageLayout newImageLayout, const VkImageSubresourceRange subresourceRange, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask) { // Create an image barrier object VkImageMemoryBarrier imageMemoryBarrier = Initializers::imageMemoryBarrier(); imageMemoryBarrier.oldLayout = oldImageLayout; imageMemoryBarrier.newLayout = newImageLayout; imageMemoryBarrier.image = image; imageMemoryBarrier.subresourceRange = subresourceRange; // Source layouts (old) // Source access mask controls actions that have to be finished on the old layout // before it will be transitioned to the new layout switch (oldImageLayout) { case VK_IMAGE_LAYOUT_UNDEFINED: // Image layout is undefined (or does not matter) // Only valid as initial layout // No flags required, listed only for completeness imageMemoryBarrier.srcAccessMask = 0; break; case VK_IMAGE_LAYOUT_PREINITIALIZED: // Image is preinitialized // Only valid as initial layout for linear images, preserves memory contents // Make sure host writes have been finished imageMemoryBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; break; case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL: // Image is a color attachment // Make sure any writes to the color buffer have been finished imageMemoryBarrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; break; case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL: // Image is a depth/stencil attachment // Make sure any writes to the depth/stencil buffer have been finished imageMemoryBarrier.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; break; case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL: // Image is a transfer source // Make sure any reads from the image have been finished imageMemoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT; break; case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL: // Image is a transfer destination // Make sure any writes to the image have been finished imageMemoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; break; case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL: // Image is read by a shader // Make sure any shader reads from the image have been finished imageMemoryBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT; break; default: // Other source layouts aren't handled (yet) break; } // Target layouts (new) // Destination access mask controls the dependency for the new image layout switch (newImageLayout) { case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL: // Image will be used as a transfer destination // Make sure any writes to the image have been finished imageMemoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; break; case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL: // Image will be used as a transfer source // Make sure any reads from the image have been finished imageMemoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; break; case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL: // Image will be used as a color attachment // Make sure any writes to the color buffer have been finished imageMemoryBarrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; break; case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL: // Image layout will be used as a depth/stencil attachment // Make sure any writes to depth/stencil buffer have been finished imageMemoryBarrier.dstAccessMask = imageMemoryBarrier.dstAccessMask | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; break; case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL: // Image will be read in a shader (sampler, input attachment) // Make sure any writes to the image have been finished if (imageMemoryBarrier.srcAccessMask == 0) { imageMemoryBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; } imageMemoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; break; default: // Other source layouts aren't handled (yet) break; } // Put barrier inside setup command buffer vkCmdPipelineBarrier( cmd_buffer, srcStageMask, dstStageMask, 0, 0, nullptr, 0, nullptr, 1, &imageMemoryBarrier); } //VALID void VContext::setImageLayout(VkCommandBuffer cmdbuffer, VkImage image, VkImageAspectFlags aspectMask, VkImageLayout oldImageLayout, VkImageLayout newImageLayout, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask) { VkImageSubresourceRange subresource_range = {}; subresource_range.aspectMask = aspectMask; subresource_range.baseMipLevel = 0; subresource_range.levelCount = 1; subresource_range.layerCount = 1; setImageLayout(cmdbuffer, image, oldImageLayout, newImageLayout, subresource_range, srcStageMask, dstStageMask); } //VALID void VContext::flushCommandBuffer(VkCommandBuffer commandBuffer, VkQueue queue, bool free) const { if (commandBuffer == nullptr) { return; } vkEndCommandBuffer(commandBuffer); VkSubmitInfo submitInfo = Initializers::submitInfo(); submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffer; // Create fence to ensure that the command buffer has finished executing VkFenceCreateInfo fenceInfo = Initializers::fenceCreateInfo(0); VkFence fence; vkCreateFence(device.logicalDevice, &fenceInfo, nullptr, &fence); // Submit to the queue vkQueueSubmit(queue, 1, &submitInfo, fence); // Wait for the fence to signal that command buffer has finished executing vkWaitForFences(device.logicalDevice, 1, &fence, VK_TRUE, 100000000000); vkDestroyFence(device.logicalDevice, fence, nullptr); if (free) { vkFreeCommandBuffers(device.logicalDevice, commandPool, 1, &commandBuffer); } } void VContext::createShaderBindingTable() { // Create buffer for the shader binding table const uint32_t sbtSize = rayTracingProperties.shaderGroupHandleSize * NUM_SHADER_GROUPS; createBuffer( VK_BUFFER_USAGE_RAY_TRACING_BIT_NV, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &mShaderBindingTable, sbtSize); mShaderBindingTable.map(); const auto shaderHandleStorage = new uint8_t[sbtSize]; // Get shader identifiers vkGetRayTracingShaderGroupHandlesNV(device.logicalDevice, Rpipeline, 0, NUM_SHADER_GROUPS, sbtSize, shaderHandleStorage); auto* data = static_cast<uint8_t*>(mShaderBindingTable.mapped); // Copy the shader identifiers to the shader binding table data += copyShaderIdentifier(data, shaderHandleStorage, INDEX_RAYGEN); data += copyShaderIdentifier(data, shaderHandleStorage, INDEX_MISS); data += copyShaderIdentifier(data, shaderHandleStorage, INDEX_SHADOWMISS); data += copyShaderIdentifier(data, shaderHandleStorage, INDEX_CLOSEST_HIT); data += copyShaderIdentifier(data, shaderHandleStorage, INDEX_SHADOWHIT); mShaderBindingTable.unmap(); } VkDeviceSize VContext::copyShaderIdentifier(uint8_t* data, const uint8_t* shaderHandleStorage, uint32_t groupIndex) const { const uint32_t shaderGroupHandleSize = rayTracingProperties.shaderGroupHandleSize; memcpy(data, shaderHandleStorage + groupIndex * shaderGroupHandleSize, shaderGroupHandleSize); data += shaderGroupHandleSize; return shaderGroupHandleSize; } void VContext::createDescriptorSets() { const std::vector<VkDescriptorPoolSize> poolSizes = { { VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV, 1 }, { VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1 }, { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1 }, { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1 }, { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}, { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1}, {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}, { VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1 } }; VkDescriptorPoolCreateInfo descriptorPoolCreateInfo = Initializers::descriptorPoolCreateInfo(poolSizes, 1); vkCreateDescriptorPool(device.logicalDevice, &descriptorPoolCreateInfo, nullptr, &descriptorPool); VkDescriptorSetAllocateInfo descriptorSetAllocateInfo = Initializers::descriptorSetAllocateInfo(descriptorPool, &RdescriptorSetLayout, 1); vkAllocateDescriptorSets(device.logicalDevice, &descriptorSetAllocateInfo, &RdescriptorSet); //Acceleration Structure VkWriteDescriptorSetAccelerationStructureNV descriptorAccelerationStructureInfo{}; descriptorAccelerationStructureInfo.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_ACCELERATION_STRUCTURE_NV; descriptorAccelerationStructureInfo.accelerationStructureCount = 1; descriptorAccelerationStructureInfo.pAccelerationStructures = &topLevelAS.accelerationStructure; VkWriteDescriptorSet accelerationStructureWrite{}; accelerationStructureWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; accelerationStructureWrite.pNext = &descriptorAccelerationStructureInfo; accelerationStructureWrite.dstSet = RdescriptorSet; accelerationStructureWrite.dstBinding = 0; accelerationStructureWrite.descriptorCount = 1; accelerationStructureWrite.descriptorType = VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV; //FINAL IMAGE VkDescriptorImageInfo storageImageDescriptor{}; storageImageDescriptor.imageView = storageImage.view; storageImageDescriptor.imageLayout = VK_IMAGE_LAYOUT_GENERAL; //ACCUMULATION IMAGE VkDescriptorImageInfo accImageDescriptor{}; accImageDescriptor.imageView = accImage.view; accImageDescriptor.imageLayout = VK_IMAGE_LAYOUT_GENERAL; VkDescriptorBufferInfo vertexBufferDescriptor{}; vertexBufferDescriptor.buffer = vertBuffer.buffer; vertexBufferDescriptor.range = VK_WHOLE_SIZE; VkDescriptorBufferInfo TriNumberDescriptor{}; TriNumberDescriptor.buffer = NumberOfTriangles.buffer; TriNumberDescriptor.range = VK_WHOLE_SIZE; VkDescriptorBufferInfo TimeBufferDescriptor{}; TimeBufferDescriptor.buffer = TimeBuffer.buffer; TimeBufferDescriptor.range = VK_WHOLE_SIZE; //Storage Image const VkWriteDescriptorSet resultImageWrite = Initializers::writeDescriptorSet(RdescriptorSet, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &storageImageDescriptor); const VkWriteDescriptorSet accImageWrite = Initializers::writeDescriptorSet(RdescriptorSet, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 7, &accImageDescriptor); //Uniform Data const VkWriteDescriptorSet uniformBufferWrite = Initializers::writeDescriptorSet(RdescriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &ubo.descriptor); const VkWriteDescriptorSet matBufferWrite = Initializers::writeDescriptorSet(RdescriptorSet, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 3, &matBuffer.descriptor); VkWriteDescriptorSet vertexBufferWrite = Initializers::writeDescriptorSet(RdescriptorSet, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 4, &vertBuffer.descriptor); VkWriteDescriptorSet TimeBufferWrite = Initializers::writeDescriptorSet(RdescriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 5, &TimeBuffer.descriptor); VkWriteDescriptorSet TriNumberWrite = Initializers::writeDescriptorSet(RdescriptorSet, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 6, &NumberOfTriangles.descriptor); std::vector<VkWriteDescriptorSet> writeDescriptorSets = { accelerationStructureWrite, resultImageWrite, uniformBufferWrite, matBufferWrite, vertexBufferWrite, TimeBufferWrite, TriNumberWrite, accImageWrite }; vkUpdateDescriptorSets(device.logicalDevice, static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, nullptr); } void VContext::createUniformBuffer() { CHECK_ERROR(createBuffer(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &ubo, sizeof(uniformData), &uniformData)); CHECK_ERROR(ubo.map()); updateUniformBuffers(true); } void VContext::updateUniformBuffers(bool updateAcc) { uniformData.projInverse = camera.matrices.perspective; uniformData.viewInverse = camera.matrices.view; memcpy(ubo.mapped, &uniformData, sizeof(uniformData)); if(updateAcc) uniformData.data.y += camera.sample; else uniformData.data.y = camera.sample; } void VContext::buildCommandbuffers() { VkCommandBufferBeginInfo cmdBufInfo = Initializers::commandBufferBeginInfo(); const VkImageSubresourceRange subresource_range = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }; for (size_t i = 0; i < commandBuffers.size(); ++i) { CHECK_ERROR(vkBeginCommandBuffer(commandBuffers[i], &cmdBufInfo)); /* Dispatch the ray tracing commands */ vkCmdBindPipeline(commandBuffers[i], VK_PIPELINE_BIND_POINT_RAY_TRACING_NV, Rpipeline); vkCmdBindDescriptorSets(commandBuffers[i], VK_PIPELINE_BIND_POINT_RAY_TRACING_NV, RpipelineLayout, 0, 1, &RdescriptorSet, 0, nullptr); // Calculate shader binding offsets, which is pretty straight forward in our example const VkDeviceSize bindingOffsetRayGenShader = rayTracingProperties.shaderGroupHandleSize * INDEX_RAYGEN; const VkDeviceSize bindingOffsetMissShader = rayTracingProperties.shaderGroupHandleSize * INDEX_MISS; const VkDeviceSize bindingOffsetHitShader = rayTracingProperties.shaderGroupHandleSize * INDEX_CLOSEST_HIT; const VkDeviceSize bindingStride = rayTracingProperties.shaderGroupHandleSize; vkCmdTraceRaysNV(commandBuffers[i], mShaderBindingTable.buffer, bindingOffsetRayGenShader, mShaderBindingTable.buffer, bindingOffsetMissShader, bindingStride, mShaderBindingTable.buffer, bindingOffsetHitShader, bindingStride, nullptr, 0, 0, WIDTH, HEIGHT, 1); //DenoiseImage(); /* Copy raytracing output to swap chain image */ // Prepare current swapchain image as transfer destination Tools::setImageLayout( commandBuffers[i], swapChain.images[i], VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresource_range, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); // Prepare ray tracing output image as transfer source Tools::setImageLayout( commandBuffers[i], storageImage.image, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, subresource_range, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); //OptixImage2D imgOut; //ConvertVulkan2Optix(storageImage.image, imgOut, commandBuffers[i]); VkImageCopy copyRegion{}; copyRegion.srcSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }; copyRegion.srcOffset = { 0, 0, 0 }; copyRegion.dstSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }; copyRegion.dstOffset = { 0, 0, 0 }; copyRegion.extent = { WIDTH, HEIGHT, 1 }; vkCmdCopyImage(commandBuffers[i], storageImage.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, swapChain.images[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copyRegion); // Transition swap chain image back for presentation Tools::setImageLayout( commandBuffers[i], swapChain.images[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, subresource_range, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); // Transition ray tracing output image back to general layout Tools::setImageLayout( commandBuffers[i], storageImage.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, subresource_range, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); CHECK_ERROR(vkEndCommandBuffer(commandBuffers[i])); } } void VContext::setupRayTracingSupport(std::vector<VObject>& objects, std::vector<int>& trianglesNumber) { // Query the ray tracing properties of the current implementation, we will need them later on rayTracingProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PROPERTIES_NV; VkPhysicalDeviceProperties2 deviceProps2{}; deviceProps2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2; deviceProps2.pNext = &rayTracingProperties; vkGetPhysicalDeviceProperties2(device.physicalDevice, &deviceProps2); VkSemaphoreCreateInfo semaphoreCreateInfo = Initializers::semaphoreCreateInfo(); // Create a semaphore used to synchronize image presentation // Ensures that the image is displayed before we start submitting new commands to the queu CHECK_ERROR(vkCreateSemaphore(device.logicalDevice, &semaphoreCreateInfo, nullptr, &semaphores.presentComplete)); // Create a semaphore used to synchronize command submission // Ensures that the image is not presented until all commands have been sumbitted and executed CHECK_ERROR(vkCreateSemaphore(device.logicalDevice, &semaphoreCreateInfo, nullptr, &semaphores.renderComplete)); camera.setPosition(glm::vec3(0, -6, -2)); camera.setPerspective(80, static_cast<float>(WIDTH) / static_cast<float>(HEIGHT), 0.1, 1024); camera.Pitch = 25; camera.Yaw = 90; uniformData.data.x = camera.sample; uniformData.data.y = 1; // Set up submit info structure // Semaphores will stay the same during application lifetime // Command buffer submission info is set by each example submitInfo = Initializers::submitInfo(); submitInfo.pWaitDstStageMask = &submitPipelineStages; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = &semaphores.presentComplete; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = &semaphores.renderComplete; createScene(objects); CreateStorageImage(); std::vector<float> mat; for(auto obj : objects) { trianglesNumber.push_back(obj.m_mesh.GetVertices().size() / 3); std::cout << "NUMBER OF TRIANGLES: " << obj.m_mesh.GetVertices().size() / 3 << " INSTANCE ID: " << obj.m_mesh.meshGeometry.instanceId << '\n'; for(auto vertex : obj.m_mesh.GetVertices()) { bufferVertices.push_back(vertex.pos.x); bufferVertices.push_back(vertex.pos.y); // bufferVertices.push_back(vertex.pos.z); bufferVertices.push_back(vertex.pos.z); bufferVertices.push_back(obj.m_mesh.meshGeometry.instanceId); bufferVertices.push_back(vertex.normal.x); bufferVertices.push_back(vertex.normal.y); bufferVertices.push_back(vertex.normal.z); bufferVertices.push_back(0); } mat.push_back(obj.m_material.colorAndRoughness.x); mat.push_back(obj.m_material.colorAndRoughness.y); mat.push_back(obj.m_material.colorAndRoughness.z); mat.push_back(obj.m_material.colorAndRoughness.w); mat.push_back(obj.m_material.ior.x); mat.push_back(obj.m_material.ior.y); mat.push_back(obj.m_material.ior.z); mat.push_back(obj.m_material.ior.w); } t.push_back(1.0f); CHECK_ERROR(createBuffer(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &TimeBuffer, t.size() * sizeof(float), t.data())); CHECK_ERROR(createBuffer(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &matBuffer, mat.size() * sizeof(float), mat.data())); CHECK_ERROR(createBuffer(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &vertBuffer, bufferVertices.size() * sizeof(float), bufferVertices.data())); CHECK_ERROR(createBuffer(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &NumberOfTriangles, trianglesNumber.size() * sizeof(int), trianglesNumber.data())); //CHECK_ERROR(ubo.map()); createUniformBuffer(); createRayTracingPipeline(); createShaderBindingTable(); createDescriptorSets(); } void VContext::prepareFrame() { // Acquire the next image from the swap chain const VkResult result = acquireNextImage(semaphores.presentComplete, &currentBuffer); // Recreate the swapchain if it's no longer compatible with the surface (OUT_OF_DATE) or no longer optimal for presentation (SUBOPTIMAL) if ((result == VK_ERROR_OUT_OF_DATE_KHR) || (result == VK_SUBOPTIMAL_KHR)) { //windowResize(); } else { CHECK_ERROR(result); } } void VContext::submitFrame() const { const VkResult result = queuePresent(graphicsQueue, currentBuffer, semaphores.renderComplete); if (!((result == VK_SUCCESS) || (result == VK_SUBOPTIMAL_KHR))) { if (result == VK_ERROR_OUT_OF_DATE_KHR) { // Swap chain is no longer compatible with the surface and needs to be recreated //windowResize(); return; } CHECK_ERROR(result); } CHECK_ERROR(vkQueueWaitIdle(graphicsQueue)); } void VContext::draw() { prepareFrame(); submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffers[currentBuffer]; CHECK_ERROR(vkQueueSubmit(graphicsQueue, 1, &submitInfo, nullptr)); submitFrame(); } #pragma endregion
41.929804
232
0.745307
Hukunaa
4f92e90fa219d48d9879ef2011fdf6b27f1ad0a7
1,789
cpp
C++
demos/gpuinvert/testge.cpp
ForrestSu/machine-learn
0ec612fed36f00db308646bf36761e22dca597ac
[ "MIT" ]
null
null
null
demos/gpuinvert/testge.cpp
ForrestSu/machine-learn
0ec612fed36f00db308646bf36761e22dca597ac
[ "MIT" ]
null
null
null
demos/gpuinvert/testge.cpp
ForrestSu/machine-learn
0ec612fed36f00db308646bf36761e22dca597ac
[ "MIT" ]
null
null
null
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * testge.cpp * Copyright (C) 2009 Remco Bouckaert * remco@cs.waikato.ac.nz, rrb@xm.co.nz */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <cuda_runtime.h> #include <cublas.h> #include "config.h" extern void invert(REAL * A, int n); /** * usage: * ./ */ int main(int argc, char** argv) { int n=1024; int dev = 0; for( int i = 1; i < argc-1 ; i ++ ) { if( strcmp( argv[i], "-dev" ) == 0 ) { dev = atoi( argv[i+1] ); } if( strcmp( argv[i], "-n" ) == 0 ) { n = atoi( argv[i+1] ); } } printf("Using device %i with n=%i\n", dev, n); if( cudaSetDevice( dev ) != cudaSuccess ) { printf( "Failed to set device %d\n", dev ); return 1; } REAL *A = new REAL[n*n]; srand(n); for( int i = 0; i < n; i++ ) { for (int j = 0; j < n; j++) { A[i*n+j] = 2.0*(rand()%32768)/32768.0 - 1.0; } A[i*n+i] += sqrt(n); } invert(A, n); cudaFreeHost( A ); return 0; } // main
24.847222
74
0.567915
ForrestSu
4f945887a0639bb27e42b1772d539ae84234e06c
554
hpp
C++
legion/engine/physics/data/convex_convex_collision_info.hpp
Rythe-Interactive/Legion-Engine.rythe-legacy
e199689024436c40054942796ce9dcd4d097d7fd
[ "MIT" ]
258
2020-10-22T07:09:57.000Z
2021-09-09T05:47:09.000Z
legion/engine/physics/data/convex_convex_collision_info.hpp
LeonBrands/Legion-Engine
40aa1f4a8c59eb0824de1cdda8e17d8dba7bed7c
[ "MIT" ]
51
2020-11-17T13:02:10.000Z
2021-09-07T18:19:39.000Z
legion/engine/physics/data/convex_convex_collision_info.hpp
LeonBrands/Legion-Engine
40aa1f4a8c59eb0824de1cdda8e17d8dba7bed7c
[ "MIT" ]
13
2020-12-08T08:06:48.000Z
2021-09-09T05:47:19.000Z
#pragma once #include <core/core.hpp> #include <physics/data/pointer_encapsulator.hpp> #include <physics/halfedgeedge.hpp> #include <physics/halfedgeface.hpp> namespace legion::physics { struct ConvexConvexCollisionInfo { math::vec3 edgeNormal; float ARefSeperation, BRefSeperation, aToBEdgeSeperation; PointerEncapsulator < HalfEdgeFace> ARefFace; PointerEncapsulator < HalfEdgeFace> BRefFace; PointerEncapsulator< HalfEdgeEdge> edgeRef; PointerEncapsulator< HalfEdgeEdge> edgeInc; }; }
23.083333
65
0.727437
Rythe-Interactive
4f94fcca0733ae5cd14685f52dc88c66056c0292
8,318
cpp
C++
Userland/Applications/SoundPlayer/SoundPlayerWidgetAdvancedView.cpp
ry-sev/serenity
4758dac21881cae6f1c7ff6e2257ef63c7eeb402
[ "BSD-2-Clause" ]
19,438
2019-05-20T15:11:11.000Z
2022-03-31T23:31:32.000Z
Userland/Applications/SoundPlayer/SoundPlayerWidgetAdvancedView.cpp
ry-sev/serenity
4758dac21881cae6f1c7ff6e2257ef63c7eeb402
[ "BSD-2-Clause" ]
7,882
2019-05-20T01:03:52.000Z
2022-03-31T23:26:31.000Z
Userland/Applications/SoundPlayer/SoundPlayerWidgetAdvancedView.cpp
ry-sev/serenity
4758dac21881cae6f1c7ff6e2257ef63c7eeb402
[ "BSD-2-Clause" ]
2,721
2019-05-23T00:44:57.000Z
2022-03-31T22:49:34.000Z
/* * Copyright (c) 2021, Cesar Torres <shortanemoia@protonmail.com> * Copyright (c) 2021, the SerenityOS developers. * * SPDX-License-Identifier: BSD-2-Clause */ #include "SoundPlayerWidgetAdvancedView.h" #include "BarsVisualizationWidget.h" #include "Common.h" #include "M3UParser.h" #include "PlaybackManager.h" #include <AK/LexicalPath.h> #include <AK/SIMD.h> #include <LibGUI/Action.h> #include <LibGUI/BoxLayout.h> #include <LibGUI/Button.h> #include <LibGUI/Label.h> #include <LibGUI/MessageBox.h> #include <LibGUI/Slider.h> #include <LibGUI/Splitter.h> #include <LibGUI/Toolbar.h> #include <LibGUI/ToolbarContainer.h> #include <LibGUI/Window.h> #include <LibGfx/Bitmap.h> SoundPlayerWidgetAdvancedView::SoundPlayerWidgetAdvancedView(GUI::Window& window, Audio::ClientConnection& connection) : Player(connection) , m_window(window) { window.resize(455, 350); window.set_minimum_size(600, 130); window.set_resizable(true); set_fill_with_background_color(true); set_layout<GUI::VerticalBoxLayout>(); m_splitter = add<GUI::HorizontalSplitter>(); m_player_view = m_splitter->add<GUI::Widget>(); m_playlist_widget = PlaylistWidget::construct(); m_playlist_widget->set_data_model(playlist().model()); m_playlist_widget->set_fixed_width(150); m_player_view->set_layout<GUI::VerticalBoxLayout>(); m_play_icon = Gfx::Bitmap::try_load_from_file("/res/icons/16x16/play.png").release_value_but_fixme_should_propagate_errors(); m_pause_icon = Gfx::Bitmap::try_load_from_file("/res/icons/16x16/pause.png").release_value_but_fixme_should_propagate_errors(); m_stop_icon = Gfx::Bitmap::try_load_from_file("/res/icons/16x16/stop.png").release_value_but_fixme_should_propagate_errors(); m_back_icon = Gfx::Bitmap::try_load_from_file("/res/icons/16x16/go-back.png").release_value_but_fixme_should_propagate_errors(); m_next_icon = Gfx::Bitmap::try_load_from_file("/res/icons/16x16/go-forward.png").release_value_but_fixme_should_propagate_errors(); m_visualization = m_player_view->add<BarsVisualizationWidget>(); m_playback_progress_slider = m_player_view->add<AutoSlider>(Orientation::Horizontal); m_playback_progress_slider->set_fixed_height(20); m_playback_progress_slider->set_jump_to_cursor(true); m_playback_progress_slider->set_min(0); m_playback_progress_slider->on_knob_released = [&](int value) { seek(value); }; auto& toolbar_container = m_player_view->add<GUI::ToolbarContainer>(); auto& menubar = toolbar_container.add<GUI::Toolbar>(); m_play_button = menubar.add<GUI::Button>(); m_play_button->set_icon(*m_play_icon); m_play_button->set_fixed_width(50); m_play_button->set_enabled(false); m_play_button->on_click = [&](unsigned) { toggle_pause(); }; m_stop_button = menubar.add<GUI::Button>(); m_stop_button->set_icon(*m_stop_icon); m_stop_button->set_fixed_width(50); m_stop_button->set_enabled(false); m_stop_button->on_click = [&](unsigned) { stop(); }; m_timestamp_label = menubar.add<GUI::Label>(); m_timestamp_label->set_fixed_width(110); // filler_label menubar.add<GUI::Label>(); m_back_button = menubar.add<GUI::Button>(); m_back_button->set_fixed_width(50); m_back_button->set_icon(*m_back_icon); m_back_button->set_enabled(false); m_back_button->on_click = [&](unsigned) { play_file_path(playlist().previous()); }; m_next_button = menubar.add<GUI::Button>(); m_next_button->set_fixed_width(50); m_next_button->set_icon(*m_next_icon); m_next_button->set_enabled(false); m_next_button->on_click = [&](unsigned) { play_file_path(playlist().next()); }; m_volume_label = &menubar.add<GUI::Label>(); m_volume_label->set_fixed_width(30); m_volume_slider = &menubar.add<GUI::HorizontalSlider>(); m_volume_slider->set_fixed_width(95); m_volume_slider->set_min(0); m_volume_slider->set_max(150); m_volume_slider->set_value(100); m_volume_slider->on_change = [&](int value) { double volume = m_nonlinear_volume_slider ? (double)(value * value) / (100 * 100) : value / 100.; set_volume(volume); }; set_nonlinear_volume_slider(false); done_initializing(); } void SoundPlayerWidgetAdvancedView::set_nonlinear_volume_slider(bool nonlinear) { m_nonlinear_volume_slider = nonlinear; } void SoundPlayerWidgetAdvancedView::drop_event(GUI::DropEvent& event) { event.accept(); if (event.mime_data().has_urls()) { auto urls = event.mime_data().urls(); if (urls.is_empty()) return; window()->move_to_front(); // FIXME: Add all paths from drop event to the playlist play_file_path(urls.first().path()); } } void SoundPlayerWidgetAdvancedView::keydown_event(GUI::KeyEvent& event) { if (event.key() == Key_Space) m_play_button->click(); if (event.key() == Key_M) toggle_mute(); if (event.key() == Key_S) m_stop_button->click(); if (event.key() == Key_Up) m_volume_slider->set_value(m_volume_slider->value() + m_volume_slider->page_step()); if (event.key() == Key_Down) m_volume_slider->set_value(m_volume_slider->value() - m_volume_slider->page_step()); GUI::Widget::keydown_event(event); } void SoundPlayerWidgetAdvancedView::set_playlist_visible(bool visible) { if (!visible) { m_playlist_widget->remove_from_parent(); m_player_view->set_max_width(window()->width()); } else if (!m_playlist_widget->parent()) { m_player_view->parent_widget()->add_child(*m_playlist_widget); } } void SoundPlayerWidgetAdvancedView::play_state_changed(Player::PlayState state) { sync_previous_next_buttons(); m_play_button->set_enabled(state != PlayState::NoFileLoaded); m_play_button->set_icon(state == PlayState::Playing ? *m_pause_icon : *m_play_icon); m_stop_button->set_enabled(state != PlayState::Stopped && state != PlayState::NoFileLoaded); m_playback_progress_slider->set_enabled(state != PlayState::NoFileLoaded); } void SoundPlayerWidgetAdvancedView::loop_mode_changed(Player::LoopMode) { } void SoundPlayerWidgetAdvancedView::mute_changed(bool) { // FIXME: Update the volume slider when player is muted } void SoundPlayerWidgetAdvancedView::sync_previous_next_buttons() { m_back_button->set_enabled(playlist().size() > 1 && !playlist().shuffling()); m_next_button->set_enabled(playlist().size() > 1); } void SoundPlayerWidgetAdvancedView::shuffle_mode_changed(Player::ShuffleMode) { sync_previous_next_buttons(); } void SoundPlayerWidgetAdvancedView::time_elapsed(int seconds) { m_timestamp_label->set_text(String::formatted("Elapsed: {:02}:{:02}:{:02}", seconds / 3600, seconds / 60, seconds % 60)); } void SoundPlayerWidgetAdvancedView::file_name_changed(StringView name) { m_window.set_title(String::formatted("{} - Sound Player", name)); } void SoundPlayerWidgetAdvancedView::total_samples_changed(int total_samples) { m_playback_progress_slider->set_max(total_samples); m_playback_progress_slider->set_page_step(total_samples / 10); } void SoundPlayerWidgetAdvancedView::sound_buffer_played(RefPtr<Audio::Buffer> buffer, int sample_rate, int samples_played) { m_visualization->set_buffer(buffer); m_visualization->set_samplerate(sample_rate); m_playback_progress_slider->set_value(samples_played); } void SoundPlayerWidgetAdvancedView::volume_changed(double volume) { m_volume_label->set_text(String::formatted("{}%", static_cast<int>(volume * 100))); } void SoundPlayerWidgetAdvancedView::playlist_loaded(StringView path, bool loaded) { if (!loaded) { GUI::MessageBox::show(&m_window, String::formatted("Could not load playlist at \"{}\".", path), "Error opening playlist", GUI::MessageBox::Type::Error); return; } set_playlist_visible(true); play_file_path(playlist().next()); } void SoundPlayerWidgetAdvancedView::audio_load_error(StringView path, StringView error_string) { GUI::MessageBox::show(&m_window, String::formatted("Failed to load audio file: {} ({})", path, error_string.is_null() ? "Unknown error" : error_string), "Filetype error", GUI::MessageBox::Type::Error); }
33.95102
160
0.72289
ry-sev
4f97d3ae1644ff5d7640881e58bffdacd8183339
8,932
cpp
C++
source/Lib/TLibRenderer/TRenImage.cpp
Joeyrr/ECP_EPM
7e7034f6dbda973b316d17cb0b8d9e0256ad86a3
[ "BSD-3-Clause", "MIT" ]
null
null
null
source/Lib/TLibRenderer/TRenImage.cpp
Joeyrr/ECP_EPM
7e7034f6dbda973b316d17cb0b8d9e0256ad86a3
[ "BSD-3-Clause", "MIT" ]
null
null
null
source/Lib/TLibRenderer/TRenImage.cpp
Joeyrr/ECP_EPM
7e7034f6dbda973b316d17cb0b8d9e0256ad86a3
[ "BSD-3-Clause", "MIT" ]
null
null
null
/* The copyright in this software is being made available under the BSD * License, included below. This software may be subject to other third party * and contributor rights, including patent rights, and no such rights are * granted under this license. * * Copyright (c) 2010-2015, ITU/ISO/IEC * 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 ISO/IEC nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "TRenImage.h" #include "TRenImagePlane.h" #include "TRenFilter.h" #include "assert.h" #if NH_3D_VSO template<typename T> TRenImage<T>::TRenImage( TRenImage& rcIn ) { allocatePlanes( rcIn.getPlane(0)->getWidth(), rcIn.getPlane(0)->getHeight(), rcIn.getNumberOfFullPlanes(), rcIn.getNumberOfQuaterPlanes() ) ; assign(&rcIn); } template<typename T> TRenImage<T>::TRenImage( UInt uiWidth, UInt uiHeight, UInt uiNumberOfFullPlanes, UInt uiNumberOfQuaterPlanes ) { allocatePlanes( uiWidth, uiHeight, uiNumberOfFullPlanes, uiNumberOfQuaterPlanes ); } template<typename T> TRenImage<T>::TRenImage() : m_uiNumberOfFullPlanes(0), m_uiNumberOfQuaterPlanes(0), m_uiNumberOfPlanes(0), m_apcPlanes(0) { } template<> TRenImage<Pel>::TRenImage( TComPicYuv* pcPicYuv, Bool bFirstPlaneOnly ) { if (bFirstPlaneOnly) //400 { m_uiNumberOfPlanes = 1; m_uiNumberOfFullPlanes = 1; m_uiNumberOfQuaterPlanes = 0; m_apcPlanes = new TRenImagePlane<Pel>*[ m_uiNumberOfPlanes ]; m_apcPlanes[0] = new TRenImagePlane<Pel>( pcPicYuv->getBuf( COMPONENT_Y ), pcPicYuv->getWidth( COMPONENT_Y ) + (REN_LUMA_MARGIN << 1), pcPicYuv->getHeight( COMPONENT_Y ) + (REN_LUMA_MARGIN << 1), pcPicYuv->getStride( COMPONENT_Y ), REN_LUMA_MARGIN ); } else //420 { m_uiNumberOfPlanes = 3; m_uiNumberOfFullPlanes = 1; m_uiNumberOfQuaterPlanes = 2; m_apcPlanes = new TRenImagePlane<Pel>*[ m_uiNumberOfPlanes ]; m_apcPlanes[0] = new TRenImagePlane<Pel>( pcPicYuv->getBuf( COMPONENT_Y ), pcPicYuv->getWidth( COMPONENT_Y ) + (REN_LUMA_MARGIN << 1), pcPicYuv->getHeight( COMPONENT_Y ) + (REN_LUMA_MARGIN << 1), pcPicYuv->getStride( COMPONENT_Y ), REN_LUMA_MARGIN ); m_apcPlanes[1] = new TRenImagePlane<Pel>( pcPicYuv->getBuf( COMPONENT_Cb ), pcPicYuv->getWidth( COMPONENT_Cb ) + REN_LUMA_MARGIN , pcPicYuv->getHeight( COMPONENT_Cb ) + REN_LUMA_MARGIN , pcPicYuv->getStride( COMPONENT_Cb), REN_LUMA_MARGIN >> 1 ); m_apcPlanes[2] = new TRenImagePlane<Pel>( pcPicYuv->getBuf( COMPONENT_Cr ), pcPicYuv->getWidth( COMPONENT_Cr ) + REN_LUMA_MARGIN , pcPicYuv->getHeight( COMPONENT_Cr ) + REN_LUMA_MARGIN , pcPicYuv->getStride( COMPONENT_Cr), REN_LUMA_MARGIN >> 1 ); } } template<typename T> TRenImage<T>* TRenImage<T>::create() { return new TRenImage( m_apcPlanes[0]->getWidth(), m_apcPlanes[0]->getHeight(), m_uiNumberOfFullPlanes, m_uiNumberOfQuaterPlanes ); } template<typename T> TRenImage<T>::TRenImage( TComPicYuv* pcPicYuv, Bool bFirstPlaneOnly ) { assert(0); } template<class T> TRenImagePlane<T>* TRenImage<T>::getPlane(UInt uiPlaneNumber) const { return m_apcPlanes[uiPlaneNumber]; } template<class T> TRenImagePlane<T>** TRenImage<T>::getPlanes() const { return m_apcPlanes; } template<typename T> Void TRenImage<T>::getDataAndStrides( T** pptData, Int* piStrides ) const { for (UInt uiCurPlane = 0; uiCurPlane < m_uiNumberOfPlanes; uiCurPlane++ ) { piStrides[uiCurPlane] = m_apcPlanes[uiCurPlane]->getStride (); pptData [uiCurPlane] = m_apcPlanes[uiCurPlane]->getPlaneData(); } } template<typename T> Void TRenImage<T>::getWidthAndHeight( Int* ppiWidths, Int* ppiHeights ) const { for (UInt uiCurPlane = 0; uiCurPlane < m_uiNumberOfPlanes; uiCurPlane++ ) { ppiWidths [uiCurPlane] = m_apcPlanes[uiCurPlane]->getWidth (); ppiHeights[uiCurPlane] = m_apcPlanes[uiCurPlane]->getHeight(); } } template<typename T> Void TRenImage<T>::allocatePlanes( UInt uiWidth, UInt uiHeight, UInt uiNumberOfFullPlanes, UInt uiNumberOfQuaterPlanes ) { assert( uiNumberOfFullPlanes + uiNumberOfQuaterPlanes); UInt uiHalfWidth = uiWidth / 2; UInt uiHalfHeight = uiHeight / 2; uiHalfWidth = (uiHalfWidth == 0) ? 1 : uiHalfWidth ; uiHalfHeight = (uiHalfHeight == 0) ? 1 : uiHalfHeight; m_uiNumberOfPlanes = uiNumberOfFullPlanes + uiNumberOfQuaterPlanes; ; m_uiNumberOfFullPlanes = uiNumberOfFullPlanes; m_uiNumberOfQuaterPlanes = uiNumberOfQuaterPlanes; this->m_apcPlanes = new TRenImagePlane<T>*[m_uiNumberOfPlanes]; for (UInt uiCurPlane = 0; uiCurPlane < uiNumberOfFullPlanes; uiCurPlane++) { this->m_apcPlanes[uiCurPlane] = new TRenImagePlane<T>(uiWidth, uiHeight, REN_LUMA_MARGIN); }; for (UInt uiCurPlane = 0; uiCurPlane < uiNumberOfQuaterPlanes; uiCurPlane++) { this->m_apcPlanes[uiCurPlane+uiNumberOfFullPlanes] = new TRenImagePlane<T>(uiHalfWidth, uiHalfHeight, REN_LUMA_MARGIN >> 1); }; } template<class T> Void TRenImage<T>::assign(Int iVal) { for (UInt uiCurPlane = 0; uiCurPlane < m_uiNumberOfPlanes; uiCurPlane++) { m_apcPlanes[uiCurPlane]->assign( iVal); } } template<class T> Void TRenImage<T>::devide( Double dDevisor ) { for (UInt uiCurPlane = 0; uiCurPlane < m_uiNumberOfPlanes; uiCurPlane++) { m_apcPlanes[uiCurPlane]->devide(dDevisor); } } template<class T> template<class S> Void TRenImage<T>::assign( TRenImage<S>* pcSrcImage ) { if (pcSrcImage->getNumberOfPlanes() != m_uiNumberOfPlanes ) { assert(0); } for (UInt uiCurPlane = 0; uiCurPlane < m_uiNumberOfPlanes; uiCurPlane++) { m_apcPlanes[uiCurPlane]->assign(pcSrcImage->getPlane(uiCurPlane)->getPlaneDataOrg(),pcSrcImage->getPlane(uiCurPlane)->getStride()); } } template<typename T> Void TRenImage<T>::setData( TRenImage* pcInputImage, Bool bClean ) { for (UInt uiPlane = 0; uiPlane < m_uiNumberOfPlanes; uiPlane++) { m_apcPlanes[uiPlane]->setData( pcInputImage->getPlane( uiPlane ), bClean ); } } template<typename T> Void TRenImage<T>::extendMargin() { for (UInt uiPlane = 0; uiPlane < m_uiNumberOfPlanes; uiPlane++) { m_apcPlanes[uiPlane]->extendMargin(); } } template<class T> Void TRenImage<T>::xDeletePlanes() { for (UInt uiCurPlane = 0; uiCurPlane < m_uiNumberOfPlanes; uiCurPlane++) { if ( m_apcPlanes[uiCurPlane]) { delete m_apcPlanes[uiCurPlane]; } m_apcPlanes[uiCurPlane] = 0; } } template<class T> Void TRenImage<T>::init() { // YUV-init m_apcPlanes[0]->assign((Pel) 0 ); for (UInt uiCurPlane = 1; uiCurPlane < m_uiNumberOfPlanes; uiCurPlane++) { m_apcPlanes[uiCurPlane]->assign( (Pel) ( 1 << ( REN_BIT_DEPTH - 1 ) ) ); } } template<class T> TRenImage<T>::~TRenImage() { xDeletePlanes(); delete[] m_apcPlanes; } template<class T> UInt TRenImage<T>::getNumberOfPlanes() const { return m_uiNumberOfPlanes; } template<class T> UInt TRenImage<T>::getNumberOfQuaterPlanes() const { return m_uiNumberOfQuaterPlanes; } template<class T> UInt TRenImage<T>::getNumberOfFullPlanes() const { return m_uiNumberOfFullPlanes; } template class TRenImage<Pel>; template class TRenImage<Int>; template class TRenImage<Double>; template class TRenImage<Bool>; template Void TRenImage<Pel>::assign<Pel> (TRenImage<Pel>* ); #endif // NH_3D
32.362319
264
0.705665
Joeyrr
4f97d758bd8742b0b9699587ca343ab4c2eba6fa
3,299
cc
C++
planner/FD/src/search/heuristic.cc
karthikv792/PlanningAssistance
5693c844e9067591ea1414ee9586bcd2dfff6f51
[ "MIT" ]
4
2019-04-23T10:41:35.000Z
2019-10-27T05:14:42.000Z
planner/FD/src/search/heuristic.cc
karthikv792/PlanningAssistance
5693c844e9067591ea1414ee9586bcd2dfff6f51
[ "MIT" ]
null
null
null
planner/FD/src/search/heuristic.cc
karthikv792/PlanningAssistance
5693c844e9067591ea1414ee9586bcd2dfff6f51
[ "MIT" ]
4
2018-01-16T00:00:22.000Z
2019-11-01T23:35:01.000Z
#include "heuristic.h" #include "cost_adapted_task.h" #include "evaluation_context.h" #include "evaluation_result.h" #include "global_operator.h" #include "globals.h" #include "option_parser.h" #include "operator_cost.h" #include <cassert> #include <cstdlib> #include <limits> using namespace std; Heuristic::Heuristic(const Options &opts) : description(opts.get_unparsed_config()), initialized(false), task(get_task_from_options(opts)), task_proxy(*task), cost_type(OperatorCost(opts.get_enum("cost_type"))) { } Heuristic::~Heuristic() { } void Heuristic::set_preferred(const GlobalOperator *op) { if (!op->is_marked()) { op->mark(); preferred_operators.push_back(op); } } void Heuristic::set_preferred(OperatorProxy op) { set_preferred(op.get_global_operator()); } bool Heuristic::reach_state( const GlobalState & /*parent_state*/, const GlobalOperator & /*op*/, const GlobalState & /*state*/) { return false; } int Heuristic::get_adjusted_cost(const GlobalOperator &op) const { return get_adjusted_action_cost(op, cost_type); } State Heuristic::convert_global_state(const GlobalState &global_state) const { return task_proxy.convert_global_state(global_state); } void Heuristic::add_options_to_parser(OptionParser &parser) { ::add_cost_type_option_to_parser(parser); // TODO: When the cost_type option is gone, use "no_transform" as default. parser.add_option<shared_ptr<AbstractTask> >( "transform", "Optional task transformation for the heuristic. " "Currently only adapt_costs is available.", OptionParser::NONE); } //this solution to get default values seems not optimal: Options Heuristic::default_options() { Options opts = Options(); opts.set<shared_ptr<AbstractTask> >("transform", g_root_task()); opts.set<int>("cost_type", NORMAL); return opts; } EvaluationResult Heuristic::compute_result(EvaluationContext &eval_context) { EvaluationResult result; if (!initialized) { initialize(); initialized = true; } assert(preferred_operators.empty()); const GlobalState &state = eval_context.get_state(); int heuristic = compute_heuristic(state); for (const GlobalOperator *preferred_operator : preferred_operators) preferred_operator->unmark(); assert(heuristic == DEAD_END || heuristic >= 0); if (heuristic == DEAD_END) { /* It is permissible to mark preferred operators for dead-end states (thus allowing a heuristic to mark them on-the-fly before knowing the final result), but if it turns out we have a dead end, we don't want to actually report any preferred operators. */ preferred_operators.clear(); heuristic = EvaluationResult::INFINITE; } #ifndef NDEBUG if (heuristic != EvaluationResult::INFINITE) { for (size_t i = 0; i < preferred_operators.size(); ++i) assert(preferred_operators[i]->is_applicable(state)); } #endif result.set_h_value(heuristic); result.set_preferred_operators(move(preferred_operators)); assert(preferred_operators.empty()); return result; } string Heuristic::get_description() const { return description; }
28.439655
78
0.695362
karthikv792
4f9875ca05479fc6ef327a0e93fe7037a41bdb9a
201
cpp
C++
demo/simple/simple/src/framesimplemainwindow.cpp
Qters/QrFrame
b5f119435fa8e80ddd02c4727cf60a39ffc153b1
[ "Apache-2.0" ]
1
2016-10-21T08:14:40.000Z
2016-10-21T08:14:40.000Z
demo/simple/simple/src/framesimplemainwindow.cpp
Qters/QrFrame
b5f119435fa8e80ddd02c4727cf60a39ffc153b1
[ "Apache-2.0" ]
null
null
null
demo/simple/simple/src/framesimplemainwindow.cpp
Qters/QrFrame
b5f119435fa8e80ddd02c4727cf60a39ffc153b1
[ "Apache-2.0" ]
null
null
null
#include "framesimplemainwindow.h" USING_NS_QRDEMO; FrameSimpleMainWindow::FrameSimpleMainWindow(QWidget *parent) : QrMainWindow(parent) { } FrameSimpleMainWindow::~FrameSimpleMainWindow() { }
14.357143
61
0.791045
Qters
4f9add04f25b88050d4f340878a1bfca21aa857f
2,833
cpp
C++
src/example/pegtl/uri.cpp
ClausKlein/PEGTL
d4278cb59a9b5b74e5e599ba4859c778b3121dc6
[ "MIT" ]
null
null
null
src/example/pegtl/uri.cpp
ClausKlein/PEGTL
d4278cb59a9b5b74e5e599ba4859c778b3121dc6
[ "MIT" ]
null
null
null
src/example/pegtl/uri.cpp
ClausKlein/PEGTL
d4278cb59a9b5b74e5e599ba4859c778b3121dc6
[ "MIT" ]
null
null
null
// Copyright (c) 2017-2021 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #include <tao/pegtl.hpp> #include <tao/pegtl/contrib/uri.hpp> #include <iostream> namespace pegtl = TAO_PEGTL_NAMESPACE; struct URI { std::string scheme; std::string authority; std::string userinfo; std::string host; std::string port; std::string path; std::string query; std::string fragment; explicit URI( const std::string& uri ); }; namespace uri { template< std::string URI::*Field > struct bind { template< typename ActionInput > static void apply( const ActionInput& in, URI& uri ) { uri.*Field = in.string(); } }; // clang-format off template< typename Rule > struct action {}; template<> struct action< pegtl::uri::scheme > : bind< &URI::scheme > {}; template<> struct action< pegtl::uri::authority > : bind< &URI::authority > {}; // userinfo: see below template<> struct action< pegtl::uri::host > : bind< &URI::host > {}; template<> struct action< pegtl::uri::port > : bind< &URI::port > {}; template<> struct action< pegtl::uri::path_noscheme > : bind< &URI::path > {}; template<> struct action< pegtl::uri::path_rootless > : bind< &URI::path > {}; template<> struct action< pegtl::uri::path_absolute > : bind< &URI::path > {}; template<> struct action< pegtl::uri::path_abempty > : bind< &URI::path > {}; template<> struct action< pegtl::uri::query > : bind< &URI::query > {}; template<> struct action< pegtl::uri::fragment > : bind< &URI::fragment > {}; // clang-format on template<> struct action< pegtl::uri::opt_userinfo > { template< typename ActionInput > static void apply( const ActionInput& in, URI& uri ) { if( !in.empty() ) { uri.userinfo = std::string( in.begin(), in.size() - 1 ); } } }; } // namespace uri URI::URI( const std::string& uri ) { using grammar = pegtl::must< pegtl::uri::URI >; pegtl::memory_input input( uri, "uri" ); pegtl::parse< grammar, uri::action >( input, *this ); } int main( int argc, char** argv ) { for( int i = 1; i < argc; ++i ) { std::cout << "Parsing " << argv[ i ] << std::endl; const URI uri( argv[ i ] ); std::cout << "URI.scheme: " << uri.scheme << std::endl; std::cout << "URI.authority: " << uri.authority << std::endl; std::cout << "URI.userinfo: " << uri.userinfo << std::endl; std::cout << "URI.host: " << uri.host << std::endl; std::cout << "URI.port: " << uri.port << std::endl; std::cout << "URI.path: " << uri.path << std::endl; std::cout << "URI.query: " << uri.query << std::endl; std::cout << "URI.fragment: " << uri.fragment << std::endl; } return 0; }
31.477778
82
0.588069
ClausKlein
4f9ae25d42a405d521059d4e7536da4a580fc445
2,025
cpp
C++
src/main.cpp
klmr/guesstimate
330892dad2fac91134e414bb148c855895211a3e
[ "BSD-3-Clause" ]
1
2020-10-15T03:37:51.000Z
2020-10-15T03:37:51.000Z
src/main.cpp
klmr/guesstimate
330892dad2fac91134e414bb148c855895211a3e
[ "BSD-3-Clause" ]
null
null
null
src/main.cpp
klmr/guesstimate
330892dad2fac91134e414bb148c855895211a3e
[ "BSD-3-Clause" ]
null
null
null
// ========================================================================== // Guesstimate - Technology Constant Estimator // ========================================================================== // Copyright (c) 2011, Manuel Holtgrewe // 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 Manuel Holtgrewe 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. // // ========================================================================== #include "measure_pthreads.h" #include "measure_omp.h" int main(int argc, char ** argv) { measurePThreads(); measureOmp(); return 0; }
48.214286
78
0.655802
klmr
4f9c2c878baf402030f1a4564098ce515828d2c5
633
cpp
C++
apps/core_test/main.cpp
max-delta/retrofit-public
5447fd6399fd74ffbb75494c103940751000db12
[ "X11" ]
3
2019-10-27T22:32:44.000Z
2020-05-21T04:00:46.000Z
apps/core_test/main.cpp
max-delta/retrofit-public
5447fd6399fd74ffbb75494c103940751000db12
[ "X11" ]
null
null
null
apps/core_test/main.cpp
max-delta/retrofit-public
5447fd6399fd74ffbb75494c103940751000db12
[ "X11" ]
null
null
null
#include "stdafx.h" #include "core/macros.h" #include "rftl/string" namespace RF { /////////////////////////////////////////////////////////////////////////////// TEST( Bootstrap, Pass ) { RF_ASSERT( true ); ASSERT_TRUE( true ); } /////////////////////////////////////////////////////////////////////////////// } int main( int argc, char** argv ) { ::testing::InitGoogleTest( &argc, argv ); int const retVal = RUN_ALL_TESTS(); if( retVal != 0 ) { if( argc >= 2 && rftl::string( argv[1] ) == "--nopause" ) { fputs( "One or more tests failed", stderr ); } else { system( "pause" ); } } return retVal; }
17.583333
79
0.440758
max-delta
4f9c7525a8cad1626c0dae645763f7f1ec566016
1,924
cpp
C++
framework/referencerenderer/rrPrimitivePacket.cpp
iabernikhin/VK-GL-CTS
a3338eb2ded98b5befda64f9325db0d219095a00
[ "Apache-2.0" ]
354
2017-01-24T17:12:38.000Z
2022-03-30T07:40:19.000Z
framework/referencerenderer/rrPrimitivePacket.cpp
iabernikhin/VK-GL-CTS
a3338eb2ded98b5befda64f9325db0d219095a00
[ "Apache-2.0" ]
275
2017-01-24T20:10:36.000Z
2022-03-24T16:24:50.000Z
framework/referencerenderer/rrPrimitivePacket.cpp
iabernikhin/VK-GL-CTS
a3338eb2ded98b5befda64f9325db0d219095a00
[ "Apache-2.0" ]
190
2017-01-24T18:02:04.000Z
2022-03-27T13:11:23.000Z
/*------------------------------------------------------------------------- * drawElements Quality Program Reference Renderer * ----------------------------------------------- * * Copyright 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Primitive packet *//*--------------------------------------------------------------------*/ #include "rrPrimitivePacket.hpp" #include "rrVertexPacket.hpp" namespace rr { GeometryEmitter::GeometryEmitter (VertexPacketAllocator& vpalloc, size_t numVertices) : m_vpalloc (vpalloc) , m_numEmitted (0) , m_maxVertices (numVertices) { } void GeometryEmitter::EmitVertex (const tcu::Vec4& position, float pointSize, const GenericVec4* varyings, int primitiveID) { VertexPacket* packet; if (++m_numEmitted > m_maxVertices) { DE_FATAL("Undefined results, too many vertices emitted."); return; } packet = m_vpalloc.alloc(); packet->position = position; packet->pointSize = pointSize; packet->primitiveID = primitiveID; for (size_t ndx = 0; ndx < m_vpalloc.getNumVertexOutputs(); ++ndx) packet->outputs[ndx] = varyings[ndx]; m_emitted.push_back(packet); } void GeometryEmitter::EndPrimitive (void) { m_numEmitted = 0; m_emitted.push_back(DE_NULL); } void GeometryEmitter::moveEmittedTo (std::vector<VertexPacket*>& output) { m_emitted.swap(output); m_emitted.clear(); } } // rr
26.356164
123
0.660083
iabernikhin
4f9cd5524214c1de620de02355c7207196458441
502
hpp
C++
src/main/cpp/platform-wrapper-regdriver/axiregdriver.hpp
DM-PRO-17-A/fpga-tidbits
017226cb8d56353454e6a84e9c2dfda176ca4865
[ "BSD-2-Clause" ]
null
null
null
src/main/cpp/platform-wrapper-regdriver/axiregdriver.hpp
DM-PRO-17-A/fpga-tidbits
017226cb8d56353454e6a84e9c2dfda176ca4865
[ "BSD-2-Clause" ]
null
null
null
src/main/cpp/platform-wrapper-regdriver/axiregdriver.hpp
DM-PRO-17-A/fpga-tidbits
017226cb8d56353454e6a84e9c2dfda176ca4865
[ "BSD-2-Clause" ]
null
null
null
#ifndef AXIREGDRIVER_H #define AXIREGDRIVER_H #include <stdint.h> #include "wrapperregdriver.h" class AXIRegDriver : public WrapperRegDriver { public: AXIRegDriver(void *baseAddr) { m_baseAddr = (AccelReg *) baseAddr; } virtual ~AXIRegDriver() {} virtual void writeReg(unsigned int regInd, AccelReg regValue) { m_baseAddr[regInd] = regValue; } virtual AccelReg readReg(unsigned int regInd) { return m_baseAddr[regInd]; } protected: AccelReg * m_baseAddr; }; #endif
17.310345
65
0.719124
DM-PRO-17-A
4f9d26eeaf71d33ebc9037a6ae49e3a3115554bb
8,209
cpp
C++
ad_map_access/src/access/GeometryStore.cpp
woojinjjang/map-1
d12bb410f03d078a995130b4e671746ace8b6287
[ "MIT" ]
61
2019-12-19T20:57:24.000Z
2022-03-29T15:20:51.000Z
ad_map_access/src/access/GeometryStore.cpp
woojinjjang/map-1
d12bb410f03d078a995130b4e671746ace8b6287
[ "MIT" ]
54
2020-04-05T05:32:47.000Z
2022-03-15T18:42:33.000Z
ad_map_access/src/access/GeometryStore.cpp
woojinjjang/map-1
d12bb410f03d078a995130b4e671746ace8b6287
[ "MIT" ]
31
2019-12-20T07:37:39.000Z
2022-03-16T13:06:16.000Z
// ----------------- BEGIN LICENSE BLOCK --------------------------------- // // Copyright (C) 2018-2021 Intel Corporation // // SPDX-License-Identifier: MIT // // ----------------- END LICENSE BLOCK ----------------------------------- #include "GeometryStore.hpp" #include <memory> #include "ad/map/access/Logging.hpp" #include "ad/map/access/Store.hpp" #include "ad/map/lane/LaneOperation.hpp" #include "ad/map/point/GeometryOperation.hpp" #include "ad/map/serialize/SerializeGeneratedTypes.hpp" namespace ad { namespace map { namespace access { GeometryStore::GeometryStore() { store_ = nullptr; points3d_ = 0; capacity3d_ = 0; } GeometryStore::~GeometryStore() { destroy(); } ///////////// // Operations bool GeometryStore::store(lane::Lane::ConstPtr lane) { if (lane) { lane::LaneId id = lane->id; auto it = lane_items_.find(id); if (it == lane_items_.end()) { uint32_t offset_left = 0, size_left = 0; if (store(lane, lane::ContactLocation::LEFT, offset_left, size_left)) { uint32_t offset_right = 0, size_right = 0; if (store(lane, lane::ContactLocation::RIGHT, offset_right, size_right)) { GeometryStoreItem item; item.leftEdgeOffset = offset_left; item.leftEdgePoints = size_left; item.rightEdgeOffset = offset_right; item.rightEdgePoints = size_right; lane_items_[id] = item; return true; } } } else { access::getLogger()->error("GeometryStore: Lane already in Store?! {}", id); throw std::runtime_error("GeometryStore: Lane already in Store?! "); } } else { throw std::runtime_error("GeometryStore: Lane invalid"); } return false; } bool GeometryStore::restore(lane::Lane::Ptr lane) const { if (lane) { lane::LaneId id = lane->id; auto it = lane_items_.find(id); if (it != lane_items_.end()) { const GeometryStoreItem &item = it->second; point::ECEFEdge left; if (restore(left, item.leftEdgeOffset, item.leftEdgePoints)) { point::ECEFEdge right; if (restore(right, item.rightEdgeOffset, item.rightEdgePoints)) { lane->edgeLeft = point::createGeometry(left, false); lane->edgeRight = point::createGeometry(right, false); return true; } else { access::getLogger()->error("GeometryStore: Lane right edge not in Store?! {}", id); } } else { access::getLogger()->error("GeometryStore: Lane left edge not in Store?! {}", id); } } else { access::getLogger()->error("GeometryStore: Lane not in Store?! {}", id); } } else { throw std::runtime_error("GeometryStore: Lane invalid"); } return false; } bool GeometryStore::check(lane::Lane::ConstPtr lane) const { if (lane) { lane::LaneId id = lane->id; auto it = lane_items_.find(id); if (it != lane_items_.end()) { const GeometryStoreItem &item = it->second; point::ECEFEdge left; if (restore(left, item.leftEdgeOffset, item.leftEdgePoints)) { point::ECEFEdge right; if (restore(right, item.rightEdgeOffset, item.rightEdgePoints)) { if (lane->edgeLeft.ecefEdge == left && lane->edgeRight.ecefEdge == right) { return true; } else { access::getLogger()->error("GeometryStore: Lane geometry mismatch?! {}", id); } } else { access::getLogger()->error("GeometryStore: Lane right edge not in Store?! {}", id); } } else { access::getLogger()->error("GeometryStore: Lane left edge not in Store?! {}", id); } } else { access::getLogger()->error("GeometryStore: Lane not in Store?! {}", id); } } else { throw std::runtime_error("GeometryStore: Lane invalid"); } return false; } /////////////// // Aux Methods bool GeometryStore::store(lane::Lane::ConstPtr lane, lane::ContactLocation location, uint32_t &offs3d, uint32_t &size) { if ((location != lane::ContactLocation::LEFT) && (location != lane::ContactLocation::RIGHT)) { throw std::runtime_error("Location must be LEFT or RIGHT"); } const point::ECEFEdge &ecef = (location == lane::ContactLocation::LEFT) ? lane->edgeLeft.ecefEdge : lane->edgeRight.ecefEdge; size = static_cast<uint32_t>(ecef.size()); lane::ContactLaneList contact_lanes = lane::getContactLanes(*lane, location); for (auto contact_lane : contact_lanes) { lane::LaneId contact_lane_id = contact_lane.toLane; auto it = lane_items_.find(contact_lane_id); if (it != lane_items_.end()) { lane::Lane::ConstPtr clane = lane::getLanePtr(contact_lane_id); if (clane) { const point::ECEFEdge &ecef1 = (location == lane::ContactLocation::LEFT) ? clane->edgeRight.ecefEdge : clane->edgeLeft.ecefEdge; if (ecef == ecef1) { offs3d = (location == lane::ContactLocation::LEFT) ? it->second.rightEdgeOffset : it->second.leftEdgeOffset; return true; } } } } return store(ecef, offs3d); } bool GeometryStore::store(const point::ECEFEdge &ecef, uint32_t &offset3d) { while (points3d_ + ecef.size() >= capacity3d_) { if (!expand()) { return false; } } offset3d = points3d_; for (auto pt : ecef) { uint32_t index = (points3d_++) * 3; store_[index++] = static_cast<double>(pt.x); store_[index++] = static_cast<double>(pt.y); store_[index++] = static_cast<double>(pt.z); } return true; } bool GeometryStore::restore(point::ECEFEdge &ecef, uint32_t offset3d, uint32_t points3d) const { if (!ecef.empty()) { throw std::runtime_error("ecef not empty"); } if (offset3d + points3d <= capacity3d_) { for (uint32_t index = offset3d * 3; points3d != 0; points3d--) { point::ECEFPoint pt; pt.x = point::ECEFCoordinate(store_[index++]); pt.y = point::ECEFCoordinate(store_[index++]); pt.z = point::ECEFCoordinate(store_[index++]); ecef.push_back(pt); } return true; } else { return false; } } ////////////// // Aux Methods void GeometryStore::destroy() { if (store_ != nullptr) { free(store_); store_ = nullptr; points3d_ = 0; capacity3d_ = 0; access::getLogger()->debug("GeometryStore: Destroyed."); } } bool GeometryStore::expand() { if (store_ == nullptr) { return create(SIZE_INCREMENT); } else { size_t bytes = (capacity3d_ + SIZE_INCREMENT) * 3 * sizeof(double); double *store = static_cast<double *>(std::realloc(store_, bytes)); if (store != nullptr) { store_ = store; capacity3d_ += SIZE_INCREMENT; return true; } else { access::getLogger()->error("GeometryStore: Cannot expand to {} bytes.", bytes); return false; } } } bool GeometryStore::create(uint32_t capacity3d) { destroy(); size_t bytes = capacity3d * 3 * sizeof(double); store_ = static_cast<double *>(std::malloc(bytes)); if (store_ != nullptr) { points3d_ = 0; capacity3d_ = capacity3d; return true; } else { access::getLogger()->error("GeometryStore: Cannot allocate {} bytes.", bytes); return false; } } bool GeometryStore::serialize(serialize::ISerializer &serializer) { bool ok = serializer.serialize(serialize::SerializeableMagic::GeometryStore) && serializer.serializeObjectMap(lane_items_) && serializer.serialize(points3d_); /*Todo the two lines below will be deleted after the map are generated again without use_zfp_*/ bool use_zfp_ = false; ok = ok && serializer.serialize(use_zfp_); if (ok) { if (!serializer.isStoring()) { if (create(points3d_)) { points3d_ = capacity3d_; } else { return false; } ok = serializer.read(store_, points3d_ * 3 * sizeof(double)); } else { ok = serializer.write(store_, points3d_ * 3 * sizeof(double)); } } return ok; } } // namespace access } // namespace map } // namespace ad
24.875758
118
0.600926
woojinjjang
4f9d626d442baaed634e97cdccdec649c287f82f
1,384
cpp
C++
src/input/test/req_type_test.cpp
fh-tech/CFLOP
6df4bf40cf34b3b109adc18b622635f814b2f4f3
[ "MIT" ]
3
2018-04-30T21:48:04.000Z
2019-01-24T05:07:11.000Z
src/input/test/req_type_test.cpp
fh-tech/CFLOP
6df4bf40cf34b3b109adc18b622635f814b2f4f3
[ "MIT" ]
null
null
null
src/input/test/req_type_test.cpp
fh-tech/CFLOP
6df4bf40cf34b3b109adc18b622635f814b2f4f3
[ "MIT" ]
null
null
null
// // Created by vik on 25.04.18. // #include <gtest/gtest.h> #include <input.h> #include "json_requests.h" using namespace input_lib; TEST(make_req_type, req_type_nodes) { std::array<req_type,5> results = {NODES_POST, NODES_DELETE, NODES_GET, NODES_PUT_START, NODES_PUT_END}; for(int i = 0; i < nodes_j_vec.size(); i++) { req_type type = make_req_type(nodes_j_vec[i]); ASSERT_EQ(type, results[i]); } } TEST(make_req_type, req_type_edges) { std::array<req_type,3> results = {EDGES_GET, EDGES_POST, EDGES_DELETE}; for(int i = 0; i < edges_j_vec.size(); i++) { req_type type = make_req_type(edges_j_vec[i]); ASSERT_EQ(type, results[i]); } } TEST(make_req_type, req_type_state) { std::array<req_type,3> results = {STATE_GET, STATE_POST, STATE_PUT}; for(int i = 0; i < state_j_vec.size(); i++) { req_type type = make_req_type(state_j_vec[i]); ASSERT_EQ(type, results[i]); } } TEST(make_req_type, invalid_json) { json j = R"({ "state": { "delete": { "id": 0 } } })"_json; endpoint e = extract_endpoint(j); ASSERT_EQ(STATE, e); req_method method = extract_req_method(j, e); ASSERT_EQ(method, DELETE); req_type type = make_req_type(j); ASSERT_EQ(type, INVALID_TYPE); }
26.113208
107
0.599711
fh-tech