hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
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
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
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 |
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 |
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 |
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 |
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 |
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 ®ion, 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 ®ion, 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 |
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 |
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 |
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 ¤t,
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 ¤t, 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 ¤t, 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 ¤t,
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 ¤t, 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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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(¤tEstimateCache_);
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(¤tEstimateCache_);
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(¤tEstimateCache_, 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 |
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 |
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, ¶ms, 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, ©Region);
// 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, ¤tBuffer);
// 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 |
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 |
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 |
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 |
4f9dc822d36e60a1cda23e23e1831df56bff1380 | 151,617 | cc | C++ | src/deoptimizer/deoptimizer.cc | hamzahamidi/v8 | d9fa5bce27a1680ab2d372f31f2721663044963e | [
"BSD-3-Clause"
] | null | null | null | src/deoptimizer/deoptimizer.cc | hamzahamidi/v8 | d9fa5bce27a1680ab2d372f31f2721663044963e | [
"BSD-3-Clause"
] | null | null | null | src/deoptimizer/deoptimizer.cc | hamzahamidi/v8 | d9fa5bce27a1680ab2d372f31f2721663044963e | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2013 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/deoptimizer/deoptimizer.h"
#include <memory>
#include "src/ast/prettyprinter.h"
#include "src/builtins/accessors.h"
#include "src/codegen/assembler-inl.h"
#include "src/codegen/callable.h"
#include "src/codegen/macro-assembler.h"
#include "src/codegen/register-configuration.h"
#include "src/diagnostics/disasm.h"
#include "src/execution/frames-inl.h"
#include "src/execution/v8threads.h"
#include "src/handles/global-handles.h"
#include "src/heap/heap-inl.h"
#include "src/init/v8.h"
#include "src/interpreter/interpreter.h"
#include "src/logging/counters.h"
#include "src/logging/log.h"
#include "src/objects/debug-objects-inl.h"
#include "src/objects/heap-number-inl.h"
#include "src/objects/smi.h"
#include "src/tracing/trace-event.h"
// Has to be the last include (doesn't have include guards)
#include "src/objects/object-macros.h"
namespace v8 {
namespace internal {
// {FrameWriter} offers a stack writer abstraction for writing
// FrameDescriptions. The main service the class provides is managing
// {top_offset_}, i.e. the offset of the next slot to write to.
class FrameWriter {
public:
static const int NO_INPUT_INDEX = -1;
FrameWriter(Deoptimizer* deoptimizer, FrameDescription* frame,
CodeTracer::Scope* trace_scope)
: deoptimizer_(deoptimizer),
frame_(frame),
trace_scope_(trace_scope),
top_offset_(frame->GetFrameSize()) {}
void PushRawValue(intptr_t value, const char* debug_hint) {
PushValue(value);
if (trace_scope_ != nullptr) {
DebugPrintOutputValue(value, debug_hint);
}
}
void PushRawObject(Object obj, const char* debug_hint) {
intptr_t value = obj.ptr();
PushValue(value);
if (trace_scope_ != nullptr) {
DebugPrintOutputObject(obj, top_offset_, debug_hint);
}
}
void PushCallerPc(intptr_t pc) {
top_offset_ -= kPCOnStackSize;
frame_->SetCallerPc(top_offset_, pc);
DebugPrintOutputValue(pc, "caller's pc\n");
}
void PushCallerFp(intptr_t fp) {
top_offset_ -= kFPOnStackSize;
frame_->SetCallerFp(top_offset_, fp);
DebugPrintOutputValue(fp, "caller's fp\n");
}
void PushCallerConstantPool(intptr_t cp) {
top_offset_ -= kSystemPointerSize;
frame_->SetCallerConstantPool(top_offset_, cp);
DebugPrintOutputValue(cp, "caller's constant_pool\n");
}
void PushTranslatedValue(const TranslatedFrame::iterator& iterator,
const char* debug_hint = "") {
Object obj = iterator->GetRawValue();
PushRawObject(obj, debug_hint);
if (trace_scope_) {
PrintF(trace_scope_->file(), " (input #%d)\n", iterator.input_index());
}
deoptimizer_->QueueValueForMaterialization(output_address(top_offset_), obj,
iterator);
}
unsigned top_offset() const { return top_offset_; }
private:
void PushValue(intptr_t value) {
CHECK_GE(top_offset_, 0);
top_offset_ -= kSystemPointerSize;
frame_->SetFrameSlot(top_offset_, value);
}
Address output_address(unsigned output_offset) {
Address output_address =
static_cast<Address>(frame_->GetTop()) + output_offset;
return output_address;
}
void DebugPrintOutputValue(intptr_t value, const char* debug_hint = "") {
if (trace_scope_ != nullptr) {
PrintF(trace_scope_->file(),
" " V8PRIxPTR_FMT ": [top + %3d] <- " V8PRIxPTR_FMT " ; %s",
output_address(top_offset_), top_offset_, value, debug_hint);
}
}
void DebugPrintOutputObject(Object obj, unsigned output_offset,
const char* debug_hint = "") {
if (trace_scope_ != nullptr) {
PrintF(trace_scope_->file(), " " V8PRIxPTR_FMT ": [top + %3d] <- ",
output_address(output_offset), output_offset);
if (obj.IsSmi()) {
PrintF(V8PRIxPTR_FMT " <Smi %d>", obj.ptr(), Smi::cast(obj).value());
} else {
obj.ShortPrint(trace_scope_->file());
}
PrintF(trace_scope_->file(), " ; %s", debug_hint);
}
}
Deoptimizer* deoptimizer_;
FrameDescription* frame_;
CodeTracer::Scope* trace_scope_;
unsigned top_offset_;
};
DeoptimizerData::DeoptimizerData(Heap* heap) : heap_(heap), current_(nullptr) {
Code* start = &deopt_entry_code_[0];
Code* end = &deopt_entry_code_[DeoptimizerData::kLastDeoptimizeKind + 1];
heap_->RegisterStrongRoots(FullObjectSlot(start), FullObjectSlot(end));
}
DeoptimizerData::~DeoptimizerData() {
Code* start = &deopt_entry_code_[0];
heap_->UnregisterStrongRoots(FullObjectSlot(start));
}
Code DeoptimizerData::deopt_entry_code(DeoptimizeKind kind) {
return deopt_entry_code_[static_cast<int>(kind)];
}
void DeoptimizerData::set_deopt_entry_code(DeoptimizeKind kind, Code code) {
deopt_entry_code_[static_cast<int>(kind)] = code;
}
Code Deoptimizer::FindDeoptimizingCode(Address addr) {
if (function_.IsHeapObject()) {
// Search all deoptimizing code in the native context of the function.
Isolate* isolate = isolate_;
NativeContext native_context = function_.context().native_context();
Object element = native_context.DeoptimizedCodeListHead();
while (!element.IsUndefined(isolate)) {
Code code = Code::cast(element);
CHECK(code.kind() == Code::OPTIMIZED_FUNCTION);
if (code.contains(addr)) return code;
element = code.next_code_link();
}
}
return Code();
}
// We rely on this function not causing a GC. It is called from generated code
// without having a real stack frame in place.
Deoptimizer* Deoptimizer::New(Address raw_function, DeoptimizeKind kind,
unsigned bailout_id, Address from,
int fp_to_sp_delta, Isolate* isolate) {
JSFunction function = JSFunction::cast(Object(raw_function));
Deoptimizer* deoptimizer = new Deoptimizer(isolate, function, kind,
bailout_id, from, fp_to_sp_delta);
CHECK_NULL(isolate->deoptimizer_data()->current_);
isolate->deoptimizer_data()->current_ = deoptimizer;
return deoptimizer;
}
Deoptimizer* Deoptimizer::Grab(Isolate* isolate) {
Deoptimizer* result = isolate->deoptimizer_data()->current_;
CHECK_NOT_NULL(result);
result->DeleteFrameDescriptions();
isolate->deoptimizer_data()->current_ = nullptr;
return result;
}
DeoptimizedFrameInfo* Deoptimizer::DebuggerInspectableFrame(
JavaScriptFrame* frame, int jsframe_index, Isolate* isolate) {
CHECK(frame->is_optimized());
TranslatedState translated_values(frame);
translated_values.Prepare(frame->fp());
TranslatedState::iterator frame_it = translated_values.end();
int counter = jsframe_index;
for (auto it = translated_values.begin(); it != translated_values.end();
it++) {
if (it->kind() == TranslatedFrame::kInterpretedFunction ||
it->kind() == TranslatedFrame::kJavaScriptBuiltinContinuation ||
it->kind() ==
TranslatedFrame::kJavaScriptBuiltinContinuationWithCatch) {
if (counter == 0) {
frame_it = it;
break;
}
counter--;
}
}
CHECK(frame_it != translated_values.end());
// We only include kJavaScriptBuiltinContinuation frames above to get the
// counting right.
CHECK_EQ(frame_it->kind(), TranslatedFrame::kInterpretedFunction);
DeoptimizedFrameInfo* info =
new DeoptimizedFrameInfo(&translated_values, frame_it, isolate);
return info;
}
namespace {
class ActivationsFinder : public ThreadVisitor {
public:
explicit ActivationsFinder(std::set<Code>* codes, Code topmost_optimized_code,
bool safe_to_deopt_topmost_optimized_code)
: codes_(codes) {
#ifdef DEBUG
topmost_ = topmost_optimized_code;
safe_to_deopt_ = safe_to_deopt_topmost_optimized_code;
#endif
}
// Find the frames with activations of codes marked for deoptimization, search
// for the trampoline to the deoptimizer call respective to each code, and use
// it to replace the current pc on the stack.
void VisitThread(Isolate* isolate, ThreadLocalTop* top) override {
for (StackFrameIterator it(isolate, top); !it.done(); it.Advance()) {
if (it.frame()->type() == StackFrame::OPTIMIZED) {
Code code = it.frame()->LookupCode();
if (code.kind() == Code::OPTIMIZED_FUNCTION &&
code.marked_for_deoptimization()) {
codes_->erase(code);
// Obtain the trampoline to the deoptimizer call.
SafepointEntry safepoint = code.GetSafepointEntry(it.frame()->pc());
int trampoline_pc = safepoint.trampoline_pc();
DCHECK_IMPLIES(code == topmost_, safe_to_deopt_);
// Replace the current pc on the stack with the trampoline.
it.frame()->set_pc(code.raw_instruction_start() + trampoline_pc);
}
}
}
}
private:
std::set<Code>* codes_;
#ifdef DEBUG
Code topmost_;
bool safe_to_deopt_;
#endif
};
} // namespace
// Move marked code from the optimized code list to the deoptimized code list,
// and replace pc on the stack for codes marked for deoptimization.
void Deoptimizer::DeoptimizeMarkedCodeForContext(NativeContext native_context) {
DisallowHeapAllocation no_allocation;
Isolate* isolate = native_context.GetIsolate();
Code topmost_optimized_code;
bool safe_to_deopt_topmost_optimized_code = false;
#ifdef DEBUG
// Make sure all activations of optimized code can deopt at their current PC.
// The topmost optimized code has special handling because it cannot be
// deoptimized due to weak object dependency.
for (StackFrameIterator it(isolate, isolate->thread_local_top()); !it.done();
it.Advance()) {
StackFrame::Type type = it.frame()->type();
if (type == StackFrame::OPTIMIZED) {
Code code = it.frame()->LookupCode();
JSFunction function =
static_cast<OptimizedFrame*>(it.frame())->function();
if (FLAG_trace_deopt) {
CodeTracer::Scope scope(isolate->GetCodeTracer());
PrintF(scope.file(), "[deoptimizer found activation of function: ");
function.PrintName(scope.file());
PrintF(scope.file(), " / %" V8PRIxPTR "]\n", function.ptr());
}
SafepointEntry safepoint = code.GetSafepointEntry(it.frame()->pc());
// Turbofan deopt is checked when we are patching addresses on stack.
bool safe_if_deopt_triggered = safepoint.has_deoptimization_index();
bool is_builtin_code = code.kind() == Code::BUILTIN;
DCHECK(topmost_optimized_code.is_null() || safe_if_deopt_triggered ||
is_builtin_code);
if (topmost_optimized_code.is_null()) {
topmost_optimized_code = code;
safe_to_deopt_topmost_optimized_code = safe_if_deopt_triggered;
}
}
}
#endif
// We will use this set to mark those Code objects that are marked for
// deoptimization and have not been found in stack frames.
std::set<Code> codes;
// Move marked code from the optimized code list to the deoptimized code list.
// Walk over all optimized code objects in this native context.
Code prev;
Object element = native_context.OptimizedCodeListHead();
while (!element.IsUndefined(isolate)) {
Code code = Code::cast(element);
CHECK_EQ(code.kind(), Code::OPTIMIZED_FUNCTION);
Object next = code.next_code_link();
if (code.marked_for_deoptimization()) {
codes.insert(code);
if (!prev.is_null()) {
// Skip this code in the optimized code list.
prev.set_next_code_link(next);
} else {
// There was no previous node, the next node is the new head.
native_context.SetOptimizedCodeListHead(next);
}
// Move the code to the _deoptimized_ code list.
code.set_next_code_link(native_context.DeoptimizedCodeListHead());
native_context.SetDeoptimizedCodeListHead(code);
} else {
// Not marked; preserve this element.
prev = code;
}
element = next;
}
ActivationsFinder visitor(&codes, topmost_optimized_code,
safe_to_deopt_topmost_optimized_code);
// Iterate over the stack of this thread.
visitor.VisitThread(isolate, isolate->thread_local_top());
// In addition to iterate over the stack of this thread, we also
// need to consider all the other threads as they may also use
// the code currently beings deoptimized.
isolate->thread_manager()->IterateArchivedThreads(&visitor);
// If there's no activation of a code in any stack then we can remove its
// deoptimization data. We do this to ensure that code objects that are
// unlinked don't transitively keep objects alive unnecessarily.
for (Code code : codes) {
isolate->heap()->InvalidateCodeDeoptimizationData(code);
}
native_context.GetOSROptimizedCodeCache().EvictMarkedCode(
native_context.GetIsolate());
}
void Deoptimizer::DeoptimizeAll(Isolate* isolate) {
RuntimeCallTimerScope runtimeTimer(isolate,
RuntimeCallCounterId::kDeoptimizeCode);
TimerEventScope<TimerEventDeoptimizeCode> timer(isolate);
TRACE_EVENT0("v8", "V8.DeoptimizeCode");
if (FLAG_trace_deopt) {
CodeTracer::Scope scope(isolate->GetCodeTracer());
PrintF(scope.file(), "[deoptimize all code in all contexts]\n");
}
isolate->AbortConcurrentOptimization(BlockingBehavior::kBlock);
DisallowHeapAllocation no_allocation;
// For all contexts, mark all code, then deoptimize.
Object context = isolate->heap()->native_contexts_list();
while (!context.IsUndefined(isolate)) {
NativeContext native_context = NativeContext::cast(context);
MarkAllCodeForContext(native_context);
OSROptimizedCodeCache::Clear(native_context);
DeoptimizeMarkedCodeForContext(native_context);
context = native_context.next_context_link();
}
}
void Deoptimizer::DeoptimizeMarkedCode(Isolate* isolate) {
RuntimeCallTimerScope runtimeTimer(isolate,
RuntimeCallCounterId::kDeoptimizeCode);
TimerEventScope<TimerEventDeoptimizeCode> timer(isolate);
TRACE_EVENT0("v8", "V8.DeoptimizeCode");
if (FLAG_trace_deopt) {
CodeTracer::Scope scope(isolate->GetCodeTracer());
PrintF(scope.file(), "[deoptimize marked code in all contexts]\n");
}
DisallowHeapAllocation no_allocation;
// For all contexts, deoptimize code already marked.
Object context = isolate->heap()->native_contexts_list();
while (!context.IsUndefined(isolate)) {
NativeContext native_context = NativeContext::cast(context);
DeoptimizeMarkedCodeForContext(native_context);
context = native_context.next_context_link();
}
}
void Deoptimizer::MarkAllCodeForContext(NativeContext native_context) {
Object element = native_context.OptimizedCodeListHead();
Isolate* isolate = native_context.GetIsolate();
while (!element.IsUndefined(isolate)) {
Code code = Code::cast(element);
CHECK_EQ(code.kind(), Code::OPTIMIZED_FUNCTION);
code.set_marked_for_deoptimization(true);
element = code.next_code_link();
}
}
void Deoptimizer::DeoptimizeFunction(JSFunction function, Code code) {
Isolate* isolate = function.GetIsolate();
RuntimeCallTimerScope runtimeTimer(isolate,
RuntimeCallCounterId::kDeoptimizeCode);
TimerEventScope<TimerEventDeoptimizeCode> timer(isolate);
TRACE_EVENT0("v8", "V8.DeoptimizeCode");
function.ResetIfBytecodeFlushed();
if (code.is_null()) code = function.code();
if (code.kind() == Code::OPTIMIZED_FUNCTION) {
// Mark the code for deoptimization and unlink any functions that also
// refer to that code. The code cannot be shared across native contexts,
// so we only need to search one.
code.set_marked_for_deoptimization(true);
// The code in the function's optimized code feedback vector slot might
// be different from the code on the function - evict it if necessary.
function.feedback_vector().EvictOptimizedCodeMarkedForDeoptimization(
function.shared(), "unlinking code marked for deopt");
if (!code.deopt_already_counted()) {
code.set_deopt_already_counted(true);
}
DeoptimizeMarkedCodeForContext(function.context().native_context());
// TODO(mythria): Ideally EvictMarkCode should compact the cache without
// having to explicitly call this. We don't do this currently because
// compacting causes GC and DeoptimizeMarkedCodeForContext uses raw
// pointers. Update DeoptimizeMarkedCodeForContext to use handles and remove
// this call from here.
OSROptimizedCodeCache::Compact(
Handle<NativeContext>(function.context().native_context(), isolate));
}
}
void Deoptimizer::ComputeOutputFrames(Deoptimizer* deoptimizer) {
deoptimizer->DoComputeOutputFrames();
}
const char* Deoptimizer::MessageFor(DeoptimizeKind kind) {
switch (kind) {
case DeoptimizeKind::kEager:
return "eager";
case DeoptimizeKind::kSoft:
return "soft";
case DeoptimizeKind::kLazy:
return "lazy";
}
FATAL("Unsupported deopt kind");
return nullptr;
}
namespace {
uint16_t InternalFormalParameterCountWithReceiver(SharedFunctionInfo sfi) {
static constexpr int kTheReceiver = 1;
return sfi.internal_formal_parameter_count() + kTheReceiver;
}
} // namespace
Deoptimizer::Deoptimizer(Isolate* isolate, JSFunction function,
DeoptimizeKind kind, unsigned bailout_id, Address from,
int fp_to_sp_delta)
: isolate_(isolate),
function_(function),
bailout_id_(bailout_id),
deopt_kind_(kind),
from_(from),
fp_to_sp_delta_(fp_to_sp_delta),
deoptimizing_throw_(false),
catch_handler_data_(-1),
catch_handler_pc_offset_(-1),
input_(nullptr),
output_count_(0),
jsframe_count_(0),
output_(nullptr),
caller_frame_top_(0),
caller_fp_(0),
caller_pc_(0),
caller_constant_pool_(0),
input_frame_context_(0),
stack_fp_(0),
trace_scope_(nullptr) {
if (isolate->deoptimizer_lazy_throw()) {
isolate->set_deoptimizer_lazy_throw(false);
deoptimizing_throw_ = true;
}
DCHECK_NE(from, kNullAddress);
compiled_code_ = FindOptimizedCode();
DCHECK(!compiled_code_.is_null());
DCHECK(function.IsJSFunction());
trace_scope_ = FLAG_trace_deopt
? new CodeTracer::Scope(isolate->GetCodeTracer())
: nullptr;
#ifdef DEBUG
DCHECK(AllowHeapAllocation::IsAllowed());
disallow_heap_allocation_ = new DisallowHeapAllocation();
#endif // DEBUG
if ((compiled_code_.kind() != Code::OPTIMIZED_FUNCTION ||
!compiled_code_.deopt_already_counted()) &&
deopt_kind_ == DeoptimizeKind::kSoft) {
isolate->counters()->soft_deopts_executed()->Increment();
}
if (compiled_code_.kind() == Code::OPTIMIZED_FUNCTION) {
compiled_code_.set_deopt_already_counted(true);
PROFILE(isolate_,
CodeDeoptEvent(compiled_code_, kind, from_, fp_to_sp_delta_));
}
unsigned size = ComputeInputFrameSize();
const int parameter_count =
InternalFormalParameterCountWithReceiver(function.shared());
input_ = new (size) FrameDescription(size, parameter_count);
if (kSupportsFixedDeoptExitSize) {
DCHECK_EQ(bailout_id_, kMaxUInt32);
// Calculate bailout id from return address.
DCHECK_GT(kDeoptExitSize, 0);
DeoptimizationData deopt_data =
DeoptimizationData::cast(compiled_code_.deoptimization_data());
Address deopt_start = compiled_code_.raw_instruction_start() +
deopt_data.DeoptExitStart().value();
int offset = static_cast<int>(from_ - kDeoptExitSize - deopt_start);
DCHECK_EQ(0, offset % kDeoptExitSize);
bailout_id_ = offset / kDeoptExitSize;
}
}
Code Deoptimizer::FindOptimizedCode() {
Code compiled_code = FindDeoptimizingCode(from_);
return !compiled_code.is_null() ? compiled_code
: isolate_->FindCodeObject(from_);
}
void Deoptimizer::PrintFunctionName() {
if (function_.IsHeapObject() && function_.IsJSFunction()) {
function_.ShortPrint(trace_scope_->file());
} else {
PrintF(trace_scope_->file(), "%s",
Code::Kind2String(compiled_code_.kind()));
}
}
Handle<JSFunction> Deoptimizer::function() const {
return Handle<JSFunction>(function_, isolate());
}
Handle<Code> Deoptimizer::compiled_code() const {
return Handle<Code>(compiled_code_, isolate());
}
Deoptimizer::~Deoptimizer() {
DCHECK(input_ == nullptr && output_ == nullptr);
DCHECK_NULL(disallow_heap_allocation_);
delete trace_scope_;
}
void Deoptimizer::DeleteFrameDescriptions() {
delete input_;
for (int i = 0; i < output_count_; ++i) {
if (output_[i] != input_) delete output_[i];
}
delete[] output_;
input_ = nullptr;
output_ = nullptr;
#ifdef DEBUG
DCHECK(!AllowHeapAllocation::IsAllowed());
DCHECK_NOT_NULL(disallow_heap_allocation_);
delete disallow_heap_allocation_;
disallow_heap_allocation_ = nullptr;
#endif // DEBUG
}
Address Deoptimizer::GetDeoptimizationEntry(Isolate* isolate,
DeoptimizeKind kind) {
DeoptimizerData* data = isolate->deoptimizer_data();
CHECK_LE(kind, DeoptimizerData::kLastDeoptimizeKind);
CHECK(!data->deopt_entry_code(kind).is_null());
return data->deopt_entry_code(kind).raw_instruction_start();
}
bool Deoptimizer::IsDeoptimizationEntry(Isolate* isolate, Address addr,
DeoptimizeKind type) {
DeoptimizerData* data = isolate->deoptimizer_data();
CHECK_LE(type, DeoptimizerData::kLastDeoptimizeKind);
Code code = data->deopt_entry_code(type);
if (code.is_null()) return false;
return addr == code.raw_instruction_start();
}
bool Deoptimizer::IsDeoptimizationEntry(Isolate* isolate, Address addr,
DeoptimizeKind* type) {
if (IsDeoptimizationEntry(isolate, addr, DeoptimizeKind::kEager)) {
*type = DeoptimizeKind::kEager;
return true;
}
if (IsDeoptimizationEntry(isolate, addr, DeoptimizeKind::kSoft)) {
*type = DeoptimizeKind::kSoft;
return true;
}
if (IsDeoptimizationEntry(isolate, addr, DeoptimizeKind::kLazy)) {
*type = DeoptimizeKind::kLazy;
return true;
}
return false;
}
int Deoptimizer::GetDeoptimizedCodeCount(Isolate* isolate) {
int length = 0;
// Count all entries in the deoptimizing code list of every context.
Object context = isolate->heap()->native_contexts_list();
while (!context.IsUndefined(isolate)) {
NativeContext native_context = NativeContext::cast(context);
Object element = native_context.DeoptimizedCodeListHead();
while (!element.IsUndefined(isolate)) {
Code code = Code::cast(element);
DCHECK(code.kind() == Code::OPTIMIZED_FUNCTION);
if (!code.marked_for_deoptimization()) {
length++;
}
element = code.next_code_link();
}
context = Context::cast(context).next_context_link();
}
return length;
}
namespace {
int LookupCatchHandler(TranslatedFrame* translated_frame, int* data_out) {
switch (translated_frame->kind()) {
case TranslatedFrame::kInterpretedFunction: {
int bytecode_offset = translated_frame->node_id().ToInt();
HandlerTable table(
translated_frame->raw_shared_info().GetBytecodeArray());
return table.LookupRange(bytecode_offset, data_out, nullptr);
}
case TranslatedFrame::kJavaScriptBuiltinContinuationWithCatch: {
return 0;
}
default:
break;
}
return -1;
}
} // namespace
// We rely on this function not causing a GC. It is called from generated code
// without having a real stack frame in place.
void Deoptimizer::DoComputeOutputFrames() {
// When we call this function, the return address of the previous frame has
// been removed from the stack by GenerateDeoptimizationEntries() so the stack
// is not iterable by the SafeStackFrameIterator.
#if V8_TARGET_ARCH_STORES_RETURN_ADDRESS_ON_STACK
DCHECK_EQ(0, isolate()->isolate_data()->stack_is_iterable());
#endif
base::ElapsedTimer timer;
// Determine basic deoptimization information. The optimized frame is
// described by the input data.
DeoptimizationData input_data =
DeoptimizationData::cast(compiled_code_.deoptimization_data());
{
// Read caller's PC, caller's FP and caller's constant pool values
// from input frame. Compute caller's frame top address.
Register fp_reg = JavaScriptFrame::fp_register();
stack_fp_ = input_->GetRegister(fp_reg.code());
caller_frame_top_ = stack_fp_ + ComputeInputFrameAboveFpFixedSize();
Address fp_address = input_->GetFramePointerAddress();
caller_fp_ = Memory<intptr_t>(fp_address);
caller_pc_ =
Memory<intptr_t>(fp_address + CommonFrameConstants::kCallerPCOffset);
input_frame_context_ = Memory<intptr_t>(
fp_address + CommonFrameConstants::kContextOrFrameTypeOffset);
if (FLAG_enable_embedded_constant_pool) {
caller_constant_pool_ = Memory<intptr_t>(
fp_address + CommonFrameConstants::kConstantPoolOffset);
}
}
if (trace_scope_ != nullptr) {
timer.Start();
PrintF(trace_scope_->file(), "[deoptimizing (DEOPT %s): begin ",
MessageFor(deopt_kind_));
PrintFunctionName();
PrintF(trace_scope_->file(),
" (opt #%d) @%d, FP to SP delta: %d, caller sp: " V8PRIxPTR_FMT
"]\n",
input_data.OptimizationId().value(), bailout_id_, fp_to_sp_delta_,
caller_frame_top_);
if (deopt_kind_ == DeoptimizeKind::kEager ||
deopt_kind_ == DeoptimizeKind::kSoft) {
compiled_code_.PrintDeoptLocation(
trace_scope_->file(), " ;;; deoptimize at ", from_);
}
}
BailoutId node_id = input_data.BytecodeOffset(bailout_id_);
ByteArray translations = input_data.TranslationByteArray();
unsigned translation_index = input_data.TranslationIndex(bailout_id_).value();
TranslationIterator state_iterator(translations, translation_index);
translated_state_.Init(
isolate_, input_->GetFramePointerAddress(), &state_iterator,
input_data.LiteralArray(), input_->GetRegisterValues(),
trace_scope_ == nullptr ? nullptr : trace_scope_->file(),
function_.IsHeapObject()
? function_.shared().internal_formal_parameter_count()
: 0);
// Do the input frame to output frame(s) translation.
size_t count = translated_state_.frames().size();
// If we are supposed to go to the catch handler, find the catching frame
// for the catch and make sure we only deoptimize upto that frame.
if (deoptimizing_throw_) {
size_t catch_handler_frame_index = count;
for (size_t i = count; i-- > 0;) {
catch_handler_pc_offset_ = LookupCatchHandler(
&(translated_state_.frames()[i]), &catch_handler_data_);
if (catch_handler_pc_offset_ >= 0) {
catch_handler_frame_index = i;
break;
}
}
CHECK_LT(catch_handler_frame_index, count);
count = catch_handler_frame_index + 1;
}
DCHECK_NULL(output_);
output_ = new FrameDescription*[count];
for (size_t i = 0; i < count; ++i) {
output_[i] = nullptr;
}
output_count_ = static_cast<int>(count);
// Translate each output frame.
int frame_index = 0; // output_frame_index
for (size_t i = 0; i < count; ++i, ++frame_index) {
// Read the ast node id, function, and frame height for this output frame.
TranslatedFrame* translated_frame = &(translated_state_.frames()[i]);
bool handle_exception = deoptimizing_throw_ && i == count - 1;
switch (translated_frame->kind()) {
case TranslatedFrame::kInterpretedFunction:
DoComputeInterpretedFrame(translated_frame, frame_index,
handle_exception);
jsframe_count_++;
break;
case TranslatedFrame::kArgumentsAdaptor:
DoComputeArgumentsAdaptorFrame(translated_frame, frame_index);
break;
case TranslatedFrame::kConstructStub:
DoComputeConstructStubFrame(translated_frame, frame_index);
break;
case TranslatedFrame::kBuiltinContinuation:
DoComputeBuiltinContinuation(translated_frame, frame_index,
BuiltinContinuationMode::STUB);
break;
case TranslatedFrame::kJavaScriptBuiltinContinuation:
DoComputeBuiltinContinuation(translated_frame, frame_index,
BuiltinContinuationMode::JAVASCRIPT);
break;
case TranslatedFrame::kJavaScriptBuiltinContinuationWithCatch:
DoComputeBuiltinContinuation(
translated_frame, frame_index,
handle_exception
? BuiltinContinuationMode::JAVASCRIPT_HANDLE_EXCEPTION
: BuiltinContinuationMode::JAVASCRIPT_WITH_CATCH);
break;
case TranslatedFrame::kInvalid:
FATAL("invalid frame");
break;
}
}
FrameDescription* topmost = output_[count - 1];
topmost->GetRegisterValues()->SetRegister(kRootRegister.code(),
isolate()->isolate_root());
// Print some helpful diagnostic information.
if (trace_scope_ != nullptr) {
double ms = timer.Elapsed().InMillisecondsF();
int index = output_count_ - 1; // Index of the topmost frame.
PrintF(trace_scope_->file(), "[deoptimizing (%s): end ",
MessageFor(deopt_kind_));
PrintFunctionName();
PrintF(trace_scope_->file(),
" @%d => node=%d, pc=" V8PRIxPTR_FMT ", caller sp=" V8PRIxPTR_FMT
", took %0.3f ms]\n",
bailout_id_, node_id.ToInt(), output_[index]->GetPc(),
caller_frame_top_, ms);
}
}
void Deoptimizer::DoComputeInterpretedFrame(TranslatedFrame* translated_frame,
int frame_index,
bool goto_catch_handler) {
SharedFunctionInfo shared = translated_frame->raw_shared_info();
TranslatedFrame::iterator value_iterator = translated_frame->begin();
const bool is_bottommost = (0 == frame_index);
const bool is_topmost = (output_count_ - 1 == frame_index);
const int real_bytecode_offset = translated_frame->node_id().ToInt();
const int bytecode_offset =
goto_catch_handler ? catch_handler_pc_offset_ : real_bytecode_offset;
const int parameters_count = InternalFormalParameterCountWithReceiver(shared);
const int locals_count = translated_frame->height();
InterpretedFrameInfo frame_info =
InterpretedFrameInfo::Precise(parameters_count, locals_count, is_topmost);
const uint32_t output_frame_size = frame_info.frame_size_in_bytes();
TranslatedFrame::iterator function_iterator = value_iterator++;
if (trace_scope_ != nullptr) {
PrintF(trace_scope_->file(), " translating interpreted frame ");
std::unique_ptr<char[]> name = shared.DebugName().ToCString();
PrintF(trace_scope_->file(), "%s", name.get());
PrintF(trace_scope_->file(),
" => bytecode_offset=%d, variable_frame_size=%d, frame_size=%d%s\n",
real_bytecode_offset, frame_info.frame_size_in_bytes_without_fixed(),
output_frame_size, goto_catch_handler ? " (throw)" : "");
}
// Allocate and store the output frame description.
FrameDescription* output_frame = new (output_frame_size)
FrameDescription(output_frame_size, parameters_count);
FrameWriter frame_writer(this, output_frame, trace_scope_);
CHECK(frame_index >= 0 && frame_index < output_count_);
CHECK_NULL(output_[frame_index]);
output_[frame_index] = output_frame;
// The top address of the frame is computed from the previous frame's top and
// this frame's size.
const intptr_t top_address =
is_bottommost ? caller_frame_top_ - output_frame_size
: output_[frame_index - 1]->GetTop() - output_frame_size;
output_frame->SetTop(top_address);
// Compute the incoming parameter translation.
ReadOnlyRoots roots(isolate());
if (ShouldPadArguments(parameters_count)) {
frame_writer.PushRawObject(roots.the_hole_value(), "padding\n");
}
for (int i = 0; i < parameters_count; ++i, ++value_iterator) {
frame_writer.PushTranslatedValue(value_iterator, "stack parameter");
}
DCHECK_EQ(output_frame->GetLastArgumentSlotOffset(),
frame_writer.top_offset());
if (trace_scope_ != nullptr) {
PrintF(trace_scope_->file(), " -------------------------\n");
}
// There are no translation commands for the caller's pc and fp, the
// context, the function and the bytecode offset. Synthesize
// their values and set them up
// explicitly.
//
// The caller's pc for the bottommost output frame is the same as in the
// input frame. For all subsequent output frames, it can be read from the
// previous one. This frame's pc can be computed from the non-optimized
// function code and AST id of the bailout.
const intptr_t caller_pc =
is_bottommost ? caller_pc_ : output_[frame_index - 1]->GetPc();
frame_writer.PushCallerPc(caller_pc);
// The caller's frame pointer for the bottommost output frame is the same
// as in the input frame. For all subsequent output frames, it can be
// read from the previous one. Also compute and set this frame's frame
// pointer.
const intptr_t caller_fp =
is_bottommost ? caller_fp_ : output_[frame_index - 1]->GetFp();
frame_writer.PushCallerFp(caller_fp);
const intptr_t fp_value = top_address + frame_writer.top_offset();
output_frame->SetFp(fp_value);
if (is_topmost) {
Register fp_reg = InterpretedFrame::fp_register();
output_frame->SetRegister(fp_reg.code(), fp_value);
}
if (FLAG_enable_embedded_constant_pool) {
// For the bottommost output frame the constant pool pointer can be gotten
// from the input frame. For subsequent output frames, it can be read from
// the previous frame.
const intptr_t caller_cp =
is_bottommost ? caller_constant_pool_
: output_[frame_index - 1]->GetConstantPool();
frame_writer.PushCallerConstantPool(caller_cp);
}
// For the bottommost output frame the context can be gotten from the input
// frame. For all subsequent output frames it can be gotten from the function
// so long as we don't inline functions that need local contexts.
// When deoptimizing into a catch block, we need to take the context
// from a register that was specified in the handler table.
TranslatedFrame::iterator context_pos = value_iterator++;
if (goto_catch_handler) {
// Skip to the translated value of the register specified
// in the handler table.
for (int i = 0; i < catch_handler_data_ + 1; ++i) {
context_pos++;
}
}
// Read the context from the translations.
Object context = context_pos->GetRawValue();
output_frame->SetContext(static_cast<intptr_t>(context.ptr()));
frame_writer.PushTranslatedValue(context_pos, "context");
// The function was mentioned explicitly in the BEGIN_FRAME.
frame_writer.PushTranslatedValue(function_iterator, "function");
// Set the bytecode array pointer.
Object bytecode_array = shared.HasBreakInfo()
? shared.GetDebugInfo().DebugBytecodeArray()
: shared.GetBytecodeArray();
frame_writer.PushRawObject(bytecode_array, "bytecode array\n");
// The bytecode offset was mentioned explicitly in the BEGIN_FRAME.
const int raw_bytecode_offset =
BytecodeArray::kHeaderSize - kHeapObjectTag + bytecode_offset;
Smi smi_bytecode_offset = Smi::FromInt(raw_bytecode_offset);
frame_writer.PushRawObject(smi_bytecode_offset, "bytecode offset\n");
if (trace_scope_ != nullptr) {
PrintF(trace_scope_->file(), " -------------------------\n");
}
// Translate the rest of the interpreter registers in the frame.
// The return_value_offset is counted from the top. Here, we compute the
// register index (counted from the start).
const int return_value_first_reg =
locals_count - translated_frame->return_value_offset();
const int return_value_count = translated_frame->return_value_count();
for (int i = 0; i < locals_count; ++i, ++value_iterator) {
// Ensure we write the return value if we have one and we are returning
// normally to a lazy deopt point.
if (is_topmost && !goto_catch_handler &&
deopt_kind_ == DeoptimizeKind::kLazy && i >= return_value_first_reg &&
i < return_value_first_reg + return_value_count) {
const int return_index = i - return_value_first_reg;
if (return_index == 0) {
frame_writer.PushRawValue(input_->GetRegister(kReturnRegister0.code()),
"return value 0\n");
// We do not handle the situation when one return value should go into
// the accumulator and another one into an ordinary register. Since
// the interpreter should never create such situation, just assert
// this does not happen.
CHECK_LE(return_value_first_reg + return_value_count, locals_count);
} else {
CHECK_EQ(return_index, 1);
frame_writer.PushRawValue(input_->GetRegister(kReturnRegister1.code()),
"return value 1\n");
}
} else {
// This is not return value, just write the value from the translations.
frame_writer.PushTranslatedValue(value_iterator, "stack parameter");
}
}
uint32_t register_slots_written = static_cast<uint32_t>(locals_count);
DCHECK_LE(register_slots_written, frame_info.register_stack_slot_count());
// Some architectures must pad the stack frame with extra stack slots
// to ensure the stack frame is aligned. Do this now.
while (register_slots_written < frame_info.register_stack_slot_count()) {
register_slots_written++;
frame_writer.PushRawObject(roots.the_hole_value(), "padding\n");
}
// Translate the accumulator register (depending on frame position).
if (is_topmost) {
if (kPadArguments) {
frame_writer.PushRawObject(roots.the_hole_value(), "padding\n");
}
// For topmost frame, put the accumulator on the stack. The
// {NotifyDeoptimized} builtin pops it off the topmost frame (possibly
// after materialization).
if (goto_catch_handler) {
// If we are lazy deopting to a catch handler, we set the accumulator to
// the exception (which lives in the result register).
intptr_t accumulator_value =
input_->GetRegister(kInterpreterAccumulatorRegister.code());
frame_writer.PushRawObject(Object(accumulator_value), "accumulator\n");
} else {
// If we are lazily deoptimizing make sure we store the deopt
// return value into the appropriate slot.
if (deopt_kind_ == DeoptimizeKind::kLazy &&
translated_frame->return_value_offset() == 0 &&
translated_frame->return_value_count() > 0) {
CHECK_EQ(translated_frame->return_value_count(), 1);
frame_writer.PushRawValue(input_->GetRegister(kReturnRegister0.code()),
"return value 0\n");
} else {
frame_writer.PushTranslatedValue(value_iterator, "accumulator");
}
}
++value_iterator; // Move over the accumulator.
} else {
// For non-topmost frames, skip the accumulator translation. For those
// frames, the return value from the callee will become the accumulator.
++value_iterator;
}
CHECK_EQ(translated_frame->end(), value_iterator);
CHECK_EQ(0u, frame_writer.top_offset());
// Compute this frame's PC and state. The PC will be a special builtin that
// continues the bytecode dispatch. Note that non-topmost and lazy-style
// bailout handlers also advance the bytecode offset before dispatch, hence
// simulating what normal handlers do upon completion of the operation.
Builtins* builtins = isolate_->builtins();
Code dispatch_builtin =
(!is_topmost || (deopt_kind_ == DeoptimizeKind::kLazy)) &&
!goto_catch_handler
? builtins->builtin(Builtins::kInterpreterEnterBytecodeAdvance)
: builtins->builtin(Builtins::kInterpreterEnterBytecodeDispatch);
output_frame->SetPc(
static_cast<intptr_t>(dispatch_builtin.InstructionStart()));
// Update constant pool.
if (FLAG_enable_embedded_constant_pool) {
intptr_t constant_pool_value =
static_cast<intptr_t>(dispatch_builtin.constant_pool());
output_frame->SetConstantPool(constant_pool_value);
if (is_topmost) {
Register constant_pool_reg =
InterpretedFrame::constant_pool_pointer_register();
output_frame->SetRegister(constant_pool_reg.code(), constant_pool_value);
}
}
// Clear the context register. The context might be a de-materialized object
// and will be materialized by {Runtime_NotifyDeoptimized}. For additional
// safety we use Smi(0) instead of the potential {arguments_marker} here.
if (is_topmost) {
intptr_t context_value = static_cast<intptr_t>(Smi::zero().ptr());
Register context_reg = JavaScriptFrame::context_register();
output_frame->SetRegister(context_reg.code(), context_value);
// Set the continuation for the topmost frame.
Code continuation = builtins->builtin(Builtins::kNotifyDeoptimized);
output_frame->SetContinuation(
static_cast<intptr_t>(continuation.InstructionStart()));
}
}
void Deoptimizer::DoComputeArgumentsAdaptorFrame(
TranslatedFrame* translated_frame, int frame_index) {
TranslatedFrame::iterator value_iterator = translated_frame->begin();
const bool is_bottommost = (0 == frame_index);
const int parameters_count = translated_frame->height();
ArgumentsAdaptorFrameInfo frame_info =
ArgumentsAdaptorFrameInfo::Precise(parameters_count);
const uint32_t output_frame_size = frame_info.frame_size_in_bytes();
TranslatedFrame::iterator function_iterator = value_iterator++;
if (trace_scope_ != nullptr) {
PrintF(trace_scope_->file(),
" translating arguments adaptor => variable_frame_size=%d, "
"frame_size=%d\n",
frame_info.frame_size_in_bytes_without_fixed(), output_frame_size);
}
// Allocate and store the output frame description.
FrameDescription* output_frame = new (output_frame_size)
FrameDescription(output_frame_size, parameters_count);
FrameWriter frame_writer(this, output_frame, trace_scope_);
// Arguments adaptor can not be topmost.
CHECK(frame_index < output_count_ - 1);
CHECK_NULL(output_[frame_index]);
output_[frame_index] = output_frame;
// The top address of the frame is computed from the previous frame's top and
// this frame's size.
const intptr_t top_address =
is_bottommost ? caller_frame_top_ - output_frame_size
: output_[frame_index - 1]->GetTop() - output_frame_size;
output_frame->SetTop(top_address);
ReadOnlyRoots roots(isolate());
if (ShouldPadArguments(parameters_count)) {
frame_writer.PushRawObject(roots.the_hole_value(), "padding\n");
}
// Compute the incoming parameter translation.
for (int i = 0; i < parameters_count; ++i, ++value_iterator) {
frame_writer.PushTranslatedValue(value_iterator, "stack parameter");
}
DCHECK_EQ(output_frame->GetLastArgumentSlotOffset(),
frame_writer.top_offset());
// Read caller's PC from the previous frame.
const intptr_t caller_pc =
is_bottommost ? caller_pc_ : output_[frame_index - 1]->GetPc();
frame_writer.PushCallerPc(caller_pc);
// Read caller's FP from the previous frame, and set this frame's FP.
const intptr_t caller_fp =
is_bottommost ? caller_fp_ : output_[frame_index - 1]->GetFp();
frame_writer.PushCallerFp(caller_fp);
intptr_t fp_value = top_address + frame_writer.top_offset();
output_frame->SetFp(fp_value);
if (FLAG_enable_embedded_constant_pool) {
// Read the caller's constant pool from the previous frame.
const intptr_t caller_cp =
is_bottommost ? caller_constant_pool_
: output_[frame_index - 1]->GetConstantPool();
frame_writer.PushCallerConstantPool(caller_cp);
}
// A marker value is used in place of the context.
intptr_t marker = StackFrame::TypeToMarker(StackFrame::ARGUMENTS_ADAPTOR);
frame_writer.PushRawValue(marker, "context (adaptor sentinel)\n");
// The function was mentioned explicitly in the ARGUMENTS_ADAPTOR_FRAME.
frame_writer.PushTranslatedValue(function_iterator, "function\n");
// Number of incoming arguments.
const uint32_t parameters_count_without_receiver = parameters_count - 1;
frame_writer.PushRawObject(Smi::FromInt(parameters_count_without_receiver),
"argc\n");
frame_writer.PushRawObject(roots.the_hole_value(), "padding\n");
CHECK_EQ(translated_frame->end(), value_iterator);
DCHECK_EQ(0, frame_writer.top_offset());
Builtins* builtins = isolate_->builtins();
Code adaptor_trampoline =
builtins->builtin(Builtins::kArgumentsAdaptorTrampoline);
intptr_t pc_value = static_cast<intptr_t>(
adaptor_trampoline.InstructionStart() +
isolate_->heap()->arguments_adaptor_deopt_pc_offset().value());
output_frame->SetPc(pc_value);
if (FLAG_enable_embedded_constant_pool) {
intptr_t constant_pool_value =
static_cast<intptr_t>(adaptor_trampoline.constant_pool());
output_frame->SetConstantPool(constant_pool_value);
}
}
void Deoptimizer::DoComputeConstructStubFrame(TranslatedFrame* translated_frame,
int frame_index) {
TranslatedFrame::iterator value_iterator = translated_frame->begin();
const bool is_topmost = (output_count_ - 1 == frame_index);
// The construct frame could become topmost only if we inlined a constructor
// call which does a tail call (otherwise the tail callee's frame would be
// the topmost one). So it could only be the DeoptimizeKind::kLazy case.
CHECK(!is_topmost || deopt_kind_ == DeoptimizeKind::kLazy);
Builtins* builtins = isolate_->builtins();
Code construct_stub = builtins->builtin(Builtins::kJSConstructStubGeneric);
BailoutId bailout_id = translated_frame->node_id();
const int parameters_count = translated_frame->height();
ConstructStubFrameInfo frame_info =
ConstructStubFrameInfo::Precise(parameters_count, is_topmost);
const uint32_t output_frame_size = frame_info.frame_size_in_bytes();
TranslatedFrame::iterator function_iterator = value_iterator++;
if (trace_scope_ != nullptr) {
PrintF(trace_scope_->file(),
" translating construct stub => bailout_id=%d (%s), "
"variable_frame_size=%d, frame_size=%d\n",
bailout_id.ToInt(),
bailout_id == BailoutId::ConstructStubCreate() ? "create" : "invoke",
frame_info.frame_size_in_bytes_without_fixed(), output_frame_size);
}
// Allocate and store the output frame description.
FrameDescription* output_frame = new (output_frame_size)
FrameDescription(output_frame_size, parameters_count);
FrameWriter frame_writer(this, output_frame, trace_scope_);
// Construct stub can not be topmost.
DCHECK(frame_index > 0 && frame_index < output_count_);
DCHECK_NULL(output_[frame_index]);
output_[frame_index] = output_frame;
// The top address of the frame is computed from the previous frame's top and
// this frame's size.
const intptr_t top_address =
output_[frame_index - 1]->GetTop() - output_frame_size;
output_frame->SetTop(top_address);
ReadOnlyRoots roots(isolate());
if (ShouldPadArguments(parameters_count)) {
frame_writer.PushRawObject(roots.the_hole_value(), "padding\n");
}
// The allocated receiver of a construct stub frame is passed as the
// receiver parameter through the translation. It might be encoding
// a captured object, so we need save it for later.
TranslatedFrame::iterator receiver_iterator = value_iterator;
// Compute the incoming parameter translation.
for (int i = 0; i < parameters_count; ++i, ++value_iterator) {
frame_writer.PushTranslatedValue(value_iterator, "stack parameter");
}
DCHECK_EQ(output_frame->GetLastArgumentSlotOffset(),
frame_writer.top_offset());
// Read caller's PC from the previous frame.
const intptr_t caller_pc = output_[frame_index - 1]->GetPc();
frame_writer.PushCallerPc(caller_pc);
// Read caller's FP from the previous frame, and set this frame's FP.
const intptr_t caller_fp = output_[frame_index - 1]->GetFp();
frame_writer.PushCallerFp(caller_fp);
const intptr_t fp_value = top_address + frame_writer.top_offset();
output_frame->SetFp(fp_value);
if (is_topmost) {
Register fp_reg = JavaScriptFrame::fp_register();
output_frame->SetRegister(fp_reg.code(), fp_value);
}
if (FLAG_enable_embedded_constant_pool) {
// Read the caller's constant pool from the previous frame.
const intptr_t caller_cp = output_[frame_index - 1]->GetConstantPool();
frame_writer.PushCallerConstantPool(caller_cp);
}
// A marker value is used to mark the frame.
intptr_t marker = StackFrame::TypeToMarker(StackFrame::CONSTRUCT);
frame_writer.PushRawValue(marker, "context (construct stub sentinel)\n");
frame_writer.PushTranslatedValue(value_iterator++, "context");
// Number of incoming arguments.
const uint32_t parameters_count_without_receiver = parameters_count - 1;
frame_writer.PushRawObject(Smi::FromInt(parameters_count_without_receiver),
"argc\n");
// The constructor function was mentioned explicitly in the
// CONSTRUCT_STUB_FRAME.
frame_writer.PushTranslatedValue(function_iterator, "constructor function\n");
// The deopt info contains the implicit receiver or the new target at the
// position of the receiver. Copy it to the top of stack, with the hole value
// as padding to maintain alignment.
frame_writer.PushRawObject(roots.the_hole_value(), "padding\n");
CHECK(bailout_id == BailoutId::ConstructStubCreate() ||
bailout_id == BailoutId::ConstructStubInvoke());
const char* debug_hint = bailout_id == BailoutId::ConstructStubCreate()
? "new target\n"
: "allocated receiver\n";
frame_writer.PushTranslatedValue(receiver_iterator, debug_hint);
if (is_topmost) {
if (kPadArguments) {
frame_writer.PushRawObject(roots.the_hole_value(), "padding\n");
}
// Ensure the result is restored back when we return to the stub.
Register result_reg = kReturnRegister0;
intptr_t result = input_->GetRegister(result_reg.code());
frame_writer.PushRawValue(result, "subcall result\n");
}
CHECK_EQ(translated_frame->end(), value_iterator);
CHECK_EQ(0u, frame_writer.top_offset());
// Compute this frame's PC.
DCHECK(bailout_id.IsValidForConstructStub());
Address start = construct_stub.InstructionStart();
const int pc_offset =
bailout_id == BailoutId::ConstructStubCreate()
? isolate_->heap()->construct_stub_create_deopt_pc_offset().value()
: isolate_->heap()->construct_stub_invoke_deopt_pc_offset().value();
intptr_t pc_value = static_cast<intptr_t>(start + pc_offset);
output_frame->SetPc(pc_value);
// Update constant pool.
if (FLAG_enable_embedded_constant_pool) {
intptr_t constant_pool_value =
static_cast<intptr_t>(construct_stub.constant_pool());
output_frame->SetConstantPool(constant_pool_value);
if (is_topmost) {
Register constant_pool_reg =
JavaScriptFrame::constant_pool_pointer_register();
output_frame->SetRegister(constant_pool_reg.code(), constant_pool_value);
}
}
// Clear the context register. The context might be a de-materialized object
// and will be materialized by {Runtime_NotifyDeoptimized}. For additional
// safety we use Smi(0) instead of the potential {arguments_marker} here.
if (is_topmost) {
intptr_t context_value = static_cast<intptr_t>(Smi::zero().ptr());
Register context_reg = JavaScriptFrame::context_register();
output_frame->SetRegister(context_reg.code(), context_value);
}
// Set the continuation for the topmost frame.
if (is_topmost) {
Builtins* builtins = isolate_->builtins();
DCHECK_EQ(DeoptimizeKind::kLazy, deopt_kind_);
Code continuation = builtins->builtin(Builtins::kNotifyDeoptimized);
output_frame->SetContinuation(
static_cast<intptr_t>(continuation.InstructionStart()));
}
}
namespace {
bool BuiltinContinuationModeIsJavaScript(BuiltinContinuationMode mode) {
switch (mode) {
case BuiltinContinuationMode::STUB:
return false;
case BuiltinContinuationMode::JAVASCRIPT:
case BuiltinContinuationMode::JAVASCRIPT_WITH_CATCH:
case BuiltinContinuationMode::JAVASCRIPT_HANDLE_EXCEPTION:
return true;
}
UNREACHABLE();
}
StackFrame::Type BuiltinContinuationModeToFrameType(
BuiltinContinuationMode mode) {
switch (mode) {
case BuiltinContinuationMode::STUB:
return StackFrame::BUILTIN_CONTINUATION;
case BuiltinContinuationMode::JAVASCRIPT:
return StackFrame::JAVA_SCRIPT_BUILTIN_CONTINUATION;
case BuiltinContinuationMode::JAVASCRIPT_WITH_CATCH:
return StackFrame::JAVA_SCRIPT_BUILTIN_CONTINUATION_WITH_CATCH;
case BuiltinContinuationMode::JAVASCRIPT_HANDLE_EXCEPTION:
return StackFrame::JAVA_SCRIPT_BUILTIN_CONTINUATION_WITH_CATCH;
}
UNREACHABLE();
}
} // namespace
Builtins::Name Deoptimizer::TrampolineForBuiltinContinuation(
BuiltinContinuationMode mode, bool must_handle_result) {
switch (mode) {
case BuiltinContinuationMode::STUB:
return must_handle_result ? Builtins::kContinueToCodeStubBuiltinWithResult
: Builtins::kContinueToCodeStubBuiltin;
case BuiltinContinuationMode::JAVASCRIPT:
case BuiltinContinuationMode::JAVASCRIPT_WITH_CATCH:
case BuiltinContinuationMode::JAVASCRIPT_HANDLE_EXCEPTION:
return must_handle_result
? Builtins::kContinueToJavaScriptBuiltinWithResult
: Builtins::kContinueToJavaScriptBuiltin;
}
UNREACHABLE();
}
// BuiltinContinuationFrames capture the machine state that is expected as input
// to a builtin, including both input register values and stack parameters. When
// the frame is reactivated (i.e. the frame below it returns), a
// ContinueToBuiltin stub restores the register state from the frame and tail
// calls to the actual target builtin, making it appear that the stub had been
// directly called by the frame above it. The input values to populate the frame
// are taken from the deopt's FrameState.
//
// Frame translation happens in two modes, EAGER and LAZY. In EAGER mode, all of
// the parameters to the Builtin are explicitly specified in the TurboFan
// FrameState node. In LAZY mode, there is always one fewer parameters specified
// in the FrameState than expected by the Builtin. In that case, construction of
// BuiltinContinuationFrame adds the final missing parameter during
// deoptimization, and that parameter is always on the stack and contains the
// value returned from the callee of the call site triggering the LAZY deopt
// (e.g. rax on x64). This requires that continuation Builtins for LAZY deopts
// must have at least one stack parameter.
//
// TO
// | .... |
// +-------------------------+
// | arg padding (arch dept) |<- at most 1*kSystemPointerSize
// +-------------------------+
// | builtin param 0 |<- FrameState input value n becomes
// +-------------------------+
// | ... |
// +-------------------------+
// | builtin param m |<- FrameState input value n+m-1, or in
// +-----needs-alignment-----+ the LAZY case, return LAZY result value
// | ContinueToBuiltin entry |
// +-------------------------+
// | | saved frame (FP) |
// | +=====needs=alignment=====+<- fpreg
// | |constant pool (if ool_cp)|
// v +-------------------------+
// |BUILTIN_CONTINUATION mark|
// +-------------------------+
// | JSFunction (or zero) |<- only if JavaScript builtin
// +-------------------------+
// | frame height above FP |
// +-------------------------+
// | context |<- this non-standard context slot contains
// +-------------------------+ the context, even for non-JS builtins.
// | builtin index |
// +-------------------------+
// | builtin input GPR reg0 |<- populated from deopt FrameState using
// +-------------------------+ the builtin's CallInterfaceDescriptor
// | ... | to map a FrameState's 0..n-1 inputs to
// +-------------------------+ the builtin's n input register params.
// | builtin input GPR regn |
// +-------------------------+
// | reg padding (arch dept) |
// +-----needs--alignment----+
// | res padding (arch dept) |<- only if {is_topmost}; result is pop'd by
// +-------------------------+<- kNotifyDeopt ASM stub and moved to acc
// | result value |<- reg, as ContinueToBuiltin stub expects.
// +-----needs-alignment-----+<- spreg
//
void Deoptimizer::DoComputeBuiltinContinuation(
TranslatedFrame* translated_frame, int frame_index,
BuiltinContinuationMode mode) {
TranslatedFrame::iterator value_iterator = translated_frame->begin();
const BailoutId bailout_id = translated_frame->node_id();
Builtins::Name builtin_name = Builtins::GetBuiltinFromBailoutId(bailout_id);
CallInterfaceDescriptor continuation_descriptor =
Builtins::CallInterfaceDescriptorFor(builtin_name);
const RegisterConfiguration* config = RegisterConfiguration::Default();
const bool is_bottommost = (0 == frame_index);
const bool is_topmost = (output_count_ - 1 == frame_index);
const int parameters_count = translated_frame->height();
BuiltinContinuationFrameInfo frame_info =
BuiltinContinuationFrameInfo::Precise(parameters_count,
continuation_descriptor, config,
is_topmost, deopt_kind_, mode);
const unsigned output_frame_size = frame_info.frame_size_in_bytes();
const unsigned output_frame_size_above_fp =
frame_info.frame_size_in_bytes_above_fp();
// Validate types of parameters. They must all be tagged except for argc for
// JS builtins.
bool has_argc = false;
const int register_parameter_count =
continuation_descriptor.GetRegisterParameterCount();
for (int i = 0; i < register_parameter_count; ++i) {
MachineType type = continuation_descriptor.GetParameterType(i);
int code = continuation_descriptor.GetRegisterParameter(i).code();
// Only tagged and int32 arguments are supported, and int32 only for the
// arguments count on JavaScript builtins.
if (type == MachineType::Int32()) {
CHECK_EQ(code, kJavaScriptCallArgCountRegister.code());
has_argc = true;
} else {
// Any other argument must be a tagged value.
CHECK(IsAnyTagged(type.representation()));
}
}
CHECK_EQ(BuiltinContinuationModeIsJavaScript(mode), has_argc);
if (trace_scope_ != nullptr) {
PrintF(trace_scope_->file(),
" translating BuiltinContinuation to %s,"
" => register_param_count=%d,"
" stack_param_count=%d, frame_size=%d\n",
Builtins::name(builtin_name), register_parameter_count,
frame_info.stack_parameter_count(), output_frame_size);
}
FrameDescription* output_frame = new (output_frame_size)
FrameDescription(output_frame_size, frame_info.stack_parameter_count());
output_[frame_index] = output_frame;
FrameWriter frame_writer(this, output_frame, trace_scope_);
// The top address of the frame is computed from the previous frame's top and
// this frame's size.
const intptr_t top_address =
is_bottommost ? caller_frame_top_ - output_frame_size
: output_[frame_index - 1]->GetTop() - output_frame_size;
output_frame->SetTop(top_address);
// Get the possible JSFunction for the case that this is a
// JavaScriptBuiltinContinuationFrame, which needs the JSFunction pointer
// like a normal JavaScriptFrame.
const intptr_t maybe_function = value_iterator->GetRawValue().ptr();
++value_iterator;
ReadOnlyRoots roots(isolate());
if (ShouldPadArguments(frame_info.stack_parameter_count())) {
frame_writer.PushRawObject(roots.the_hole_value(), "padding\n");
}
for (uint32_t i = 0; i < frame_info.translated_stack_parameter_count();
++i, ++value_iterator) {
frame_writer.PushTranslatedValue(value_iterator, "stack parameter");
}
switch (mode) {
case BuiltinContinuationMode::STUB:
break;
case BuiltinContinuationMode::JAVASCRIPT:
break;
case BuiltinContinuationMode::JAVASCRIPT_WITH_CATCH: {
frame_writer.PushRawObject(roots.the_hole_value(),
"placeholder for exception on lazy deopt\n");
} break;
case BuiltinContinuationMode::JAVASCRIPT_HANDLE_EXCEPTION: {
intptr_t accumulator_value =
input_->GetRegister(kInterpreterAccumulatorRegister.code());
frame_writer.PushRawObject(Object(accumulator_value),
"exception (from accumulator)\n");
} break;
}
if (frame_info.frame_has_result_stack_slot()) {
frame_writer.PushRawObject(roots.the_hole_value(),
"placeholder for return result on lazy deopt\n");
}
DCHECK_EQ(output_frame->GetLastArgumentSlotOffset(),
frame_writer.top_offset());
std::vector<TranslatedFrame::iterator> register_values;
int total_registers = config->num_general_registers();
register_values.resize(total_registers, {value_iterator});
for (int i = 0; i < register_parameter_count; ++i, ++value_iterator) {
int code = continuation_descriptor.GetRegisterParameter(i).code();
register_values[code] = value_iterator;
}
// The context register is always implicit in the CallInterfaceDescriptor but
// its register must be explicitly set when continuing to the builtin. Make
// sure that it's harvested from the translation and copied into the register
// set (it was automatically added at the end of the FrameState by the
// instruction selector).
Object context = value_iterator->GetRawValue();
const intptr_t value = context.ptr();
TranslatedFrame::iterator context_register_value = value_iterator++;
register_values[kContextRegister.code()] = context_register_value;
output_frame->SetContext(value);
output_frame->SetRegister(kContextRegister.code(), value);
// Set caller's PC (JSFunction continuation).
const intptr_t caller_pc =
is_bottommost ? caller_pc_ : output_[frame_index - 1]->GetPc();
frame_writer.PushCallerPc(caller_pc);
// Read caller's FP from the previous frame, and set this frame's FP.
const intptr_t caller_fp =
is_bottommost ? caller_fp_ : output_[frame_index - 1]->GetFp();
frame_writer.PushCallerFp(caller_fp);
const intptr_t fp_value = top_address + frame_writer.top_offset();
output_frame->SetFp(fp_value);
DCHECK_EQ(output_frame_size_above_fp, frame_writer.top_offset());
if (FLAG_enable_embedded_constant_pool) {
// Read the caller's constant pool from the previous frame.
const intptr_t caller_cp =
is_bottommost ? caller_constant_pool_
: output_[frame_index - 1]->GetConstantPool();
frame_writer.PushCallerConstantPool(caller_cp);
}
// A marker value is used in place of the context.
const intptr_t marker =
StackFrame::TypeToMarker(BuiltinContinuationModeToFrameType(mode));
frame_writer.PushRawValue(marker,
"context (builtin continuation sentinel)\n");
if (BuiltinContinuationModeIsJavaScript(mode)) {
frame_writer.PushRawValue(maybe_function, "JSFunction\n");
} else {
frame_writer.PushRawValue(0, "unused\n");
}
// The delta from the SP to the FP; used to reconstruct SP in
// Isolate::UnwindAndFindHandler.
frame_writer.PushRawObject(Smi::FromInt(output_frame_size_above_fp),
"frame height at deoptimization\n");
// The context even if this is a stub contininuation frame. We can't use the
// usual context slot, because we must store the frame marker there.
frame_writer.PushTranslatedValue(context_register_value,
"builtin JavaScript context\n");
// The builtin to continue to.
frame_writer.PushRawObject(Smi::FromInt(builtin_name), "builtin index\n");
const int allocatable_register_count =
config->num_allocatable_general_registers();
for (int i = 0; i < allocatable_register_count; ++i) {
int code = config->GetAllocatableGeneralCode(i);
ScopedVector<char> str(128);
if (trace_scope_ != nullptr) {
if (BuiltinContinuationModeIsJavaScript(mode) &&
code == kJavaScriptCallArgCountRegister.code()) {
SNPrintF(
str,
"tagged argument count %s (will be untagged by continuation)\n",
RegisterName(Register::from_code(code)));
} else {
SNPrintF(str, "builtin register argument %s\n",
RegisterName(Register::from_code(code)));
}
}
frame_writer.PushTranslatedValue(
register_values[code], trace_scope_ != nullptr ? str.begin() : "");
}
// Some architectures must pad the stack frame with extra stack slots
// to ensure the stack frame is aligned.
const int padding_slot_count =
BuiltinContinuationFrameConstants::PaddingSlotCount(
allocatable_register_count);
for (int i = 0; i < padding_slot_count; ++i) {
frame_writer.PushRawObject(roots.the_hole_value(), "padding\n");
}
if (is_topmost) {
if (kPadArguments) {
frame_writer.PushRawObject(roots.the_hole_value(), "padding\n");
}
// Ensure the result is restored back when we return to the stub.
if (frame_info.frame_has_result_stack_slot()) {
Register result_reg = kReturnRegister0;
frame_writer.PushRawValue(input_->GetRegister(result_reg.code()),
"callback result\n");
} else {
frame_writer.PushRawObject(roots.undefined_value(), "callback result\n");
}
}
CHECK_EQ(translated_frame->end(), value_iterator);
CHECK_EQ(0u, frame_writer.top_offset());
// Clear the context register. The context might be a de-materialized object
// and will be materialized by {Runtime_NotifyDeoptimized}. For additional
// safety we use Smi(0) instead of the potential {arguments_marker} here.
if (is_topmost) {
intptr_t context_value = static_cast<intptr_t>(Smi::zero().ptr());
Register context_reg = JavaScriptFrame::context_register();
output_frame->SetRegister(context_reg.code(), context_value);
}
// Ensure the frame pointer register points to the callee's frame. The builtin
// will build its own frame once we continue to it.
Register fp_reg = JavaScriptFrame::fp_register();
output_frame->SetRegister(fp_reg.code(), fp_value);
Code continue_to_builtin =
isolate()->builtins()->builtin(TrampolineForBuiltinContinuation(
mode, frame_info.frame_has_result_stack_slot()));
output_frame->SetPc(
static_cast<intptr_t>(continue_to_builtin.InstructionStart()));
Code continuation =
isolate()->builtins()->builtin(Builtins::kNotifyDeoptimized);
output_frame->SetContinuation(
static_cast<intptr_t>(continuation.InstructionStart()));
}
void Deoptimizer::MaterializeHeapObjects() {
translated_state_.Prepare(static_cast<Address>(stack_fp_));
if (FLAG_deopt_every_n_times > 0) {
// Doing a GC here will find problems with the deoptimized frames.
isolate_->heap()->CollectAllGarbage(Heap::kNoGCFlags,
GarbageCollectionReason::kTesting);
}
for (auto& materialization : values_to_materialize_) {
Handle<Object> value = materialization.value_->GetValue();
if (trace_scope_ != nullptr) {
PrintF("Materialization [" V8PRIxPTR_FMT "] <- " V8PRIxPTR_FMT " ; ",
static_cast<intptr_t>(materialization.output_slot_address_),
value->ptr());
value->ShortPrint(trace_scope_->file());
PrintF(trace_scope_->file(), "\n");
}
*(reinterpret_cast<Address*>(materialization.output_slot_address_)) =
value->ptr();
}
translated_state_.VerifyMaterializedObjects();
bool feedback_updated = translated_state_.DoUpdateFeedback();
if (trace_scope_ != nullptr && feedback_updated) {
PrintF(trace_scope_->file(), "Feedback updated");
compiled_code_.PrintDeoptLocation(trace_scope_->file(),
" from deoptimization at ", from_);
}
isolate_->materialized_object_store()->Remove(
static_cast<Address>(stack_fp_));
}
void Deoptimizer::QueueValueForMaterialization(
Address output_address, Object obj,
const TranslatedFrame::iterator& iterator) {
if (obj == ReadOnlyRoots(isolate_).arguments_marker()) {
values_to_materialize_.push_back({output_address, iterator});
}
}
unsigned Deoptimizer::ComputeInputFrameAboveFpFixedSize() const {
unsigned fixed_size = CommonFrameConstants::kFixedFrameSizeAboveFp;
// TODO(jkummerow): If {function_->IsSmi()} can indeed be true, then
// {function_} should not have type {JSFunction}.
if (!function_.IsSmi()) {
fixed_size += ComputeIncomingArgumentSize(function_.shared());
}
return fixed_size;
}
unsigned Deoptimizer::ComputeInputFrameSize() const {
// The fp-to-sp delta already takes the context, constant pool pointer and the
// function into account so we have to avoid double counting them.
unsigned fixed_size_above_fp = ComputeInputFrameAboveFpFixedSize();
unsigned result = fixed_size_above_fp + fp_to_sp_delta_;
if (compiled_code_.kind() == Code::OPTIMIZED_FUNCTION) {
unsigned stack_slots = compiled_code_.stack_slots();
unsigned outgoing_size = 0;
// ComputeOutgoingArgumentSize(compiled_code_, bailout_id_);
CHECK_EQ(fixed_size_above_fp + (stack_slots * kSystemPointerSize) -
CommonFrameConstants::kFixedFrameSizeAboveFp + outgoing_size,
result);
}
return result;
}
// static
unsigned Deoptimizer::ComputeIncomingArgumentSize(SharedFunctionInfo shared) {
int parameter_slots = InternalFormalParameterCountWithReceiver(shared);
if (ShouldPadArguments(parameter_slots)) parameter_slots++;
return parameter_slots * kSystemPointerSize;
}
void Deoptimizer::EnsureCodeForDeoptimizationEntry(Isolate* isolate,
DeoptimizeKind kind) {
CHECK(kind == DeoptimizeKind::kEager || kind == DeoptimizeKind::kSoft ||
kind == DeoptimizeKind::kLazy);
DeoptimizerData* data = isolate->deoptimizer_data();
if (!data->deopt_entry_code(kind).is_null()) return;
MacroAssembler masm(isolate, CodeObjectRequired::kYes,
NewAssemblerBuffer(16 * KB));
masm.set_emit_debug_code(false);
GenerateDeoptimizationEntries(&masm, masm.isolate(), kind);
CodeDesc desc;
masm.GetCode(isolate, &desc);
DCHECK(!RelocInfo::RequiresRelocationAfterCodegen(desc));
// Allocate the code as immovable since the entry addresses will be used
// directly and there is no support for relocating them.
Handle<Code> code =
Factory::CodeBuilder(isolate, desc, Code::STUB).set_immovable().Build();
CHECK(isolate->heap()->IsImmovable(*code));
CHECK(data->deopt_entry_code(kind).is_null());
data->set_deopt_entry_code(kind, *code);
}
void Deoptimizer::EnsureCodeForDeoptimizationEntries(Isolate* isolate) {
EnsureCodeForDeoptimizationEntry(isolate, DeoptimizeKind::kEager);
EnsureCodeForDeoptimizationEntry(isolate, DeoptimizeKind::kLazy);
EnsureCodeForDeoptimizationEntry(isolate, DeoptimizeKind::kSoft);
}
FrameDescription::FrameDescription(uint32_t frame_size, int parameter_count)
: frame_size_(frame_size),
parameter_count_(parameter_count),
top_(kZapUint32),
pc_(kZapUint32),
fp_(kZapUint32),
context_(kZapUint32),
constant_pool_(kZapUint32) {
// Zap all the registers.
for (int r = 0; r < Register::kNumRegisters; r++) {
// TODO(jbramley): It isn't safe to use kZapUint32 here. If the register
// isn't used before the next safepoint, the GC will try to scan it as a
// tagged value. kZapUint32 looks like a valid tagged pointer, but it isn't.
#if defined(V8_OS_WIN) && defined(V8_TARGET_ARCH_ARM64)
// x18 is reserved as platform register on Windows arm64 platform
const int kPlatformRegister = 18;
if (r != kPlatformRegister) {
SetRegister(r, kZapUint32);
}
#else
SetRegister(r, kZapUint32);
#endif
}
// Zap all the slots.
for (unsigned o = 0; o < frame_size; o += kSystemPointerSize) {
SetFrameSlot(o, kZapUint32);
}
}
void TranslationBuffer::Add(int32_t value) {
// This wouldn't handle kMinInt correctly if it ever encountered it.
DCHECK_NE(value, kMinInt);
// Encode the sign bit in the least significant bit.
bool is_negative = (value < 0);
uint32_t bits = (static_cast<uint32_t>(is_negative ? -value : value) << 1) |
static_cast<uint32_t>(is_negative);
// Encode the individual bytes using the least significant bit of
// each byte to indicate whether or not more bytes follow.
do {
uint32_t next = bits >> 7;
contents_.push_back(((bits << 1) & 0xFF) | (next != 0));
bits = next;
} while (bits != 0);
}
TranslationIterator::TranslationIterator(ByteArray buffer, int index)
: buffer_(buffer), index_(index) {
DCHECK(index >= 0 && index < buffer.length());
}
int32_t TranslationIterator::Next() {
// Run through the bytes until we reach one with a least significant
// bit of zero (marks the end).
uint32_t bits = 0;
for (int i = 0; true; i += 7) {
DCHECK(HasNext());
uint8_t next = buffer_.get(index_++);
bits |= (next >> 1) << i;
if ((next & 1) == 0) break;
}
// The bits encode the sign in the least significant bit.
bool is_negative = (bits & 1) == 1;
int32_t result = bits >> 1;
return is_negative ? -result : result;
}
bool TranslationIterator::HasNext() const { return index_ < buffer_.length(); }
Handle<ByteArray> TranslationBuffer::CreateByteArray(Factory* factory) {
Handle<ByteArray> result =
factory->NewByteArray(CurrentIndex(), AllocationType::kOld);
contents_.CopyTo(result->GetDataStartAddress());
return result;
}
void Translation::BeginBuiltinContinuationFrame(BailoutId bailout_id,
int literal_id,
unsigned height) {
buffer_->Add(BUILTIN_CONTINUATION_FRAME);
buffer_->Add(bailout_id.ToInt());
buffer_->Add(literal_id);
buffer_->Add(height);
}
void Translation::BeginJavaScriptBuiltinContinuationFrame(BailoutId bailout_id,
int literal_id,
unsigned height) {
buffer_->Add(JAVA_SCRIPT_BUILTIN_CONTINUATION_FRAME);
buffer_->Add(bailout_id.ToInt());
buffer_->Add(literal_id);
buffer_->Add(height);
}
void Translation::BeginJavaScriptBuiltinContinuationWithCatchFrame(
BailoutId bailout_id, int literal_id, unsigned height) {
buffer_->Add(JAVA_SCRIPT_BUILTIN_CONTINUATION_WITH_CATCH_FRAME);
buffer_->Add(bailout_id.ToInt());
buffer_->Add(literal_id);
buffer_->Add(height);
}
void Translation::BeginConstructStubFrame(BailoutId bailout_id, int literal_id,
unsigned height) {
buffer_->Add(CONSTRUCT_STUB_FRAME);
buffer_->Add(bailout_id.ToInt());
buffer_->Add(literal_id);
buffer_->Add(height);
}
void Translation::BeginArgumentsAdaptorFrame(int literal_id, unsigned height) {
buffer_->Add(ARGUMENTS_ADAPTOR_FRAME);
buffer_->Add(literal_id);
buffer_->Add(height);
}
void Translation::BeginInterpretedFrame(BailoutId bytecode_offset,
int literal_id, unsigned height,
int return_value_offset,
int return_value_count) {
buffer_->Add(INTERPRETED_FRAME);
buffer_->Add(bytecode_offset.ToInt());
buffer_->Add(literal_id);
buffer_->Add(height);
buffer_->Add(return_value_offset);
buffer_->Add(return_value_count);
}
void Translation::ArgumentsElements(CreateArgumentsType type) {
buffer_->Add(ARGUMENTS_ELEMENTS);
buffer_->Add(static_cast<uint8_t>(type));
}
void Translation::ArgumentsLength(CreateArgumentsType type) {
buffer_->Add(ARGUMENTS_LENGTH);
buffer_->Add(static_cast<uint8_t>(type));
}
void Translation::BeginCapturedObject(int length) {
buffer_->Add(CAPTURED_OBJECT);
buffer_->Add(length);
}
void Translation::DuplicateObject(int object_index) {
buffer_->Add(DUPLICATED_OBJECT);
buffer_->Add(object_index);
}
void Translation::StoreRegister(Register reg) {
buffer_->Add(REGISTER);
buffer_->Add(reg.code());
}
void Translation::StoreInt32Register(Register reg) {
buffer_->Add(INT32_REGISTER);
buffer_->Add(reg.code());
}
void Translation::StoreInt64Register(Register reg) {
buffer_->Add(INT64_REGISTER);
buffer_->Add(reg.code());
}
void Translation::StoreUint32Register(Register reg) {
buffer_->Add(UINT32_REGISTER);
buffer_->Add(reg.code());
}
void Translation::StoreBoolRegister(Register reg) {
buffer_->Add(BOOL_REGISTER);
buffer_->Add(reg.code());
}
void Translation::StoreFloatRegister(FloatRegister reg) {
buffer_->Add(FLOAT_REGISTER);
buffer_->Add(reg.code());
}
void Translation::StoreDoubleRegister(DoubleRegister reg) {
buffer_->Add(DOUBLE_REGISTER);
buffer_->Add(reg.code());
}
void Translation::StoreStackSlot(int index) {
buffer_->Add(STACK_SLOT);
buffer_->Add(index);
}
void Translation::StoreInt32StackSlot(int index) {
buffer_->Add(INT32_STACK_SLOT);
buffer_->Add(index);
}
void Translation::StoreInt64StackSlot(int index) {
buffer_->Add(INT64_STACK_SLOT);
buffer_->Add(index);
}
void Translation::StoreUint32StackSlot(int index) {
buffer_->Add(UINT32_STACK_SLOT);
buffer_->Add(index);
}
void Translation::StoreBoolStackSlot(int index) {
buffer_->Add(BOOL_STACK_SLOT);
buffer_->Add(index);
}
void Translation::StoreFloatStackSlot(int index) {
buffer_->Add(FLOAT_STACK_SLOT);
buffer_->Add(index);
}
void Translation::StoreDoubleStackSlot(int index) {
buffer_->Add(DOUBLE_STACK_SLOT);
buffer_->Add(index);
}
void Translation::StoreLiteral(int literal_id) {
buffer_->Add(LITERAL);
buffer_->Add(literal_id);
}
void Translation::AddUpdateFeedback(int vector_literal, int slot) {
buffer_->Add(UPDATE_FEEDBACK);
buffer_->Add(vector_literal);
buffer_->Add(slot);
}
void Translation::StoreJSFrameFunction() {
StoreStackSlot((StandardFrameConstants::kCallerPCOffset -
StandardFrameConstants::kFunctionOffset) /
kSystemPointerSize);
}
int Translation::NumberOfOperandsFor(Opcode opcode) {
switch (opcode) {
case DUPLICATED_OBJECT:
case ARGUMENTS_ELEMENTS:
case ARGUMENTS_LENGTH:
case CAPTURED_OBJECT:
case REGISTER:
case INT32_REGISTER:
case INT64_REGISTER:
case UINT32_REGISTER:
case BOOL_REGISTER:
case FLOAT_REGISTER:
case DOUBLE_REGISTER:
case STACK_SLOT:
case INT32_STACK_SLOT:
case INT64_STACK_SLOT:
case UINT32_STACK_SLOT:
case BOOL_STACK_SLOT:
case FLOAT_STACK_SLOT:
case DOUBLE_STACK_SLOT:
case LITERAL:
return 1;
case ARGUMENTS_ADAPTOR_FRAME:
case UPDATE_FEEDBACK:
return 2;
case BEGIN:
case CONSTRUCT_STUB_FRAME:
case BUILTIN_CONTINUATION_FRAME:
case JAVA_SCRIPT_BUILTIN_CONTINUATION_FRAME:
case JAVA_SCRIPT_BUILTIN_CONTINUATION_WITH_CATCH_FRAME:
return 3;
case INTERPRETED_FRAME:
return 5;
}
FATAL("Unexpected translation type");
return -1;
}
#if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
const char* Translation::StringFor(Opcode opcode) {
#define TRANSLATION_OPCODE_CASE(item) \
case item: \
return #item;
switch (opcode) { TRANSLATION_OPCODE_LIST(TRANSLATION_OPCODE_CASE) }
#undef TRANSLATION_OPCODE_CASE
UNREACHABLE();
}
#endif
Handle<FixedArray> MaterializedObjectStore::Get(Address fp) {
int index = StackIdToIndex(fp);
if (index == -1) {
return Handle<FixedArray>::null();
}
Handle<FixedArray> array = GetStackEntries();
CHECK_GT(array->length(), index);
return Handle<FixedArray>::cast(Handle<Object>(array->get(index), isolate()));
}
void MaterializedObjectStore::Set(Address fp,
Handle<FixedArray> materialized_objects) {
int index = StackIdToIndex(fp);
if (index == -1) {
index = static_cast<int>(frame_fps_.size());
frame_fps_.push_back(fp);
}
Handle<FixedArray> array = EnsureStackEntries(index + 1);
array->set(index, *materialized_objects);
}
bool MaterializedObjectStore::Remove(Address fp) {
auto it = std::find(frame_fps_.begin(), frame_fps_.end(), fp);
if (it == frame_fps_.end()) return false;
int index = static_cast<int>(std::distance(frame_fps_.begin(), it));
frame_fps_.erase(it);
FixedArray array = isolate()->heap()->materialized_objects();
CHECK_LT(index, array.length());
int fps_size = static_cast<int>(frame_fps_.size());
for (int i = index; i < fps_size; i++) {
array.set(i, array.get(i + 1));
}
array.set(fps_size, ReadOnlyRoots(isolate()).undefined_value());
return true;
}
int MaterializedObjectStore::StackIdToIndex(Address fp) {
auto it = std::find(frame_fps_.begin(), frame_fps_.end(), fp);
return it == frame_fps_.end()
? -1
: static_cast<int>(std::distance(frame_fps_.begin(), it));
}
Handle<FixedArray> MaterializedObjectStore::GetStackEntries() {
return Handle<FixedArray>(isolate()->heap()->materialized_objects(),
isolate());
}
Handle<FixedArray> MaterializedObjectStore::EnsureStackEntries(int length) {
Handle<FixedArray> array = GetStackEntries();
if (array->length() >= length) {
return array;
}
int new_length = length > 10 ? length : 10;
if (new_length < 2 * array->length()) {
new_length = 2 * array->length();
}
Handle<FixedArray> new_array =
isolate()->factory()->NewFixedArray(new_length, AllocationType::kOld);
for (int i = 0; i < array->length(); i++) {
new_array->set(i, array->get(i));
}
HeapObject undefined_value = ReadOnlyRoots(isolate()).undefined_value();
for (int i = array->length(); i < length; i++) {
new_array->set(i, undefined_value);
}
isolate()->heap()->SetRootMaterializedObjects(*new_array);
return new_array;
}
namespace {
Handle<Object> GetValueForDebugger(TranslatedFrame::iterator it,
Isolate* isolate) {
if (it->GetRawValue() == ReadOnlyRoots(isolate).arguments_marker()) {
if (!it->IsMaterializableByDebugger()) {
return isolate->factory()->optimized_out();
}
}
return it->GetValue();
}
} // namespace
DeoptimizedFrameInfo::DeoptimizedFrameInfo(TranslatedState* state,
TranslatedState::iterator frame_it,
Isolate* isolate) {
int parameter_count =
frame_it->shared_info()->internal_formal_parameter_count();
TranslatedFrame::iterator stack_it = frame_it->begin();
// Get the function. Note that this might materialize the function.
// In case the debugger mutates this value, we should deoptimize
// the function and remember the value in the materialized value store.
function_ = Handle<JSFunction>::cast(stack_it->GetValue());
stack_it++; // Skip the function.
stack_it++; // Skip the receiver.
DCHECK_EQ(TranslatedFrame::kInterpretedFunction, frame_it->kind());
source_position_ = Deoptimizer::ComputeSourcePositionFromBytecodeArray(
*frame_it->shared_info(), frame_it->node_id());
DCHECK_EQ(parameter_count,
function_->shared().internal_formal_parameter_count());
parameters_.resize(static_cast<size_t>(parameter_count));
for (int i = 0; i < parameter_count; i++) {
Handle<Object> parameter = GetValueForDebugger(stack_it, isolate);
SetParameter(i, parameter);
stack_it++;
}
// Get the context.
context_ = GetValueForDebugger(stack_it, isolate);
stack_it++;
// Get the expression stack.
DCHECK_EQ(TranslatedFrame::kInterpretedFunction, frame_it->kind());
const int stack_height = frame_it->height(); // Accumulator *not* included.
expression_stack_.resize(static_cast<size_t>(stack_height));
for (int i = 0; i < stack_height; i++) {
Handle<Object> expression = GetValueForDebugger(stack_it, isolate);
SetExpression(i, expression);
stack_it++;
}
DCHECK_EQ(TranslatedFrame::kInterpretedFunction, frame_it->kind());
stack_it++; // Skip the accumulator.
CHECK(stack_it == frame_it->end());
}
Deoptimizer::DeoptInfo Deoptimizer::GetDeoptInfo(Code code, Address pc) {
CHECK(code.InstructionStart() <= pc && pc <= code.InstructionEnd());
SourcePosition last_position = SourcePosition::Unknown();
DeoptimizeReason last_reason = DeoptimizeReason::kUnknown;
int last_deopt_id = kNoDeoptimizationId;
int mask = RelocInfo::ModeMask(RelocInfo::DEOPT_REASON) |
RelocInfo::ModeMask(RelocInfo::DEOPT_ID) |
RelocInfo::ModeMask(RelocInfo::DEOPT_SCRIPT_OFFSET) |
RelocInfo::ModeMask(RelocInfo::DEOPT_INLINING_ID);
for (RelocIterator it(code, mask); !it.done(); it.next()) {
RelocInfo* info = it.rinfo();
if (info->pc() >= pc) break;
if (info->rmode() == RelocInfo::DEOPT_SCRIPT_OFFSET) {
int script_offset = static_cast<int>(info->data());
it.next();
DCHECK(it.rinfo()->rmode() == RelocInfo::DEOPT_INLINING_ID);
int inlining_id = static_cast<int>(it.rinfo()->data());
last_position = SourcePosition(script_offset, inlining_id);
} else if (info->rmode() == RelocInfo::DEOPT_ID) {
last_deopt_id = static_cast<int>(info->data());
} else if (info->rmode() == RelocInfo::DEOPT_REASON) {
last_reason = static_cast<DeoptimizeReason>(info->data());
}
}
return DeoptInfo(last_position, last_reason, last_deopt_id);
}
// static
int Deoptimizer::ComputeSourcePositionFromBytecodeArray(
SharedFunctionInfo shared, BailoutId node_id) {
DCHECK(shared.HasBytecodeArray());
return AbstractCode::cast(shared.GetBytecodeArray())
.SourcePosition(node_id.ToInt());
}
// static
TranslatedValue TranslatedValue::NewDeferredObject(TranslatedState* container,
int length,
int object_index) {
TranslatedValue slot(container, kCapturedObject);
slot.materialization_info_ = {object_index, length};
return slot;
}
// static
TranslatedValue TranslatedValue::NewDuplicateObject(TranslatedState* container,
int id) {
TranslatedValue slot(container, kDuplicatedObject);
slot.materialization_info_ = {id, -1};
return slot;
}
// static
TranslatedValue TranslatedValue::NewFloat(TranslatedState* container,
Float32 value) {
TranslatedValue slot(container, kFloat);
slot.float_value_ = value;
return slot;
}
// static
TranslatedValue TranslatedValue::NewDouble(TranslatedState* container,
Float64 value) {
TranslatedValue slot(container, kDouble);
slot.double_value_ = value;
return slot;
}
// static
TranslatedValue TranslatedValue::NewInt32(TranslatedState* container,
int32_t value) {
TranslatedValue slot(container, kInt32);
slot.int32_value_ = value;
return slot;
}
// static
TranslatedValue TranslatedValue::NewInt64(TranslatedState* container,
int64_t value) {
TranslatedValue slot(container, kInt64);
slot.int64_value_ = value;
return slot;
}
// static
TranslatedValue TranslatedValue::NewUInt32(TranslatedState* container,
uint32_t value) {
TranslatedValue slot(container, kUInt32);
slot.uint32_value_ = value;
return slot;
}
// static
TranslatedValue TranslatedValue::NewBool(TranslatedState* container,
uint32_t value) {
TranslatedValue slot(container, kBoolBit);
slot.uint32_value_ = value;
return slot;
}
// static
TranslatedValue TranslatedValue::NewTagged(TranslatedState* container,
Object literal) {
TranslatedValue slot(container, kTagged);
slot.raw_literal_ = literal;
return slot;
}
// static
TranslatedValue TranslatedValue::NewInvalid(TranslatedState* container) {
return TranslatedValue(container, kInvalid);
}
Isolate* TranslatedValue::isolate() const { return container_->isolate(); }
Object TranslatedValue::raw_literal() const {
DCHECK_EQ(kTagged, kind());
return raw_literal_;
}
int32_t TranslatedValue::int32_value() const {
DCHECK_EQ(kInt32, kind());
return int32_value_;
}
int64_t TranslatedValue::int64_value() const {
DCHECK_EQ(kInt64, kind());
return int64_value_;
}
uint32_t TranslatedValue::uint32_value() const {
DCHECK(kind() == kUInt32 || kind() == kBoolBit);
return uint32_value_;
}
Float32 TranslatedValue::float_value() const {
DCHECK_EQ(kFloat, kind());
return float_value_;
}
Float64 TranslatedValue::double_value() const {
DCHECK_EQ(kDouble, kind());
return double_value_;
}
int TranslatedValue::object_length() const {
DCHECK_EQ(kind(), kCapturedObject);
return materialization_info_.length_;
}
int TranslatedValue::object_index() const {
DCHECK(kind() == kCapturedObject || kind() == kDuplicatedObject);
return materialization_info_.id_;
}
Object TranslatedValue::GetRawValue() const {
// If we have a value, return it.
if (materialization_state() == kFinished) {
return *storage_;
}
// Otherwise, do a best effort to get the value without allocation.
switch (kind()) {
case kTagged:
return raw_literal();
case kInt32: {
bool is_smi = Smi::IsValid(int32_value());
if (is_smi) {
return Smi::FromInt(int32_value());
}
break;
}
case kInt64: {
bool is_smi = (int64_value() >= static_cast<int64_t>(Smi::kMinValue) &&
int64_value() <= static_cast<int64_t>(Smi::kMaxValue));
if (is_smi) {
return Smi::FromIntptr(static_cast<intptr_t>(int64_value()));
}
break;
}
case kUInt32: {
bool is_smi = (uint32_value() <= static_cast<uintptr_t>(Smi::kMaxValue));
if (is_smi) {
return Smi::FromInt(static_cast<int32_t>(uint32_value()));
}
break;
}
case kBoolBit: {
if (uint32_value() == 0) {
return ReadOnlyRoots(isolate()).false_value();
} else {
CHECK_EQ(1U, uint32_value());
return ReadOnlyRoots(isolate()).true_value();
}
}
default:
break;
}
// If we could not get the value without allocation, return the arguments
// marker.
return ReadOnlyRoots(isolate()).arguments_marker();
}
void TranslatedValue::set_initialized_storage(Handle<Object> storage) {
DCHECK_EQ(kUninitialized, materialization_state());
storage_ = storage;
materialization_state_ = kFinished;
}
Handle<Object> TranslatedValue::GetValue() {
// If we already have a value, then get it.
if (materialization_state() == kFinished) return storage_;
// Otherwise we have to materialize.
switch (kind()) {
case TranslatedValue::kTagged:
case TranslatedValue::kInt32:
case TranslatedValue::kInt64:
case TranslatedValue::kUInt32:
case TranslatedValue::kBoolBit:
case TranslatedValue::kFloat:
case TranslatedValue::kDouble: {
MaterializeSimple();
return storage_;
}
case TranslatedValue::kCapturedObject:
case TranslatedValue::kDuplicatedObject: {
// We need to materialize the object (or possibly even object graphs).
// To make the object verifier happy, we materialize in two steps.
// 1. Allocate storage for reachable objects. This makes sure that for
// each object we have allocated space on heap. The space will be
// a byte array that will be later initialized, or a fully
// initialized object if it is safe to allocate one that will
// pass the verifier.
container_->EnsureObjectAllocatedAt(this);
// 2. Initialize the objects. If we have allocated only byte arrays
// for some objects, we now overwrite the byte arrays with the
// correct object fields. Note that this phase does not allocate
// any new objects, so it does not trigger the object verifier.
return container_->InitializeObjectAt(this);
}
case TranslatedValue::kInvalid:
FATAL("unexpected case");
return Handle<Object>::null();
}
FATAL("internal error: value missing");
return Handle<Object>::null();
}
void TranslatedValue::MaterializeSimple() {
// If we already have materialized, return.
if (materialization_state() == kFinished) return;
Object raw_value = GetRawValue();
if (raw_value != ReadOnlyRoots(isolate()).arguments_marker()) {
// We can get the value without allocation, just return it here.
set_initialized_storage(Handle<Object>(raw_value, isolate()));
return;
}
switch (kind()) {
case kInt32:
set_initialized_storage(
Handle<Object>(isolate()->factory()->NewNumber(int32_value())));
return;
case kInt64:
set_initialized_storage(Handle<Object>(
isolate()->factory()->NewNumber(static_cast<double>(int64_value()))));
return;
case kUInt32:
set_initialized_storage(
Handle<Object>(isolate()->factory()->NewNumber(uint32_value())));
return;
case kFloat: {
double scalar_value = float_value().get_scalar();
set_initialized_storage(
Handle<Object>(isolate()->factory()->NewNumber(scalar_value)));
return;
}
case kDouble: {
double scalar_value = double_value().get_scalar();
set_initialized_storage(
Handle<Object>(isolate()->factory()->NewNumber(scalar_value)));
return;
}
case kCapturedObject:
case kDuplicatedObject:
case kInvalid:
case kTagged:
case kBoolBit:
FATAL("internal error: unexpected materialization.");
break;
}
}
bool TranslatedValue::IsMaterializedObject() const {
switch (kind()) {
case kCapturedObject:
case kDuplicatedObject:
return true;
default:
return false;
}
}
bool TranslatedValue::IsMaterializableByDebugger() const {
// At the moment, we only allow materialization of doubles.
return (kind() == kDouble);
}
int TranslatedValue::GetChildrenCount() const {
if (kind() == kCapturedObject) {
return object_length();
} else {
return 0;
}
}
uint64_t TranslatedState::GetUInt64Slot(Address fp, int slot_offset) {
#if V8_TARGET_ARCH_32_BIT
return ReadUnalignedValue<uint64_t>(fp + slot_offset);
#else
return Memory<uint64_t>(fp + slot_offset);
#endif
}
uint32_t TranslatedState::GetUInt32Slot(Address fp, int slot_offset) {
Address address = fp + slot_offset;
#if V8_TARGET_BIG_ENDIAN && V8_HOST_ARCH_64_BIT
return Memory<uint32_t>(address + kIntSize);
#else
return Memory<uint32_t>(address);
#endif
}
Float32 TranslatedState::GetFloatSlot(Address fp, int slot_offset) {
#if !V8_TARGET_ARCH_S390X && !V8_TARGET_ARCH_PPC64
return Float32::FromBits(GetUInt32Slot(fp, slot_offset));
#else
return Float32::FromBits(Memory<uint32_t>(fp + slot_offset));
#endif
}
Float64 TranslatedState::GetDoubleSlot(Address fp, int slot_offset) {
return Float64::FromBits(GetUInt64Slot(fp, slot_offset));
}
void TranslatedValue::Handlify() {
if (kind() == kTagged) {
set_initialized_storage(Handle<Object>(raw_literal(), isolate()));
raw_literal_ = Object();
}
}
TranslatedFrame TranslatedFrame::InterpretedFrame(
BailoutId bytecode_offset, SharedFunctionInfo shared_info, int height,
int return_value_offset, int return_value_count) {
TranslatedFrame frame(kInterpretedFunction, shared_info, height,
return_value_offset, return_value_count);
frame.node_id_ = bytecode_offset;
return frame;
}
TranslatedFrame TranslatedFrame::ArgumentsAdaptorFrame(
SharedFunctionInfo shared_info, int height) {
return TranslatedFrame(kArgumentsAdaptor, shared_info, height);
}
TranslatedFrame TranslatedFrame::ConstructStubFrame(
BailoutId bailout_id, SharedFunctionInfo shared_info, int height) {
TranslatedFrame frame(kConstructStub, shared_info, height);
frame.node_id_ = bailout_id;
return frame;
}
TranslatedFrame TranslatedFrame::BuiltinContinuationFrame(
BailoutId bailout_id, SharedFunctionInfo shared_info, int height) {
TranslatedFrame frame(kBuiltinContinuation, shared_info, height);
frame.node_id_ = bailout_id;
return frame;
}
TranslatedFrame TranslatedFrame::JavaScriptBuiltinContinuationFrame(
BailoutId bailout_id, SharedFunctionInfo shared_info, int height) {
TranslatedFrame frame(kJavaScriptBuiltinContinuation, shared_info, height);
frame.node_id_ = bailout_id;
return frame;
}
TranslatedFrame TranslatedFrame::JavaScriptBuiltinContinuationWithCatchFrame(
BailoutId bailout_id, SharedFunctionInfo shared_info, int height) {
TranslatedFrame frame(kJavaScriptBuiltinContinuationWithCatch, shared_info,
height);
frame.node_id_ = bailout_id;
return frame;
}
int TranslatedFrame::GetValueCount() {
// The function is added to all frame state descriptors in
// InstructionSelector::AddInputsToFrameStateDescriptor.
static constexpr int kTheFunction = 1;
switch (kind()) {
case kInterpretedFunction: {
int parameter_count =
InternalFormalParameterCountWithReceiver(raw_shared_info_);
static constexpr int kTheContext = 1;
static constexpr int kTheAccumulator = 1;
return height() + parameter_count + kTheContext + kTheFunction +
kTheAccumulator;
}
case kArgumentsAdaptor:
return height() + kTheFunction;
case kConstructStub:
case kBuiltinContinuation:
case kJavaScriptBuiltinContinuation:
case kJavaScriptBuiltinContinuationWithCatch: {
static constexpr int kTheContext = 1;
return height() + kTheContext + kTheFunction;
}
case kInvalid:
UNREACHABLE();
}
UNREACHABLE();
}
void TranslatedFrame::Handlify() {
if (!raw_shared_info_.is_null()) {
shared_info_ = Handle<SharedFunctionInfo>(raw_shared_info_,
raw_shared_info_.GetIsolate());
raw_shared_info_ = SharedFunctionInfo();
}
for (auto& value : values_) {
value.Handlify();
}
}
TranslatedFrame TranslatedState::CreateNextTranslatedFrame(
TranslationIterator* iterator, FixedArray literal_array, Address fp,
FILE* trace_file) {
Translation::Opcode opcode =
static_cast<Translation::Opcode>(iterator->Next());
switch (opcode) {
case Translation::INTERPRETED_FRAME: {
BailoutId bytecode_offset = BailoutId(iterator->Next());
SharedFunctionInfo shared_info =
SharedFunctionInfo::cast(literal_array.get(iterator->Next()));
int height = iterator->Next();
int return_value_offset = iterator->Next();
int return_value_count = iterator->Next();
if (trace_file != nullptr) {
std::unique_ptr<char[]> name = shared_info.DebugName().ToCString();
PrintF(trace_file, " reading input frame %s", name.get());
int arg_count = InternalFormalParameterCountWithReceiver(shared_info);
PrintF(trace_file,
" => bytecode_offset=%d, args=%d, height=%d, retval=%i(#%i); "
"inputs:\n",
bytecode_offset.ToInt(), arg_count, height, return_value_offset,
return_value_count);
}
return TranslatedFrame::InterpretedFrame(bytecode_offset, shared_info,
height, return_value_offset,
return_value_count);
}
case Translation::ARGUMENTS_ADAPTOR_FRAME: {
SharedFunctionInfo shared_info =
SharedFunctionInfo::cast(literal_array.get(iterator->Next()));
int height = iterator->Next();
if (trace_file != nullptr) {
std::unique_ptr<char[]> name = shared_info.DebugName().ToCString();
PrintF(trace_file, " reading arguments adaptor frame %s", name.get());
PrintF(trace_file, " => height=%d; inputs:\n", height);
}
return TranslatedFrame::ArgumentsAdaptorFrame(shared_info, height);
}
case Translation::CONSTRUCT_STUB_FRAME: {
BailoutId bailout_id = BailoutId(iterator->Next());
SharedFunctionInfo shared_info =
SharedFunctionInfo::cast(literal_array.get(iterator->Next()));
int height = iterator->Next();
if (trace_file != nullptr) {
std::unique_ptr<char[]> name = shared_info.DebugName().ToCString();
PrintF(trace_file, " reading construct stub frame %s", name.get());
PrintF(trace_file, " => bailout_id=%d, height=%d; inputs:\n",
bailout_id.ToInt(), height);
}
return TranslatedFrame::ConstructStubFrame(bailout_id, shared_info,
height);
}
case Translation::BUILTIN_CONTINUATION_FRAME: {
BailoutId bailout_id = BailoutId(iterator->Next());
SharedFunctionInfo shared_info =
SharedFunctionInfo::cast(literal_array.get(iterator->Next()));
int height = iterator->Next();
if (trace_file != nullptr) {
std::unique_ptr<char[]> name = shared_info.DebugName().ToCString();
PrintF(trace_file, " reading builtin continuation frame %s",
name.get());
PrintF(trace_file, " => bailout_id=%d, height=%d; inputs:\n",
bailout_id.ToInt(), height);
}
return TranslatedFrame::BuiltinContinuationFrame(bailout_id, shared_info,
height);
}
case Translation::JAVA_SCRIPT_BUILTIN_CONTINUATION_FRAME: {
BailoutId bailout_id = BailoutId(iterator->Next());
SharedFunctionInfo shared_info =
SharedFunctionInfo::cast(literal_array.get(iterator->Next()));
int height = iterator->Next();
if (trace_file != nullptr) {
std::unique_ptr<char[]> name = shared_info.DebugName().ToCString();
PrintF(trace_file, " reading JavaScript builtin continuation frame %s",
name.get());
PrintF(trace_file, " => bailout_id=%d, height=%d; inputs:\n",
bailout_id.ToInt(), height);
}
return TranslatedFrame::JavaScriptBuiltinContinuationFrame(
bailout_id, shared_info, height);
}
case Translation::JAVA_SCRIPT_BUILTIN_CONTINUATION_WITH_CATCH_FRAME: {
BailoutId bailout_id = BailoutId(iterator->Next());
SharedFunctionInfo shared_info =
SharedFunctionInfo::cast(literal_array.get(iterator->Next()));
int height = iterator->Next();
if (trace_file != nullptr) {
std::unique_ptr<char[]> name = shared_info.DebugName().ToCString();
PrintF(trace_file,
" reading JavaScript builtin continuation frame with catch %s",
name.get());
PrintF(trace_file, " => bailout_id=%d, height=%d; inputs:\n",
bailout_id.ToInt(), height);
}
return TranslatedFrame::JavaScriptBuiltinContinuationWithCatchFrame(
bailout_id, shared_info, height);
}
case Translation::UPDATE_FEEDBACK:
case Translation::BEGIN:
case Translation::DUPLICATED_OBJECT:
case Translation::ARGUMENTS_ELEMENTS:
case Translation::ARGUMENTS_LENGTH:
case Translation::CAPTURED_OBJECT:
case Translation::REGISTER:
case Translation::INT32_REGISTER:
case Translation::INT64_REGISTER:
case Translation::UINT32_REGISTER:
case Translation::BOOL_REGISTER:
case Translation::FLOAT_REGISTER:
case Translation::DOUBLE_REGISTER:
case Translation::STACK_SLOT:
case Translation::INT32_STACK_SLOT:
case Translation::INT64_STACK_SLOT:
case Translation::UINT32_STACK_SLOT:
case Translation::BOOL_STACK_SLOT:
case Translation::FLOAT_STACK_SLOT:
case Translation::DOUBLE_STACK_SLOT:
case Translation::LITERAL:
break;
}
FATAL("We should never get here - unexpected deopt info.");
return TranslatedFrame::InvalidFrame();
}
// static
void TranslatedFrame::AdvanceIterator(
std::deque<TranslatedValue>::iterator* iter) {
int values_to_skip = 1;
while (values_to_skip > 0) {
// Consume the current element.
values_to_skip--;
// Add all the children.
values_to_skip += (*iter)->GetChildrenCount();
(*iter)++;
}
}
Address TranslatedState::ComputeArgumentsPosition(Address input_frame_pointer,
CreateArgumentsType type,
int* length) {
Address parent_frame_pointer = *reinterpret_cast<Address*>(
input_frame_pointer + StandardFrameConstants::kCallerFPOffset);
intptr_t parent_frame_type = Memory<intptr_t>(
parent_frame_pointer + CommonFrameConstants::kContextOrFrameTypeOffset);
Address arguments_frame;
if (parent_frame_type ==
StackFrame::TypeToMarker(StackFrame::ARGUMENTS_ADAPTOR)) {
if (length)
*length = Smi::cast(*FullObjectSlot(
parent_frame_pointer +
ArgumentsAdaptorFrameConstants::kLengthOffset))
.value();
arguments_frame = parent_frame_pointer;
} else {
if (length) *length = formal_parameter_count_;
arguments_frame = input_frame_pointer;
}
if (type == CreateArgumentsType::kRestParameter) {
// If the actual number of arguments is less than the number of formal
// parameters, we have zero rest parameters.
if (length) *length = std::max(0, *length - formal_parameter_count_);
}
return arguments_frame;
}
// Creates translated values for an arguments backing store, or the backing
// store for rest parameters depending on the given {type}. The TranslatedValue
// objects for the fields are not read from the TranslationIterator, but instead
// created on-the-fly based on dynamic information in the optimized frame.
void TranslatedState::CreateArgumentsElementsTranslatedValues(
int frame_index, Address input_frame_pointer, CreateArgumentsType type,
FILE* trace_file) {
TranslatedFrame& frame = frames_[frame_index];
int length;
Address arguments_frame =
ComputeArgumentsPosition(input_frame_pointer, type, &length);
int object_index = static_cast<int>(object_positions_.size());
int value_index = static_cast<int>(frame.values_.size());
if (trace_file != nullptr) {
PrintF(trace_file, "arguments elements object #%d (type = %d, length = %d)",
object_index, static_cast<uint8_t>(type), length);
}
object_positions_.push_back({frame_index, value_index});
frame.Add(TranslatedValue::NewDeferredObject(
this, length + FixedArray::kHeaderSize / kTaggedSize, object_index));
ReadOnlyRoots roots(isolate_);
frame.Add(TranslatedValue::NewTagged(this, roots.fixed_array_map()));
frame.Add(TranslatedValue::NewInt32(this, length));
int number_of_holes = 0;
if (type == CreateArgumentsType::kMappedArguments) {
// If the actual number of arguments is less than the number of formal
// parameters, we have fewer holes to fill to not overshoot the length.
number_of_holes = Min(formal_parameter_count_, length);
}
for (int i = 0; i < number_of_holes; ++i) {
frame.Add(TranslatedValue::NewTagged(this, roots.the_hole_value()));
}
for (int i = length - number_of_holes - 1; i >= 0; --i) {
Address argument_slot = arguments_frame +
CommonFrameConstants::kFixedFrameSizeAboveFp +
i * kSystemPointerSize;
frame.Add(TranslatedValue::NewTagged(this, *FullObjectSlot(argument_slot)));
}
}
// We can't intermix stack decoding and allocations because the deoptimization
// infrastracture is not GC safe.
// Thus we build a temporary structure in malloced space.
// The TranslatedValue objects created correspond to the static translation
// instructions from the TranslationIterator, except for
// Translation::ARGUMENTS_ELEMENTS, where the number and values of the
// FixedArray elements depend on dynamic information from the optimized frame.
// Returns the number of expected nested translations from the
// TranslationIterator.
int TranslatedState::CreateNextTranslatedValue(
int frame_index, TranslationIterator* iterator, FixedArray literal_array,
Address fp, RegisterValues* registers, FILE* trace_file) {
disasm::NameConverter converter;
TranslatedFrame& frame = frames_[frame_index];
int value_index = static_cast<int>(frame.values_.size());
Translation::Opcode opcode =
static_cast<Translation::Opcode>(iterator->Next());
switch (opcode) {
case Translation::BEGIN:
case Translation::INTERPRETED_FRAME:
case Translation::ARGUMENTS_ADAPTOR_FRAME:
case Translation::CONSTRUCT_STUB_FRAME:
case Translation::JAVA_SCRIPT_BUILTIN_CONTINUATION_FRAME:
case Translation::JAVA_SCRIPT_BUILTIN_CONTINUATION_WITH_CATCH_FRAME:
case Translation::BUILTIN_CONTINUATION_FRAME:
case Translation::UPDATE_FEEDBACK:
// Peeled off before getting here.
break;
case Translation::DUPLICATED_OBJECT: {
int object_id = iterator->Next();
if (trace_file != nullptr) {
PrintF(trace_file, "duplicated object #%d", object_id);
}
object_positions_.push_back(object_positions_[object_id]);
TranslatedValue translated_value =
TranslatedValue::NewDuplicateObject(this, object_id);
frame.Add(translated_value);
return translated_value.GetChildrenCount();
}
case Translation::ARGUMENTS_ELEMENTS: {
CreateArgumentsType arguments_type =
static_cast<CreateArgumentsType>(iterator->Next());
CreateArgumentsElementsTranslatedValues(frame_index, fp, arguments_type,
trace_file);
return 0;
}
case Translation::ARGUMENTS_LENGTH: {
CreateArgumentsType arguments_type =
static_cast<CreateArgumentsType>(iterator->Next());
int length;
ComputeArgumentsPosition(fp, arguments_type, &length);
if (trace_file != nullptr) {
PrintF(trace_file, "arguments length field (type = %d, length = %d)",
static_cast<uint8_t>(arguments_type), length);
}
frame.Add(TranslatedValue::NewInt32(this, length));
return 0;
}
case Translation::CAPTURED_OBJECT: {
int field_count = iterator->Next();
int object_index = static_cast<int>(object_positions_.size());
if (trace_file != nullptr) {
PrintF(trace_file, "captured object #%d (length = %d)", object_index,
field_count);
}
object_positions_.push_back({frame_index, value_index});
TranslatedValue translated_value =
TranslatedValue::NewDeferredObject(this, field_count, object_index);
frame.Add(translated_value);
return translated_value.GetChildrenCount();
}
case Translation::REGISTER: {
int input_reg = iterator->Next();
if (registers == nullptr) {
TranslatedValue translated_value = TranslatedValue::NewInvalid(this);
frame.Add(translated_value);
return translated_value.GetChildrenCount();
}
intptr_t value = registers->GetRegister(input_reg);
Address uncompressed_value = DecompressIfNeeded(value);
if (trace_file != nullptr) {
PrintF(trace_file, V8PRIxPTR_FMT " ; %s ", uncompressed_value,
converter.NameOfCPURegister(input_reg));
Object(uncompressed_value).ShortPrint(trace_file);
}
TranslatedValue translated_value =
TranslatedValue::NewTagged(this, Object(uncompressed_value));
frame.Add(translated_value);
return translated_value.GetChildrenCount();
}
case Translation::INT32_REGISTER: {
int input_reg = iterator->Next();
if (registers == nullptr) {
TranslatedValue translated_value = TranslatedValue::NewInvalid(this);
frame.Add(translated_value);
return translated_value.GetChildrenCount();
}
intptr_t value = registers->GetRegister(input_reg);
if (trace_file != nullptr) {
PrintF(trace_file, "%" V8PRIdPTR " ; %s (int32)", value,
converter.NameOfCPURegister(input_reg));
}
TranslatedValue translated_value =
TranslatedValue::NewInt32(this, static_cast<int32_t>(value));
frame.Add(translated_value);
return translated_value.GetChildrenCount();
}
case Translation::INT64_REGISTER: {
int input_reg = iterator->Next();
if (registers == nullptr) {
TranslatedValue translated_value = TranslatedValue::NewInvalid(this);
frame.Add(translated_value);
return translated_value.GetChildrenCount();
}
intptr_t value = registers->GetRegister(input_reg);
if (trace_file != nullptr) {
PrintF(trace_file, "%" V8PRIdPTR " ; %s (int64)", value,
converter.NameOfCPURegister(input_reg));
}
TranslatedValue translated_value =
TranslatedValue::NewInt64(this, static_cast<int64_t>(value));
frame.Add(translated_value);
return translated_value.GetChildrenCount();
}
case Translation::UINT32_REGISTER: {
int input_reg = iterator->Next();
if (registers == nullptr) {
TranslatedValue translated_value = TranslatedValue::NewInvalid(this);
frame.Add(translated_value);
return translated_value.GetChildrenCount();
}
intptr_t value = registers->GetRegister(input_reg);
if (trace_file != nullptr) {
PrintF(trace_file, "%" V8PRIuPTR " ; %s (uint32)", value,
converter.NameOfCPURegister(input_reg));
}
TranslatedValue translated_value =
TranslatedValue::NewUInt32(this, static_cast<uint32_t>(value));
frame.Add(translated_value);
return translated_value.GetChildrenCount();
}
case Translation::BOOL_REGISTER: {
int input_reg = iterator->Next();
if (registers == nullptr) {
TranslatedValue translated_value = TranslatedValue::NewInvalid(this);
frame.Add(translated_value);
return translated_value.GetChildrenCount();
}
intptr_t value = registers->GetRegister(input_reg);
if (trace_file != nullptr) {
PrintF(trace_file, "%" V8PRIdPTR " ; %s (bool)", value,
converter.NameOfCPURegister(input_reg));
}
TranslatedValue translated_value =
TranslatedValue::NewBool(this, static_cast<uint32_t>(value));
frame.Add(translated_value);
return translated_value.GetChildrenCount();
}
case Translation::FLOAT_REGISTER: {
int input_reg = iterator->Next();
if (registers == nullptr) {
TranslatedValue translated_value = TranslatedValue::NewInvalid(this);
frame.Add(translated_value);
return translated_value.GetChildrenCount();
}
Float32 value = registers->GetFloatRegister(input_reg);
if (trace_file != nullptr) {
PrintF(trace_file, "%e ; %s (float)", value.get_scalar(),
RegisterName(FloatRegister::from_code(input_reg)));
}
TranslatedValue translated_value = TranslatedValue::NewFloat(this, value);
frame.Add(translated_value);
return translated_value.GetChildrenCount();
}
case Translation::DOUBLE_REGISTER: {
int input_reg = iterator->Next();
if (registers == nullptr) {
TranslatedValue translated_value = TranslatedValue::NewInvalid(this);
frame.Add(translated_value);
return translated_value.GetChildrenCount();
}
Float64 value = registers->GetDoubleRegister(input_reg);
if (trace_file != nullptr) {
PrintF(trace_file, "%e ; %s (double)", value.get_scalar(),
RegisterName(DoubleRegister::from_code(input_reg)));
}
TranslatedValue translated_value =
TranslatedValue::NewDouble(this, value);
frame.Add(translated_value);
return translated_value.GetChildrenCount();
}
case Translation::STACK_SLOT: {
int slot_offset =
OptimizedFrame::StackSlotOffsetRelativeToFp(iterator->Next());
intptr_t value = *(reinterpret_cast<intptr_t*>(fp + slot_offset));
Address uncompressed_value = DecompressIfNeeded(value);
if (trace_file != nullptr) {
PrintF(trace_file, V8PRIxPTR_FMT " ; [fp %c %3d] ",
uncompressed_value, slot_offset < 0 ? '-' : '+',
std::abs(slot_offset));
Object(uncompressed_value).ShortPrint(trace_file);
}
TranslatedValue translated_value =
TranslatedValue::NewTagged(this, Object(uncompressed_value));
frame.Add(translated_value);
return translated_value.GetChildrenCount();
}
case Translation::INT32_STACK_SLOT: {
int slot_offset =
OptimizedFrame::StackSlotOffsetRelativeToFp(iterator->Next());
uint32_t value = GetUInt32Slot(fp, slot_offset);
if (trace_file != nullptr) {
PrintF(trace_file, "%d ; (int32) [fp %c %3d] ",
static_cast<int32_t>(value), slot_offset < 0 ? '-' : '+',
std::abs(slot_offset));
}
TranslatedValue translated_value = TranslatedValue::NewInt32(this, value);
frame.Add(translated_value);
return translated_value.GetChildrenCount();
}
case Translation::INT64_STACK_SLOT: {
int slot_offset =
OptimizedFrame::StackSlotOffsetRelativeToFp(iterator->Next());
uint64_t value = GetUInt64Slot(fp, slot_offset);
if (trace_file != nullptr) {
PrintF(trace_file, "%" V8PRIdPTR " ; (int64) [fp %c %3d] ",
static_cast<intptr_t>(value), slot_offset < 0 ? '-' : '+',
std::abs(slot_offset));
}
TranslatedValue translated_value = TranslatedValue::NewInt64(this, value);
frame.Add(translated_value);
return translated_value.GetChildrenCount();
}
case Translation::UINT32_STACK_SLOT: {
int slot_offset =
OptimizedFrame::StackSlotOffsetRelativeToFp(iterator->Next());
uint32_t value = GetUInt32Slot(fp, slot_offset);
if (trace_file != nullptr) {
PrintF(trace_file, "%u ; (uint32) [fp %c %3d] ", value,
slot_offset < 0 ? '-' : '+', std::abs(slot_offset));
}
TranslatedValue translated_value =
TranslatedValue::NewUInt32(this, value);
frame.Add(translated_value);
return translated_value.GetChildrenCount();
}
case Translation::BOOL_STACK_SLOT: {
int slot_offset =
OptimizedFrame::StackSlotOffsetRelativeToFp(iterator->Next());
uint32_t value = GetUInt32Slot(fp, slot_offset);
if (trace_file != nullptr) {
PrintF(trace_file, "%u ; (bool) [fp %c %3d] ", value,
slot_offset < 0 ? '-' : '+', std::abs(slot_offset));
}
TranslatedValue translated_value = TranslatedValue::NewBool(this, value);
frame.Add(translated_value);
return translated_value.GetChildrenCount();
}
case Translation::FLOAT_STACK_SLOT: {
int slot_offset =
OptimizedFrame::StackSlotOffsetRelativeToFp(iterator->Next());
Float32 value = GetFloatSlot(fp, slot_offset);
if (trace_file != nullptr) {
PrintF(trace_file, "%e ; (float) [fp %c %3d] ", value.get_scalar(),
slot_offset < 0 ? '-' : '+', std::abs(slot_offset));
}
TranslatedValue translated_value = TranslatedValue::NewFloat(this, value);
frame.Add(translated_value);
return translated_value.GetChildrenCount();
}
case Translation::DOUBLE_STACK_SLOT: {
int slot_offset =
OptimizedFrame::StackSlotOffsetRelativeToFp(iterator->Next());
Float64 value = GetDoubleSlot(fp, slot_offset);
if (trace_file != nullptr) {
PrintF(trace_file, "%e ; (double) [fp %c %d] ", value.get_scalar(),
slot_offset < 0 ? '-' : '+', std::abs(slot_offset));
}
TranslatedValue translated_value =
TranslatedValue::NewDouble(this, value);
frame.Add(translated_value);
return translated_value.GetChildrenCount();
}
case Translation::LITERAL: {
int literal_index = iterator->Next();
Object value = literal_array.get(literal_index);
if (trace_file != nullptr) {
PrintF(trace_file, V8PRIxPTR_FMT " ; (literal %2d) ", value.ptr(),
literal_index);
value.ShortPrint(trace_file);
}
TranslatedValue translated_value =
TranslatedValue::NewTagged(this, value);
frame.Add(translated_value);
return translated_value.GetChildrenCount();
}
}
FATAL("We should never get here - unexpected deopt info.");
}
Address TranslatedState::DecompressIfNeeded(intptr_t value) {
if (COMPRESS_POINTERS_BOOL) {
return DecompressTaggedAny(isolate()->isolate_root(),
static_cast<uint32_t>(value));
} else {
return value;
}
}
TranslatedState::TranslatedState(const JavaScriptFrame* frame) {
int deopt_index = Safepoint::kNoDeoptimizationIndex;
DeoptimizationData data =
static_cast<const OptimizedFrame*>(frame)->GetDeoptimizationData(
&deopt_index);
DCHECK(!data.is_null() && deopt_index != Safepoint::kNoDeoptimizationIndex);
TranslationIterator it(data.TranslationByteArray(),
data.TranslationIndex(deopt_index).value());
Init(frame->isolate(), frame->fp(), &it, data.LiteralArray(),
nullptr /* registers */, nullptr /* trace file */,
frame->function().shared().internal_formal_parameter_count());
}
void TranslatedState::Init(Isolate* isolate, Address input_frame_pointer,
TranslationIterator* iterator,
FixedArray literal_array, RegisterValues* registers,
FILE* trace_file, int formal_parameter_count) {
DCHECK(frames_.empty());
formal_parameter_count_ = formal_parameter_count;
isolate_ = isolate;
// Read out the 'header' translation.
Translation::Opcode opcode =
static_cast<Translation::Opcode>(iterator->Next());
CHECK(opcode == Translation::BEGIN);
int count = iterator->Next();
frames_.reserve(count);
iterator->Next(); // Drop JS frames count.
int update_feedback_count = iterator->Next();
CHECK_GE(update_feedback_count, 0);
CHECK_LE(update_feedback_count, 1);
if (update_feedback_count == 1) {
ReadUpdateFeedback(iterator, literal_array, trace_file);
}
std::stack<int> nested_counts;
// Read the frames
for (int frame_index = 0; frame_index < count; frame_index++) {
// Read the frame descriptor.
frames_.push_back(CreateNextTranslatedFrame(
iterator, literal_array, input_frame_pointer, trace_file));
TranslatedFrame& frame = frames_.back();
// Read the values.
int values_to_process = frame.GetValueCount();
while (values_to_process > 0 || !nested_counts.empty()) {
if (trace_file != nullptr) {
if (nested_counts.empty()) {
// For top level values, print the value number.
PrintF(trace_file,
" %3i: ", frame.GetValueCount() - values_to_process);
} else {
// Take care of indenting for nested values.
PrintF(trace_file, " ");
for (size_t j = 0; j < nested_counts.size(); j++) {
PrintF(trace_file, " ");
}
}
}
int nested_count =
CreateNextTranslatedValue(frame_index, iterator, literal_array,
input_frame_pointer, registers, trace_file);
if (trace_file != nullptr) {
PrintF(trace_file, "\n");
}
// Update the value count and resolve the nesting.
values_to_process--;
if (nested_count > 0) {
nested_counts.push(values_to_process);
values_to_process = nested_count;
} else {
while (values_to_process == 0 && !nested_counts.empty()) {
values_to_process = nested_counts.top();
nested_counts.pop();
}
}
}
}
CHECK(!iterator->HasNext() || static_cast<Translation::Opcode>(
iterator->Next()) == Translation::BEGIN);
}
void TranslatedState::Prepare(Address stack_frame_pointer) {
for (auto& frame : frames_) frame.Handlify();
if (!feedback_vector_.is_null()) {
feedback_vector_handle_ =
Handle<FeedbackVector>(feedback_vector_, isolate());
feedback_vector_ = FeedbackVector();
}
stack_frame_pointer_ = stack_frame_pointer;
UpdateFromPreviouslyMaterializedObjects();
}
TranslatedValue* TranslatedState::GetValueByObjectIndex(int object_index) {
CHECK_LT(static_cast<size_t>(object_index), object_positions_.size());
TranslatedState::ObjectPosition pos = object_positions_[object_index];
return &(frames_[pos.frame_index_].values_[pos.value_index_]);
}
Handle<Object> TranslatedState::InitializeObjectAt(TranslatedValue* slot) {
slot = ResolveCapturedObject(slot);
DisallowHeapAllocation no_allocation;
if (slot->materialization_state() != TranslatedValue::kFinished) {
std::stack<int> worklist;
worklist.push(slot->object_index());
slot->mark_finished();
while (!worklist.empty()) {
int index = worklist.top();
worklist.pop();
InitializeCapturedObjectAt(index, &worklist, no_allocation);
}
}
return slot->GetStorage();
}
void TranslatedState::InitializeCapturedObjectAt(
int object_index, std::stack<int>* worklist,
const DisallowHeapAllocation& no_allocation) {
CHECK_LT(static_cast<size_t>(object_index), object_positions_.size());
TranslatedState::ObjectPosition pos = object_positions_[object_index];
int value_index = pos.value_index_;
TranslatedFrame* frame = &(frames_[pos.frame_index_]);
TranslatedValue* slot = &(frame->values_[value_index]);
value_index++;
CHECK_EQ(TranslatedValue::kFinished, slot->materialization_state());
CHECK_EQ(TranslatedValue::kCapturedObject, slot->kind());
// Ensure all fields are initialized.
int children_init_index = value_index;
for (int i = 0; i < slot->GetChildrenCount(); i++) {
// If the field is an object that has not been initialized yet, queue it
// for initialization (and mark it as such).
TranslatedValue* child_slot = frame->ValueAt(children_init_index);
if (child_slot->kind() == TranslatedValue::kCapturedObject ||
child_slot->kind() == TranslatedValue::kDuplicatedObject) {
child_slot = ResolveCapturedObject(child_slot);
if (child_slot->materialization_state() != TranslatedValue::kFinished) {
DCHECK_EQ(TranslatedValue::kAllocated,
child_slot->materialization_state());
worklist->push(child_slot->object_index());
child_slot->mark_finished();
}
}
SkipSlots(1, frame, &children_init_index);
}
// Read the map.
// The map should never be materialized, so let us check we already have
// an existing object here.
CHECK_EQ(frame->values_[value_index].kind(), TranslatedValue::kTagged);
Handle<Map> map = Handle<Map>::cast(frame->values_[value_index].GetValue());
CHECK(map->IsMap());
value_index++;
// Handle the special cases.
switch (map->instance_type()) {
case HEAP_NUMBER_TYPE:
case FIXED_DOUBLE_ARRAY_TYPE:
return;
case FIXED_ARRAY_TYPE:
case AWAIT_CONTEXT_TYPE:
case BLOCK_CONTEXT_TYPE:
case CATCH_CONTEXT_TYPE:
case DEBUG_EVALUATE_CONTEXT_TYPE:
case EVAL_CONTEXT_TYPE:
case FUNCTION_CONTEXT_TYPE:
case MODULE_CONTEXT_TYPE:
case NATIVE_CONTEXT_TYPE:
case SCRIPT_CONTEXT_TYPE:
case WITH_CONTEXT_TYPE:
case OBJECT_BOILERPLATE_DESCRIPTION_TYPE:
case HASH_TABLE_TYPE:
case ORDERED_HASH_MAP_TYPE:
case ORDERED_HASH_SET_TYPE:
case NAME_DICTIONARY_TYPE:
case GLOBAL_DICTIONARY_TYPE:
case NUMBER_DICTIONARY_TYPE:
case SIMPLE_NUMBER_DICTIONARY_TYPE:
case STRING_TABLE_TYPE:
case PROPERTY_ARRAY_TYPE:
case SCRIPT_CONTEXT_TABLE_TYPE:
InitializeObjectWithTaggedFieldsAt(frame, &value_index, slot, map,
no_allocation);
break;
default:
CHECK(map->IsJSObjectMap());
InitializeJSObjectAt(frame, &value_index, slot, map, no_allocation);
break;
}
CHECK_EQ(value_index, children_init_index);
}
void TranslatedState::EnsureObjectAllocatedAt(TranslatedValue* slot) {
slot = ResolveCapturedObject(slot);
if (slot->materialization_state() == TranslatedValue::kUninitialized) {
std::stack<int> worklist;
worklist.push(slot->object_index());
slot->mark_allocated();
while (!worklist.empty()) {
int index = worklist.top();
worklist.pop();
EnsureCapturedObjectAllocatedAt(index, &worklist);
}
}
}
void TranslatedState::MaterializeFixedDoubleArray(TranslatedFrame* frame,
int* value_index,
TranslatedValue* slot,
Handle<Map> map) {
int length = Smi::cast(frame->values_[*value_index].GetRawValue()).value();
(*value_index)++;
Handle<FixedDoubleArray> array = Handle<FixedDoubleArray>::cast(
isolate()->factory()->NewFixedDoubleArray(length));
CHECK_GT(length, 0);
for (int i = 0; i < length; i++) {
CHECK_NE(TranslatedValue::kCapturedObject,
frame->values_[*value_index].kind());
Handle<Object> value = frame->values_[*value_index].GetValue();
if (value->IsNumber()) {
array->set(i, value->Number());
} else {
CHECK(value.is_identical_to(isolate()->factory()->the_hole_value()));
array->set_the_hole(isolate(), i);
}
(*value_index)++;
}
slot->set_storage(array);
}
void TranslatedState::MaterializeHeapNumber(TranslatedFrame* frame,
int* value_index,
TranslatedValue* slot) {
CHECK_NE(TranslatedValue::kCapturedObject,
frame->values_[*value_index].kind());
Handle<Object> value = frame->values_[*value_index].GetValue();
CHECK(value->IsNumber());
Handle<HeapNumber> box = isolate()->factory()->NewHeapNumber(value->Number());
(*value_index)++;
slot->set_storage(box);
}
namespace {
enum DoubleStorageKind : uint8_t {
kStoreTagged,
kStoreUnboxedDouble,
kStoreMutableHeapNumber,
};
} // namespace
void TranslatedState::SkipSlots(int slots_to_skip, TranslatedFrame* frame,
int* value_index) {
while (slots_to_skip > 0) {
TranslatedValue* slot = &(frame->values_[*value_index]);
(*value_index)++;
slots_to_skip--;
if (slot->kind() == TranslatedValue::kCapturedObject) {
slots_to_skip += slot->GetChildrenCount();
}
}
}
void TranslatedState::EnsureCapturedObjectAllocatedAt(
int object_index, std::stack<int>* worklist) {
CHECK_LT(static_cast<size_t>(object_index), object_positions_.size());
TranslatedState::ObjectPosition pos = object_positions_[object_index];
int value_index = pos.value_index_;
TranslatedFrame* frame = &(frames_[pos.frame_index_]);
TranslatedValue* slot = &(frame->values_[value_index]);
value_index++;
CHECK_EQ(TranslatedValue::kAllocated, slot->materialization_state());
CHECK_EQ(TranslatedValue::kCapturedObject, slot->kind());
// Read the map.
// The map should never be materialized, so let us check we already have
// an existing object here.
CHECK_EQ(frame->values_[value_index].kind(), TranslatedValue::kTagged);
Handle<Map> map = Handle<Map>::cast(frame->values_[value_index].GetValue());
CHECK(map->IsMap());
value_index++;
// Handle the special cases.
switch (map->instance_type()) {
case FIXED_DOUBLE_ARRAY_TYPE:
// Materialize (i.e. allocate&initialize) the array and return since
// there is no need to process the children.
return MaterializeFixedDoubleArray(frame, &value_index, slot, map);
case HEAP_NUMBER_TYPE:
// Materialize (i.e. allocate&initialize) the heap number and return.
// There is no need to process the children.
return MaterializeHeapNumber(frame, &value_index, slot);
case FIXED_ARRAY_TYPE:
case SCRIPT_CONTEXT_TABLE_TYPE:
case AWAIT_CONTEXT_TYPE:
case BLOCK_CONTEXT_TYPE:
case CATCH_CONTEXT_TYPE:
case DEBUG_EVALUATE_CONTEXT_TYPE:
case EVAL_CONTEXT_TYPE:
case FUNCTION_CONTEXT_TYPE:
case MODULE_CONTEXT_TYPE:
case NATIVE_CONTEXT_TYPE:
case SCRIPT_CONTEXT_TYPE:
case WITH_CONTEXT_TYPE:
case HASH_TABLE_TYPE:
case ORDERED_HASH_MAP_TYPE:
case ORDERED_HASH_SET_TYPE:
case NAME_DICTIONARY_TYPE:
case GLOBAL_DICTIONARY_TYPE:
case NUMBER_DICTIONARY_TYPE:
case SIMPLE_NUMBER_DICTIONARY_TYPE:
case STRING_TABLE_TYPE: {
// Check we have the right size.
int array_length =
Smi::cast(frame->values_[value_index].GetRawValue()).value();
int instance_size = FixedArray::SizeFor(array_length);
CHECK_EQ(instance_size, slot->GetChildrenCount() * kTaggedSize);
// Canonicalize empty fixed array.
if (*map == ReadOnlyRoots(isolate()).empty_fixed_array().map() &&
array_length == 0) {
slot->set_storage(isolate()->factory()->empty_fixed_array());
} else {
slot->set_storage(AllocateStorageFor(slot));
}
// Make sure all the remaining children (after the map) are allocated.
return EnsureChildrenAllocated(slot->GetChildrenCount() - 1, frame,
&value_index, worklist);
}
case PROPERTY_ARRAY_TYPE: {
// Check we have the right size.
int length_or_hash =
Smi::cast(frame->values_[value_index].GetRawValue()).value();
int array_length = PropertyArray::LengthField::decode(length_or_hash);
int instance_size = PropertyArray::SizeFor(array_length);
CHECK_EQ(instance_size, slot->GetChildrenCount() * kTaggedSize);
slot->set_storage(AllocateStorageFor(slot));
// Make sure all the remaining children (after the map) are allocated.
return EnsureChildrenAllocated(slot->GetChildrenCount() - 1, frame,
&value_index, worklist);
}
default:
CHECK(map->IsJSObjectMap());
EnsureJSObjectAllocated(slot, map);
TranslatedValue* properties_slot = &(frame->values_[value_index]);
value_index++;
if (properties_slot->kind() == TranslatedValue::kCapturedObject) {
// If we are materializing the property array, make sure we put
// the mutable heap numbers at the right places.
EnsurePropertiesAllocatedAndMarked(properties_slot, map);
EnsureChildrenAllocated(properties_slot->GetChildrenCount(), frame,
&value_index, worklist);
}
// Make sure all the remaining children (after the map and properties) are
// allocated.
return EnsureChildrenAllocated(slot->GetChildrenCount() - 2, frame,
&value_index, worklist);
}
UNREACHABLE();
}
void TranslatedState::EnsureChildrenAllocated(int count, TranslatedFrame* frame,
int* value_index,
std::stack<int>* worklist) {
// Ensure all children are allocated.
for (int i = 0; i < count; i++) {
// If the field is an object that has not been allocated yet, queue it
// for initialization (and mark it as such).
TranslatedValue* child_slot = frame->ValueAt(*value_index);
if (child_slot->kind() == TranslatedValue::kCapturedObject ||
child_slot->kind() == TranslatedValue::kDuplicatedObject) {
child_slot = ResolveCapturedObject(child_slot);
if (child_slot->materialization_state() ==
TranslatedValue::kUninitialized) {
worklist->push(child_slot->object_index());
child_slot->mark_allocated();
}
} else {
// Make sure the simple values (heap numbers, etc.) are properly
// initialized.
child_slot->MaterializeSimple();
}
SkipSlots(1, frame, value_index);
}
}
void TranslatedState::EnsurePropertiesAllocatedAndMarked(
TranslatedValue* properties_slot, Handle<Map> map) {
CHECK_EQ(TranslatedValue::kUninitialized,
properties_slot->materialization_state());
Handle<ByteArray> object_storage = AllocateStorageFor(properties_slot);
properties_slot->mark_allocated();
properties_slot->set_storage(object_storage);
// Set markers for the double properties.
Handle<DescriptorArray> descriptors(map->instance_descriptors(), isolate());
int field_count = map->NumberOfOwnDescriptors();
for (int i = 0; i < field_count; i++) {
FieldIndex index = FieldIndex::ForDescriptor(*map, i);
if (descriptors->GetDetails(i).representation().IsDouble() &&
!index.is_inobject()) {
CHECK(!map->IsUnboxedDoubleField(index));
int outobject_index = index.outobject_array_index();
int array_index = outobject_index * kTaggedSize;
object_storage->set(array_index, kStoreMutableHeapNumber);
}
}
}
Handle<ByteArray> TranslatedState::AllocateStorageFor(TranslatedValue* slot) {
int allocate_size =
ByteArray::LengthFor(slot->GetChildrenCount() * kTaggedSize);
// It is important to allocate all the objects tenured so that the marker
// does not visit them.
Handle<ByteArray> object_storage =
isolate()->factory()->NewByteArray(allocate_size, AllocationType::kOld);
for (int i = 0; i < object_storage->length(); i++) {
object_storage->set(i, kStoreTagged);
}
return object_storage;
}
void TranslatedState::EnsureJSObjectAllocated(TranslatedValue* slot,
Handle<Map> map) {
CHECK_EQ(map->instance_size(), slot->GetChildrenCount() * kTaggedSize);
Handle<ByteArray> object_storage = AllocateStorageFor(slot);
// Now we handle the interesting (JSObject) case.
Handle<DescriptorArray> descriptors(map->instance_descriptors(), isolate());
int field_count = map->NumberOfOwnDescriptors();
// Set markers for the double properties.
for (int i = 0; i < field_count; i++) {
FieldIndex index = FieldIndex::ForDescriptor(*map, i);
if (descriptors->GetDetails(i).representation().IsDouble() &&
index.is_inobject()) {
CHECK_GE(index.index(), FixedArray::kHeaderSize / kTaggedSize);
int array_index = index.index() * kTaggedSize - FixedArray::kHeaderSize;
uint8_t marker = map->IsUnboxedDoubleField(index)
? kStoreUnboxedDouble
: kStoreMutableHeapNumber;
object_storage->set(array_index, marker);
}
}
slot->set_storage(object_storage);
}
Handle<Object> TranslatedState::GetValueAndAdvance(TranslatedFrame* frame,
int* value_index) {
TranslatedValue* slot = frame->ValueAt(*value_index);
SkipSlots(1, frame, value_index);
if (slot->kind() == TranslatedValue::kDuplicatedObject) {
slot = ResolveCapturedObject(slot);
}
CHECK_NE(TranslatedValue::kUninitialized, slot->materialization_state());
return slot->GetStorage();
}
void TranslatedState::InitializeJSObjectAt(
TranslatedFrame* frame, int* value_index, TranslatedValue* slot,
Handle<Map> map, const DisallowHeapAllocation& no_allocation) {
Handle<HeapObject> object_storage = Handle<HeapObject>::cast(slot->storage_);
DCHECK_EQ(TranslatedValue::kCapturedObject, slot->kind());
// The object should have at least a map and some payload.
CHECK_GE(slot->GetChildrenCount(), 2);
// Notify the concurrent marker about the layout change.
isolate()->heap()->NotifyObjectLayoutChange(*object_storage, no_allocation);
// Fill the property array field.
{
Handle<Object> properties = GetValueAndAdvance(frame, value_index);
WRITE_FIELD(*object_storage, JSObject::kPropertiesOrHashOffset,
*properties);
WRITE_BARRIER(*object_storage, JSObject::kPropertiesOrHashOffset,
*properties);
}
// For all the other fields we first look at the fixed array and check the
// marker to see if we store an unboxed double.
DCHECK_EQ(kTaggedSize, JSObject::kPropertiesOrHashOffset);
for (int i = 2; i < slot->GetChildrenCount(); i++) {
// Initialize and extract the value from its slot.
Handle<Object> field_value = GetValueAndAdvance(frame, value_index);
// Read out the marker and ensure the field is consistent with
// what the markers in the storage say (note that all heap numbers
// should be fully initialized by now).
int offset = i * kTaggedSize;
uint8_t marker = object_storage->ReadField<uint8_t>(offset);
if (marker == kStoreUnboxedDouble) {
double double_field_value;
if (field_value->IsSmi()) {
double_field_value = Smi::cast(*field_value).value();
} else {
CHECK(field_value->IsHeapNumber());
double_field_value = HeapNumber::cast(*field_value).value();
}
object_storage->WriteField<double>(offset, double_field_value);
} else if (marker == kStoreMutableHeapNumber) {
CHECK(field_value->IsHeapNumber());
WRITE_FIELD(*object_storage, offset, *field_value);
WRITE_BARRIER(*object_storage, offset, *field_value);
} else {
CHECK_EQ(kStoreTagged, marker);
WRITE_FIELD(*object_storage, offset, *field_value);
WRITE_BARRIER(*object_storage, offset, *field_value);
}
}
object_storage->synchronized_set_map(*map);
}
void TranslatedState::InitializeObjectWithTaggedFieldsAt(
TranslatedFrame* frame, int* value_index, TranslatedValue* slot,
Handle<Map> map, const DisallowHeapAllocation& no_allocation) {
Handle<HeapObject> object_storage = Handle<HeapObject>::cast(slot->storage_);
// Skip the writes if we already have the canonical empty fixed array.
if (*object_storage == ReadOnlyRoots(isolate()).empty_fixed_array()) {
CHECK_EQ(2, slot->GetChildrenCount());
Handle<Object> length_value = GetValueAndAdvance(frame, value_index);
CHECK_EQ(*length_value, Smi::FromInt(0));
return;
}
// Notify the concurrent marker about the layout change.
isolate()->heap()->NotifyObjectLayoutChange(*object_storage, no_allocation);
// Write the fields to the object.
for (int i = 1; i < slot->GetChildrenCount(); i++) {
Handle<Object> field_value = GetValueAndAdvance(frame, value_index);
int offset = i * kTaggedSize;
uint8_t marker = object_storage->ReadField<uint8_t>(offset);
if (i > 1 && marker == kStoreMutableHeapNumber) {
CHECK(field_value->IsHeapNumber());
} else {
CHECK(marker == kStoreTagged || i == 1);
}
WRITE_FIELD(*object_storage, offset, *field_value);
WRITE_BARRIER(*object_storage, offset, *field_value);
}
object_storage->synchronized_set_map(*map);
}
TranslatedValue* TranslatedState::ResolveCapturedObject(TranslatedValue* slot) {
while (slot->kind() == TranslatedValue::kDuplicatedObject) {
slot = GetValueByObjectIndex(slot->object_index());
}
CHECK_EQ(TranslatedValue::kCapturedObject, slot->kind());
return slot;
}
TranslatedFrame* TranslatedState::GetFrameFromJSFrameIndex(int jsframe_index) {
for (size_t i = 0; i < frames_.size(); i++) {
if (frames_[i].kind() == TranslatedFrame::kInterpretedFunction ||
frames_[i].kind() == TranslatedFrame::kJavaScriptBuiltinContinuation ||
frames_[i].kind() ==
TranslatedFrame::kJavaScriptBuiltinContinuationWithCatch) {
if (jsframe_index > 0) {
jsframe_index--;
} else {
return &(frames_[i]);
}
}
}
return nullptr;
}
TranslatedFrame* TranslatedState::GetArgumentsInfoFromJSFrameIndex(
int jsframe_index, int* args_count) {
for (size_t i = 0; i < frames_.size(); i++) {
if (frames_[i].kind() == TranslatedFrame::kInterpretedFunction ||
frames_[i].kind() == TranslatedFrame::kJavaScriptBuiltinContinuation ||
frames_[i].kind() ==
TranslatedFrame::kJavaScriptBuiltinContinuationWithCatch) {
if (jsframe_index > 0) {
jsframe_index--;
} else {
// We have the JS function frame, now check if it has arguments
// adaptor.
if (i > 0 &&
frames_[i - 1].kind() == TranslatedFrame::kArgumentsAdaptor) {
*args_count = frames_[i - 1].height();
return &(frames_[i - 1]);
}
// JavaScriptBuiltinContinuation frames that are not preceeded by
// a arguments adapter frame are currently only used by C++ API calls
// from TurboFan. Calls to C++ API functions from TurboFan need
// a special marker frame state, otherwise the API call wouldn't
// be shown in a stack trace.
if (frames_[i].kind() ==
TranslatedFrame::kJavaScriptBuiltinContinuation &&
frames_[i].shared_info()->internal_formal_parameter_count() ==
SharedFunctionInfo::kDontAdaptArgumentsSentinel) {
DCHECK(frames_[i].shared_info()->IsApiFunction());
// The argument count for this special case is always the second
// to last value in the TranslatedFrame. It should also always be
// {1}, as the GenericLazyDeoptContinuation builtin only has one
// argument (the receiver).
static constexpr int kTheContext = 1;
const int height = frames_[i].height() + kTheContext;
Object argc_object = frames_[i].ValueAt(height - 1)->GetRawValue();
CHECK(argc_object.IsSmi());
*args_count = Smi::ToInt(argc_object);
DCHECK_EQ(*args_count, 1);
} else {
*args_count = InternalFormalParameterCountWithReceiver(
*frames_[i].shared_info());
}
return &(frames_[i]);
}
}
}
return nullptr;
}
void TranslatedState::StoreMaterializedValuesAndDeopt(JavaScriptFrame* frame) {
MaterializedObjectStore* materialized_store =
isolate_->materialized_object_store();
Handle<FixedArray> previously_materialized_objects =
materialized_store->Get(stack_frame_pointer_);
Handle<Object> marker = isolate_->factory()->arguments_marker();
int length = static_cast<int>(object_positions_.size());
bool new_store = false;
if (previously_materialized_objects.is_null()) {
previously_materialized_objects =
isolate_->factory()->NewFixedArray(length, AllocationType::kOld);
for (int i = 0; i < length; i++) {
previously_materialized_objects->set(i, *marker);
}
new_store = true;
}
CHECK_EQ(length, previously_materialized_objects->length());
bool value_changed = false;
for (int i = 0; i < length; i++) {
TranslatedState::ObjectPosition pos = object_positions_[i];
TranslatedValue* value_info =
&(frames_[pos.frame_index_].values_[pos.value_index_]);
CHECK(value_info->IsMaterializedObject());
// Skip duplicate objects (i.e., those that point to some
// other object id).
if (value_info->object_index() != i) continue;
Handle<Object> value(value_info->GetRawValue(), isolate_);
if (!value.is_identical_to(marker)) {
if (previously_materialized_objects->get(i) == *marker) {
previously_materialized_objects->set(i, *value);
value_changed = true;
} else {
CHECK(previously_materialized_objects->get(i) == *value);
}
}
}
if (new_store && value_changed) {
materialized_store->Set(stack_frame_pointer_,
previously_materialized_objects);
CHECK_EQ(frames_[0].kind(), TranslatedFrame::kInterpretedFunction);
CHECK_EQ(frame->function(), frames_[0].front().GetRawValue());
Deoptimizer::DeoptimizeFunction(frame->function(), frame->LookupCode());
}
}
void TranslatedState::UpdateFromPreviouslyMaterializedObjects() {
MaterializedObjectStore* materialized_store =
isolate_->materialized_object_store();
Handle<FixedArray> previously_materialized_objects =
materialized_store->Get(stack_frame_pointer_);
// If we have no previously materialized objects, there is nothing to do.
if (previously_materialized_objects.is_null()) return;
Handle<Object> marker = isolate_->factory()->arguments_marker();
int length = static_cast<int>(object_positions_.size());
CHECK_EQ(length, previously_materialized_objects->length());
for (int i = 0; i < length; i++) {
// For a previously materialized objects, inject their value into the
// translated values.
if (previously_materialized_objects->get(i) != *marker) {
TranslatedState::ObjectPosition pos = object_positions_[i];
TranslatedValue* value_info =
&(frames_[pos.frame_index_].values_[pos.value_index_]);
CHECK(value_info->IsMaterializedObject());
if (value_info->kind() == TranslatedValue::kCapturedObject) {
value_info->set_initialized_storage(
Handle<Object>(previously_materialized_objects->get(i), isolate_));
}
}
}
}
void TranslatedState::VerifyMaterializedObjects() {
#if VERIFY_HEAP
int length = static_cast<int>(object_positions_.size());
for (int i = 0; i < length; i++) {
TranslatedValue* slot = GetValueByObjectIndex(i);
if (slot->kind() == TranslatedValue::kCapturedObject) {
CHECK_EQ(slot, GetValueByObjectIndex(slot->object_index()));
if (slot->materialization_state() == TranslatedValue::kFinished) {
slot->GetStorage()->ObjectVerify(isolate());
} else {
CHECK_EQ(slot->materialization_state(),
TranslatedValue::kUninitialized);
}
}
}
#endif
}
bool TranslatedState::DoUpdateFeedback() {
if (!feedback_vector_handle_.is_null()) {
CHECK(!feedback_slot_.IsInvalid());
isolate()->CountUsage(v8::Isolate::kDeoptimizerDisableSpeculation);
FeedbackNexus nexus(feedback_vector_handle_, feedback_slot_);
nexus.SetSpeculationMode(SpeculationMode::kDisallowSpeculation);
return true;
}
return false;
}
void TranslatedState::ReadUpdateFeedback(TranslationIterator* iterator,
FixedArray literal_array,
FILE* trace_file) {
CHECK_EQ(Translation::UPDATE_FEEDBACK, iterator->Next());
feedback_vector_ = FeedbackVector::cast(literal_array.get(iterator->Next()));
feedback_slot_ = FeedbackSlot(iterator->Next());
if (trace_file != nullptr) {
PrintF(trace_file, " reading FeedbackVector (slot %d)\n",
feedback_slot_.ToInt());
}
}
} // namespace internal
} // namespace v8
// Undefine the heap manipulation macros.
#include "src/objects/object-macros-undef.h"
| 37.809726 | 80 | 0.687509 | hamzahamidi |
4fa25ae6059c19eaf59014eee5b9c58e7cae2cb2 | 547 | hh | C++ | SimpleProxy/dispatcher/ibusiness_event.hh | svcx8/SimpleProxy | d8617ecfa64a12e1613108265f4c6c0b59627422 | [
"MIT"
] | null | null | null | SimpleProxy/dispatcher/ibusiness_event.hh | svcx8/SimpleProxy | d8617ecfa64a12e1613108265f4c6c0b59627422 | [
"MIT"
] | null | null | null | SimpleProxy/dispatcher/ibusiness_event.hh | svcx8/SimpleProxy | d8617ecfa64a12e1613108265f4c6c0b59627422 | [
"MIT"
] | null | null | null | #ifndef IBUSINESS_EVENT_HEADER
#define IBUSINESS_EVENT_HEADER
#include <cstdint>
#include <absl/status/status.h>
class IPoller;
class IBusinessEvent {
public:
virtual ~IBusinessEvent() {}
virtual absl::Status OnAcceptable(int) { return absl::OkStatus(); };
virtual absl::Status OnCloseable(int) { return absl::OkStatus(); };
virtual absl::Status OnReadable(int) { return absl::OkStatus(); };
virtual absl::Status OnWritable(int) { return absl::OkStatus(); };
IPoller* poller_ = nullptr;
};
#endif // ibusiness_event.hh | 27.35 | 72 | 0.71298 | svcx8 |
4fa39bebec315f4c3905e866dfd5dd6f499c793d | 4,428 | cc | C++ | plugins/kyotocabinet/nb_db_kyotocabinet.cc | rtsisyk/mininb | 959aa346f5294ee7fa0afb8e4e8b306a65afb8bd | [
"BSD-2-Clause"
] | 6 | 2015-07-01T13:12:58.000Z | 2016-03-28T05:15:46.000Z | plugins/kyotocabinet/nb_db_kyotocabinet.cc | rtsisyk/mininb | 959aa346f5294ee7fa0afb8e4e8b306a65afb8bd | [
"BSD-2-Clause"
] | 1 | 2015-07-01T13:16:39.000Z | 2015-07-01T13:16:39.000Z | plugins/kyotocabinet/nb_db_kyotocabinet.cc | rtsisyk/mininb | 959aa346f5294ee7fa0afb8e4e8b306a65afb8bd | [
"BSD-2-Clause"
] | null | null | null | /*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``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> 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 "../../nb_plugin_api.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <kcpolydb.h>
struct nb_db_kyotocabinet {
struct nb_db base;
kyotocabinet::TreeDB instance;
};
static struct nb_db *
nb_db_kyotocabinet_open(const struct nb_db_opts *opts)
{
struct nb_db_kyotocabinet *kyotocabinet =
new struct nb_db_kyotocabinet();
assert (kyotocabinet != NULL);
int r;
r = mkdir(opts->path, 0777);
if (r != 0 && errno != EEXIST) {
fprintf(stderr, "mkdir: %d\n", r);
return NULL;
}
char path[FILENAME_MAX];
snprintf(path, FILENAME_MAX - 4, "%s/db", opts->path);
path[FILENAME_MAX - 1] = 0;
int open_options = kyotocabinet::PolyDB::OWRITER |
kyotocabinet::PolyDB::OCREATE;
int tune_options = kyotocabinet::TreeDB::TSMALL |
kyotocabinet::TreeDB::TLINEAR;
kyotocabinet->instance.tune_options(tune_options);
//kyotocabinet->instance.tune_page(1024);
if (!kyotocabinet->instance.open(path, open_options)) {
fprintf(stderr, "db->open failed: %s\n",
kyotocabinet->instance.error().name());
goto error_2;
}
kyotocabinet->base.opts = opts;
return &kyotocabinet->base;
error_2:
delete kyotocabinet;
return NULL;
}
static void
nb_db_kyotocabinet_close(struct nb_db *db)
{
struct nb_db_kyotocabinet *kyotocabinet =
(struct nb_db_kyotocabinet *) db;
if (!kyotocabinet->instance.close()) {
fprintf(stderr, "db->close failed: %s\n",
kyotocabinet->instance.error().name());
}
delete kyotocabinet;
}
static int
nb_db_kyotocabinet_replace(struct nb_db *db, const void *key, size_t key_len,
const void *val, size_t val_len)
{
struct nb_db_kyotocabinet *kc = (struct nb_db_kyotocabinet *) db;
if (!kc->instance.set((const char *) key, key_len,
(const char *) val, val_len)) {
fprintf(stderr, "db->set() failed\n");
return -1;
}
return 0;
}
static int
nb_db_kyotocabinet_remove(struct nb_db *db, const void *key, size_t key_len)
{
struct nb_db_kyotocabinet *kc = (struct nb_db_kyotocabinet *) db;
if (!kc->instance.remove((const char *) key, key_len)) {
fprintf(stderr, "db->remove() failed\n");
return -1;
}
return 0;
}
static int
nb_db_kyotocabinet_select(struct nb_db *db, const void *key, size_t key_len,
void **pval, size_t *pval_len)
{
struct nb_db_kyotocabinet *kc = (struct nb_db_kyotocabinet *) db;
assert (pval == NULL);
(void) pval;
(void) pval_len;
if (!kc->instance.get((const char *) key, key_len,
NULL, 0)) {
fprintf(stderr, "db->select() failed\n");
return -1;
}
return 0;
}
static void
nb_db_kyotocabinet_valfree(struct nb_db *db, void *val)
{
(void) db;
free(val);
}
static struct nb_db_if plugin = {
.name = "kyotocabinet",
.open = nb_db_kyotocabinet_open,
.close = nb_db_kyotocabinet_close,
.replace = nb_db_kyotocabinet_replace,
.remove = nb_db_kyotocabinet_remove,
.select = nb_db_kyotocabinet_select,
.valfree = nb_db_kyotocabinet_valfree,
};
extern "C" NB_DB_PLUGIN const struct nb_db_if *
nb_db_kyotocabinet_plugin(void)
{
return &plugin;
}
| 25.894737 | 77 | 0.712963 | rtsisyk |
4fa3e2e008182a61975450f3953dca6f99a7ee42 | 30,213 | cpp | C++ | level_zero/api/core/ze_core_loader.cpp | mattcarter2017/compute-runtime | 1f52802aac02c78c19d5493dd3a2402830bbe438 | [
"Intel",
"MIT"
] | null | null | null | level_zero/api/core/ze_core_loader.cpp | mattcarter2017/compute-runtime | 1f52802aac02c78c19d5493dd3a2402830bbe438 | [
"Intel",
"MIT"
] | null | null | null | level_zero/api/core/ze_core_loader.cpp | mattcarter2017/compute-runtime | 1f52802aac02c78c19d5493dd3a2402830bbe438 | [
"Intel",
"MIT"
] | null | null | null | /*
* Copyright (C) 2020-2022 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "level_zero/experimental/source/tracing/tracing_imp.h"
#include "level_zero/source/inc/ze_intel_gpu.h"
#include <level_zero/ze_api.h>
#include <level_zero/ze_ddi.h>
#include <level_zero/zet_api.h>
#include <level_zero/zet_ddi.h>
#include "ze_ddi_tables.h"
ze_gpu_driver_dditable_t driver_ddiTable;
ZE_APIEXPORT ze_result_t ZE_APICALL
zeGetDriverProcAddrTable(
ze_api_version_t version,
ze_driver_dditable_t *pDdiTable) {
if (nullptr == pDdiTable)
return ZE_RESULT_ERROR_INVALID_ARGUMENT;
if (ZE_MAJOR_VERSION(driver_ddiTable.version) != ZE_MAJOR_VERSION(version) ||
ZE_MINOR_VERSION(driver_ddiTable.version) > ZE_MINOR_VERSION(version))
return ZE_RESULT_ERROR_UNSUPPORTED_VERSION;
driver_ddiTable.enableTracing = getenv_tobool("ZET_ENABLE_API_TRACING_EXP");
ze_result_t result = ZE_RESULT_SUCCESS;
pDdiTable->pfnGet = zeDriverGet;
pDdiTable->pfnGetApiVersion = zeDriverGetApiVersion;
pDdiTable->pfnGetProperties = zeDriverGetProperties;
pDdiTable->pfnGetIpcProperties = zeDriverGetIpcProperties;
pDdiTable->pfnGetExtensionProperties = zeDriverGetExtensionProperties;
pDdiTable->pfnGetExtensionFunctionAddress = zeDriverGetExtensionFunctionAddress;
driver_ddiTable.core_ddiTable.Driver = *pDdiTable;
if (driver_ddiTable.enableTracing) {
pDdiTable->pfnGet = zeDriverGet_Tracing;
pDdiTable->pfnGetApiVersion = zeDriverGetApiVersion_Tracing;
pDdiTable->pfnGetProperties = zeDriverGetProperties_Tracing;
pDdiTable->pfnGetIpcProperties = zeDriverGetIpcProperties_Tracing;
pDdiTable->pfnGetExtensionProperties = zeDriverGetExtensionProperties_Tracing;
}
return result;
}
ZE_DLLEXPORT ze_result_t ZE_APICALL
zeGetMemProcAddrTable(
ze_api_version_t version,
ze_mem_dditable_t *pDdiTable) {
if (nullptr == pDdiTable)
return ZE_RESULT_ERROR_INVALID_ARGUMENT;
if (ZE_MAJOR_VERSION(driver_ddiTable.version) != ZE_MAJOR_VERSION(version) ||
ZE_MINOR_VERSION(driver_ddiTable.version) > ZE_MINOR_VERSION(version))
return ZE_RESULT_ERROR_UNSUPPORTED_VERSION;
driver_ddiTable.enableTracing = getenv_tobool("ZET_ENABLE_API_TRACING_EXP");
ze_result_t result = ZE_RESULT_SUCCESS;
pDdiTable->pfnAllocShared = zeMemAllocShared;
pDdiTable->pfnAllocDevice = zeMemAllocDevice;
pDdiTable->pfnAllocHost = zeMemAllocHost;
pDdiTable->pfnFree = zeMemFree;
pDdiTable->pfnFreeExt = zeMemFreeExt;
pDdiTable->pfnGetAllocProperties = zeMemGetAllocProperties;
pDdiTable->pfnGetAddressRange = zeMemGetAddressRange;
pDdiTable->pfnGetIpcHandle = zeMemGetIpcHandle;
pDdiTable->pfnOpenIpcHandle = zeMemOpenIpcHandle;
pDdiTable->pfnCloseIpcHandle = zeMemCloseIpcHandle;
driver_ddiTable.core_ddiTable.Mem = *pDdiTable;
if (driver_ddiTable.enableTracing) {
pDdiTable->pfnAllocShared = zeMemAllocShared_Tracing;
pDdiTable->pfnAllocDevice = zeMemAllocDevice_Tracing;
pDdiTable->pfnAllocHost = zeMemAllocHost_Tracing;
pDdiTable->pfnFree = zeMemFree_Tracing;
pDdiTable->pfnGetAllocProperties = zeMemGetAllocProperties_Tracing;
pDdiTable->pfnGetAddressRange = zeMemGetAddressRange_Tracing;
pDdiTable->pfnGetIpcHandle = zeMemGetIpcHandle_Tracing;
pDdiTable->pfnOpenIpcHandle = zeMemOpenIpcHandle_Tracing;
pDdiTable->pfnCloseIpcHandle = zeMemCloseIpcHandle_Tracing;
}
return result;
}
ZE_DLLEXPORT ze_result_t ZE_APICALL
zeGetContextProcAddrTable(
ze_api_version_t version,
ze_context_dditable_t *pDdiTable) {
if (nullptr == pDdiTable)
return ZE_RESULT_ERROR_INVALID_ARGUMENT;
if (ZE_MAJOR_VERSION(driver_ddiTable.version) != ZE_MAJOR_VERSION(version) ||
ZE_MINOR_VERSION(driver_ddiTable.version) > ZE_MINOR_VERSION(version))
return ZE_RESULT_ERROR_UNSUPPORTED_VERSION;
driver_ddiTable.enableTracing = getenv_tobool("ZET_ENABLE_API_TRACING_EXP");
ze_result_t result = ZE_RESULT_SUCCESS;
pDdiTable->pfnCreate = zeContextCreate;
pDdiTable->pfnCreateEx = zeContextCreateEx;
pDdiTable->pfnDestroy = zeContextDestroy;
pDdiTable->pfnGetStatus = zeContextGetStatus;
pDdiTable->pfnSystemBarrier = zeContextSystemBarrier;
pDdiTable->pfnMakeMemoryResident = zeContextMakeMemoryResident;
pDdiTable->pfnEvictMemory = zeContextEvictMemory;
pDdiTable->pfnMakeImageResident = zeContextMakeImageResident;
pDdiTable->pfnEvictImage = zeContextEvictImage;
driver_ddiTable.core_ddiTable.Context = *pDdiTable;
if (driver_ddiTable.enableTracing) {
pDdiTable->pfnCreate = zeContextCreate_Tracing;
pDdiTable->pfnDestroy = zeContextDestroy_Tracing;
pDdiTable->pfnGetStatus = zeContextGetStatus_Tracing;
pDdiTable->pfnSystemBarrier = zeContextSystemBarrier_Tracing;
pDdiTable->pfnMakeMemoryResident = zeContextMakeMemoryResident_Tracing;
pDdiTable->pfnEvictMemory = zeContextEvictMemory_Tracing;
pDdiTable->pfnMakeImageResident = zeContextMakeImageResident_Tracing;
pDdiTable->pfnEvictImage = zeContextEvictImage_Tracing;
}
return result;
}
ZE_DLLEXPORT ze_result_t ZE_APICALL
zeGetPhysicalMemProcAddrTable(
ze_api_version_t version,
ze_physical_mem_dditable_t *pDdiTable) {
if (nullptr == pDdiTable)
return ZE_RESULT_ERROR_INVALID_ARGUMENT;
if (ZE_MAJOR_VERSION(driver_ddiTable.version) != ZE_MAJOR_VERSION(version) ||
ZE_MINOR_VERSION(driver_ddiTable.version) > ZE_MINOR_VERSION(version))
return ZE_RESULT_ERROR_UNSUPPORTED_VERSION;
driver_ddiTable.enableTracing = getenv_tobool("ZET_ENABLE_API_TRACING_EXP");
ze_result_t result = ZE_RESULT_SUCCESS;
pDdiTable->pfnCreate = zePhysicalMemCreate;
pDdiTable->pfnDestroy = zePhysicalMemDestroy;
driver_ddiTable.core_ddiTable.PhysicalMem = *pDdiTable;
if (driver_ddiTable.enableTracing) {
pDdiTable->pfnCreate = zePhysicalMemCreate_Tracing;
pDdiTable->pfnDestroy = zePhysicalMemDestroy_Tracing;
}
return result;
}
ZE_DLLEXPORT ze_result_t ZE_APICALL
zeGetVirtualMemProcAddrTable(
ze_api_version_t version,
ze_virtual_mem_dditable_t *pDdiTable) {
if (nullptr == pDdiTable)
return ZE_RESULT_ERROR_INVALID_ARGUMENT;
if (ZE_MAJOR_VERSION(driver_ddiTable.version) != ZE_MAJOR_VERSION(version) ||
ZE_MINOR_VERSION(driver_ddiTable.version) > ZE_MINOR_VERSION(version))
return ZE_RESULT_ERROR_UNSUPPORTED_VERSION;
driver_ddiTable.enableTracing = getenv_tobool("ZET_ENABLE_API_TRACING_EXP");
ze_result_t result = ZE_RESULT_SUCCESS;
pDdiTable->pfnReserve = zeVirtualMemReserve;
pDdiTable->pfnFree = zeVirtualMemFree;
pDdiTable->pfnQueryPageSize = zeVirtualMemQueryPageSize;
pDdiTable->pfnMap = zeVirtualMemMap;
pDdiTable->pfnUnmap = zeVirtualMemUnmap;
pDdiTable->pfnSetAccessAttribute = zeVirtualMemSetAccessAttribute;
pDdiTable->pfnGetAccessAttribute = zeVirtualMemGetAccessAttribute;
driver_ddiTable.core_ddiTable.VirtualMem = *pDdiTable;
if (driver_ddiTable.enableTracing) {
pDdiTable->pfnReserve = zeVirtualMemReserve_Tracing;
pDdiTable->pfnFree = zeVirtualMemFree_Tracing;
pDdiTable->pfnQueryPageSize = zeVirtualMemQueryPageSize_Tracing;
pDdiTable->pfnMap = zeVirtualMemMap_Tracing;
pDdiTable->pfnUnmap = zeVirtualMemUnmap_Tracing;
pDdiTable->pfnSetAccessAttribute = zeVirtualMemSetAccessAttribute_Tracing;
pDdiTable->pfnGetAccessAttribute = zeVirtualMemGetAccessAttribute_Tracing;
}
return result;
}
ZE_APIEXPORT ze_result_t ZE_APICALL
zeGetGlobalProcAddrTable(
ze_api_version_t version,
ze_global_dditable_t *pDdiTable) {
if (nullptr == pDdiTable)
return ZE_RESULT_ERROR_INVALID_ARGUMENT;
if (ZE_MAJOR_VERSION(driver_ddiTable.version) != ZE_MAJOR_VERSION(version) ||
ZE_MINOR_VERSION(driver_ddiTable.version) > ZE_MINOR_VERSION(version))
return ZE_RESULT_ERROR_UNSUPPORTED_VERSION;
driver_ddiTable.enableTracing = getenv_tobool("ZET_ENABLE_API_TRACING_EXP");
ze_result_t result = ZE_RESULT_SUCCESS;
pDdiTable->pfnInit = zeInit;
driver_ddiTable.core_ddiTable.Global = *pDdiTable;
if (driver_ddiTable.enableTracing) {
pDdiTable->pfnInit = zeInit_Tracing;
}
return result;
}
ZE_APIEXPORT ze_result_t ZE_APICALL
zeGetDeviceProcAddrTable(
ze_api_version_t version,
ze_device_dditable_t *pDdiTable) {
if (nullptr == pDdiTable)
return ZE_RESULT_ERROR_INVALID_ARGUMENT;
if (ZE_MAJOR_VERSION(driver_ddiTable.version) != ZE_MAJOR_VERSION(version) ||
ZE_MINOR_VERSION(driver_ddiTable.version) > ZE_MINOR_VERSION(version))
return ZE_RESULT_ERROR_UNSUPPORTED_VERSION;
driver_ddiTable.enableTracing = getenv_tobool("ZET_ENABLE_API_TRACING_EXP");
ze_result_t result = ZE_RESULT_SUCCESS;
pDdiTable->pfnGet = zeDeviceGet;
pDdiTable->pfnGetCommandQueueGroupProperties = zeDeviceGetCommandQueueGroupProperties;
pDdiTable->pfnGetSubDevices = zeDeviceGetSubDevices;
pDdiTable->pfnGetProperties = zeDeviceGetProperties;
pDdiTable->pfnGetComputeProperties = zeDeviceGetComputeProperties;
pDdiTable->pfnGetModuleProperties = zeDeviceGetModuleProperties;
pDdiTable->pfnGetMemoryProperties = zeDeviceGetMemoryProperties;
pDdiTable->pfnGetMemoryAccessProperties = zeDeviceGetMemoryAccessProperties;
pDdiTable->pfnGetCacheProperties = zeDeviceGetCacheProperties;
pDdiTable->pfnGetImageProperties = zeDeviceGetImageProperties;
pDdiTable->pfnGetP2PProperties = zeDeviceGetP2PProperties;
pDdiTable->pfnCanAccessPeer = zeDeviceCanAccessPeer;
pDdiTable->pfnGetStatus = zeDeviceGetStatus;
pDdiTable->pfnGetExternalMemoryProperties = zeDeviceGetExternalMemoryProperties;
pDdiTable->pfnGetGlobalTimestamps = zeDeviceGetGlobalTimestamps;
pDdiTable->pfnReserveCacheExt = zeDeviceReserveCacheExt;
pDdiTable->pfnSetCacheAdviceExt = zeDeviceSetCacheAdviceExt;
pDdiTable->pfnPciGetPropertiesExt = zeDevicePciGetPropertiesExt;
driver_ddiTable.core_ddiTable.Device = *pDdiTable;
if (driver_ddiTable.enableTracing) {
pDdiTable->pfnGet = zeDeviceGet_Tracing;
pDdiTable->pfnGetCommandQueueGroupProperties = zeDeviceGetCommandQueueGroupProperties_Tracing;
pDdiTable->pfnGetSubDevices = zeDeviceGetSubDevices_Tracing;
pDdiTable->pfnGetProperties = zeDeviceGetProperties_Tracing;
pDdiTable->pfnGetComputeProperties = zeDeviceGetComputeProperties_Tracing;
pDdiTable->pfnGetModuleProperties = zeDeviceGetModuleProperties_Tracing;
pDdiTable->pfnGetMemoryProperties = zeDeviceGetMemoryProperties_Tracing;
pDdiTable->pfnGetMemoryAccessProperties = zeDeviceGetMemoryAccessProperties_Tracing;
pDdiTable->pfnGetCacheProperties = zeDeviceGetCacheProperties_Tracing;
pDdiTable->pfnGetImageProperties = zeDeviceGetImageProperties_Tracing;
pDdiTable->pfnGetP2PProperties = zeDeviceGetP2PProperties_Tracing;
pDdiTable->pfnCanAccessPeer = zeDeviceCanAccessPeer_Tracing;
pDdiTable->pfnGetStatus = zeDeviceGetStatus_Tracing;
pDdiTable->pfnGetExternalMemoryProperties = zeDeviceGetExternalMemoryProperties_Tracing;
}
return result;
}
ZE_APIEXPORT ze_result_t ZE_APICALL
zeGetCommandQueueProcAddrTable(
ze_api_version_t version,
ze_command_queue_dditable_t *pDdiTable) {
if (nullptr == pDdiTable)
return ZE_RESULT_ERROR_INVALID_ARGUMENT;
if (ZE_MAJOR_VERSION(driver_ddiTable.version) != ZE_MAJOR_VERSION(version) ||
ZE_MINOR_VERSION(driver_ddiTable.version) > ZE_MINOR_VERSION(version))
return ZE_RESULT_ERROR_UNSUPPORTED_VERSION;
driver_ddiTable.enableTracing = getenv_tobool("ZET_ENABLE_API_TRACING_EXP");
ze_result_t result = ZE_RESULT_SUCCESS;
pDdiTable->pfnCreate = zeCommandQueueCreate;
pDdiTable->pfnDestroy = zeCommandQueueDestroy;
pDdiTable->pfnExecuteCommandLists = zeCommandQueueExecuteCommandLists;
pDdiTable->pfnSynchronize = zeCommandQueueSynchronize;
driver_ddiTable.core_ddiTable.CommandQueue = *pDdiTable;
if (driver_ddiTable.enableTracing) {
pDdiTable->pfnCreate = zeCommandQueueCreate_Tracing;
pDdiTable->pfnDestroy = zeCommandQueueDestroy_Tracing;
pDdiTable->pfnExecuteCommandLists = zeCommandQueueExecuteCommandLists_Tracing;
pDdiTable->pfnSynchronize = zeCommandQueueSynchronize_Tracing;
}
return result;
}
ZE_APIEXPORT ze_result_t ZE_APICALL
zeGetCommandListProcAddrTable(
ze_api_version_t version,
ze_command_list_dditable_t *pDdiTable) {
if (nullptr == pDdiTable)
return ZE_RESULT_ERROR_INVALID_ARGUMENT;
if (ZE_MAJOR_VERSION(driver_ddiTable.version) != ZE_MAJOR_VERSION(version) ||
ZE_MINOR_VERSION(driver_ddiTable.version) > ZE_MINOR_VERSION(version))
return ZE_RESULT_ERROR_UNSUPPORTED_VERSION;
driver_ddiTable.enableTracing = getenv_tobool("ZET_ENABLE_API_TRACING_EXP");
ze_result_t result = ZE_RESULT_SUCCESS;
pDdiTable->pfnAppendBarrier = zeCommandListAppendBarrier;
pDdiTable->pfnAppendMemoryRangesBarrier = zeCommandListAppendMemoryRangesBarrier;
pDdiTable->pfnCreate = zeCommandListCreate;
pDdiTable->pfnCreateImmediate = zeCommandListCreateImmediate;
pDdiTable->pfnDestroy = zeCommandListDestroy;
pDdiTable->pfnClose = zeCommandListClose;
pDdiTable->pfnReset = zeCommandListReset;
pDdiTable->pfnAppendMemoryCopy = zeCommandListAppendMemoryCopy;
pDdiTable->pfnAppendMemoryCopyRegion = zeCommandListAppendMemoryCopyRegion;
pDdiTable->pfnAppendMemoryFill = zeCommandListAppendMemoryFill;
pDdiTable->pfnAppendImageCopy = zeCommandListAppendImageCopy;
pDdiTable->pfnAppendImageCopyRegion = zeCommandListAppendImageCopyRegion;
pDdiTable->pfnAppendImageCopyToMemory = zeCommandListAppendImageCopyToMemory;
pDdiTable->pfnAppendImageCopyFromMemory = zeCommandListAppendImageCopyFromMemory;
pDdiTable->pfnAppendMemoryPrefetch = zeCommandListAppendMemoryPrefetch;
pDdiTable->pfnAppendMemAdvise = zeCommandListAppendMemAdvise;
pDdiTable->pfnAppendSignalEvent = zeCommandListAppendSignalEvent;
pDdiTable->pfnAppendWaitOnEvents = zeCommandListAppendWaitOnEvents;
pDdiTable->pfnAppendEventReset = zeCommandListAppendEventReset;
pDdiTable->pfnAppendLaunchKernel = zeCommandListAppendLaunchKernel;
pDdiTable->pfnAppendLaunchCooperativeKernel = zeCommandListAppendLaunchCooperativeKernel;
pDdiTable->pfnAppendLaunchKernelIndirect = zeCommandListAppendLaunchKernelIndirect;
pDdiTable->pfnAppendLaunchMultipleKernelsIndirect = zeCommandListAppendLaunchMultipleKernelsIndirect;
pDdiTable->pfnAppendWriteGlobalTimestamp = zeCommandListAppendWriteGlobalTimestamp;
pDdiTable->pfnAppendMemoryCopyFromContext = zeCommandListAppendMemoryCopyFromContext;
pDdiTable->pfnAppendQueryKernelTimestamps = zeCommandListAppendQueryKernelTimestamps;
driver_ddiTable.core_ddiTable.CommandList = *pDdiTable;
if (driver_ddiTable.enableTracing) {
pDdiTable->pfnAppendBarrier = zeCommandListAppendBarrier_Tracing;
pDdiTable->pfnAppendMemoryRangesBarrier = zeCommandListAppendMemoryRangesBarrier_Tracing;
pDdiTable->pfnCreate = zeCommandListCreate_Tracing;
pDdiTable->pfnCreateImmediate = zeCommandListCreateImmediate_Tracing;
pDdiTable->pfnDestroy = zeCommandListDestroy_Tracing;
pDdiTable->pfnClose = zeCommandListClose_Tracing;
pDdiTable->pfnReset = zeCommandListReset_Tracing;
pDdiTable->pfnAppendMemoryCopy = zeCommandListAppendMemoryCopy_Tracing;
pDdiTable->pfnAppendMemoryCopyRegion = zeCommandListAppendMemoryCopyRegion_Tracing;
pDdiTable->pfnAppendMemoryFill = zeCommandListAppendMemoryFill_Tracing;
pDdiTable->pfnAppendImageCopy = zeCommandListAppendImageCopy_Tracing;
pDdiTable->pfnAppendImageCopyRegion = zeCommandListAppendImageCopyRegion_Tracing;
pDdiTable->pfnAppendImageCopyToMemory = zeCommandListAppendImageCopyToMemory_Tracing;
pDdiTable->pfnAppendImageCopyFromMemory = zeCommandListAppendImageCopyFromMemory_Tracing;
pDdiTable->pfnAppendMemoryPrefetch = zeCommandListAppendMemoryPrefetch_Tracing;
pDdiTable->pfnAppendMemAdvise = zeCommandListAppendMemAdvise_Tracing;
pDdiTable->pfnAppendSignalEvent = zeCommandListAppendSignalEvent_Tracing;
pDdiTable->pfnAppendWaitOnEvents = zeCommandListAppendWaitOnEvents_Tracing;
pDdiTable->pfnAppendEventReset = zeCommandListAppendEventReset_Tracing;
pDdiTable->pfnAppendLaunchKernel = zeCommandListAppendLaunchKernel_Tracing;
pDdiTable->pfnAppendLaunchCooperativeKernel = zeCommandListAppendLaunchCooperativeKernel_Tracing;
pDdiTable->pfnAppendLaunchKernelIndirect = zeCommandListAppendLaunchKernelIndirect_Tracing;
pDdiTable->pfnAppendLaunchMultipleKernelsIndirect = zeCommandListAppendLaunchMultipleKernelsIndirect_Tracing;
pDdiTable->pfnAppendWriteGlobalTimestamp = zeCommandListAppendWriteGlobalTimestamp_Tracing;
pDdiTable->pfnAppendMemoryCopyFromContext = zeCommandListAppendMemoryCopyFromContext_Tracing;
pDdiTable->pfnAppendQueryKernelTimestamps = zeCommandListAppendQueryKernelTimestamps_Tracing;
}
return result;
}
ZE_APIEXPORT ze_result_t ZE_APICALL
zeGetFenceProcAddrTable(
ze_api_version_t version,
ze_fence_dditable_t *pDdiTable) {
if (nullptr == pDdiTable)
return ZE_RESULT_ERROR_INVALID_ARGUMENT;
if (ZE_MAJOR_VERSION(driver_ddiTable.version) != ZE_MAJOR_VERSION(version) ||
ZE_MINOR_VERSION(driver_ddiTable.version) > ZE_MINOR_VERSION(version))
return ZE_RESULT_ERROR_UNSUPPORTED_VERSION;
driver_ddiTable.enableTracing = getenv_tobool("ZET_ENABLE_API_TRACING_EXP");
ze_result_t result = ZE_RESULT_SUCCESS;
pDdiTable->pfnCreate = zeFenceCreate;
pDdiTable->pfnDestroy = zeFenceDestroy;
pDdiTable->pfnHostSynchronize = zeFenceHostSynchronize;
pDdiTable->pfnQueryStatus = zeFenceQueryStatus;
pDdiTable->pfnReset = zeFenceReset;
driver_ddiTable.core_ddiTable.Fence = *pDdiTable;
if (driver_ddiTable.enableTracing) {
pDdiTable->pfnCreate = zeFenceCreate_Tracing;
pDdiTable->pfnDestroy = zeFenceDestroy_Tracing;
pDdiTable->pfnHostSynchronize = zeFenceHostSynchronize_Tracing;
pDdiTable->pfnQueryStatus = zeFenceQueryStatus_Tracing;
pDdiTable->pfnReset = zeFenceReset_Tracing;
}
return result;
}
ZE_APIEXPORT ze_result_t ZE_APICALL
zeGetEventPoolProcAddrTable(
ze_api_version_t version,
ze_event_pool_dditable_t *pDdiTable) {
if (nullptr == pDdiTable)
return ZE_RESULT_ERROR_INVALID_ARGUMENT;
if (ZE_MAJOR_VERSION(driver_ddiTable.version) != ZE_MAJOR_VERSION(version) ||
ZE_MINOR_VERSION(driver_ddiTable.version) > ZE_MINOR_VERSION(version))
return ZE_RESULT_ERROR_UNSUPPORTED_VERSION;
driver_ddiTable.enableTracing = getenv_tobool("ZET_ENABLE_API_TRACING_EXP");
ze_result_t result = ZE_RESULT_SUCCESS;
pDdiTable->pfnCreate = zeEventPoolCreate;
pDdiTable->pfnDestroy = zeEventPoolDestroy;
pDdiTable->pfnGetIpcHandle = zeEventPoolGetIpcHandle;
pDdiTable->pfnOpenIpcHandle = zeEventPoolOpenIpcHandle;
pDdiTable->pfnCloseIpcHandle = zeEventPoolCloseIpcHandle;
driver_ddiTable.core_ddiTable.EventPool = *pDdiTable;
if (driver_ddiTable.enableTracing) {
pDdiTable->pfnCreate = zeEventPoolCreate_Tracing;
pDdiTable->pfnDestroy = zeEventPoolDestroy_Tracing;
pDdiTable->pfnGetIpcHandle = zeEventPoolGetIpcHandle_Tracing;
pDdiTable->pfnOpenIpcHandle = zeEventPoolOpenIpcHandle_Tracing;
pDdiTable->pfnCloseIpcHandle = zeEventPoolCloseIpcHandle_Tracing;
}
return result;
}
ZE_APIEXPORT ze_result_t ZE_APICALL
zeGetEventProcAddrTable(
ze_api_version_t version,
ze_event_dditable_t *pDdiTable) {
if (nullptr == pDdiTable)
return ZE_RESULT_ERROR_INVALID_ARGUMENT;
if (ZE_MAJOR_VERSION(driver_ddiTable.version) != ZE_MAJOR_VERSION(version) ||
ZE_MINOR_VERSION(driver_ddiTable.version) > ZE_MINOR_VERSION(version))
return ZE_RESULT_ERROR_UNSUPPORTED_VERSION;
driver_ddiTable.enableTracing = getenv_tobool("ZET_ENABLE_API_TRACING_EXP");
ze_result_t result = ZE_RESULT_SUCCESS;
pDdiTable->pfnCreate = zeEventCreate;
pDdiTable->pfnDestroy = zeEventDestroy;
pDdiTable->pfnHostSignal = zeEventHostSignal;
pDdiTable->pfnHostSynchronize = zeEventHostSynchronize;
pDdiTable->pfnQueryStatus = zeEventQueryStatus;
pDdiTable->pfnHostReset = zeEventHostReset;
pDdiTable->pfnQueryKernelTimestamp = zeEventQueryKernelTimestamp;
driver_ddiTable.core_ddiTable.Event = *pDdiTable;
if (driver_ddiTable.enableTracing) {
pDdiTable->pfnCreate = zeEventCreate_Tracing;
pDdiTable->pfnDestroy = zeEventDestroy_Tracing;
pDdiTable->pfnHostSignal = zeEventHostSignal_Tracing;
pDdiTable->pfnHostSynchronize = zeEventHostSynchronize_Tracing;
pDdiTable->pfnQueryStatus = zeEventQueryStatus_Tracing;
pDdiTable->pfnHostReset = zeEventHostReset_Tracing;
pDdiTable->pfnQueryKernelTimestamp = zeEventQueryKernelTimestamp_Tracing;
}
return result;
}
ZE_APIEXPORT ze_result_t ZE_APICALL
zeGetEventExpProcAddrTable(
ze_api_version_t version,
ze_event_exp_dditable_t *pDdiTable) {
if (nullptr == pDdiTable)
return ZE_RESULT_ERROR_INVALID_ARGUMENT;
if (ZE_MAJOR_VERSION(driver_ddiTable.version) != ZE_MAJOR_VERSION(version) ||
ZE_MINOR_VERSION(driver_ddiTable.version) > ZE_MINOR_VERSION(version))
return ZE_RESULT_ERROR_UNSUPPORTED_VERSION;
ze_result_t result = ZE_RESULT_SUCCESS;
pDdiTable->pfnQueryTimestampsExp = zeEventQueryTimestampsExp;
return result;
}
ZE_APIEXPORT ze_result_t ZE_APICALL
zeGetImageProcAddrTable(
ze_api_version_t version,
ze_image_dditable_t *pDdiTable) {
if (nullptr == pDdiTable)
return ZE_RESULT_ERROR_INVALID_ARGUMENT;
if (ZE_MAJOR_VERSION(driver_ddiTable.version) != ZE_MAJOR_VERSION(version) ||
ZE_MINOR_VERSION(driver_ddiTable.version) > ZE_MINOR_VERSION(version))
return ZE_RESULT_ERROR_UNSUPPORTED_VERSION;
driver_ddiTable.enableTracing = getenv_tobool("ZET_ENABLE_API_TRACING_EXP");
ze_result_t result = ZE_RESULT_SUCCESS;
pDdiTable->pfnGetProperties = zeImageGetProperties;
pDdiTable->pfnCreate = zeImageCreate;
pDdiTable->pfnDestroy = zeImageDestroy;
pDdiTable->pfnGetAllocPropertiesExt = zeImageGetAllocPropertiesExt;
driver_ddiTable.core_ddiTable.Image = *pDdiTable;
if (driver_ddiTable.enableTracing) {
pDdiTable->pfnGetProperties = zeImageGetProperties_Tracing;
pDdiTable->pfnCreate = zeImageCreate_Tracing;
pDdiTable->pfnDestroy = zeImageDestroy_Tracing;
pDdiTable->pfnGetAllocPropertiesExt = zeImageGetAllocPropertiesExt;
}
return result;
}
ZE_APIEXPORT ze_result_t ZE_APICALL
zeGetModuleProcAddrTable(
ze_api_version_t version,
ze_module_dditable_t *pDdiTable) {
if (nullptr == pDdiTable)
return ZE_RESULT_ERROR_INVALID_ARGUMENT;
if (ZE_MAJOR_VERSION(driver_ddiTable.version) != ZE_MAJOR_VERSION(version) ||
ZE_MINOR_VERSION(driver_ddiTable.version) > ZE_MINOR_VERSION(version))
return ZE_RESULT_ERROR_UNSUPPORTED_VERSION;
driver_ddiTable.enableTracing = getenv_tobool("ZET_ENABLE_API_TRACING_EXP");
ze_result_t result = ZE_RESULT_SUCCESS;
pDdiTable->pfnCreate = zeModuleCreate;
pDdiTable->pfnDestroy = zeModuleDestroy;
pDdiTable->pfnDynamicLink = zeModuleDynamicLink;
pDdiTable->pfnGetNativeBinary = zeModuleGetNativeBinary;
pDdiTable->pfnGetGlobalPointer = zeModuleGetGlobalPointer;
pDdiTable->pfnGetKernelNames = zeModuleGetKernelNames;
pDdiTable->pfnGetFunctionPointer = zeModuleGetFunctionPointer;
pDdiTable->pfnGetProperties = zeModuleGetProperties;
driver_ddiTable.core_ddiTable.Module = *pDdiTable;
if (driver_ddiTable.enableTracing) {
pDdiTable->pfnCreate = zeModuleCreate_Tracing;
pDdiTable->pfnDestroy = zeModuleDestroy_Tracing;
pDdiTable->pfnGetNativeBinary = zeModuleGetNativeBinary_Tracing;
pDdiTable->pfnDynamicLink = zeModuleDynamicLink_Tracing;
pDdiTable->pfnGetGlobalPointer = zeModuleGetGlobalPointer_Tracing;
pDdiTable->pfnGetFunctionPointer = zeModuleGetFunctionPointer_Tracing;
pDdiTable->pfnGetKernelNames = zeModuleGetKernelNames_Tracing;
pDdiTable->pfnGetProperties = zeModuleGetProperties_Tracing;
}
return result;
}
ZE_APIEXPORT ze_result_t ZE_APICALL
zeGetModuleBuildLogProcAddrTable(
ze_api_version_t version,
ze_module_build_log_dditable_t *pDdiTable) {
if (nullptr == pDdiTable)
return ZE_RESULT_ERROR_INVALID_ARGUMENT;
if (ZE_MAJOR_VERSION(driver_ddiTable.version) != ZE_MAJOR_VERSION(version) ||
ZE_MINOR_VERSION(driver_ddiTable.version) > ZE_MINOR_VERSION(version))
return ZE_RESULT_ERROR_UNSUPPORTED_VERSION;
driver_ddiTable.enableTracing = getenv_tobool("ZET_ENABLE_API_TRACING_EXP");
ze_result_t result = ZE_RESULT_SUCCESS;
pDdiTable->pfnDestroy = zeModuleBuildLogDestroy;
pDdiTable->pfnGetString = zeModuleBuildLogGetString;
driver_ddiTable.core_ddiTable.ModuleBuildLog = *pDdiTable;
if (driver_ddiTable.enableTracing) {
pDdiTable->pfnDestroy = zeModuleBuildLogDestroy_Tracing;
pDdiTable->pfnGetString = zeModuleBuildLogGetString_Tracing;
}
return result;
}
ZE_APIEXPORT ze_result_t ZE_APICALL
zeGetKernelProcAddrTable(
ze_api_version_t version,
ze_kernel_dditable_t *pDdiTable) {
if (nullptr == pDdiTable)
return ZE_RESULT_ERROR_INVALID_ARGUMENT;
if (ZE_MAJOR_VERSION(driver_ddiTable.version) != ZE_MAJOR_VERSION(version) ||
ZE_MINOR_VERSION(driver_ddiTable.version) > ZE_MINOR_VERSION(version))
return ZE_RESULT_ERROR_UNSUPPORTED_VERSION;
driver_ddiTable.enableTracing = getenv_tobool("ZET_ENABLE_API_TRACING_EXP");
ze_result_t result = ZE_RESULT_SUCCESS;
pDdiTable->pfnCreate = zeKernelCreate;
pDdiTable->pfnDestroy = zeKernelDestroy;
pDdiTable->pfnSetGroupSize = zeKernelSetGroupSize;
pDdiTable->pfnSuggestGroupSize = zeKernelSuggestGroupSize;
pDdiTable->pfnSuggestMaxCooperativeGroupCount = zeKernelSuggestMaxCooperativeGroupCount;
pDdiTable->pfnSetArgumentValue = zeKernelSetArgumentValue;
pDdiTable->pfnSetIndirectAccess = zeKernelSetIndirectAccess;
pDdiTable->pfnGetIndirectAccess = zeKernelGetIndirectAccess;
pDdiTable->pfnGetSourceAttributes = zeKernelGetSourceAttributes;
pDdiTable->pfnGetProperties = zeKernelGetProperties;
pDdiTable->pfnSetCacheConfig = zeKernelSetCacheConfig;
pDdiTable->pfnGetName = zeKernelGetName;
driver_ddiTable.core_ddiTable.Kernel = *pDdiTable;
if (driver_ddiTable.enableTracing) {
pDdiTable->pfnCreate = zeKernelCreate_Tracing;
pDdiTable->pfnDestroy = zeKernelDestroy_Tracing;
pDdiTable->pfnSetGroupSize = zeKernelSetGroupSize_Tracing;
pDdiTable->pfnSuggestGroupSize = zeKernelSuggestGroupSize_Tracing;
pDdiTable->pfnSuggestMaxCooperativeGroupCount = zeKernelSuggestMaxCooperativeGroupCount_Tracing;
pDdiTable->pfnSetArgumentValue = zeKernelSetArgumentValue_Tracing;
pDdiTable->pfnSetIndirectAccess = zeKernelSetIndirectAccess_Tracing;
pDdiTable->pfnGetIndirectAccess = zeKernelGetIndirectAccess_Tracing;
pDdiTable->pfnGetSourceAttributes = zeKernelGetSourceAttributes_Tracing;
pDdiTable->pfnGetProperties = zeKernelGetProperties_Tracing;
pDdiTable->pfnSetCacheConfig = zeKernelSetCacheConfig_Tracing;
pDdiTable->pfnGetName = zeKernelGetName_Tracing;
}
return result;
}
ZE_APIEXPORT ze_result_t ZE_APICALL
zeGetSamplerProcAddrTable(
ze_api_version_t version,
ze_sampler_dditable_t *pDdiTable) {
if (nullptr == pDdiTable)
return ZE_RESULT_ERROR_INVALID_ARGUMENT;
if (ZE_MAJOR_VERSION(driver_ddiTable.version) != ZE_MAJOR_VERSION(version) ||
ZE_MINOR_VERSION(driver_ddiTable.version) > ZE_MINOR_VERSION(version))
return ZE_RESULT_ERROR_UNSUPPORTED_VERSION;
driver_ddiTable.enableTracing = getenv_tobool("ZET_ENABLE_API_TRACING_EXP");
ze_result_t result = ZE_RESULT_SUCCESS;
pDdiTable->pfnCreate = zeSamplerCreate;
pDdiTable->pfnDestroy = zeSamplerDestroy;
driver_ddiTable.core_ddiTable.Sampler = *pDdiTable;
if (driver_ddiTable.enableTracing) {
pDdiTable->pfnCreate = zeSamplerCreate_Tracing;
pDdiTable->pfnDestroy = zeSamplerDestroy_Tracing;
}
return result;
}
ZE_APIEXPORT ze_result_t ZE_APICALL
zeGetKernelExpProcAddrTable(
ze_api_version_t version,
ze_kernel_exp_dditable_t *pDdiTable) {
if (nullptr == pDdiTable)
return ZE_RESULT_ERROR_INVALID_ARGUMENT;
if (ZE_MAJOR_VERSION(driver_ddiTable.version) != ZE_MAJOR_VERSION(version) ||
ZE_MINOR_VERSION(driver_ddiTable.version) > ZE_MINOR_VERSION(version))
return ZE_RESULT_ERROR_UNSUPPORTED_VERSION;
ze_result_t result = ZE_RESULT_SUCCESS;
pDdiTable->pfnSetGlobalOffsetExp = zeKernelSetGlobalOffsetExp;
pDdiTable->pfnSchedulingHintExp = zeKernelSchedulingHintExp;
driver_ddiTable.core_ddiTable.KernelExp = *pDdiTable;
return result;
}
ZE_APIEXPORT ze_result_t ZE_APICALL
zeGetImageExpProcAddrTable(
ze_api_version_t version,
ze_image_exp_dditable_t *pDdiTable) {
if (nullptr == pDdiTable)
return ZE_RESULT_ERROR_INVALID_ARGUMENT;
if (ZE_MAJOR_VERSION(driver_ddiTable.version) != ZE_MAJOR_VERSION(version) ||
ZE_MINOR_VERSION(driver_ddiTable.version) > ZE_MINOR_VERSION(version))
return ZE_RESULT_ERROR_UNSUPPORTED_VERSION;
ze_result_t result = ZE_RESULT_SUCCESS;
pDdiTable->pfnGetMemoryPropertiesExp = zeImageGetMemoryPropertiesExp;
pDdiTable->pfnViewCreateExp = zeImageViewCreateExp;
driver_ddiTable.core_ddiTable.ImageExp = *pDdiTable;
return result;
}
| 48.186603 | 117 | 0.787873 | mattcarter2017 |
4fa49dfc22566a12573aaf42fe3b51b02c76c4e9 | 338 | cpp | C++ | COSC1076/week5/question02.cpp | davidkevork/RMIT | 41c17de726f28c06ee1321fd2e7ee699acfdd611 | [
"MIT"
] | null | null | null | COSC1076/week5/question02.cpp | davidkevork/RMIT | 41c17de726f28c06ee1321fd2e7ee699acfdd611 | [
"MIT"
] | null | null | null | COSC1076/week5/question02.cpp | davidkevork/RMIT | 41c17de726f28c06ee1321fd2e7ee699acfdd611 | [
"MIT"
] | null | null | null | #include <iostream>
int stringLength(char* string) {
int length = 0;
char lastChar = string[0];
while (lastChar != '\0') {
length += 1;
lastChar = string[length];
}
return length;
}
int main() {
char string[20] = "hello world";
std::cout << string << std::endl;
std::cout << stringLength(string) << std::endl;
}
| 18.777778 | 49 | 0.600592 | davidkevork |
4fa5e3f37b31c1a52391f2d82cca7cf4c44f1d12 | 2,396 | cpp | C++ | src/common/file_buffer.cpp | shenyunlong/duckdb | ecb90f22b36a50b051fdd8e0d681bade3365c430 | [
"MIT"
] | null | null | null | src/common/file_buffer.cpp | shenyunlong/duckdb | ecb90f22b36a50b051fdd8e0d681bade3365c430 | [
"MIT"
] | 7 | 2020-08-25T22:24:16.000Z | 2020-09-06T00:16:49.000Z | src/common/file_buffer.cpp | shenyunlong/duckdb | ecb90f22b36a50b051fdd8e0d681bade3365c430 | [
"MIT"
] | null | null | null | #include "duckdb/common/file_buffer.hpp"
#include "duckdb/common/file_system.hpp"
#include "duckdb/common/helper.hpp"
#include "duckdb/common/checksum.hpp"
#include "duckdb/common/exception.hpp"
#include <cstring>
namespace duckdb {
using namespace std;
FileBuffer::FileBuffer(FileBufferType type, uint64_t bufsiz) : type(type) {
const int SECTOR_SIZE = Storage::SECTOR_SIZE;
// round up to the nearest SECTOR_SIZE, thi sis only really necessary if the file buffer will be used for Direct IO
if (bufsiz % SECTOR_SIZE != 0) {
bufsiz += SECTOR_SIZE - (bufsiz % SECTOR_SIZE);
}
assert(bufsiz % SECTOR_SIZE == 0);
assert(bufsiz >= SECTOR_SIZE);
// we add (SECTOR_SIZE - 1) to ensure that we can align the buffer to SECTOR_SIZE
malloced_buffer = (data_ptr_t)malloc(bufsiz + (SECTOR_SIZE - 1));
if (!malloced_buffer) {
throw std::bad_alloc();
}
// round to multiple of SECTOR_SIZE
uint64_t num = (uint64_t)malloced_buffer;
uint64_t remainder = num % SECTOR_SIZE;
if (remainder != 0) {
num = num + SECTOR_SIZE - remainder;
}
assert(num % SECTOR_SIZE == 0);
assert(num + bufsiz <= ((uint64_t)malloced_buffer + bufsiz + (SECTOR_SIZE - 1)));
assert(num >= (uint64_t)malloced_buffer);
// construct the FileBuffer object
internal_buffer = (data_ptr_t)num;
internal_size = bufsiz;
buffer = internal_buffer + Storage::BLOCK_HEADER_SIZE;
size = internal_size - Storage::BLOCK_HEADER_SIZE;
}
FileBuffer::~FileBuffer() {
free(malloced_buffer);
}
void FileBuffer::Read(FileHandle &handle, uint64_t location) {
// read the buffer from disk
handle.Read(internal_buffer, internal_size, location);
// compute the checksum
uint64_t stored_checksum = *((uint64_t *)internal_buffer);
uint64_t computed_checksum = Checksum(buffer, size);
// verify the checksum
if (stored_checksum != computed_checksum) {
throw IOException("Corrupt database file: computed checksum %llu does not match stored checksum %llu in block",
computed_checksum, stored_checksum);
}
}
void FileBuffer::Write(FileHandle &handle, uint64_t location) {
// compute the checksum and write it to the start of the buffer
uint64_t checksum = Checksum(buffer, size);
*((uint64_t *)internal_buffer) = checksum;
// now write the buffer
handle.Write(internal_buffer, internal_size, location);
}
void FileBuffer::Clear() {
memset(internal_buffer, 0, internal_size);
}
} // namespace duckdb
| 34.228571 | 116 | 0.738314 | shenyunlong |
4fa6098a8545c15491b9629bfd8f756c5152f9f9 | 7,546 | hpp | C++ | library/src/auxiliary/rocauxiliary_orm2l_unm2l.hpp | YvanMokwinski/rocSOLVER | 3ff9ad6e60da6dd5f6d3fe5ab02cf0d5bed9aa5f | [
"BSD-2-Clause"
] | null | null | null | library/src/auxiliary/rocauxiliary_orm2l_unm2l.hpp | YvanMokwinski/rocSOLVER | 3ff9ad6e60da6dd5f6d3fe5ab02cf0d5bed9aa5f | [
"BSD-2-Clause"
] | null | null | null | library/src/auxiliary/rocauxiliary_orm2l_unm2l.hpp | YvanMokwinski/rocSOLVER | 3ff9ad6e60da6dd5f6d3fe5ab02cf0d5bed9aa5f | [
"BSD-2-Clause"
] | null | null | null | /************************************************************************
* Derived from the BSD3-licensed
* LAPACK routine (version 3.7.0) --
* Univ. of Tennessee, Univ. of California Berkeley,
* Univ. of Colorado Denver and NAG Ltd..
* December 2016
* Copyright (c) 2019-2021 Advanced Micro Devices, Inc.
* ***********************************************************************/
#pragma once
#include "rocauxiliary_lacgv.hpp"
#include "rocauxiliary_larf.hpp"
#include "rocblas.hpp"
#include "rocsolver.h"
template <typename T, bool BATCHED>
void rocsolver_orm2l_unm2l_getMemorySize(const rocblas_side side,
const rocblas_int m,
const rocblas_int n,
const rocblas_int k,
const rocblas_int batch_count,
size_t* size_scalars,
size_t* size_Abyx,
size_t* size_diag,
size_t* size_workArr)
{
// if quick return no workspace needed
if(m == 0 || n == 0 || k == 0 || batch_count == 0)
{
*size_scalars = 0;
*size_Abyx = 0;
*size_diag = 0;
*size_workArr = 0;
return;
}
// size of temporary array for diagonal elements
*size_diag = sizeof(T) * batch_count;
// memory requirements to call larf
rocsolver_larf_getMemorySize<T, BATCHED>(side, m, n, batch_count, size_scalars, size_Abyx,
size_workArr);
}
template <bool COMPLEX, typename T, typename U>
rocblas_status rocsolver_orm2l_ormql_argCheck(rocblas_handle handle,
const rocblas_side side,
const rocblas_operation trans,
const rocblas_int m,
const rocblas_int n,
const rocblas_int k,
const rocblas_int lda,
const rocblas_int ldc,
T A,
T C,
U ipiv)
{
// order is important for unit tests:
// 1. invalid/non-supported values
if(side != rocblas_side_left && side != rocblas_side_right)
return rocblas_status_invalid_value;
if(trans != rocblas_operation_none && trans != rocblas_operation_transpose
&& trans != rocblas_operation_conjugate_transpose)
return rocblas_status_invalid_value;
if((COMPLEX && trans == rocblas_operation_transpose)
|| (!COMPLEX && trans == rocblas_operation_conjugate_transpose))
return rocblas_status_invalid_value;
bool left = (side == rocblas_side_left);
// 2. invalid size
if(m < 0 || n < 0 || k < 0 || ldc < m)
return rocblas_status_invalid_size;
if(left && (lda < m || k > m))
return rocblas_status_invalid_size;
if(!left && (lda < n || k > n))
return rocblas_status_invalid_size;
// skip pointer check if querying memory size
if(rocblas_is_device_memory_size_query(handle))
return rocblas_status_continue;
// 3. invalid pointers
if((m * n && !C) || (k && !ipiv) || (left && m * k && !A) || (!left && n * k && !A))
return rocblas_status_invalid_pointer;
return rocblas_status_continue;
}
template <typename T, typename U, bool COMPLEX = is_complex<T>>
rocblas_status rocsolver_orm2l_unm2l_template(rocblas_handle handle,
const rocblas_side side,
const rocblas_operation trans,
const rocblas_int m,
const rocblas_int n,
const rocblas_int k,
U A,
const rocblas_int shiftA,
const rocblas_int lda,
const rocblas_stride strideA,
T* ipiv,
const rocblas_stride strideP,
U C,
const rocblas_int shiftC,
const rocblas_int ldc,
const rocblas_stride strideC,
const rocblas_int batch_count,
T* scalars,
T* Abyx,
T* diag,
T** workArr)
{
ROCSOLVER_ENTER("orm2l_unm2l", "side:", side, "trans:", trans, "m:", m, "n:", n, "k:", k,
"shiftA:", shiftA, "lda:", lda, "shiftC:", shiftC, "ldc:", ldc,
"bc:", batch_count);
// quick return
if(!n || !m || !k || !batch_count)
return rocblas_status_success;
hipStream_t stream;
rocblas_get_stream(handle, &stream);
// determine limits and indices
bool left = (side == rocblas_side_left);
bool transpose = (trans != rocblas_operation_none);
rocblas_int start, step, nq, ncol, nrow;
if(left)
{
nq = m;
ncol = n;
if(!transpose)
{
start = -1;
step = 1;
}
else
{
start = k;
step = -1;
}
}
else
{
nq = n;
nrow = m;
if(!transpose)
{
start = k;
step = -1;
}
else
{
start = -1;
step = 1;
}
}
// conjugate tau
if(COMPLEX && transpose)
rocsolver_lacgv_template<T>(handle, k, ipiv, 0, 1, strideP, batch_count);
rocblas_int i;
for(rocblas_int j = 1; j <= k; ++j)
{
i = start + step * j; // current householder vector
if(left)
{
nrow = m - k + i + 1;
}
else
{
ncol = n - k + i + 1;
}
// insert one in A(nq-k+i,i), i.e. the i-th element of the (nq-k)-th
// subdiagonal, to build/apply the householder matrix
hipLaunchKernelGGL(set_diag<T>, dim3(batch_count, 1, 1), dim3(1, 1, 1), 0, stream, diag, 0,
1, A, shiftA + idx2D(nq - k + i, i, lda), lda, strideA, 1, true);
// Apply current Householder reflector
rocsolver_larf_template(handle, side, nrow, ncol, A, shiftA + idx2D(0, i, lda), 1, strideA,
(ipiv + i), strideP, C, shiftC, ldc, strideC, batch_count, scalars,
Abyx, workArr);
// restore original value of A(nq-k+i,i)
hipLaunchKernelGGL(restore_diag<T>, dim3(batch_count, 1, 1), dim3(1, 1, 1), 0, stream, diag,
0, 1, A, shiftA + idx2D(nq - k + i, i, lda), lda, strideA, 1);
}
// restore tau
if(COMPLEX && transpose)
rocsolver_lacgv_template<T>(handle, k, ipiv, 0, 1, strideP, batch_count);
return rocblas_status_success;
}
| 38.111111 | 100 | 0.45428 | YvanMokwinski |
4fa87be11855da78c6587ab7fcfc031daca74187 | 1,037 | cpp | C++ | tests/in_place.cpp | NathanSWard/optional | 71de89349f982e7a6dd02b87a5f3d083161f8eca | [
"CC0-1.0"
] | 2 | 2019-09-03T13:45:03.000Z | 2019-09-03T13:45:21.000Z | tests/in_place.cpp | e-schumann/optional | e165e3554c888e7969513e1c5cdf3d9ffce642f7 | [
"CC0-1.0"
] | null | null | null | tests/in_place.cpp | e-schumann/optional | e165e3554c888e7969513e1c5cdf3d9ffce642f7 | [
"CC0-1.0"
] | null | null | null | #include "catch.hpp"
#include <tl/optional.hpp>
#include <tuple>
#include <vector>
struct takes_init_and_variadic {
std::vector<int> v;
std::tuple<int, int> t;
template <class... Args>
takes_init_and_variadic(std::initializer_list<int> l, Args &&... args)
: v(l), t(std::forward<Args>(args)...) {}
};
TEST_CASE("In place", "[in_place]") {
tl::optional<int> o1{tl::in_place};
tl::optional<int> o2(tl::in_place);
REQUIRE(o1);
REQUIRE(o1 == 0);
REQUIRE(o2);
REQUIRE(o2 == 0);
tl::optional<int> o3(tl::in_place, 42);
REQUIRE(o3 == 42);
tl::optional<std::tuple<int, int>> o4(tl::in_place, 0, 1);
REQUIRE(o4);
REQUIRE(std::get<0>(*o4) == 0);
REQUIRE(std::get<1>(*o4) == 1);
tl::optional<std::vector<int>> o5(tl::in_place, {0, 1});
REQUIRE(o5);
REQUIRE((*o5)[0] == 0);
REQUIRE((*o5)[1] == 1);
tl::optional<takes_init_and_variadic> o6(tl::in_place, {0, 1}, 2, 3);
REQUIRE(o6->v[0] == 0);
REQUIRE(o6->v[1] == 1);
REQUIRE(std::get<0>(o6->t) == 2);
REQUIRE(std::get<1>(o6->t) == 3);
}
| 24.690476 | 72 | 0.594021 | NathanSWard |
4faea4ab3ce93c24e81efae27f6558f7c174b84b | 47,171 | cpp | C++ | src/bdap/linkmanager.cpp | AmirAbrams/dynamic-swap | a102b9750f023b8617dcb4447025503307812959 | [
"MIT"
] | 76 | 2017-04-06T13:58:15.000Z | 2022-01-04T16:36:58.000Z | src/bdap/linkmanager.cpp | AmirAbrams/dynamic-swap | a102b9750f023b8617dcb4447025503307812959 | [
"MIT"
] | 181 | 2016-11-19T21:09:35.000Z | 2021-08-21T02:57:23.000Z | src/bdap/linkmanager.cpp | duality-solutions/Dynamic-2 | 432c340140307340d1babced012d0de51dbf64ae | [
"MIT"
] | 61 | 2017-01-08T11:30:24.000Z | 2021-08-13T07:06:46.000Z | // Copyright (c) 2019-2021 Duality Blockchain Solutions Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bdap/linkmanager.h"
#include "bdap/domainentry.h"
#include "bdap/domainentrydb.h"
#include "bdap/linking.h"
#include "bdap/utils.h"
#include "bdap/vgp/include/encryption.h" // for VGP DecryptBDAPData
#include "dht/ed25519.h"
#include "pubkey.h"
#include "wallet/wallet.h"
CLinkManager* pLinkManager = NULL;
//#ifdef ENABLE_WALLET
std::string CLink::LinkState() const
{
if (nLinkState == 0) {
return "Unknown";
}
else if (nLinkState == 1) {
return "Pending";
}
else if (nLinkState == 2) {
return "Complete";
}
else if (nLinkState == 3) {
return "Deleted";
}
return "Undefined";
}
std::string CLink::ToString() const
{
return strprintf(
"CLink(\n"
" nVersion = %d\n"
" LinkID = %s\n"
" fRequestFromMe = %s\n"
" fAcceptFromMe = %s\n"
" LinkState = %s\n"
" RequestorFullObjectPath = %s\n"
" RecipientFullObjectPath = %s\n"
" RequestorPubKey = %s\n"
" RecipientPubKey = %s\n"
" SharedRequestPubKey = %s\n"
" SharedAcceptPubKey = %s\n"
" LinkMessage = %s\n"
" nHeightRequest = %d\n"
" nExpireTimeRequest = %d\n"
" txHashRequest = %s\n"
" nHeightAccept = %d\n"
" nExpireTimeAccept = %d\n"
" txHashAccept = %s\n"
" SubjectID = %s\n"
" RequestorWalletAddress = %s\n"
" RecipientWalletAddress = %s\n"
")\n",
nVersion,
LinkID.ToString(),
fRequestFromMe ? "true" : "false",
fAcceptFromMe ? "true" : "false",
LinkState(),
stringFromVch(RequestorFullObjectPath),
stringFromVch(RecipientFullObjectPath),
stringFromVch(RequestorPubKey),
stringFromVch(RecipientPubKey),
stringFromVch(SharedRequestPubKey),
stringFromVch(SharedAcceptPubKey),
stringFromVch(LinkMessage),
nHeightRequest,
nExpireTimeRequest,
txHashRequest.ToString(),
nHeightAccept,
nExpireTimeAccept,
txHashAccept.ToString(),
SubjectID.ToString(),
stringFromVch(RequestorWalletAddress),
stringFromVch(RecipientWalletAddress)
);
}
std::string CLink::RequestorFQDN() const
{
return stringFromVch(RequestorFullObjectPath);
}
std::string CLink::RecipientFQDN() const
{
return stringFromVch(RecipientFullObjectPath);
}
std::string CLink::RequestorPubKeyString() const
{
return stringFromVch(RequestorPubKey);
}
std::string CLink::RecipientPubKeyString() const
{
return stringFromVch(RecipientPubKey);
}
#ifdef ENABLE_WALLET
bool CLinkManager::IsLinkFromMe(const std::vector<unsigned char>& vchLinkPubKey)
{
if (!pwalletMain)
return false;
CKeyID keyID(Hash160(vchLinkPubKey.begin(), vchLinkPubKey.end()));
CKeyEd25519 keyOut;
if (pwalletMain->GetDHTKey(keyID, keyOut))
return true;
return false;
}
bool CLinkManager::IsLinkForMe(const std::vector<unsigned char>& vchLinkPubKey, const std::vector<unsigned char>& vchSharedPubKey)
{
if (!pwalletMain)
return false;
std::vector<std::vector<unsigned char>> vvchMyDHTPubKeys;
if (!pwalletMain->GetDHTPubKeys(vvchMyDHTPubKeys))
return false;
if (vvchMyDHTPubKeys.size() == 0)
return false;
for (const std::vector<unsigned char>& vchMyDHTPubKey : vvchMyDHTPubKeys) {
CKeyID keyID(Hash160(vchMyDHTPubKey.begin(), vchMyDHTPubKey.end()));
CKeyEd25519 dhtKey;
if (pwalletMain->GetDHTKey(keyID, dhtKey)) {
std::vector<unsigned char> vchGetSharedPubKey = GetLinkSharedPubKey(dhtKey, vchLinkPubKey);
if (vchGetSharedPubKey == vchSharedPubKey)
return true;
}
}
return false;
}
bool CLinkManager::GetLinkPrivateKey(const std::vector<unsigned char>& vchSenderPubKey, const std::vector<unsigned char>& vchSharedPubKey, std::array<char, 32>& sharedSeed, std::string& strErrorMessage)
{
if (!pwalletMain)
return false;
std::vector<std::vector<unsigned char>> vvchDHTPubKeys;
if (!pwalletMain->GetDHTPubKeys(vvchDHTPubKeys)) {
strErrorMessage = "Failed to get DHT key vector.";
return false;
}
// loop through each account key to check if it matches the shared key
for (const std::vector<unsigned char>& vchPubKey : vvchDHTPubKeys) {
CDomainEntry entry;
if (pDomainEntryDB->ReadDomainEntryPubKey(vchPubKey, entry)) {
CKeyEd25519 dhtKey;
CKeyID keyID(Hash160(vchPubKey.begin(), vchPubKey.end()));
if (pwalletMain->GetDHTKey(keyID, dhtKey)) {
if (vchSharedPubKey == GetLinkSharedPubKey(dhtKey, vchSenderPubKey)) {
sharedSeed = GetLinkSharedPrivateKey(dhtKey, vchSenderPubKey);
return true;
}
}
else {
strErrorMessage = strErrorMessage + "Error getting DHT private key.\n";
}
}
}
return false;
}
#endif // ENABLE_WALLET
bool CLinkManager::FindLink(const uint256& id, CLink& link)
{
if (m_Links.count(id) > 0) {
link = m_Links.at(id);
return true;
}
return false;
}
bool CLinkManager::FindLinkBySubjectID(const uint256& subjectID, CLink& getLink)
{
for (const std::pair<uint256, CLink>& link : m_Links)
{
if (link.second.SubjectID == subjectID) // pending request
{
getLink = link.second;
return true;
}
}
return false;
}
#ifdef ENABLE_WALLET
void CLinkManager::ProcessQueue()
{
if (!pwalletMain)
return;
if (pwalletMain->IsLocked())
return;
// make sure we are not stuck in an infinite loop
size_t size = QueueSize();
size_t counter = 0;
LogPrintf("CLinkManager::%s -- Start links in queue = %d\n", __func__, size);
while (!linkQueue.empty() && size > counter)
{
// TODO (BDAP): Do we need to lock the queue while processing?
CLinkStorage storage = linkQueue.front();
ProcessLink(storage);
linkQueue.pop();
counter++;
}
LogPrintf("CLinkManager::%s -- Finished links in queue = %d\n", __func__, QueueSize());
}
#else
void CLinkManager::ProcessQueue()
{
return;
}
#endif // ENABLE_WALLET
bool CLinkManager::ListMyPendingRequests(std::vector<CLink>& vchLinks)
{
for (const std::pair<uint256, CLink>& link : m_Links)
{
if (link.second.nLinkState == 1 && link.second.fRequestFromMe) // pending request
{
vchLinks.push_back(link.second);
}
}
return true;
}
bool CLinkManager::ListMyPendingAccepts(std::vector<CLink>& vchLinks)
{
for (const std::pair<uint256, CLink>& link : m_Links)
{
//LogPrintf("%s -- link:\n%s\n", __func__, link.second.ToString());
if (link.second.nLinkState == 1 && (!link.second.fRequestFromMe || (link.second.fRequestFromMe && link.second.fAcceptFromMe))) // pending accept
{
vchLinks.push_back(link.second);
}
}
return true;
}
bool CLinkManager::ListMyCompleted(std::vector<CLink>& vchLinks)
{
for (const std::pair<uint256, CLink>& link : m_Links)
{
if (link.second.nLinkState == 2 && !link.second.txHashRequest.IsNull()) // completed link
{
vchLinks.push_back(link.second);
}
}
return true;
}
bool CLinkManager::ProcessLink(const CLinkStorage& storage, const bool fStoreInQueueOnly)
{
#ifndef ENABLE_WALLET
linkQueue.push(storage);
return true;
#else
if (!pwalletMain) {
linkQueue.push(storage);
return true;
}
if (fStoreInQueueOnly || pwalletMain->IsLocked()) {
linkQueue.push(storage);
return true;
}
int nDataVersion = -1;
if (!storage.Encrypted())
{
if (storage.nType == 1) // Clear text link request
{
std::vector<unsigned char> vchData = RemoveVersionFromLinkData(storage.vchRawData, nDataVersion);
CLinkRequest link(vchData, storage.txHash);
LogPrint("bdap", "%s -- %s\n", __func__, link.ToString());
link.nHeight = storage.nHeight;
link.txHash = storage.txHash;
link.nExpireTime = storage.nExpireTime;
CDomainEntry entry;
if (GetDomainEntry(link.RequestorFullObjectPath, entry)) {
if (SignatureProofIsValid(entry.GetWalletAddress(), link.RecipientFQDN(), link.SignatureProof)) {
bool fIsLinkFromMe = IsLinkFromMe(storage.vchLinkPubKey);
LogPrint("bdap", "%s -- Link request from me found with a valid signature proof. Link requestor = %s, recipient = %s, pubkey = %s\n", __func__, link.RequestorFQDN(), link.RecipientFQDN(), stringFromVch(storage.vchLinkPubKey));
uint256 linkID = GetLinkID(link);
CLink record;
std::map<uint256, CLink>::iterator it = m_Links.find(linkID);
if (it != m_Links.end()) {
record = it->second;
}
record.LinkID = linkID;
record.fRequestFromMe = fIsLinkFromMe;
if (record.nHeightAccept > 0) {
record.nLinkState = 2;
}
else {
record.nLinkState = 1;
}
record.RequestorFullObjectPath = link.RequestorFullObjectPath;
record.RecipientFullObjectPath = link.RecipientFullObjectPath;
record.RequestorPubKey = link.RequestorPubKey;
record.SharedRequestPubKey = link.SharedPubKey;
record.LinkMessage = link.LinkMessage;
record.nHeightRequest = link.nHeight;
record.nExpireTimeRequest = link.nExpireTime;
record.txHashRequest = link.txHash;
record.RequestorWalletAddress = entry.WalletAddress;
if (record.SharedAcceptPubKey.size() > 0 && record.SharedRequestPubKey.size() > 0)
{
std::string strErrorMessage = "";
if (!GetMessageInfo(record, strErrorMessage))
{
LogPrintf("%s -- Error getting message info %s\n", __func__, strErrorMessage);
}
else
{
pwalletMain->WriteLinkMessageInfo(record.SubjectID, record.vchSecretPubKeyBytes);
m_LinkMessageInfo[record.SubjectID] = record.vchSecretPubKeyBytes;
}
//LogPrintf("%s -- link request = %s\n", __func__, record.ToString());
}
LogPrint("bdap", "%s -- Clear text link request added to map id = %s\n", __func__, linkID.ToString());
m_Links[linkID] = record;
}
else
LogPrintf("%s ***** Warning. Link request found with an invalid signature proof! Link requestor = %s, recipient = %s, pubkey = %s\n", __func__, link.RequestorFQDN(), link.RecipientFQDN(), stringFromVch(storage.vchLinkPubKey));
}
else {
LogPrintf("%s -- Link request GetDomainEntry failed.\n", __func__);
return false;
}
}
else if (storage.nType == 2) // Clear text accept
{
std::vector<unsigned char> vchData = RemoveVersionFromLinkData(storage.vchRawData, nDataVersion);
CLinkAccept link(vchData, storage.txHash);
LogPrint("bdap", "%s -- %s\n", __func__, link.ToString());
link.nHeight = storage.nHeight;
link.txHash = storage.txHash;
link.nExpireTime = storage.nExpireTime;
CDomainEntry entry;
if (GetDomainEntry(link.RecipientFullObjectPath, entry)) {
if (SignatureProofIsValid(entry.GetWalletAddress(), link.RequestorFQDN(), link.SignatureProof)) {
bool fIsLinkFromMe = IsLinkFromMe(storage.vchLinkPubKey);
//bool fIsLinkForMe = IsLinkForMe(storage.vchLinkPubKey, storage.vchSharedPubKey);
LogPrint("bdap", "%s -- Link accept from me found with a valid signature proof. Link requestor = %s, recipient = %s, pubkey = %s\n", __func__, link.RequestorFQDN(), link.RecipientFQDN(), stringFromVch(storage.vchLinkPubKey));
uint256 linkID = GetLinkID(link);
CLink record;
std::map<uint256, CLink>::iterator it = m_Links.find(linkID);
if (it != m_Links.end()) {
record = it->second;
}
record.LinkID = linkID;
record.fAcceptFromMe = fIsLinkFromMe;
record.nLinkState = 2;
record.RequestorFullObjectPath = link.RequestorFullObjectPath;
record.RecipientFullObjectPath = link.RecipientFullObjectPath;
record.RecipientPubKey = link.RecipientPubKey;
record.SharedAcceptPubKey = link.SharedPubKey;
record.nHeightAccept = link.nHeight;
record.nExpireTimeAccept = link.nExpireTime;
record.txHashAccept = link.txHash;
record.RecipientWalletAddress = entry.WalletAddress;
if (record.SharedAcceptPubKey.size() > 0 && record.SharedRequestPubKey.size() > 0)
{
std::string strErrorMessage = "";
if (!GetMessageInfo(record, strErrorMessage))
{
LogPrintf("%s -- Error getting message info %s\n", __func__, strErrorMessage);
}
else
{
pwalletMain->WriteLinkMessageInfo(record.SubjectID, record.vchSecretPubKeyBytes);
m_LinkMessageInfo[record.SubjectID] = record.vchSecretPubKeyBytes;
}
//LogPrintf("%s -- link accept = %s\n", __func__, record.ToString());
}
LogPrint("bdap", "%s -- Clear text accept added to map id = %s, %s\n", __func__, linkID.ToString(), record.ToString());
m_Links[linkID] = record;
}
else
LogPrintf("%s -- Warning! Link accept found with an invalid signature proof! Link requestor = %s, recipient = %s, pubkey = %s\n", __func__, link.RequestorFQDN(), link.RecipientFQDN(), stringFromVch(storage.vchLinkPubKey));
}
else {
LogPrintf("%s -- Link accept GetDomainEntry failed.\n", __func__);
return false;
}
}
}
else if (storage.Encrypted() && !pwalletMain->IsLocked())
{
bool fIsLinkFromMe = IsLinkFromMe(storage.vchLinkPubKey);
bool fIsLinkForMe = IsLinkForMe(storage.vchLinkPubKey, storage.vchSharedPubKey);
if (!fIsLinkFromMe && !fIsLinkForMe) {
// This happens if you lose your DHT private key but have the BDAP account link wallet private key.
LogPrintf("%s -- ** Warning: Encrypted link received but can not process it: TxID = %s\n", __func__, storage.txHash.ToString());
return false;
}
if (storage.nType == 1 && fIsLinkFromMe) // Encrypted link request from me
{
//LogPrintf("%s -- Version 1 link request from me found! vchLinkPubKey = %s\n", __func__, stringFromVch(storage.vchLinkPubKey));
CKeyEd25519 privDHTKey;
CKeyID keyID(Hash160(storage.vchLinkPubKey.begin(), storage.vchLinkPubKey.end()));
if (pwalletMain->GetDHTKey(keyID, privDHTKey)) {
std::vector<unsigned char> vchData = RemoveVersionFromLinkData(storage.vchRawData, nDataVersion);
std::string strMessage = "";
std::vector<unsigned char> dataDecrypted;
if (DecryptBDAPData(privDHTKey.GetPrivSeedBytes(), vchData, dataDecrypted, strMessage)) {
std::vector<unsigned char> vchData, vchHash;
CScript scriptData;
scriptData << OP_RETURN << dataDecrypted;
if (GetBDAPData(scriptData, vchData, vchHash)) {
CLinkRequest link(dataDecrypted, storage.txHash);
LogPrint("bdap", "%s -- %s\n", __func__, link.ToString());
CDomainEntry entry;
if (!GetDomainEntry(link.RequestorFullObjectPath, entry)) {
LogPrintf("%s -- Failed to get link requestor %s\n", __func__, stringFromVch(link.RequestorFullObjectPath));
return false;
}
if (!SignatureProofIsValid(entry.GetWalletAddress(), link.RecipientFQDN(), link.SignatureProof)) {
LogPrintf("%s ***** Warning. Link request found with an invalid signature proof! Link requestor = %s, recipient = %s, pubkey = %s\n", __func__, link.RequestorFQDN(), link.RecipientFQDN(), stringFromVch(storage.vchLinkPubKey));
return false;
}
link.nHeight = storage.nHeight;
link.nExpireTime = storage.nExpireTime;
uint256 linkID = GetLinkID(link);
CLink record;
std::map<uint256, CLink>::iterator it = m_Links.find(linkID);
if (it != m_Links.end()) {
record = it->second;
}
record.LinkID = linkID;
record.fRequestFromMe = fIsLinkFromMe;
record.fAcceptFromMe = (fIsLinkFromMe && fIsLinkForMe);
if (record.nHeightAccept > 0) {
record.nLinkState = 2;
}
else {
record.nLinkState = 1;
}
record.RequestorFullObjectPath = link.RequestorFullObjectPath;
record.RecipientFullObjectPath = link.RecipientFullObjectPath;
record.RequestorPubKey = link.RequestorPubKey;
record.SharedRequestPubKey = link.SharedPubKey;
record.LinkMessage = link.LinkMessage;
record.nHeightRequest = link.nHeight;
record.nExpireTimeRequest = link.nExpireTime;
record.txHashRequest = link.txHash;
record.RequestorWalletAddress = entry.WalletAddress;
if (record.SharedAcceptPubKey.size() > 0 && record.SharedRequestPubKey.size() > 0)
{
std::string strErrorMessage = "";
if (!GetMessageInfo(record, strErrorMessage))
{
LogPrintf("%s -- Error getting message info %s\n", __func__, strErrorMessage);
}
else
{
pwalletMain->WriteLinkMessageInfo(record.SubjectID, record.vchSecretPubKeyBytes);
m_LinkMessageInfo[record.SubjectID] = record.vchSecretPubKeyBytes;
}
//LogPrintf("%s -- link request = %s\n", __func__, record.ToString());
}
LogPrint("bdap", "%s -- Encrypted link request from me added to map id = %s\n%s\n", __func__, linkID.ToString(), record.ToString());
m_Links[linkID] = record;
}
else {
LogPrintf("%s -- Link request GetBDAPData failed.\n", __func__);
return false;
}
}
else {
LogPrintf("%s -- Link request DecryptBDAPData failed.\n", __func__);
return false;
}
}
else {
LogPrintf("%s -- Link request GetDHTKey failed.\n", __func__);
return false;
}
}
else if (storage.nType == 1 && !fIsLinkFromMe && fIsLinkForMe) // Encrypted link request for me
{
//LogPrintf("%s -- Version 1 link request for me found! vchLinkPubKey = %s\n", __func__, stringFromVch(storage.vchLinkPubKey));
CKeyEd25519 sharedDHTKey;
std::array<char, 32> sharedSeed;
std::string strErrorMessage;
if (GetLinkPrivateKey(storage.vchLinkPubKey, storage.vchSharedPubKey, sharedSeed, strErrorMessage)) {
CKeyEd25519 sharedKey(sharedSeed);
std::vector<unsigned char> vchData = RemoveVersionFromLinkData(storage.vchRawData, nDataVersion);
std::string strMessage = "";
std::vector<unsigned char> dataDecrypted;
if (DecryptBDAPData(sharedKey.GetPrivSeedBytes(), vchData, dataDecrypted, strMessage)) {
std::vector<unsigned char> vchData, vchHash;
CScript scriptData;
scriptData << OP_RETURN << dataDecrypted;
if (GetBDAPData(scriptData, vchData, vchHash)) {
CLinkRequest link(dataDecrypted, storage.txHash);
LogPrint("bdap", "%s -- %s\n", __func__, link.ToString());
CDomainEntry entry;
if (!GetDomainEntry(link.RequestorFullObjectPath, entry)) {
LogPrintf("%s -- Failed to get link requestor %s\n", __func__, stringFromVch(link.RequestorFullObjectPath));
return false;
}
if (!SignatureProofIsValid(entry.GetWalletAddress(), link.RecipientFQDN(), link.SignatureProof)) {
LogPrintf("%s ***** Warning. Link request found with an invalid signature proof! Link requestor = %s, recipient = %s, pubkey = %s\n", __func__, link.RequestorFQDN(), link.RecipientFQDN(), stringFromVch(storage.vchLinkPubKey));
return false;
}
link.nHeight = storage.nHeight;
link.nExpireTime = storage.nExpireTime;
uint256 linkID = GetLinkID(link);
CLink record;
std::map<uint256, CLink>::iterator it = m_Links.find(linkID);
if (it != m_Links.end()) {
record = it->second;
}
record.LinkID = linkID;
record.fRequestFromMe = fIsLinkFromMe;
if (record.nHeightAccept > 0) {
record.nLinkState = 2;
}
else {
record.nLinkState = 1;
}
record.RequestorFullObjectPath = link.RequestorFullObjectPath;
record.RecipientFullObjectPath = link.RecipientFullObjectPath;
record.RequestorPubKey = link.RequestorPubKey;
record.SharedRequestPubKey = link.SharedPubKey;
record.LinkMessage = link.LinkMessage;
record.nHeightRequest = link.nHeight;
record.nExpireTimeRequest = link.nExpireTime;
record.txHashRequest = link.txHash;
record.RequestorWalletAddress = entry.WalletAddress;
if (record.SharedAcceptPubKey.size() > 0 && record.SharedRequestPubKey.size() > 0)
{
std::string strErrorMessage = "";
if (!GetMessageInfo(record, strErrorMessage))
{
LogPrintf("%s -- Error getting message info %s\n", __func__, strErrorMessage);
}
else
{
pwalletMain->WriteLinkMessageInfo(record.SubjectID, record.vchSecretPubKeyBytes);
m_LinkMessageInfo[record.SubjectID] = record.vchSecretPubKeyBytes;
}
//LogPrintf("%s -- link request = %s\n", __func__, record.ToString());
}
LogPrint("bdap", "%s -- Encrypted link request for me added to map id = %s\n%s\n", __func__, linkID.ToString(), record.ToString());
m_Links[linkID] = record;
}
else {
LogPrintf("%s -- Link request GetBDAPData failed.\n", __func__);
return false;
}
}
else {
LogPrintf("%s -- Link request DecryptBDAPData failed.\n", __func__);
return false;
}
}
else {
LogPrintf("%s -- Link request GetLinkPrivateKey failed.\n", __func__);
return false;
}
}
else if (storage.nType == 2 && fIsLinkFromMe) // Link accept from me
{
//LogPrintf("%s -- Version 1 encrypted link accept from me found! vchLinkPubKey = %s\n", __func__, stringFromVch(storage.vchLinkPubKey));
CKeyEd25519 privDHTKey;
CKeyID keyID(Hash160(storage.vchLinkPubKey.begin(), storage.vchLinkPubKey.end()));
if (pwalletMain->GetDHTKey(keyID, privDHTKey)) {
std::vector<unsigned char> vchData = RemoveVersionFromLinkData(storage.vchRawData, nDataVersion);
std::string strMessage = "";
std::vector<unsigned char> dataDecrypted;
if (DecryptBDAPData(privDHTKey.GetPrivSeedBytes(), vchData, dataDecrypted, strMessage)) {
std::vector<unsigned char> vchData, vchHash;
CScript scriptData;
scriptData << OP_RETURN << dataDecrypted;
if (GetBDAPData(scriptData, vchData, vchHash)) {
CLinkAccept link(dataDecrypted, storage.txHash);
LogPrint("bdap", "%s -- %s\n", __func__, link.ToString());
CDomainEntry entry;
if (!GetDomainEntry(link.RecipientFullObjectPath, entry)) {
LogPrintf("%s -- Failed to get link recipient %s\n", __func__, stringFromVch(link.RecipientFullObjectPath));
return false;
}
if (!SignatureProofIsValid(entry.GetWalletAddress(), link.RequestorFQDN(), link.SignatureProof)) {
LogPrintf("%s ***** Warning. Link accept found with an invalid signature proof! Link requestor = %s, recipient = %s, pubkey = %s\n", __func__, link.RequestorFQDN(), link.RecipientFQDN(), stringFromVch(storage.vchLinkPubKey));
return false;
}
link.nHeight = storage.nHeight;
link.nExpireTime = storage.nExpireTime;
uint256 linkID = GetLinkID(link);
CLink record;
std::map<uint256, CLink>::iterator it = m_Links.find(linkID);
if (it != m_Links.end()) {
record = it->second;
}
record.LinkID = linkID;
record.fRequestFromMe = (fIsLinkFromMe && fIsLinkForMe);
record.fAcceptFromMe = fIsLinkFromMe;
record.nLinkState = 2;
record.RequestorFullObjectPath = link.RequestorFullObjectPath;
record.RecipientFullObjectPath = link.RecipientFullObjectPath;
record.RecipientPubKey = link.RecipientPubKey;
record.SharedAcceptPubKey = link.SharedPubKey;
record.nHeightAccept = link.nHeight;
record.nExpireTimeAccept = link.nExpireTime;
record.txHashAccept = link.txHash;
record.RecipientWalletAddress = entry.WalletAddress;
if (record.SharedAcceptPubKey.size() > 0 && record.SharedRequestPubKey.size() > 0)
{
std::string strErrorMessage = "";
if (!GetMessageInfo(record, strErrorMessage))
{
LogPrintf("%s -- Error getting message info %s\n", __func__, strErrorMessage);
}
else
{
pwalletMain->WriteLinkMessageInfo(record.SubjectID, record.vchSecretPubKeyBytes);
m_LinkMessageInfo[record.SubjectID] = record.vchSecretPubKeyBytes;
}
//LogPrintf("%s -- accept request = %s\n", __func__, record.ToString());
}
LogPrint("bdap", "%s -- Encrypted link accept from me added to map id = %s\n%s\n", __func__, linkID.ToString(), record.ToString());
m_Links[linkID] = record;
}
else {
LogPrintf("%s -- Link accept GetBDAPData failed.\n", __func__);
return false;
}
}
else {
LogPrintf("%s -- Link accept DecryptBDAPData failed.\n", __func__);
return false;
}
}
else {
LogPrintf("%s -- Link accept GetDHTKey failed.\n", __func__);
return false;
}
}
else if (storage.nType == 2 && !fIsLinkFromMe && fIsLinkForMe) // Link accept for me
{
//LogPrintf("%s -- Version 1 link accept for me found! vchLinkPubKey = %s\n", __func__, stringFromVch(storage.vchLinkPubKey));
CKeyEd25519 sharedDHTKey;
std::array<char, 32> sharedSeed;
std::string strErrorMessage;
if (GetLinkPrivateKey(storage.vchLinkPubKey, storage.vchSharedPubKey, sharedSeed, strErrorMessage)) {
CKeyEd25519 sharedKey(sharedSeed);
std::vector<unsigned char> vchData = RemoveVersionFromLinkData(storage.vchRawData, nDataVersion);
std::string strMessage = "";
std::vector<unsigned char> dataDecrypted;
if (DecryptBDAPData(sharedKey.GetPrivSeedBytes(), vchData, dataDecrypted, strMessage)) {
std::vector<unsigned char> vchData, vchHash;
CScript scriptData;
scriptData << OP_RETURN << dataDecrypted;
if (GetBDAPData(scriptData, vchData, vchHash)) {
CLinkAccept link(dataDecrypted, storage.txHash);
LogPrint("bdap", "%s -- %s\n", __func__, link.ToString());
CDomainEntry entry;
if (!GetDomainEntry(link.RecipientFullObjectPath, entry)) {
LogPrintf("%s -- Failed to get link recipient %s\n", __func__, stringFromVch(link.RecipientFullObjectPath));
return false;
}
if (!SignatureProofIsValid(entry.GetWalletAddress(), link.RequestorFQDN(), link.SignatureProof)) {
LogPrintf("%s ***** Warning. Link accept found with an invalid signature proof! Link requestor = %s, recipient = %s, pubkey = %s\n", __func__, link.RequestorFQDN(), link.RecipientFQDN(), stringFromVch(storage.vchLinkPubKey));
return false;
}
link.nHeight = storage.nHeight;
link.nExpireTime = storage.nExpireTime;
uint256 linkID = GetLinkID(link);
CLink record;
std::map<uint256, CLink>::iterator it = m_Links.find(linkID);
if (it != m_Links.end()) {
record = it->second;
}
record.LinkID = linkID;
record.fAcceptFromMe = fIsLinkFromMe;
record.nLinkState = 2;
record.RequestorFullObjectPath = link.RequestorFullObjectPath;
record.RecipientFullObjectPath = link.RecipientFullObjectPath;
record.RecipientPubKey = link.RecipientPubKey;
record.SharedAcceptPubKey = link.SharedPubKey;
record.nHeightAccept = link.nHeight;
record.nExpireTimeAccept = link.nExpireTime;
record.txHashAccept = link.txHash;
record.RecipientWalletAddress = entry.WalletAddress;
if (record.SharedAcceptPubKey.size() > 0 && record.SharedRequestPubKey.size() > 0)
{
std::string strErrorMessage = "";
if (!GetMessageInfo(record, strErrorMessage))
{
LogPrintf("%s -- Error getting message info %s\n", __func__, strErrorMessage);
}
else
{
pwalletMain->WriteLinkMessageInfo(record.SubjectID, record.vchSecretPubKeyBytes);
m_LinkMessageInfo[record.SubjectID] = record.vchSecretPubKeyBytes;
}
//LogPrintf("%s -- accept request = %s\n", __func__, record.ToString());
}
LogPrint("bdap", "%s -- Encrypted link accept for me added to map id = %s\n%s\n", __func__, linkID.ToString(), record.ToString());
m_Links[linkID] = record;
}
else {
LogPrintf("%s -- Link accept GetBDAPData failed.\n", __func__);
return false;
}
}
else {
LogPrintf("%s -- Link accept DecryptBDAPData failed.\n", __func__);
return false;
}
}
else {
LogPrintf("%s -- Link accept GetLinkPrivateKey failed.\n", __func__);
return false;
}
}
else
{
linkQueue.push(storage);
}
}
return true;
#endif // ENABLE_WALLET
}
std::vector<CLinkInfo> CLinkManager::GetCompletedLinkInfo(const std::vector<unsigned char>& vchFullObjectPath)
{
std::vector<CLinkInfo> vchLinkInfo;
for(const std::pair<uint256, CLink>& link : m_Links)
{
if (link.second.nLinkState == 2) // completed link
{
if (link.second.RequestorFullObjectPath == vchFullObjectPath)
{
CLinkInfo linkInfo(link.second.RecipientFullObjectPath, link.second.RecipientPubKey, link.second.RequestorPubKey);
vchLinkInfo.push_back(linkInfo);
}
else if (link.second.RecipientFullObjectPath == vchFullObjectPath)
{
CLinkInfo linkInfo(link.second.RequestorFullObjectPath, link.second.RequestorPubKey, link.second.RecipientPubKey);
vchLinkInfo.push_back(linkInfo);
}
}
}
return vchLinkInfo;
}
int CLinkManager::IsMyMessage(const uint256& subjectID, const uint256& messageID, const int64_t& timestamp)
{
std::vector<unsigned char> vchPubKey;
if (GetLinkMessageInfo(subjectID, vchPubKey))
{
if (messageID != GetMessageID(vchPubKey, timestamp))
{
// Incorrect message id. Might be spoofed.
return -100;
}
return 1;
}
return 0;
}
void CLinkManager::LoadLinkMessageInfo(const uint256& subjectID, const std::vector<unsigned char>& vchPubKey)
{
if (m_LinkMessageInfo.count(subjectID) == 0)
m_LinkMessageInfo[subjectID] = vchPubKey;
}
bool CLinkManager::GetLinkMessageInfo(const uint256& subjectID, std::vector<unsigned char>& vchPubKey)
{
std::map<uint256, std::vector<unsigned char>>::iterator it = m_LinkMessageInfo.find(subjectID);
if (it != m_LinkMessageInfo.end()) {
vchPubKey = it->second;
return true; // found subjectID
}
return false; // doesn't exist
}
uint256 GetLinkID(const CLinkRequest& request)
{
std::vector<unsigned char> vchLinkPath = request.LinkPath();
return Hash(vchLinkPath.begin(), vchLinkPath.end());
}
uint256 GetLinkID(const CLinkAccept& accept)
{
std::vector<unsigned char> vchLinkPath = accept.LinkPath();
return Hash(vchLinkPath.begin(), vchLinkPath.end());
}
uint256 GetLinkID(const std::string& account1, const std::string& account2)
{
if (account1 != account2) {
std::vector<unsigned char> vchSeparator = {':'};
std::set<std::string> sorted;
sorted.insert(account1);
sorted.insert(account2);
std::set<std::string>::iterator it = sorted.begin();
std::vector<unsigned char> vchLink1 = vchFromString(*it);
std::advance(it, 1);
std::vector<unsigned char> vchLink2 = vchFromString(*it);
vchLink1.insert(vchLink1.end(), vchSeparator.begin(), vchSeparator.end());
vchLink1.insert(vchLink1.end(), vchLink2.begin(), vchLink2.end());
return Hash(vchLink1.begin(), vchLink1.end());
}
return uint256();
}
#ifdef ENABLE_WALLET
bool GetSharedPrivateSeed(const CLink& link, std::array<char, 32>& seed, std::string& strErrorMessage)
{
if (!pwalletMain)
return false;
if (link.nLinkState != 2)
return false;
//LogPrint("bdap", "%s -- %s\n", __func__, link.ToString());
std::array<char, 32> sharedSeed1;
std::array<char, 32> sharedSeed2;
CDomainEntry entry;
if (pDomainEntryDB->GetDomainEntryInfo(link.RecipientFullObjectPath, entry)) {
if (link.fRequestFromMe) // Requestor
{
// first key exchange: requestor link pubkey + recipient account pubkey
std::vector<unsigned char> vchRecipientPubKey = entry.DHTPublicKey;
std::vector<unsigned char> vchRequestorPubKey = link.RequestorPubKey;
CKeyEd25519 reqKey;
CKeyID reqKeyID(Hash160(vchRequestorPubKey.begin(), vchRequestorPubKey.end()));
if (pwalletMain->GetDHTKey(reqKeyID, reqKey)) {
std::vector<unsigned char> vchGetLinkSharedPubKey = GetLinkSharedPubKey(reqKey, vchRecipientPubKey);
if (link.SharedRequestPubKey == vchGetLinkSharedPubKey)
{
sharedSeed1 = GetLinkSharedPrivateKey(reqKey, vchRecipientPubKey);
}
else
{
strErrorMessage = strprintf("Requestor SharedRequestPubKey (%s) does not match derived shared request public key (%s).",
stringFromVch(link.SharedRequestPubKey), stringFromVch(vchGetLinkSharedPubKey));
return false;
}
}
else {
strErrorMessage = strprintf("Failed to get reqKey %s DHT private key.", stringFromVch(vchRequestorPubKey));
return false;
}
// second key exchange: recipient link pubkey + requestor account pubkey
CDomainEntry entryRequestor;
if (pDomainEntryDB->GetDomainEntryInfo(link.RequestorFullObjectPath, entryRequestor))
{
std::vector<unsigned char> vchReqPubKey = entryRequestor.DHTPublicKey;
std::vector<unsigned char> vchLinkPubKey = link.RecipientPubKey;
CKeyEd25519 linkKey;
CKeyID linkKeyID(Hash160(vchReqPubKey.begin(), vchReqPubKey.end()));
if (pwalletMain->GetDHTKey(linkKeyID, linkKey)) {
std::vector<unsigned char> vchGetLinkSharedPubKey = GetLinkSharedPubKey(linkKey, vchLinkPubKey);
if (link.SharedAcceptPubKey == vchGetLinkSharedPubKey)
{
sharedSeed2 = GetLinkSharedPrivateKey(linkKey, vchLinkPubKey);
}
else
{
strErrorMessage = strprintf("Requestor SharedAcceptPubKey (%s) does not match derived shared link public key (%s).",
stringFromVch(link.SharedAcceptPubKey), stringFromVch(vchGetLinkSharedPubKey));
return false;
}
}
else {
strErrorMessage = strprintf("Failed to get requestor link Key %s DHT private key.", stringFromVch(vchLinkPubKey));
return false;
}
}
else
{
strErrorMessage = strprintf("Can not find %s link requestor record.", stringFromVch(link.RequestorFullObjectPath));
return false;
}
}
else // Recipient
{
// first key exchange: requestor link pubkey + recipient account pubkey
std::vector<unsigned char> vchRecipientPubKey = entry.DHTPublicKey;
std::vector<unsigned char> vchRequestorPubKey = link.RequestorPubKey;
CKeyEd25519 recKey;
CKeyID recKeyID(Hash160(vchRecipientPubKey.begin(), vchRecipientPubKey.end()));
if (pwalletMain->GetDHTKey(recKeyID, recKey))
{
std::vector<unsigned char> vchGetLinkSharedPubKey = GetLinkSharedPubKey(recKey, vchRequestorPubKey);
if (link.SharedRequestPubKey == vchGetLinkSharedPubKey) {
sharedSeed1 = GetLinkSharedPrivateKey(recKey, vchRequestorPubKey);
}
else
{
strErrorMessage = strprintf("Recipient SharedRequestPubKey (%s) does not match derived shared request public key (%s).",
stringFromVch(link.SharedRequestPubKey), stringFromVch(vchGetLinkSharedPubKey));
return false;
}
}
else {
strErrorMessage = strprintf("Failed to get recKey %s DHT private key.", stringFromVch(vchRecipientPubKey));
return false;
}
// second key exchange: recipient link pubkey + requestor account pubkey
CDomainEntry entryRequestor;
if (pDomainEntryDB->GetDomainEntryInfo(link.RequestorFullObjectPath, entryRequestor))
{
std::vector<unsigned char> vchLinkPubKey = link.RecipientPubKey;
std::vector<unsigned char> vchReqPubKey = entryRequestor.DHTPublicKey;
CKeyEd25519 linkKey;
CKeyID linkKeyID(Hash160(vchLinkPubKey.begin(), vchLinkPubKey.end()));
if (pwalletMain->GetDHTKey(linkKeyID, linkKey))
{
std::vector<unsigned char> vchGetLinkSharedPubKey = GetLinkSharedPubKey(linkKey, vchReqPubKey);
if (link.SharedAcceptPubKey == vchGetLinkSharedPubKey) {
sharedSeed2 = GetLinkSharedPrivateKey(linkKey, vchReqPubKey);
}
else
{
strErrorMessage = strprintf("Recipient SharedAcceptPubKey (%s) does not match derived shared link public key (%s).",
stringFromVch(link.SharedAcceptPubKey), stringFromVch(vchGetLinkSharedPubKey));
return false;
}
}
else {
strErrorMessage = strprintf("Failed to get recipient linkKey %s DHT private key.", stringFromVch(vchLinkPubKey));
return false;
}
}
else
{
strErrorMessage = strprintf("Can not find %s link requestor record.", stringFromVch(link.RequestorFullObjectPath));
return false;
}
}
}
else
{
strErrorMessage = strprintf("Can not find %s link recipient record.", stringFromVch(link.RecipientFullObjectPath));
return false;
}
CKeyEd25519 sharedKey1(sharedSeed1);
CKeyEd25519 sharedKey2(sharedSeed2);
// third key exchange: shared link request pubkey + shared link accept pubkey
// Only the link recipient and requestor can derive this secret key.
// the third shared public key is not on the blockchain and should only be known by the participants.
seed = GetLinkSharedPrivateKey(sharedKey1, sharedKey2.GetPubKey());
return true;
}
bool GetMessageInfo(CLink& link, std::string& strErrorMessage)
{
std::array<char, 32> seed;
if (!GetSharedPrivateSeed(link, seed, strErrorMessage))
{
return false;
}
CKeyEd25519 key(seed);
link.vchSecretPubKeyBytes = key.GetPubKeyBytes();
link.SubjectID = Hash(link.vchSecretPubKeyBytes.begin(), link.vchSecretPubKeyBytes.end());
return true;
}
#endif // ENABLE_WALLET
uint256 GetMessageID(const std::vector<unsigned char>& vchPubKey, const int64_t& timestamp)
{
CScript scriptMessage;
scriptMessage << vchPubKey << timestamp;
return Hash(scriptMessage.begin(), scriptMessage.end());
}
uint256 GetMessageID(const CKeyEd25519& key, const int64_t& timestamp)
{
return GetMessageID(key.GetPubKeyBytes(), timestamp);
}
//#endif // ENABLE_WALLET | 47.265531 | 254 | 0.545271 | AmirAbrams |
4fb200e44ebaa6efdcfc1efaec83b8ffcc78b838 | 2,997 | hpp | C++ | examples/record_printer/client_hello_record.hpp | pioneer19/libcornet | 9eb91629d8f9a6793b28af10a3535bfba0cc24ca | [
"Apache-2.0"
] | 1 | 2020-07-25T06:39:24.000Z | 2020-07-25T06:39:24.000Z | examples/record_printer/client_hello_record.hpp | pioneer19/libcornet | 9eb91629d8f9a6793b28af10a3535bfba0cc24ca | [
"Apache-2.0"
] | 1 | 2020-07-25T05:32:10.000Z | 2020-07-25T05:32:10.000Z | examples/record_printer/client_hello_record.hpp | pioneer19/libcornet | 9eb91629d8f9a6793b28af10a3535bfba0cc24ca | [
"Apache-2.0"
] | 1 | 2020-07-25T05:28:54.000Z | 2020-07-25T05:28:54.000Z | /*
* Copyright 2020 Alex Syrnikov <pioneer19@post.cz>
* SPDX-License-Identifier: Apache-2.0
*
* This file is part of libcornet (https://github.com/pioneer19/libcornet).
*/
const uint8_t tls13_client_hello_record[] = {
0x16, 0x03, 0x01, 0x00, 0xea, // TlsPlaintext handshake, legacy version, length
0x01, 0x00, 0x00, 0xe6, // ClientHello(1), length(24 bit)
0x03, 0x03, // ProtocolVersion
0xe9, 0x53, 0xc0, 0xde, 0x38, 0x8c, 0x75, 0x82, // Random 32 bytes
0xbc, 0x49, 0xd5, 0xb2, 0xec, 0x46, 0x7c, 0x99,
0x21, 0xc5, 0xdb, 0x64, 0x3c, 0x66, 0x07, 0xa4,
0x18, 0x0e, 0x4d, 0x2a, 0x1a, 0x23, 0x2b, 0x08,
0x20, // legacy session vector length
0x99, 0x57, 0x6c, 0xce, 0x6e, 0x83, 0xc0, 0x69,
0xdc, 0xd9, 0x98, 0x43, 0x07, 0xe2, 0xbe, 0xfc,
0xb4, 0x38, 0x86, 0x33, 0x00, 0xf5, 0x58, 0x5f,
0x2b, 0x95, 0xce, 0x6f, 0xfe, 0x42, 0xf5, 0x26,
0x00, 0x08, // CipherSuites vector length
0x13, 0x02, 0x13, 0x03, 0x13, 0x01, 0x00, 0xff,
0x01, 0x00, // legacy_compression_methods<1..2^8-1>
// === Extensions ===
0x00, 0x95, // Extension extensions<8..2^16-1>;
0x00, 0x00, 0x00, 0x14, // ExtensionType(server_name), data_length(2 bytes)
0x00, 0x12, // ServerNameList vector length
0x00, 0x00, 0x0f, // ServerName type(1byte) and length
0x6d, 0x61, 0x73, 0x74, 0x65, 0x72, 0x73, 0x70,
0x6c, 0x69, 0x6e, 0x65, 0x2e, 0x65, 0x75,
0x00, 0x0b, 0x00, 0x04, // ExtensionType(unknown), data_length(2 bytes)
0x03, 0x00, 0x01, 0x02,
0x00, 0x0a, 0x00, 0x0c, // supported_groups(10)
0x00, 0x0a, 0x00, 0x1d, 0x00, 0x17, 0x00, 0x1e,
0x00, 0x19, 0x00, 0x18,
0x00, 0x23, 0x00, 0x00, // unknown extension
0x00, 0x16, 0x00, 0x00, // unknown extension
0x00, 0x17, 0x00, 0x00, // unknown extension
0x00, 0x0d, 0x00, 0x1e, // signature_algorithms(13)
0x00, 0x1c, 0x04, 0x03, 0x05, 0x03, 0x06, 0x03,
0x08, 0x07, 0x08, 0x08, 0x08, 0x09, 0x08, 0x0a,
0x08, 0x0b, 0x08, 0x04, 0x08, 0x05, 0x08, 0x06,
0x04, 0x01, 0x05, 0x01, 0x06, 0x01,
0x00, 0x2b, 0x00, 0x03, // supported_versions(43),
0x02, 0x03, 0x04, // length, TLS 1.3 (0x03, 0x04)
0x00, 0x2d, 0x00, 0x02, // psk_key_exchange_modes(45)
0x01, 0x01, // length 1, mode PSK_DHE_KE = 1
0x00, 0x33, 0x00, 0x26, // key_share(51)
0x00, 0x24, 0x00, 0x1d, 0x00, 0x20, 0xcd, 0xbe,
0xc4, 0xf3, 0x5a, 0x48, 0x28, 0x6e, 0x59, 0xb0,
0xe7, 0xeb, 0x2e, 0xe5, 0xa0, 0x51, 0x05, 0x21,
0x45, 0x7e, 0xdf, 0xa1, 0x12, 0x69, 0x23, 0x42,
0x2e, 0x92, 0x38, 0xcd, 0xd5, 0x0e
};
| 48.33871 | 91 | 0.54688 | pioneer19 |
4fb215be17b7a517f5c703eef67e7a23eb9a1c2c | 73,408 | cpp | C++ | src/mongo/s/commands_admin.cpp | nleite/mongo | 1a1b6b0aaeefbae06942867e4dcf55d00d42afe0 | [
"Apache-2.0"
] | null | null | null | src/mongo/s/commands_admin.cpp | nleite/mongo | 1a1b6b0aaeefbae06942867e4dcf55d00d42afe0 | [
"Apache-2.0"
] | null | null | null | src/mongo/s/commands_admin.cpp | nleite/mongo | 1a1b6b0aaeefbae06942867e4dcf55d00d42afe0 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2008 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "pch.h"
#include "mongo/db/commands.h"
#include "mongo/client/connpool.h"
#include "mongo/client/dbclientcursor.h"
#include "mongo/db/auth/action_set.h"
#include "mongo/db/auth/action_type.h"
#include "mongo/db/auth/authorization_manager.h"
#include "mongo/db/auth/privilege.h"
#include "mongo/db/dbmessage.h"
#include "mongo/db/field_parser.h"
#include "mongo/db/hasher.h"
#include "mongo/db/index_names.h"
#include "mongo/db/stats/counters.h"
#include "mongo/s/chunk.h"
#include "mongo/s/client_info.h"
#include "mongo/s/config.h"
#include "mongo/s/grid.h"
#include "mongo/s/strategy.h"
#include "mongo/s/type_chunk.h"
#include "mongo/s/type_database.h"
#include "mongo/s/type_shard.h"
#include "mongo/s/writeback_listener.h"
#include "mongo/util/net/listen.h"
#include "mongo/util/net/message.h"
#include "mongo/util/processinfo.h"
#include "mongo/util/ramlog.h"
#include "mongo/util/stringutils.h"
#include "mongo/util/timer.h"
#include "mongo/util/version.h"
namespace mongo {
namespace dbgrid_cmds {
class GridAdminCmd : public Command {
public:
GridAdminCmd( const char * n ) : Command( n , false, tolowerString(n).c_str() ) {
}
virtual bool slaveOk() const {
return true;
}
virtual bool adminOnly() const {
return true;
}
// all grid commands are designed not to lock
virtual LockType locktype() const { return NONE; }
bool okForConfigChanges( string& errmsg ) {
string e;
if ( ! configServer.allUp(e) ) {
errmsg = str::stream() << "not all config servers are up: " << e;
return false;
}
return true;
}
};
// --------------- misc commands ----------------------
class NetStatCmd : public GridAdminCmd {
public:
NetStatCmd() : GridAdminCmd("netstat") { }
virtual void help( stringstream& help ) const {
help << " shows status/reachability of servers in the cluster";
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::netstat);
out->push_back(Privilege(AuthorizationManager::CLUSTER_RESOURCE_NAME, actions));
}
bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) {
result.append("configserver", configServer.getPrimary().getConnString() );
result.append("isdbgrid", 1);
return true;
}
} netstat;
class FlushRouterConfigCmd : public GridAdminCmd {
public:
FlushRouterConfigCmd() : GridAdminCmd("flushRouterConfig") { }
virtual void help( stringstream& help ) const {
help << "flush all router config";
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::flushRouterConfig);
out->push_back(Privilege(AuthorizationManager::CLUSTER_RESOURCE_NAME, actions));
}
bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) {
grid.flushConfig();
result.appendBool( "flushed" , true );
return true;
}
} flushRouterConfigCmd;
class FsyncCommand : public GridAdminCmd {
public:
FsyncCommand() : GridAdminCmd( "fsync" ) {}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::fsync);
out->push_back(Privilege(AuthorizationManager::SERVER_RESOURCE_NAME, actions));
}
bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) {
if ( cmdObj["lock"].trueValue() ) {
errmsg = "can't do lock through mongos";
return false;
}
BSONObjBuilder sub;
bool ok = true;
int numFiles = 0;
vector<Shard> shards;
Shard::getAllShards( shards );
for ( vector<Shard>::iterator i=shards.begin(); i!=shards.end(); i++ ) {
Shard s = *i;
BSONObj x = s.runCommand( "admin" , "fsync" );
sub.append( s.getName() , x );
if ( ! x["ok"].trueValue() ) {
ok = false;
errmsg = x["errmsg"].String();
}
numFiles += x["numFiles"].numberInt();
}
result.append( "numFiles" , numFiles );
result.append( "all" , sub.obj() );
return ok;
}
} fsyncCmd;
// ------------ database level commands -------------
class MoveDatabasePrimaryCommand : public GridAdminCmd {
public:
MoveDatabasePrimaryCommand() : GridAdminCmd("movePrimary") { }
virtual void help( stringstream& help ) const {
help << " example: { moveprimary : 'foo' , to : 'localhost:9999' }";
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::movePrimary);
out->push_back(Privilege(AuthorizationManager::CLUSTER_RESOURCE_NAME, actions));
}
bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) {
string dbname = cmdObj.firstElement().valuestrsafe();
if ( dbname.size() == 0 ) {
errmsg = "no db";
return false;
}
if ( dbname == "config" ) {
errmsg = "can't move config db";
return false;
}
// Flush the configuration
// This can't be perfect, but it's better than nothing.
grid.flushConfig();
DBConfigPtr config = grid.getDBConfig( dbname , false );
if ( ! config ) {
errmsg = "can't find db!";
return false;
}
string to = cmdObj["to"].valuestrsafe();
if ( ! to.size() ) {
errmsg = "you have to specify where you want to move it";
return false;
}
Shard s = Shard::make( to );
if ( config->getPrimary() == s.getConnString() ) {
errmsg = "it is already the primary";
return false;
}
if ( ! grid.knowAboutShard( s.getConnString() ) ) {
errmsg = "that server isn't known to me";
return false;
}
log() << "Moving " << dbname << " primary from: " << config->getPrimary().toString()
<< " to: " << s.toString() << endl;
// Locking enabled now...
DistributedLock lockSetup( configServer.getConnectionString(), dbname + "-movePrimary" );
dist_lock_try dlk;
// Distributed locking added.
try{
dlk = dist_lock_try( &lockSetup , string("Moving primary shard of ") + dbname );
}
catch( LockException& e ){
errmsg = str::stream() << "error locking distributed lock to move primary shard of " << dbname << causedBy( e );
warning() << errmsg << endl;
return false;
}
if ( ! dlk.got() ) {
errmsg = (string)"metadata lock is already taken for moving " + dbname;
return false;
}
set<string> shardedColls;
config->getAllShardedCollections( shardedColls );
BSONArrayBuilder barr;
barr.append( shardedColls );
ScopedDbConnection toconn(s.getConnString());
// TODO ERH - we need a clone command which replays operations from clone start to now
// can just use local.oplog.$main
BSONObj cloneRes;
bool worked = toconn->runCommand(
dbname.c_str(),
BSON( "clone" << config->getPrimary().getConnString() <<
"collsToIgnore" << barr.arr() ),
cloneRes );
toconn.done();
if ( ! worked ) {
log() << "clone failed" << cloneRes << endl;
errmsg = "clone failed";
return false;
}
string oldPrimary = config->getPrimary().getConnString();
ScopedDbConnection fromconn(config->getPrimary().getConnString());
config->setPrimary( s.getConnString() );
if( shardedColls.empty() ){
// TODO: Collections can be created in the meantime, and we should handle in the future.
log() << "movePrimary dropping database on " << oldPrimary << ", no sharded collections in " << dbname << endl;
try {
fromconn->dropDatabase( dbname.c_str() );
}
catch( DBException& e ){
e.addContext( str::stream() << "movePrimary could not drop the database " << dbname << " on " << oldPrimary );
throw;
}
}
else if( cloneRes["clonedColls"].type() != Array ){
// Legacy behavior from old mongod with sharded collections, *do not* delete database,
// but inform user they can drop manually (or ignore).
warning() << "movePrimary legacy mongod behavior detected, user must manually remove unsharded collections in "
<< "database " << dbname << " on " << oldPrimary << endl;
}
else {
// We moved some unsharded collections, but not all
BSONObjIterator it( cloneRes["clonedColls"].Obj() );
while( it.more() ){
BSONElement el = it.next();
if( el.type() == String ){
try {
log() << "movePrimary dropping cloned collection " << el.String() << " on " << oldPrimary << endl;
fromconn->dropCollection( el.String() );
}
catch( DBException& e ){
e.addContext( str::stream() << "movePrimary could not drop the cloned collection " << el.String() << " on " << oldPrimary );
throw;
}
}
}
}
fromconn.done();
result << "primary " << s.toString();
return true;
}
} movePrimary;
class EnableShardingCmd : public GridAdminCmd {
public:
EnableShardingCmd() : GridAdminCmd( "enableSharding" ) {}
virtual void help( stringstream& help ) const {
help
<< "Enable sharding for a db. (Use 'shardcollection' command afterwards.)\n"
<< " { enablesharding : \"<dbname>\" }\n";
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::enableSharding);
out->push_back(Privilege(AuthorizationManager::CLUSTER_RESOURCE_NAME, actions));
}
bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) {
string dbname = cmdObj.firstElement().valuestrsafe();
if ( dbname.size() == 0 ) {
errmsg = "no db";
return false;
}
if ( dbname == "admin" ) {
errmsg = "can't shard the admin db";
return false;
}
if ( dbname == "local" ) {
errmsg = "can't shard the local db";
return false;
}
DBConfigPtr config = grid.getDBConfig( dbname );
if ( config->isShardingEnabled() ) {
errmsg = "already enabled";
return false;
}
if ( ! okForConfigChanges( errmsg ) )
return false;
log() << "enabling sharding on: " << dbname << endl;
config->enableSharding();
return true;
}
} enableShardingCmd;
// ------------ collection level commands -------------
class ShardCollectionCmd : public GridAdminCmd {
public:
ShardCollectionCmd() : GridAdminCmd( "shardCollection" ) {}
virtual void help( stringstream& help ) const {
help
<< "Shard a collection. Requires key. Optional unique. Sharding must already be enabled for the database.\n"
<< " { enablesharding : \"<dbname>\" }\n";
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::shardCollection);
out->push_back(Privilege(AuthorizationManager::CLUSTER_RESOURCE_NAME, actions));
}
bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) {
const string ns = cmdObj.firstElement().valuestrsafe();
if ( ns.size() == 0 ) {
errmsg = "no ns";
return false;
}
const NamespaceString nsStr( ns );
if ( !nsStr.isValid() ){
errmsg = str::stream() << "bad ns[" << ns << "]";
return false;
}
DBConfigPtr config = grid.getDBConfig( ns );
if ( ! config->isShardingEnabled() ) {
errmsg = "sharding not enabled for db";
return false;
}
if ( config->isSharded( ns ) ) {
errmsg = "already sharded";
return false;
}
BSONObj proposedKey = cmdObj.getObjectField( "key" );
if ( proposedKey.isEmpty() ) {
errmsg = "no shard key";
return false;
}
bool isHashedShardKey = // br
( IndexNames::findPluginName( proposedKey ) == IndexNames::HASHED );
// Currently the allowable shard keys are either
// i) a hashed single field, e.g. { a : "hashed" }, or
// ii) a compound list of ascending fields, e.g. { a : 1 , b : 1 }
if ( isHashedShardKey ) {
// case i)
if ( proposedKey.nFields() > 1 ) {
errmsg = "hashed shard keys currently only support single field keys";
return false;
}
if ( cmdObj["unique"].trueValue() ) {
// it's possible to ensure uniqueness on the hashed field by
// declaring an additional (non-hashed) unique index on the field,
// but the hashed shard key itself should not be declared unique
errmsg = "hashed shard keys cannot be declared unique.";
return false;
}
} else {
// case ii)
BSONForEach(e, proposedKey) {
if (!e.isNumber() || e.number() != 1.0) {
errmsg = str::stream() << "Unsupported shard key pattern. Pattern must"
<< " either be a single hashed field, or a list"
<< " of ascending fields.";
return false;
}
}
}
if ( ns.find( ".system." ) != string::npos ) {
errmsg = "can't shard system namespaces";
return false;
}
if ( ! okForConfigChanges( errmsg ) )
return false;
//the rest of the checks require a connection to the primary db
ScopedDbConnection conn(config->getPrimary().getConnString());
//check that collection is not capped
BSONObj res = conn->findOne( config->getName() + ".system.namespaces",
BSON( "name" << ns ) );
if ( res["options"].type() == Object &&
res["options"].embeddedObject()["capped"].trueValue() ) {
errmsg = "can't shard capped collection";
conn.done();
return false;
}
// The proposed shard key must be validated against the set of existing indexes.
// In particular, we must ensure the following constraints
//
// 1. All existing unique indexes, except those which start with the _id index,
// must contain the proposed key as a prefix (uniqueness of the _id index is
// ensured by the _id generation process or guaranteed by the user).
//
// 2. If the collection is not empty, there must exist at least one index that
// is "useful" for the proposed key. A "useful" index is defined as follows
// Useful Index:
// i. contains proposedKey as a prefix
// ii. is not sparse
// iii. contains no null values
// iv. is not multikey (maybe lift this restriction later)
// v. if a hashed index, has default seed (lift this restriction later)
//
// 3. If the proposed shard key is specified as unique, there must exist a useful,
// unique index exactly equal to the proposedKey (not just a prefix).
//
// After validating these constraint:
//
// 4. If there is no useful index, and the collection is non-empty, we
// must fail.
//
// 5. If the collection is empty, and it's still possible to create an index
// on the proposed key, we go ahead and do so.
string indexNS = config->getName() + ".system.indexes";
// 1. Verify consistency with existing unique indexes
BSONObj uniqueQuery = BSON( "ns" << ns << "unique" << true );
auto_ptr<DBClientCursor> uniqueQueryResult =
conn->query( indexNS , uniqueQuery );
ShardKeyPattern proposedShardKey( proposedKey );
while ( uniqueQueryResult->more() ) {
BSONObj idx = uniqueQueryResult->next();
BSONObj currentKey = idx["key"].embeddedObject();
if( ! proposedShardKey.isUniqueIndexCompatible( currentKey ) ) {
errmsg = str::stream() << "can't shard collection '" << ns << "' "
<< "with unique index on " << currentKey << " "
<< "and proposed shard key " << proposedKey << ". "
<< "Uniqueness can't be maintained unless "
<< "shard key is a prefix";
conn.done();
return false;
}
}
// 2. Check for a useful index
bool hasUsefulIndexForKey = false;
BSONObj allQuery = BSON( "ns" << ns );
auto_ptr<DBClientCursor> allQueryResult =
conn->query( indexNS , allQuery );
BSONArrayBuilder allIndexes;
while ( allQueryResult->more() ) {
BSONObj idx = allQueryResult->next();
allIndexes.append( idx );
BSONObj currentKey = idx["key"].embeddedObject();
// Check 2.i. and 2.ii.
if ( ! idx["sparse"].trueValue() && proposedKey.isPrefixOf( currentKey ) ) {
// We can't currently use hashed indexes with a non-default hash seed
// Check v.
// Note that this means that, for sharding, we only support one hashed index
// per field per collection.
if ( isHashedShardKey && !idx["seed"].eoo()
&& idx["seed"].numberInt() != BSONElementHasher::DEFAULT_HASH_SEED ) {
errmsg = str::stream()
<< "can't shard collection " << ns << " with hashed shard key "
<< proposedKey
<< " because the hashed index uses a non-default seed of "
<< idx["seed"].numberInt();
conn.done();
return false;
}
hasUsefulIndexForKey = true;
}
}
// 3. If proposed key is required to be unique, additionally check for exact match.
bool careAboutUnique = cmdObj["unique"].trueValue();
if ( hasUsefulIndexForKey && careAboutUnique ) {
BSONObj eqQuery = BSON( "ns" << ns << "key" << proposedKey );
BSONObj eqQueryResult = conn->findOne( indexNS, eqQuery );
if ( eqQueryResult.isEmpty() ) {
hasUsefulIndexForKey = false; // if no exact match, index not useful,
// but still possible to create one later
}
else {
bool isExplicitlyUnique = eqQueryResult["unique"].trueValue();
BSONObj currKey = eqQueryResult["key"].embeddedObject();
bool isCurrentID = str::equals( currKey.firstElementFieldName() , "_id" );
if ( ! isExplicitlyUnique && ! isCurrentID ) {
errmsg = str::stream() << "can't shard collection " << ns << ", "
<< proposedKey << " index not unique, "
<< "and unique index explicitly specified";
conn.done();
return false;
}
}
}
if ( hasUsefulIndexForKey ) {
// Check 2.iii and 2.iv. Make sure no null entries in the sharding index
// and that there is a useful, non-multikey index available
BSONObjBuilder cmd;
cmd.append( "checkShardingIndex" , ns );
cmd.append( "keyPattern" , proposedKey );
BSONObj cmdObj = cmd.obj();
if ( ! conn.get()->runCommand( "admin" , cmdObj , res ) ) {
errmsg = res["errmsg"].str();
conn.done();
return false;
}
}
// 4. if no useful index, and collection is non-empty, fail
else if ( conn->count( ns ) != 0 ) {
errmsg = str::stream() << "please create an index that starts with the "
<< "shard key before sharding.";
result.append( "proposedKey" , proposedKey );
result.appendArray( "curIndexes" , allIndexes.done() );
conn.done();
return false;
}
// 5. If no useful index exists, and collection empty, create one on proposedKey.
// Only need to call ensureIndex on primary shard, since indexes get copied to
// receiving shard whenever a migrate occurs.
else {
// call ensureIndex with cache=false, see SERVER-1691
bool ensureSuccess = conn->ensureIndex( ns ,
proposedKey ,
careAboutUnique ,
"" ,
false );
if ( ! ensureSuccess ) {
errmsg = "ensureIndex failed to create index on primary shard";
conn.done();
return false;
}
}
bool isEmpty = ( conn->count( ns ) == 0 );
conn.done();
// Pre-splitting:
// For new collections which use hashed shard keys, we can can pre-split the
// range of possible hashes into a large number of chunks, and distribute them
// evenly at creation time. Until we design a better initialization scheme, the
// safest way to pre-split is to
// 1. make one big chunk for each shard
// 2. move them one at a time
// 3. split the big chunks to achieve the desired total number of initial chunks
vector<Shard> shards;
Shard primary = config->getPrimary();
primary.getAllShards( shards );
int numShards = shards.size();
vector<BSONObj> initSplits; // there will be at most numShards-1 of these
vector<BSONObj> allSplits; // all of the initial desired split points
// only pre-split when using a hashed shard key and collection is still empty
if ( isHashedShardKey && isEmpty ){
int numChunks = cmdObj["numInitialChunks"].numberInt();
if ( numChunks <= 0 )
numChunks = 2*numShards; // default number of initial chunks
// hashes are signed, 64-bit ints. So we divide the range (-MIN long, +MAX long)
// into intervals of size (2^64/numChunks) and create split points at the
// boundaries. The logic below ensures that initial chunks are all
// symmetric around 0.
long long intervalSize = ( std::numeric_limits<long long>::max()/ numChunks )*2;
long long current = 0;
if( numChunks % 2 == 0 ){
allSplits.push_back( BSON(proposedKey.firstElementFieldName() << current) );
current += intervalSize;
} else {
current += intervalSize/2;
}
for( int i=0; i < (numChunks-1)/2; i++ ){
allSplits.push_back( BSON(proposedKey.firstElementFieldName() << current) );
allSplits.push_back( BSON(proposedKey.firstElementFieldName() << -current));
current += intervalSize;
}
sort( allSplits.begin() , allSplits.end() );
// 1. the initial splits define the "big chunks" that we will subdivide later
int lastIndex = -1;
for ( int i = 1; i < numShards; i++ ){
if ( lastIndex < (i*numChunks)/numShards - 1 ){
lastIndex = (i*numChunks)/numShards - 1;
initSplits.push_back( allSplits[ lastIndex ] );
}
}
}
tlog() << "CMD: shardcollection: " << cmdObj << endl;
config->shardCollection( ns , proposedKey , careAboutUnique , &initSplits );
result << "collectionsharded" << ns;
// only initially move chunks when using a hashed shard key
if (isHashedShardKey) {
// Reload the new config info. If we created more than one initial chunk, then
// we need to move them around to balance.
ChunkManagerPtr chunkManager = config->getChunkManager( ns , true );
ChunkMap chunkMap = chunkManager->getChunkMap();
// 2. Move and commit each "big chunk" to a different shard.
int i = 0;
for ( ChunkMap::const_iterator c = chunkMap.begin(); c != chunkMap.end(); ++c,++i ){
Shard to = shards[ i % numShards ];
ChunkPtr chunk = c->second;
// can't move chunk to shard it's already on
if ( to == chunk->getShard() )
continue;
BSONObj moveResult;
if (!chunk->moveAndCommit(to, Chunk::MaxChunkSize,
false, true, moveResult)) {
warning() << "Couldn't move chunk " << chunk << " to shard " << to
<< " while sharding collection " << ns << ". Reason: "
<< moveResult << endl;
}
}
if (allSplits.empty()) {
return true;
}
// Reload the config info, after all the migrations
chunkManager = config->getChunkManager( ns , true );
// 3. Subdivide the big chunks by splitting at each of the points in "allSplits"
// that we haven't already split by.
ChunkPtr currentChunk = chunkManager->findIntersectingChunk( allSplits[0] );
vector<BSONObj> subSplits;
for ( unsigned i = 0 ; i <= allSplits.size(); i++){
if ( i == allSplits.size() || ! currentChunk->containsPoint( allSplits[i] ) ) {
if ( ! subSplits.empty() ){
BSONObj splitResult;
if ( ! currentChunk->multiSplit( subSplits , splitResult ) ){
warning() << "Couldn't split chunk " << currentChunk
<< " while sharding collection " << ns << ". Reason: "
<< splitResult << endl;
}
subSplits.clear();
}
if ( i < allSplits.size() )
currentChunk = chunkManager->findIntersectingChunk( allSplits[i] );
} else {
subSplits.push_back( allSplits[i] );
}
}
// Proactively refresh the chunk manager. Not really necessary, but this way it's
// immediately up-to-date the next time it's used.
config->getChunkManager( ns , true );
}
return true;
}
} shardCollectionCmd;
class GetShardVersion : public GridAdminCmd {
public:
GetShardVersion() : GridAdminCmd( "getShardVersion" ) {}
virtual void help( stringstream& help ) const {
help << " example: { getShardVersion : 'alleyinsider.foo' } ";
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::getShardVersion);
out->push_back(Privilege(AuthorizationManager::CLUSTER_RESOURCE_NAME, actions));
}
bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) {
string ns = cmdObj.firstElement().valuestrsafe();
if ( ns.size() == 0 ) {
errmsg = "need to specify fully namespace";
return false;
}
DBConfigPtr config = grid.getDBConfig( ns );
if ( ! config->isSharded( ns ) ) {
errmsg = "ns not sharded.";
return false;
}
ChunkManagerPtr cm = config->getChunkManagerIfExists( ns );
if ( ! cm ) {
errmsg = "no chunk manager?";
return false;
}
cm->_printChunks();
cm->getVersion().addToBSON( result );
return 1;
}
} getShardVersionCmd;
class SplitCollectionCmd : public GridAdminCmd {
public:
SplitCollectionCmd() : GridAdminCmd( "split" ) {}
virtual void help( stringstream& help ) const {
help
<< " example: - split the shard that contains give key \n"
<< " { split : 'alleyinsider.blog.posts' , find : { ts : 1 } }\n"
<< " example: - split the shard that contains the key with this as the middle \n"
<< " { split : 'alleyinsider.blog.posts' , middle : { ts : 1 } }\n"
<< " NOTE: this does not move move the chunks, it merely creates a logical separation \n"
;
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::split);
out->push_back(Privilege(AuthorizationManager::CLUSTER_RESOURCE_NAME, actions));
}
bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) {
if ( ! okForConfigChanges( errmsg ) )
return false;
ShardConnection::sync();
string ns = cmdObj.firstElement().valuestrsafe();
if ( ns.size() == 0 ) {
errmsg = "no ns";
return false;
}
DBConfigPtr config = grid.getDBConfig( ns );
if ( ! config->isSharded( ns ) ) {
config->reload();
if ( ! config->isSharded( ns ) ) {
errmsg = "ns not sharded. have to shard before can split";
return false;
}
}
const BSONField<BSONObj> findField("find", BSONObj());
const BSONField<BSONArray> boundsField("bounds", BSONArray());
const BSONField<BSONObj> middleField("middle", BSONObj());
BSONObj find;
if (FieldParser::extract(cmdObj, findField, &find, &errmsg) ==
FieldParser::FIELD_INVALID) {
return false;
}
BSONArray bounds;
if (FieldParser::extract(cmdObj, boundsField, &bounds, &errmsg) ==
FieldParser::FIELD_INVALID) {
return false;
}
if (!bounds.isEmpty()) {
if (!bounds.hasField("0")) {
errmsg = "lower bound not specified";
return false;
}
if (!bounds.hasField("1")) {
errmsg = "upper bound not specified";
return false;
}
}
if (!find.isEmpty() && !bounds.isEmpty()) {
errmsg = "cannot specify bounds and find at the same time";
return false;
}
BSONObj middle;
if (FieldParser::extract(cmdObj, middleField, &middle, &errmsg) ==
FieldParser::FIELD_INVALID) {
return false;
}
if (find.isEmpty() && bounds.isEmpty() && middle.isEmpty()) {
errmsg = "need to specify find/bounds or middle";
return false;
}
if (!find.isEmpty() && !middle.isEmpty()) {
errmsg = "cannot specify find and middle together";
return false;
}
if (!bounds.isEmpty() && !middle.isEmpty()) {
errmsg = "cannot specify bounds and middle together";
return false;
}
ChunkManagerPtr info = config->getChunkManager( ns );
ChunkPtr chunk;
if (!find.isEmpty()) {
chunk = info->findChunkForDoc(find);
}
else if (!bounds.isEmpty()) {
chunk = info->findIntersectingChunk(bounds[0].Obj());
verify(chunk.get());
if (chunk->getMin() != bounds[0].Obj() ||
chunk->getMax() != bounds[1].Obj()) {
errmsg = "no chunk found from the given upper and lower bounds";
return false;
}
}
else { // middle
chunk = info->findIntersectingChunk(middle);
}
verify(chunk.get());
log() << "splitting: " << ns << " shard: " << chunk << endl;
BSONObj res;
bool worked;
if ( middle.isEmpty() ) {
BSONObj ret = chunk->singleSplit( true /* force a split even if not enough data */ , res );
worked = !ret.isEmpty();
}
else {
// sanity check if the key provided is a valid split point
if ( ( middle == chunk->getMin() ) || ( middle == chunk->getMax() ) ) {
errmsg = "cannot split on initial or final chunk's key";
return false;
}
if (!fieldsMatch(middle, info->getShardKey().key())){
errmsg = "middle has different fields (or different order) than shard key";
return false;
}
vector<BSONObj> splitPoints;
splitPoints.push_back( middle );
worked = chunk->multiSplit( splitPoints , res );
}
if ( !worked ) {
errmsg = "split failed";
result.append( "cause" , res );
return false;
}
config->getChunkManager( ns , true );
return true;
}
} splitCollectionCmd;
class MoveChunkCmd : public GridAdminCmd {
public:
MoveChunkCmd() : GridAdminCmd( "moveChunk" ) {}
virtual void help( stringstream& help ) const {
help << "Example: move chunk that contains the doc {num : 7} to shard001\n"
<< " { movechunk : 'test.foo' , find : { num : 7 } , to : 'shard0001' }\n"
<< "Example: move chunk with lower bound 0 and upper bound 10 to shard001\n"
<< " { movechunk : 'test.foo' , bounds : [ { num : 0 } , { num : 10 } ] "
<< " , to : 'shard001' }\n";
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::moveChunk);
out->push_back(Privilege(AuthorizationManager::CLUSTER_RESOURCE_NAME, actions));
}
bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) {
if ( ! okForConfigChanges( errmsg ) )
return false;
ShardConnection::sync();
Timer t;
string ns = cmdObj.firstElement().valuestrsafe();
if ( ns.size() == 0 ) {
errmsg = "no ns";
return false;
}
DBConfigPtr config = grid.getDBConfig( ns );
if ( ! config->isSharded( ns ) ) {
config->reload();
if ( ! config->isSharded( ns ) ) {
errmsg = "ns not sharded. have to shard before we can move a chunk";
return false;
}
}
string toString = cmdObj["to"].valuestrsafe();
if ( ! toString.size() ) {
errmsg = "you have to specify where you want to move the chunk";
return false;
}
Shard to = Shard::make( toString );
// so far, chunk size serves test purposes; it may or may not become a supported parameter
long long maxChunkSizeBytes = cmdObj["maxChunkSizeBytes"].numberLong();
if ( maxChunkSizeBytes == 0 ) {
maxChunkSizeBytes = Chunk::MaxChunkSize;
}
BSONObj find = cmdObj.getObjectField( "find" );
BSONObj bounds = cmdObj.getObjectField( "bounds" );
// check that only one of the two chunk specification methods is used
if ( find.isEmpty() == bounds.isEmpty() ) {
errmsg = "need to specify either a find query, or both lower and upper bounds.";
return false;
}
ChunkManagerPtr info = config->getChunkManager( ns );
ChunkPtr c = find.isEmpty() ?
info->findIntersectingChunk( bounds[0].Obj() ) :
info->findChunkForDoc( find );
if ( ! bounds.isEmpty() && ( c->getMin() != bounds[0].Obj() ||
c->getMax() != bounds[1].Obj() ) ) {
errmsg = "no chunk found with those upper and lower bounds";
return false;
}
const Shard& from = c->getShard();
if ( from == to ) {
errmsg = "that chunk is already on that shard";
return false;
}
tlog() << "CMD: movechunk: " << cmdObj << endl;
BSONObj res;
if (!c->moveAndCommit(to,
maxChunkSizeBytes,
cmdObj["_secondaryThrottle"].trueValue(),
cmdObj["_waitForDelete"].trueValue(),
res)) {
errmsg = "move failed";
result.append( "cause" , res );
return false;
}
// preemptively reload the config to get new version info
config->getChunkManager( ns , true );
result.append( "millis" , t.millis() );
return true;
}
} moveChunkCmd;
// ------------ server level commands -------------
class ListShardsCmd : public GridAdminCmd {
public:
ListShardsCmd() : GridAdminCmd("listShards") { }
virtual void help( stringstream& help ) const {
help << "list all shards of the system";
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::listShards);
out->push_back(Privilege(AuthorizationManager::CLUSTER_RESOURCE_NAME, actions));
}
bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) {
ScopedDbConnection conn(configServer.getPrimary().getConnString(), 30);
vector<BSONObj> all;
auto_ptr<DBClientCursor> cursor = conn->query( ShardType::ConfigNS , BSONObj() );
while ( cursor->more() ) {
BSONObj o = cursor->next();
all.push_back( o );
}
result.append("shards" , all );
conn.done();
return true;
}
} listShardsCmd;
/* a shard is a single mongod server or a replica pair. add it (them) to the cluster as a storage partition. */
class AddShard : public GridAdminCmd {
public:
AddShard() : GridAdminCmd("addShard") { }
virtual void help( stringstream& help ) const {
help << "add a new shard to the system";
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::addShard);
out->push_back(Privilege(AuthorizationManager::CLUSTER_RESOURCE_NAME, actions));
}
bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) {
errmsg.clear();
// get replica set component hosts
ConnectionString servers = ConnectionString::parse( cmdObj.firstElement().valuestrsafe() , errmsg );
if ( ! errmsg.empty() ) {
log() << "addshard request " << cmdObj << " failed:" << errmsg << endl;
return false;
}
// using localhost in server names implies every other process must use localhost addresses too
vector<HostAndPort> serverAddrs = servers.getServers();
for ( size_t i = 0 ; i < serverAddrs.size() ; i++ ) {
if ( serverAddrs[i].isLocalHost() != grid.allowLocalHost() ) {
errmsg = str::stream() <<
"can't use localhost as a shard since all shards need to communicate. " <<
"either use all shards and configdbs in localhost or all in actual IPs " <<
" host: " << serverAddrs[i].toString() << " isLocalHost:" << serverAddrs[i].isLocalHost();
log() << "addshard request " << cmdObj << " failed: attempt to mix localhosts and IPs" << endl;
return false;
}
// it's fine if mongods of a set all use default port
if ( ! serverAddrs[i].hasPort() ) {
serverAddrs[i].setPort( CmdLine::ShardServerPort );
}
}
// name is optional; addShard will provide one if needed
string name = "";
if ( cmdObj["name"].type() == String ) {
name = cmdObj["name"].valuestrsafe();
}
// maxSize is the space usage cap in a shard in MBs
long long maxSize = 0;
if ( cmdObj[ ShardType::maxSize() ].isNumber() ) {
maxSize = cmdObj[ ShardType::maxSize() ].numberLong();
}
if ( ! grid.addShard( &name , servers , maxSize , errmsg ) ) {
log() << "addshard request " << cmdObj << " failed: " << errmsg << endl;
return false;
}
result << "shardAdded" << name;
return true;
}
} addServer;
/* See usage docs at:
* http://dochub.mongodb.org/core/configuringsharding#ConfiguringSharding-Removingashard
*/
class RemoveShardCmd : public GridAdminCmd {
public:
RemoveShardCmd() : GridAdminCmd("removeShard") { }
virtual void help( stringstream& help ) const {
help << "remove a shard to the system.";
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::removeShard);
out->push_back(Privilege(AuthorizationManager::CLUSTER_RESOURCE_NAME, actions));
}
bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) {
string target = cmdObj.firstElement().valuestrsafe();
Shard s = Shard::make( target );
if ( ! grid.knowAboutShard( s.getConnString() ) ) {
errmsg = "unknown shard";
return false;
}
ScopedDbConnection conn(configServer.getPrimary().getConnString(), 30);
if (conn->count(ShardType::ConfigNS,
BSON(ShardType::name() << NE << s.getName() <<
ShardType::draining(true)))){
conn.done();
errmsg = "Can't have more than one draining shard at a time";
return false;
}
if (conn->count(ShardType::ConfigNS, BSON(ShardType::name() << NE << s.getName())) == 0){
conn.done();
errmsg = "Can't remove last shard";
return false;
}
BSONObj primaryDoc = BSON(DatabaseType::name.ne("local") <<
DatabaseType::primary(s.getName()));
BSONObj dbInfo; // appended at end of result on success
{
boost::scoped_ptr<DBClientCursor> cursor (conn->query(DatabaseType::ConfigNS, primaryDoc));
if (cursor->more()) { // skip block and allocations if empty
BSONObjBuilder dbInfoBuilder;
dbInfoBuilder.append("note", "you need to drop or movePrimary these databases");
BSONArrayBuilder dbs(dbInfoBuilder.subarrayStart("dbsToMove"));
while (cursor->more()){
BSONObj db = cursor->nextSafe();
dbs.append(db[DatabaseType::name()]);
}
dbs.doneFast();
dbInfo = dbInfoBuilder.obj();
}
}
// If the server is not yet draining chunks, put it in draining mode.
BSONObj searchDoc = BSON(ShardType::name() << s.getName());
BSONObj drainingDoc = BSON(ShardType::name() << s.getName() << ShardType::draining(true));
BSONObj shardDoc = conn->findOne(ShardType::ConfigNS, drainingDoc);
if ( shardDoc.isEmpty() ) {
// TODO prevent move chunks to this shard.
log() << "going to start draining shard: " << s.getName() << endl;
BSONObj newStatus = BSON( "$set" << BSON( ShardType::draining(true) ) );
conn->update( ShardType::ConfigNS , searchDoc , newStatus, false /* do no upsert */);
errmsg = conn->getLastError();
if ( errmsg.size() ) {
log() << "error starting remove shard: " << s.getName() << " err: " << errmsg << endl;
return false;
}
BSONObj primaryLocalDoc = BSON(DatabaseType::name("local") <<
DatabaseType::primary(s.getName()));
PRINT(primaryLocalDoc);
if (conn->count(DatabaseType::ConfigNS, primaryLocalDoc)) {
log() << "This shard is listed as primary of local db. Removing entry." << endl;
conn->remove(DatabaseType::ConfigNS, BSON(DatabaseType::name("local")));
errmsg = conn->getLastError();
if ( errmsg.size() ) {
log() << "error removing local db: " << errmsg << endl;
return false;
}
}
Shard::reloadShardInfo();
result.append( "msg" , "draining started successfully" );
result.append( "state" , "started" );
result.append( "shard" , s.getName() );
result.appendElements(dbInfo);
conn.done();
return true;
}
// If the server has been completely drained, remove it from the ConfigDB.
// Check not only for chunks but also databases.
BSONObj shardIDDoc = BSON(ChunkType::shard(shardDoc[ShardType::name()].str()));
long long chunkCount = conn->count(ChunkType::ConfigNS, shardIDDoc);
long long dbCount = conn->count( DatabaseType::ConfigNS , primaryDoc );
if ( ( chunkCount == 0 ) && ( dbCount == 0 ) ) {
log() << "going to remove shard: " << s.getName() << endl;
conn->remove( ShardType::ConfigNS , searchDoc );
errmsg = conn->getLastError();
if ( errmsg.size() ) {
log() << "error concluding remove shard: " << s.getName() << " err: " << errmsg << endl;
return false;
}
string shardName = shardDoc[ ShardType::name() ].str();
Shard::removeShard( shardName );
shardConnectionPool.removeHost( shardName );
ReplicaSetMonitor::remove( shardName, true );
Shard::reloadShardInfo();
result.append( "msg" , "removeshard completed successfully" );
result.append( "state" , "completed" );
result.append( "shard" , s.getName() );
conn.done();
return true;
}
// If the server is already in draining mode, just report on its progress.
// Report on databases (not just chunks) that are left too.
result.append( "msg" , "draining ongoing" );
result.append( "state" , "ongoing" );
BSONObjBuilder inner;
inner.append( "chunks" , chunkCount );
inner.append( "dbs" , dbCount );
result.append( "remaining" , inner.obj() );
result.appendElements(dbInfo);
conn.done();
return true;
}
} removeShardCmd;
// --------------- public commands ----------------
class IsDbGridCmd : public Command {
public:
virtual LockType locktype() const { return NONE; }
virtual bool slaveOk() const {
return true;
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {} // No auth required
IsDbGridCmd() : Command("isdbgrid") { }
bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) {
result.append("isdbgrid", 1);
result.append("hostname", getHostNameCached());
return true;
}
} isdbgrid;
class CmdIsMaster : public Command {
public:
virtual LockType locktype() const { return NONE; }
virtual bool slaveOk() const {
return true;
}
virtual void help( stringstream& help ) const {
help << "test if this is master half of a replica pair";
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {} // No auth required
CmdIsMaster() : Command("isMaster" , false , "ismaster") { }
virtual bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) {
result.appendBool("ismaster", true );
result.append("msg", "isdbgrid");
result.appendNumber("maxBsonObjectSize", BSONObjMaxUserSize);
result.appendNumber("maxMessageSizeBytes", MaxMessageSizeBytes);
result.appendDate("localTime", jsTime());
return true;
}
} ismaster;
class CmdWhatsMyUri : public Command {
public:
CmdWhatsMyUri() : Command("whatsmyuri") { }
virtual bool logTheOp() {
return false; // the modification will be logged directly
}
virtual bool slaveOk() const {
return true;
}
virtual LockType locktype() const { return NONE; }
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {} // No auth required
virtual void help( stringstream &help ) const {
help << "{whatsmyuri:1}";
}
virtual bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) {
result << "you" << ClientInfo::get()->getRemote();
return true;
}
} cmdWhatsMyUri;
class CmdShardingGetPrevError : public Command {
public:
virtual LockType locktype() const { return NONE; }
virtual bool slaveOk() const {
return true;
}
virtual void help( stringstream& help ) const {
help << "get previous error (since last reseterror command)";
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {} // No auth required
CmdShardingGetPrevError() : Command( "getPrevError" , false , "getpreverror") { }
virtual bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) {
errmsg += "getpreverror not supported for sharded environments";
return false;
}
} cmdGetPrevError;
class CmdShardingGetLastError : public Command {
public:
virtual LockType locktype() const { return NONE; }
virtual bool slaveOk() const {
return true;
}
virtual void help( stringstream& help ) const {
help << "check for an error on the last command executed";
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {} // No auth required
CmdShardingGetLastError() : Command("getLastError" , false , "getlasterror") { }
virtual bool run(const string& dbName, BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) {
LastError *le = lastError.disableForCommand();
verify( le );
{
if ( le->msg.size() && le->nPrev == 1 ) {
le->appendSelf( result );
return true;
}
}
ClientInfo * client = ClientInfo::get();
bool res = client->getLastError( dbName, cmdObj , result, errmsg );
client->disableForCommand();
return res;
}
} cmdGetLastError;
}
class CmdShardingResetError : public Command {
public:
CmdShardingResetError() : Command( "resetError" , false , "reseterror" ) {}
virtual LockType locktype() const { return NONE; }
virtual bool slaveOk() const {
return true;
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {} // No auth required
bool run(const string& dbName , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool /*fromRepl*/) {
LastError *le = lastError.get();
if ( le )
le->reset();
ClientInfo * client = ClientInfo::get();
set<string> * shards = client->getPrev();
for ( set<string>::iterator i = shards->begin(); i != shards->end(); i++ ) {
string theShard = *i;
ShardConnection conn( theShard , "" );
BSONObj res;
conn->runCommand( dbName , cmdObj , res );
conn.done();
}
return true;
}
} cmdShardingResetError;
class CmdListDatabases : public Command {
public:
CmdListDatabases() : Command("listDatabases", true , "listdatabases" ) {}
virtual bool logTheOp() { return false; }
virtual bool slaveOk() const { return true; }
virtual bool slaveOverrideOk() const { return true; }
virtual bool adminOnly() const { return true; }
virtual LockType locktype() const { return NONE; }
virtual void help( stringstream& help ) const { help << "list databases on cluster"; }
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::listDatabases);
out->push_back(Privilege(AuthorizationManager::SERVER_RESOURCE_NAME, actions));
}
bool run(const string& , BSONObj& jsobj, int, string& errmsg, BSONObjBuilder& result, bool /*fromRepl*/) {
vector<Shard> shards;
Shard::getAllShards( shards );
map<string,long long> sizes;
map< string,shared_ptr<BSONObjBuilder> > dbShardInfo;
for ( vector<Shard>::iterator i=shards.begin(); i!=shards.end(); i++ ) {
Shard s = *i;
BSONObj x = s.runCommand( "admin" , "listDatabases" );
BSONObjIterator j( x["databases"].Obj() );
while ( j.more() ) {
BSONObj theDB = j.next().Obj();
string name = theDB["name"].String();
long long size = theDB["sizeOnDisk"].numberLong();
long long& totalSize = sizes[name];
if ( size == 1 ) {
if ( totalSize <= 1 )
totalSize = 1;
}
else
totalSize += size;
shared_ptr<BSONObjBuilder>& bb = dbShardInfo[name];
if ( ! bb.get() )
bb.reset( new BSONObjBuilder() );
bb->appendNumber( s.getName() , size );
}
}
long long totalSize = 0;
BSONArrayBuilder bb( result.subarrayStart( "databases" ) );
for ( map<string,long long>::iterator i=sizes.begin(); i!=sizes.end(); ++i ) {
string name = i->first;
if ( name == "local" ) {
// we don't return local
// since all shards have their own independent local
continue;
}
if ( name == "config" || name == "admin" ) {
//always get this from the config servers
continue;
}
long long size = i->second;
totalSize += size;
BSONObjBuilder temp;
temp.append( "name" , name );
temp.appendNumber( "sizeOnDisk" , size );
temp.appendBool( "empty" , size == 1 );
temp.append( "shards" , dbShardInfo[name]->obj() );
bb.append( temp.obj() );
}
{ // get config db from the config servers (first one)
ScopedDbConnection conn(configServer.getPrimary().getConnString(), 30);
BSONObj x;
if ( conn->simpleCommand( "config" , &x , "dbstats" ) ){
BSONObjBuilder b;
b.append( "name" , "config" );
b.appendBool( "empty" , false );
if ( x["fileSize"].type() )
b.appendAs( x["fileSize"] , "sizeOnDisk" );
else
b.append( "sizeOnDisk" , 1 );
bb.append( b.obj() );
}
else {
bb.append( BSON( "name" << "config" ) );
}
conn.done();
}
{ // get admin db from the config servers (first one)
ScopedDbConnection conn(configServer.getPrimary().getConnString(), 30);
BSONObj x;
if ( conn->simpleCommand( "admin" , &x , "dbstats" ) ){
BSONObjBuilder b;
b.append( "name" , "admin" );
b.appendBool( "empty" , false );
if ( x["fileSize"].type() )
b.appendAs( x["fileSize"] , "sizeOnDisk" );
else
b.append( "sizeOnDisk" , 1 );
bb.append( b.obj() );
}
else {
bb.append( BSON( "name" << "admin" ) );
}
conn.done();
}
bb.done();
result.appendNumber( "totalSize" , totalSize );
result.appendNumber( "totalSizeMb" , totalSize / ( 1024 * 1024 ) );
return 1;
}
} cmdListDatabases;
class CmdCloseAllDatabases : public Command {
public:
CmdCloseAllDatabases() : Command("closeAllDatabases", false , "closeAllDatabases" ) {}
virtual bool logTheOp() { return false; }
virtual bool slaveOk() const { return true; }
virtual bool slaveOverrideOk() const { return true; }
virtual bool adminOnly() const { return true; }
virtual LockType locktype() const { return NONE; }
virtual void help( stringstream& help ) const { help << "Not supported sharded"; }
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::closeAllDatabases);
out->push_back(Privilege(AuthorizationManager::SERVER_RESOURCE_NAME, actions));
}
bool run(const string& , BSONObj& jsobj, int, string& errmsg, BSONObjBuilder& /*result*/, bool /*fromRepl*/) {
errmsg = "closeAllDatabases isn't supported through mongos";
return false;
}
} cmdCloseAllDatabases;
class CmdReplSetGetStatus : public Command {
public:
CmdReplSetGetStatus() : Command("replSetGetStatus"){}
virtual bool logTheOp() { return false; }
virtual bool slaveOk() const { return true; }
virtual bool adminOnly() const { return true; }
virtual LockType locktype() const { return NONE; }
virtual void help( stringstream& help ) const { help << "Not supported through mongos"; }
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
// TODO: Should this require no auth since it's not supported in mongos anyway?
ActionSet actions;
actions.addAction(ActionType::replSetGetStatus);
out->push_back(Privilege(AuthorizationManager::SERVER_RESOURCE_NAME, actions));
}
bool run(const string& , BSONObj& jsobj, int, string& errmsg, BSONObjBuilder& result, bool /*fromRepl*/) {
if ( jsobj["forShell"].trueValue() ) {
lastError.disableForCommand();
ClientInfo::get()->disableForCommand();
}
errmsg = "replSetGetStatus is not supported through mongos";
result.append("info", "mongos"); // see sayReplSetMemberState
return false;
}
} cmdReplSetGetStatus;
CmdShutdown cmdShutdown;
void CmdShutdown::help( stringstream& help ) const {
help << "shutdown the database. must be ran against admin db and "
<< "either (1) ran from localhost or (2) authenticated.";
}
bool CmdShutdown::run(const string& dbname, BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool fromRepl) {
return shutdownHelper();
}
} // namespace mongo
| 45.538462 | 156 | 0.468314 | nleite |
4fb26419819029cbca5a4561cdcaaa756c6d76f2 | 895 | cpp | C++ | src/playground/oop.cpp | yyqian/cpp-arsenal | 1f3ce5c044d388a7ddc81f326f304c3acfa420fc | [
"MIT"
] | null | null | null | src/playground/oop.cpp | yyqian/cpp-arsenal | 1f3ce5c044d388a7ddc81f326f304c3acfa420fc | [
"MIT"
] | null | null | null | src/playground/oop.cpp | yyqian/cpp-arsenal | 1f3ce5c044d388a7ddc81f326f304c3acfa420fc | [
"MIT"
] | null | null | null | #include <string>
class Quote {
public:
Quote() = default;
Quote(const std::string &book, double sales_price)
: bookNo(book), price(sales_price) {}
std::string isbn() const { return bookNo; }
virtual double net_price(std::size_t n) const { return n * price; }
virtual ~Quote() = default;
private:
std::string bookNo;
protected:
double price = 0.0;
};
class Bulk_quote : public Quote {
public:
Bulk_quote() = default;
Bulk_quote(const std::string &book, double p, std::size_t qty, double disc)
: Quote(book, p), min_qty(qty), discount(disc) {}
double net_price(std::size_t n) const override;
private:
std::size_t min_qty = 0;
double discount = 0.0;
};
double Bulk_quote::net_price(std::size_t cnt) const {
if (cnt >= min_qty) {
return cnt * (1 - discount) * price;
} else {
return cnt * price;
}
}
| 23.552632 | 78 | 0.625698 | yyqian |
4fb59c89f9637b5a55fea3244994655ee8f3d196 | 2,981 | cc | C++ | code/render/coregraphics/base/multiplerendertargetbase.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 67 | 2015-03-30T19:56:16.000Z | 2022-03-11T13:52:17.000Z | code/render/coregraphics/base/multiplerendertargetbase.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 5 | 2015-04-15T17:17:33.000Z | 2016-02-11T00:40:17.000Z | code/render/coregraphics/base/multiplerendertargetbase.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 34 | 2015-03-30T15:08:00.000Z | 2021-09-23T05:55:10.000Z | //------------------------------------------------------------------------------
// multiplerendertargetbase.cc
// (C) 2007 Radon Labs GmbH
// (C) 2013-2016 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "coregraphics/base/multiplerendertargetbase.h"
namespace Base
{
__ImplementClass(Base::MultipleRenderTargetBase, 'MRTB', Core::RefCounted);
using namespace CoreGraphics;
using namespace Resources;
//------------------------------------------------------------------------------
/**
*/
MultipleRenderTargetBase::MultipleRenderTargetBase() :
clearDepthStencil(false),
depthStencilTarget(0),
numRenderTargets(0)
{
IndexT i;
for (i = 0; i < MaxNumRenderTargets; i++)
{
this->clearColor[i].set(0.0f, 0.0f, 0.0f, 0.0f);
this->clearDepth = 1.0f;
this->clearStencil = 0;
}
}
//------------------------------------------------------------------------------
/**
*/
MultipleRenderTargetBase::~MultipleRenderTargetBase()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
void
MultipleRenderTargetBase::AddRenderTarget(const Ptr<RenderTarget>& rt)
{
n_assert(rt.isvalid());
n_assert(this->numRenderTargets < MaxNumRenderTargets);
this->renderTarget[this->numRenderTargets] = rt;
this->renderTarget[this->numRenderTargets]->SetMRTIndex(this->numRenderTargets);
this->numRenderTargets++;
}
//------------------------------------------------------------------------------
/**
*/
void
MultipleRenderTargetBase::BeginPass()
{
IndexT i;
for (i = 0; i < this->numRenderTargets; i++)
{
uint clearFlags = this->renderTarget[i]->GetClearFlags();
this->renderTarget[i]->SetClearFlags(this->clearFlags[i]);
this->renderTarget[i]->SetClearColor(this->clearColor[i]);
this->renderTarget[i]->BeginPass();
}
}
//------------------------------------------------------------------------------
/**
*/
void
MultipleRenderTargetBase::BeginBatch(CoreGraphics::FrameBatchType::Code batchType)
{
IndexT i;
for (i = 0; i < this->numRenderTargets; i++)
{
this->renderTarget[i]->BeginBatch(batchType);
}
}
//------------------------------------------------------------------------------
/**
*/
void
MultipleRenderTargetBase::EndBatch()
{
IndexT i;
for (i = 0; i < this->numRenderTargets; i++)
{
this->renderTarget[i]->EndBatch();
}
}
//------------------------------------------------------------------------------
/**
*/
void
MultipleRenderTargetBase::EndPass()
{
IndexT i;
for (i = 0; i < this->numRenderTargets; i++)
{
this->renderTarget[i]->EndPass();
}
}
//------------------------------------------------------------------------------
/**
*/
void
MultipleRenderTargetBase::OnDisplayResized(SizeT width, SizeT height)
{
// override me
}
} // namespace Base | 25.05042 | 84 | 0.482724 | gscept |
4fb7a2f953cc7c8e7943c2a7b5d9c4caf1c4d5a3 | 1,144 | cpp | C++ | cpp/subprojects/common/src/common/data/vector_dok.cpp | Waguy02/Boomer-Scripted | b06bb9213d64dca0c05d41701dea12666931618c | [
"MIT"
] | 8 | 2020-06-30T01:06:43.000Z | 2022-03-14T01:58:29.000Z | cpp/subprojects/common/src/common/data/vector_dok.cpp | Waguy02/Boomer-Scripted | b06bb9213d64dca0c05d41701dea12666931618c | [
"MIT"
] | 3 | 2020-12-14T11:30:18.000Z | 2022-02-07T06:31:51.000Z | cpp/subprojects/common/src/common/data/vector_dok.cpp | Waguy02/Boomer-Scripted | b06bb9213d64dca0c05d41701dea12666931618c | [
"MIT"
] | 4 | 2020-06-24T08:45:00.000Z | 2021-12-23T21:44:51.000Z | #include "common/data/vector_dok.hpp"
template<typename T>
DokVector<T>::DokVector(T sparseValue)
: sparseValue_(sparseValue) {
}
template<typename T>
typename DokVector<T>::iterator DokVector<T>::begin() {
return data_.begin();
}
template<typename T>
typename DokVector<T>::iterator DokVector<T>::end() {
return data_.end();
}
template<typename T>
typename DokVector<T>::const_iterator DokVector<T>::cbegin() const {
return data_.cbegin();
}
template<typename T>
typename DokVector<T>::const_iterator DokVector<T>::cend() const {
return data_.cend();
}
template<typename T>
const T& DokVector<T>::operator[](uint32 pos) const {
auto it = data_.find(pos);
return it != data_.cend() ? it->second : sparseValue_;
}
template<typename T>
void DokVector<T>::set(uint32 pos, T value) {
auto result = data_.emplace(pos, value);
if (!result.second) {
result.first->second = value;
}
}
template<typename T>
void DokVector<T>::clear() {
data_.clear();
}
template class DokVector<uint8>;
template class DokVector<uint32>;
template class DokVector<float32>;
template class DokVector<float64>;
| 21.584906 | 68 | 0.698427 | Waguy02 |
4fb7e82857d84cd5366a009336fff5bb0ea3b537 | 1,814 | cpp | C++ | tests/src/test_rates_root.cpp | JhaPrajjwal/k40gen | 89cd669d8e7327569705033ea299f32849a0a896 | [
"Apache-2.0"
] | 3 | 2019-03-22T15:03:29.000Z | 2019-07-03T12:08:48.000Z | tests/src/test_rates_root.cpp | JhaPrajjwal/k40gen | 89cd669d8e7327569705033ea299f32849a0a896 | [
"Apache-2.0"
] | 1 | 2019-04-01T08:21:04.000Z | 2019-04-01T08:22:45.000Z | tests/src/test_rates_root.cpp | JhaPrajjwal/k40gen | 89cd669d8e7327569705033ea299f32849a0a896 | [
"Apache-2.0"
] | 5 | 2019-03-22T15:03:33.000Z | 2019-07-16T19:19:40.000Z | #include <numeric>
#include <iostream>
#include <array>
#include <iomanip>
#include <generate.h>
#include <storage.h>
#include <test_functions.h>
#include <TApplication.h>
#include <TH1.h>
#include <TF1.h>
#include <TFitResult.h>
#include <TCanvas.h>
#include <TROOT.h>
#define CATCH_CONFIG_RUNNER
#include "catch2/catch.hpp"
using namespace std;
int main(int argc, char* argv[]) {
gROOT->SetBatch();
return Catch::Session().run( argc, argv );
}
TEST_CASE( "Rates makes sense [ROOT]", "[rates_ROOT]" ) {
map<bool, unique_ptr<TH1I>> histos;
array<float, 4> rates{7000., 0., 0., 0.};
for (bool use_avx2 : {false, true}) {
string name = string{"diffs_"} + (use_avx2 ? "avx2" : "scalar");
auto r = histos.emplace(use_avx2, make_unique<TH1I>(name.c_str(), name.c_str(), 100, 0, 1000000));
auto& time_histo = r.first->second;
Generators gens{1052, 9523, rates};
long dt = std::lround(1e7);
long time_start = 0, time_end = time_start + dt;
auto [times, values] = generate(time_start, time_end, gens, "reference", use_avx2);
const size_t n_times = times.size();
for (size_t i = 0; i < n_times - 1; ++i) {
if (((values[i + 1]) >> 8) == (values[i] >> 8)) {
time_histo->Fill(times[i + 1] - times[i]);
}
}
TF1 expo{"exp", "expo", time_histo->GetBinCenter(1),
time_histo->GetBinCenter(1 + time_histo->GetNbinsX())};
auto fit = time_histo->Fit(&expo, "RS");
// parameter is negative
REQUIRE(std::fabs(rates[0] + (fit->Parameter(1) * 1e9)) / rates[0] < 1e-3);
}
TCanvas canvas{"canvas", "canvas", 600, 800};
canvas.Divide(1, 2);
for (auto& [arch, histo] : histos) {
canvas.cd(arch + 1);
histo->Draw();
}
canvas.Print("distributions.png");
}
| 26.289855 | 104 | 0.601985 | JhaPrajjwal |
4fb84a3b3aa2b769bcbd0205f640df54c7e9d1fc | 13,607 | cc | C++ | src/atlas/parallel/GatherScatter.cc | wdeconinck/atlas | 8949d2b362b9b5431023a967bcf4ca84f6b8ce05 | [
"Apache-2.0"
] | 3 | 2021-08-17T03:08:45.000Z | 2021-09-09T09:22:54.000Z | src/atlas/parallel/GatherScatter.cc | pmarguinaud/atlas | 7e0a1251685e07a5dcccc84f4d9251d5a066e2ee | [
"Apache-2.0"
] | 62 | 2020-10-21T15:27:38.000Z | 2022-03-28T12:42:43.000Z | src/atlas/parallel/GatherScatter.cc | pmarguinaud/atlas | 7e0a1251685e07a5dcccc84f4d9251d5a066e2ee | [
"Apache-2.0"
] | 1 | 2021-03-10T19:19:08.000Z | 2021-03-10T19:19:08.000Z | /*
* (C) Copyright 2013 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation
* nor does it submit to any jurisdiction.
*/
#include <algorithm>
#include <iostream>
#include <numeric>
#include <sstream>
#include <stdexcept>
#include "atlas/array.h"
#include "atlas/array/ArrayView.h"
#include "atlas/parallel/GatherScatter.h"
#include "atlas/parallel/mpi/Statistics.h"
#include "atlas/runtime/Log.h"
#include "atlas/runtime/Trace.h"
namespace atlas {
namespace parallel {
namespace {
struct IsGhostPoint {
IsGhostPoint( const int part[], const idx_t ridx[], const idx_t base, const int N ) {
part_ = part;
ridx_ = ridx;
base_ = base;
mypart_ = mpi::rank();
}
bool operator()( idx_t idx ) {
if ( part_[idx] != mypart_ ) {
return true;
}
if ( ridx_[idx] != base_ + idx ) {
return true;
}
return false;
}
int mypart_;
const int* part_;
const idx_t* ridx_;
idx_t base_;
};
struct Node {
int p;
idx_t i;
gidx_t g;
Node() = default;
Node( gidx_t gid, int part, idx_t idx ) {
g = gid;
p = part;
i = idx;
}
bool operator<( const Node& other ) const { return ( g < other.g ); }
bool operator==( const Node& other ) const { return ( g == other.g ); }
};
} // namespace
GatherScatter::GatherScatter() : name_(), is_setup_( false ) {
myproc = mpi::rank();
nproc = mpi::size();
}
GatherScatter::GatherScatter( const std::string& name ) : name_( name ), is_setup_( false ) {
myproc = mpi::rank();
nproc = mpi::size();
}
void GatherScatter::setup( const int part[], const idx_t remote_idx[], const int base, const gidx_t glb_idx[],
const int mask[], const idx_t parsize ) {
ATLAS_TRACE( "GatherScatter::setup" );
parsize_ = parsize;
glbcounts_.resize( nproc );
glbcounts_.assign( nproc, 0 );
glbdispls_.resize( nproc );
glbdispls_.assign( nproc, 0 );
const idx_t nvar = 3;
std::vector<gidx_t> sendnodes( parsize_ * nvar );
loccnt_ = 0;
for ( idx_t n = 0; n < parsize_; ++n ) {
if ( !mask[n] ) {
sendnodes[loccnt_++] = glb_idx[n];
sendnodes[loccnt_++] = part[n];
sendnodes[loccnt_++] = remote_idx[n] - base;
}
}
ATLAS_TRACE_MPI( ALLGATHER ) { mpi::comm().allGather( loccnt_, glbcounts_.begin(), glbcounts_.end() ); }
glbcnt_ = std::accumulate( glbcounts_.begin(), glbcounts_.end(), 0 );
glbdispls_[0] = 0;
for ( idx_t jproc = 1; jproc < nproc; ++jproc ) // start at 1
{
glbdispls_[jproc] = glbcounts_[jproc - 1] + glbdispls_[jproc - 1];
}
std::vector<gidx_t> recvnodes( glbcnt_ );
ATLAS_TRACE_MPI( ALLGATHER ) {
mpi::comm().allGatherv( sendnodes.begin(), sendnodes.begin() + loccnt_, recvnodes.data(), glbcounts_.data(),
glbdispls_.data() );
}
// Load recvnodes in sorting structure
idx_t nb_recv_nodes = glbcnt_ / nvar;
std::vector<Node> node_sort( nb_recv_nodes );
for ( idx_t n = 0; n < nb_recv_nodes; ++n ) {
node_sort[n].g = recvnodes[n * nvar + 0];
node_sort[n].p = recvnodes[n * nvar + 1];
node_sort[n].i = recvnodes[n * nvar + 2];
}
recvnodes.clear();
// Sort on "g" member, and remove duplicates
ATLAS_TRACE_SCOPE( "sorting" ) {
std::sort( node_sort.begin(), node_sort.end() );
node_sort.erase( std::unique( node_sort.begin(), node_sort.end() ), node_sort.end() );
}
glbcounts_.assign( nproc, 0 );
glbdispls_.assign( nproc, 0 );
for ( size_t n = 0; n < node_sort.size(); ++n ) {
++glbcounts_[node_sort[n].p];
}
glbdispls_[0] = 0;
for ( idx_t jproc = 1; jproc < nproc; ++jproc ) // start at 1
{
glbdispls_[jproc] = glbcounts_[jproc - 1] + glbdispls_[jproc - 1];
}
glbcnt_ = std::accumulate( glbcounts_.begin(), glbcounts_.end(), 0 );
loccnt_ = glbcounts_[myproc];
glbmap_.clear();
glbmap_.resize( glbcnt_ );
locmap_.clear();
locmap_.resize( loccnt_ );
std::vector<int> idx( nproc, 0 );
int n{0};
for ( const auto& node : node_sort ) {
idx_t jproc = node.p;
glbmap_[glbdispls_[jproc] + idx[jproc]] = n++;
if ( jproc == myproc ) {
locmap_[idx[jproc]] = node.i;
}
++idx[jproc];
}
is_setup_ = true;
}
void GatherScatter::setup( const int part[], const idx_t remote_idx[], const int base, const gidx_t glb_idx[],
const idx_t parsize ) {
std::vector<int> mask( parsize );
IsGhostPoint is_ghost( part, remote_idx, base, parsize );
for ( idx_t jj = 0; jj < parsize; ++jj ) {
mask[jj] = is_ghost( jj ) ? 1 : 0;
}
setup( part, remote_idx, base, glb_idx, mask.data(), parsize );
}
/////////////////////
GatherScatter* atlas__GatherScatter__new() {
return new GatherScatter();
}
void atlas__GatherScatter__delete( GatherScatter* This ) {
delete This;
}
void atlas__GatherScatter__setup32( GatherScatter* This, int part[], idx_t remote_idx[], int base, int glb_idx[],
int parsize ) {
#if ATLAS_BITS_GLOBAL == 32
This->setup( part, remote_idx, base, glb_idx, parsize );
#else
std::vector<gidx_t> glb_idx_convert( parsize );
for ( int j = 0; j < parsize; ++j ) {
glb_idx_convert[j] = glb_idx[j];
}
This->setup( part, remote_idx, base, glb_idx_convert.data(), parsize );
#endif
}
void atlas__GatherScatter__setup64( GatherScatter* This, int part[], idx_t remote_idx[], int base, long glb_idx[],
int parsize ) {
#if ATLAS_BITS_GLOBAL == 64
This->setup( part, remote_idx, base, glb_idx, parsize );
#else
std::vector<gidx_t> glb_idx_convert( parsize );
for ( idx_t j = 0; j < parsize; ++j ) {
glb_idx_convert[j] = glb_idx[j];
}
This->setup( part, remote_idx, base, glb_idx_convert.data(), parsize );
#endif
}
int atlas__GatherScatter__glb_dof( GatherScatter* This ) {
return This->glb_dof();
}
void atlas__GatherScatter__gather_int( GatherScatter* This, int lfield[], int lvar_strides[], int lvar_extents[],
int lvar_rank, int gfield[], int gvar_strides[], int gvar_extents[],
int gvar_rank ) {
std::vector<idx_t> lvstrides( lvar_rank );
std::vector<idx_t> lvextents( lvar_rank );
std::vector<idx_t> gvstrides( gvar_rank );
std::vector<idx_t> gvextents( gvar_rank );
for ( int n = 0; n < lvar_rank; ++n ) {
lvstrides[n] = lvar_strides[n];
lvextents[n] = lvar_extents[n];
}
for ( int n = 0; n < gvar_rank; ++n ) {
gvstrides[n] = gvar_strides[n];
gvextents[n] = gvar_extents[n];
}
This->gather( lfield, lvstrides.data(), lvextents.data(), lvar_rank, gfield, gvstrides.data(), gvextents.data(),
gvar_rank );
}
void atlas__GatherScatter__gather_long( GatherScatter* This, long lfield[], int lvar_strides[], int lvar_extents[],
int lvar_rank, long gfield[], int gvar_strides[], int gvar_extents[],
int gvar_rank ) {
std::vector<idx_t> lvstrides( lvar_rank );
std::vector<idx_t> lvextents( lvar_rank );
std::vector<idx_t> gvstrides( gvar_rank );
std::vector<idx_t> gvextents( gvar_rank );
for ( int n = 0; n < lvar_rank; ++n ) {
lvstrides[n] = lvar_strides[n];
lvextents[n] = lvar_extents[n];
}
for ( int n = 0; n < gvar_rank; ++n ) {
gvstrides[n] = gvar_strides[n];
gvextents[n] = gvar_extents[n];
}
This->gather( lfield, lvstrides.data(), lvextents.data(), lvar_rank, gfield, gvstrides.data(), gvextents.data(),
gvar_rank );
}
void atlas__GatherScatter__gather_float( GatherScatter* This, float lfield[], int lvar_strides[], int lvar_extents[],
int lvar_rank, float gfield[], int gvar_strides[], int gvar_extents[],
int gvar_rank ) {
std::vector<idx_t> lvstrides( lvar_rank );
std::vector<idx_t> lvextents( lvar_rank );
std::vector<idx_t> gvstrides( gvar_rank );
std::vector<idx_t> gvextents( gvar_rank );
for ( int n = 0; n < lvar_rank; ++n ) {
lvstrides[n] = lvar_strides[n];
lvextents[n] = lvar_extents[n];
}
for ( int n = 0; n < gvar_rank; ++n ) {
gvstrides[n] = gvar_strides[n];
gvextents[n] = gvar_extents[n];
}
This->gather( lfield, lvstrides.data(), lvextents.data(), lvar_rank, gfield, gvstrides.data(), gvextents.data(),
gvar_rank );
}
void atlas__GatherScatter__gather_double( GatherScatter* This, double lfield[], int lvar_strides[], int lvar_extents[],
int lvar_rank, double gfield[], int gvar_strides[], int gvar_extents[],
int gvar_rank ) {
std::vector<idx_t> lvstrides( lvar_rank );
std::vector<idx_t> lvextents( lvar_rank );
std::vector<idx_t> gvstrides( gvar_rank );
std::vector<idx_t> gvextents( gvar_rank );
for ( int n = 0; n < lvar_rank; ++n ) {
lvstrides[n] = lvar_strides[n];
lvextents[n] = lvar_extents[n];
}
for ( int n = 0; n < gvar_rank; ++n ) {
gvstrides[n] = gvar_strides[n];
gvextents[n] = gvar_extents[n];
}
This->gather( lfield, lvstrides.data(), lvextents.data(), lvar_rank, gfield, gvstrides.data(), gvextents.data(),
gvar_rank );
}
void atlas__GatherScatter__scatter_int( GatherScatter* This, int gfield[], int gvar_strides[], int gvar_extents[],
int gvar_rank, int lfield[], int lvar_strides[], int lvar_extents[],
int lvar_rank ) {
std::vector<idx_t> lvstrides( lvar_rank );
std::vector<idx_t> lvextents( lvar_rank );
std::vector<idx_t> gvstrides( gvar_rank );
std::vector<idx_t> gvextents( gvar_rank );
for ( int n = 0; n < lvar_rank; ++n ) {
lvstrides[n] = lvar_strides[n];
lvextents[n] = lvar_extents[n];
}
for ( int n = 0; n < gvar_rank; ++n ) {
gvstrides[n] = gvar_strides[n];
gvextents[n] = gvar_extents[n];
}
This->scatter( gfield, gvstrides.data(), gvextents.data(), gvar_rank, lfield, lvstrides.data(), lvextents.data(),
lvar_rank );
}
void atlas__GatherScatter__scatter_long( GatherScatter* This, long gfield[], int gvar_strides[], int gvar_extents[],
int gvar_rank, long lfield[], int lvar_strides[], int lvar_extents[],
int lvar_rank ) {
std::vector<idx_t> lvstrides( lvar_rank );
std::vector<idx_t> lvextents( lvar_rank );
std::vector<idx_t> gvstrides( gvar_rank );
std::vector<idx_t> gvextents( gvar_rank );
for ( int n = 0; n < lvar_rank; ++n ) {
lvstrides[n] = lvar_strides[n];
lvextents[n] = lvar_extents[n];
}
for ( int n = 0; n < gvar_rank; ++n ) {
gvstrides[n] = gvar_strides[n];
gvextents[n] = gvar_extents[n];
}
This->scatter( gfield, gvstrides.data(), gvextents.data(), gvar_rank, lfield, lvstrides.data(), lvextents.data(),
lvar_rank );
}
void atlas__GatherScatter__scatter_float( GatherScatter* This, float gfield[], int gvar_strides[], int gvar_extents[],
int gvar_rank, float lfield[], int lvar_strides[], int lvar_extents[],
int lvar_rank ) {
std::vector<idx_t> lvstrides( lvar_rank );
std::vector<idx_t> lvextents( lvar_rank );
std::vector<idx_t> gvstrides( gvar_rank );
std::vector<idx_t> gvextents( gvar_rank );
for ( int n = 0; n < lvar_rank; ++n ) {
lvstrides[n] = lvar_strides[n];
lvextents[n] = lvar_extents[n];
}
for ( int n = 0; n < gvar_rank; ++n ) {
gvstrides[n] = gvar_strides[n];
gvextents[n] = gvar_extents[n];
}
This->scatter( gfield, gvstrides.data(), gvextents.data(), gvar_rank, lfield, lvstrides.data(), lvextents.data(),
lvar_rank );
}
void atlas__GatherScatter__scatter_double( GatherScatter* This, double gfield[], int gvar_strides[], int gvar_extents[],
int gvar_rank, double lfield[], int lvar_strides[], int lvar_extents[],
int lvar_rank ) {
std::vector<idx_t> lvstrides( lvar_rank );
std::vector<idx_t> lvextents( lvar_rank );
std::vector<idx_t> gvstrides( gvar_rank );
std::vector<idx_t> gvextents( gvar_rank );
for ( int n = 0; n < lvar_rank; ++n ) {
lvstrides[n] = lvar_strides[n];
lvextents[n] = lvar_extents[n];
}
for ( int n = 0; n < gvar_rank; ++n ) {
gvstrides[n] = gvar_strides[n];
gvextents[n] = gvar_extents[n];
}
This->scatter( gfield, gvstrides.data(), gvextents.data(), gvar_rank, lfield, lvstrides.data(), lvextents.data(),
lvar_rank );
}
/////////////////////
} // namespace parallel
} // namespace atlas
| 36.18883 | 120 | 0.582715 | wdeconinck |
4fbd4fd29e2e81fd5b8e65f374e2602f9d35217e | 9,645 | cpp | C++ | AVSCommon/Utils/src/LibcurlUtils/LibCurlHttpContentFetcher.cpp | merdahl/avs-device-sdk | 2cc16d8cc472afc9b7a736a8c1169f12b71dd229 | [
"Apache-2.0"
] | 1 | 2022-01-09T21:26:04.000Z | 2022-01-09T21:26:04.000Z | AVSCommon/Utils/src/LibcurlUtils/LibCurlHttpContentFetcher.cpp | justdoGIT/avs-device-sdk | 2cc16d8cc472afc9b7a736a8c1169f12b71dd229 | [
"Apache-2.0"
] | null | null | null | AVSCommon/Utils/src/LibcurlUtils/LibCurlHttpContentFetcher.cpp | justdoGIT/avs-device-sdk | 2cc16d8cc472afc9b7a736a8c1169f12b71dd229 | [
"Apache-2.0"
] | 1 | 2018-10-12T07:58:44.000Z | 2018-10-12T07:58:44.000Z | /*
* LibCurlHttpContentFetcher.cpp
*
* Copyright 2016-2017 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 <AVSCommon/Utils/LibcurlUtils/CurlEasyHandleWrapper.h>
#include <AVSCommon/Utils/LibcurlUtils/LibCurlHttpContentFetcher.h>
#include <AVSCommon/Utils/Memory/Memory.h>
#include <AVSCommon/Utils/SDS/InProcessSDS.h>
namespace alexaClientSDK {
namespace avsCommon {
namespace utils {
namespace libcurlUtils {
/// String to identify log entries originating from this file.
static const std::string TAG("LibCurlHttpContentFetcher");
/**
* Create a LogEntry using this file's TAG and the specified event string.
*
* @param The event string for this @c LogEntry.
*/
#define LX(event) alexaClientSDK::avsCommon::utils::logger::LogEntry(TAG, event)
size_t LibCurlHttpContentFetcher::headerCallback(char* data, size_t size, size_t nmemb, void* userData) {
if (!userData) {
ACSDK_ERROR(LX("headerCallback").d("reason", "nullUserDataPointer"));
return 0;
}
std::string line(static_cast<const char*>(data), size * nmemb);
if (line.find("HTTP") == 0) {
// To find lines like: "HTTP/1.1 200 OK"
std::istringstream iss(line);
std::string httpVersion;
long statusCode;
iss >> httpVersion >> statusCode;
LibCurlHttpContentFetcher* thisObject = static_cast<LibCurlHttpContentFetcher*>(userData);
thisObject->m_lastStatusCode = statusCode;
} else if (line.find("Content-Type") == 0) {
// To find lines like: "Content-Type: audio/x-mpegurl; charset=utf-8"
std::istringstream iss(line);
std::string contentTypeBeginning;
std::string contentType;
iss >> contentTypeBeginning >> contentType;
contentType.pop_back();
LibCurlHttpContentFetcher* thisObject = static_cast<LibCurlHttpContentFetcher*>(userData);
thisObject->m_lastContentType = contentType;
}
return size * nmemb;
}
size_t LibCurlHttpContentFetcher::bodyCallback(char* data, size_t size, size_t nmemb, void* userData) {
if (!userData) {
ACSDK_ERROR(LX("bodyCallback").d("reason", "nullUserDataPointer"));
return 0;
}
LibCurlHttpContentFetcher* thisObject = static_cast<LibCurlHttpContentFetcher*>(userData);
if (!thisObject->m_bodyCallbackBegan) {
thisObject->m_bodyCallbackBegan = true;
thisObject->m_statusCodePromise.set_value(thisObject->m_lastStatusCode);
thisObject->m_contentTypePromise.set_value(thisObject->m_lastContentType);
}
auto streamWriter = thisObject->m_streamWriter;
if (streamWriter) {
avsCommon::avs::attachment::AttachmentWriter::WriteStatus writeStatus =
avsCommon::avs::attachment::AttachmentWriter::WriteStatus::OK;
auto numBytesWritten = streamWriter->write(data, size * nmemb, &writeStatus);
return numBytesWritten;
} else {
return 0;
}
}
size_t LibCurlHttpContentFetcher::noopCallback(char* data, size_t size, size_t nmemb, void* userData) {
return 0;
}
LibCurlHttpContentFetcher::LibCurlHttpContentFetcher(const std::string& url) :
m_url{url},
m_bodyCallbackBegan{false},
m_lastStatusCode{0} {
m_hasObjectBeenUsed.clear();
}
std::unique_ptr<avsCommon::utils::HTTPContent> LibCurlHttpContentFetcher::getContent(FetchOptions fetchOption) {
if (m_hasObjectBeenUsed.test_and_set()) {
return nullptr;
}
if (!m_curlWrapper.setURL(m_url)) {
ACSDK_ERROR(LX("getContentFailed").d("reason", "failedToSetUrl"));
return nullptr;
}
auto curlReturnValue = curl_easy_setopt(m_curlWrapper.getCurlHandle(), CURLOPT_FOLLOWLOCATION, 1L);
if (curlReturnValue != CURLE_OK) {
ACSDK_ERROR(LX("getContentFailed").d("reason", "enableFollowRedirectsFailed"));
return nullptr;
}
curlReturnValue = curl_easy_setopt(m_curlWrapper.getCurlHandle(), CURLOPT_AUTOREFERER, 1L);
if (curlReturnValue != CURLE_OK) {
ACSDK_ERROR(LX("getContentFailed").d("reason", "enableAutoReferralSettingToRedirectsFailed"));
return nullptr;
}
// This enables the libcurl cookie engine, allowing it to send cookies
curlReturnValue = curl_easy_setopt(m_curlWrapper.getCurlHandle(), CURLOPT_COOKIEFILE, "");
if (curlReturnValue != CURLE_OK) {
ACSDK_ERROR(LX("getContentFailed").d("reason", "enableLibCurlCookieEngineFailed"));
return nullptr;
}
auto httpStatusCodeFuture = m_statusCodePromise.get_future();
auto contentTypeFuture = m_contentTypePromise.get_future();
std::shared_ptr<avsCommon::avs::attachment::InProcessAttachment> stream = nullptr;
switch (fetchOption) {
case FetchOptions::CONTENT_TYPE:
/*
* Since this option only wants the content-type, I set a noop callback for parsing the body of the HTTP
* response. For some webpages, it is required to set a body callback in order for the full webpage data
* to render.
*/
curlReturnValue = curl_easy_setopt(m_curlWrapper.getCurlHandle(), CURLOPT_WRITEFUNCTION, noopCallback);
if (curlReturnValue != CURLE_OK) {
ACSDK_ERROR(LX("getContentFailed").d("reason", "failedToSetCurlCallback"));
return nullptr;
}
m_thread = std::thread([this]() {
long finalResponseCode = 0;
char* contentType = nullptr;
auto curlReturnValue = curl_easy_perform(m_curlWrapper.getCurlHandle());
if (curlReturnValue != CURLE_OK && curlReturnValue != CURLE_WRITE_ERROR) {
ACSDK_ERROR(LX("curlEasyPerformFailed").d("error", curl_easy_strerror(curlReturnValue)));
}
curlReturnValue =
curl_easy_getinfo(m_curlWrapper.getCurlHandle(), CURLINFO_RESPONSE_CODE, &finalResponseCode);
if (curlReturnValue != CURLE_OK) {
ACSDK_ERROR(LX("curlEasyGetInfoFailed").d("error", curl_easy_strerror(curlReturnValue)));
}
ACSDK_DEBUG9(LX("getContent").d("responseCode", finalResponseCode).sensitive("url", m_url));
m_statusCodePromise.set_value(finalResponseCode);
curlReturnValue = curl_easy_getinfo(m_curlWrapper.getCurlHandle(), CURLINFO_CONTENT_TYPE, &contentType);
if (curlReturnValue == CURLE_OK && contentType) {
ACSDK_DEBUG9(LX("getContent").d("contentType", contentType).sensitive("url", m_url));
m_contentTypePromise.set_value(std::string(contentType));
} else {
ACSDK_ERROR(LX("curlEasyGetInfoFailed").d("error", curl_easy_strerror(curlReturnValue)));
ACSDK_ERROR(LX("getContent").d("contentType", "failedToGetContentType").sensitive("url", m_url));
m_contentTypePromise.set_value("");
}
});
break;
case FetchOptions::ENTIRE_BODY:
// Using the url as the identifier for the attachment
stream = std::make_shared<avsCommon::avs::attachment::InProcessAttachment>(m_url);
m_streamWriter = stream->createWriter();
if (!m_streamWriter) {
ACSDK_ERROR(LX("getContentFailed").d("reason", "failedToCreateWriter"));
return nullptr;
}
if (!m_curlWrapper.setWriteCallback(bodyCallback, this)) {
ACSDK_ERROR(LX("getContentFailed").d("reason", "failedToSetCurlBodyCallback"));
return nullptr;
}
if (!m_curlWrapper.setHeaderCallback(headerCallback, this)) {
ACSDK_ERROR(LX("getContentFailed").d("reason", "failedToSetCurlHeaderCallback"));
return nullptr;
}
m_thread = std::thread([this]() {
auto curlReturnValue = curl_easy_perform(m_curlWrapper.getCurlHandle());
if (curlReturnValue != CURLE_OK) {
ACSDK_ERROR(LX("curlEasyPerformFailed").d("error", curl_easy_strerror(curlReturnValue)));
}
if (!m_bodyCallbackBegan) {
m_statusCodePromise.set_value(m_lastStatusCode);
m_contentTypePromise.set_value(m_lastContentType);
}
/*
* Curl easy perform has finished and all data has been written. Closing writer so that readers know
* when they have caught up and read everything.
*/
m_streamWriter->close();
});
break;
default:
return nullptr;
}
return avsCommon::utils::memory::make_unique<avsCommon::utils::HTTPContent>(
avsCommon::utils::HTTPContent{std::move(httpStatusCodeFuture), std::move(contentTypeFuture), stream});
}
LibCurlHttpContentFetcher::~LibCurlHttpContentFetcher() {
if (m_thread.joinable()) {
m_thread.join();
}
}
} // namespace libcurlUtils
} // namespace utils
} // namespace avsCommon
} // namespace alexaClientSDK
| 45.928571 | 120 | 0.655677 | merdahl |
4fbd68a1b78c449f2e424f71ef756e62ead38c8b | 4,317 | cpp | C++ | source/PyMaterialX/PyMaterialXCore/PyDefinition.cpp | nzanepro/MaterialX | 9100ac81231d87f7fbf4dc32f7030867e466bc41 | [
"BSD-3-Clause"
] | null | null | null | source/PyMaterialX/PyMaterialXCore/PyDefinition.cpp | nzanepro/MaterialX | 9100ac81231d87f7fbf4dc32f7030867e466bc41 | [
"BSD-3-Clause"
] | null | null | null | source/PyMaterialX/PyMaterialXCore/PyDefinition.cpp | nzanepro/MaterialX | 9100ac81231d87f7fbf4dc32f7030867e466bc41 | [
"BSD-3-Clause"
] | null | null | null | //
// TM & (c) 2017 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd.
// All rights reserved. See LICENSE.txt for license.
//
#include <PyMaterialX/PyMaterialX.h>
#include <MaterialXCore/Definition.h>
#include <MaterialXCore/Material.h>
namespace py = pybind11;
namespace mx = MaterialX;
void bindPyDefinition(py::module& mod)
{
py::class_<mx::NodeDef, mx::NodeDefPtr, mx::InterfaceElement>(mod, "NodeDef")
.def("setNodeString", &mx::NodeDef::setNodeString)
.def("hasNodeString", &mx::NodeDef::hasNodeString)
.def("getNodeString", &mx::NodeDef::getNodeString)
.def("setNodeGroup", &mx::NodeDef::setNodeGroup)
.def("hasNodeGroup", &mx::NodeDef::hasNodeGroup)
.def("getNodeGroup", &mx::NodeDef::getNodeGroup)
.def("getImplementation", &mx::NodeDef::getImplementation)
.def("getImplementation", &mx::NodeDef::getImplementation,
py::arg("target") = mx::EMPTY_STRING,
py::arg("language") = mx::EMPTY_STRING)
.def("getInstantiatingShaderRefs", &mx::NodeDef::getInstantiatingShaderRefs)
.def("isVersionCompatible", &mx::NodeDef::isVersionCompatible)
.def_readonly_static("CATEGORY", &mx::NodeDef::CATEGORY)
.def_readonly_static("NODE_ATTRIBUTE", &mx::NodeDef::NODE_ATTRIBUTE);
py::class_<mx::Implementation, mx::ImplementationPtr, mx::InterfaceElement>(mod, "Implementation")
.def("setFile", &mx::Implementation::setFile)
.def("hasFile", &mx::Implementation::hasFile)
.def("getFile", &mx::Implementation::getFile)
.def("setFunction", &mx::Implementation::setFunction)
.def("hasFunction", &mx::Implementation::hasFunction)
.def("getFunction", &mx::Implementation::getFunction)
.def("setLanguage", &mx::Implementation::setLanguage)
.def("hasLanguage", &mx::Implementation::hasLanguage)
.def("getLanguage", &mx::Implementation::getLanguage)
.def("setNodeDef", &mx::Implementation::setNodeDef)
.def("getNodeDef", &mx::Implementation::getNodeDef)
.def_readonly_static("CATEGORY", &mx::Implementation::CATEGORY)
.def_readonly_static("FILE_ATTRIBUTE", &mx::Implementation::FILE_ATTRIBUTE)
.def_readonly_static("FUNCTION_ATTRIBUTE", &mx::Implementation::FUNCTION_ATTRIBUTE)
.def_readonly_static("LANGUAGE_ATTRIBUTE", &mx::Implementation::LANGUAGE_ATTRIBUTE);
py::class_<mx::TypeDef, mx::TypeDefPtr, mx::Element>(mod, "TypeDef")
.def("setSemantic", &mx::TypeDef::setSemantic)
.def("hasSemantic", &mx::TypeDef::hasSemantic)
.def("getSemantic", &mx::TypeDef::getSemantic)
.def("setContext", &mx::TypeDef::setContext)
.def("hasContext", &mx::TypeDef::hasContext)
.def("getContext", &mx::TypeDef::getContext)
.def("addMember", &mx::TypeDef::addMember,
py::arg("name") = mx::EMPTY_STRING)
.def("getMember", &mx::TypeDef::getMember)
.def("getMembers", &mx::TypeDef::getMembers)
.def("removeMember", &mx::TypeDef::removeMember)
.def_readonly_static("CATEGORY", &mx::TypeDef::CATEGORY)
.def_readonly_static("SEMANTIC_ATTRIBUTE", &mx::TypeDef::SEMANTIC_ATTRIBUTE)
.def_readonly_static("CONTEXT_ATTRIBUTE", &mx::TypeDef::CONTEXT_ATTRIBUTE);
py::class_<mx::Member, mx::MemberPtr, mx::TypedElement>(mod, "Member")
.def_readonly_static("CATEGORY", &mx::TypeDef::CATEGORY);
py::class_<mx::Unit, mx::UnitPtr, mx::Element>(mod, "Unit")
.def_readonly_static("CATEGORY", &mx::Unit::CATEGORY);
py::class_<mx::UnitDef, mx::UnitDefPtr, mx::Element>(mod, "UnitDef")
.def("setUnitType", &mx::UnitDef::hasUnitType)
.def("hasUnitType", &mx::UnitDef::hasUnitType)
.def("getUnitType", &mx::UnitDef::getUnitType)
.def("addUnit", &mx::UnitDef::addUnit)
.def("getUnit", &mx::UnitDef::getUnit)
.def("getUnits", &mx::UnitDef::getUnits)
.def_readonly_static("CATEGORY", &mx::UnitDef::CATEGORY)
.def_readonly_static("UNITTYPE_ATTRIBUTE", &mx::UnitDef::UNITTYPE_ATTRIBUTE);
py::class_<mx::UnitTypeDef, mx::UnitTypeDefPtr, mx::Element>(mod, "UnitTypeDef")
.def("getUnitDefs", &mx::UnitTypeDef::getUnitDefs)
.def_readonly_static("CATEGORY", &mx::UnitTypeDef::CATEGORY);
}
| 50.197674 | 102 | 0.665508 | nzanepro |
4fbf226090e4518546a97c8a6309253c44196e1c | 1,756 | hpp | C++ | lshkit/trunk/3rd-party/boost/boost/mpl/aux_/msvc_eti_base.hpp | wzj1695224/BinClone | 3b6dedb9a1f08be6dbcdce8f3278351ef5530ed8 | [
"Apache-2.0"
] | 21 | 2015-05-22T09:22:16.000Z | 2021-04-06T18:54:07.000Z | lshkit/trunk/3rd-party/boost/boost/mpl/aux_/msvc_eti_base.hpp | mrfarhadi/BinClone | 035c20ab27ec00935c12ce54fe9c52bba4aaeff2 | [
"Apache-2.0"
] | 1 | 2020-05-21T08:43:19.000Z | 2020-05-21T08:43:19.000Z | lshkit/trunk/3rd-party/boost/boost/mpl/aux_/msvc_eti_base.hpp | mrfarhadi/BinClone | 035c20ab27ec00935c12ce54fe9c52bba4aaeff2 | [
"Apache-2.0"
] | 11 | 2015-09-08T20:56:14.000Z | 2019-12-22T12:52:45.000Z |
#ifndef BOOST_MPL_AUX_MSVC_ETI_BASE_HPP_INCLUDED
#define BOOST_MPL_AUX_MSVC_ETI_BASE_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2001-2004
//
// 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)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id: msvc_eti_base.hpp,v 1.2 2009/02/16 01:51:05 wdong-pku Exp $
// $Date: 2009/02/16 01:51:05 $
// $Revision: 1.2 $
#include <boost/mpl/aux_/is_msvc_eti_arg.hpp>
#include <boost/mpl/aux_/config/eti.hpp>
#include <boost/mpl/aux_/config/gcc.hpp>
#include <boost/mpl/aux_/config/workaround.hpp>
namespace boost { namespace mpl { namespace aux {
#if defined(BOOST_MPL_CFG_MSVC_70_ETI_BUG)
template< bool > struct msvc_eti_base_impl
{
template< typename T > struct result_
: T
{
typedef T type;
};
};
template<> struct msvc_eti_base_impl<true>
{
template< typename T > struct result_
{
typedef result_ type;
typedef result_ first;
typedef result_ second;
typedef result_ tag;
enum { value = 0 };
};
};
template< typename T > struct msvc_eti_base
: msvc_eti_base_impl< is_msvc_eti_arg<T>::value >
::template result_<T>
{
};
#else // !BOOST_MPL_CFG_MSVC_70_ETI_BUG
template< typename T > struct msvc_eti_base
: T
{
#if BOOST_WORKAROUND(BOOST_MPL_CFG_GCC, BOOST_TESTED_AT(0x0304))
msvc_eti_base();
#endif
typedef T type;
};
#endif
template<> struct msvc_eti_base<int>
{
typedef msvc_eti_base type;
typedef msvc_eti_base first;
typedef msvc_eti_base second;
typedef msvc_eti_base tag;
enum { value = 0 };
};
}}}
#endif // BOOST_MPL_AUX_MSVC_ETI_BASE_HPP_INCLUDED
| 22.512821 | 67 | 0.702733 | wzj1695224 |
4fc1fb870b57f09e99aab228be1843909616589a | 5,030 | cpp | C++ | src/Widgets/ThemesSettingsPanel.cpp | huntermalm/Layers | 1f2f6eabe3be8dfbc60d682ca47543f7807a0bbf | [
"MIT"
] | null | null | null | src/Widgets/ThemesSettingsPanel.cpp | huntermalm/Layers | 1f2f6eabe3be8dfbc60d682ca47543f7807a0bbf | [
"MIT"
] | null | null | null | src/Widgets/ThemesSettingsPanel.cpp | huntermalm/Layers | 1f2f6eabe3be8dfbc60d682ca47543f7807a0bbf | [
"MIT"
] | null | null | null | #include "../../include/AttributeWidgets.h"
#include "../../include/Application.h"
#include "../../include/Layouts.h"
#include "../../include/SettingsPanels.h"
using Layers::Button;
using Layers::Combobox;
using Layers::Theme;
using Layers::ThemesSettingsPanel;
ThemesSettingsPanel::ThemesSettingsPanel(QWidget* parent) : Widget(parent)
{
init_child_themeable_reference_list();
init_attributes();
set_icon(new Graphic(":/svgs/panel_icon.svg", QSize(20, 20)));
set_name("themes_settings_panel");
set_proper_name("Themes Panel");
m_theme_label->set_name("theme_label");
m_theme_label->set_proper_name("\"Theme\" Label");
m_theme_label->set_font_size(15);
m_theme_combobox->set_icon(new Graphic(":/svgs/combobox_icon.svg", QSize(21, 18)));
m_theme_combobox->set_item_renaming_disabled(false);
m_theme_combobox->set_name("theme_combobox");
m_theme_combobox->set_proper_name("Theme Combobox");
m_theme_combobox->set_font_size(15);
connect(m_theme_combobox, SIGNAL(item_replaced(const QString&, const QString&)),
layersApp, SLOT(rename_theme(const QString&, const QString&)));
connect(m_theme_combobox, &Combobox::current_item_changed, [this] {
layersApp->apply_theme(layersApp->themes()[m_theme_combobox->current_item()]);
});
m_new_theme_button->set_name("new_theme_button");
m_new_theme_button->set_proper_name("New Theme Button");
m_customize_theme_button->set_name("customize_theme_button");
m_customize_theme_button->set_proper_name("Customize Theme Button");
m_delete_theme_button->set_name("delete_theme_button");
m_delete_theme_button->set_proper_name("Delete Theme Button");
m_theme_info_button->set_name("theme_info_button");
m_theme_info_button->set_proper_name("Theme Info Button");
m_theme_info_button->disable_graphic_hover_color();
m_separator_1->replace_all_attributes_with(m_control_separator);
m_separator_1->setFixedSize(1, 30);
m_separator_2->replace_all_attributes_with(m_control_separator);
m_separator_2->setFixedSize(1, 30);
m_spacer_1->setFixedWidth(12);
m_spacer_2->setFixedWidth(12);
m_control_separator->set_name("separator");
m_control_separator->set_proper_name("Separators");
m_control_separator->setFixedSize(1, 30);
//m_control_separator->set_ACW_primary("border_awc", false);
//m_control_separator->set_ACW_primary("hover_background_caw", false);
//m_control_separator->set_ACW_primary("outline_caw", false);
//m_control_separator->set_ACW_primary("corner_color_caw", false);
//m_control_separator->set_ACW_primary("corner_radii_awc", false);
setup_layout();
}
void ThemesSettingsPanel::init_attributes()
{
a_fill.set_disabled();
m_spacer_1->a_fill.set_disabled();
m_spacer_2->a_fill.set_disabled();
m_theme_info_button->graphic()->svg()->a_use_common_hover_color.set_value(false);
}
void ThemesSettingsPanel::init_child_themeable_reference_list()
{
add_child_themeable_reference(m_theme_label);
add_child_themeable_reference(m_theme_combobox);
add_child_themeable_reference(m_new_theme_button);
add_child_themeable_reference(m_customize_theme_button);
add_child_themeable_reference(m_delete_theme_button);
add_child_themeable_reference(m_theme_info_button);
add_child_themeable_reference(m_control_separator);
}
void ThemesSettingsPanel::apply_theme(Theme& theme)
{
if (theme.is_custom())
show_custom_theme_buttons();
else
show_custom_theme_buttons(false);
Themeable::apply_theme(theme);
}
Button* ThemesSettingsPanel::customize_theme_button() const
{
return m_customize_theme_button;
}
Button* ThemesSettingsPanel::new_theme_button() const
{
return m_new_theme_button;
}
Combobox* ThemesSettingsPanel::theme_combobox() const
{
return m_theme_combobox;
}
void ThemesSettingsPanel::show_custom_theme_buttons(bool cond)
{
if (cond)
{
m_customize_theme_button->show();
m_delete_theme_button->show();
m_separator_2->show();
m_spacer_1->show();
m_spacer_2->show();
}
else
{
m_customize_theme_button->hide();
m_delete_theme_button->hide();
m_separator_2->hide();
m_spacer_1->hide();
m_spacer_2->hide();
}
}
void ThemesSettingsPanel::setup_layout()
{
QHBoxLayout* theme_buttons_hbox = new QHBoxLayout;
theme_buttons_hbox->setContentsMargins(0, 5, 0, 0);
theme_buttons_hbox->setSpacing(0);
theme_buttons_hbox->addWidget(m_new_theme_button);
theme_buttons_hbox->addSpacing(12);
theme_buttons_hbox->addWidget(m_separator_1);
theme_buttons_hbox->addSpacing(12);
theme_buttons_hbox->addWidget(m_customize_theme_button);
theme_buttons_hbox->addWidget(m_delete_theme_button);
theme_buttons_hbox->addWidget(m_spacer_1);
theme_buttons_hbox->addWidget(m_separator_2);
theme_buttons_hbox->addWidget(m_spacer_2);
theme_buttons_hbox->addWidget(m_theme_info_button);
theme_buttons_hbox->addStretch();
VerticalLayout* main_layout = new VerticalLayout;
main_layout->setContentsMargins(32, 32, 0, 0);
main_layout->addWidget(m_theme_label);
main_layout->addWidget(m_theme_combobox);
main_layout->addLayout(theme_buttons_hbox);
main_layout->addStretch();
setLayout(main_layout);
}
| 30.11976 | 84 | 0.79841 | huntermalm |
4fc32173d2cdfb2532a258a3d90c2c36ecacdf0f | 1,809 | inl | C++ | dependencies/checkframebufferstatus/checkFramebufferStatus.inl | jaredhoberock/gotham | e3551cc355646530574d086d7cc2b82e41e8f798 | [
"Apache-2.0"
] | 6 | 2015-12-29T07:21:01.000Z | 2020-05-29T10:47:38.000Z | dependencies/checkframebufferstatus/checkFramebufferStatus.inl | jaredhoberock/gotham | e3551cc355646530574d086d7cc2b82e41e8f798 | [
"Apache-2.0"
] | null | null | null | dependencies/checkframebufferstatus/checkFramebufferStatus.inl | jaredhoberock/gotham | e3551cc355646530574d086d7cc2b82e41e8f798 | [
"Apache-2.0"
] | null | null | null | /*! \file checkFramebufferStatus.inl
* \author Jared Hoberock
* \brief Inline file for checkFramebufferStatus.h.
*/
#include "checkFramebufferStatus.h"
#include <iostream>
void checkFramebufferStatus(const char *filename, const unsigned int lineNumber)
{
GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
if(status != GL_FRAMEBUFFER_COMPLETE_EXT)
{
std::cerr << filename << "(" << lineNumber << "): ";
switch(status)
{
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT:
{
std::cerr << "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT" << std::endl;
break;
} // end case
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT:
{
std::cerr << "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT" << std::endl;
break;
} // end case
case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT:
{
std::cerr << "GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT" << std::endl;
break;
} // end case
case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT:
{
std::cerr << "GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT" << std::endl;
break;
} // end case
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT:
{
std::cerr << "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT" << std::endl;
break;
} // end case
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT:
{
std::cerr << "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT" << std::endl;
break;
} // end case
case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
{
std::cerr << "GL_FRAMEBUFFER_UNSUPPORTED_EXT" << std::endl;
break;
} // end case
} // end switch
} // end if
} // end checkFramebufferStatus()
| 28.714286 | 86 | 0.627418 | jaredhoberock |
4fc35df192304b723558bbf337928fba775972f7 | 7,310 | cpp | C++ | src/lib/operators/projection.cpp | dey4ss/hyrise | c304b9ced36044e303eb8a4d68a05fc7edc04819 | [
"MIT"
] | null | null | null | src/lib/operators/projection.cpp | dey4ss/hyrise | c304b9ced36044e303eb8a4d68a05fc7edc04819 | [
"MIT"
] | null | null | null | src/lib/operators/projection.cpp | dey4ss/hyrise | c304b9ced36044e303eb8a4d68a05fc7edc04819 | [
"MIT"
] | null | null | null | #include "projection.hpp"
#include <algorithm>
#include <functional>
#include <memory>
#include <numeric>
#include <string>
#include <utility>
#include <vector>
#include "expression/evaluation/expression_evaluator.hpp"
#include "expression/expression_utils.hpp"
#include "expression/pqp_column_expression.hpp"
#include "expression/value_expression.hpp"
#include "storage/segment_iterate.hpp"
#include "utils/assert.hpp"
namespace opossum {
Projection::Projection(const std::shared_ptr<const AbstractOperator>& in,
const std::vector<std::shared_ptr<AbstractExpression>>& expressions)
: AbstractReadOnlyOperator(OperatorType::Projection, in), expressions(expressions) {}
const std::string& Projection::name() const {
static const auto name = std::string{"Projection"};
return name;
}
std::shared_ptr<AbstractOperator> Projection::_on_deep_copy(
const std::shared_ptr<AbstractOperator>& copied_input_left,
const std::shared_ptr<AbstractOperator>& copied_input_right) const {
return std::make_shared<Projection>(copied_input_left, expressions_deep_copy(expressions));
}
void Projection::_on_set_parameters(const std::unordered_map<ParameterID, AllTypeVariant>& parameters) {
expressions_set_parameters(expressions, parameters);
}
void Projection::_on_set_transaction_context(const std::weak_ptr<TransactionContext>& transaction_context) {
expressions_set_transaction_context(expressions, transaction_context);
}
std::shared_ptr<const Table> Projection::_on_execute() {
const auto& input_table = *input_table_left();
/**
* If an expression is a PQPColumnExpression then it might be possible to forward the input column, if the
* input TableType (References or Data) matches the output column type (ReferenceSegment or not).
*/
const auto only_projects_columns = std::all_of(expressions.begin(), expressions.end(), [&](const auto& expression) {
return expression->type == ExpressionType::PQPColumn;
});
const auto output_table_type = only_projects_columns ? input_table.type() : TableType::Data;
const auto forward_columns = input_table.type() == output_table_type;
const auto uncorrelated_subquery_results =
ExpressionEvaluator::populate_uncorrelated_subquery_results_cache(expressions);
auto column_is_nullable = std::vector<bool>(expressions.size(), false);
/**
* Perform the projection
*/
auto output_chunk_segments = std::vector<Segments>(input_table.chunk_count());
const auto chunk_count_input_table = input_table.chunk_count();
for (auto chunk_id = ChunkID{0}; chunk_id < chunk_count_input_table; ++chunk_id) {
const auto input_chunk = input_table.get_chunk(chunk_id);
Assert(input_chunk, "Physically deleted chunk should not reach this point, see get_chunk / #1686.");
auto output_segments = Segments{expressions.size()};
ExpressionEvaluator evaluator(input_table_left(), chunk_id, uncorrelated_subquery_results);
for (auto column_id = ColumnID{0}; column_id < expressions.size(); ++column_id) {
const auto& expression = expressions[column_id];
// Forward input column if possible
if (expression->type == ExpressionType::PQPColumn && forward_columns) {
const auto pqp_column_expression = std::static_pointer_cast<PQPColumnExpression>(expression);
output_segments[column_id] = input_chunk->get_segment(pqp_column_expression->column_id);
column_is_nullable[column_id] =
column_is_nullable[column_id] || input_table.column_is_nullable(pqp_column_expression->column_id);
} else if (expression->type == ExpressionType::PQPColumn && !forward_columns) {
// The current column will be returned without any logical modifications. As other columns do get modified (and
// returned as a ValueSegment), all segments (including this one) need to become ValueSegments. This segment is
// not yet a ValueSegment (otherwise forward_columns would be true); thus we need to materialize it.
const auto pqp_column_expression = std::static_pointer_cast<PQPColumnExpression>(expression);
const auto segment = input_chunk->get_segment(pqp_column_expression->column_id);
resolve_data_type(expression->data_type(), [&](const auto data_type) {
using ColumnDataType = typename decltype(data_type)::type;
bool has_null = false;
auto values = pmr_concurrent_vector<ColumnDataType>(segment->size());
auto null_values = pmr_concurrent_vector<bool>(segment->size());
auto chunk_offset = ChunkOffset{0};
segment_iterate<ColumnDataType>(*segment, [&](const auto& position) {
if (position.is_null()) {
has_null = true;
null_values[chunk_offset] = true;
} else {
values[chunk_offset] = position.value();
}
++chunk_offset;
});
auto value_segment = std::shared_ptr<ValueSegment<ColumnDataType>>{};
if (has_null) {
value_segment = std::make_shared<ValueSegment<ColumnDataType>>(std::move(values), std::move(null_values));
} else {
value_segment = std::make_shared<ValueSegment<ColumnDataType>>(std::move(values));
}
output_segments[column_id] = std::move(value_segment);
column_is_nullable[column_id] = has_null;
});
} else {
auto output_segment = evaluator.evaluate_expression_to_segment(*expression);
column_is_nullable[column_id] = column_is_nullable[column_id] || output_segment->is_nullable();
output_segments[column_id] = std::move(output_segment);
}
}
output_chunk_segments[chunk_id] = std::move(output_segments);
}
/**
* Determine the TableColumnDefinitions and build the output table
*/
TableColumnDefinitions column_definitions;
for (auto column_id = ColumnID{0}; column_id < expressions.size(); ++column_id) {
column_definitions.emplace_back(expressions[column_id]->as_column_name(), expressions[column_id]->data_type(),
column_is_nullable[column_id]);
}
auto output_chunks = std::vector<std::shared_ptr<Chunk>>{chunk_count_input_table};
for (auto chunk_id = ChunkID{0}; chunk_id < chunk_count_input_table; ++chunk_id) {
const auto input_chunk = input_table.get_chunk(chunk_id);
Assert(input_chunk, "Physically deleted chunk should not reach this point, see get_chunk / #1686.");
// The output chunk contains all rows that are in the stored chunk, including invalid rows. We forward this
// information so that following operators (currently, the Validate operator) can use it for optimizations.
output_chunks[chunk_id] =
std::make_shared<Chunk>(std::move(output_chunk_segments[chunk_id]), input_chunk->mvcc_data());
output_chunks[chunk_id]->increase_invalid_row_count(input_chunk->invalid_row_count());
}
return std::make_shared<Table>(column_definitions, output_table_type, std::move(output_chunks),
input_table.uses_mvcc());
}
// returns the singleton dummy table used for literal projections
std::shared_ptr<Table> Projection::dummy_table() {
static auto shared_dummy = std::make_shared<DummyTable>();
return shared_dummy;
}
} // namespace opossum
| 45.123457 | 119 | 0.723119 | dey4ss |
4fc3d34ec7353af5e033a67beba373d497b54d53 | 790 | cpp | C++ | Part3/eleven.cpp | praseedpai/BasicCppCourse | fb6c2300dfb48961a5f647a51eb9c2032bfb45ea | [
"MIT"
] | null | null | null | Part3/eleven.cpp | praseedpai/BasicCppCourse | fb6c2300dfb48961a5f647a51eb9c2032bfb45ea | [
"MIT"
] | null | null | null | Part3/eleven.cpp | praseedpai/BasicCppCourse | fb6c2300dfb48961a5f647a51eb9c2032bfb45ea | [
"MIT"
] | 1 | 2021-05-03T16:09:46.000Z | 2021-05-03T16:09:46.000Z | ///////////////////////////////////
// eleven.cpp
// A C/C++ program to demonstrate pointers
// g++ -oeleven.exe eleven.cpp
// cl /Feeleven.exe eleven.cpp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main( int argc , char **argv , char **envp ){
int arr[] = { 0,2,4,5,6};
int arr_count = sizeof(arr)/sizeof(arr[0]);
//--- allocate dynamic memory
int *parr = (int *) malloc(sizeof(int) * arr_count);
//----- if failed, print failure and exit
if ( parr == 0 ) { printf("Memory Allocation Failure\n"); return 0;}
memcpy(parr,arr,arr_count*sizeof(int));
int *temp = parr;
for(int i=0; i<arr_count; ++i ) {
printf("%p\t%d\n", temp, *temp );
temp++;
}
free(parr); // free memory from the heap
return 0;
}
| 29.259259 | 71 | 0.556962 | praseedpai |
4fc70deb3e9d24c0023e94283629a9144144c227 | 15,279 | cpp | C++ | ChipsEninge/02_Script/DirectX/Effects/Effects.cpp | jerrypoiu/DX11_ChipsEngine2021 | a558fb0013259a380d68b66142fc48b575208980 | [
"MIT"
] | 1 | 2021-01-25T11:38:21.000Z | 2021-01-25T11:38:21.000Z | ChipsEninge/02_Script/DirectX/Effects/Effects.cpp | jerrypoiu/ChipsEngine | a558fb0013259a380d68b66142fc48b575208980 | [
"MIT"
] | null | null | null | ChipsEninge/02_Script/DirectX/Effects/Effects.cpp | jerrypoiu/ChipsEngine | a558fb0013259a380d68b66142fc48b575208980 | [
"MIT"
] | null | null | null | #include "DirectX/Effects/Effects.h"
#pragma region Effect
Effect::Effect(ID3D11Device* device, const std::wstring& filename)
: mFX(0)
{
std::ifstream fin(filename, std::ios::binary);
fin.seekg(0, std::ios_base::end);
int size = (int)fin.tellg();
fin.seekg(0, std::ios_base::beg);
std::vector<char> compiledShader(size);
fin.read(&compiledShader[0], size);
fin.close();
D3DX11CreateEffectFromMemory(&compiledShader[0], size,0, device, &mFX);
}
Effect::~Effect()
{
SAFE_RELEASE(mFX);
}
#pragma endregion
#pragma region StandardShaderEffect
StandardShaderEffect::StandardShaderEffect(ID3D11Device* device, const std::wstring& filename)
: Effect(device, filename)
{
DebugTech = mFX->GetTechniqueByName("Debug");
StandardTech = mFX->GetTechniqueByName("Standard");
CartoonTech = mFX->GetTechniqueByName("Cartoon");
DepthTech = mFX->GetTechniqueByName("Depth");
UseDiffuse = mFX->GetVariableByName("gUseDiffuse")->AsScalar();
UseAlphaClip = mFX->GetVariableByName("gUseAlphaClip")->AsScalar();
UseNormal = mFX->GetVariableByName("gUseNormal")->AsScalar();
UseSpecular = mFX->GetVariableByName("gUseSpecular")->AsScalar();
UseReflect = mFX->GetVariableByName("gUseReflect")->AsScalar();
UseCartoon = mFX->GetVariableByName("gUseCartoon")->AsScalar();
UseFog = mFX->GetVariableByName("gUseFog")->AsScalar();
UseShadow = mFX->GetVariableByName("gUseShadow")->AsScalar();
UseRimLight = mFX->GetVariableByName("gRimLight")->AsScalar();
UseSkinning = mFX->GetVariableByName("gSkinning")->AsScalar();
WorldViewProj = mFX->GetVariableByName("gWorldViewProj")->AsMatrix();
World = mFX->GetVariableByName("gWorld")->AsMatrix();
WorldView = mFX->GetVariableByName("gWorldView")->AsMatrix();
WorldInvTranspose = mFX->GetVariableByName("gWorldInvTranspose")->AsMatrix();
ShadowTransform = mFX->GetVariableByName("gShadowTransform")->AsMatrix();
TexTransform = mFX->GetVariableByName("gTexTransform")->AsMatrix();
BoneTransforms = mFX->GetVariableByName("gBoneTransforms")->AsMatrix();
NearFar = mFX->GetVariableByName("gNearFar")->AsVector();
EyePosW = mFX->GetVariableByName("gEyePosW")->AsVector();
FogColor = mFX->GetVariableByName("gFogColor")->AsVector();
FogStart = mFX->GetVariableByName("gFogStart")->AsScalar();
FogRange = mFX->GetVariableByName("gFogRange")->AsScalar();
DirLights = mFX->GetVariableByName("gDirLights");
PointLights = mFX->GetVariableByName("gPointLights");
SpotLights = mFX->GetVariableByName("gSpotLights");
MatNum = mFX->GetVariableByName("gMatNum")->AsScalar();
PointLightCount = mFX->GetVariableByName("gPointLightCount")->AsScalar();
SpotLightCount = mFX->GetVariableByName("gSpotLightCount")->AsScalar();
Mat = mFX->GetVariableByName("gMaterial");
DiffuseMap = mFX->GetVariableByName("gDiffuseMap")->AsShaderResource();
SpecularMap = mFX->GetVariableByName("gSpecularMap")->AsShaderResource();
CubeMap = mFX->GetVariableByName("gCubeMap")->AsShaderResource();
NormalMap = mFX->GetVariableByName("gNormalMap")->AsShaderResource();
ShadowMap = mFX->GetVariableByName("gShadowMap")->AsShaderResource();
}
StandardShaderEffect::~StandardShaderEffect()
{
}
#pragma endregion
#pragma region BuildShadowMapEffect
BuildShadowMapEffect::BuildShadowMapEffect(ID3D11Device* device, const std::wstring& filename)
: Effect(device, filename)
{
UseSkinning = mFX->GetVariableByName("gSkinning")->AsScalar();
BoneTransforms = mFX->GetVariableByName("gBoneTransforms")->AsMatrix();
BuildShadowMapTech = mFX->GetTechniqueByName("BuildShadowMapTech");
ViewProj = mFX->GetVariableByName("gViewProj")->AsMatrix();
WorldViewProj = mFX->GetVariableByName("gWorldViewProj")->AsMatrix();
World = mFX->GetVariableByName("gWorld")->AsMatrix();
WorldInvTranspose = mFX->GetVariableByName("gWorldInvTranspose")->AsMatrix();
TexTransform = mFX->GetVariableByName("gTexTransform")->AsMatrix();
EyePosW = mFX->GetVariableByName("gEyePosW")->AsVector();
HeightScale = mFX->GetVariableByName("gHeightScale")->AsScalar();
}
BuildShadowMapEffect::~BuildShadowMapEffect()
{
}
#pragma endregion
#pragma region SkyEffect
SkyEffect::SkyEffect(ID3D11Device* device, const std::wstring& filename)
: Effect(device, filename)
{
SkyTech = mFX->GetTechniqueByName("SkyTech");
WorldViewProj = mFX->GetVariableByName("gWorldViewProj")->AsMatrix();
WorldView = mFX->GetVariableByName("gWorldView")->AsMatrix();
NearFar = mFX->GetVariableByName("gNearFar")->AsVector();
CubeMap = mFX->GetVariableByName("gCubeMap")->AsShaderResource();
}
SkyEffect::~SkyEffect()
{
}
#pragma endregion
#pragma region ParticleEffect
ParticleEffect::ParticleEffect(ID3D11Device* device, const std::wstring& filename)
: Effect(device, filename)
{
StreamOutTech = mFX->GetTechniqueByName("StreamOutTech");
DrawTech = mFX->GetTechniqueByName("DrawTech");
NearFar = mFX->GetVariableByName("gNearFar")->AsVector();
View = mFX->GetVariableByName("gView")->AsMatrix();
ViewProj = mFX->GetVariableByName("gViewProj")->AsMatrix();
GameTime = mFX->GetVariableByName("gGameTime")->AsScalar();
TimeStep = mFX->GetVariableByName("gTimeStep")->AsScalar();
EmitSpread = mFX->GetVariableByName("gEmitSpread")->AsScalar();
CreateIntervalTime = mFX->GetVariableByName("gCreateIntervalTime")->AsScalar();
DeleteTime = mFX->GetVariableByName("gDeleteTime")->AsScalar();
FadeTime = mFX->GetVariableByName("gFadeTime")->AsScalar();
RandomizePosition = mFX->GetVariableByName("gRandomizePosition")->AsScalar();
EyePosW = mFX->GetVariableByName("gEyePosW")->AsVector();
EmitPosW = mFX->GetVariableByName("gEmitPosW")->AsVector();
EmitDirW = mFX->GetVariableByName("gEmitDirW")->AsVector();
EmitColor = mFX->GetVariableByName("gEmitColor")->AsVector();
EmitSizeW = mFX->GetVariableByName("gEmitSizeW")->AsVector();
EmitMove = mFX->GetVariableByName("gAccelW")->AsVector();
TexArray = mFX->GetVariableByName("gTexArray")->AsShaderResource();
RandomTex = mFX->GetVariableByName("gRandomTex")->AsShaderResource();
}
ParticleEffect::~ParticleEffect()
{
}
#pragma endregion
#pragma region PostProcessingEffect
PostProcessingEffect::PostProcessingEffect(ID3D11Device* device, const std::wstring& filename)
: Effect(device, filename)
{
PostProcessingTech = mFX->GetTechniqueByName("PostProcessing");
DownSamplingTech = mFX->GetTechniqueByName("DownSampling");
SSAOTech = mFX->GetTechniqueByName("ScreenSpaceAmbientOcclusion");
RayMarchingTech = mFX->GetTechniqueByName("RayMarching");
CameraRotMat = mFX->GetVariableByName("gCameraRotMat")->AsMatrix();
Proj = mFX->GetVariableByName("gProj")->AsMatrix();
View = mFX->GetVariableByName("gView")->AsMatrix();
EyePosW = mFX->GetVariableByName("gEyePosW")->AsVector();
Resolution = mFX->GetVariableByName("gResolution")->AsVector();
NearFar = mFX->GetVariableByName("gNearFar")->AsVector();
DirLights = mFX->GetVariableByName("gDirLights");
PointLights = mFX->GetVariableByName("gPointLights");
SpotLights = mFX->GetVariableByName("gSpotLights");
PointLightCount = mFX->GetVariableByName("gPointLightCount")->AsScalar();
SpotLightCount = mFX->GetVariableByName("gSpotLightCount")->AsScalar();
LutSize = mFX->GetVariableByName("gLutSize")->AsScalar();
LutCoordinateInverse = mFX->GetVariableByName("gLutCoordinateInverse")->AsScalar();
TotalTime = mFX->GetVariableByName("gTotalTime")->AsScalar();
StartFadeInTime = mFX->GetVariableByName("gStartFadeInTime")->AsScalar();
StartFadeOutTime = mFX->GetVariableByName("gStartFadeOutTime")->AsScalar();
Mat = mFX->GetVariableByName("gMaterial");
DownsampledScreenTexture = mFX->GetVariableByName("gDownsampledScreenTexture")->AsShaderResource();
SSAOTexture = mFX->GetVariableByName("gSSAOTexture")->AsShaderResource();
RayMarchingTexture = mFX->GetVariableByName("gRayMarchingTexture")->AsShaderResource();
ScreenTexture = mFX->GetVariableByName("gScreenTexture")->AsShaderResource();
PreScreenTexture = mFX->GetVariableByName("gPreScreenTexture")->AsShaderResource();
DepthTexture = mFX->GetVariableByName("gDepthTexture")->AsShaderResource();
LutTexture = mFX->GetVariableByName("gLutTexture")->AsShaderResource();
GrayNoiseTexture = mFX->GetVariableByName("gGrayNoiseTexture")->AsShaderResource();
CubeMap = mFX->GetVariableByName("gSkyBox")->AsShaderResource();
//RayMarching
RayMarching = mFX->GetVariableByName("gRaymarching")->AsScalar();
//Ambient Occlusion & Dark
SSAO = mFX->GetVariableByName("gSSAO")->AsScalar();
SSAOradius = mFX->GetVariableByName("gSsaoRadius")->AsScalar();
SSAObias = mFX->GetVariableByName("gSsaoBias")->AsScalar();
SSAOscale = mFX->GetVariableByName("gSsaoScale")->AsScalar();
SSAOamount = mFX->GetVariableByName("gSsaoAmount")->AsScalar();
Dark = mFX->GetVariableByName("gDark")->AsScalar();
DarkAmount = mFX->GetVariableByName("gDarkAmount")->AsScalar();
//Depth of field
DepthOfField = mFX->GetVariableByName("gDepthOfField")->AsScalar();
DepthOfFieldAmount = mFX->GetVariableByName("gDepthOfFieldAmount")->AsScalar();
DepthOfFieldFocalDepth = mFX->GetVariableByName("gDepthOfFieldFocalDepth")->AsScalar();
DepthOfFieldFallOffStart = mFX->GetVariableByName("gDepthOfFieldFallOffStart")->AsScalar();
DepthOfFieldFallOffEnd = mFX->GetVariableByName("gDepthOfFieldFallOffEnd")->AsScalar();
//Blur
MotionBlur = mFX->GetVariableByName("gMotionBlur")->AsScalar();
MotionBlurReferenceDistance = mFX->GetVariableByName("gMdotionBlurReferenceDistance")->AsScalar();
MotionBlurAmount = mFX->GetVariableByName("gMdotionBlurAmount")->AsScalar();
GaussianBlur = mFX->GetVariableByName("gGaussianBlur")->AsScalar();
GaussianBlurAmount = mFX->GetVariableByName("gGaussianBlurAmount")->AsScalar();
BoxBlur = mFX->GetVariableByName("gBoxBlur")->AsScalar();
BoxBlurAmount = mFX->GetVariableByName("gBoxBlurAmount")->AsScalar();
VerticalBlur = mFX->GetVariableByName("gVerticalBlur")->AsScalar();
VerticalBlurAmount = mFX->GetVariableByName("gVerticalBlurAmount")->AsScalar();
HorizontalBlur = mFX->GetVariableByName("gHorizontalBlur")->AsScalar();
HorizontalBlurAmount = mFX->GetVariableByName("gHorizontalBlurAmount")->AsScalar();
//Lens Distortion
Rain = mFX->GetVariableByName("gRain")->AsScalar();
RainSpeed = mFX->GetVariableByName("gRainSpeed")->AsScalar();
RainAmount = mFX->GetVariableByName("gRainAmount")->AsScalar();
Blood = mFX->GetVariableByName("gBlood")->AsScalar();
BloodSpeed = mFX->GetVariableByName("gBloodSpeed")->AsScalar();
BloodAmount = mFX->GetVariableByName("gBloodAmount")->AsScalar();
//Chromatic Averration
ChromaticAberration = mFX->GetVariableByName("gChromaticAberration")->AsScalar();
ChromaticAberrationAmount = mFX->GetVariableByName("gChromaticAberrationAmount")->AsScalar();
//Bloom
Bloom = mFX->GetVariableByName("gBloom")->AsScalar();
OverBloom = mFX->GetVariableByName("gOverBloom")->AsScalar();
BloomAmount = mFX->GetVariableByName("gBloomAmount")->AsScalar();
//Vignette
Vignette = mFX->GetVariableByName("gVignetting")->AsScalar();
VignetteAmount = mFX->GetVariableByName("gVignettingAmount")->AsScalar();
//Color Grading
Gamma = mFX->GetVariableByName("gGamma")->AsScalar();
GammaAmount = mFX->GetVariableByName("gGammaAmount")->AsScalar();
Contrast = mFX->GetVariableByName("gContrast")->AsScalar();
ContrastAmount = mFX->GetVariableByName("gContrastAmount")->AsScalar();
Bright = mFX->GetVariableByName("gBright")->AsScalar();
BrightAmount = mFX->GetVariableByName("gBrightAmount")->AsScalar();
Saturate = mFX->GetVariableByName("gSaturate")->AsScalar();
SaturateAmount = mFX->GetVariableByName("gSaturateAmount")->AsScalar();
SmoothStep = mFX->GetVariableByName("gSmoothStep")->AsScalar();
SmoothStepMin = mFX->GetVariableByName("gSmoothStepMin")->AsScalar();
SmoothStepMax = mFX->GetVariableByName("gSmoothStepMax")->AsScalar();
Tint = mFX->GetVariableByName("gTint")->AsScalar();
TintColor = mFX->GetVariableByName("gTintColor")->AsVector();
Sepia = mFX->GetVariableByName("gSepia")->AsScalar();
GrayScale = mFX->GetVariableByName("gGrayScale")->AsScalar();
Inverse = mFX->GetVariableByName("gInverse")->AsScalar();
Lut = mFX->GetVariableByName("gLUT")->AsScalar();
LutAmount = mFX->GetVariableByName("gLutAmount")->AsScalar();
TonemapACES = mFX->GetVariableByName("gTonemapACES")->AsScalar();
TonemapUnreal = mFX->GetVariableByName("gTonemapUnreal")->AsScalar();
TonemapUnrealExposure = mFX->GetVariableByName("gTonemapUnrealExposure")->AsScalar();
TonemapReinhard = mFX->GetVariableByName("gTonemapReinhard")->AsScalar();
//Film Effect
OldGame = mFX->GetVariableByName("gOldGame")->AsScalar();
OldGameAmount = mFX->GetVariableByName("gOldGameMosaicAmount")->AsScalar();
OldGameLevel = mFX->GetVariableByName("gOldGameColorLevel")->AsScalar();
OldGameMaxColor = mFX->GetVariableByName("gOldGameMaxColor")->AsVector();
OldGameMinColor = mFX->GetVariableByName("gOldGameMinColor")->AsVector();
Edge = mFX->GetVariableByName("gEdge")->AsScalar();
EdgeIndex = mFX->GetVariableByName("gEdgeIndex")->AsScalar();
Embossed = mFX->GetVariableByName("gEmbossed")->AsScalar();
Flicker = mFX->GetVariableByName("gFlicker")->AsScalar();
FlickerAmount = mFX->GetVariableByName("gFlickerAmount")->AsScalar();
FlickerFrequence = mFX->GetVariableByName("gFlickerFrequence")->AsScalar();
Cartoon = mFX->GetVariableByName("gCartoon")->AsScalar();
Mosaic = mFX->GetVariableByName("gMosaic")->AsScalar();
MosaicAmount = mFX->GetVariableByName("gMosaicAmount")->AsScalar();
VerticalLines = mFX->GetVariableByName("gVerticalLines")->AsScalar();
VerticalLinesAmount = mFX->GetVariableByName("gVerticalLinesAmount")->AsScalar();
HorizontalLines = mFX->GetVariableByName("gHorizontalLines")->AsScalar();
HorizontalLinesAmount = mFX->GetVariableByName("gHorizontalLinesAmount")->AsScalar();
Noise = mFX->GetVariableByName("gNoise")->AsScalar();
NoiseFiness = mFX->GetVariableByName("gNoiseFiness")->AsScalar();
NoiseBlend = mFX->GetVariableByName("gNoiseBlend")->AsScalar();
CinematicLine = mFX->GetVariableByName("gCinematicLine")->AsScalar();
CinematicLineAmount = mFX->GetVariableByName("gCinematicLineAmount")->AsScalar();
//Fade In, Out
FadeIn = mFX->GetVariableByName("gFadeIn")->AsScalar();
FadeInSpeed = mFX->GetVariableByName("gFadeInSpeed")->AsScalar();
FadeOut = mFX->GetVariableByName("gFadeOut")->AsScalar();
FadeOutSpeed = mFX->GetVariableByName("gFadeOutSpeed")->AsScalar();
}
PostProcessingEffect::~PostProcessingEffect()
{
}
#pragma endregion
#pragma region Effects
StandardShaderEffect* Effects::StandardShaderFX = 0;
SkyEffect* Effects::SkyFX = 0;
ParticleEffect* Effects::ParticleFX = 0;
BuildShadowMapEffect* Effects::BuildShadowMapFX = 0;
PostProcessingEffect* Effects::PostProcessingFX = 0;
void Effects::InitAll(ID3D11Device* device)
{
StandardShaderFX = new StandardShaderEffect(device, TEXT("01_Asset/Fx/StandardShader.fxo"));
SkyFX = new SkyEffect(device, TEXT("01_Asset/Fx/Sky.fxo"));
ParticleFX = new ParticleEffect(device, TEXT("01_Asset/Fx/Particle.fxo"));
BuildShadowMapFX = new BuildShadowMapEffect(device, TEXT("01_Asset/Fx/BuildShadowMap.fxo"));
PostProcessingFX = new PostProcessingEffect(device, TEXT("01_Asset/Fx/PostProcessing.fxo"));
}
void Effects::DestroyAll()
{
SAFE_DELETE(StandardShaderFX);
SAFE_DELETE(SkyFX);
SAFE_DELETE(ParticleFX);
SAFE_DELETE(BuildShadowMapFX);
SAFE_DELETE(PostProcessingFX);
}
#pragma endregion | 48.504762 | 100 | 0.764579 | jerrypoiu |
4fcca642dc4aeab95c4edaad254336a279d46d27 | 5,675 | cpp | C++ | src/render/EnvironmentMapPass.cpp | Kuranes/KickstartRT_demo | 6de7453ca42e46db180f8bead7ba23f9e8936b69 | [
"MIT"
] | 83 | 2021-07-19T13:55:33.000Z | 2022-03-29T16:00:57.000Z | src/render/EnvironmentMapPass.cpp | CompileException/donut | bc400a8c2c9db9c3c5ed16190dc108e75722b503 | [
"MIT"
] | 2 | 2021-11-04T06:41:28.000Z | 2021-11-30T08:25:28.000Z | src/render/EnvironmentMapPass.cpp | CompileException/donut | bc400a8c2c9db9c3c5ed16190dc108e75722b503 | [
"MIT"
] | 10 | 2021-07-19T15:03:58.000Z | 2022-01-10T07:15:35.000Z | /*
* Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <donut/render/EnvironmentMapPass.h>
#include <donut/engine/FramebufferFactory.h>
#include <donut/engine/ShaderFactory.h>
#include <donut/engine/CommonRenderPasses.h>
#include <donut/engine/View.h>
#include <donut/core/math/math.h>
using namespace donut::math;
#include <donut/shaders/sky_cb.h>
using namespace donut::engine;
using namespace donut::render;
EnvironmentMapPass::EnvironmentMapPass(
nvrhi::IDevice* device,
std::shared_ptr<ShaderFactory> shaderFactory,
std::shared_ptr<CommonRenderPasses> commonPasses,
std::shared_ptr<FramebufferFactory> framebufferFactory,
const ICompositeView& compositeView,
nvrhi::ITexture* environmentMap)
: m_CommonPasses(commonPasses)
, m_FramebufferFactory(framebufferFactory)
{
nvrhi::TextureDimension envMapDimension = environmentMap->getDesc().dimension;
bool isCubeMap = (envMapDimension == nvrhi::TextureDimension::TextureCube) ||
(envMapDimension == nvrhi::TextureDimension::TextureCubeArray);
std::vector<engine::ShaderMacro> PSMacros;
PSMacros.push_back(engine::ShaderMacro("LATLONG_TEXTURE", isCubeMap ? "0" : "1"));
m_PixelShader = shaderFactory->CreateShader("donut/passes/environment_map_ps.hlsl", "main",
&PSMacros, nvrhi::ShaderType::Pixel);
nvrhi::BufferDesc constantBufferDesc;
constantBufferDesc.byteSize = sizeof(SkyConstants);
constantBufferDesc.debugName = "SkyConstants";
constantBufferDesc.isConstantBuffer = true;
constantBufferDesc.isVolatile = true;
constantBufferDesc.maxVersions = engine::c_MaxRenderPassConstantBufferVersions;
m_SkyCB = device->createBuffer(constantBufferDesc);
const IView* sampleView = compositeView.GetChildView(ViewType::PLANAR, 0);
nvrhi::IFramebuffer* sampleFramebuffer = m_FramebufferFactory->GetFramebuffer(*sampleView);
{
nvrhi::BindingLayoutDesc layoutDesc;
layoutDesc.visibility = nvrhi::ShaderType::Pixel;
layoutDesc.bindings = {
nvrhi::BindingLayoutItem::VolatileConstantBuffer(0),
nvrhi::BindingLayoutItem::Texture_SRV(0),
nvrhi::BindingLayoutItem::Sampler(0)
};
m_RenderBindingLayout = device->createBindingLayout(layoutDesc);
nvrhi::BindingSetDesc bindingSetDesc;
bindingSetDesc.bindings = {
nvrhi::BindingSetItem::ConstantBuffer(0, m_SkyCB),
nvrhi::BindingSetItem::Texture_SRV(0, environmentMap),
nvrhi::BindingSetItem::Sampler(0, commonPasses->m_LinearWrapSampler)
};
m_RenderBindingSet = device->createBindingSet(bindingSetDesc, m_RenderBindingLayout);
nvrhi::GraphicsPipelineDesc pipelineDesc;
pipelineDesc.primType = nvrhi::PrimitiveType::TriangleStrip;
pipelineDesc.VS = sampleView->IsReverseDepth() ? m_CommonPasses->m_FullscreenVS : m_CommonPasses->m_FullscreenAtOneVS;
pipelineDesc.PS = m_PixelShader;
pipelineDesc.bindingLayouts = { m_RenderBindingLayout };
pipelineDesc.renderState.rasterState.setCullNone();
pipelineDesc.renderState.depthStencilState
.enableDepthTest()
.disableDepthWrite()
.disableStencil()
.setDepthFunc(sampleView->IsReverseDepth()
? nvrhi::ComparisonFunc::GreaterOrEqual
: nvrhi::ComparisonFunc::LessOrEqual);
m_RenderPso = device->createGraphicsPipeline(pipelineDesc, sampleFramebuffer);
}
}
void EnvironmentMapPass::Render(
nvrhi::ICommandList* commandList,
const ICompositeView& compositeView)
{
commandList->beginMarker("Environment Map");
for (uint viewIndex = 0; viewIndex < compositeView.GetNumChildViews(ViewType::PLANAR); viewIndex++)
{
const IView* view = compositeView.GetChildView(ViewType::PLANAR, viewIndex);
nvrhi::GraphicsState state;
state.pipeline = m_RenderPso;
state.framebuffer = m_FramebufferFactory->GetFramebuffer(*view);
state.bindings = { m_RenderBindingSet };
state.viewport = view->GetViewportState();
SkyConstants skyConstants = {};
skyConstants.matClipToTranslatedWorld = view->GetInverseViewProjectionMatrix() * affineToHomogeneous(translation(-view->GetViewOrigin()));
commandList->writeBuffer(m_SkyCB, &skyConstants, sizeof(skyConstants));
commandList->setGraphicsState(state);
nvrhi::DrawArguments args;
args.instanceCount = 1;
args.vertexCount = 4;
commandList->draw(args);
}
commandList->endMarker();
}
| 42.350746 | 146 | 0.728458 | Kuranes |
4fd0363b306ceb4c7c6dc060c357e2cec1a701a8 | 6,434 | hh | C++ | GeometryService/inc/G4GeometryOptions.hh | lborrel/Offline | db9f647bad3c702171ab5ffa5ccc04c82b3f8984 | [
"Apache-2.0"
] | 9 | 2020-03-28T00:21:41.000Z | 2021-12-09T20:53:26.000Z | GeometryService/inc/G4GeometryOptions.hh | lborrel/Offline | db9f647bad3c702171ab5ffa5ccc04c82b3f8984 | [
"Apache-2.0"
] | 684 | 2019-08-28T23:37:43.000Z | 2022-03-31T22:47:45.000Z | GeometryService/inc/G4GeometryOptions.hh | lborrel/Offline | db9f647bad3c702171ab5ffa5ccc04c82b3f8984 | [
"Apache-2.0"
] | 61 | 2019-08-16T23:28:08.000Z | 2021-12-20T08:29:48.000Z | #ifndef G4GEOMETRY_OPTIONS
#define G4GEOMETRY_OPTIONS
//
// G4 geometry options look-up facility, to be used in conjunction
// with SimpleConfig.
//
//
// Original author: Kyle Knoepfel
//
// This method is used for setting and overriding various flags that
// are specified when creating volumes in G4. Ideally, it would go in
// the Mu2eG4Helper service, but it is tied to GeometryService because of
// SimpleConfig and linkage loops.
//
// The idiom of this helper is the following:
//
// (1) A SimpleConfig file can specify the following assignments:
//
// bool <var_prefix>.isVisible = [ true or false ];
// bool <var_prefix>.isSolid = [ true or false ];
// bool <var_prefix>.forceAuxEdgeVisible = [ true or false ];
// bool <var_prefix>.placePV = [ true or false ];
// bool <var_prefix>.doSurfaceCheck = [ true or false ];
//
// (2) The various flags are loaded into the option maps by the
// following syntax within a .cc file:
//
// G4GeometryOptions* geomOptions = art::ServiceHandle<GeometryService>()->geomOptions();
// geomOption->loadEntry( configFile, "MATCHING_TOKEN", <var_prefix> );
//
// where the "MATCHING_TOKEN" is specified by the User in terms
// of what you want the querying functions to look for. Normally
// the value of "MATCHING_TOKEN" applies to several volumes, but
// it could be chosen for each volume. If "loadEntry" is
// not included for a given volume, then the 5 flags above
// default to global values.
//
// (3) To access the flags, the following can be done:
//
// const auto geomOptions = art::ServiceHandle<GeometryService>()->geomOptions();
// geomOptions->isVisible( "MATCHING_TOKEN" );
// geomOptions->isSolid ( "MATCHING_TOKEN" );
// etc.
//
// If one were to do the following (the following is pseudo-code):
//
// vector<VolumeParams> volumes; // A vector with a lot of volume parameters
//
// for ( const auto& volParams ; volumes ) {
//
// finishNesting( volParams,
// ...
// geomOptions->isVisible( volParams.volumeName );
// ... );
// }
//
// such a query could take a long time. For that reason, the
// "MATCHING_TOKEN" value does not need to match that of the
// volume name to be created. The following can be much faster:
//
// vector<VolumeParams> volumes; // A vector with a lot of volume parameters
// bool isVisible = geomOptions->isVisible( "Straw" ); // look-up once.
// for ( const auto& volParams ; volumes ) {
//
// finishNesting( volParams,
// ...
// isVisible
// ... );
// }
//
// Note that an individual volume (e.g. straw) can be viewed by
// specifying an override (see point 5).
//
// (4) The (e.g.) visible() facility will first search through the
// corresponding map for a match. If no match is found---i.e. an
// entry corresponding to the requested "MATCHING_TOKEN" does not
// exist---the default visible value is returned.
//
// (5) The value returned from step 4 can be overridden by specifying
// override commands in Mu2eG4/geom/g4_userOptions.txt (e.g.):
//
// bool g4.doSurfaceCheck = true;
// vector<string> g4.doSurfaceCheck.drop = {"*"};
// vector<string> g4.doSurfaceCheck.keep = {"PSShield*"};
// vector<string> g4.doSurfaceCheck.order = { "g4.doSurfaceCheck.drop",
// "g4.doSurfaceCheck.keep" };
//
// In this case, the default "doSurfaceCheck" value is true, but
// the doSurfaceCheck's for all volumes are disabled by the drop
// "*" command, since "*" matches to all volumes. All volumes
// that match "PSShield*" then have their surface checks enabled.
// Note that the commands in "drop" and "keep" always override
// the default g4.doSurfaceCheck value.
//
// The actual drop/keep commands are not implemented unless they
// are specified in the *.order vector in the order desired.
//
// Additional drop/keep commands can be added. The only
// requirement is that their suffixes must of the form *.keep* or
// *.drop*.
#include <map>
#include <string>
#include <vector>
#include <regex>
namespace mu2e {
class SimpleConfig;
class G4GeometryOptData {
public:
typedef std::vector<std::string> VS;
typedef std::pair<bool,std::regex> Ordering;
typedef std::vector<Ordering> OrderingList;
G4GeometryOptData( bool defaultValue, const std::string& name );
void loadOrderingStrings( const SimpleConfig& config, const std::string& varString );
void mapInserter ( const std::string& volName, bool value );
bool queryMap ( const std::string& volName ) const;
bool default_value() const {return default_;}
private:
std::pair<bool,bool> flagOverridden( const std::string& volName ) const;
std::string name_;
std::map<std::string, bool> map_;
OrderingList ordering_;
bool default_;
};
class G4GeometryOptions {
public:
G4GeometryOptions( const SimpleConfig& config );
// Disable copy c'tor and copy assignment
G4GeometryOptions (const G4GeometryOptions&) = delete;
G4GeometryOptions& operator=(const G4GeometryOptions&) = delete;
void loadEntry( const SimpleConfig& config, const std::string& volName, const std::string& prefix );
bool isSolid ( const std::string& volName ) const;
bool isVisible ( const std::string& volName ) const;
bool doSurfaceCheck ( const std::string& volName ) const;
bool forceAuxEdgeVisible( const std::string& volName ) const;
bool placePV ( const std::string& volName ) const;
private:
G4GeometryOptData dataSurfaceCheck_;
G4GeometryOptData dataIsVisible_;
G4GeometryOptData dataIsSolid_;
G4GeometryOptData dataForceAuxEdge_;
G4GeometryOptData dataPlacePV_;
};
}
#endif /*G4GEOMETRY_OPTIONS*/
| 36.350282 | 106 | 0.613926 | lborrel |
4fd0fa30ee8922027abd6fd8dc0fa3da87685323 | 291 | cpp | C++ | mitsui/mitsuiA.cpp | KoukiNAGATA/c- | ae51bacb9facb936a151dd777beb6688383a2dcd | [
"MIT"
] | null | null | null | mitsui/mitsuiA.cpp | KoukiNAGATA/c- | ae51bacb9facb936a151dd777beb6688383a2dcd | [
"MIT"
] | 3 | 2021-03-31T01:39:25.000Z | 2021-05-04T10:02:35.000Z | mitsui/mitsuiA.cpp | KoukiNAGATA/c- | ae51bacb9facb936a151dd777beb6688383a2dcd | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <cstdio>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int A, B, C, D;
cin >> A >> B >> C >> D;
if (A != C)
{
cout << 1 << "\n";
return 0;
}
cout << 0 << "\n";
return 0;
}
| 14.55 | 28 | 0.474227 | KoukiNAGATA |
4fd8ce5bb6a5438c2c7c90bf28f7aace7da37961 | 1,791 | hpp | C++ | include/StackImpl.hpp | Slava-100/lab-05-stack | 06a365e8c27870e2b133cc9ee9102b9e41247a49 | [
"MIT"
] | null | null | null | include/StackImpl.hpp | Slava-100/lab-05-stack | 06a365e8c27870e2b133cc9ee9102b9e41247a49 | [
"MIT"
] | null | null | null | include/StackImpl.hpp | Slava-100/lab-05-stack | 06a365e8c27870e2b133cc9ee9102b9e41247a49 | [
"MIT"
] | null | null | null | // Copyright 2021 Slava-100 <svat.strel.2001@gmail.com>
#ifndef INCLUDE_STACKIMPL_HPP_
#define INCLUDE_STACKIMPL_HPP_
#include <utility>
template <typename T>
class StackImpl {
public:
StackImpl() : _tail(nullptr), _size(0) {}
StackImpl(const StackImpl &) = delete;
StackImpl(StackImpl &&) = delete;
StackImpl &operator=(const StackImpl &) = delete;
StackImpl &operator=(StackImpl &&) = delete;
~StackImpl() {
while (_tail != nullptr) {
auto tmp = _tail;
_tail = _tail->prev;
delete tmp;
}
}
void push(const T &value) {
auto new_node = new _list_node(value);
_add_new_node(new_node);
}
void push(T &&value) {
auto new_node = new _list_node(std::move(value));
_add_new_node(new_node);
}
template <typename... args_t>
void emplace(args_t &&...args) {
auto new_node = new _list_node(std::forward<args_t>(args)...);
_add_new_node(new_node);
}
T pop() {
if (!_tail) throw std::runtime_error("pop from empty stack");
auto tmp = _tail;
auto ret_value = tmp->value;
_tail = _tail->prev;
delete tmp;
--_size;
return ret_value;
}
std::size_t size() const { return _size; }
bool empty() const { return _tail == nullptr; }
private:
struct _list_node {
explicit _list_node(const T &val) : value(val), prev(nullptr) {}
explicit _list_node(T &&val) : value(std::move(val)), prev(nullptr) {}
template <typename... args_t>
explicit _list_node(args_t &&...args)
: value(std::forward<args_t>(args)...), prev(nullptr) {}
T value;
_list_node *prev;
};
void _add_new_node(_list_node *new_node) {
new_node->prev = _tail;
_tail = new_node;
++_size;
}
_list_node *_tail;
std::size_t _size;
};
#endif // INCLUDE_STACKIMPL_HPP_
| 22.3875 | 74 | 0.639308 | Slava-100 |
4fd93003389cc1ccc0a29376623c280ab7874358 | 6,055 | cpp | C++ | libgpopt/src/xforms/CXformSimplifyGbAgg.cpp | davidli2010/gporca | 4c946e5e41051c832736b2fce712c37ca651ddf5 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | libgpopt/src/xforms/CXformSimplifyGbAgg.cpp | davidli2010/gporca | 4c946e5e41051c832736b2fce712c37ca651ddf5 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | libgpopt/src/xforms/CXformSimplifyGbAgg.cpp | davidli2010/gporca | 4c946e5e41051c832736b2fce712c37ca651ddf5 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | //---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2012 EMC Corp.
//
// @filename:
// CXformSimplifyGbAgg.cpp
//
// @doc:
// Implementation of simplifying an aggregate expression by finding
// the minimal grouping columns based on functional dependencies
//---------------------------------------------------------------------------
#include "gpos/base.h"
#include "gpopt/base/CUtils.h"
#include "gpopt/base/CKeyCollection.h"
#include "gpopt/operators/ops.h"
#include "gpopt/operators/COperator.h"
#include "gpopt/xforms/CXformSimplifyGbAgg.h"
using namespace gpmd;
using namespace gpopt;
//---------------------------------------------------------------------------
// @function:
// CXformSimplifyGbAgg::CXformSimplifyGbAgg
//
// @doc:
// Ctor
//
//---------------------------------------------------------------------------
CXformSimplifyGbAgg::CXformSimplifyGbAgg
(
CMemoryPool *mp
)
:
CXformExploration
(
// pattern
GPOS_NEW(mp) CExpression
(
mp,
GPOS_NEW(mp) CLogicalGbAgg(mp),
GPOS_NEW(mp) CExpression(mp, GPOS_NEW(mp) CPatternLeaf(mp)), // relational child
GPOS_NEW(mp) CExpression(mp, GPOS_NEW(mp) CPatternTree(mp)) // scalar project list
)
)
{}
//---------------------------------------------------------------------------
// @function:
// CXformSimplifyGbAgg::Exfp
//
// @doc:
// Compute xform promise for a given expression handle;
// aggregate must have grouping columns
//
//---------------------------------------------------------------------------
CXform::EXformPromise
CXformSimplifyGbAgg::Exfp
(
CExpressionHandle &exprhdl
)
const
{
CLogicalGbAgg *popAgg = CLogicalGbAgg::PopConvert(exprhdl.Pop());
GPOS_ASSERT(COperator::EgbaggtypeGlobal == popAgg->Egbaggtype());
if (0 == popAgg->Pdrgpcr()->Size() || NULL != popAgg->PdrgpcrMinimal())
{
return CXform::ExfpNone;
}
return CXform::ExfpHigh;
}
//---------------------------------------------------------------------------
// @function:
// CXformSimplifyGbAgg::FDropGbAgg
//
// @doc:
// Return true if GbAgg operator can be dropped because grouping
// columns include a key
//
//---------------------------------------------------------------------------
BOOL
CXformSimplifyGbAgg::FDropGbAgg
(
CMemoryPool *mp,
CExpression *pexpr,
CXformResult *pxfres
)
{
CLogicalGbAgg *popAgg = CLogicalGbAgg::PopConvert(pexpr->Pop());
CExpression *pexprRelational = (*pexpr)[0];
CExpression *pexprProjectList = (*pexpr)[1];
if (0 < pexprProjectList->Arity())
{
// GbAgg cannot be dropped if Agg functions are computed
return false;
}
CKeyCollection *pkc = CDrvdPropRelational::GetRelationalProperties(pexprRelational->PdpDerive())->Pkc();
if (NULL == pkc)
{
// relational child does not have key
return false;
}
const ULONG ulKeys = pkc->Keys();
BOOL fDrop = false;
for (ULONG ul = 0; !fDrop && ul < ulKeys; ul++)
{
CColRefArray *pdrgpcrKey = pkc->PdrgpcrKey(mp, ul);
CColRefSet *pcrs = GPOS_NEW(mp) CColRefSet(mp, pdrgpcrKey);
pdrgpcrKey->Release();
CColRefSet *pcrsGrpCols = GPOS_NEW(mp) CColRefSet(mp);
pcrsGrpCols->Include(popAgg->Pdrgpcr());
BOOL fGrpColsHasKey = pcrsGrpCols->ContainsAll(pcrs);
pcrs->Release();
pcrsGrpCols->Release();
if (fGrpColsHasKey)
{
// Gb operator can be dropped
pexprRelational->AddRef();
CExpression *pexprResult =
CUtils::PexprLogicalSelect(mp, pexprRelational, CPredicateUtils::PexprConjunction(mp, NULL));
pxfres->Add(pexprResult);
fDrop = true;
}
}
return fDrop;
}
//---------------------------------------------------------------------------
// @function:
// CXformSimplifyGbAgg::Transform
//
// @doc:
// Actual transformation to simplify a aggregate expression
//
//---------------------------------------------------------------------------
void
CXformSimplifyGbAgg::Transform
(
CXformContext *pxfctxt,
CXformResult *pxfres,
CExpression *pexpr
)
const
{
GPOS_ASSERT(NULL != pxfctxt);
GPOS_ASSERT(NULL != pxfres);
GPOS_ASSERT(FPromising(pxfctxt->Pmp(), this, pexpr));
GPOS_ASSERT(FCheckPattern(pexpr));
CMemoryPool *mp = pxfctxt->Pmp();
if (FDropGbAgg(mp, pexpr,pxfres))
{
// grouping columns could be dropped, GbAgg is transformed to a Select
return;
}
// extract components
CLogicalGbAgg *popAgg = CLogicalGbAgg::PopConvert(pexpr->Pop());
CExpression *pexprRelational = (*pexpr)[0];
CExpression *pexprProjectList = (*pexpr)[1];
CColRefArray *colref_array = popAgg->Pdrgpcr();
CColRefSet *pcrsGrpCols = GPOS_NEW(mp) CColRefSet(mp);
pcrsGrpCols->Include(colref_array);
CColRefSet *pcrsCovered = GPOS_NEW(mp) CColRefSet(mp); // set of grouping columns covered by FD's
CColRefSet *pcrsMinimal = GPOS_NEW(mp) CColRefSet(mp); // a set of minimal grouping columns based on FD's
CFunctionalDependencyArray *pdrgpfd = CDrvdPropRelational::GetRelationalProperties(pexpr->PdpDerive())->Pdrgpfd();
// collect grouping columns FD's
const ULONG size = (pdrgpfd == NULL) ? 0 : pdrgpfd->Size();
for (ULONG ul = 0; ul < size; ul++)
{
CFunctionalDependency *pfd = (*pdrgpfd)[ul];
if (pfd->FIncluded(pcrsGrpCols))
{
pcrsCovered->Include(pfd->PcrsDetermined());
pcrsCovered->Include(pfd->PcrsKey());
pcrsMinimal->Include(pfd->PcrsKey());
}
}
BOOL fCovered = pcrsCovered->Equals(pcrsGrpCols);
pcrsGrpCols->Release();
pcrsCovered->Release();
if (!fCovered)
{
// the union of RHS of collected FD's does not cover all grouping columns
pcrsMinimal->Release();
return;
}
// create a new Agg with minimal grouping columns
colref_array->AddRef();
CLogicalGbAgg *popAggNew = GPOS_NEW(mp) CLogicalGbAgg(mp, colref_array, pcrsMinimal->Pdrgpcr(mp), popAgg->Egbaggtype());
pcrsMinimal->Release();
GPOS_ASSERT(!popAgg->Matches(popAggNew) && "Simplified aggregate matches original aggregate");
pexprRelational->AddRef();
pexprProjectList->AddRef();
CExpression *pexprResult = GPOS_NEW(mp) CExpression(mp, popAggNew, pexprRelational, pexprProjectList);
pxfres->Add(pexprResult);
}
// EOF
| 26.911111 | 121 | 0.623452 | davidli2010 |
4fdc6c1719a2d84e03001c2f4eb4ce38d1fc074b | 4,189 | cc | C++ | src/mem/spm/governor/explicit_local_spm.cc | danned/gem5spm-riscv | 4790fd1ec5972dae40c1871283121041296984e5 | [
"BSD-3-Clause"
] | 3 | 2019-03-26T14:51:39.000Z | 2021-12-23T04:47:09.000Z | src/mem/spm/governor/explicit_local_spm.cc | danned/gem5spm-riscv | 4790fd1ec5972dae40c1871283121041296984e5 | [
"BSD-3-Clause"
] | null | null | null | src/mem/spm/governor/explicit_local_spm.cc | danned/gem5spm-riscv | 4790fd1ec5972dae40c1871283121041296984e5 | [
"BSD-3-Clause"
] | 1 | 2019-04-01T03:22:57.000Z | 2019-04-01T03:22:57.000Z | #include "mem/spm/governor/explicit_local_spm.hh"
#include <iostream>
ExplicitLocalSPM *
ExplicitLocalSPMParams::create()
{
return new ExplicitLocalSPM(this);
}
ExplicitLocalSPM::ExplicitLocalSPM(const Params *p)
: BaseGovernor(p)
{
gov_type = "ExplicitLocal";
}
ExplicitLocalSPM::~ExplicitLocalSPM()
{
}
void
ExplicitLocalSPM::init()
{
}
int
ExplicitLocalSPM::allocate(GOVRequest *gov_request)
{
printRequestStatus(gov_request);
const int total_num_pages = gov_request->getNumberOfPages(Unserved_Aligned);
if (total_num_pages <= 0) {
return 0;
}
int remaining_pages = total_num_pages;
// just do this if we are not called by a child policy
if (!gov_type.compare("ExplicitLocal") && hybrid_mem) {
cache_invalidator_helper(gov_request);
}
// Allocate on local SPM
PMMU *host_pmmu = gov_request->getPMMUPtr();
HostInfo host_info (gov_request->getThreadContext(),
gov_request->getPMMUPtr(),
host_pmmu,
(Addr)gov_request->annotations->spm_addr,
total_num_pages);
host_info.setAllocMode(gov_request->getAnnotations()->alloc_mode);
remaining_pages -= allocation_helper_on_free_pages(gov_request, &host_info);
// just do this if we are not called by a child policy
if (!gov_type.compare("ExplicitLocal") && uncacheable_spm) {
add_mapping_unallocated_pages(gov_request);
}
assert (total_num_pages == remaining_pages);
return total_num_pages - remaining_pages;
}
int
ExplicitLocalSPM::deAllocate(GOVRequest *gov_request)
{
printRequestStatus(gov_request);
int total_num_pages = gov_request->getNumberOfPages(Unserved_Aligned);
if (total_num_pages <= 0) {
return 0;
}
HostInfo host_info (gov_request->getThreadContext(), gov_request->getPMMUPtr(),
nullptr, Addr(0), total_num_pages);
host_info.setDeallocMode(gov_request->getAnnotations()->dealloc_mode);
int num_removed_pages = dallocation_helper_virtual_address(gov_request, &host_info);
return num_removed_pages;
}
int
ExplicitLocalSPM::allocation_helper_on_free_pages(GOVRequest *gov_request,
HostInfo *host_info)
{
PMMU *requester_pmmu = gov_request->getPMMUPtr();
int total_num_pages = gov_request->getNumberOfPages(Unserved_Aligned);
int remaining_pages = total_num_pages;
// since we are allocating explicitly, we must ensure that end_spm_addr
// is not greater than max_spm_addr
if ((host_info->getSPMaddress()/host_info->getHostPMMU()->getPageSizeBytes()
+ total_num_pages) <= host_info->getHostPMMU()->getSPMSizePages()) {
int num_added_pages = requester_pmmu->addATTMappingsVAddress(gov_request, host_info);
host_info->getHostPMMU()->setUsedPages(host_info->getSPMaddress(), num_added_pages,
gov_request->getRequesterNodeID());
DPRINTF(GOV, "%s: Allocating %d/%d/%d free SPM slot(s) for node (%d,%d) on node (%d,%d) "
"starting from slot address = %u\n",
gov_type, num_added_pages, host_info->getNumPages(), total_num_pages,
host_info->getUserPMMU()->getNodeID() / num_column,
host_info->getUserPMMU()->getNodeID() % num_column,
host_info->getHostPMMU()->getNodeID() / num_column,
host_info->getHostPMMU()->getNodeID() % num_column,
host_info->getSPMaddress());
gov_request->incPagesServed(host_info->getNumPages());
remaining_pages -= host_info->getNumPages();
}
else {
// not enough space on this SPM, allocation too large
DPRINTF(GOV, "%s: Couldn't allocate %d SPM slot(s) for node (%d,%d) on node (%d,%d)\n",
gov_type, remaining_pages,
host_info->getUserPMMU()->getNodeID() / num_column,
host_info->getUserPMMU()->getNodeID() % num_column,
host_info->getHostPMMU()->getNodeID() / num_column,
host_info->getHostPMMU()->getNodeID() % num_column);
}
return total_num_pages - remaining_pages;
}
| 34.908333 | 97 | 0.664359 | danned |
4fdc7935166d58b7a66106112a6a2a1f4ae9af45 | 8,768 | cc | C++ | lite/kernels/host/generate_proposals_compute.cc | wanglei91/Paddle-Lite | 8b2479f4cdd6970be507203d791bede5a453c09d | [
"Apache-2.0"
] | 1,799 | 2019-08-19T03:29:38.000Z | 2022-03-31T14:30:50.000Z | lite/kernels/host/generate_proposals_compute.cc | wanglei91/Paddle-Lite | 8b2479f4cdd6970be507203d791bede5a453c09d | [
"Apache-2.0"
] | 3,767 | 2019-08-19T03:36:04.000Z | 2022-03-31T14:37:26.000Z | lite/kernels/host/generate_proposals_compute.cc | wanglei91/Paddle-Lite | 8b2479f4cdd6970be507203d791bede5a453c09d | [
"Apache-2.0"
] | 798 | 2019-08-19T02:28:23.000Z | 2022-03-31T08:31:54.000Z | // Copyright (c) 2019 PaddlePaddle 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 "lite/kernels/host/generate_proposals_compute.h"
#include <string>
#include <utility>
#include <vector>
#include "lite/backends/host/math/bbox_util.h"
#include "lite/backends/host/math/gather.h"
#include "lite/backends/host/math/nms_util.h"
#include "lite/backends/host/math/transpose.h"
#include "lite/core/op_registry.h"
namespace paddle {
namespace lite {
namespace kernels {
namespace host {
std::pair<Tensor, Tensor> ProposalForOneImage(
const Tensor &im_info_slice,
const Tensor &anchors,
const Tensor &variances, // H * W * A * 4
const Tensor &bbox_deltas_slice, // [A, 4]
const Tensor &scores_slice, // [A, 1]
int pre_nms_top_n,
int post_nms_top_n,
float nms_thresh,
float min_size,
float eta) {
// sort scores_slice
Tensor index_t;
index_t.Resize(std::vector<int64_t>({scores_slice.numel()}));
auto *index = index_t.mutable_data<int>();
for (int i = 0; i < index_t.numel(); i++) {
index[i] = i;
}
auto *scores_data = scores_slice.data<float>();
auto compare_func = [scores_data](const int64_t &i, const int64_t &j) {
return scores_data[i] > scores_data[j];
};
if (pre_nms_top_n <= 0 || pre_nms_top_n >= scores_slice.numel()) {
std::stable_sort(index, index + scores_slice.numel(), compare_func);
} else {
std::nth_element(index,
index + pre_nms_top_n,
index + scores_slice.numel(),
compare_func);
index_t.Resize({pre_nms_top_n});
}
Tensor scores_sel, bbox_sel, anchor_sel, var_sel;
scores_sel.Resize(std::vector<int64_t>({index_t.numel(), 1}));
bbox_sel.Resize(std::vector<int64_t>({index_t.numel(), 4}));
anchor_sel.Resize(std::vector<int64_t>({index_t.numel(), 4}));
var_sel.Resize(std::vector<int64_t>({index_t.numel(), 4}));
lite::host::math::Gather<float>(scores_slice, index_t, &scores_sel);
lite::host::math::Gather<float>(bbox_deltas_slice, index_t, &bbox_sel);
lite::host::math::Gather<float>(anchors, index_t, &anchor_sel);
lite::host::math::Gather<float>(variances, index_t, &var_sel);
Tensor proposals;
proposals.Resize(std::vector<int64_t>({index_t.numel(), 4}));
lite::host::math::BoxCoder<float>(
&anchor_sel, &bbox_sel, &var_sel, &proposals);
lite::host::math::ClipTiledBoxes<float>(
im_info_slice, proposals, &proposals, false);
Tensor keep;
lite::host::math::FilterBoxes<float>(
&proposals, min_size, im_info_slice, true, &keep);
Tensor scores_filter;
scores_filter.Resize(std::vector<int64_t>({keep.numel(), 1}));
bbox_sel.Resize(std::vector<int64_t>({keep.numel(), 4}));
lite::host::math::Gather<float>(scores_sel, keep, &scores_filter);
lite::host::math::Gather<float>(proposals, keep, &bbox_sel);
if (nms_thresh <= 0) {
return std::make_pair(bbox_sel, scores_filter);
}
Tensor keep_nms =
lite::host::math::NMS<float>(&bbox_sel, &scores_filter, nms_thresh, eta);
if (post_nms_top_n > 0 && post_nms_top_n < keep_nms.numel()) {
keep_nms.Resize(std::vector<int64_t>({post_nms_top_n}));
}
proposals.Resize(std::vector<int64_t>({keep_nms.numel(), 4}));
scores_sel.Resize(std::vector<int64_t>({keep_nms.numel(), 1}));
lite::host::math::Gather<float>(bbox_sel, keep_nms, &proposals);
lite::host::math::Gather<float>(scores_filter, keep_nms, &scores_sel);
return std::make_pair(proposals, scores_sel);
}
void GenerateProposalsCompute::Run() {
auto ¶m = Param<param_t>();
auto *scores = param.Scores; // N * A * H * W
auto *bbox_deltas = param.BboxDeltas; // N * 4A * H * W
auto *im_info = param.ImInfo; // N * 3
auto *anchors = param.Anchors; // H * W * A * 4
auto *variances = param.Variances; // H * W * A * 4
auto *rpn_rois = param.RpnRois; // A * 4
auto *rpn_roi_probs = param.RpnRoiProbs; // A * 1
int pre_nms_top_n = param.pre_nms_topN;
int post_nms_top_n = param.post_nms_topN;
float nms_thresh = param.nms_thresh;
float min_size = param.min_size;
float eta = param.eta;
auto &scores_dim = scores->dims();
int64_t num = scores_dim[0];
int64_t c_score = scores_dim[1];
int64_t h_score = scores_dim[2];
int64_t w_score = scores_dim[3];
auto &bbox_dim = bbox_deltas->dims();
int64_t c_bbox = bbox_dim[1];
int64_t h_bbox = bbox_dim[2];
int64_t w_bbox = bbox_dim[3];
rpn_rois->Resize({bbox_deltas->numel(), 4});
rpn_roi_probs->Resize(std::vector<int64_t>({scores->numel(), 1}));
Tensor bbox_deltas_swap, scores_swap;
scores_swap.Resize(std::vector<int64_t>({num, h_score, w_score, c_score}));
bbox_deltas_swap.Resize(std::vector<int64_t>({num, h_bbox, w_bbox, c_bbox}));
std::vector<int> orders({0, 2, 3, 1});
lite::host::math::Transpose<float>(*scores, &scores_swap, orders);
lite::host::math::Transpose<float>(*bbox_deltas, &bbox_deltas_swap, orders);
LoD lod;
lod.resize(1);
auto &lod0 = lod[0];
lod0.push_back(0);
anchors->Resize(std::vector<int64_t>({anchors->numel() / 4, 4}));
variances->Resize(std::vector<int64_t>({variances->numel() / 4, 4}));
std::vector<int64_t> tmp_lod;
std::vector<int64_t> tmp_num;
int64_t num_proposals = 0;
for (int64_t i = 0; i < num; ++i) {
Tensor im_info_slice = im_info->Slice<float>(i, i + 1);
Tensor bbox_deltas_slice = bbox_deltas_swap.Slice<float>(i, i + 1);
Tensor scores_slice = scores_swap.Slice<float>(i, i + 1);
bbox_deltas_slice.Resize(
std::vector<int64_t>({c_bbox * h_bbox * w_bbox / 4, 4}));
scores_slice.Resize(std::vector<int64_t>({c_score * h_score * w_score, 1}));
std::pair<Tensor, Tensor> tensor_pair =
ProposalForOneImage(im_info_slice,
*anchors,
*variances,
bbox_deltas_slice,
scores_slice,
pre_nms_top_n,
post_nms_top_n,
nms_thresh,
min_size,
eta);
Tensor &proposals = tensor_pair.first;
Tensor &scores = tensor_pair.second;
lite::host::math::AppendTensor<float>(
rpn_rois, 4 * num_proposals, proposals);
lite::host::math::AppendTensor<float>(rpn_roi_probs, num_proposals, scores);
num_proposals += proposals.dims()[0];
lod0.push_back(num_proposals);
tmp_lod.push_back(num_proposals);
tmp_num.push_back(proposals.dims()[0]);
}
if (param.RpnRoisLod != nullptr) {
param.RpnRoisLod->Resize(DDim(std::vector<DDim::value_type>({num})));
int64_t *lod_data = param.RpnRoisLod->mutable_data<int64_t>();
for (int i = 0; i < num; i++) {
lod_data[i] = tmp_lod[i];
}
}
if (param.RpnRoisNum != nullptr) {
param.RpnRoisNum->Resize(DDim(std::vector<DDim::value_type>({num})));
int64_t *num_data = param.RpnRoisNum->mutable_data<int64_t>();
for (int i = 0; i < num; i++) {
num_data[i] = tmp_num[i];
}
}
rpn_rois->set_lod(lod);
rpn_roi_probs->set_lod(lod);
rpn_rois->Resize({num_proposals, 4});
rpn_roi_probs->Resize({num_proposals, 1});
}
} // namespace host
} // namespace kernels
} // namespace lite
} // namespace paddle
REGISTER_LITE_KERNEL(generate_proposals,
kHost,
kFloat,
kNCHW,
paddle::lite::kernels::host::GenerateProposalsCompute,
def)
.BindInput("Scores", {LiteType::GetTensorTy(TARGET(kHost))})
.BindInput("BboxDeltas", {LiteType::GetTensorTy(TARGET(kHost))})
.BindInput("ImInfo", {LiteType::GetTensorTy(TARGET(kHost))})
.BindInput("Anchors", {LiteType::GetTensorTy(TARGET(kHost))})
.BindInput("Variances", {LiteType::GetTensorTy(TARGET(kHost))})
.BindOutput("RpnRois", {LiteType::GetTensorTy(TARGET(kHost))})
.BindOutput("RpnRoiProbs", {LiteType::GetTensorTy(TARGET(kHost))})
.BindOutput("RpnRoisLod",
{LiteType::GetTensorTy(TARGET(kHost), PRECISION(kInt64))})
.BindOutput("RpnRoisNum",
{LiteType::GetTensorTy(TARGET(kHost), PRECISION(kInt64))})
.Finalize();
| 38.625551 | 80 | 0.649293 | wanglei91 |
4fdcc9f7ff1c8b0928366d3a70940ed2cf2e80a4 | 30,056 | cpp | C++ | Source/core/svg/SVGUseElement.cpp | scheib/blink | d18c0cc5b4e96ea87c556bfa57955538de498a9f | [
"BSD-3-Clause"
] | 1 | 2017-08-25T05:15:52.000Z | 2017-08-25T05:15:52.000Z | Source/core/svg/SVGUseElement.cpp | scheib/blink | d18c0cc5b4e96ea87c556bfa57955538de498a9f | [
"BSD-3-Clause"
] | null | null | null | Source/core/svg/SVGUseElement.cpp | scheib/blink | d18c0cc5b4e96ea87c556bfa57955538de498a9f | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2004, 2005, 2006, 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
* Copyright (C) 2004, 2005, 2006, 2007 Rob Buis <buis@kde.org>
* Copyright (C) Research In Motion Limited 2009-2010. All rights reserved.
* Copyright (C) 2011 Torch Mobile (Beijing) Co. Ltd. All rights reserved.
* Copyright (C) 2012 University of Szeged
* Copyright (C) 2012 Renata Hodovan <reni@webkit.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "core/svg/SVGUseElement.h"
#include "bindings/core/v8/ExceptionStatePlaceholder.h"
#include "core/XLinkNames.h"
#include "core/dom/Document.h"
#include "core/dom/ElementTraversal.h"
#include "core/events/Event.h"
#include "core/dom/shadow/ElementShadow.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/fetch/FetchRequest.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/rendering/svg/RenderSVGTransformableContainer.h"
#include "core/svg/SVGGElement.h"
#include "core/svg/SVGLengthContext.h"
#include "core/svg/SVGSVGElement.h"
#include "core/xml/parser/XMLDocumentParser.h"
namespace blink {
inline SVGUseElement::SVGUseElement(Document& document)
: SVGGraphicsElement(SVGNames::useTag, document)
, m_x(SVGAnimatedLength::create(this, SVGNames::xAttr, SVGLength::create(LengthModeWidth), AllowNegativeLengths))
, m_y(SVGAnimatedLength::create(this, SVGNames::yAttr, SVGLength::create(LengthModeHeight), AllowNegativeLengths))
, m_width(SVGAnimatedLength::create(this, SVGNames::widthAttr, SVGLength::create(LengthModeWidth), ForbidNegativeLengths))
, m_height(SVGAnimatedLength::create(this, SVGNames::heightAttr, SVGLength::create(LengthModeHeight), ForbidNegativeLengths))
, m_haveFiredLoadEvent(false)
, m_needsShadowTreeRecreation(false)
, m_svgLoadEventTimer(this, &SVGElement::svgLoadEventTimerFired)
{
SVGURIReference::initialize(this);
ASSERT(hasCustomStyleCallbacks());
addToPropertyMap(m_x);
addToPropertyMap(m_y);
addToPropertyMap(m_width);
addToPropertyMap(m_height);
}
PassRefPtrWillBeRawPtr<SVGUseElement> SVGUseElement::create(Document& document)
{
// Always build a user agent #shadow-root for SVGUseElement.
RefPtrWillBeRawPtr<SVGUseElement> use = adoptRefWillBeNoop(new SVGUseElement(document));
use->ensureUserAgentShadowRoot();
return use.release();
}
SVGUseElement::~SVGUseElement()
{
setDocumentResource(0);
#if !ENABLE(OILPAN)
clearResourceReferences();
#endif
}
void SVGUseElement::trace(Visitor* visitor)
{
visitor->trace(m_x);
visitor->trace(m_y);
visitor->trace(m_width);
visitor->trace(m_height);
visitor->trace(m_targetElementInstance);
SVGGraphicsElement::trace(visitor);
SVGURIReference::trace(visitor);
}
bool SVGUseElement::isSupportedAttribute(const QualifiedName& attrName)
{
DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
if (supportedAttributes.isEmpty()) {
SVGURIReference::addSupportedAttributes(supportedAttributes);
supportedAttributes.add(SVGNames::xAttr);
supportedAttributes.add(SVGNames::yAttr);
supportedAttributes.add(SVGNames::widthAttr);
supportedAttributes.add(SVGNames::heightAttr);
}
return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
}
void SVGUseElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
parseAttributeNew(name, value);
}
#if ENABLE(ASSERT)
static inline bool isWellFormedDocument(Document* document)
{
if (document->isXMLDocument())
return static_cast<XMLDocumentParser*>(document->parser())->wellFormed();
return true;
}
#endif
Node::InsertionNotificationRequest SVGUseElement::insertedInto(ContainerNode* rootParent)
{
// This functions exists to assure assumptions made in the code regarding SVGElementInstance creation/destruction are satisfied.
SVGGraphicsElement::insertedInto(rootParent);
if (!rootParent->inDocument())
return InsertionDone;
ASSERT(!m_targetElementInstance || !isWellFormedDocument(&document()));
ASSERT(!hasPendingResources() || !isWellFormedDocument(&document()));
invalidateShadowTree();
if (!isStructurallyExternal())
sendSVGLoadEventIfPossibleAsynchronously();
return InsertionDone;
}
void SVGUseElement::removedFrom(ContainerNode* rootParent)
{
SVGGraphicsElement::removedFrom(rootParent);
if (rootParent->inDocument())
clearResourceReferences();
}
TreeScope* SVGUseElement::referencedScope() const
{
if (!isExternalURIReference(hrefString(), document()))
return &treeScope();
return externalDocument();
}
Document* SVGUseElement::externalDocument() const
{
if (m_resource && m_resource->isLoaded()) {
// Gracefully handle error condition.
if (m_resource->errorOccurred())
return 0;
ASSERT(m_resource->document());
return m_resource->document();
}
return 0;
}
void transferUseWidthAndHeightIfNeeded(const SVGUseElement& use, SVGElement* shadowElement, const SVGElement& originalElement)
{
DEFINE_STATIC_LOCAL(const AtomicString, hundredPercentString, ("100%", AtomicString::ConstructFromLiteral));
ASSERT(shadowElement);
if (isSVGSymbolElement(*shadowElement)) {
// Spec (<use> on <symbol>): This generated 'svg' will always have explicit values for attributes width and height.
// If attributes width and/or height are provided on the 'use' element, then these attributes
// will be transferred to the generated 'svg'. If attributes width and/or height are not specified,
// the generated 'svg' element will use values of 100% for these attributes.
shadowElement->setAttribute(SVGNames::widthAttr, use.width()->isSpecified() ? AtomicString(use.width()->currentValue()->valueAsString()) : hundredPercentString);
shadowElement->setAttribute(SVGNames::heightAttr, use.height()->isSpecified() ? AtomicString(use.height()->currentValue()->valueAsString()) : hundredPercentString);
} else if (isSVGSVGElement(*shadowElement)) {
// Spec (<use> on <svg>): If attributes width and/or height are provided on the 'use' element, then these
// values will override the corresponding attributes on the 'svg' in the generated tree.
if (use.width()->isSpecified())
shadowElement->setAttribute(SVGNames::widthAttr, AtomicString(use.width()->currentValue()->valueAsString()));
else
shadowElement->setAttribute(SVGNames::widthAttr, originalElement.getAttribute(SVGNames::widthAttr));
if (use.height()->isSpecified())
shadowElement->setAttribute(SVGNames::heightAttr, AtomicString(use.height()->currentValue()->valueAsString()));
else
shadowElement->setAttribute(SVGNames::heightAttr, originalElement.getAttribute(SVGNames::heightAttr));
}
}
void SVGUseElement::svgAttributeChanged(const QualifiedName& attrName)
{
if (!isSupportedAttribute(attrName)) {
SVGGraphicsElement::svgAttributeChanged(attrName);
return;
}
SVGElement::InvalidationGuard invalidationGuard(this);
RenderObject* renderer = this->renderer();
if (attrName == SVGNames::xAttr
|| attrName == SVGNames::yAttr
|| attrName == SVGNames::widthAttr
|| attrName == SVGNames::heightAttr) {
updateRelativeLengthsInformation();
if (m_targetElementInstance) {
ASSERT(m_targetElementInstance->correspondingElement());
transferUseWidthAndHeightIfNeeded(*this, m_targetElementInstance.get(), *m_targetElementInstance->correspondingElement());
}
if (renderer)
markForLayoutAndParentResourceInvalidation(renderer);
return;
}
if (SVGURIReference::isKnownAttribute(attrName)) {
bool isExternalReference = isExternalURIReference(hrefString(), document());
if (isExternalReference) {
KURL url = document().completeURL(hrefString());
if (url.hasFragmentIdentifier()) {
FetchRequest request(ResourceRequest(url), localName());
setDocumentResource(document().fetcher()->fetchSVGDocument(request));
}
} else {
setDocumentResource(0);
}
invalidateShadowTree();
return;
}
if (!renderer)
return;
ASSERT_NOT_REACHED();
}
static bool isDisallowedElement(Node* node)
{
// Spec: "Any 'svg', 'symbol', 'g', graphics element or other 'use' is potentially a template object that can be re-used
// (i.e., "instanced") in the SVG document via a 'use' element."
// "Graphics Element" is defined as 'circle', 'ellipse', 'image', 'line', 'path', 'polygon', 'polyline', 'rect', 'text'
// Excluded are anything that is used by reference or that only make sense to appear once in a document.
// We must also allow the shadow roots of other use elements.
if (node->isShadowRoot() || node->isTextNode())
return false;
if (!node->isSVGElement())
return true;
Element* element = toElement(node);
DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, allowedElementTags, ());
if (allowedElementTags.isEmpty()) {
allowedElementTags.add(SVGNames::aTag);
allowedElementTags.add(SVGNames::circleTag);
allowedElementTags.add(SVGNames::descTag);
allowedElementTags.add(SVGNames::ellipseTag);
allowedElementTags.add(SVGNames::gTag);
allowedElementTags.add(SVGNames::imageTag);
allowedElementTags.add(SVGNames::lineTag);
allowedElementTags.add(SVGNames::metadataTag);
allowedElementTags.add(SVGNames::pathTag);
allowedElementTags.add(SVGNames::polygonTag);
allowedElementTags.add(SVGNames::polylineTag);
allowedElementTags.add(SVGNames::rectTag);
allowedElementTags.add(SVGNames::svgTag);
allowedElementTags.add(SVGNames::switchTag);
allowedElementTags.add(SVGNames::symbolTag);
allowedElementTags.add(SVGNames::textTag);
allowedElementTags.add(SVGNames::textPathTag);
allowedElementTags.add(SVGNames::titleTag);
allowedElementTags.add(SVGNames::tspanTag);
allowedElementTags.add(SVGNames::useTag);
}
return !allowedElementTags.contains<SVGAttributeHashTranslator>(element->tagQName());
}
static bool subtreeContainsDisallowedElement(Node* start)
{
if (isDisallowedElement(start))
return true;
for (Node* cur = start->firstChild(); cur; cur = cur->nextSibling()) {
if (subtreeContainsDisallowedElement(cur))
return true;
}
return false;
}
void SVGUseElement::scheduleShadowTreeRecreation()
{
if (!referencedScope() || inUseShadowTree())
return;
m_needsShadowTreeRecreation = true;
document().scheduleUseShadowTreeUpdate(*this);
}
void SVGUseElement::clearResourceReferences()
{
if (m_targetElementInstance)
m_targetElementInstance = nullptr;
// FIXME: We should try to optimize this, to at least allow partial reclones.
if (ShadowRoot* shadowTreeRootElement = userAgentShadowRoot())
shadowTreeRootElement->removeChildren(OmitSubtreeModifiedEvent);
m_needsShadowTreeRecreation = false;
document().unscheduleUseShadowTreeUpdate(*this);
removeAllOutgoingReferences();
}
void SVGUseElement::buildPendingResource()
{
if (!referencedScope() || inUseShadowTree())
return;
clearResourceReferences();
if (!inDocument())
return;
AtomicString id;
Element* target = SVGURIReference::targetElementFromIRIString(hrefString(), treeScope(), &id, externalDocument());
if (!target || !target->inDocument()) {
// If we can't find the target of an external element, just give up.
// We can't observe if the target somewhen enters the external document, nor should we do it.
if (externalDocument())
return;
if (id.isEmpty())
return;
referencedScope()->document().accessSVGExtensions().addPendingResource(id, this);
ASSERT(hasPendingResources());
return;
}
if (target->isSVGElement()) {
buildShadowAndInstanceTree(toSVGElement(target));
invalidateDependentShadowTrees();
}
ASSERT(!m_needsShadowTreeRecreation);
}
static PassRefPtrWillBeRawPtr<Node> cloneNodeAndAssociate(Node& toClone)
{
RefPtrWillBeRawPtr<Node> clone = toClone.cloneNode(false);
if (!clone->isSVGElement())
return clone.release();
SVGElement& svgElement = toSVGElement(toClone);
ASSERT(!svgElement.correspondingElement());
toSVGElement(clone.get())->setCorrespondingElement(&svgElement);
if (EventTargetData* data = toClone.eventTargetData())
data->eventListenerMap.copyEventListenersNotCreatedFromMarkupToTarget(clone.get());
TrackExceptionState exceptionState;
for (Node* node = toClone.firstChild(); node && !exceptionState.hadException(); node = node->nextSibling())
clone->appendChild(cloneNodeAndAssociate(*node), exceptionState);
return clone.release();
}
void SVGUseElement::buildShadowAndInstanceTree(SVGElement* target)
{
ASSERT(!m_targetElementInstance);
// <use> creates a "user agent" shadow root. Do not build the shadow/instance tree for <use>
// elements living in a user agent shadow tree because they will get expanded in a second
// pass -- see expandUseElementsInShadowTree().
if (inUseShadowTree())
return;
// Do not allow self-referencing.
// 'target' may be null, if it's a non SVG namespaced element.
if (!target || target == this)
return;
// Set up root SVG element in shadow tree.
RefPtrWillBeRawPtr<Element> newChild = target->cloneElementWithoutChildren();
m_targetElementInstance = toSVGElement(newChild.get());
ShadowRoot* shadowTreeRootElement = userAgentShadowRoot();
shadowTreeRootElement->appendChild(newChild.release());
// Clone the target subtree into the shadow tree, not handling <use> and <symbol> yet.
// SVG specification does not say a word about <use> & cycles. My view on this is: just ignore it!
// Non-appearing <use> content is easier to debug, then half-appearing content.
if (!buildShadowTree(target, m_targetElementInstance.get(), false)) {
clearResourceReferences();
return;
}
if (instanceTreeIsLoading(m_targetElementInstance.get()))
return;
// Assure shadow tree building was successfull
ASSERT(m_targetElementInstance);
ASSERT(m_targetElementInstance->correspondingUseElement() == this);
ASSERT(m_targetElementInstance->correspondingElement() == target);
// Expand all <use> elements in the shadow tree.
// Expand means: replace the actual <use> element by what it references.
if (!expandUseElementsInShadowTree(m_targetElementInstance.get())) {
clearResourceReferences();
return;
}
// Expand all <symbol> elements in the shadow tree.
// Expand means: replace the actual <symbol> element by the <svg> element.
expandSymbolElementsInShadowTree(toSVGElement(shadowTreeRootElement->firstChild()));
m_targetElementInstance = toSVGElement(shadowTreeRootElement->firstChild());
transferUseWidthAndHeightIfNeeded(*this, m_targetElementInstance.get(), *m_targetElementInstance->correspondingElement());
ASSERT(m_targetElementInstance->parentNode() == shadowTreeRootElement);
// Update relative length information.
updateRelativeLengthsInformation();
}
RenderObject* SVGUseElement::createRenderer(RenderStyle*)
{
return new RenderSVGTransformableContainer(this);
}
static bool isDirectReference(const SVGElement& element)
{
return isSVGPathElement(element)
|| isSVGRectElement(element)
|| isSVGCircleElement(element)
|| isSVGEllipseElement(element)
|| isSVGPolygonElement(element)
|| isSVGPolylineElement(element)
|| isSVGTextElement(element);
}
void SVGUseElement::toClipPath(Path& path)
{
ASSERT(path.isEmpty());
Node* n = userAgentShadowRoot()->firstChild();
if (!n || !n->isSVGElement())
return;
SVGElement& element = toSVGElement(*n);
if (element.isSVGGraphicsElement()) {
if (!isDirectReference(element)) {
// Spec: Indirect references are an error (14.3.5)
document().accessSVGExtensions().reportError("Not allowed to use indirect reference in <clip-path>");
} else {
toSVGGraphicsElement(element).toClipPath(path);
// FIXME: Avoid manual resolution of x/y here. Its potentially harmful.
SVGLengthContext lengthContext(this);
path.translate(FloatSize(m_x->currentValue()->value(lengthContext), m_y->currentValue()->value(lengthContext)));
path.transform(calculateAnimatedLocalTransform());
}
}
}
RenderObject* SVGUseElement::rendererClipChild() const
{
if (Node* n = userAgentShadowRoot()->firstChild()) {
if (n->isSVGElement() && isDirectReference(toSVGElement(*n)))
return n->renderer();
}
return 0;
}
bool SVGUseElement::buildShadowTree(SVGElement* target, SVGElement* targetInstance, bool foundUse)
{
ASSERT(target);
ASSERT(targetInstance);
// Spec: If the referenced object is itself a 'use', or if there are 'use' subelements within the referenced
// object, the instance tree will contain recursive expansion of the indirect references to form a complete tree.
if (isSVGUseElement(*target)) {
// We only need to track first degree <use> dependencies. Indirect references are handled
// as the invalidation bubbles up the dependency chain.
if (!foundUse && !isStructurallyExternal()) {
addReferenceTo(target);
foundUse = true;
}
} else if (isDisallowedElement(target)) {
return false;
}
targetInstance->setCorrespondingElement(target);
if (EventTargetData* data = target->eventTargetData())
data->eventListenerMap.copyEventListenersNotCreatedFromMarkupToTarget(targetInstance);
for (Node* child = target->firstChild(); child; child = child->nextSibling()) {
// Skip any disallowed element.
if (isDisallowedElement(child))
continue;
RefPtrWillBeRawPtr<Node> newChild = child->cloneNode(false);
targetInstance->appendChild(newChild.get());
if (newChild->isSVGElement()) {
// Enter recursion, appending new instance tree nodes to the "instance" object.
if (!buildShadowTree(toSVGElement(child), toSVGElement(newChild), foundUse))
return false;
}
}
return true;
}
bool SVGUseElement::hasCycleUseReferencing(SVGUseElement* use, ContainerNode* targetInstance, SVGElement*& newTarget)
{
ASSERT(referencedScope());
Element* targetElement = SVGURIReference::targetElementFromIRIString(use->hrefString(), *referencedScope());
newTarget = 0;
if (targetElement && targetElement->isSVGElement())
newTarget = toSVGElement(targetElement);
if (!newTarget)
return false;
// Shortcut for self-references
if (newTarget == this)
return true;
AtomicString targetId = newTarget->getIdAttribute();
ContainerNode* instance = targetInstance->parentNode();
while (instance && instance->isSVGElement()) {
SVGElement* element = toSVGElement(instance);
if (element->hasID() && element->getIdAttribute() == targetId && element->document() == newTarget->document())
return true;
instance = instance->parentNode();
}
return false;
}
static inline void removeDisallowedElementsFromSubtree(Element& subtree)
{
ASSERT(!subtree.inDocument());
Element* element = ElementTraversal::firstWithin(subtree);
while (element) {
if (isDisallowedElement(element)) {
Element* next = ElementTraversal::nextSkippingChildren(*element, &subtree);
// The subtree is not in document so this won't generate events that could mutate the tree.
element->parentNode()->removeChild(element);
element = next;
} else {
element = ElementTraversal::next(*element, &subtree);
}
}
}
bool SVGUseElement::expandUseElementsInShadowTree(SVGElement* element)
{
ASSERT(element);
// Why expand the <use> elements in the shadow tree here, and not just
// do this directly in buildShadowTree, if we encounter a <use> element?
//
// Short answer: Because we may miss to expand some elements. For example, if a <symbol>
// contains <use> tags, we'd miss them. So once we're done with setting up the
// actual shadow tree (after the special case modification for svg/symbol) we have
// to walk it completely and expand all <use> elements.
if (isSVGUseElement(*element)) {
SVGUseElement* use = toSVGUseElement(element);
ASSERT(!use->resourceIsStillLoading());
SVGElement* target = 0;
if (hasCycleUseReferencing(toSVGUseElement(use->correspondingElement()), use, target))
return false;
if (target && isDisallowedElement(target))
return false;
// Don't ASSERT(target) here, it may be "pending", too.
// Setup sub-shadow tree root node
RefPtrWillBeRawPtr<SVGGElement> cloneParent = SVGGElement::create(referencedScope()->document());
cloneParent->setCorrespondingElement(use->correspondingElement());
// Move already cloned elements to the new <g> element
for (Node* child = use->firstChild(); child; ) {
Node* nextChild = child->nextSibling();
cloneParent->appendChild(child);
child = nextChild;
}
// Spec: In the generated content, the 'use' will be replaced by 'g', where all attributes from the
// 'use' element except for x, y, width, height and xlink:href are transferred to the generated 'g' element.
transferUseAttributesToReplacedElement(use, cloneParent.get());
if (target) {
RefPtrWillBeRawPtr<Node> newChild = cloneNodeAndAssociate(*target);
ASSERT(newChild->isSVGElement());
transferUseWidthAndHeightIfNeeded(*use, toSVGElement(newChild.get()), *target);
cloneParent->appendChild(newChild.release());
}
// We don't walk the target tree element-by-element, and clone each element,
// but instead use cloneElementWithChildren(). This is an optimization for the common
// case where <use> doesn't contain disallowed elements (ie. <foreignObject>).
// Though if there are disallowed elements in the subtree, we have to remove them.
// For instance: <use> on <g> containing <foreignObject> (indirect case).
if (subtreeContainsDisallowedElement(cloneParent.get()))
removeDisallowedElementsFromSubtree(*cloneParent);
RefPtrWillBeRawPtr<SVGElement> replacingElement(cloneParent.get());
// Replace <use> with referenced content.
ASSERT(use->parentNode());
use->parentNode()->replaceChild(cloneParent.release(), use);
// Expand the siblings because the *element* is replaced and we will
// lose the sibling chain when we are back from recursion.
element = replacingElement.get();
for (RefPtrWillBeRawPtr<SVGElement> sibling = Traversal<SVGElement>::nextSibling(*element); sibling; sibling = Traversal<SVGElement>::nextSibling(*sibling)) {
if (!expandUseElementsInShadowTree(sibling.get()))
return false;
}
}
for (RefPtrWillBeRawPtr<SVGElement> child = Traversal<SVGElement>::firstChild(*element); child; child = Traversal<SVGElement>::nextSibling(*child)) {
if (!expandUseElementsInShadowTree(child.get()))
return false;
}
return true;
}
void SVGUseElement::expandSymbolElementsInShadowTree(SVGElement* element)
{
ASSERT(element);
if (isSVGSymbolElement(*element)) {
// Spec: The referenced 'symbol' and its contents are deep-cloned into the generated tree,
// with the exception that the 'symbol' is replaced by an 'svg'. This generated 'svg' will
// always have explicit values for attributes width and height. If attributes width and/or
// height are provided on the 'use' element, then these attributes will be transferred to
// the generated 'svg'. If attributes width and/or height are not specified, the generated
// 'svg' element will use values of 100% for these attributes.
ASSERT(referencedScope());
RefPtrWillBeRawPtr<SVGSVGElement> svgElement = SVGSVGElement::create(referencedScope()->document());
// Transfer all data (attributes, etc.) from <symbol> to the new <svg> element.
svgElement->cloneDataFromElement(*element);
svgElement->setCorrespondingElement(element->correspondingElement());
// Move already cloned elements to the new <svg> element
for (Node* child = element->firstChild(); child; ) {
Node* nextChild = child->nextSibling();
svgElement->appendChild(child);
child = nextChild;
}
// We don't walk the target tree element-by-element, and clone each element,
// but instead use cloneNode(deep=true). This is an optimization for the common
// case where <use> doesn't contain disallowed elements (ie. <foreignObject>).
// Though if there are disallowed elements in the subtree, we have to remove them.
// For instance: <use> on <g> containing <foreignObject> (indirect case).
if (subtreeContainsDisallowedElement(svgElement.get()))
removeDisallowedElementsFromSubtree(*svgElement);
RefPtrWillBeRawPtr<SVGElement> replacingElement(svgElement.get());
// Replace <symbol> with <svg>.
ASSERT(element->parentNode());
element->parentNode()->replaceChild(svgElement.release(), element);
// Expand the siblings because the *element* is replaced and we will
// lose the sibling chain when we are back from recursion.
element = replacingElement.get();
}
for (RefPtrWillBeRawPtr<SVGElement> child = Traversal<SVGElement>::firstChild(*element); child; child = Traversal<SVGElement>::nextSibling(*child))
expandSymbolElementsInShadowTree(child.get());
}
void SVGUseElement::invalidateShadowTree()
{
if (!inActiveDocument() || m_needsShadowTreeRecreation)
return;
scheduleShadowTreeRecreation();
invalidateDependentShadowTrees();
}
void SVGUseElement::invalidateDependentShadowTrees()
{
// Recursively invalidate dependent <use> shadow trees
const WillBeHeapHashSet<RawPtrWillBeWeakMember<SVGElement> >& instances = instancesForElement();
for (SVGElement* instance : instances) {
if (SVGUseElement* element = instance->correspondingUseElement()) {
ASSERT(element->inDocument());
element->invalidateShadowTree();
}
}
}
void SVGUseElement::transferUseAttributesToReplacedElement(SVGElement* from, SVGElement* to) const
{
ASSERT(from);
ASSERT(to);
to->cloneDataFromElement(*from);
to->removeAttribute(SVGNames::xAttr);
to->removeAttribute(SVGNames::yAttr);
to->removeAttribute(SVGNames::widthAttr);
to->removeAttribute(SVGNames::heightAttr);
to->removeAttribute(XLinkNames::hrefAttr);
}
bool SVGUseElement::selfHasRelativeLengths() const
{
if (m_x->currentValue()->isRelative()
|| m_y->currentValue()->isRelative()
|| m_width->currentValue()->isRelative()
|| m_height->currentValue()->isRelative())
return true;
if (!m_targetElementInstance)
return false;
return m_targetElementInstance->hasRelativeLengths();
}
void SVGUseElement::notifyFinished(Resource* resource)
{
if (!inDocument())
return;
invalidateShadowTree();
if (resource->errorOccurred())
dispatchEvent(Event::create(EventTypeNames::error));
else if (!resource->wasCanceled()) {
if (m_haveFiredLoadEvent)
return;
if (!isStructurallyExternal())
return;
ASSERT(!m_haveFiredLoadEvent);
m_haveFiredLoadEvent = true;
sendSVGLoadEventIfPossibleAsynchronously();
}
}
bool SVGUseElement::resourceIsStillLoading()
{
if (m_resource && m_resource->isLoading())
return true;
return false;
}
bool SVGUseElement::instanceTreeIsLoading(SVGElement* targetInstance)
{
for (SVGElement* element = Traversal<SVGElement>::firstChild(*targetInstance); element; element = Traversal<SVGElement>::nextSibling(*element)) {
if (SVGUseElement* use = element->correspondingUseElement()) {
if (use->resourceIsStillLoading())
return true;
}
if (element->hasChildren() && instanceTreeIsLoading(element))
return true;
}
return false;
}
void SVGUseElement::setDocumentResource(ResourcePtr<DocumentResource> resource)
{
if (m_resource == resource)
return;
if (m_resource)
m_resource->removeClient(this);
m_resource = resource;
if (m_resource)
m_resource->addClient(this);
}
}
| 39.288889 | 172 | 0.694504 | scheib |
4fdee9a5c071edd7361349f9787638d4247466b2 | 10,690 | cpp | C++ | source/common/widgets/StackedContainer.cpp | varunamachi/quartz | 29b0cf7fb981ec95db894259e32af233f64fa616 | [
"MIT"
] | 6 | 2018-01-07T18:11:27.000Z | 2022-03-25T03:32:45.000Z | source/common/widgets/StackedContainer.cpp | varunamachi/quartz | 29b0cf7fb981ec95db894259e32af233f64fa616 | [
"MIT"
] | 8 | 2019-02-28T02:25:53.000Z | 2019-02-28T15:47:18.000Z | source/common/widgets/StackedContainer.cpp | varunamachi/quartz | 29b0cf7fb981ec95db894259e32af233f64fa616 | [
"MIT"
] | 4 | 2016-05-28T16:31:06.000Z | 2019-09-25T07:13:45.000Z | #include <QVariant>
#include <QMouseEvent>
#include <QStackedWidget>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QPushButton>
#include <common/iconstore/IconFontStore.h>
#include "QzScroller.h"
#include "IdButton.h"
#include "StackedContainer.h"
namespace Quartz {
struct Item {
using Ptr = std::shared_ptr<Item>;
IdButton* m_btn;
QWidget* m_widget;
int m_index;
inline Item(int index, IdButton* btn, QWidget* widget)
: m_index(index)
, m_btn(btn)
, m_widget(widget) {
}
static inline Item::Ptr create(int index, IdButton* btn, QWidget* widget) {
return std::make_shared<Item>(index, btn, widget);
}
};
struct AbstractContainer::Data {
Data(int selectorDimention,
int buttonDimention,
Position selectorPosition,
Qt::Orientation orientation,
QzScroller* scroller,
QStackedWidget* stackedWidget)
: m_btnHeight(selectorDimention)
, m_btnWidth(buttonDimention)
, m_selectorPosition(selectorPosition)
, m_orientation(orientation)
, m_selector(scroller)
, m_stackWidget(stackedWidget)
, m_autoSelPolicy(AutoSelectionPolicy::SelectFirstAdded)
, m_selectedId("") {
}
int m_btnHeight;
int m_btnWidth;
Position m_selectorPosition;
Qt::Orientation m_orientation;
QzScroller* m_selector;
QStackedWidget* m_stackWidget;
AutoSelectionPolicy m_autoSelPolicy;
QString m_selectedId;
QHash<QString, Item::Ptr> m_items;
};
AbstractContainer::AbstractContainer(int selectorDimention,
int buttonDimention,
Position selectorPosition,
Qt::Orientation orientation,
QWidget* parent)
: QWidget(parent)
, m_data(new Data{selectorDimention,
buttonDimention,
selectorPosition,
orientation,
new QzScroller(orientation,
selectorDimention,
selectorDimention,
this),
new QStackedWidget(this)}) {
m_data->m_btnWidth = buttonDimention;
m_data->m_btnHeight = selectorDimention;
if (orientation == Qt::Horizontal) {
m_data->m_selector->setMaximumHeight(selectorDimention);
} else {
m_data->m_selector->setMaximumWidth(selectorDimention);
}
m_data->m_selector->setContentsMargins(QMargins());
m_data->m_stackWidget->setContentsMargins(QMargins());
this->setContentsMargins(QMargins());
}
AbstractContainer::~AbstractContainer() {
}
QWidget* AbstractContainer::widget(const QString& id) const {
QWidget* widget = nullptr;
auto item = m_data->m_items.value(id);
if (item) {
widget = item->m_widget;
}
return widget;
}
QWidget* AbstractContainer::selectedWidget() const {
QWidget* selected = nullptr;
auto item = m_data->m_items.value(m_data->m_selectedId);
if (item != nullptr) {
selected = item->m_widget;
}
return selected;
}
QString AbstractContainer::currentId() const {
return m_data->m_selectedId;
}
QList<QString> AbstractContainer::allIds() const {
return m_data->m_items.keys();
}
void AbstractContainer::addWidget(const QString& id,
const QString& displayName,
QWidget* widget) {
this->addWidget(id, displayName, QIcon{}, QIcon{}, widget);
}
void AbstractContainer::addWidget(const QString& id,
const QString& displayName,
const QIcon& icon,
const QIcon& activeIcon,
QWidget* widget) {
if (widget != nullptr) {
IdButton* btn = nullptr;
if (icon.isNull()) {
btn = new IdButton(
id, displayName, m_data->m_btnHeight, m_data->m_btnWidth, this);
} else {
auto btmTxt = this->containerOrientation() == Qt::Vertical;
btn = new IdButton(id,
displayName,
m_data->m_btnHeight,
m_data->m_btnWidth,
icon,
activeIcon,
btmTxt,
this);
}
btn->setContentsMargins({});
widget->setContentsMargins({});
auto index = m_data->m_stackWidget->addWidget(widget);
auto item = Item::create(index, btn, widget);
m_data->m_items.insert(id, item);
m_data->m_selector->addWidget(btn);
m_data->m_stackWidget->addWidget(widget);
connect(btn, SIGNAL(activated(QString)), this, SLOT(select(QString)));
widget->setProperty("item_id", id);
if (m_data->m_autoSelPolicy == AutoSelectionPolicy::SelectFirstAdded) {
if (m_data->m_selectedId.isEmpty()) {
this->select(id);
}
} else if (m_data->m_autoSelPolicy
== AutoSelectionPolicy::SelectLastAdded) {
this->select(id);
} else {
m_data->m_stackWidget->setVisible(false);
}
emit sigAdded(id, widget);
}
}
void AbstractContainer::removeWidget(const QString& id) {
auto item = m_data->m_items.value(id);
if (item) {
auto theWidget = widget(id);
m_data->m_selector->removeWidget(item->m_btn);
m_data->m_stackWidget->removeWidget(item->m_widget);
m_data->m_items.remove(id);
if (m_data->m_selectedId == id) {
m_data->m_selectedId = m_data->m_items.isEmpty()
? ""
: m_data->m_items.begin().key();
emit sigSelected(m_data->m_selectedId, selectedWidget());
}
updateIndeces();
theWidget->setProperty("item_id", QVariant());
emit sigRemoved(id);
}
}
void AbstractContainer::removeWidget(QWidget* widget) {
for (auto it = m_data->m_items.begin(); it != m_data->m_items.end(); ++it) {
auto item = it.value();
if (item->m_widget == widget) {
removeWidget(it.key());
/* I am not breaking here because same widget might have been added
* multiple times. If later if we find it not important we can break
* here.
*/
}
}
}
void AbstractContainer::select(const QString& id) {
auto item = m_data->m_items.value(id);
if (item) {
if (m_data->m_selectedId != ""
&& item->m_index == m_data->m_stackWidget->currentIndex()) {
m_data->m_stackWidget->setVisible(false);
item->m_btn->setChecked(false);
m_data->m_selectedId = "";
} else {
auto prev = m_data->m_items.value(m_data->m_selectedId);
item->m_btn->setChecked(true);
m_data->m_stackWidget->setCurrentIndex(item->m_index);
m_data->m_selectedId = id;
if (prev != nullptr) {
prev->m_btn->setChecked(false);
} else {
m_data->m_stackWidget->setVisible(true);
}
}
emit sigSelected(id, item->m_widget);
}
}
void AbstractContainer::hideAll() {
auto item = m_data->m_items.value(m_data->m_selectedId);
if (item) {
m_data->m_stackWidget->setVisible(false);
item->m_btn->setChecked(false);
m_data->m_selectedId = "";
}
}
void AbstractContainer::setAutoSelectionPolicy(AutoSelectionPolicy policy) {
m_data->m_autoSelPolicy = policy;
}
QStackedWidget* AbstractContainer::stackedWidget() const {
return m_data->m_stackWidget;
}
QzScroller* AbstractContainer::selector() const {
return m_data->m_selector;
}
AbstractContainer::Position AbstractContainer::selectorPosition() const {
return m_data->m_selectorPosition;
}
Qt::Orientation AbstractContainer::containerOrientation() const {
return m_data->m_orientation;
}
int AbstractContainer::buttonWidth() const {
return m_data->m_btnWidth;
}
int AbstractContainer::buttonHeight() const {
return m_data->m_btnHeight;
}
AutoSelectionPolicy AbstractContainer::autoSelectionPolicy() const {
return m_data->m_autoSelPolicy;
}
void AbstractContainer::updateIndeces() {
for (int i = 0;
i < m_data->m_stackWidget->count() && i < m_data->m_items.size();
++i) {
auto widget = m_data->m_stackWidget->widget(i);
auto itemId = widget->property("item_id");
if (itemId.isValid()) {
auto id = itemId.toString();
auto item = m_data->m_items.value(id);
item->m_index = i;
}
}
}
int AbstractContainer::numWidgets() const {
return m_data->m_items.size();
}
bool AbstractContainer::isEmpty() {
return m_data->m_items.isEmpty();
}
// Stacked container
StackedContainer::StackedContainer(int selectorDimention,
int buttonDimention,
AbstractContainer::Position selectorPosition,
Qt::Orientation orientation,
QWidget* parent)
: AbstractContainer(selectorDimention,
buttonDimention,
selectorPosition,
orientation,
parent) {
QBoxLayout* layout = nullptr;
if (orientation == Qt::Vertical) {
layout = new QHBoxLayout();
} else {
layout = new QVBoxLayout();
}
if (selectorPosition == Position::Before) {
layout->addWidget(selector());
layout->addWidget(stackedWidget());
layout->setAlignment(selector(),
orientation == Qt::Horizontal ? Qt::AlignTop
: Qt::AlignLeft);
} else {
layout->addWidget(stackedWidget());
layout->addWidget(selector());
layout->setAlignment(selector(),
orientation == Qt::Horizontal ? Qt::AlignBottom
: Qt::AlignRight);
}
layout->setContentsMargins(QMargins{});
auto margins = this->contentsMargins();
margins.setLeft(0);
this->setContentsMargins(margins);
this->setLayout(layout);
}
StackedContainer::~StackedContainer() {
}
QString StackedContainer::containerType() const {
return "StackedContainer";
}
} // namespace Quartz
| 31.075581 | 80 | 0.575304 | varunamachi |
4fe1d403e823872161e865c37354ed666537d721 | 702 | cpp | C++ | test/unit-tests/compiler/compiler_test.cpp | twantonie/centurion | 198b80f9e8a29da2ae7d3c15e48ffa1a046165c3 | [
"MIT"
] | 126 | 2020-12-05T00:05:56.000Z | 2022-03-30T15:15:03.000Z | test/unit-tests/compiler/compiler_test.cpp | twantonie/centurion | 198b80f9e8a29da2ae7d3c15e48ffa1a046165c3 | [
"MIT"
] | 46 | 2020-12-27T14:25:22.000Z | 2022-01-26T13:58:11.000Z | test/unit-tests/compiler/compiler_test.cpp | twantonie/centurion | 198b80f9e8a29da2ae7d3c15e48ffa1a046165c3 | [
"MIT"
] | 13 | 2021-01-20T20:50:18.000Z | 2022-03-25T06:59:03.000Z | #include "compiler/compiler.hpp"
#include <gtest/gtest.h>
TEST(Compiler, IsDebugBuild)
{
#ifdef NDEBUG
ASSERT_FALSE(cen::is_debug_build());
#else
ASSERT_TRUE(cen::is_debug_build());
#endif
}
TEST(Compiler, IsReleaseBuild)
{
#ifdef NDEBUG
ASSERT_TRUE(cen::is_release_build());
#else
ASSERT_FALSE(cen::is_release_build());
#endif
}
TEST(Compiler, OnMSVC)
{
#ifdef _MSC_VER
ASSERT_TRUE(cen::on_msvc());
#else
ASSERT_FALSE(cen::on_msvc());
#endif
}
TEST(Compiler, OnClang)
{
#ifdef __clang__
ASSERT_TRUE(cen::on_clang());
#else
ASSERT_FALSE(cen::on_clang());
#endif
}
TEST(Compiler, OnGCC)
{
#ifdef __GNUC__
ASSERT_TRUE(cen::on_gcc());
#else
ASSERT_FALSE(cen::on_gcc());
#endif
}
| 14.326531 | 40 | 0.7151 | twantonie |