hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
9bbe12f5b7d24e930ec1ff5cee3a1c846859aa44
56,875
cpp
C++
pywinrt/winsdk/src/py.Windows.Networking.Proximity.cpp
pywinrt/python-winsdk
1e2958a712949579f5e84d38220062b2cec12511
[ "MIT" ]
3
2022-02-14T14:53:08.000Z
2022-03-29T20:48:54.000Z
pywinrt/winsdk/src/py.Windows.Networking.Proximity.cpp
pywinrt/python-winsdk
1e2958a712949579f5e84d38220062b2cec12511
[ "MIT" ]
4
2022-01-28T02:53:52.000Z
2022-02-26T18:10:05.000Z
pywinrt/winsdk/src/py.Windows.Networking.Proximity.cpp
pywinrt/python-winsdk
1e2958a712949579f5e84d38220062b2cec12511
[ "MIT" ]
null
null
null
// WARNING: Please don't edit this file. It was generated by Python/WinRT v1.0.0-beta.4 #include "pybase.h" #include "py.Windows.Networking.Proximity.h" PyTypeObject* py::winrt_type<winrt::Windows::Networking::Proximity::ConnectionRequestedEventArgs>::python_type; PyTypeObject* py::winrt_type<winrt::Windows::Networking::Proximity::PeerFinder>::python_type; PyTypeObject* py::winrt_type<winrt::Windows::Networking::Proximity::PeerInformation>::python_type; PyTypeObject* py::winrt_type<winrt::Windows::Networking::Proximity::PeerWatcher>::python_type; PyTypeObject* py::winrt_type<winrt::Windows::Networking::Proximity::ProximityDevice>::python_type; PyTypeObject* py::winrt_type<winrt::Windows::Networking::Proximity::ProximityMessage>::python_type; PyTypeObject* py::winrt_type<winrt::Windows::Networking::Proximity::TriggeredConnectionStateChangedEventArgs>::python_type; namespace py::cpp::Windows::Networking::Proximity { // ----- ConnectionRequestedEventArgs class -------------------- constexpr const char* const _type_name_ConnectionRequestedEventArgs = "ConnectionRequestedEventArgs"; static PyObject* _new_ConnectionRequestedEventArgs(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { py::set_invalid_activation_error(_type_name_ConnectionRequestedEventArgs); return nullptr; } static void _dealloc_ConnectionRequestedEventArgs(py::wrapper::Windows::Networking::Proximity::ConnectionRequestedEventArgs* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* ConnectionRequestedEventArgs_get_PeerInformation(py::wrapper::Windows::Networking::Proximity::ConnectionRequestedEventArgs* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.PeerInformation()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* _from_ConnectionRequestedEventArgs(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::Networking::Proximity::ConnectionRequestedEventArgs>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_ConnectionRequestedEventArgs[] = { { "_from", reinterpret_cast<PyCFunction>(_from_ConnectionRequestedEventArgs), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_ConnectionRequestedEventArgs[] = { { "peer_information", reinterpret_cast<getter>(ConnectionRequestedEventArgs_get_PeerInformation), nullptr, nullptr, nullptr }, { } }; static PyType_Slot _type_slots_ConnectionRequestedEventArgs[] = { { Py_tp_new, _new_ConnectionRequestedEventArgs }, { Py_tp_dealloc, _dealloc_ConnectionRequestedEventArgs }, { Py_tp_methods, _methods_ConnectionRequestedEventArgs }, { Py_tp_getset, _getset_ConnectionRequestedEventArgs }, { }, }; static PyType_Spec _type_spec_ConnectionRequestedEventArgs = { "_winsdk_Windows_Networking_Proximity.ConnectionRequestedEventArgs", sizeof(py::wrapper::Windows::Networking::Proximity::ConnectionRequestedEventArgs), 0, Py_TPFLAGS_DEFAULT, _type_slots_ConnectionRequestedEventArgs }; // ----- PeerFinder class -------------------- constexpr const char* const _type_name_PeerFinder = "PeerFinder"; static PyObject* _new_PeerFinder(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { py::set_invalid_activation_error(_type_name_PeerFinder); return nullptr; } static PyObject* PeerFinder_ConnectAsync(PyObject* /*unused*/, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 1) { try { auto param0 = py::convert_to<winrt::Windows::Networking::Proximity::PeerInformation>(args, 0); return py::convert(winrt::Windows::Networking::Proximity::PeerFinder::ConnectAsync(param0)); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* PeerFinder_CreateWatcher(PyObject* /*unused*/, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { return py::convert(winrt::Windows::Networking::Proximity::PeerFinder::CreateWatcher()); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* PeerFinder_FindAllPeersAsync(PyObject* /*unused*/, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { return py::convert(winrt::Windows::Networking::Proximity::PeerFinder::FindAllPeersAsync()); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* PeerFinder_Start(PyObject* /*unused*/, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { winrt::Windows::Networking::Proximity::PeerFinder::Start(); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } else if (arg_count == 1) { try { auto param0 = py::convert_to<winrt::hstring>(args, 0); winrt::Windows::Networking::Proximity::PeerFinder::Start(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* PeerFinder_Stop(PyObject* /*unused*/, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { winrt::Windows::Networking::Proximity::PeerFinder::Stop(); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* PeerFinder_get_DisplayName(PyObject* /*unused*/, void* /*unused*/) noexcept { try { return py::convert(winrt::Windows::Networking::Proximity::PeerFinder::DisplayName()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerFinder_put_DisplayName(PyObject* /*unused*/, PyObject* arg, void* /*unused*/) noexcept { try { auto param0 = py::convert_to<winrt::hstring>(arg); winrt::Windows::Networking::Proximity::PeerFinder::DisplayName(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerFinder_get_AllowWiFiDirect(PyObject* /*unused*/, void* /*unused*/) noexcept { try { return py::convert(winrt::Windows::Networking::Proximity::PeerFinder::AllowWiFiDirect()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerFinder_put_AllowWiFiDirect(PyObject* /*unused*/, PyObject* arg, void* /*unused*/) noexcept { try { auto param0 = py::convert_to<bool>(arg); winrt::Windows::Networking::Proximity::PeerFinder::AllowWiFiDirect(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerFinder_get_AllowInfrastructure(PyObject* /*unused*/, void* /*unused*/) noexcept { try { return py::convert(winrt::Windows::Networking::Proximity::PeerFinder::AllowInfrastructure()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerFinder_put_AllowInfrastructure(PyObject* /*unused*/, PyObject* arg, void* /*unused*/) noexcept { try { auto param0 = py::convert_to<bool>(arg); winrt::Windows::Networking::Proximity::PeerFinder::AllowInfrastructure(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerFinder_get_AllowBluetooth(PyObject* /*unused*/, void* /*unused*/) noexcept { try { return py::convert(winrt::Windows::Networking::Proximity::PeerFinder::AllowBluetooth()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerFinder_put_AllowBluetooth(PyObject* /*unused*/, PyObject* arg, void* /*unused*/) noexcept { try { auto param0 = py::convert_to<bool>(arg); winrt::Windows::Networking::Proximity::PeerFinder::AllowBluetooth(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerFinder_get_AlternateIdentities(PyObject* /*unused*/, void* /*unused*/) noexcept { try { return py::convert(winrt::Windows::Networking::Proximity::PeerFinder::AlternateIdentities()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerFinder_get_SupportedDiscoveryTypes(PyObject* /*unused*/, void* /*unused*/) noexcept { try { return py::convert(winrt::Windows::Networking::Proximity::PeerFinder::SupportedDiscoveryTypes()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerFinder_get_Role(PyObject* /*unused*/, void* /*unused*/) noexcept { try { return py::convert(winrt::Windows::Networking::Proximity::PeerFinder::Role()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerFinder_put_Role(PyObject* /*unused*/, PyObject* arg, void* /*unused*/) noexcept { try { auto param0 = py::convert_to<winrt::Windows::Networking::Proximity::PeerRole>(arg); winrt::Windows::Networking::Proximity::PeerFinder::Role(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerFinder_get_DiscoveryData(PyObject* /*unused*/, void* /*unused*/) noexcept { try { return py::convert(winrt::Windows::Networking::Proximity::PeerFinder::DiscoveryData()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerFinder_put_DiscoveryData(PyObject* /*unused*/, PyObject* arg, void* /*unused*/) noexcept { try { auto param0 = py::convert_to<winrt::Windows::Storage::Streams::IBuffer>(arg); winrt::Windows::Networking::Proximity::PeerFinder::DiscoveryData(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerFinder_add_ConnectionRequested(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::Foundation::IInspectable, winrt::Windows::Networking::Proximity::ConnectionRequestedEventArgs>>(arg); return py::convert(winrt::Windows::Networking::Proximity::PeerFinder::ConnectionRequested(param0)); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerFinder_remove_ConnectionRequested(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::event_token>(arg); winrt::Windows::Networking::Proximity::PeerFinder::ConnectionRequested(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerFinder_add_TriggeredConnectionStateChanged(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::Foundation::IInspectable, winrt::Windows::Networking::Proximity::TriggeredConnectionStateChangedEventArgs>>(arg); return py::convert(winrt::Windows::Networking::Proximity::PeerFinder::TriggeredConnectionStateChanged(param0)); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerFinder_remove_TriggeredConnectionStateChanged(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::event_token>(arg); winrt::Windows::Networking::Proximity::PeerFinder::TriggeredConnectionStateChanged(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_PeerFinder[] = { { "connect_async", reinterpret_cast<PyCFunction>(PeerFinder_ConnectAsync), METH_VARARGS | METH_STATIC, nullptr }, { "create_watcher", reinterpret_cast<PyCFunction>(PeerFinder_CreateWatcher), METH_VARARGS | METH_STATIC, nullptr }, { "find_all_peers_async", reinterpret_cast<PyCFunction>(PeerFinder_FindAllPeersAsync), METH_VARARGS | METH_STATIC, nullptr }, { "start", reinterpret_cast<PyCFunction>(PeerFinder_Start), METH_VARARGS | METH_STATIC, nullptr }, { "stop", reinterpret_cast<PyCFunction>(PeerFinder_Stop), METH_VARARGS | METH_STATIC, nullptr }, { "get_display_name", reinterpret_cast<PyCFunction>(PeerFinder_get_DisplayName), METH_NOARGS | METH_STATIC, nullptr }, { "put_display_name", reinterpret_cast<PyCFunction>(PeerFinder_put_DisplayName), METH_O | METH_STATIC, nullptr }, { "get_allow_wi_fi_direct", reinterpret_cast<PyCFunction>(PeerFinder_get_AllowWiFiDirect), METH_NOARGS | METH_STATIC, nullptr }, { "put_allow_wi_fi_direct", reinterpret_cast<PyCFunction>(PeerFinder_put_AllowWiFiDirect), METH_O | METH_STATIC, nullptr }, { "get_allow_infrastructure", reinterpret_cast<PyCFunction>(PeerFinder_get_AllowInfrastructure), METH_NOARGS | METH_STATIC, nullptr }, { "put_allow_infrastructure", reinterpret_cast<PyCFunction>(PeerFinder_put_AllowInfrastructure), METH_O | METH_STATIC, nullptr }, { "get_allow_bluetooth", reinterpret_cast<PyCFunction>(PeerFinder_get_AllowBluetooth), METH_NOARGS | METH_STATIC, nullptr }, { "put_allow_bluetooth", reinterpret_cast<PyCFunction>(PeerFinder_put_AllowBluetooth), METH_O | METH_STATIC, nullptr }, { "get_alternate_identities", reinterpret_cast<PyCFunction>(PeerFinder_get_AlternateIdentities), METH_NOARGS | METH_STATIC, nullptr }, { "get_supported_discovery_types", reinterpret_cast<PyCFunction>(PeerFinder_get_SupportedDiscoveryTypes), METH_NOARGS | METH_STATIC, nullptr }, { "get_role", reinterpret_cast<PyCFunction>(PeerFinder_get_Role), METH_NOARGS | METH_STATIC, nullptr }, { "put_role", reinterpret_cast<PyCFunction>(PeerFinder_put_Role), METH_O | METH_STATIC, nullptr }, { "get_discovery_data", reinterpret_cast<PyCFunction>(PeerFinder_get_DiscoveryData), METH_NOARGS | METH_STATIC, nullptr }, { "put_discovery_data", reinterpret_cast<PyCFunction>(PeerFinder_put_DiscoveryData), METH_O | METH_STATIC, nullptr }, { "add_connection_requested", reinterpret_cast<PyCFunction>(PeerFinder_add_ConnectionRequested), METH_O | METH_STATIC, nullptr }, { "remove_connection_requested", reinterpret_cast<PyCFunction>(PeerFinder_remove_ConnectionRequested), METH_O | METH_STATIC, nullptr }, { "add_triggered_connection_state_changed", reinterpret_cast<PyCFunction>(PeerFinder_add_TriggeredConnectionStateChanged), METH_O | METH_STATIC, nullptr }, { "remove_triggered_connection_state_changed", reinterpret_cast<PyCFunction>(PeerFinder_remove_TriggeredConnectionStateChanged), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_PeerFinder[] = { { } }; static PyType_Slot _type_slots_PeerFinder[] = { { Py_tp_new, _new_PeerFinder }, { Py_tp_methods, _methods_PeerFinder }, { Py_tp_getset, _getset_PeerFinder }, { }, }; static PyType_Spec _type_spec_PeerFinder = { "_winsdk_Windows_Networking_Proximity.PeerFinder", 0, 0, Py_TPFLAGS_DEFAULT, _type_slots_PeerFinder }; // ----- PeerInformation class -------------------- constexpr const char* const _type_name_PeerInformation = "PeerInformation"; static PyObject* _new_PeerInformation(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { py::set_invalid_activation_error(_type_name_PeerInformation); return nullptr; } static void _dealloc_PeerInformation(py::wrapper::Windows::Networking::Proximity::PeerInformation* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* PeerInformation_get_DisplayName(py::wrapper::Windows::Networking::Proximity::PeerInformation* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.DisplayName()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerInformation_get_DiscoveryData(py::wrapper::Windows::Networking::Proximity::PeerInformation* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.DiscoveryData()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerInformation_get_Id(py::wrapper::Windows::Networking::Proximity::PeerInformation* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.Id()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerInformation_get_HostName(py::wrapper::Windows::Networking::Proximity::PeerInformation* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.HostName()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerInformation_get_ServiceName(py::wrapper::Windows::Networking::Proximity::PeerInformation* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.ServiceName()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* _from_PeerInformation(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::Networking::Proximity::PeerInformation>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_PeerInformation[] = { { "_from", reinterpret_cast<PyCFunction>(_from_PeerInformation), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_PeerInformation[] = { { "display_name", reinterpret_cast<getter>(PeerInformation_get_DisplayName), nullptr, nullptr, nullptr }, { "discovery_data", reinterpret_cast<getter>(PeerInformation_get_DiscoveryData), nullptr, nullptr, nullptr }, { "id", reinterpret_cast<getter>(PeerInformation_get_Id), nullptr, nullptr, nullptr }, { "host_name", reinterpret_cast<getter>(PeerInformation_get_HostName), nullptr, nullptr, nullptr }, { "service_name", reinterpret_cast<getter>(PeerInformation_get_ServiceName), nullptr, nullptr, nullptr }, { } }; static PyType_Slot _type_slots_PeerInformation[] = { { Py_tp_new, _new_PeerInformation }, { Py_tp_dealloc, _dealloc_PeerInformation }, { Py_tp_methods, _methods_PeerInformation }, { Py_tp_getset, _getset_PeerInformation }, { }, }; static PyType_Spec _type_spec_PeerInformation = { "_winsdk_Windows_Networking_Proximity.PeerInformation", sizeof(py::wrapper::Windows::Networking::Proximity::PeerInformation), 0, Py_TPFLAGS_DEFAULT, _type_slots_PeerInformation }; // ----- PeerWatcher class -------------------- constexpr const char* const _type_name_PeerWatcher = "PeerWatcher"; static PyObject* _new_PeerWatcher(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { py::set_invalid_activation_error(_type_name_PeerWatcher); return nullptr; } static void _dealloc_PeerWatcher(py::wrapper::Windows::Networking::Proximity::PeerWatcher* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* PeerWatcher_Start(py::wrapper::Windows::Networking::Proximity::PeerWatcher* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { self->obj.Start(); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* PeerWatcher_Stop(py::wrapper::Windows::Networking::Proximity::PeerWatcher* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { self->obj.Stop(); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* PeerWatcher_get_Status(py::wrapper::Windows::Networking::Proximity::PeerWatcher* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.Status()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerWatcher_add_Added(py::wrapper::Windows::Networking::Proximity::PeerWatcher* self, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::Networking::Proximity::PeerWatcher, winrt::Windows::Networking::Proximity::PeerInformation>>(arg); return py::convert(self->obj.Added(param0)); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerWatcher_remove_Added(py::wrapper::Windows::Networking::Proximity::PeerWatcher* self, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::event_token>(arg); self->obj.Added(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerWatcher_add_EnumerationCompleted(py::wrapper::Windows::Networking::Proximity::PeerWatcher* self, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::Networking::Proximity::PeerWatcher, winrt::Windows::Foundation::IInspectable>>(arg); return py::convert(self->obj.EnumerationCompleted(param0)); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerWatcher_remove_EnumerationCompleted(py::wrapper::Windows::Networking::Proximity::PeerWatcher* self, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::event_token>(arg); self->obj.EnumerationCompleted(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerWatcher_add_Removed(py::wrapper::Windows::Networking::Proximity::PeerWatcher* self, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::Networking::Proximity::PeerWatcher, winrt::Windows::Networking::Proximity::PeerInformation>>(arg); return py::convert(self->obj.Removed(param0)); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerWatcher_remove_Removed(py::wrapper::Windows::Networking::Proximity::PeerWatcher* self, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::event_token>(arg); self->obj.Removed(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerWatcher_add_Stopped(py::wrapper::Windows::Networking::Proximity::PeerWatcher* self, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::Networking::Proximity::PeerWatcher, winrt::Windows::Foundation::IInspectable>>(arg); return py::convert(self->obj.Stopped(param0)); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerWatcher_remove_Stopped(py::wrapper::Windows::Networking::Proximity::PeerWatcher* self, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::event_token>(arg); self->obj.Stopped(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerWatcher_add_Updated(py::wrapper::Windows::Networking::Proximity::PeerWatcher* self, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::Networking::Proximity::PeerWatcher, winrt::Windows::Networking::Proximity::PeerInformation>>(arg); return py::convert(self->obj.Updated(param0)); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* PeerWatcher_remove_Updated(py::wrapper::Windows::Networking::Proximity::PeerWatcher* self, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::event_token>(arg); self->obj.Updated(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* _from_PeerWatcher(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::Networking::Proximity::PeerWatcher>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_PeerWatcher[] = { { "start", reinterpret_cast<PyCFunction>(PeerWatcher_Start), METH_VARARGS, nullptr }, { "stop", reinterpret_cast<PyCFunction>(PeerWatcher_Stop), METH_VARARGS, nullptr }, { "add_added", reinterpret_cast<PyCFunction>(PeerWatcher_add_Added), METH_O, nullptr }, { "remove_added", reinterpret_cast<PyCFunction>(PeerWatcher_remove_Added), METH_O, nullptr }, { "add_enumeration_completed", reinterpret_cast<PyCFunction>(PeerWatcher_add_EnumerationCompleted), METH_O, nullptr }, { "remove_enumeration_completed", reinterpret_cast<PyCFunction>(PeerWatcher_remove_EnumerationCompleted), METH_O, nullptr }, { "add_removed", reinterpret_cast<PyCFunction>(PeerWatcher_add_Removed), METH_O, nullptr }, { "remove_removed", reinterpret_cast<PyCFunction>(PeerWatcher_remove_Removed), METH_O, nullptr }, { "add_stopped", reinterpret_cast<PyCFunction>(PeerWatcher_add_Stopped), METH_O, nullptr }, { "remove_stopped", reinterpret_cast<PyCFunction>(PeerWatcher_remove_Stopped), METH_O, nullptr }, { "add_updated", reinterpret_cast<PyCFunction>(PeerWatcher_add_Updated), METH_O, nullptr }, { "remove_updated", reinterpret_cast<PyCFunction>(PeerWatcher_remove_Updated), METH_O, nullptr }, { "_from", reinterpret_cast<PyCFunction>(_from_PeerWatcher), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_PeerWatcher[] = { { "status", reinterpret_cast<getter>(PeerWatcher_get_Status), nullptr, nullptr, nullptr }, { } }; static PyType_Slot _type_slots_PeerWatcher[] = { { Py_tp_new, _new_PeerWatcher }, { Py_tp_dealloc, _dealloc_PeerWatcher }, { Py_tp_methods, _methods_PeerWatcher }, { Py_tp_getset, _getset_PeerWatcher }, { }, }; static PyType_Spec _type_spec_PeerWatcher = { "_winsdk_Windows_Networking_Proximity.PeerWatcher", sizeof(py::wrapper::Windows::Networking::Proximity::PeerWatcher), 0, Py_TPFLAGS_DEFAULT, _type_slots_PeerWatcher }; // ----- ProximityDevice class -------------------- constexpr const char* const _type_name_ProximityDevice = "ProximityDevice"; static PyObject* _new_ProximityDevice(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { py::set_invalid_activation_error(_type_name_ProximityDevice); return nullptr; } static void _dealloc_ProximityDevice(py::wrapper::Windows::Networking::Proximity::ProximityDevice* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* ProximityDevice_FromId(PyObject* /*unused*/, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 1) { try { auto param0 = py::convert_to<winrt::hstring>(args, 0); return py::convert(winrt::Windows::Networking::Proximity::ProximityDevice::FromId(param0)); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* ProximityDevice_GetDefault(PyObject* /*unused*/, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { return py::convert(winrt::Windows::Networking::Proximity::ProximityDevice::GetDefault()); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* ProximityDevice_GetDeviceSelector(PyObject* /*unused*/, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 0) { try { return py::convert(winrt::Windows::Networking::Proximity::ProximityDevice::GetDeviceSelector()); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* ProximityDevice_PublishBinaryMessage(py::wrapper::Windows::Networking::Proximity::ProximityDevice* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 2) { try { auto param0 = py::convert_to<winrt::hstring>(args, 0); auto param1 = py::convert_to<winrt::Windows::Storage::Streams::IBuffer>(args, 1); return py::convert(self->obj.PublishBinaryMessage(param0, param1)); } catch (...) { py::to_PyErr(); return nullptr; } } else if (arg_count == 3) { try { auto param0 = py::convert_to<winrt::hstring>(args, 0); auto param1 = py::convert_to<winrt::Windows::Storage::Streams::IBuffer>(args, 1); auto param2 = py::convert_to<winrt::Windows::Networking::Proximity::MessageTransmittedHandler>(args, 2); return py::convert(self->obj.PublishBinaryMessage(param0, param1, param2)); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* ProximityDevice_PublishMessage(py::wrapper::Windows::Networking::Proximity::ProximityDevice* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 2) { try { auto param0 = py::convert_to<winrt::hstring>(args, 0); auto param1 = py::convert_to<winrt::hstring>(args, 1); return py::convert(self->obj.PublishMessage(param0, param1)); } catch (...) { py::to_PyErr(); return nullptr; } } else if (arg_count == 3) { try { auto param0 = py::convert_to<winrt::hstring>(args, 0); auto param1 = py::convert_to<winrt::hstring>(args, 1); auto param2 = py::convert_to<winrt::Windows::Networking::Proximity::MessageTransmittedHandler>(args, 2); return py::convert(self->obj.PublishMessage(param0, param1, param2)); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* ProximityDevice_PublishUriMessage(py::wrapper::Windows::Networking::Proximity::ProximityDevice* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 1) { try { auto param0 = py::convert_to<winrt::Windows::Foundation::Uri>(args, 0); return py::convert(self->obj.PublishUriMessage(param0)); } catch (...) { py::to_PyErr(); return nullptr; } } else if (arg_count == 2) { try { auto param0 = py::convert_to<winrt::Windows::Foundation::Uri>(args, 0); auto param1 = py::convert_to<winrt::Windows::Networking::Proximity::MessageTransmittedHandler>(args, 1); return py::convert(self->obj.PublishUriMessage(param0, param1)); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* ProximityDevice_StopPublishingMessage(py::wrapper::Windows::Networking::Proximity::ProximityDevice* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 1) { try { auto param0 = py::convert_to<int64_t>(args, 0); self->obj.StopPublishingMessage(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* ProximityDevice_StopSubscribingForMessage(py::wrapper::Windows::Networking::Proximity::ProximityDevice* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 1) { try { auto param0 = py::convert_to<int64_t>(args, 0); self->obj.StopSubscribingForMessage(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* ProximityDevice_SubscribeForMessage(py::wrapper::Windows::Networking::Proximity::ProximityDevice* self, PyObject* args) noexcept { Py_ssize_t arg_count = PyTuple_Size(args); if (arg_count == 2) { try { auto param0 = py::convert_to<winrt::hstring>(args, 0); auto param1 = py::convert_to<winrt::Windows::Networking::Proximity::MessageReceivedHandler>(args, 1); return py::convert(self->obj.SubscribeForMessage(param0, param1)); } catch (...) { py::to_PyErr(); return nullptr; } } else { py::set_invalid_arg_count_error(arg_count); return nullptr; } } static PyObject* ProximityDevice_get_BitsPerSecond(py::wrapper::Windows::Networking::Proximity::ProximityDevice* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.BitsPerSecond()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* ProximityDevice_get_DeviceId(py::wrapper::Windows::Networking::Proximity::ProximityDevice* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.DeviceId()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* ProximityDevice_get_MaxMessageBytes(py::wrapper::Windows::Networking::Proximity::ProximityDevice* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.MaxMessageBytes()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* ProximityDevice_add_DeviceArrived(py::wrapper::Windows::Networking::Proximity::ProximityDevice* self, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::Windows::Networking::Proximity::DeviceArrivedEventHandler>(arg); return py::convert(self->obj.DeviceArrived(param0)); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* ProximityDevice_remove_DeviceArrived(py::wrapper::Windows::Networking::Proximity::ProximityDevice* self, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::event_token>(arg); self->obj.DeviceArrived(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* ProximityDevice_add_DeviceDeparted(py::wrapper::Windows::Networking::Proximity::ProximityDevice* self, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::Windows::Networking::Proximity::DeviceDepartedEventHandler>(arg); return py::convert(self->obj.DeviceDeparted(param0)); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* ProximityDevice_remove_DeviceDeparted(py::wrapper::Windows::Networking::Proximity::ProximityDevice* self, PyObject* arg) noexcept { try { auto param0 = py::convert_to<winrt::event_token>(arg); self->obj.DeviceDeparted(param0); Py_RETURN_NONE; } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* _from_ProximityDevice(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::Networking::Proximity::ProximityDevice>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_ProximityDevice[] = { { "from_id", reinterpret_cast<PyCFunction>(ProximityDevice_FromId), METH_VARARGS | METH_STATIC, nullptr }, { "get_default", reinterpret_cast<PyCFunction>(ProximityDevice_GetDefault), METH_VARARGS | METH_STATIC, nullptr }, { "get_device_selector", reinterpret_cast<PyCFunction>(ProximityDevice_GetDeviceSelector), METH_VARARGS | METH_STATIC, nullptr }, { "publish_binary_message", reinterpret_cast<PyCFunction>(ProximityDevice_PublishBinaryMessage), METH_VARARGS, nullptr }, { "publish_message", reinterpret_cast<PyCFunction>(ProximityDevice_PublishMessage), METH_VARARGS, nullptr }, { "publish_uri_message", reinterpret_cast<PyCFunction>(ProximityDevice_PublishUriMessage), METH_VARARGS, nullptr }, { "stop_publishing_message", reinterpret_cast<PyCFunction>(ProximityDevice_StopPublishingMessage), METH_VARARGS, nullptr }, { "stop_subscribing_for_message", reinterpret_cast<PyCFunction>(ProximityDevice_StopSubscribingForMessage), METH_VARARGS, nullptr }, { "subscribe_for_message", reinterpret_cast<PyCFunction>(ProximityDevice_SubscribeForMessage), METH_VARARGS, nullptr }, { "add_device_arrived", reinterpret_cast<PyCFunction>(ProximityDevice_add_DeviceArrived), METH_O, nullptr }, { "remove_device_arrived", reinterpret_cast<PyCFunction>(ProximityDevice_remove_DeviceArrived), METH_O, nullptr }, { "add_device_departed", reinterpret_cast<PyCFunction>(ProximityDevice_add_DeviceDeparted), METH_O, nullptr }, { "remove_device_departed", reinterpret_cast<PyCFunction>(ProximityDevice_remove_DeviceDeparted), METH_O, nullptr }, { "_from", reinterpret_cast<PyCFunction>(_from_ProximityDevice), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_ProximityDevice[] = { { "bits_per_second", reinterpret_cast<getter>(ProximityDevice_get_BitsPerSecond), nullptr, nullptr, nullptr }, { "device_id", reinterpret_cast<getter>(ProximityDevice_get_DeviceId), nullptr, nullptr, nullptr }, { "max_message_bytes", reinterpret_cast<getter>(ProximityDevice_get_MaxMessageBytes), nullptr, nullptr, nullptr }, { } }; static PyType_Slot _type_slots_ProximityDevice[] = { { Py_tp_new, _new_ProximityDevice }, { Py_tp_dealloc, _dealloc_ProximityDevice }, { Py_tp_methods, _methods_ProximityDevice }, { Py_tp_getset, _getset_ProximityDevice }, { }, }; static PyType_Spec _type_spec_ProximityDevice = { "_winsdk_Windows_Networking_Proximity.ProximityDevice", sizeof(py::wrapper::Windows::Networking::Proximity::ProximityDevice), 0, Py_TPFLAGS_DEFAULT, _type_slots_ProximityDevice }; // ----- ProximityMessage class -------------------- constexpr const char* const _type_name_ProximityMessage = "ProximityMessage"; static PyObject* _new_ProximityMessage(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { py::set_invalid_activation_error(_type_name_ProximityMessage); return nullptr; } static void _dealloc_ProximityMessage(py::wrapper::Windows::Networking::Proximity::ProximityMessage* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* ProximityMessage_get_Data(py::wrapper::Windows::Networking::Proximity::ProximityMessage* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.Data()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* ProximityMessage_get_DataAsString(py::wrapper::Windows::Networking::Proximity::ProximityMessage* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.DataAsString()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* ProximityMessage_get_MessageType(py::wrapper::Windows::Networking::Proximity::ProximityMessage* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.MessageType()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* ProximityMessage_get_SubscriptionId(py::wrapper::Windows::Networking::Proximity::ProximityMessage* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.SubscriptionId()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* _from_ProximityMessage(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::Networking::Proximity::ProximityMessage>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_ProximityMessage[] = { { "_from", reinterpret_cast<PyCFunction>(_from_ProximityMessage), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_ProximityMessage[] = { { "data", reinterpret_cast<getter>(ProximityMessage_get_Data), nullptr, nullptr, nullptr }, { "data_as_string", reinterpret_cast<getter>(ProximityMessage_get_DataAsString), nullptr, nullptr, nullptr }, { "message_type", reinterpret_cast<getter>(ProximityMessage_get_MessageType), nullptr, nullptr, nullptr }, { "subscription_id", reinterpret_cast<getter>(ProximityMessage_get_SubscriptionId), nullptr, nullptr, nullptr }, { } }; static PyType_Slot _type_slots_ProximityMessage[] = { { Py_tp_new, _new_ProximityMessage }, { Py_tp_dealloc, _dealloc_ProximityMessage }, { Py_tp_methods, _methods_ProximityMessage }, { Py_tp_getset, _getset_ProximityMessage }, { }, }; static PyType_Spec _type_spec_ProximityMessage = { "_winsdk_Windows_Networking_Proximity.ProximityMessage", sizeof(py::wrapper::Windows::Networking::Proximity::ProximityMessage), 0, Py_TPFLAGS_DEFAULT, _type_slots_ProximityMessage }; // ----- TriggeredConnectionStateChangedEventArgs class -------------------- constexpr const char* const _type_name_TriggeredConnectionStateChangedEventArgs = "TriggeredConnectionStateChangedEventArgs"; static PyObject* _new_TriggeredConnectionStateChangedEventArgs(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { py::set_invalid_activation_error(_type_name_TriggeredConnectionStateChangedEventArgs); return nullptr; } static void _dealloc_TriggeredConnectionStateChangedEventArgs(py::wrapper::Windows::Networking::Proximity::TriggeredConnectionStateChangedEventArgs* self) { auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj); py::wrapped_instance(hash_value, nullptr); self->obj = nullptr; } static PyObject* TriggeredConnectionStateChangedEventArgs_get_Id(py::wrapper::Windows::Networking::Proximity::TriggeredConnectionStateChangedEventArgs* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.Id()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* TriggeredConnectionStateChangedEventArgs_get_Socket(py::wrapper::Windows::Networking::Proximity::TriggeredConnectionStateChangedEventArgs* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.Socket()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* TriggeredConnectionStateChangedEventArgs_get_State(py::wrapper::Windows::Networking::Proximity::TriggeredConnectionStateChangedEventArgs* self, void* /*unused*/) noexcept { try { return py::convert(self->obj.State()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyObject* _from_TriggeredConnectionStateChangedEventArgs(PyObject* /*unused*/, PyObject* arg) noexcept { try { auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg); return py::convert(return_value.as<winrt::Windows::Networking::Proximity::TriggeredConnectionStateChangedEventArgs>()); } catch (...) { py::to_PyErr(); return nullptr; } } static PyMethodDef _methods_TriggeredConnectionStateChangedEventArgs[] = { { "_from", reinterpret_cast<PyCFunction>(_from_TriggeredConnectionStateChangedEventArgs), METH_O | METH_STATIC, nullptr }, { } }; static PyGetSetDef _getset_TriggeredConnectionStateChangedEventArgs[] = { { "id", reinterpret_cast<getter>(TriggeredConnectionStateChangedEventArgs_get_Id), nullptr, nullptr, nullptr }, { "socket", reinterpret_cast<getter>(TriggeredConnectionStateChangedEventArgs_get_Socket), nullptr, nullptr, nullptr }, { "state", reinterpret_cast<getter>(TriggeredConnectionStateChangedEventArgs_get_State), nullptr, nullptr, nullptr }, { } }; static PyType_Slot _type_slots_TriggeredConnectionStateChangedEventArgs[] = { { Py_tp_new, _new_TriggeredConnectionStateChangedEventArgs }, { Py_tp_dealloc, _dealloc_TriggeredConnectionStateChangedEventArgs }, { Py_tp_methods, _methods_TriggeredConnectionStateChangedEventArgs }, { Py_tp_getset, _getset_TriggeredConnectionStateChangedEventArgs }, { }, }; static PyType_Spec _type_spec_TriggeredConnectionStateChangedEventArgs = { "_winsdk_Windows_Networking_Proximity.TriggeredConnectionStateChangedEventArgs", sizeof(py::wrapper::Windows::Networking::Proximity::TriggeredConnectionStateChangedEventArgs), 0, Py_TPFLAGS_DEFAULT, _type_slots_TriggeredConnectionStateChangedEventArgs }; // ----- Windows.Networking.Proximity Initialization -------------------- static int module_exec(PyObject* module) noexcept { try { py::pyobj_handle bases { PyTuple_Pack(1, py::winrt_type<py::Object>::python_type) }; py::winrt_type<winrt::Windows::Networking::Proximity::ConnectionRequestedEventArgs>::python_type = py::register_python_type(module, _type_name_ConnectionRequestedEventArgs, &_type_spec_ConnectionRequestedEventArgs, bases.get()); py::winrt_type<winrt::Windows::Networking::Proximity::PeerFinder>::python_type = py::register_python_type(module, _type_name_PeerFinder, &_type_spec_PeerFinder, nullptr); py::winrt_type<winrt::Windows::Networking::Proximity::PeerInformation>::python_type = py::register_python_type(module, _type_name_PeerInformation, &_type_spec_PeerInformation, bases.get()); py::winrt_type<winrt::Windows::Networking::Proximity::PeerWatcher>::python_type = py::register_python_type(module, _type_name_PeerWatcher, &_type_spec_PeerWatcher, bases.get()); py::winrt_type<winrt::Windows::Networking::Proximity::ProximityDevice>::python_type = py::register_python_type(module, _type_name_ProximityDevice, &_type_spec_ProximityDevice, bases.get()); py::winrt_type<winrt::Windows::Networking::Proximity::ProximityMessage>::python_type = py::register_python_type(module, _type_name_ProximityMessage, &_type_spec_ProximityMessage, bases.get()); py::winrt_type<winrt::Windows::Networking::Proximity::TriggeredConnectionStateChangedEventArgs>::python_type = py::register_python_type(module, _type_name_TriggeredConnectionStateChangedEventArgs, &_type_spec_TriggeredConnectionStateChangedEventArgs, bases.get()); return 0; } catch (...) { py::to_PyErr(); return -1; } } static PyModuleDef_Slot module_slots[] = {{Py_mod_exec, module_exec}, {}}; PyDoc_STRVAR(module_doc, "Windows.Networking.Proximity"); static PyModuleDef module_def = {PyModuleDef_HEAD_INIT, "_winsdk_Windows_Networking_Proximity", module_doc, 0, nullptr, module_slots, nullptr, nullptr, nullptr}; } // py::cpp::Windows::Networking::Proximity PyMODINIT_FUNC PyInit__winsdk_Windows_Networking_Proximity (void) noexcept { return PyModuleDef_Init(&py::cpp::Windows::Networking::Proximity::module_def); }
34.32408
276
0.599648
pywinrt
9bbf252752ae1ef4d98f83d5c6ede747e24e2b01
164
cpp
C++
code/random-stuff/dzien-probny/test.cpp
tonowak/acmlib
ec295b8c76c588914475ad42cff81a64a6f2ebd5
[ "MIT" ]
6
2019-06-25T14:07:08.000Z
2022-01-04T12:28:55.000Z
code/random-stuff/dzien-probny/test.cpp
tonowak/acmlib
ec295b8c76c588914475ad42cff81a64a6f2ebd5
[ "MIT" ]
null
null
null
code/random-stuff/dzien-probny/test.cpp
tonowak/acmlib
ec295b8c76c588914475ad42cff81a64a6f2ebd5
[ "MIT" ]
1
2021-11-12T01:40:38.000Z
2021-11-12T01:40:38.000Z
#include "../../utils/testing/test-wrapper.cpp" #include "main.cpp" void test() { test_int128(); //test_float128(); test_clock(); test_rd(); test_policy(); }
14.909091
47
0.652439
tonowak
9bc25f05c0413407d9bdc1438266b84d865d8b20
3,588
cpp
C++
tests/src/surface.cpp
viennagrid/viennagrid-dev
6e47c8d098a0b691d6b9988f2444cd11d440f4c2
[ "MIT" ]
7
2015-09-13T03:50:58.000Z
2019-06-27T14:24:49.000Z
tests/src/surface.cpp
viennagrid/viennagrid-dev
6e47c8d098a0b691d6b9988f2444cd11d440f4c2
[ "MIT" ]
null
null
null
tests/src/surface.cpp
viennagrid/viennagrid-dev
6e47c8d098a0b691d6b9988f2444cd11d440f4c2
[ "MIT" ]
5
2015-07-03T07:14:15.000Z
2021-05-20T00:51:58.000Z
/* ======================================================================= Copyright (c) 2011-2014, Institute for Microelectronics, Institute for Analysis and Scientific Computing, TU Wien. ----------------- ViennaGrid - The Vienna Grid Library ----------------- License: MIT (X11), see file LICENSE in the base directory ======================================================================= */ #ifdef _MSC_VER #pragma warning( disable : 4503 ) //truncated name decoration #endif #include "viennagrid/algorithm/boundary.hpp" #include "viennagrid/algorithm/centroid.hpp" #include "viennagrid/config/default_configs.hpp" #include "viennagrid/io/vtk_reader.hpp" #include "viennagrid/io/vtk_writer.hpp" #include "viennagrid/io/opendx_writer.hpp" #include "viennagrid/io/netgen_reader.hpp" #include "viennagrid/algorithm/volume.hpp" #include "viennagrid/algorithm/surface.hpp" template <typename MeshType, typename ReaderType> void test(ReaderType & my_reader, std::string const & infile) { typedef typename viennagrid::result_of::segmentation<MeshType>::type SegmentationType; typedef typename viennagrid::result_of::cell_range<MeshType>::type CellRange; typedef typename viennagrid::result_of::iterator<CellRange>::type CellIterator; MeshType mesh; SegmentationType segmentation(mesh); try { my_reader(mesh, segmentation, infile); } catch (std::exception const & ex) { std::cerr << ex.what() << std::endl; std::cerr << "File-Reader failed. Aborting program..." << std::endl; exit(EXIT_FAILURE); } std::cout << "Volume of mesh: " << viennagrid::volume(mesh) << std::endl; std::cout << "Surface of mesh: " << viennagrid::surface(mesh) << std::endl; CellRange cells(mesh); for (CellIterator cit = cells.begin(); cit != cells.end(); ++cit) { //std::cout << *cit << std::endl; std::cout << "Surface: " << viennagrid::surface(*cit) << std::endl; } } int main() { // typedef viennagrid::result_of::mesh<viennagrid::config::quadrilateral_2d>::type Mesh2d; // typedef viennagrid::result_of::mesh<viennagrid::config::hexahedral_3d>::type Mesh3d; std::cout << "*****************" << std::endl; std::cout << "* Test started! *" << std::endl; std::cout << "*****************" << std::endl; std::string path = "../examples/data/"; viennagrid::io::netgen_reader my_netgen_reader; std::cout << "*********** triangular, 2d ***********" << std::endl; test<viennagrid::triangular_2d_mesh>(my_netgen_reader, path + "square32.mesh"); std::cout << "*********** tetrahedral, 3d ***********" << std::endl; test<viennagrid::tetrahedral_3d_mesh>(my_netgen_reader, path + "cube48.mesh"); std::cout << "*********** quadrilateral, 2d ***********" << std::endl; viennagrid::io::vtk_reader<viennagrid::quadrilateral_2d_mesh> vtk_reader_2d; test<viennagrid::quadrilateral_2d_mesh>(vtk_reader_2d, path + "quadrilateral2.vtu"); std::cout << "*********** hexahedral, 3d ***********" << std::endl; viennagrid::io::vtk_reader<viennagrid::hexahedral_3d_mesh> vtk_reader_3d; test<viennagrid::hexahedral_3d_mesh >(vtk_reader_3d, path + "hexahedron2.vtu"); std::cout << "*******************************" << std::endl; std::cout << "* Test finished successfully! *" << std::endl; std::cout << "*******************************" << std::endl; return EXIT_SUCCESS; }
35.88
99
0.582776
viennagrid
9bc3c5920ea11806285b41d2f75adb8e9ce10742
2,367
cpp
C++
Kattis/theescape.cpp
hardik0899/Competitive_Programming
199039ad7a26a5f48152fe231a9ca5ac8685a707
[ "MIT" ]
1
2020-10-16T18:14:30.000Z
2020-10-16T18:14:30.000Z
Kattis/theescape.cpp
hardik0899/Competitive_Programming
199039ad7a26a5f48152fe231a9ca5ac8685a707
[ "MIT" ]
null
null
null
Kattis/theescape.cpp
hardik0899/Competitive_Programming
199039ad7a26a5f48152fe231a9ca5ac8685a707
[ "MIT" ]
1
2021-01-06T04:45:38.000Z
2021-01-06T04:45:38.000Z
#define __USE_MINGW_ANSI_STDIO 0 #include <iostream> #include <iomanip> #include <stdio.h> #include <stdlib.h> #include <vector> #include <algorithm> #include <queue> #include <map> #include <unordered_map> #include <set> #include <unordered_set> #include <stack> #include <deque> #include <string.h> #include <sstream> #include <math.h> using namespace std; #define PI atan2(0, -1) #define epsilon 0.000000001 #define INF 5000000000000000000 #define MOD 1000000007 int N, M, root = 0, dp1 [200010], dp2 [200010], dp3 [200010]; // 1: wolves to remove so everyone escapes to a leaf (considering only the subtree rooted at curr) // 2: wolves to remove so everyone escapes to a leaf OR can reach de-wolfed curr // 3: wolves to remove so everyone escapes to a leaf AND curr can get to a leaf vector<int> adjacency [200010]; bool isPig [200010]; void extendIt(int u, int v){ if(isPig[u]){ dp1[u] = dp3[v]; dp2[u] = min(dp1[v], dp2[v]); dp3[u] = dp3[v]; } else{ dp1[u] = dp1[v]; dp2[u] = min(dp1[v], dp2[v])+1; dp3[u] = dp3[v]+1; } } void chainIt(int u, int v){ int ndp1 = dp1[u]+dp1[v]; ndp1 = min(ndp1, min(dp2[u]+dp3[v], dp2[v]+dp3[u])); int ndp2 = dp2[u]+min(dp1[v], dp2[v]); int ndp3 = min(dp3[u]+min(dp1[v], dp2[v]), dp2[u]+dp3[v]); dp1[u] = ndp1; dp2[u] = ndp2; dp3[u] = ndp3; } void solveIt(int curr, int prevy){ if(adjacency[curr].size() == 1){ dp1[curr] = 0; dp2[curr] = dp3[curr] = isPig[curr] ? 0 : 1; return; } bool firsty = true; for(int nexty : adjacency[curr]){ if(nexty == prevy) continue; solveIt(nexty, curr); if(firsty){ extendIt(curr, nexty); firsty = false; } else chainIt(curr, nexty); } } int main(){ //freopen("disrupt.in", "r", stdin); freopen("disrupt.out", "w", stdout); ios_base::sync_with_stdio(0); cin.tie(0); cout << fixed << setprecision(18); cin >> N >> M; memset(isPig, false, sizeof(isPig)); for(int i = 1; i < N; i++){ int a, b; cin >> a >> b; adjacency[a].push_back(b); adjacency[b].push_back(a); } for(int i = 0; i < M; i++){ int x; cin >> x; isPig[x] = true; } while(adjacency[root].size() == 1) root++; solveIt(root, -1); cout << dp1[root] << '\n'; return 0; }
26.897727
98
0.576679
hardik0899
9bc3e6c92eed8fa76798113d5011aec3ae42656b
277
hpp
C++
includes/itr/Request.hpp
juliendoutre/itr
ea555c8f0f4a6b02e5545911bdd48a3b1fb51a97
[ "MIT" ]
null
null
null
includes/itr/Request.hpp
juliendoutre/itr
ea555c8f0f4a6b02e5545911bdd48a3b1fb51a97
[ "MIT" ]
null
null
null
includes/itr/Request.hpp
juliendoutre/itr
ea555c8f0f4a6b02e5545911bdd48a3b1fb51a97
[ "MIT" ]
null
null
null
#ifndef Request_hpp_INCLUDED #define Request_hpp_INCLUDED #include "Semaphore.hpp" class Request { protected: Semaphore returnSema; public: virtual void execute() = 0; virtual bool shouldTerminate() = 0; void waitReturn(); virtual ~Request(); }; #endif
14.578947
39
0.707581
juliendoutre
9bd03d4ce5f613dcc6661652d7163cb0506fc854
1,699
cpp
C++
third_party/gfootball_engine/src/managers/resourcemanagerpool.cpp
mahi97/football
18d51cb110034ce7080b2ccce14a2539d2a04af3
[ "Apache-2.0" ]
3
2019-06-20T05:47:02.000Z
2019-08-25T05:04:11.000Z
third_party/gfootball_engine/src/managers/resourcemanagerpool.cpp
AzharMithani/football
0f09bcb8b3d48ac31987e13739e21a58ef0ca405
[ "Apache-2.0" ]
1
2019-06-09T10:06:36.000Z
2019-06-09T10:06:36.000Z
third_party/gfootball_engine/src/managers/resourcemanagerpool.cpp
nczempin/gfootball
617e9cb6d48b4ac7187b9b3de68bd4ab44ea528e
[ "Apache-2.0" ]
1
2019-06-09T12:42:28.000Z
2019-06-09T12:42:28.000Z
// Copyright 2019 Google LLC & Bastiaan Konings // 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. // written by bastiaan konings schuiling 2008 - 2014 // this work is public domain. the code is undocumented, scruffy, untested, and should generally not be used for anything important. // i do not offer support, so don't ask. to be used for inspiration :) #include "resourcemanagerpool.hpp" namespace blunted { ResourceManager<GeometryData> geometryManager(""); ResourceManager<Surface> surfaceManager(""); ResourceManager<Texture> textureManager(""); ResourceManager<VertexBuffer> verticesManager(""); void ResourceManagerPool::CleanUp() { geometryManager.RemoveUnused(); surfaceManager.RemoveUnused(); textureManager.RemoveUnused(); verticesManager.RemoveUnused(); } ResourceManager<GeometryData>* ResourceManagerPool::getGeometryManager() { return &geometryManager; } ResourceManager<Surface>* ResourceManagerPool::getSurfaceManager() { return &surfaceManager; } ResourceManager<Texture>* ResourceManagerPool::getTextureManager() { return &textureManager; } ResourceManager<VertexBuffer>* ResourceManagerPool::getVerticesManager() { return &verticesManager; } }
33.98
132
0.77163
mahi97
9bdb165c1d171092d34ee9a908cc6b774b72c0c9
719
cpp
C++
probes/K10/src/test.cpp
mikrosimage/OpenDisplayCalib
a8cc37aa72d378faedc4a44171bcb29a20394432
[ "BSD-3-Clause" ]
16
2015-02-25T22:35:54.000Z
2021-12-14T19:59:30.000Z
probes/K10/src/test.cpp
mikrosimage/OpenDisplayCalib
a8cc37aa72d378faedc4a44171bcb29a20394432
[ "BSD-3-Clause" ]
2
2015-04-02T13:43:01.000Z
2015-06-01T13:42:00.000Z
probes/K10/src/test.cpp
mikrosimage/OpenDisplayCalib
a8cc37aa72d378faedc4a44171bcb29a20394432
[ "BSD-3-Clause" ]
5
2016-03-02T16:08:49.000Z
2019-11-29T11:16:54.000Z
/* * test.cpp * * Created on: 27 avr. 2010 * Author: mfe */ #include <windows.h> #include <winbase.h> #include <stdio.h> #include <conio.h> #include <string.h> #include <cmath> #include "K10.h" #include <iostream> using namespace std; int main() { string port = K10::isConnected(); cout << "K-10 is connected on port " << port << endl; K10 probe(port); string serial = probe.init(); cout << "probe serial : " << serial << endl; float X = 0, Y = 0, Z = 0; probe.getXYZ(X, Y, Z); float sumXYZ = X + Y + Z; float x = X / sumXYZ; float y = Y / sumXYZ; printf("measure : %f %f %f\n", x, y, Y); printf("measure : %f %f %f\n", X, Y, Z); probe.release(); return 0; }
21.147059
55
0.561892
mikrosimage
9be06e8b76b50e1604601f64dddb331474142265
18,358
cpp
C++
src/mongo/db/query/optimizer/cascades/physical_rewriter.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/db/query/optimizer/cascades/physical_rewriter.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/db/query/optimizer/cascades/physical_rewriter.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2022-present MongoDB, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * 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 * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the Server Side Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #include "mongo/db/query/optimizer/cascades/physical_rewriter.h" #include "mongo/db/query/optimizer/cascades/enforcers.h" #include "mongo/db/query/optimizer/cascades/implementers.h" #include "mongo/db/query/optimizer/explain.h" #include "mongo/db/query/optimizer/utils/memo_utils.h" namespace mongo::optimizer::cascades { using namespace properties; /** * Helper class used to check if two physical property sets are compatible by testing each * constituent property for compatibility. This is used to check if a winner's circle entry can be * reused. */ class PropCompatibleVisitor { public: bool operator()(const PhysProperty&, const CollationRequirement& requiredProp) { return collationsCompatible( getPropertyConst<CollationRequirement>(_availableProps).getCollationSpec(), requiredProp.getCollationSpec()); } bool operator()(const PhysProperty&, const LimitSkipRequirement& requiredProp) { const auto& available = getPropertyConst<LimitSkipRequirement>(_availableProps); return available.getSkip() >= requiredProp.getSkip() && available.getAbsoluteLimit() <= requiredProp.getAbsoluteLimit(); } bool operator()(const PhysProperty&, const ProjectionRequirement& requiredProp) { const auto& availableProjections = getPropertyConst<ProjectionRequirement>(_availableProps).getProjections(); // Do we have a projection superset (not necessarily strict superset)? for (const ProjectionName& projectionName : requiredProp.getProjections().getVector()) { if (!availableProjections.find(projectionName).second) { return false; } } return true; } bool operator()(const PhysProperty&, const IndexingRequirement& requiredProp) { const auto& available = getPropertyConst<IndexingRequirement>(_availableProps); return available.getIndexReqTarget() == requiredProp.getIndexReqTarget() && (available.getDedupRID() || !requiredProp.getDedupRID()) && available.getSatisfiedPartialIndexesGroupId() == requiredProp.getSatisfiedPartialIndexesGroupId(); } template <class T> bool operator()(const PhysProperty&, const T& requiredProp) { return getPropertyConst<T>(_availableProps) == requiredProp; } static bool propertiesCompatible(const PhysProps& requiredProps, const PhysProps& availableProps) { if (requiredProps.size() != availableProps.size()) { return false; } PropCompatibleVisitor visitor(availableProps); for (const auto& [key, prop] : requiredProps) { if (availableProps.find(key) == availableProps.cend() || !prop.visit(visitor)) { return false; } } return true; } private: PropCompatibleVisitor(const PhysProps& availableProp) : _availableProps(availableProp) {} // We don't own this. const PhysProps& _availableProps; }; PhysicalRewriter::PhysicalRewriter(Memo& memo, const QueryHints& hints, const RIDProjectionsMap& ridProjections, const CostingInterface& costDerivation, std::unique_ptr<LogicalRewriter>& logicalRewriter) : _memo(memo), _costDerivation(costDerivation), _hints(hints), _ridProjections(ridProjections), _logicalRewriter(logicalRewriter) {} static void printCandidateInfo(const ABT& node, const GroupIdType groupId, const CostType nodeCost, const ChildPropsType& childProps, const PhysOptimizationResult& bestResult) { std::cout << "group: " << groupId << ", id: " << bestResult._index << ", nodeCost: " << nodeCost.toString() << ", best cost: " << (bestResult._nodeInfo ? bestResult._nodeInfo->_cost : CostType::kInfinity).toString() << "\n"; std::cout << ExplainGenerator::explainPhysProps("Physical properties", bestResult._physProps) << "\n"; std::cout << "Node: \n" << ExplainGenerator::explainV2(node) << "\n"; for (const auto& childProp : childProps) { std::cout << ExplainGenerator::explainPhysProps("Child properties", childProp.second); } } void PhysicalRewriter::costAndRetainBestNode(ABT node, ChildPropsType childProps, NodeCEMap nodeCEMap, const GroupIdType groupId, PrefixId& prefixId, PhysOptimizationResult& bestResult) { const CostAndCE nodeCostAndCE = _costDerivation.deriveCost(_memo, bestResult._physProps, node.ref(), childProps, nodeCEMap); const CostType nodeCost = nodeCostAndCE._cost; uassert(6624056, "Must get non-infinity cost for physical node.", !nodeCost.isInfinite()); if (_memo.getDebugInfo().hasDebugLevel(3)) { std::cout << "Requesting optimization\n"; printCandidateInfo(node, groupId, nodeCost, childProps, bestResult); } const CostType childCostLimit = bestResult._nodeInfo ? bestResult._nodeInfo->_cost : bestResult._costLimit; const auto [success, cost] = optimizeChildren(nodeCost, childProps, prefixId, childCostLimit); const bool improvement = success && (!bestResult._nodeInfo || cost < bestResult._nodeInfo->_cost); if (_memo.getDebugInfo().hasDebugLevel(3)) { std::cout << (success ? (improvement ? "Improved" : "Did not improve") : "Failed optimizing") << "\n"; printCandidateInfo(node, groupId, nodeCost, childProps, bestResult); } PhysNodeInfo candidateNodeInfo{ unwrapConstFilter(std::move(node)), cost, nodeCost, nodeCostAndCE._ce}; const bool keepRejectedPlans = _hints._keepRejectedPlans; if (improvement) { if (keepRejectedPlans && bestResult._nodeInfo) { bestResult._rejectedNodeInfo.push_back(std::move(*bestResult._nodeInfo)); } bestResult._nodeInfo = std::move(candidateNodeInfo); } else if (keepRejectedPlans) { bestResult._rejectedNodeInfo.push_back(std::move(candidateNodeInfo)); } } /** * Convert nodes from logical to physical memo delegators. * Performs branch-and-bound search. */ std::pair<bool, CostType> PhysicalRewriter::optimizeChildren(const CostType nodeCost, ChildPropsType childProps, PrefixId& prefixId, const CostType costLimit) { const bool disableBranchAndBound = _hints._disableBranchAndBound; CostType totalCost = nodeCost; if (costLimit < totalCost && !disableBranchAndBound) { return {false, CostType::kInfinity}; } for (auto& [node, props] : childProps) { const GroupIdType groupId = node->cast<MemoLogicalDelegatorNode>()->getGroupId(); const CostType childCostLimit = disableBranchAndBound ? CostType::kInfinity : (costLimit - totalCost); auto optGroupResult = optimizeGroup(groupId, std::move(props), prefixId, childCostLimit); if (!optGroupResult._success) { return {false, CostType::kInfinity}; } totalCost += optGroupResult._cost; if (costLimit < totalCost && !disableBranchAndBound) { return {false, CostType::kInfinity}; } ABT optimizedChild = make<MemoPhysicalDelegatorNode>(MemoPhysicalNodeId{groupId, optGroupResult._index}); std::swap(*node, optimizedChild); } return {true, totalCost}; } PhysicalRewriter::OptimizeGroupResult::OptimizeGroupResult() : _success(false), _index(0), _cost(CostType::kInfinity) {} PhysicalRewriter::OptimizeGroupResult::OptimizeGroupResult(const size_t index, const CostType cost) : _success(true), _index(index), _cost(std::move(cost)) { uassert(6624347, "Cannot have successful optimization with infinite cost", _cost < CostType::kInfinity); } PhysicalRewriter::OptimizeGroupResult PhysicalRewriter::optimizeGroup(const GroupIdType groupId, PhysProps physProps, PrefixId& prefixId, CostType costLimit) { const size_t localPlanExplorationCount = ++_memo._stats._physPlanExplorationCount; if (_memo.getDebugInfo().hasDebugLevel(2)) { std::cout << "#" << localPlanExplorationCount << " Optimizing group " << groupId << ", cost limit: " << costLimit.toString() << "\n"; std::cout << ExplainGenerator::explainPhysProps("Physical properties", physProps) << "\n"; } Group& group = _memo.getGroup(groupId); const LogicalProps& logicalProps = group._logicalProperties; if (hasProperty<IndexingAvailability>(logicalProps) && !hasProperty<IndexingRequirement>(physProps)) { // Re-optimize under complete scan indexing requirements. setPropertyOverwrite( physProps, IndexingRequirement{IndexReqTarget::Complete, true /*dedupRID*/, groupId}); } auto& physicalNodes = group._physicalNodes; // Establish if we have found exact match of the physical properties in the winner's circle. const auto [exactPropsIndex, hasExactProps] = physicalNodes.find(physProps); // If true, we have found compatible (but not equal) props with cost under our cost limit. bool hasCompatibleProps = false; if (hasExactProps) { PhysOptimizationResult& physNode = physicalNodes.at(exactPropsIndex); if (!physNode.isOptimized()) { // Currently optimizing under the same properties higher up the stack (recursive loop). return {}; } // At this point we have an optimized entry. if (!physNode._nodeInfo) { if (physNode._costLimit < costLimit) { physNode.raiseCostLimit(costLimit); // Fall through and continue optimizing. } else { // Previously failed to optimize under less strict cost limit. return {}; } } else if (costLimit < physNode._nodeInfo->_cost) { // We have a stricter limit than our previous optimization's cost. return {}; } else { // Reuse result under identical properties. if (_memo.getDebugInfo().hasDebugLevel(3)) { std::cout << "Reusing winner's circle entry: group: " << groupId << ", id: " << physNode._index << ", cost: " << physNode._nodeInfo->_cost.toString() << ", limit: " << costLimit.toString() << "\n"; std::cout << "Existing props: " << ExplainGenerator::explainPhysProps("existing", physNode._physProps) << "\n"; std::cout << "New props: " << ExplainGenerator::explainPhysProps("new", physProps) << "\n"; std::cout << "Reused plan: " << ExplainGenerator::explainV2(physNode._nodeInfo->_node) << "\n"; } return {physNode._index, physNode._nodeInfo->_cost}; } } else { // Check winner's circle for compatible properties. for (const auto& physNode : physicalNodes.getNodes()) { _memo._stats._physMemoCheckCount++; if (!physNode->_nodeInfo) { continue; } // At this point we have an optimized entry. if (costLimit < physNode->_nodeInfo->_cost) { // Properties are not identical. Continue exploring even if limit was stricter. continue; } if (!PropCompatibleVisitor::propertiesCompatible(physProps, physNode->_physProps)) { // We are stricter that what is available. continue; } if (physNode->_nodeInfo->_cost < costLimit) { if (_memo.getDebugInfo().hasDebugLevel(3)) { std::cout << "Reducing cost limit: group: " << groupId << ", id: " << physNode->_index << ", cost: " << physNode->_nodeInfo->_cost.toString() << ", limit: " << costLimit.toString() << "\n"; std::cout << ExplainGenerator::explainPhysProps("Existing props", physNode->_physProps) << "\n"; std::cout << ExplainGenerator::explainPhysProps("New props", physProps) << "\n"; } // Reduce cost limit result under compatible properties. hasCompatibleProps = true; costLimit = physNode->_nodeInfo->_cost; } } } // If found an exact match for properties, re-use entry and continue optimizing under higher // cost limit. Otherwise create with a new entry for the current properties. PhysOptimizationResult& bestResult = hasExactProps ? physicalNodes.at(exactPropsIndex) : physicalNodes.addOptimizationResult(physProps, costLimit); // Enforcement rewrites run just once, and are independent of the logical nodes. if (hasProperty<ProjectionRequirement>(bestResult._physProps)) { // Verify properties can be enforced and add enforcers if necessary. addEnforcers(groupId, _memo.getMetadata(), _ridProjections, prefixId, bestResult._queue, bestResult._physProps, logicalProps); } // Iterate until we perform all logical for the group and physical rewrites for our best plan. const OrderPreservingABTSet& logicalNodes = group._logicalNodes; while (bestResult._lastImplementedNodePos < logicalNodes.size() || !bestResult._queue.empty()) { if (_logicalRewriter) { // Attempt to perform logical rewrites. _logicalRewriter->rewriteGroup(groupId); } // Add rewrites to convert logical into physical nodes. Only add rewrites for newly added // logical nodes. addImplementers( _memo, _hints, _ridProjections, prefixId, bestResult, logicalProps, logicalNodes); // Perform physical rewrites, use branch-and-bound. while (!bestResult._queue.empty()) { PhysRewriteEntry rewrite = std::move(*bestResult._queue.top()); bestResult._queue.pop(); NodeCEMap nodeCEMap = std::move(rewrite._nodeCEMap); if (nodeCEMap.empty()) { nodeCEMap.emplace( rewrite._node.cast<Node>(), getPropertyConst<CardinalityEstimate>(logicalProps).getEstimate()); } costAndRetainBestNode(std::move(rewrite._node), std::move(rewrite._childProps), std::move(nodeCEMap), groupId, prefixId, bestResult); } } uassert(6624128, "Result is not optimized!", bestResult.isOptimized()); if (!bestResult._nodeInfo) { uassert(6624348, "Must optimize successfully if found compatible properties!", !hasCompatibleProps); return {}; } // We have a successful rewrite. if (_memo.getDebugInfo().hasDebugLevel(2)) { std::cout << "#" << localPlanExplorationCount << " Optimized group: " << groupId << ", id: " << bestResult._index << ", cost: " << bestResult._nodeInfo->_cost.toString() << "\n"; std::cout << ExplainGenerator::explainPhysProps("Physical properties", bestResult._physProps) << "\n"; std::cout << "Node: \n" << ExplainGenerator::explainV2( bestResult._nodeInfo->_node, false /*displayProperties*/, &_memo); } return {bestResult._index, bestResult._nodeInfo->_cost}; } } // namespace mongo::optimizer::cascades
45.328395
100
0.6017
benety
9be2a8fc174178052e2e78a680976dde0f7f33f4
2,556
cpp
C++
project2D/GameStateManager.cpp
PancakesMan/GameStateProject
09a2587d96759768f04c521585b90bd961ef1758
[ "MIT" ]
null
null
null
project2D/GameStateManager.cpp
PancakesMan/GameStateProject
09a2587d96759768f04c521585b90bd961ef1758
[ "MIT" ]
null
null
null
project2D/GameStateManager.cpp
PancakesMan/GameStateProject
09a2587d96759768f04c521585b90bd961ef1758
[ "MIT" ]
null
null
null
#pragma once #include "GameStateManager.h" #include "IGameState.h" #include <assert.h> GameStateManager::GameStateManager() { } GameStateManager::~GameStateManager() { for (auto iter = m_registeredStates.begin(); iter != m_registeredStates.end(); iter++) delete iter->value; m_registeredStates.clear(); } void GameStateManager::updateStates(float deltaTime) { processCommands(); (*m_activeStates.top()).update(deltaTime); //for (auto iter = m_activeStates.begin(); iter != m_activeStates.end(); iter++) //(*iter)->update(deltaTime); } void GameStateManager::renderStates(aie::Renderer2D * renderer) { //(*m_activeStates.rbegin())->render(renderer); for (auto iter = m_activeStates.begin(); iter != m_activeStates.end(); iter++) (*iter)->render(renderer); } void GameStateManager::setState(int id, IGameState * state) { Command command; command.cmd = eCommand::SET; command.id = id; command.state = state; m_commands.AddToEnd(command); } void GameStateManager::pushState(int id) { Command command; command.cmd = eCommand::PUSH; command.id = id; command.state = nullptr; m_commands.AddToEnd(command); } void GameStateManager::popState() { Command command; command.cmd = eCommand::POP; command.id = -1; command.state = nullptr; m_commands.AddToEnd(command); } IGameState* GameStateManager::getTopState() { if (m_activeStates.count() > 0) return m_activeStates.top(); return nullptr; } void GameStateManager::processCommands() { for (auto iter = m_commands.begin(); iter != m_commands.end(); iter++) { Command &c = (*iter); switch (c.cmd) { case eCommand::POP: processPopState(); break; case eCommand::PUSH: processPushState(c.id); break; case eCommand::SET: processSetState(c.id, c.state); break; default: assert(false && "Command not found!"); break; } } m_commands.Clear(); } void GameStateManager::processSetState(int id, IGameState * state) { //auto iter = m_registeredStates.find(id); if (m_registeredStates.find(id) != -1) m_registeredStates.remove(id); // Delete the state if it already exists // Replace it with the new state m_registeredStates[id] = state; } void GameStateManager::processPushState(int id) { auto iter = m_registeredStates.find(id); if (iter != -1) m_activeStates.push(m_registeredStates[id]); // If the state exists, add it to the list of active states else assert((int)id && "State not found!"); // if not, crash } void GameStateManager::processPopState() { if (m_activeStates.count() > 0) m_activeStates.pop(); }
21.478992
106
0.704617
PancakesMan
9be6ade99d5a69c2f208dc23c2c013f8f8a6df7e
861
cpp
C++
aoj/Volume05/0586/solve.cpp
tobyapi/online-judge-solutions
4088adb97ea592e8e6582ae7d2ecde2f85e2ed9c
[ "MIT" ]
null
null
null
aoj/Volume05/0586/solve.cpp
tobyapi/online-judge-solutions
4088adb97ea592e8e6582ae7d2ecde2f85e2ed9c
[ "MIT" ]
null
null
null
aoj/Volume05/0586/solve.cpp
tobyapi/online-judge-solutions
4088adb97ea592e8e6582ae7d2ecde2f85e2ed9c
[ "MIT" ]
null
null
null
#include<iostream> #include<cmath> #include<vector> #include<map> #include<algorithm> #include <sstream> using namespace std; bool is_prime(int n){ for(int i=2; i*i<=n; i++) if(n%i==0)return false; return true; } string toString(int a){ ostringstream oss; oss << a; return oss.str(); } int toInt(string s){ istringstream iss(s); int a; iss >> a; return a; } int main(void){ int n,c; string str="",C=""; cin >> n >> c; for(int i=0;i<n;i++)str+="9"; C=c+'0'; if(c<0 && n>1){ cout << str << str << endl; return 0; } while(true){ string rstr=str; reverse(rstr.begin(),rstr.end()); string res=str+C+rstr; int ans=toInt(res); if(is_prime(ans)){ cout << ans << endl; return 0; } int tmp=toInt(str); tmp--; str=toString(tmp); } return 0; }
13.887097
37
0.544715
tobyapi
9be9ba20b72641875842bb0b49d116b698556012
467
cpp
C++
Models/NetworkingModels/Connection.cpp
lordzsolt/DS_Client
78845ea5bfc20be8fedccdbae71f3763d873da02
[ "MIT" ]
null
null
null
Models/NetworkingModels/Connection.cpp
lordzsolt/DS_Client
78845ea5bfc20be8fedccdbae71f3763d873da02
[ "MIT" ]
null
null
null
Models/NetworkingModels/Connection.cpp
lordzsolt/DS_Client
78845ea5bfc20be8fedccdbae71f3763d873da02
[ "MIT" ]
null
null
null
#include "Connection.h" Connection::Connection(SOCKET socket, Recipient recipient) : _socket(socket), _recipient(recipient) { } Connection::~Connection() { } SOCKET Connection::socket() const { return _socket; } void Connection::setSocket(const SOCKET &socket) { _socket = socket; } Recipient Connection::recipient() const { return _recipient; } void Connection::setRecipient(const Recipient &recipient) { _recipient = recipient; }
13.342857
58
0.706638
lordzsolt
9bea79b4d6457b629dcc50a10d23dd97ac76bd3e
5,418
hh
C++
include/threadmap.hh
GYJQTYL2/DoubleTake
cdcd0200bb364b5343beae72756420e6c3954a6f
[ "MIT" ]
19
2015-09-17T18:10:14.000Z
2021-08-16T11:26:33.000Z
include/threadmap.hh
GYJQTYL2/DoubleTake
cdcd0200bb364b5343beae72756420e6c3954a6f
[ "MIT" ]
17
2015-04-27T14:33:42.000Z
2016-05-23T20:15:48.000Z
include/threadmap.hh
plasma-umass/DoubleTake
cdcd0200bb364b5343beae72756420e6c3954a6f
[ "MIT" ]
13
2015-07-29T15:15:00.000Z
2021-01-15T04:53:21.000Z
#if !defined(DOUBLETAKE_THREADMAP_H) #define DOUBLETAKE_THREADMAP_H /* * @file threadmap.h * @brief Mapping between pthread_t and internal thread information. * @author Tongping Liu <http://www.cs.umass.edu/~tonyliu> */ #include <assert.h> #include <pthread.h> #include <stdint.h> #include <stdlib.h> #include <new> #include "hashfuncs.hh" #include "hashmap.hh" #include "internalheap.hh" #include "list.hh" #include "log.hh" #include "mm.hh" #include "recordentries.hh" #include "semaphore.hh" #include "spinlock.hh" #include "threadstruct.hh" #include "xdefines.hh" class threadmap { public: threadmap() {} static threadmap& getInstance() { static char buf[sizeof(threadmap)]; static threadmap* theOneTrueObject = new (buf) threadmap(); return *theOneTrueObject; } void initialize() { // PRINF("xmap initializeNNNNNNNNNNNNNN\n"); _xmap.initialize(HashFuncs::hashAddr, HashFuncs::compareAddr, xdefines::THREAD_MAP_SIZE); listInit(&_alivethreads); } thread_t* getThreadInfo(pthread_t thread) { thread_t* info = NULL; _xmap.find((void*)thread, sizeof(void*), &info); if(info == NULL) { PRINF("Can't find thread_t for thread %lx. Exit now!!\n", thread); abort(); } return info; } void deleteThreadMap(pthread_t thread) { _xmap.erase((void*)thread, sizeof(void*)); } void insertAliveThread(thread_t* thread, pthread_t tid) { // Malloc struct aliveThread* ath = (struct aliveThread*)InternalHeap::getInstance().malloc(sizeof(struct aliveThread)); assert(ath != NULL); listInit(&ath->list); ath->thread = thread; PRINF("Insert alive thread %p\n", (void *)thread); listInsertTail(&ath->list, &_alivethreads); _xmap.insert((void*)tid, sizeof(void*), thread); } void removeAliveThread(thread_t* thread) { // First, remove thread from the threadmap. deleteThreadMap(thread->self); // Second, remove thread from the alive list. struct aliveThread* ath; // Now the _alivethreads list should not be empty. assert(isListEmpty(&_alivethreads) != true); // Search the whole list for given tid. ath = (struct aliveThread*)nextEntry(&_alivethreads); while(true) { PRINF("Traverse thread %p\n", (void *)ath->thread); // If we found the entry, remove this entry from the list. if(ath->thread == thread) { listRemoveNode(&ath->list); break; } // It is impossible that we haven't find the node until the end of a list. if(isListTail(&ath->list, &_alivethreads) == true) { PRWRN("WRong, we can't find alive thread %p in the list.", (void *)thread); abort(); } ath = (struct aliveThread*)nextEntry(&ath->list); } InternalHeap::getInstance().free((void*)ath); // Setting a thread structure to be "Free" status. setFreeThread(thread); } // Set a threadInfo structure to be free. void setFreeThread(thread_t* thread) { thread->available = true; } // How to return a thread event from specified entry. inline struct syncEvent* getThreadEvent(list_t* entry) { // FIXME: if we changed the structure of syncEvent. int threadEventOffset = sizeof(list_t); return (struct syncEvent*)((intptr_t)entry - threadEventOffset); } public: class aliveThreadIterator { struct aliveThread* thread; public: aliveThreadIterator(struct aliveThread* ithread = NULL) { thread = ithread; } ~aliveThreadIterator() {} aliveThreadIterator& operator++(int) // in postfix ++ { if(!isListTail(&thread->list, &_alivethreads)) { thread = (struct aliveThread*)nextEntry(&thread->list); } else { thread = NULL; } return *this; } // aliveThreadIterator& operator -- (); // Iterpreted as a = b is treated as a.operator=(b) aliveThreadIterator& operator=(const aliveThreadIterator& that) { thread = that.thread; return *this; } bool operator==(const aliveThreadIterator& that) const { return thread == that.thread; } bool operator!=(const aliveThreadIterator& that) const { return thread != that.thread; } thread_t* getThread() { return thread->thread; } }; void traverseAllThreads() { struct aliveThread* ath; // Search the whole list for given tid. ath = (struct aliveThread*)nextEntry(&_alivethreads); while(true) { thread_t* thread = ath->thread; if(thread->status != E_THREAD_WAITFOR_REAPING) { PRINF("thread %p self %p status %d\n", (void *)thread, (void*)thread->self, thread->status); } // Update to the next thread. if(isListTail(&ath->list, &_alivethreads)) { break; } else { ath = (struct aliveThread*)nextEntry(&ath->list); } } } // Acquire the first entry of the hash table aliveThreadIterator begin() { // Get the first non-null entry if(isListEmpty(&_alivethreads) != true) { return aliveThreadIterator((struct aliveThread*)nextEntry(&_alivethreads)); } else { return end(); } } aliveThreadIterator end() { return aliveThreadIterator(NULL); } private: // We are maintainning a private hash map for each thread. typedef HashMap<void*, thread_t*, spinlock, InternalHeapAllocator> threadHashMap; // The variables map shared by all threads threadHashMap _xmap; static list_t _alivethreads; }; #endif
27.226131
100
0.66076
GYJQTYL2
9bf043771fc2395d6f34fef93afb03bac9e92ee6
193
hpp
C++
samples/chalet/app.hpp
YiJiangFengYun/vulkan-graphics-examples
e7b788b8f47dd238b08840c019940c7c52335a54
[ "MIT" ]
1
2018-03-01T01:05:25.000Z
2018-03-01T01:05:25.000Z
samples/chalet/app.hpp
YiJiangFengYun/vulkan-graphics-examples
e7b788b8f47dd238b08840c019940c7c52335a54
[ "MIT" ]
null
null
null
samples/chalet/app.hpp
YiJiangFengYun/vulkan-graphics-examples
e7b788b8f47dd238b08840c019940c7c52335a54
[ "MIT" ]
null
null
null
#ifndef APP_H #define APP_H #include "sampleslib/app.hpp" namespace chalet { class App : public sampleslib::App { public: App(); private: }; } #endif // !APP_H
10.157895
38
0.585492
YiJiangFengYun
9bf410394e8999d85ded440780dd5e1122aa13e2
659
cpp
C++
laboratorios/lab_04/02_funcao_seno.cpp
sueyvid/Atividade_de_programacao_cpp
691941fc94125eddd4e5466862d5a1fe04dfb520
[ "MIT" ]
null
null
null
laboratorios/lab_04/02_funcao_seno.cpp
sueyvid/Atividade_de_programacao_cpp
691941fc94125eddd4e5466862d5a1fe04dfb520
[ "MIT" ]
null
null
null
laboratorios/lab_04/02_funcao_seno.cpp
sueyvid/Atividade_de_programacao_cpp
691941fc94125eddd4e5466862d5a1fe04dfb520
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> using namespace std; float qual_seno_do_angulo(float x, int n); int qual_o_fatorial(int y); int main() { float alfa; int num_termos; cin >> alfa >> num_termos; cout << qual_seno_do_angulo(alfa, num_termos); return 0; } int qual_o_fatorial(int y){ int j, r = 0; for(j = 1; j < y; j++){ r = j*(j+1); } return r; } float qual_seno_do_angulo(float x, int n){ int i, sen = 0, fat; x *= M_PI/180; for(i = 0; i < n; i++){ fat = (2*i+1); sen += pow(-1, i)*pow(x, fat)/qual_o_fatorial(fat); } cout << sen << endl; return sen; }
17.342105
59
0.54173
sueyvid
9bf61b1cc4954f6bf3f3beeb571039004faac9da
19,537
cpp
C++
simMolView3D.cpp
neelsoumya/cycells
a3a6e632addf0a91c75c0a579ad0d41ad9d7a089
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
simMolView3D.cpp
neelsoumya/cycells
a3a6e632addf0a91c75c0a579ad0d41ad9d7a089
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
simMolView3D.cpp
neelsoumya/cycells
a3a6e632addf0a91c75c0a579ad0d41ad9d7a089
[ "Naumen", "Condor-1.1", "MS-PL" ]
3
2018-06-20T21:55:11.000Z
2020-10-21T19:04:54.000Z
/************************************************************************ * * * Copyright (C) 2007 Christina Warrender and Drew Levin * * * * This file is part of QtCyCells. * * * * QtCyCells 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. * * * * QtCyCells 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 QtCyCells; if not, write to the Free Software Foundation, * * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * * ************************************************************************/ /************************************************************************ * File SimMolView3D.cc * * render() routine for SimMolView3D * * Allows 3D display of tissue model * ************************************************************************/ #include <GL/gl.h> #include <GL/glut.h> #include <math.h> #include <iostream> #include <sys/types.h> #include <unistd.h> #include "simMolView3D.h" #include "tissue.h" #include "cellType.h" using namespace std; #define MAX(x,y) ( x > y ? x : y ) #define MIN(x,y) ( x < y ? x : y ) #define TURN_SENSITIVITY 200.0 #define ZOOM_SENSITIVITY 2400.0 /************************************************************************ * SimMolView3D() * * Constructor * * * * Parameters * * QWidget *parent: Window containing this view * * int x, y, w, h: Position (x,y) and size (w,h) of view * * const Tissue *t; Pointer to model tissue * * * * Returns - nothing * ************************************************************************/ SimMolView3D::SimMolView3D(QWidget *parent, int x, int y, int w, int h, const Tissue *t, int mol_id) : SimView(parent, x, y, w, h), m_tissuep(t), m_molId(mol_id), m_first(true), m_mousedown(false), oldPos(0,0), m_anglex(0.0), m_angley(0.0), m_zoom(1.0), frame(0) { // Get tissue size info (do once at beginning rather than repeatedly) m_xsize = m_tissuep->getXSize(); m_ysize = m_tissuep->getYSize(); m_zsize = m_tissuep->getZSize(); m_maxlength = MAX(MAX(m_xsize, m_ysize), m_zsize); } /************************************************************************ * render() * * OpenGL code to draw current view of model * * * * Returns - nothing * ************************************************************************/ void SimMolView3D::render() { if (m_first) { // set up lighting GLfloat light_position[] = { 1.0, 1.0, m_zsize*2, 0.0 }; GLfloat light_position2[] = { m_xsize, m_ysize, m_zsize*2, 0.0}; GLfloat white_light[] = { 1.0, 1.0, 1.0, 1.0 }; GLfloat lmodel_ambient[] = { 0.9, 0.9, 0.9, 0.9 }; glLightfv(GL_LIGHT0, GL_POSITION, light_position); glLightfv(GL_LIGHT0, GL_DIFFUSE, white_light); glLightfv(GL_LIGHT0, GL_SPECULAR, white_light); glLightfv(GL_LIGHT1, GL_POSITION, light_position2); glLightfv(GL_LIGHT1, GL_DIFFUSE, white_light); glLightfv(GL_LIGHT1, GL_SPECULAR, white_light); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_LIGHT1); glClearColor(1.0, 1.0, 1.0, 0.0); // set white background; no blending glShadeModel(GL_SMOOTH); glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); // set size/projection - should be in resize routine? glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-m_xsize/2*m_zoom, m_xsize/2*m_zoom, -m_ysize/2*m_zoom, m_ysize/2*m_zoom, 9*m_maxlength, 11*m_maxlength); m_first = false; } // clear; get ready to do model/view transformations glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // Position and orient the camera gluLookAt(10*m_maxlength*sin(m_anglex)*cos(m_angley)+m_xsize/2, 10*m_maxlength*sin(m_angley)+m_ysize/2, -10*m_maxlength*cos(m_anglex)*cos(m_angley)+m_zsize/2, m_xsize/2, m_ysize/2, m_zsize/2, 0.0, 1.0, 0.0); renderMolecules(); drawBorder(); if (draw_time) drawTime(); glFlush(); if (save_image) saveImage(); swapBuffers(); frame++; } /************************************************************************ * renderMolecules() * * * * Parameters - none * * * * Returns - nothing * ************************************************************************/ void SimMolView3D::renderMolecules() { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_COLOR_MATERIAL); int xnum = m_tissuep->getXSize()/m_tissuep->getGridSize(); int ynum = m_tissuep->getYSize()/m_tissuep->getGridSize(); int znum = m_tissuep->getZSize()/m_tissuep->getGridSize(); // get concentration data for this molecule type const Array3D<Molecule::Conc>& conc = m_tissuep->getConc(m_molId); Color color = Color(0,0,0,255); double scale; // loop through grid cells for (int i=1; i<=xnum; i++) for (int j=1; j<=ynum; j++) for (int k=1; k<=znum; k++) { double c = conc.at(i, j, k); // scale color according to concentration if (c == 0) // nothing to draw continue; else if (c >= 1.66e-14) // White glColor4fv(Color(255,255,255,255).getfv()); else if (c >= 1.66e-16) // Red -> White { scale = (log10(c)+15.78)/2; scale = MIN(MAX(scale, 0), 1); glColor4fv(blendColors(255,0,0,255,255,255,scale).getfv()); } else if (c >= 1.66e-18) // Orange -> Red { scale = (log10(c)+17.78)/2; scale = MIN(MAX(scale, 0), 1); glColor4fv(blendColors(255,116,0,255,0,0,scale).getfv()); } else if (c >= 1.66e-20) // Yellow -> Orange { scale = (log10(c)+19.78)/2; scale = MIN(MAX(scale, 0), 1); glColor4fv(blendColors(255,255,0,255,116,0,scale).getfv()); } else if (c >= 1.66e-22) // Green -> Yellow { scale = (log10(c)+21.78)/2; scale = MIN(MAX(scale, 0), 1); glColor4fv(blendColors(0,255,0,255,255,0,scale).getfv()); } else if (c >= 1.66e-24) // Blue -> Green { scale = (log10(c)+23.78)/2; scale = MIN(MAX(scale, 0), 1); glColor4fv(blendColors(0,0,255,0,255,0,scale).getfv()); } else if (c >= 1.66e-26) // Purple -> Blue { scale = (log10(c)+25.78)/2; scale = MIN(MAX(scale, 0), 1); glColor4fv(blendColors(164,0,255,0,0,255,scale).getfv()); } else if (c >= 1.66e-28) // Black -> Purple { scale = (log10(c)+27.78)/2; scale = MIN(MAX(scale, 0), 1); glColor4fv(blendColors(0,0,0,164,0,255,scale).getfv()); } else glColor4fv(Color(0,0,0,1.0).getfv()); // scale, translate by grid cell indices & draw glPushMatrix(); glScalef(m_tissuep->getGridSize(), m_tissuep->getGridSize(), m_tissuep->getGridSize()); glTranslatef(i-1.0, j-1.0, k-1.0); drawGrid(); glPopMatrix(); } glDisable(GL_COLOR_MATERIAL); } /************************************************************************ * drawGrid() * * OpenGL code to draw a grid cell; calling routine must handle * * translation to appropriate location * * * * Parameters - none * * * * Returns - nothing * ************************************************************************/ void SimMolView3D::drawGrid() { // glPolygonMode(GL_FRONT); glBegin(GL_QUADS); // back glVertex3f(0.0, 0.0, 0.0); glVertex3f(1.0, 0.0, 0.0); glVertex3f(1.0, 1.0, 0.0); glVertex3f(0.0, 1.0, 0.0); // top glVertex3f(0.0, 1.0, 1.0); glVertex3f(1.0, 1.0, 1.0); glVertex3f(1.0, 1.0, 0.0); glVertex3f(0.0, 1.0, 0.0); // left glVertex3f(0.0, 0.0, 0.0); glVertex3f(0.0, 0.0, 1.0); glVertex3f(0.0, 1.0, 1.0); glVertex3f(0.0, 1.0, 0.0); // right glVertex3f(1.0, 0.0, 0.0); glVertex3f(1.0, 0.0, 1.0); glVertex3f(1.0, 1.0, 1.0); glVertex3f(1.0, 1.0, 0.0); // bottom glVertex3f(0.0, 0.0, 0.0); glVertex3f(0.0, 0.0, 1.0); glVertex3f(1.0, 0.0, 1.0); glVertex3f(1.0, 0.0, 0.0); // front glVertex3f(0.0, 0.0, 1.0); glVertex3f(1.0, 0.0, 1.0); glVertex3f(1.0, 1.0, 1.0); glVertex3f(0.0, 1.0, 1.0); glEnd(); // glDisable(GL_COLOR_MATERIAL); } /************************************************************************ * drawBorder() * * OpenGL code to draw border box around the limits of the simulation * * * * Parameters - none * * * * Returns - nothing * ************************************************************************/ void SimMolView3D::drawBorder() { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glEnable(GL_COLOR_MATERIAL); glColor3f(0.4, 0.4, 0.4); glBegin(GL_QUADS); // back glVertex3f(0.0, 0.0, 0.0); glVertex3f(m_xsize, 0.0, 0.0); glVertex3f(m_xsize, m_ysize, 0.0); glVertex3f(0.0, m_ysize, 0.0); // top glVertex3f(0.0, m_ysize, m_zsize); glVertex3f(m_xsize, m_ysize, m_zsize); glVertex3f(m_xsize, m_ysize, 0.0); glVertex3f(0.0, m_ysize, 0.0); // left glVertex3f(0.0, 0.0, 0.0); glVertex3f(0.0, 0.0, m_zsize); glVertex3f(0.0, m_ysize, m_zsize); glVertex3f(0.0, m_ysize, 0.0); // right glVertex3f(m_xsize, 0.0, 0.0); glVertex3f(m_xsize, 0.0, m_zsize); glVertex3f(m_xsize, m_ysize, m_zsize); glVertex3f(m_xsize, m_ysize, 0.0); // bottom glVertex3f(0.0, 0.0, 0.0); glVertex3f(0.0, 0.0, m_zsize); glVertex3f(m_xsize, 0.0, m_zsize); glVertex3f(m_xsize, 0.0, 0.0); // front glVertex3f(0.0, 0.0, m_zsize); glVertex3f(m_xsize, 0.0, m_zsize); glVertex3f(m_xsize, m_ysize, m_zsize); glVertex3f(0.0, m_ysize, m_zsize); glEnd(); glDisable(GL_COLOR_MATERIAL); } /************************************************************************ * drawTime () * * OpenGL code to draw the simulation time in the upper left corner. * * * * Parameters - none * * * * Returns - nothing * ************************************************************************/ void SimMolView3D::drawTime() { const char *c; double time; int days, hours, minutes, seconds; char str_days[256]; time = m_tissuep->getTime(); days = (int)floor(time/86400); time -= days*86400; hours = (int)floor(time/3600); time -= hours*3600; minutes = (int)floor(time/60); seconds = (int)time-(minutes*60); if (days > 0) { sprintf(str_days, "Day %d ", days); } else { sprintf(str_days, ""); } sprintf(time_string, "%s %d:%02d:%02d", str_days, hours, minutes, seconds); glEnable(GL_COLOR_MATERIAL); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluOrtho2D(0, width, 0, height); glScalef(1, -1, 1); glTranslatef(0, -height, 0); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glColor3d(0.9, 0.9, 0.9); glRasterPos2f(10, 28); for (c=time_string; *c != '\0'; c++) { glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *c); } glColor3d(0.1, 0.1, 0.1); glRasterPos2f(11, 29); for (c=time_string; *c != '\0'; c++) { glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *c); } glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); } /************************************************************************ * mousePressEvent() * * QT4 function to track mouse dragging. * * * * Parameters - event * * * * Returns - nothing * ************************************************************************/ void SimMolView3D::mousePressEvent(QMouseEvent *event) { oldPos = event->pos(); } /************************************************************************ * mouseMoveEvent() * * QT4 function to track mouse dragging. Only functions if the * * mouse button is pressed. Reorients the OpenGL view. * * * * Parameters - event * * * * Returns - nothing * ************************************************************************/ void SimMolView3D::mouseMoveEvent(QMouseEvent *event) { // Only react to mouse dragging, not regular movement. if ((event->buttons() & Qt::LeftButton)) { QPoint dxy = event->pos() - oldPos; oldPos = event->pos(); m_anglex += dxy.x() / TURN_SENSITIVITY; m_angley += dxy.y() / TURN_SENSITIVITY; render(); } } /************************************************************************ * wheelEvent() * * QT4 function to track the mouse wheel. Zooms in and out by * * narrowing or widening the view frustum. * * * * Parameters - event * * * * Returns - nothing * ************************************************************************/ void SimMolView3D::wheelEvent(QWheelEvent *event) { // Get mouse wheel rotation in 1/8 of a degree. // Most mouse wheels click every 15 degrees, or 120 delta units. double delta = (double)(event->delta()); if (delta > 0) // Zoom in m_zoom *= 1 - (delta / ZOOM_SENSITIVITY); else // Zoom Out m_zoom /= 1 - (-delta / ZOOM_SENSITIVITY); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-m_xsize/2*m_zoom, m_xsize/2*m_zoom, -m_ysize/2*m_zoom, m_ysize/2*m_zoom, 9*m_maxlength, 11*m_maxlength); render(); } /************************************************************************ * saveImage() * * private function to save current frame as an image file. * * * * Parameters - none * * * * Returns - nothing * ************************************************************************/ void SimMolView3D::saveImage() { makeCurrent(); int pid = (int)getpid(); printf("Frame: %5d\n", frame); QImage *screen = new QImage(grabFrameBuffer()); screen->save(QString("/nfs/adaptive/drew/cycells2/cycells/frames/frame_%1_%2.png").arg(pid).arg(frame, 6, 10, QChar('0')), "PNG"); delete screen; } /************************************************************************ * blendColors() * * Blends two RGB colors based on the scale factor * * * * Parameters - Color 1, Color2, scale factor * * * * Will return Color 1 with scale factor of 0 and Color 2 with scale * * factor of 1 * * * * Returns - nothing * ************************************************************************/ Color SimMolView3D::blendColors(int r1, int g1, int b1, int r2, int g2, int b2, double scale) { float r, g, b; r = ((double)r1 + (r2-r1)*scale)/255; g = ((double)g1 + (g2-g1)*scale)/255; b = ((double)b1 + (b2-b1)*scale)/255; if (r > 1 || g > 1 || b > 1 || r < 0 || g < 0 || b < 0) { printf("\nColor1: (%d, %d, %d)\n", r1, g1, b1); printf("Color2: (%d, %d, %d)\n", r2, g2, b2); printf("Scale: %f\n", scale); printf("Color: (%f, %f, %f)\n\n", r, g, b); } return Color(r, g, b, 1.0); }
38.840954
131
0.417004
neelsoumya
9bfde68d2f9577a5c0e63857d70d0409acaa1820
14,943
cpp
C++
llvm/tools/clang/lib/Driver/CompilationInfo.cpp
ghsecuritylab/ellcc-mirror
b03a4afac74d50cf0987554b8c0cd8209bcb92a2
[ "BSD-2-Clause" ]
null
null
null
llvm/tools/clang/lib/Driver/CompilationInfo.cpp
ghsecuritylab/ellcc-mirror
b03a4afac74d50cf0987554b8c0cd8209bcb92a2
[ "BSD-2-Clause" ]
null
null
null
llvm/tools/clang/lib/Driver/CompilationInfo.cpp
ghsecuritylab/ellcc-mirror
b03a4afac74d50cf0987554b8c0cd8209bcb92a2
[ "BSD-2-Clause" ]
null
null
null
#include "clang/Driver/CompilationInfo.h" #include "clang/Driver/DriverDiagnostic.h" #include "clang/Driver/Driver.h" using namespace clang::compilationinfo; namespace { const char ellcc_linux[] = "global:\n" " static_default: true\n" "compiler:\n" " cxx_include_dirs:\n" " - $R/include/c++\n" "assembler:\n" " output:\n" " - -o $O\n" "linker:\n" " exe: $E/ecc-ld$X\n" " output:\n" " - -o $O\n" " start:\n" " - -e _start\n" " opt_static:\n" " - -Bstatic\n" " opt_rdynamic:\n" " - -export-dynamic\n" " opt_dynamic:\n" " - -Bdynamic\n" " opt_shared:\n" " - -shared\n" " opt_notshared:\n" " - -dynamic-linker /usr/libexec/ld.so\n" " opt_pthread:\n" " - -pthread\n" " cxx_libraries:\n" " - -lc++\n" " - -lm\n" " profile_libraries:\n" " - -lprofile_rt\n" " c_libraries:\n" " - -(\n" // This is need for ARM and profiling. " - -lc\n" " - -lcompiler-rt\n" " - -)\n" ""; const char arm_ellcc_linux[] = "based_on: ellcc-linux\n" "compiler:\n" " options:\n" " - -target arm-ellcc-linux-eabi\n" " c_include_dirs:\n" " - $R/include/arm\n" " - $R/include\n" "assembler:\n" " exe: $E/arm-elf-as$X\n" "linker:\n" " options:\n" " - -m armelf_linux_eabi\n" " - --build-id\n" " - --hash-style=gnu\n" " - --eh-frame-hdr\n" " static_crt1: $R/lib/arm/linux/crt1.o\n" " dynamic_crt1: $R/lib/arm/linux/Scrt1.o\n" " crtbegin: $R/lib/arm/linux/crtbegin.o\n" " crtend: $R/lib/arm/linux/crtend.o\n" " library_paths:\n" " - -L $R/lib/arm/linux\n" ""; const char armeb_ellcc_linux[] = "based_on: ellcc-linux\n" "compiler:\n" " options:\n" " - -target armeb-ellcc-linux-eabi\n" " c_include_dirs:\n" " - $R/include/arm\n" " - $R/include\n" "assembler:\n" " exe: $E/arm-elf-as$X\n" " options:\n" " - -EB\n" "linker:\n" " options:\n" " - -m armelfb_linux_eabi\n" " - --build-id\n" " - --hash-style=gnu\n" " - --eh-frame-hdr\n" " static_crt1: $R/lib/armeb/linux/crt1.o\n" " dynamic_crt1: $R/lib/armeb/linux/Scrt1.o\n" " crtbegin: $R/lib/armeb/linux/crtbegin.o\n" " crtend: $R/lib/armeb/linux/crtend.o\n" " library_paths:\n" " - -L $R/lib/armeb/linux\n" ""; const char aarch64_ellcc_linux[] = "based_on: ellcc-linux\n" "compiler:\n" " options:\n" " - -target aarch64-ellcc-linux\n" " c_include_dirs:\n" " - $R/include/aarch64\n" " - $R/include\n" "assembler:\n" " exe: $E/aarch64-elf-as$X\n" "linker:\n" " options:\n" " - -m aarch64linux\n" " - --build-id\n" " - --hash-style=gnu\n" " - --eh-frame-hdr\n" " static_crt1: $R/lib/aarch64/linux/crt1.o\n" " dynamic_crt1: $R/lib/aarch64/linux/Scrt1.o\n" " crtbegin: $R/lib/aarch64/linux/crtbegin.o\n" " crtend: $R/lib/aarch64/linux/crtend.o\n" " library_paths:\n" " - -L $R/lib/aarch64/linux\n" ""; const char i386_ellcc_linux[] = "based_on: ellcc-linux\n" "compiler:\n" " options:\n" " - -target i386-ellcc-linux\n" " c_include_dirs:\n" " - $R/include/i386\n" " - $R/include\n" "assembler:\n" " exe: $E/i386-elf-as$X\n" "linker:\n" " options:\n" " - -m elf_i386\n" " - --build-id\n" " - --hash-style=gnu\n" " - --eh-frame-hdr\n" " static_crt1: $R/lib/i386/linux/crt1.o\n" " dynamic_crt1: $R/lib/i386/linux/Scrt1.o\n" " crtbegin: $R/lib/i386/linux/crtbegin.o\n" " crtend: $R/lib/i386/linux/crtend.o\n" " library_paths:\n" " - -L $R/lib/i386/linux\n" ""; const char microblaze_ellcc_linux[] = "based_on: ellcc-linux\n" "compiler:\n" " options:\n" " - -target microblaze-ellcc-linux\n" " c_include_dirs:\n" " - $R/include/microblaze\n" " - $R/include\n" "assembler:\n" " exe: $E/microblaze-elf-as$X\n" "linker:\n" " options:\n" " - -m elf32mb_linux\n" " static_crt1: $R/lib/microblaze/linux/crt1.o\n" " dynamic_crt1: $R/lib/microblaze/linux/Scrt1.o\n" " crtbegin: $R/lib/microblaze/linux/crtbegin.o\n" " crtend: $R/lib/microblaze/linux/crtend.o\n" " library_paths:\n" " - -L $R/lib/microblaze/linux\n" ""; const char mips_ellcc_linux[] = "based_on: ellcc-linux\n" "compiler:\n" " options:\n" " - -target mips-ellcc-linux\n" " c_include_dirs:\n" " - $R/include/mips\n" " - $R/include\n" "assembler:\n" " exe: $E/mips-elf-as$X\n" "linker:\n" " options:\n" " - -m elf32ebmip\n" " - --build-id\n" " - --eh-frame-hdr\n" " static_crt1: $R/lib/mips/linux/crt1.o\n" " dynamic_crt1: $R/lib/mips/linux/Scrt1.o\n" " crtbegin: $R/lib/mips/linux/crtbegin.o\n" " crtend: $R/lib/mips/linux/crtend.o\n" " library_paths:\n" " - -L $R/lib/mips/linux\n" ""; const char mipsel_ellcc_linux[] = "based_on: ellcc-linux\n" "compiler:\n" " options:\n" " - -target mipsel-ellcc-linux\n" " c_include_dirs:\n" " - $R/include/mips\n" " - $R/include\n" "assembler:\n" " exe: $E/mips-elf-as$X\n" " options:\n" " - -EL\n" "linker:\n" " options:\n" " - -m elf32elmip\n" " - --build-id\n" " - --eh-frame-hdr\n" " static_crt1: $R/lib/mipsel/linux/crt1.o\n" " dynamic_crt1: $R/lib/mipsel/linux/Scrt1.o\n" " crtbegin: $R/lib/mipsel/linux/crtbegin.o\n" " crtend: $R/lib/mipsel/linux/crtend.o\n" " library_paths:\n" " - -L $R/lib/mipsel/linux\n" ""; const char ppc_ellcc_linux[] = "based_on: ellcc-linux\n" "compiler:\n" " options:\n" " - -target ppc-ellcc-linux\n" " c_include_dirs:\n" " - $R/include/ppc\n" " - $R/include\n" "assembler:\n" " exe: $E/ppc-elf-as$X\n" " options:\n" " - -a32\n" " - -many\n" "linker:\n" " options:\n" " - -m elf32ppc\n" " - --build-id\n" " - --hash-style=gnu\n" " - --eh-frame-hdr\n" " static_crt1: $R/lib/ppc/linux/crt1.o\n" " dynamic_crt1: $R/lib/ppc/linux/Scrt1.o\n" " crtbegin: $R/lib/ppc/linux/crtbegin.o\n" " crtend: $R/lib/ppc/linux/crtend.o\n" " library_paths:\n" " - -L $R/lib/ppc/linux\n" ""; const char ppc64_ellcc_linux[] = "based_on: ellcc-linux\n" "compiler:\n" " options:\n" " - -target ppc64-ellcc-linux\n" " c_include_dirs:\n" " - $R/include/ppc\n" " - $R/include\n" "assembler:\n" " exe: $E/ppc-elf-as$X\n" " options:\n" " - -a64\n" " - -many\n" "linker:\n" " options:\n" " - -m elf64ppc\n" " - --build-id\n" " - --hash-style=gnu\n" " - --eh-frame-hdr\n" " static_crt1: $R/lib/ppc64/linux/crt1.o\n" " dynamic_crt1: $R/lib/ppc64/linux/Scrt1.o\n" " crtbegin: $R/lib/ppc64/linux/crtbegin.o\n" " crtend: $R/lib/ppc64/linux/crtend.o\n" " library_paths:\n" " - -L $R/lib/ppc64/linux\n" ""; const char x86_64_ellcc_linux[] = "based_on: ellcc-linux\n" "compiler:\n" " options:\n" " - -target x86_64-ellcc-linux\n" " c_include_dirs:\n" " - $R/include/x86_64\n" " - $R/include\n" "assembler:\n" " exe: $E/x86_64-elf-as$X\n" "linker:\n" " options:\n" " - -m elf_x86_64\n" " - --build-id\n" " - --hash-style=gnu\n" " - --eh-frame-hdr\n" " static_crt1: $R/lib/x86_64/linux/crt1.o\n" " dynamic_crt1: $R/lib/x86_64/linux/Scrt1.o\n" " crtbegin: $R/lib/x86_64/linux/crtbegin.o\n" " crtend: $R/lib/x86_64/linux/crtend.o\n" " library_paths:\n" " - -L $R/lib/x86_64/linux\n" ""; using namespace clang::compilationinfo; void PredefinedInfo(CompilationInfo &Info) { if (Info.InfoMap.size() == 0) { Info.DefineInfo("ellcc-linux", ellcc_linux); Info.DefineInfo("arm-ellcc-linux", arm_ellcc_linux); Info.DefineInfo("armeb-ellcc-linux", armeb_ellcc_linux); Info.DefineInfo("aarch64-ellcc-linux", aarch64_ellcc_linux); Info.DefineInfo("i386-ellcc-linux", i386_ellcc_linux); Info.DefineInfo("microblaze-ellcc-linux", microblaze_ellcc_linux); Info.DefineInfo("mips-ellcc-linux", mips_ellcc_linux); Info.DefineInfo("mipsel-ellcc-linux", mipsel_ellcc_linux); Info.DefineInfo("ppc-ellcc-linux", ppc_ellcc_linux); Info.DefineInfo("ppc64-ellcc-linux", ppc64_ellcc_linux); Info.DefineInfo("x86_64-ellcc-linux", x86_64_ellcc_linux); } } } void clang::compilationinfo::ExpandArg(std::string &arg, const char *sub, const std::string &value) { // Expand sub into value. size_t index = 0; while ((index = arg.find(sub, index)) != std::string::npos) { if (index > 0 && arg[index - 1] == '\\') { // An escaped sub start character. Remove the escape arg.erase(index - 1, 1); continue; } // Make the substitution. arg.replace(index, strlen(sub), value); } } void clang::compilationinfo::ExpandArgWithAll(std::string &arg, const clang::driver::Driver &TheDriver, const char *Output) { if (arg.find_first_of('$') == std::string::npos) { // No expansions to do. return; } // Perform expansions. ExpandArg(arg, "$E", TheDriver.Dir); ExpandArg(arg, "$R", TheDriver.ResourceDir); #if defined(LLVM_ON_WIN32) ExpandArg(arg, "$X", ".exe"); #else ExpandArg(arg, "$X", ""); #endif if (Output) { ExpandArg(arg, "$O", Output); } } /// ExpandArgs - Expand arguments. /// Expand "-option value" into two entries. /// Make argument substitutions. void clang::compilationinfo::ExpandArgs(StrSequence &options, const clang::driver::Driver &TheDriver, const char *Output) { // Expand "-option value" into two entries. StrSequence newOptions; for (StrSequence::iterator it = options.begin(), ie = options.end(); it != ie; ++it) { // Find the first option terminator. size_t space = it->find_first_of(" \t='\""); if (space != std::string::npos && isspace((*it)[space])) { // Have a terminated option. Ignore trailing spaces. size_t nonspace = it->find_first_not_of(" \t", space); if (nonspace != std::string::npos) { // Need to split the option into two arguments. newOptions.push_back(it->substr(0, space)); newOptions.push_back(it->substr(nonspace)); } else { newOptions.push_back(*it); } } else { newOptions.push_back(*it); } } options = newOptions; // Expand $X substitutions. for (auto &i : options) { ExpandArgWithAll(i, TheDriver, Output); } } bool CompilationInfo::ReadInfo(llvm::MemoryBuffer &Buffer) { llvm::yaml::Input yin(Buffer.getMemBufferRef()); yin >> *this; if (yin.error()) { TheDriver.Diag(diag::err_drv_malformed_compilation_info) << Buffer.getBufferIdentifier(); return false; } if (this->dump) { // Look at the info. llvm::yaml::Output yout(llvm::outs()); yout << *this; } return true; } bool CompilationInfo::CheckForAndReadInfo(const char *target, driver::Driver &TheDriver) { // Look for a file that contains info for this target. std::unique_ptr<CompilationInfo> Info(new CompilationInfo(TheDriver)); llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> BufferOrErr = llvm::MemoryBuffer::getFile(target); bool valid = false; if (!BufferOrErr.getError()) { // Get info from the file. valid = Info->ReadInfo(*BufferOrErr.get()); } if (!valid) { // Look in the config directory. llvm::SmallString<128> P(TheDriver.ResourceDir); llvm::sys::path::append(P, "config", target); BufferOrErr = llvm::MemoryBuffer::getFile(P.str()); if (!BufferOrErr.getError()) { // Get info from the file. valid = Info->ReadInfo(*BufferOrErr.get()); } } if (!valid) { // Can't open as a file. Look for predefined info. PredefinedInfo(*Info); std::map<std::string, const char *>::iterator it; it = Info->InfoMap.find(target); if (it != Info->InfoMap.end()) { // Predefined info exists for this target. std::unique_ptr<llvm::MemoryBuffer> Buffer = llvm::MemoryBuffer::getMemBuffer(it->second, target); valid = Info->ReadInfo(*Buffer.get()); } } if (valid) { // Give the info to the driver. TheDriver.Info = std::move(Info); } return valid; } void CompilationInfo::HandleBasedOn(CompilationInfo &config) { if (config.based_on.empty()) { return; } if (++config.nesting > 10) { // Nesting level exceeded. config.TheDriver.Diag(diag::err_drv_compilation_info_nesting) << config.nesting << config.based_on; --config.nesting; return; } if (config.dump) { llvm::outs() << "# based_on `" << config.based_on << "'\n"; } // Look for a file that contains info for this target. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> BufferOrErr = llvm::MemoryBuffer::getFile(config.based_on); if (!BufferOrErr.getError()) { // Get info from the file. llvm::yaml::Input yin(BufferOrErr.get()->getMemBufferRef()); std::string name = config.based_on; config.based_on.erase(); yin >> config; if (yin.error()) { // Failed. config.TheDriver.Diag(diag::err_drv_malformed_compilation_info) << name; } --config.nesting; return; } // Look in the config directory. llvm::SmallString<128> P(config.TheDriver.ResourceDir); llvm::sys::path::append(P, "config", config.based_on); BufferOrErr = llvm::MemoryBuffer::getFile(P.str()); if (!BufferOrErr.getError()) { // Get info from the file. llvm::yaml::Input yin(BufferOrErr.get()->getMemBufferRef()); std::string name = config.based_on; config.based_on.erase(); yin >> config; if (yin.error()) { // Failed. config.TheDriver.Diag(diag::err_drv_malformed_compilation_info) << name; } --config.nesting; return; } // Look for predefined info. PredefinedInfo(config); std::map<std::string, const char *>::iterator it; it = clang::compilationinfo::CompilationInfo:: InfoMap.find(config.based_on.c_str()); if (it != clang::compilationinfo::CompilationInfo::InfoMap.end()) { // Predefined info exists for this target. std::unique_ptr<llvm::MemoryBuffer> Buffer = llvm::MemoryBuffer::getMemBuffer(it->second, config.based_on); llvm::yaml::Input yin(Buffer->getMemBufferRef()); std::string name = config.based_on; config.based_on.erase(); yin >> config; if (yin.error()) { // Failed. config.TheDriver.Diag(diag::err_drv_malformed_compilation_info) << name; } --config.nesting; return; } else { // Can't find info. Failed. config.TheDriver.Diag(diag::err_drv_invalid_based_on) << config.based_on; --config.nesting; return; } }
28.19434
80
0.589841
ghsecuritylab
5004f365f3fa6f8dc9f2999fb8b01ae21b87a582
797
cpp
C++
4. Алгоритмы на графах/64. Построить матрицу смежности #3271/[OK]184696.cpp
godnoTA/acm.bsu.by
3e1cf1c545c691de82b5e1d2e0768b41ea581734
[ "Unlicense" ]
19
2018-05-19T16:37:14.000Z
2022-03-23T20:13:43.000Z
4. Алгоритмы на графах/64. Построить матрицу смежности #3271/[OK]184211.cpp
godnoTA/acm.bsu.by
3e1cf1c545c691de82b5e1d2e0768b41ea581734
[ "Unlicense" ]
6
2020-05-07T21:06:48.000Z
2020-06-05T17:52:57.000Z
4. Алгоритмы на графах/64. Построить матрицу смежности #3271/[OK]184696.cpp
godnoTA/acm.bsu.by
3e1cf1c545c691de82b5e1d2e0768b41ea581734
[ "Unlicense" ]
31
2019-03-01T21:41:38.000Z
2022-03-27T17:56:39.000Z
#include <iostream> #include <fstream> using namespace std; int main() { ifstream fin("input.txt"); int n1, n2; fin >> n1; fin >> n2; bool** mas = new bool*[n1]; for (int i = 0; i < n1; i++) mas[i] = new bool[n1]; for (int i = 0; i < n1; i++) { for (int j = 0; j < n1; j++) { mas[i][j] = false; } } int I, J; for (int i = 0; i < n2; i++) { fin >> I; fin >> J; mas[I - 1][J - 1] = true; mas[J - 1][I - 1] = true; } fin.close(); ofstream fout("output.txt"); for (int i = 0; i < n1; i++) { for (int j = 0; j < n1 - 1; j++) fout << (mas[i][j] == true ? "1 " : "0 "); fout << (mas[i][n1-1] == true ? "1\n" : "0\n"); } fout.close(); for (int i = 0; i < n1; i++) delete[] mas[i]; delete[] mas; return 0; }
17.711111
50
0.434128
godnoTA
50082b197d669084dd43b3dd9fb165b7bd98334d
7,093
cpp
C++
src/erpc/erpc_basic_codec.cpp
Seeed-Studio/seeed-ambd-firmware
7334817a6fcf311fbe3c9a8c5644b805ae12bdab
[ "MIT" ]
21
2020-09-14T08:44:19.000Z
2022-03-28T16:11:15.000Z
src/erpc/erpc_basic_codec.cpp
Seeed-Studio/seeed-ambd-firmware
7334817a6fcf311fbe3c9a8c5644b805ae12bdab
[ "MIT" ]
10
2020-11-18T16:56:47.000Z
2022-01-18T00:03:20.000Z
src/erpc/erpc_basic_codec.cpp
Seeed-Studio/seeed-ambd-firmware
7334817a6fcf311fbe3c9a8c5644b805ae12bdab
[ "MIT" ]
9
2020-11-12T03:35:56.000Z
2022-03-10T12:31:47.000Z
/* * Copyright (c) 2014, Freescale Semiconductor, Inc. * Copyright 2016-2017 NXP * All rights reserved. * * * SPDX-License-Identifier: BSD-3-Clause */ #include "erpc_basic_codec.h" #include <cassert> using namespace erpc; //////////////////////////////////////////////////////////////////////////////// // Code //////////////////////////////////////////////////////////////////////////////// const uint32_t BasicCodec::kBasicCodecVersion = 1; void BasicCodec::startWriteMessage(message_type_t type, uint32_t service, uint32_t request, uint32_t sequence) { uint32_t header = (kBasicCodecVersion << 24) | ((service & 0xff) << 16) | ((request & 0xff) << 8) | (type & 0xff); write(header); write(sequence); } void BasicCodec::writeData(const void *value, uint32_t length) { if (!m_status) { if (value != NULL) { m_status = m_cursor.write(value, length); } else { m_status = kErpcStatus_MemoryError; } } } void BasicCodec::write(bool value) { // Make sure the bool is a single byte. uint8_t v = value; writeData(&v, sizeof(v)); } void BasicCodec::write(int8_t value) { writeData(&value, sizeof(value)); } void BasicCodec::write(int16_t value) { writeData(&value, sizeof(value)); } void BasicCodec::write(int32_t value) { writeData(&value, sizeof(value)); } void BasicCodec::write(int64_t value) { writeData(&value, sizeof(value)); } void BasicCodec::write(uint8_t value) { writeData(&value, sizeof(value)); } void BasicCodec::write(uint16_t value) { writeData(&value, sizeof(value)); } void BasicCodec::write(uint32_t value) { writeData(&value, sizeof(value)); } void BasicCodec::write(uint64_t value) { writeData(&value, sizeof(value)); } void BasicCodec::write(float value) { writeData(&value, sizeof(value)); } void BasicCodec::write(double value) { writeData(&value, sizeof(value)); } void BasicCodec::writePtr(uintptr_t value) { uint8_t ptrSize = sizeof(value); write(ptrSize); writeData(&value, ptrSize); } void BasicCodec::writeString(uint32_t length, const char *value) { // Just treat the string as binary. writeBinary(length, reinterpret_cast<const uint8_t *>(value)); } void BasicCodec::writeBinary(uint32_t length, const uint8_t *value) { // Write the blob length as a u32. write(length); writeData(value, length); } void BasicCodec::startWriteList(uint32_t length) { // Write the list length as a u32. write(length); } void BasicCodec::startWriteUnion(int32_t discriminator) { // Write the union discriminator as a u32. write(discriminator); } void BasicCodec::writeNullFlag(bool isNull) { write(static_cast<uint8_t>(isNull ? kIsNull : kNotNull)); } void BasicCodec::writeCallback(arrayOfFunPtr callbacks, uint8_t callbacksCount, funPtr callback) { assert(callbacksCount > 1); // callbacks = callbacks table for (uint8_t i = 0; i < callbacksCount; i++) { if (callbacks[i] == callback) { write(i); break; } if (i + 1 == callbacksCount) { updateStatus(kErpcStatus_UnknownCallback); } } } void BasicCodec::writeCallback(funPtr callback1, funPtr callback2) { // callbacks = callback directly // When declared only one callback function no serialization is needed. if (callback1 != callback2) { updateStatus(kErpcStatus_UnknownCallback); } } void BasicCodec::startReadMessage(message_type_t *type, uint32_t *service, uint32_t *request, uint32_t *sequence) { uint32_t header; read(&header); if (((header >> 24) & 0xff) != kBasicCodecVersion) { updateStatus(kErpcStatus_InvalidMessageVersion); } if (!m_status) { *service = ((header >> 16) & 0xff); *request = ((header >> 8) & 0xff); *type = static_cast<message_type_t>(header & 0xff); read(sequence); } } void BasicCodec::readData(void *value, uint32_t length) { if (!m_status) { if (value != NULL) { m_status = m_cursor.read(value, length); } else { m_status = kErpcStatus_MemoryError; } } } void BasicCodec::read(bool *value) { uint8_t v = 0; readData(&v, sizeof(v)); if (!m_status) { *value = v; } } void BasicCodec::read(int8_t *value) { readData(value, sizeof(*value)); } void BasicCodec::read(int16_t *value) { readData(value, sizeof(*value)); } void BasicCodec::read(int32_t *value) { readData(value, sizeof(*value)); } void BasicCodec::read(int64_t *value) { readData(value, sizeof(*value)); } void BasicCodec::read(uint8_t *value) { readData(value, sizeof(*value)); } void BasicCodec::read(uint16_t *value) { readData(value, sizeof(*value)); } void BasicCodec::read(uint32_t *value) { readData(value, sizeof(*value)); } void BasicCodec::read(uint64_t *value) { readData(value, sizeof(*value)); } void BasicCodec::read(float *value) { readData(value, sizeof(*value)); } void BasicCodec::read(double *value) { readData(value, sizeof(*value)); } void BasicCodec::readPtr(uintptr_t *value) { uint8_t ptrSize; read(&ptrSize); if (ptrSize > sizeof(*value)) { updateStatus(kErpcStatus_BadAddressScale); } readData(value, ptrSize); } void BasicCodec::readString(uint32_t *length, char **value) { readBinary(length, reinterpret_cast<uint8_t **>(value)); } void BasicCodec::readBinary(uint32_t *length, uint8_t **value) { // Read length first as u32. read(length); if (!m_status) { if (m_cursor.getRemaining() >= *length) { // Return current pointer into buffer. *value = m_cursor.get(); // Skip over data. m_cursor += *length; } else { *length = 0; m_status = kErpcStatus_BufferOverrun; } } else { *length = 0; } } void BasicCodec::startReadList(uint32_t *length) { // Read list length as u32. read(length); if (m_status) { *length = 0; } } void BasicCodec::startReadUnion(int32_t *discriminator) { // Read union discriminator as u32. read(discriminator); } void BasicCodec::readNullFlag(bool *isNull) { uint8_t flag; read(&flag); if (!m_status) { *isNull = (flag == kIsNull); } } void BasicCodec::readCallback(arrayOfFunPtr callbacks, uint8_t callbacksCount, funPtr *callback) { assert(callbacksCount > 1); // callbacks = callbacks table uint8_t _tmp_local; read(&_tmp_local); if (!m_status) { if (_tmp_local < callbacksCount) { *callback = callbacks[_tmp_local]; } else { m_status = kErpcStatus_UnknownCallback; } } } void BasicCodec::readCallback(funPtr callbacks1, funPtr *callback2) { // callbacks = callback directly *callback2 = callbacks1; }
19.75766
118
0.612153
Seeed-Studio
5008c1c0189f9ef01607038169bfc6c053a0569e
15,603
cpp
C++
src/db/Capnp2DbEngine.cpp
nneesshh/pb-entity-db
efb3ca2c5f1f509ae12a3181545d77daf6de1d0b
[ "MIT" ]
2
2018-08-08T02:10:12.000Z
2019-05-04T04:51:12.000Z
src/db/Capnp2DbEngine.cpp
nneesshh/pb-entity-db
efb3ca2c5f1f509ae12a3181545d77daf6de1d0b
[ "MIT" ]
null
null
null
src/db/Capnp2DbEngine.cpp
nneesshh/pb-entity-db
efb3ca2c5f1f509ae12a3181545d77daf6de1d0b
[ "MIT" ]
null
null
null
//------------------------------------------------------------------------------ // Capnp2DbEngine.cpp // (C) 2016 n.lee //------------------------------------------------------------------------------ #include "Capnp2DbEngine.h" #include <capnp/schema-parser.h> #include <capnp/message.h> #include <capnp/serialize-packed.h> #include <capnp/schema.h> #include <capnp/dynamic.h> #define WIN32_LEAN_AND_MEAN 1 #include <Windows.h> #include <kj/windows-sanity.h> #include <time.h> #include <locale.h> #include <array> #include "ZdbConnectionPoolSession.h" #ifdef _MSC_VER #ifdef _DEBUG #define new new(_NORMAL_BLOCK, __FILE__,__LINE__) #endif #endif //------------------------------------------------------------------------------ /** */ Capnp2DbEngine::Capnp2DbEngine() { } //------------------------------------------------------------------------------ /** */ Capnp2DbEngine::~Capnp2DbEngine() { if (_db) { _db->Close(); delete _db; } } //------------------------------------------------------------------------------ /** */ void Capnp2DbEngine::OnInit(StdLog *pLog, const char * sURL, const char *sUser, const char *sPass, const char *sSchema, int nPoolSize) { // init db _db = new ZdbDriver(pLog, sURL, sUser, sPass, sSchema, nPoolSize); } //------------------------------------------------------------------------------ /** */ void Capnp2DbEngine::OnDelete() { } //------------------------------------------------------------------------------ /** */ void Capnp2DbEngine::Open() { while (!_db->Open()) { util_sleep(15 * 1000); } _opened = true; } //------------------------------------------------------------------------------ /** */ void Capnp2DbEngine::Close() { _db->Close(); _opened = false; } //------------------------------------------------------------------------------ /** */ bool Capnp2DbEngine::ExecQuery(::capnp::MessageReader& storedProc, ::capnp::StructSchema& root_schema, ::capnp::MessageBuilder& out) { ::capnp::DynamicStruct::Reader root = storedProc.getRoot<::capnp::DynamicStruct, ::capnp::StructSchema>(root_schema); auto& root_proto = root_schema.getProto(); const std::string& full_proc_name = root_proto.getDisplayName(); auto proc_name_offset = root_proto.getDisplayNamePrefixLength(); const char *sProcName = full_proc_name.c_str() + proc_name_offset; ZdbStoredProc proc(_db, sProcName); ParseProc(root, sProcName, &proc); // exec query if (1) { ZdbResultSet rs(_db, &proc); proc.Call(&rs); // return records if (rs.IsOpened()) { // ::capnp::Orphanage root_orphanage = out.getOrphanage(); ::capnp::DynamicStruct::Builder root_struct_builder = out.initRoot<::capnp::DynamicStruct, ::capnp::StructSchema>(root_schema); // KJ_IF_MAYBE(fld_return_record_list, root_schema.findFieldByName("return_record_list")) { // ParseResult(rs, *fld_return_record_list, root_orphanage, root_struct_builder); } else { // multiple record set KJ_IF_MAYBE(fld_return_recordsets, root_schema.findFieldByName("return_recordsets")) { if (fld_return_recordsets->getType().isStruct()) { // ::capnp::DynamicStruct::Builder return_recordsets_struct_builder = root_struct_builder.init(*fld_return_recordsets).as<::capnp::DynamicStruct>(); ::capnp::StructSchema structType = fld_return_recordsets->getType().asStruct(); for (auto field : structType.getFields()) { // ParseResult(rs, field, root_orphanage, return_recordsets_struct_builder); // if (!rs.HasMoreResultSets()) { break; } } } } } } // rs.Close(); } return true; } //------------------------------------------------------------------------------ /** */ bool Capnp2DbEngine::ExecUpdate(::capnp::MessageReader& storedProc, ::capnp::StructSchema& root_schema) { ::capnp::DynamicStruct::Reader root = storedProc.getRoot<::capnp::DynamicStruct, ::capnp::StructSchema>(root_schema); auto& root_proto = root_schema.getProto(); const std::string& full_proc_name = root_proto.getDisplayName(); auto proc_name_offset = root_proto.getDisplayNamePrefixLength(); const char *sProcName = full_proc_name.c_str() + proc_name_offset; ZdbStoredProc proc(_db, sProcName); ParseProc(root, sProcName, &proc); // exec update proc.Call(); return true; } //------------------------------------------------------------------------------ /** */ void Capnp2DbEngine::ParseProc(::capnp::DynamicStruct::Reader& root, const char *sProcName, IDBStoredProc *pOutProc) { auto structValue = root.as<::capnp::DynamicStruct>(); for (auto field : structValue.getSchema().getFields()) { if (!structValue.has(field)) continue; const std::string &field_name = field.getProto().getName(); // parse name if (field_name == "param") { ::capnp::DynamicValue::Reader field_reader = structValue.get(field); switch (field_reader.getType()) { case ::capnp::DynamicValue::STRUCT: { ::capnp::DynamicStruct::Reader& param = field_reader.as<::capnp::DynamicStruct>(); int nParamsCount = ParseParamsCount(pOutProc, param); pOutProc->Prepare(sProcName, nParamsCount); // ParseParams(pOutProc, param); break; } default: break; } } } } //------------------------------------------------------------------------------ /** */ int Capnp2DbEngine::ParseParamsCount(IDBStoredProc *pProc, ::capnp::DynamicStruct::Reader& param) { int nCount = 0; for (auto field : param.getSchema().getFields()) { if (!param.has(field)) continue; ::capnp::schema::Type::Which which = field.getType().which(); switch (which) { case ::capnp::schema::Type::BOOL: case ::capnp::schema::Type::INT8: case ::capnp::schema::Type::INT16: case ::capnp::schema::Type::INT32: case ::capnp::schema::Type::INT64: case ::capnp::schema::Type::UINT8: case ::capnp::schema::Type::UINT16: case ::capnp::schema::Type::UINT32: case ::capnp::schema::Type::UINT64: case ::capnp::schema::Type::FLOAT32: case ::capnp::schema::Type::FLOAT64: case ::capnp::schema::Type::TEXT: case ::capnp::schema::Type::DATA: case ::capnp::schema::Type::ENUM: { ++nCount; break; } case ::capnp::schema::Type::STRUCT: { ::capnp::DynamicValue::Reader field_reader = param.get(field); ::capnp::DynamicStruct::Reader& subparam = field_reader.as<::capnp::DynamicStruct>(); nCount += ParseParamsCount(pProc, subparam); break; } default: break; } } return nCount; } //------------------------------------------------------------------------------ /** */ void Capnp2DbEngine::ParseParams(IDBStoredProc *pProc, ::capnp::DynamicStruct::Reader& param) { for (auto field : param.getSchema().getFields()) { if (!param.has(field)) continue; ::capnp::DynamicValue::Reader field_reader = param.get(field); const std::string &field_name = field.getProto().getName(); ::capnp::schema::Type::Which which = field.getType().which(); switch (which) { case ::capnp::schema::Type::BOOL: case ::capnp::schema::Type::INT8: case ::capnp::schema::Type::INT16: case ::capnp::schema::Type::INT32: case ::capnp::schema::Type::UINT8: case ::capnp::schema::Type::UINT16: case ::capnp::schema::Type::UINT32: { int32_t nVal = field_reader.as<int32_t>(); pProc->AddInputParameter((char *)field_name.c_str(), nVal); break; } case ::capnp::schema::Type::INT64: { int64_t nVal = field_reader.as<int64_t>(); pProc->AddInputInt64Parameter((char *)field_name.c_str(), nVal); break; } case ::capnp::schema::Type::UINT64: { // we use UINT64 as time_t time_t tmVal = (time_t)field_reader.as<uint64_t>(); pProc->AddInputParameter((char *)field_name.c_str(), tmVal); break; } case ::capnp::schema::Type::FLOAT32: case ::capnp::schema::Type::FLOAT64: { double dVal = field_reader.as<double>(); pProc->AddInputParameter((char *)field_name.c_str(), dVal); break; } case ::capnp::schema::Type::TEXT: { ::kj::StringPtr chars = field_reader.as<::capnp::Text>(); pProc->AddInputParameter((char *)field_name.c_str(), chars.cStr()); break; } case ::capnp::schema::Type::DATA: { ::kj::ArrayPtr<const kj::byte> bytes = field_reader.as<::capnp::Data>(); pProc->AddInputParameter((char *)field_name.c_str(), (unsigned char *)bytes.begin(), bytes.size()); break; } case ::capnp::schema::Type::ENUM: { auto enumValue = field_reader.as<::capnp::DynamicEnum>(); int nVal = enumValue.getRaw(); pProc->AddInputParameter((char *)field_name.c_str(), nVal); break; } case ::capnp::schema::Type::STRUCT: { ::capnp::DynamicStruct::Reader& subparam = field_reader.as<::capnp::DynamicStruct>(); ParseParams(pProc, subparam); break; } default: break; } } } //------------------------------------------------------------------------------ /** */ void Capnp2DbEngine::ParseResult(IDBResultSet& rs, ::capnp::StructSchema::Field& struct_schema_field, ::capnp::Orphanage& root_orphanage, ::capnp::DynamicStruct::Builder& parent_struct_builder) { ::capnp::Type& filed_type = struct_schema_field.getType(); if (filed_type.isList()) { ::capnp::ListSchema listType = filed_type.asList(); if (listType.getElementType().isStruct()) { ::capnp::StructSchema structElementType = listType.getStructElementType(); // std::array<int, 256> arrIndex = { 0 }; std::vector<::capnp::Orphan<::capnp::DynamicStruct> > vTmp; vTmp.reserve(256); // first get by name if (rs.MoveNext()) { int nIndex = 0; ::capnp::Orphan<::capnp::DynamicStruct> return_record_orphan = root_orphanage.newOrphan(structElementType); ::capnp::DynamicStruct::Builder& one_record = return_record_orphan.get(); AddFirstReturnRecord(rs, one_record, arrIndex, nIndex); vTmp.push_back(kj::mv(return_record_orphan)); } // more get by index while (rs.MoveNext()) { int nIndex = 0; ::capnp::Orphan<::capnp::DynamicStruct> return_record_orphan = root_orphanage.newOrphan(structElementType); ::capnp::DynamicStruct::Builder& one_record = return_record_orphan.get(); AddReturnRecord(rs, one_record, arrIndex, nIndex); vTmp.push_back(kj::mv(return_record_orphan)); } int nRows = vTmp.size(); if (nRows > 0) { ::capnp::DynamicList::Builder list_builder = parent_struct_builder.init(struct_schema_field, nRows).as<::capnp::DynamicList>(); // int i; for (i = 0; i < nRows; ++i) { list_builder.adopt(i, kj::mv(vTmp[i])); } } } } } //------------------------------------------------------------------------------ /** */ void Capnp2DbEngine::AddFirstReturnRecord(IDBResultSet& rs, ::capnp::DynamicStruct::Builder& return_record, std::array<int, 256>& arrIndex, int& nIndex) { int nFieldIndex = 0; for (auto field : return_record.getSchema().getFields()) { if (!return_record.has(field)) continue; const std::string &field_name = field.getProto().getName(); ::capnp::schema::Type::Which which = field.getType().which(); switch(which) { case ::capnp::schema::Type::BOOL: case ::capnp::schema::Type::INT8: case ::capnp::schema::Type::INT16: case ::capnp::schema::Type::INT32: case ::capnp::schema::Type::UINT8: case ::capnp::schema::Type::UINT16: case ::capnp::schema::Type::UINT32: { int32_t nVal = INT32_MIN; rs.GetFieldValue((char *)field_name.c_str(), &nVal, &nFieldIndex); return_record.set(field, nVal); break; } case ::capnp::schema::Type::INT64: { int64_t nVal = INT64_MIN; rs.GetFieldInt64Value((char *)field_name.c_str(), &nVal, &nFieldIndex); return_record.set(field, nVal); break; } case ::capnp::schema::Type::UINT64: { // we use UINT64 as time_t time_t tmVal = INT64_MIN; rs.GetFieldValue((char *)field_name.c_str(), &tmVal, &nFieldIndex); return_record.set(field, (uint64_t)tmVal); break; } case ::capnp::schema::Type::FLOAT32: { float fVal = FLT_MIN; rs.GetFieldFloatValue((char *)field_name.c_str(), &fVal, &nFieldIndex); return_record.set(field, fVal); break; } case ::capnp::schema::Type::FLOAT64: { double dVal = DBL_MIN; rs.GetFieldDoubleValue((char *)field_name.c_str(), &dVal, &nFieldIndex); return_record.set(field, dVal); break; } case ::capnp::schema::Type::TEXT: { const char *scratch; rs.GetFieldValue((char *)field_name.c_str(), &scratch, &nFieldIndex); return_record.set(field, scratch); break; } case ::capnp::schema::Type::DATA: { unsigned char *blob; long blobSize; rs.GetFieldValue((char *)field_name.c_str(), &blob, &blobSize, &nFieldIndex); return_record.set(field, ::capnp::Data::Reader(reinterpret_cast<const ::kj::byte*>(blob), (size_t)blobSize)); break; } case ::capnp::schema::Type::ENUM: { int nVal = INT_MIN; rs.GetFieldValue((char *)field_name.c_str(), &nVal, &nFieldIndex); return_record.set(field, nVal); break; } case ::capnp::schema::Type::STRUCT: { ::capnp::DynamicValue::Builder field_builder = return_record.get(field); AddFirstReturnRecord(rs, field_builder.as<::capnp::DynamicStruct>(), arrIndex, nIndex); break; } default: break; } // arrIndex[nIndex++] = nFieldIndex; } } //------------------------------------------------------------------------------ /** */ void Capnp2DbEngine::AddReturnRecord(IDBResultSet& rs, ::capnp::DynamicStruct::Builder& return_record, std::array<int, 256>& arrIndex, int& nIndex) { for (auto field : return_record.getSchema().getFields()) { if (!return_record.has(field)) continue; const std::string &field_name = field.getProto().getName(); ::capnp::schema::Type::Which which = field.getType().which(); switch (which) { case ::capnp::schema::Type::BOOL: case ::capnp::schema::Type::INT8: case ::capnp::schema::Type::INT16: case ::capnp::schema::Type::INT32: case ::capnp::schema::Type::UINT8: case ::capnp::schema::Type::UINT16: case ::capnp::schema::Type::UINT32: { int32_t nVal = INT32_MIN; rs.GetFieldValue(arrIndex[nIndex], &nVal); return_record.set(field, nVal); break; } case ::capnp::schema::Type::INT64: { int64_t nVal = INT64_MIN; rs.GetFieldInt64Value(arrIndex[nIndex], &nVal); return_record.set(field, nVal); break; } case ::capnp::schema::Type::UINT64: { // we use UINT64 as time_t time_t tmVal = INT64_MIN; rs.GetFieldValue(arrIndex[nIndex], &tmVal); return_record.set(field, (uint64_t)tmVal); break; } case ::capnp::schema::Type::FLOAT32: { float fVal = FLT_MIN; rs.GetFieldFloatValue(arrIndex[nIndex], &fVal); return_record.set(field, fVal); break; } case ::capnp::schema::Type::FLOAT64: { double dVal = DBL_MIN; rs.GetFieldDoubleValue(arrIndex[nIndex], &dVal); return_record.set(field, dVal); break; } case ::capnp::schema::Type::TEXT: { const char *scratch; rs.GetFieldValue(arrIndex[nIndex], &scratch); return_record.set(field, scratch); break; } case ::capnp::schema::Type::DATA: { unsigned char *blob; long blobSize; rs.GetFieldValue(arrIndex[nIndex], &blob, &blobSize); return_record.set(field, ::capnp::Data::Reader(reinterpret_cast<const ::kj::byte*>(blob), (size_t)blobSize)); break; } case ::capnp::schema::Type::ENUM: { int nVal = INT_MIN; rs.GetFieldValue(arrIndex[nIndex], &nVal); return_record.set(field, nVal); break; } case ::capnp::schema::Type::STRUCT: { ::capnp::DynamicValue::Builder field_builder = return_record.get(field); AddReturnRecord(rs, field_builder.as<::capnp::DynamicStruct>(), arrIndex, nIndex); break; } default: break; } // ++nIndex; } } /* -- EOF -- */
28.317604
190
0.617445
nneesshh
5009bc05bc1e84f9f371cc010c7b05ea1e65b80e
3,978
cpp
C++
src/Npfs/Resources/StdStringFile.cpp
joluxer/NpfsCpp
f19d422b9ab4fa67e35c1e0c29dfa2abc8b0d78f
[ "Zlib" ]
null
null
null
src/Npfs/Resources/StdStringFile.cpp
joluxer/NpfsCpp
f19d422b9ab4fa67e35c1e0c29dfa2abc8b0d78f
[ "Zlib" ]
null
null
null
src/Npfs/Resources/StdStringFile.cpp
joluxer/NpfsCpp
f19d422b9ab4fa67e35c1e0c29dfa2abc8b0d78f
[ "Zlib" ]
null
null
null
/* * StdStringFile.cpp * */ #include "StdStringFile.h" #include <string.h> #include <assert.h> namespace Npfs { StdStringFile::StdStringFile(const char* filename, Npfs::Directory* parent, std::string& storage, uint16_t umask) : Npfs::Resource(filename, parent), fileData(storage), updateHandler(0), changeHandler(0), truncHandler(0), modifiedHandler(0) { // deny all accesses stat.mode &= ~0777; stat.mode |= 0666 & ~umask; stat.setMode(stat.mode); } //StdStringFile::~StdStringFile() //{ // // Auto-generated destructor stub //} void * StdStringFile::IoRefState::operator new(size_t size) throw() { return new unsigned char[size]; } void StdStringFile::IoRefState::operator delete(void *mem) throw() { delete[] (unsigned char*)mem; } Npfs::Resource::ResultMessage StdStringFile::open(Npfs::OpenIoState& workRef, uint8_t mode, uint32_t& iounit) { ResultMessage result = 0; setNewSize(fileData.length()); if (!updateHandler || updateHandler->execute(fileData, stat.length)) { IoRefState* ioRef = new IoRefState; if (!handleNoMemory(ioRef, result)) { ioRef->isWritten = false; workRef.ioState = ioRef; result = OpSuccess; } else { result = NoMemory; } } return result; } Npfs::Resource::ResultMessage StdStringFile::read(Npfs::OpenIoState& workRef, unsigned char* dataBuffer, uint32_t& count, uint64_t offset) // in count will be returned the actual read amount of data { ResultMessage result = OpSuccess; setNewSize(fileData.length()); if (stat.length <= offset) { // nichts kann gelesen werden count = 0; } // sonst ist die volle Menge lesbar if (count) count = fileData.copy((char*) dataBuffer, count, offset); return result; } Npfs::Resource::ResultMessage StdStringFile::write(Npfs::OpenIoState& workRef, const unsigned char* dataBuffer, uint32_t& count, uint64_t offset) { ResultMessage result = OpSuccess; IoRefState* ioRef = static_cast<IoRefState*>(workRef.ioState); if (fileData.length() < (offset + count)) { fileData.reserve(offset + count); fileData.append((offset + count) - fileData.length(), 0); ioRef->isWritten = true; } if (count) { fileData.replace(offset, count, (const char*) dataBuffer, count); // Datei-Laenge bearbeiten setNewSize(fileData.length()); stat.qid.version++; ioRef->isWritten = true; if (modifiedHandler) { uint32_t countCopy = count; // needed, as the handler is allowed to modify the value, but we want to ignore these changes. uint64_t offsetCopy = offset; // needed, as the handler is allowed to modify the value, but we want to ignore these changes. modifiedHandler->notify(fileData, countCopy, offsetCopy); } } return result; } void StdStringFile::flush(Npfs::OpenIoState& workRef) { // intentionally left empty } Npfs::Resource::ResultMessage StdStringFile::close(Npfs::OpenIoState& workRef) { ResultMessage result = OpSuccess; IoRefState* ioRef = static_cast<IoRefState*>(workRef.ioState); setNewSize(fileData.length()); if (ioRef->isWritten) { if (!changeHandler || changeHandler->notify(fileData, stat.length)) { delete ioRef; workRef.ioState = ioRef = 0; } else { result = 0; } } else { delete ioRef; workRef.ioState = ioRef = 0; } return result; } Npfs::Resource::ResultMessage StdStringFile::trunc(Npfs::BlockingOpState* &workRef, uint64_t newLength) { ResultMessage result = 0; if (truncHandler) { if (truncHandler->notify(fileData, newLength)) { fileData.erase(newLength); setNewSize(fileData.length()); result = OpSuccess; } } else { fileData.erase(newLength); setNewSize(fileData.length()); result = OpSuccess; } return result; } const NpStat& StdStringFile::getStat() { setNewSize(fileData.length()); return Resource::getStat(); } }
21.857143
199
0.672448
joluxer
500b7fdd8572a9a1a4b1f2b78aba99ab17a8ab64
361
cpp
C++
util.cpp
fightling/decklink-debugger
796be29a62a02593cf7b53e695b2f53f04a2fc75
[ "MIT" ]
18
2018-01-07T19:19:59.000Z
2021-12-27T14:11:32.000Z
util.cpp
fightling/decklink-debugger
796be29a62a02593cf7b53e695b2f53f04a2fc75
[ "MIT" ]
8
2018-01-10T23:28:11.000Z
2021-07-15T22:12:50.000Z
util.cpp
fightling/decklink-debugger
796be29a62a02593cf7b53e695b2f53f04a2fc75
[ "MIT" ]
10
2018-05-10T19:53:30.000Z
2020-12-05T11:54:20.000Z
#include "util.h" #include "log.h" void throwIfNotOk(HRESULT result, const char* message) { if(result != S_OK) { LOG(ERROR) << "result (=0x" << std::hex << result << ") != S_OK, " << message; throw message; } } void throwIfNull(void* ptr, const char* message) { if(ptr == nullptr) { LOG(ERROR) << "ptr == nullptr, " << message; throw message; } }
19
80
0.603878
fightling
500f9e1313fc7facaffc9c3141733bb0f5f3593b
3,119
cpp
C++
gecode/circuit_orbit.cpp
Wikunia/hakank
030bc928d2efe8dcbc5118bda3f8ae9575d0fd13
[ "MIT" ]
279
2015-01-10T09:55:35.000Z
2022-03-28T02:34:03.000Z
gecode/circuit_orbit.cpp
Wikunia/hakank
030bc928d2efe8dcbc5118bda3f8ae9575d0fd13
[ "MIT" ]
10
2017-10-05T15:48:50.000Z
2021-09-20T12:06:52.000Z
gecode/circuit_orbit.cpp
Wikunia/hakank
030bc928d2efe8dcbc5118bda3f8ae9575d0fd13
[ "MIT" ]
83
2015-01-20T03:44:00.000Z
2022-03-13T23:53:06.000Z
/* Global constraint circuit using "orbits" in Gecode. The following model implements the constraint circuit using permutation orbits of the first element in the array (x). (It was created when playing around with some other problem in MiniZinc.) For more about the circuit constraint, see the Global Constraint Catalog: http://www.emn.fr/x-info/sdemasse/gccat/Ccircuit.html Comparing with the simple model using the Gecode's builtin circuit // .... circuit(*this, x, n-1, opt.icl()); branch(*this, x, INT_VAR_SIZE_MIN, INT_VAL_MIN); // ... the two models has the same statistics: - 0 failures - peak depth - nodes But not the same number of propagations, which is probably not a surprise. Via occular investigation Gist it seems that they have the same search tree. However, the order of solutions are not identical in the two models (given the same branchings). Compare with the MiniZinc model: * MiniZinc: http://www.hakank.org/minizinc/circuit_test.mzn Note: The MiniZinc model is 1-based, this Gecode model is 0-based. This Gecode model was created by Hakan Kjellerstrand (hakank@gmail.com) Also, see my Gecode page: http://www.hakank.org/gecode/ . */ #include <gecode/driver.hh> #include <gecode/int.hh> #include <gecode/minimodel.hh> using namespace Gecode; void circuit_orbit(Space &space, IntVarArray x, IntConLevel icl = ICL_BND) { int n = x.size(); /** * z is an temporary array which contains the orbits of x[0]. * * Basic condition: z[i] must not be 0 until i = n-1 and * then it must be 0 */ // IntVarArray z(*this, n, 0, n-1); IntVarArray z(space, n, 0, n-1); distinct(space, x, icl); distinct(space, z, icl); // put the orbit of x[0] in in z[1..n] rel(space, z[0] == x[0], icl); for(int i = 1; i < n; i++) { // z[i] = x[z[i-1]] // element(space, x, z[i-1], z[i], icl); rel(space, z[i] == element(x, z[i-1])); } // may not be 0 for i < n-1 for(int i = 0; i < n-1; i++) { rel(space, z[i] != 0, icl); } // when i = n-1 it must be 0 rel(space, z[n-1] == 0, icl); } class CircuitOrbit : public Script { protected: const int n; // size of problem IntVarArray x; // the array public: CircuitOrbit(const SizeOptions& opt) : n(opt.size()), x(*this, n, 0, n-1) { circuit_orbit(*this, x, opt.icl()); branch(*this, x, INT_VAR_DEGREE_MIN(), INT_VAL_SPLIT_MIN()); } // Print solution virtual void print(std::ostream& os) const { os << "\t" << x << std::endl; } // Constructor for cloning s CircuitOrbit(bool share, CircuitOrbit& s) : Script(share,s), n(s.n) { x.update(*this, share, s.x); } // Copy during cloning virtual Space* copy(bool share) { return new CircuitOrbit(share,*this); } }; int main(int argc, char* argv[]) { SizeOptions opt("CircuitOrbit"); opt.solutions(1); opt.icl(ICL_VAL); opt.parse(argc,argv); if (!opt.size()) { opt.size(100); } opt.c_d(opt.size()*2); Script::run<CircuitOrbit,DFS,SizeOptions>(opt); return 0; }
21.964789
78
0.633216
Wikunia
5010e8dc531979476c8bd20d4159bf090ef09f8d
518
hpp
C++
WorldEditor/Tool.hpp
madeso/infection-survivors
654fc5405dcecccaa7e54f1fdbfec379e0c185da
[ "Zlib" ]
null
null
null
WorldEditor/Tool.hpp
madeso/infection-survivors
654fc5405dcecccaa7e54f1fdbfec379e0c185da
[ "Zlib" ]
null
null
null
WorldEditor/Tool.hpp
madeso/infection-survivors
654fc5405dcecccaa7e54f1fdbfec379e0c185da
[ "Zlib" ]
null
null
null
#ifndef LLW_TOOL_HPP #define LLW_TOOL_HPP #include "lunarlady/math/vec2.hpp" #include "wx.hpp" #include "WorldEditor/ToolAction.hpp" class WorldView; class World; class Tool { public: Tool(WorldView* iWorldView, ToolAction iToolAction); virtual ~Tool() {} virtual bool onInput(const ::lunarlady::math::vec2& movement, wxMouseEvent& event) = 0; ToolAction getToolAction() const; protected: WorldView& getWorldView(); World& getWorld(); private: WorldView* mWorldView; const ToolAction mToolAction; }; #endif
20.72
88
0.760618
madeso
5012af5bc7f8726f86cf7e515e89e54fbed12019
6,365
cpp
C++
src/tools/mdReader.cpp
xinhaixiangyunpiao/SmartPipe
5d26e642224108b65f21456cbc41fcc48afe1934
[ "MIT" ]
2
2021-12-08T03:45:43.000Z
2021-12-08T13:43:02.000Z
src/tools/mdReader.cpp
xinhaixiangyunpiao/SmartPipe
5d26e642224108b65f21456cbc41fcc48afe1934
[ "MIT" ]
null
null
null
src/tools/mdReader.cpp
xinhaixiangyunpiao/SmartPipe
5d26e642224108b65f21456cbc41fcc48afe1934
[ "MIT" ]
null
null
null
#include <fstream> #include <iostream> #include <cassert> #include "mdReader.h" namespace sp{ MDReader::MDReader(std::string path){ this->path = path; std::ifstream fin(path); if(!fin.is_open()){ std::cout << "app file not opened." << std::endl; } assert(fin.is_open()); char c; char last; std::string name = ""; std::string s = ""; fin >> c; std::vector<std::vector<std::string>> v; std::vector<std::string> line; while(true){ while(fin >> c){ // 解析表名 if(c == ':'){ name = s; s = ""; break; } s += c; } if(fin >> c && c != '|') // 文件末尾 break; bool endFlag = false; while(true){ if(endFlag) break; bool clFlag = false; while(true){ if(clFlag) break; while(fin >> c){ if(c == '|' && last == '|'){ // 一行结束 clFlag = true; if(!line.empty()) v.push_back(line); line.clear(); break; }else if(c == '|'){ // 一个内容结束 bool empty = true; for(int i = 0; i < s.size(); i++) if(s[i] != '-'){ empty = false; break; } if(!empty) line.push_back(s); s = ""; last = c; break; }else if(c == '#'){ // 一个表结束 clFlag = true; endFlag = true; if(!line.empty()) v.push_back(line); m[name] = v; v.clear(); line.clear(); break; } s += c; last = c; } } } } fin.close(); genFsTable(); genDeployTable(); printFsTable(); printDeployTable(); } MDReader::~MDReader(){ } void MDReader::printM(){ for(auto i : m){ std::cout << i.first << ":" << std::endl; for(int j = 0; j < i.second.size(); j++){ for(int k = 0; k < i.second[0].size(); k++){ std::cout << i.second[j][k] << " "; } std::cout << std::endl; } std::cout << std::endl; } } void MDReader::printFsTable(){ for(auto i : Fs_table){ std::cout << "Function Name: " << std::get<0>(i) << " pre_Qs: "; for(auto j : std::get<1>(i)) std::cout << j << " "; std::cout << "next_Qs: "; for(auto j : std::get<2>(i)) std::cout << j << " "; std::cout << "Params: "; for(auto j : std::get<3>(i)) std::cout << j << " "; std::cout << std::endl; } } void MDReader::printDeployTable(){ for(auto i : D_table){ std::cout << "lcore id: " << i.first << " functions: "; for(auto j : i.second) std::cout << j << " "; std::cout << std::endl; } } void MDReader::genFsTable(){ assert(m["tasks"].size() >= 1); // gen function table for(int i = 1; i < m["tasks"].size(); i++){ std::vector<int> pre_Qs, next_Qs; std::string function_name = ""; std::vector<std::string> params; /** pre_Qs **/ if(m["tasks"][i][1] == "None"){ // 输入队列组为空 }else{ int id = 0; for(int j = 0; j < m["tasks"][i][1].size(); j++){ if(m["tasks"][i][1][j] >= '0' && m["tasks"][i][1][j] <= '9'){ id *= 10; id += m["tasks"][i][1][j] - '0'; }else if(m["tasks"][i][1][j] == ','){ pre_Qs.push_back(id); id = 0; } } pre_Qs.push_back(id); } /** next_Qs **/ if(m["tasks"][i][2] == "None"){ // 输出队列组为空 }else{ int id = 0; for(int j = 0; j < m["tasks"][i][2].size(); j++){ if(m["tasks"][i][2][j] >= '0' && m["tasks"][i][2][j] <= '9'){ id *= 10; id += m["tasks"][i][2][j] - '0'; }else if(m["tasks"][i][2][j] == ','){ next_Qs.push_back(id); id = 0; } } next_Qs.push_back(id); } /** Function name **/ function_name = m["tasks"][i][3]; /** param **/ std::string cur = ""; for(int j = 0; j < m["tasks"][i][4].size(); j++){ if(m["tasks"][i][4][j] == ','){ if(cur != ""){ if(cur != "" && cur != "None") params.push_back(cur); cur = ""; } }else cur += m["tasks"][i][4][j]; } if(cur != "" && cur != "None") params.push_back(cur); /** add to FsTable */ Fs_table.push_back(std::make_tuple(function_name, pre_Qs, next_Qs, params)); } } void MDReader::genDeployTable(){ assert(m["deploy"].size() >= 1); for(int i = 1; i < m["deploy"].size(); i++){ int lcore_id = atoi(m["deploy"][i][0].c_str()); std::vector<int> tasks_id_vec; int task_id = 0; for(int j = 0; j < m["deploy"][i][1].size(); j++){ if(m["deploy"][i][1][j] >= '0' && m["deploy"][i][1][j] <= '9'){ task_id *= 10; task_id += m["deploy"][i][1][j] - '0'; }else if(m["deploy"][i][1][j] == ','){ tasks_id_vec.push_back(task_id); task_id = 0; } } tasks_id_vec.push_back(task_id); D_table[lcore_id] = tasks_id_vec; } } std::vector<std::tuple<std::string, std::vector<int>, std::vector<int>, std::vector<std::string>>> MDReader::getFsTable(){ return Fs_table; } std::map<int, std::vector<int>> MDReader::getDeployTable(){ return D_table; } };
30.023585
122
0.364179
xinhaixiangyunpiao
50149195e681700189c64bb8a73d45c5fd83539a
63,015
cpp
C++
Dodo-Engine/code/renderer/Renderer.cpp
TKscoot/Dodo-Engine
ba6c56a898d2e07e0fd7e89161cbdafd8bc02abd
[ "MIT" ]
null
null
null
Dodo-Engine/code/renderer/Renderer.cpp
TKscoot/Dodo-Engine
ba6c56a898d2e07e0fd7e89161cbdafd8bc02abd
[ "MIT" ]
null
null
null
Dodo-Engine/code/renderer/Renderer.cpp
TKscoot/Dodo-Engine
ba6c56a898d2e07e0fd7e89161cbdafd8bc02abd
[ "MIT" ]
null
null
null
#include "dodopch.h" #include "Renderer.h" using namespace Dodo::Environment; bool Dodo::Rendering::CRenderer::m_bFramebufferResized = false; DodoError Dodo::Rendering::CRenderer::Initialize(std::shared_ptr<VKIntegration> _integration, std::shared_ptr<CWindow> _window) { m_pIntegration = _integration; m_pWindow = _window; CreateSwapChain(); CreateImageViews(); CreateRenderPass(); CreateDescriptorSetLayout(); CreateGraphicsPipeline(); CreateCommandPool(); CreateDepthResources(); CreateFramebuffers(); CreateTextureImages(); CreateTextureImageViews(); CreateTextureSampler(); CreateVertexBuffers(); CreateIndexBuffers(); CreateUniformBuffers(); CreateDescriptorPool(); CreateDescriptorSets(); // GUI m_pGui = std::make_shared<Rendering::GUI>(m_pIntegration, &m_pCamera->cameraPos, &m_pCamera->cameraFront, m_pCamera->camSpeed); m_pGui->CreateRenderPass(m_vkSwapChainImageFormat, FindDepthFormat()); m_pGui->CreateFramebuffers(m_vkSwapChainImageViews, m_vkDepthImageView, m_vkSwapChainExtent); m_pGui->Initialize(m_vkRenderPass, m_vkSwapChainExtent.width, m_vkSwapChainExtent.height); // Skybox m_pSkybox = std::make_shared<CSkybox>(m_pIntegration, m_vkRenderPass, m_vkCommandPool, m_vkSwapChainExtent); m_pSkybox->Initialize(); // ShadowMap m_pShadowMap = std::make_shared<CShadowMapping>(m_pIntegration, m_pCamera); m_pShadowMap->Initialize(); CreateCommandBuffers(); CreateSyncObjects(); return DODO_OK; } DodoError Dodo::Rendering::CRenderer::DrawFrame(double deltaTime) { DodoError result = DODO_INITIALIZATION_FAILED; VkResult vkResult = VK_ERROR_INITIALIZATION_FAILED; uint32_t imageIndex = 0; vkResult = vkWaitForFences(m_pIntegration->device(), 1, &m_sSyncObjects.inFlightFences[m_iCurrentFrame], VK_TRUE, std::numeric_limits<uint64_t>::max()); CError::CheckError<VkResult>(vkResult); vkResult = vkResetFences(m_pIntegration->device(), 1, &m_sSyncObjects.inFlightFences[m_iCurrentFrame]); CError::CheckError<VkResult>(vkResult); vkResult = vkAcquireNextImageKHR(m_pIntegration->device(), m_vkSwapChain, std::numeric_limits<uint64_t>::max(), m_sSyncObjects.imageAvailableSemaphores[m_iCurrentFrame], VK_NULL_HANDLE, &imageIndex); // check if swapchain needs to be recreated if (vkResult == VK_ERROR_OUT_OF_DATE_KHR || vkResult == VK_SUBOPTIMAL_KHR || m_bFramebufferResized) { m_bFramebufferResized = false; RecreateSwapChain(); } else { CError::CheckError<VkResult>(vkResult); } // Update uniform buffers here!! UpdateUniformBuffer(); m_pSkybox->UpdateUniformBuffer(m_pCamera); m_pShadowMap->UpdateUniformBuffer(); VkSubmitInfo submitInfo = {}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; std::vector<VkSemaphore> waitSemaphores = { m_sSyncObjects.imageAvailableSemaphores[m_iCurrentFrame] }; std::vector<VkPipelineStageFlags> waitStages = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT }; std::vector<VkCommandBuffer> commandBuffers; if (m_bDrawGui) { commandBuffers = { m_vkCommandBuffers.at(imageIndex), m_pGui->m_vkCommandBuffers.at(imageIndex) }; } else { commandBuffers = { m_vkCommandBuffers.at(imageIndex)}; } submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = waitSemaphores.data(); submitInfo.pWaitDstStageMask = waitStages.data(); submitInfo.commandBufferCount = commandBuffers.size(); submitInfo.pCommandBuffers = commandBuffers.data(); std::vector<VkSemaphore> signalSemaphores = { m_sSyncObjects.renderFinishedSemaphores[m_iCurrentFrame] }; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = signalSemaphores.data(); vkResetFences(m_pIntegration->device(), 1, &m_sSyncObjects.inFlightFences[m_iCurrentFrame]); vkResult = vkQueueSubmit(m_pIntegration->queues().graphicsQueue, 1, &submitInfo, m_sSyncObjects.inFlightFences[m_iCurrentFrame]); CError::CheckError<VkResult>(vkResult); VkPresentInfoKHR presentInfo = {}; presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; presentInfo.waitSemaphoreCount = 1; presentInfo.pWaitSemaphores = signalSemaphores.data(); presentInfo.swapchainCount = 1; presentInfo.pSwapchains = &m_vkSwapChain; presentInfo.pImageIndices = &imageIndex; presentInfo.pResults = nullptr; vkResult = vkQueuePresentKHR(m_pIntegration->queues().presentQueue, &presentInfo); CError::CheckError<VkResult>(vkResult); m_fFrameTimeCounter += deltaTime; if (m_bDrawGui) { if (vkWaitForFences(m_pIntegration->device(), 1, &m_sSyncObjects.inFlightFences[m_iCurrentFrame], VK_TRUE, std::numeric_limits<uint64_t>::max()) == VK_SUCCESS) { //UpdateCommandBuffers(); if (m_fFrameTimeCounter >= 1.0f) { m_pGui->NewFrame(deltaTime, true); m_fFrameTimeCounter = 0.0f; } else { m_pGui->NewFrame(deltaTime, false); } if (m_pGui->UpdateBuffers()) { m_pGui->DrawFrame(m_vkSwapChainExtent, m_vkRenderPass, m_vkSwapChainFramebuffers, deltaTime); } } } m_iCurrentFrame = (m_iCurrentFrame + 1) % MAX_FRAMES_IN_FLIGHT; result = DODO_OK; return result; } DodoError Dodo::Rendering::CRenderer::Finalize() { CleanupSwapChain(); m_pGui->Finalize(); for (auto &mat : m_pMaterials) { mat->Finalize(); } vkDestroyDescriptorSetLayout(m_pIntegration->device(), m_vkDescriptorSetLayout, nullptr); for (auto &mesh : m_pMeshes) { vkDestroyBuffer(m_pIntegration->device(), mesh->m_dataBuffers.indexBuffer, nullptr); vkFreeMemory(m_pIntegration->device(), mesh->m_dataBuffers.indexBufferMemory, nullptr); vkDestroyBuffer(m_pIntegration->device(), mesh->m_dataBuffers.vertexBuffer, nullptr); vkFreeMemory(m_pIntegration->device(), mesh->m_dataBuffers.vertexBufferMemory, nullptr); } for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { vkDestroySemaphore(m_pIntegration->device(), m_sSyncObjects.renderFinishedSemaphores[i], nullptr); vkDestroySemaphore(m_pIntegration->device(), m_sSyncObjects.imageAvailableSemaphores[i], nullptr); vkDestroyFence(m_pIntegration->device(), m_sSyncObjects.inFlightFences[i], nullptr); } vkDestroyCommandPool(m_pIntegration->device(), m_vkCommandPool, nullptr); m_pIntegration->Finalize(); return DODO_OK; } VkResult Dodo::Rendering::CRenderer::CreateSwapChain() { VkResult result = VK_ERROR_INITIALIZATION_FAILED; SwapChainSupportDetails swapChainDetails = QuerySwapChainSupport(); VkSurfaceFormatKHR surfaceFormat = ChooseSwapSurfaceFormat(swapChainDetails.formats); VkPresentModeKHR presentMode = ChooseSwapPresentMode(swapChainDetails.presentModes); VkExtent2D extent = ChooseSwapExtent(swapChainDetails.capabilities); // Number of images in the swap chain uint32_t imageCount = swapChainDetails.capabilities.minImageCount + 1; if (swapChainDetails.capabilities.maxImageCount > 0 && imageCount > swapChainDetails.capabilities.maxImageCount) { imageCount = swapChainDetails.capabilities.maxImageCount; } VkSwapchainCreateInfoKHR createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; createInfo.surface = m_pIntegration->surface(); createInfo.minImageCount = imageCount; createInfo.imageFormat = surfaceFormat.format; createInfo.imageColorSpace = surfaceFormat.colorSpace; createInfo.imageExtent = extent; createInfo.imageArrayLayers = 1; createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; //uint32_t queueFamilyIndices[] = { // (uint32_t)m_pIntegration->queueFamilies().graphicsQueueFamilyIndices, // (uint32_t)m_pIntegration->queueFamilies().presentQueueFamilyIndices }; std::vector<uint32_t> queueFamilyIndices(2); queueFamilyIndices = { (uint32_t)m_pIntegration->queueFamilies().graphicsQueueFamilyIndices, (uint32_t)m_pIntegration->queueFamilies().presentQueueFamilyIndices }; if (m_pIntegration->queueFamilies().graphicsQueueFamilyIndices != m_pIntegration->queueFamilies().presentQueueFamilyIndices) { createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT; createInfo.queueFamilyIndexCount = queueFamilyIndices.size(); createInfo.pQueueFamilyIndices = queueFamilyIndices.data(); } else { createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; } createInfo.preTransform = swapChainDetails.capabilities.currentTransform; createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; createInfo.presentMode = presentMode; createInfo.clipped = VK_TRUE; result = vkCreateSwapchainKHR(m_pIntegration->device(), &createInfo, nullptr, &m_vkSwapChain); CError::CheckError<VkResult>(result); result = vkGetSwapchainImagesKHR(m_pIntegration->device(), m_vkSwapChain, &imageCount, nullptr); m_vkSwapChainImages.resize(imageCount); result = vkGetSwapchainImagesKHR(m_pIntegration->device(), m_vkSwapChain, &imageCount, m_vkSwapChainImages.data()); m_vkSwapChainImageFormat = surfaceFormat.format; m_vkSwapChainExtent = extent; return result; } VkImageView Dodo::Rendering::CRenderer::CreateImageView(VkImage image, VkFormat format, VkImageAspectFlags aspectFlags) { VkImageViewCreateInfo viewInfo = {}; viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; viewInfo.image = image; viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; viewInfo.format = format; viewInfo.subresourceRange.aspectMask = aspectFlags; viewInfo.subresourceRange.baseMipLevel = 0; viewInfo.subresourceRange.levelCount = 1; viewInfo.subresourceRange.baseArrayLayer = 0; viewInfo.subresourceRange.layerCount = 1; VkImageView imageView; if (vkCreateImageView(m_pIntegration->device(), &viewInfo, nullptr, &imageView) != VK_SUCCESS) { throw std::runtime_error("failed to create texture image view!"); } return imageView; } VkResult Dodo::Rendering::CRenderer::CreateTextureImage(Components::CMaterial::Texture &_texture) { VkResult result = VK_ERROR_INITIALIZATION_FAILED; VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; VkDeviceSize imageSize = _texture.texWidth * _texture.texHeight * 4; result = CreateBuffer(imageSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); void* data; vkMapMemory(m_pIntegration->device(), stagingBufferMemory, 0, imageSize, 0, &data); memcpy(data, _texture.pixels, static_cast<size_t>(imageSize)); vkUnmapMemory(m_pIntegration->device(), stagingBufferMemory); stbi_image_free(_texture.pixels); result = CreateImage( _texture.texWidth, _texture.texHeight, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, _texture.textureData.textureImage, _texture.textureData.textureImageMemory); result = TransitionImageLayout( _texture.textureData.textureImage, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); result = CopyBufferToImage( stagingBuffer, _texture.textureData.textureImage, static_cast<uint32_t>(_texture.texWidth), static_cast<uint32_t>(_texture.texHeight)); result = TransitionImageLayout( _texture.textureData.textureImage, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); vkDestroyBuffer(m_pIntegration->device(), stagingBuffer, nullptr); vkFreeMemory(m_pIntegration->device(), stagingBufferMemory, nullptr); return result; } VkResult Dodo::Rendering::CRenderer::CreateImageViews() { VkResult result = VK_ERROR_INITIALIZATION_FAILED; m_vkSwapChainImageViews.resize(m_vkSwapChainImages.size()); for (size_t i = 0; i < m_vkSwapChainImages.size(); i++) { m_vkSwapChainImageViews[i] = CreateImageView( m_vkSwapChainImages[i], m_vkSwapChainImageFormat, VK_IMAGE_ASPECT_COLOR_BIT); } return result; } VkResult Dodo::Rendering::CRenderer::CreateRenderPass() { VkResult result = VK_ERROR_INITIALIZATION_FAILED; VkAttachmentDescription colorAttachment = {}; colorAttachment.format = m_vkSwapChainImageFormat; colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT; colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; VkAttachmentDescription depthAttachment = {}; depthAttachment.format = FindDepthFormat(); depthAttachment.samples = VK_SAMPLE_COUNT_1_BIT; depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; VkAttachmentReference colorAttachmentRef = {}; colorAttachmentRef.attachment = 0; colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkAttachmentReference depthAttachmentRef = {}; depthAttachmentRef.attachment = 1; depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; VkSubpassDescription subpass = {}; subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass.colorAttachmentCount = 1; subpass.pColorAttachments = &colorAttachmentRef; subpass.pDepthStencilAttachment = &depthAttachmentRef; VkSubpassDependency dependency = {}; dependency.srcSubpass = VK_SUBPASS_EXTERNAL; dependency.dstSubpass = 0; dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.srcAccessMask = 0; dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; std::array<VkAttachmentDescription, 2> attachments = { colorAttachment, depthAttachment }; 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; renderPassInfo.dependencyCount = 1; renderPassInfo.pDependencies = &dependency; result = vkCreateRenderPass(m_pIntegration->device(), &renderPassInfo, nullptr, &m_vkRenderPass); CError::CheckError<VkResult>(result); return result; } VkResult Dodo::Rendering::CRenderer::CreateDescriptorSetLayout() { VkResult result = VK_ERROR_INITIALIZATION_FAILED; VkDescriptorSetLayoutBinding uboLayoutBinding = {}; uboLayoutBinding.binding = 0; uboLayoutBinding.descriptorCount = 1; uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; uboLayoutBinding.pImmutableSamplers = nullptr; // image sampling related uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT; //VkDescriptorSetLayoutCreateInfo layoutInfo = {}; //layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; //layoutInfo.bindingCount = 1; //layoutInfo.pBindings = &uboLayoutBinding; VkDescriptorSetLayoutBinding albedoSamplerLayoutBinding = {}; albedoSamplerLayoutBinding.binding = 1; albedoSamplerLayoutBinding.descriptorCount = 1; albedoSamplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; albedoSamplerLayoutBinding.pImmutableSamplers = nullptr; albedoSamplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; VkDescriptorSetLayoutBinding normalSamplerLayoutBinding = {}; normalSamplerLayoutBinding.binding = 2; normalSamplerLayoutBinding.descriptorCount = 1; normalSamplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; normalSamplerLayoutBinding.pImmutableSamplers = nullptr; normalSamplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; VkDescriptorSetLayoutBinding metallicSamplerLayoutBinding = {}; metallicSamplerLayoutBinding.binding = 3; metallicSamplerLayoutBinding.descriptorCount = 1; metallicSamplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; metallicSamplerLayoutBinding.pImmutableSamplers = nullptr; metallicSamplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; VkDescriptorSetLayoutBinding roughnessSamplerLayoutBinding = {}; roughnessSamplerLayoutBinding.binding = 4; roughnessSamplerLayoutBinding.descriptorCount = 1; roughnessSamplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; roughnessSamplerLayoutBinding.pImmutableSamplers = nullptr; roughnessSamplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; VkDescriptorSetLayoutBinding lightUboLayoutBinding = {}; lightUboLayoutBinding.binding = 5; lightUboLayoutBinding.descriptorCount = 1; lightUboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; lightUboLayoutBinding.pImmutableSamplers = nullptr; // image sampling related lightUboLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; std::array<VkDescriptorSetLayoutBinding, 6> bindings = { uboLayoutBinding, albedoSamplerLayoutBinding, normalSamplerLayoutBinding, metallicSamplerLayoutBinding, roughnessSamplerLayoutBinding, lightUboLayoutBinding }; VkDescriptorSetLayoutCreateInfo layoutInfo = {}; layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size()); layoutInfo.pBindings = bindings.data(); result = vkCreateDescriptorSetLayout(m_pIntegration->device(), &layoutInfo, nullptr, &m_vkDescriptorSetLayout); CError::CheckError<VkResult>(result); return result; } VkResult Dodo::Rendering::CRenderer::CreateGraphicsPipeline() { VkResult result = VK_ERROR_INITIALIZATION_FAILED; std::vector<VkPipelineShaderStageCreateInfo> shaderStages; //for (auto material : m_pMaterials) //{ m_pMaterials[0]->CreateShaders(); VkPipelineShaderStageCreateInfo vertShaderStageInfo = {}; vertShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT; vertShaderStageInfo.module = m_pMaterials[0]->shaders().vertShaderStage.module; vertShaderStageInfo.pName = "main"; shaderStages.push_back(vertShaderStageInfo); VkPipelineShaderStageCreateInfo fragShaderStageInfo = {}; fragShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT; fragShaderStageInfo.module = m_pMaterials[0]->shaders().fragShaderStage.module; fragShaderStageInfo.pName = "main"; shaderStages.push_back(fragShaderStageInfo); //} auto bindingDescriptions = CMaterial::GetBindingDescription(); auto attributeDescriptions = CMaterial::GetAttributeDescriptions(); VkPipelineVertexInputStateCreateInfo vertexInputInfo = {}; vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vertexInputInfo.vertexBindingDescriptionCount = 1; vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(attributeDescriptions.size()); vertexInputInfo.pVertexBindingDescriptions = &bindingDescriptions; vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions.data(); VkPipelineInputAssemblyStateCreateInfo inputAssembly = {}; inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; inputAssembly.primitiveRestartEnable = VK_FALSE; VkViewport viewport = {}; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = (float)m_vkSwapChainExtent.width; viewport.height = (float)m_vkSwapChainExtent.height; viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor = {}; scissor.offset = { 0, 0 }; scissor.extent = m_vkSwapChainExtent; VkPipelineViewportStateCreateInfo viewportState = {}; viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewportState.viewportCount = 1; viewportState.pViewports = &viewport; viewportState.scissorCount = 1; viewportState.pScissors = &scissor; VkPipelineRasterizationStateCreateInfo rasterizer = {}; rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rasterizer.depthClampEnable = VK_FALSE; rasterizer.rasterizerDiscardEnable = VK_FALSE; rasterizer.polygonMode = VK_POLYGON_MODE_FILL; rasterizer.lineWidth = 1.0f; rasterizer.cullMode = VK_CULL_MODE_BACK_BIT; rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; rasterizer.depthBiasEnable = VK_FALSE; rasterizer.depthBiasConstantFactor = 0.0f; // Optional rasterizer.depthBiasClamp = 0.0f; // Optional rasterizer.depthBiasSlopeFactor = 0.0f; // Optional VkPipelineMultisampleStateCreateInfo multisampling = {}; multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; multisampling.sampleShadingEnable = VK_FALSE; multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; multisampling.minSampleShading = 1.0f; // Optional multisampling.pSampleMask = nullptr; // Optional multisampling.alphaToCoverageEnable = VK_FALSE; // Optional multisampling.alphaToOneEnable = VK_FALSE; // Optional VkPipelineDepthStencilStateCreateInfo depthStencil = {}; depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; depthStencil.depthTestEnable = VK_TRUE; depthStencil.depthWriteEnable = VK_TRUE; depthStencil.depthCompareOp = VK_COMPARE_OP_LESS; depthStencil.depthBoundsTestEnable = VK_FALSE; depthStencil.stencilTestEnable = VK_FALSE; depthStencil.minDepthBounds = 0.0f; // Optional depthStencil.maxDepthBounds = 1.0f; // Optional depthStencil.stencilTestEnable = VK_FALSE; depthStencil.front = {}; // Optional depthStencil.back = {}; // Optional VkPipelineColorBlendAttachmentState colorBlendAttachment = {}; colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; colorBlendAttachment.blendEnable = VK_FALSE; colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; // Optional colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; // Optional colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; // Optional colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; // Optional VkPipelineColorBlendStateCreateInfo colorBlending = {}; colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; colorBlending.logicOpEnable = VK_FALSE; colorBlending.logicOp = VK_LOGIC_OP_COPY; colorBlending.attachmentCount = 1; colorBlending.pAttachments = &colorBlendAttachment; colorBlending.blendConstants[0] = 0.0f; colorBlending.blendConstants[1] = 0.0f; colorBlending.blendConstants[2] = 0.0f; colorBlending.blendConstants[3] = 0.0f; std::vector<VkPushConstantRange> pushConstantRanges = { vks::initializers::pushConstantRange(VK_SHADER_STAGE_VERTEX_BIT, sizeof(glm::vec3), 0), vks::initializers::pushConstantRange(VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(CMaterial::PushConsts), sizeof(Vector3f)), }; VkPipelineLayoutCreateInfo pipelineLayoutInfo = {}; pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipelineLayoutInfo.setLayoutCount = 1; // Optional pipelineLayoutInfo.pSetLayouts = &m_vkDescriptorSetLayout; pipelineLayoutInfo.pushConstantRangeCount = 2; pipelineLayoutInfo.pPushConstantRanges = pushConstantRanges.data(); result = vkCreatePipelineLayout(m_pIntegration->device(), &pipelineLayoutInfo, nullptr, &m_vkPipelineLayout); CError::CheckError<VkResult>(result); VkGraphicsPipelineCreateInfo pipelineInfo = {}; pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipelineInfo.stageCount = 2; pipelineInfo.pStages = shaderStages.data(); pipelineInfo.pVertexInputState = &vertexInputInfo; pipelineInfo.pInputAssemblyState = &inputAssembly; pipelineInfo.pViewportState = &viewportState; pipelineInfo.pRasterizationState = &rasterizer; pipelineInfo.pMultisampleState = &multisampling; pipelineInfo.pDepthStencilState = &depthStencil; pipelineInfo.pColorBlendState = &colorBlending; pipelineInfo.pDynamicState = nullptr; pipelineInfo.layout = m_vkPipelineLayout; pipelineInfo.renderPass = m_vkRenderPass; pipelineInfo.subpass = 0; pipelineInfo.basePipelineHandle = VK_NULL_HANDLE; pipelineInfo.basePipelineIndex = -1; pipelineInfo.flags = VK_DYNAMIC_STATE_SCISSOR | VK_DYNAMIC_STATE_VIEWPORT; // on swap recreation shader modules problems result = vkCreateGraphicsPipelines(m_pIntegration->device(), VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &m_vkGraphicsPipeline); CError::CheckError<VkResult>(result); for (auto &stage : shaderStages) { vkDestroyShaderModule(m_pIntegration->device(), stage.module, nullptr); } return result; } VkResult Dodo::Rendering::CRenderer::CreateFramebuffers() { VkResult result = VK_ERROR_INITIALIZATION_FAILED; m_vkSwapChainFramebuffers.resize(m_vkSwapChainImageViews.size()); for (size_t i = 0; i < m_vkSwapChainImageViews.size(); i++) { std::array<VkImageView, 2> attachments = { m_vkSwapChainImageViews[i], m_vkDepthImageView }; VkFramebufferCreateInfo framebufferInfo = {}; framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebufferInfo.renderPass = m_vkRenderPass; framebufferInfo.attachmentCount = static_cast<uint32_t>(attachments.size()); framebufferInfo.pAttachments = attachments.data(); framebufferInfo.width = m_vkSwapChainExtent.width; framebufferInfo.height = m_vkSwapChainExtent.height; framebufferInfo.layers = 1; result = vkCreateFramebuffer(m_pIntegration->device(), &framebufferInfo, nullptr, &m_vkSwapChainFramebuffers[i]); CError::CheckError<VkResult>(result); } return result; } VkResult Dodo::Rendering::CRenderer::CreateCommandPool() { VkResult result = VK_ERROR_INITIALIZATION_FAILED; VkCommandPoolCreateInfo poolInfo = {}; poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; poolInfo.queueFamilyIndex = m_pIntegration->queueFamilies().graphicsQueueFamilyIndices; poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; result = vkCreateCommandPool(m_pIntegration->device(), &poolInfo, nullptr, &m_vkCommandPool); CError::CheckError<VkResult>(result); return result; } VkResult Dodo::Rendering::CRenderer::CreateTextureImages() { VkResult result = VK_ERROR_INITIALIZATION_FAILED; for (auto &mat : m_pMaterials) { CMaterial::Textures* textures = &mat->textures(); result = CreateTextureImage(textures->albedo ); CError::CheckError<VkResult>(result); result = CreateTextureImage(textures->normal ); CError::CheckError<VkResult>(result); result = CreateTextureImage(textures->metallic ); CError::CheckError<VkResult>(result); result = CreateTextureImage(textures->roughness); CError::CheckError<VkResult>(result); } return result; } VkResult Dodo::Rendering::CRenderer::CreateTextureImageViews() { VkResult result = VK_ERROR_INITIALIZATION_FAILED; for (auto &mat : m_pMaterials) { CMaterial::Textures* textures = &mat->textures(); textures->albedo. textureData.textureImageView = CreateImageView(textures->albedo.textureData.textureImage, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT); textures->normal. textureData.textureImageView = CreateImageView(textures->normal.textureData.textureImage, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT); textures->metallic. textureData.textureImageView = CreateImageView(textures->metallic.textureData.textureImage, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT); textures->roughness.textureData.textureImageView = CreateImageView(textures->roughness.textureData.textureImage, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT); } return result; } VkResult Dodo::Rendering::CRenderer::CreateTextureSampler() { VkResult result = VK_ERROR_INITIALIZATION_FAILED; VkSamplerCreateInfo samplerInfo = {}; samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; samplerInfo.magFilter = VK_FILTER_LINEAR; samplerInfo.minFilter = VK_FILTER_LINEAR; samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.anisotropyEnable = VK_TRUE; samplerInfo.maxAnisotropy = 16; samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK; samplerInfo.unnormalizedCoordinates = VK_FALSE; samplerInfo.compareEnable = VK_FALSE; samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS; samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; samplerInfo.mipLodBias = 0.0f; samplerInfo.minLod = 0.0f; samplerInfo.maxLod = 0.0f; for (auto &mat : m_pMaterials) { CMaterial::Textures* texures = &mat->textures(); result = vkCreateSampler(m_pIntegration->device(), &samplerInfo, nullptr, &texures->albedo.textureData.textureSampler); result = vkCreateSampler(m_pIntegration->device(), &samplerInfo, nullptr, &texures->normal.textureData.textureSampler); result = vkCreateSampler(m_pIntegration->device(), &samplerInfo, nullptr, &texures->metallic.textureData.textureSampler); result = vkCreateSampler(m_pIntegration->device(), &samplerInfo, nullptr, &texures->roughness.textureData.textureSampler); CError::CheckError<VkResult>(result); } return result; } VkResult Dodo::Rendering::CRenderer::CreateDepthResources() { VkResult result = VK_ERROR_INITIALIZATION_FAILED; VkFormat depthFormat = FindDepthFormat(); result = CreateImage( m_vkSwapChainExtent.width, m_vkSwapChainExtent.height, depthFormat, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, m_vkDepthImage, m_vkDepthImageMemory); m_vkDepthImageView = CreateImageView(m_vkDepthImage, depthFormat, VK_IMAGE_ASPECT_DEPTH_BIT); TransitionImageLayout(m_vkDepthImage, depthFormat, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); return result; } VkResult Dodo::Rendering::CRenderer::CreateVertexBuffers() { VkResult result = VK_ERROR_INITIALIZATION_FAILED; for (const std::shared_ptr<Components::CMesh> mesh : m_pMeshes) { const std::vector<Vertex> verts = mesh->vertices(); VkDeviceSize bufferSize = sizeof(verts[0]) * verts.size(); // creating staging buffer VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; result = CreateBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); // copying vert data to staging buffer void* data; vkMapMemory(m_pIntegration->device(), stagingBufferMemory, 0, bufferSize, 0, &data); memcpy(data, verts.data(), (size_t)bufferSize); vkUnmapMemory(m_pIntegration->device(), stagingBufferMemory); // creating vertex Buffer CreateBuffer( bufferSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, mesh->m_dataBuffers.vertexBuffer, mesh->m_dataBuffers.vertexBufferMemory); // copying staging buffer to vertex buffer CopyBuffer(stagingBuffer, mesh->m_dataBuffers.vertexBuffer, bufferSize); vkDestroyBuffer(m_pIntegration->device(), stagingBuffer, nullptr); vkFreeMemory(m_pIntegration->device(), stagingBufferMemory, nullptr); // push vertex buffer to array for further use (buffer binding, etc.) //m_matDataBuffers.push_back(buffer); } return result; } VkResult Dodo::Rendering::CRenderer::CreateIndexBuffers() { VkResult result = VK_ERROR_INITIALIZATION_FAILED; for (const std::shared_ptr<Components::CMesh> mesh : m_pMeshes) { VkDeviceSize bufferSize = sizeof(mesh->m_indices[0]) * mesh->m_indices.size(); VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; CreateBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); void* data; vkMapMemory(m_pIntegration->device(), stagingBufferMemory, 0, bufferSize, 0, &data); memcpy(data, mesh->m_indices.data(), (size_t)bufferSize); vkUnmapMemory(m_pIntegration->device(), stagingBufferMemory); CreateBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, mesh->m_dataBuffers.indexBuffer, mesh->m_dataBuffers.indexBufferMemory); CopyBuffer(stagingBuffer, mesh->m_dataBuffers.indexBuffer, bufferSize); vkDestroyBuffer(m_pIntegration->device(), stagingBuffer, nullptr); vkFreeMemory(m_pIntegration->device(), stagingBufferMemory, nullptr); m_matDataBuffers.push_back(mesh->m_dataBuffers); } return result; } VkResult Dodo::Rendering::CRenderer::CreateUniformBuffers() { VkResult result = VK_ERROR_INITIALIZATION_FAILED; m_vkUniformBuffers.resize(m_pTransforms.size()); m_vkUniformBuffersMemory.resize(m_pTransforms.size()); for (size_t i = 0; i < m_pTransforms.size(); i++) { VkDeviceSize bufferSize = sizeof(CMaterial::UniformBufferObject); result = CreateBuffer( bufferSize, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, m_vkUniformBuffers[i], m_vkUniformBuffersMemory[i]); CError::CheckError<VkResult>(result); } VkDeviceSize lightBufferSize = sizeof(CLight::LightProperties) * m_pLights.size(); result = CreateBuffer( lightBufferSize, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, m_vkLightUniformBuffer, m_vkLightUniformBufferMemory); CError::CheckError<VkResult>(result); return result; } VkResult Dodo::Rendering::CRenderer::CreateCommandBuffers() { VkResult result = VK_ERROR_INITIALIZATION_FAILED; m_vkCommandBuffers.resize(m_vkSwapChainFramebuffers.size()); VkCommandBufferAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.commandPool = m_vkCommandPool; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandBufferCount = (uint32_t)m_vkCommandBuffers.size(); result = vkAllocateCommandBuffers(m_pIntegration->device(), &allocInfo, m_vkCommandBuffers.data()); CError::CheckError<VkResult>(result); //GUI m_pGui->CreateCommandBuffer(&m_vkSwapChainFramebuffers, m_vkCommandPool); m_pGui->NewFrame(deltaTime(), true); m_pGui->UpdateBuffers(); m_pGui->DrawFrame(m_vkSwapChainExtent, m_vkRenderPass, m_vkSwapChainFramebuffers); for (size_t i = 0; i < m_vkCommandBuffers.size(); i++) { VkCommandBufferBeginInfo beginInfo = {}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; beginInfo.pInheritanceInfo = nullptr; result = vkBeginCommandBuffer(m_vkCommandBuffers[i], &beginInfo); CError::CheckError<VkResult>(result); VkRenderPassBeginInfo renderPassInfo = {}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassInfo.renderPass = m_vkRenderPass; renderPassInfo.framebuffer = m_vkSwapChainFramebuffers[i]; renderPassInfo.renderArea.offset = { 0, 0 }; renderPassInfo.renderArea.extent = m_vkSwapChainExtent; std::array<VkClearValue, 2> clearValues = {}; clearValues[0].color = { 0.2f, 0.2f, 0.2f, 1.0f }; clearValues[1].depthStencil = { 1.0f, 0 }; renderPassInfo.clearValueCount = clearValues.size(); renderPassInfo.pClearValues = clearValues.data(); vkCmdBeginRenderPass(m_vkCommandBuffers[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); // Skybox m_pSkybox->BuildOnMainCmdBuf(m_vkCommandBuffers[i]); vkCmdBindPipeline(m_vkCommandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_vkGraphicsPipeline); //std::vector<VkBuffer> vertexBuffers = {}; VkBuffer *vertexBuffers = new VkBuffer[m_matDataBuffers.size()]; VkDeviceSize offsets[1] = { 0 }; for (int j = 0; j < m_pMeshes.size(); j++) { vkCmdBindVertexBuffers(m_vkCommandBuffers[i], 0, 1, &m_pMeshes[j]->m_dataBuffers.vertexBuffer, offsets); vkCmdBindIndexBuffer(m_vkCommandBuffers[i], m_pMeshes[j]->m_dataBuffers.indexBuffer, 0, VK_INDEX_TYPE_UINT32); vkCmdBindDescriptorSets(m_vkCommandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_vkPipelineLayout, 0, 1, &m_vkDescriptorSets[j], 0, nullptr); Vector3f pos = m_pMeshes[j]->entity->GetComponent<Components::CTransform>()->getPosition(); vkCmdPushConstants(m_vkCommandBuffers[i], m_vkPipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(Math::Vector3f), &pos); CMaterial::PushConsts pushConsts = m_pMeshes[j]->entity->GetComponent<Components::CMaterial>()->pushConstants(); vkCmdPushConstants(m_vkCommandBuffers[i], m_vkPipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(Vector3f), sizeof(CMaterial::PushConsts), &pushConsts); vkCmdDrawIndexed(m_vkCommandBuffers[i], m_pMeshes[j]->m_indices.size(), 1, 0, 0, 0); } vkCmdEndRenderPass(m_vkCommandBuffers[i]); m_pShadowMap->RecordCommandBuffer(m_vkCommandBuffers[i]); result = vkEndCommandBuffer(m_vkCommandBuffers[i]); CError::CheckError<VkResult>(result); } return result; } VkResult Dodo::Rendering::CRenderer::CreateSyncObjects() { m_sSyncObjects.imageAvailableSemaphores.resize(MAX_FRAMES_IN_FLIGHT); m_sSyncObjects.renderFinishedSemaphores.resize(MAX_FRAMES_IN_FLIGHT); m_sSyncObjects.inFlightFences.resize(MAX_FRAMES_IN_FLIGHT); VkResult result = VK_ERROR_INITIALIZATION_FAILED; VkSemaphoreCreateInfo semaphoreInfo = {}; semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; VkFenceCreateInfo fenceInfo = {}; fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { result = vkCreateSemaphore(m_pIntegration->device(), &semaphoreInfo, nullptr, &m_sSyncObjects.imageAvailableSemaphores[i]); CError::CheckError<VkResult>(result); result = vkCreateSemaphore(m_pIntegration->device(), &semaphoreInfo, nullptr, &m_sSyncObjects.renderFinishedSemaphores[i]); CError::CheckError<VkResult>(result); result = vkCreateFence(m_pIntegration->device(), &fenceInfo, nullptr, &m_sSyncObjects.inFlightFences[i]); CError::CheckError<VkResult>(result); } return result; } VkResult Dodo::Rendering::CRenderer::CreateDescriptorPool() { VkResult result = VK_ERROR_INITIALIZATION_FAILED; std::array<VkDescriptorPoolSize, 6> poolSizes = {}; poolSizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; poolSizes[0].descriptorCount = static_cast<uint32_t>(m_pMaterials.size()); poolSizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; poolSizes[1].descriptorCount = static_cast<uint32_t>(m_pMaterials.size()); poolSizes[2].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; poolSizes[2].descriptorCount = static_cast<uint32_t>(m_pMaterials.size()); poolSizes[3].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; poolSizes[3].descriptorCount = static_cast<uint32_t>(m_pMaterials.size()); poolSizes[4].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; poolSizes[4].descriptorCount = static_cast<uint32_t>(m_pMaterials.size()); poolSizes[5].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; poolSizes[5].descriptorCount = static_cast<uint32_t>(m_pMaterials.size()); VkDescriptorPoolCreateInfo poolInfo = {}; poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size()); poolInfo.pPoolSizes = poolSizes.data(); poolInfo.maxSets = static_cast<uint32_t>(m_pMaterials.size()); result = vkCreateDescriptorPool(m_pIntegration->device(), &poolInfo, nullptr, &m_vkDescriptorPool); CError::CheckError<VkResult>(result); return result; } VkResult Dodo::Rendering::CRenderer::CreateDescriptorSets() { VkResult result = VK_ERROR_INITIALIZATION_FAILED; std::vector<VkDescriptorSetLayout> layouts(m_pMaterials.size(), m_vkDescriptorSetLayout); VkDescriptorSetAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; allocInfo.descriptorPool = m_vkDescriptorPool; allocInfo.descriptorSetCount = m_pMaterials.size(); allocInfo.pSetLayouts = layouts.data(); m_vkDescriptorSets.resize(m_pMaterials.size()); result = vkAllocateDescriptorSets(m_pIntegration->device(), &allocInfo, m_vkDescriptorSets.data()); CError::CheckError<VkResult>(result); for (size_t i = 0; i < m_pMaterials.size(); i++) { VkDescriptorBufferInfo bufferInfo = {}; bufferInfo.buffer = m_vkUniformBuffers[i]; bufferInfo.offset = 0; bufferInfo.range = sizeof(CMaterial::UniformBufferObject); VkDescriptorImageInfo imageInfo = {}; imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; m_pMaterials[i]->textures().albedo.textureData.imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; m_pMaterials[i]->textures().normal.textureData.imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; m_pMaterials[i]->textures().metallic.textureData.imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; m_pMaterials[i]->textures().roughness.textureData.imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; m_pMaterials[i]->textures().albedo.textureData.imageInfo.imageView = m_pMaterials[i]->textures().albedo.textureData.textureImageView; m_pMaterials[i]->textures().normal.textureData.imageInfo.imageView = m_pMaterials[i]->textures().normal.textureData.textureImageView; m_pMaterials[i]->textures().metallic.textureData.imageInfo.imageView = m_pMaterials[i]->textures().metallic.textureData.textureImageView; m_pMaterials[i]->textures().roughness.textureData.imageInfo.imageView = m_pMaterials[i]->textures().roughness.textureData.textureImageView; m_pMaterials[i]->textures().albedo.textureData.imageInfo.sampler = m_pMaterials[i]->textures().albedo.textureData.textureSampler; m_pMaterials[i]->textures().normal.textureData.imageInfo.sampler = m_pMaterials[i]->textures().normal.textureData.textureSampler; m_pMaterials[i]->textures().metallic.textureData.imageInfo.sampler = m_pMaterials[i]->textures().metallic.textureData.textureSampler; m_pMaterials[i]->textures().roughness.textureData.imageInfo.sampler = m_pMaterials[i]->textures().roughness.textureData.textureSampler; VkDescriptorBufferInfo lightBufferInfo = {}; lightBufferInfo.buffer = m_vkLightUniformBuffer; lightBufferInfo.offset = 0; lightBufferInfo.range = sizeof(CLight::LightProperties) * m_pLights.size(); std::vector<VkWriteDescriptorSet> writeDescriptorSets = { vks::initializers::writeDescriptorSet(m_vkDescriptorSets[i], VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &bufferInfo), vks::initializers::writeDescriptorSet(m_vkDescriptorSets[i], VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &m_pMaterials[i]->textures().albedo.textureData.imageInfo), vks::initializers::writeDescriptorSet(m_vkDescriptorSets[i], VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2, &m_pMaterials[i]->textures().normal.textureData.imageInfo), vks::initializers::writeDescriptorSet(m_vkDescriptorSets[i], VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 3, &m_pMaterials[i]->textures().metallic.textureData.imageInfo), vks::initializers::writeDescriptorSet(m_vkDescriptorSets[i], VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 4, &m_pMaterials[i]->textures().roughness.textureData.imageInfo), vks::initializers::writeDescriptorSet(m_vkDescriptorSets[i], VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 5, &lightBufferInfo) }; vkUpdateDescriptorSets( m_pIntegration->device(), static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, nullptr); } return result; } VkResult Dodo::Rendering::CRenderer::UpdateCommandBuffers() { VkResult result = VK_ERROR_INITIALIZATION_FAILED; for (size_t i = 0; i < m_vkCommandBuffers.size(); i++) { VkCommandBufferBeginInfo beginInfo = {}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; beginInfo.pInheritanceInfo = nullptr; result = vkBeginCommandBuffer(m_vkCommandBuffers[i], &beginInfo); CError::CheckError<VkResult>(result); VkRenderPassBeginInfo renderPassInfo = {}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassInfo.renderPass = m_vkRenderPass; renderPassInfo.framebuffer = m_vkSwapChainFramebuffers[i]; renderPassInfo.renderArea.offset = { 0, 0 }; renderPassInfo.renderArea.extent = m_vkSwapChainExtent; std::array<VkClearValue, 2> clearValues = {}; clearValues[0].color = { 0.2f, 0.2f, 0.2f, 1.0f }; clearValues[1].depthStencil = { 1.0f, 0 }; renderPassInfo.clearValueCount = clearValues.size(); renderPassInfo.pClearValues = clearValues.data(); vkCmdBeginRenderPass(m_vkCommandBuffers[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindPipeline(m_vkCommandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_vkGraphicsPipeline); if (m_pGui->uiSettings.displayModels) { VkBuffer *vertexBuffers = new VkBuffer[m_matDataBuffers.size()]; VkDeviceSize offsets[1] = { 0 }; for (int j = 0; j < m_pMeshes.size(); j++) { vertexBuffers[j] = m_matDataBuffers[j].vertexBuffer; vkCmdBindVertexBuffers(m_vkCommandBuffers[i], 0, 1, &m_matDataBuffers[j].vertexBuffer, offsets); // evtl buggy bei mehreren vertex buffern vkCmdBindIndexBuffer(m_vkCommandBuffers[i], m_pMeshes[j]->m_dataBuffers.indexBuffer, 0, VK_INDEX_TYPE_UINT32); vkCmdBindDescriptorSets(m_vkCommandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_vkPipelineLayout, 0, 1, &m_vkDescriptorSets[j], 0, nullptr); Vector3f pos = m_pMeshes[j]->entity->GetComponent<Components::CTransform>()->getPosition(); vkCmdPushConstants(m_vkCommandBuffers[i], m_vkPipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(Math::Vector3f), &pos); float f = 0.5f; //m_pMeshes[0]->entity->GetComponent<Components::CMaterial>()->setPushConstants(1.0f, 0.0f, 1.0f, 1.0f, 1.0f); //m_pMeshes[1]->entity->GetComponent<Components::CMaterial>()->setPushConstants(0.0f, 0.8f, 1.0f, 1.0f, 1.0f); CMaterial::PushConsts pushConsts = m_pMaterials[j]->entity->GetComponent<Components::CMaterial>()->pushConstants(); pushConsts.roughness = m_pGui->uiSettings.roughness; pushConsts.metallic = m_pGui->uiSettings.metallic; vkCmdPushConstants(m_vkCommandBuffers[i], m_vkPipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(Vector3f), sizeof(CMaterial::PushConsts), &pushConsts); vkCmdDrawIndexed(m_vkCommandBuffers[i], m_pMeshes[j]->m_indices.size(), 1, 0, 0, 0); } } vkCmdEndRenderPass(m_vkCommandBuffers[i]); result = vkEndCommandBuffer(m_vkCommandBuffers[i]); CError::CheckError<VkResult>(result); } return result; } VkResult Dodo::Rendering::CRenderer::CreateBuffer(VkDeviceSize _size, VkBufferUsageFlags _usage, VkMemoryPropertyFlags _properties, VkBuffer &_buffer, VkDeviceMemory &_bufferMemory) { VkResult result = VK_ERROR_INITIALIZATION_FAILED; VkBufferCreateInfo bufferInfo = {}; bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferInfo.size = _size; bufferInfo.usage = _usage; bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; result = vkCreateBuffer(m_pIntegration->device(), &bufferInfo, nullptr, &_buffer); CError::CheckError<VkResult>(result); VkMemoryRequirements memRequirements; vkGetBufferMemoryRequirements(m_pIntegration->device(), _buffer, &memRequirements); VkMemoryAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.allocationSize = memRequirements.size; allocInfo.memoryTypeIndex = m_pIntegration->FindMemoryType( memRequirements.memoryTypeBits, _properties); result = vkAllocateMemory(m_pIntegration->device(), &allocInfo, nullptr, &_bufferMemory); CError::CheckError<VkResult>(result); vkBindBufferMemory(m_pIntegration->device(), _buffer, _bufferMemory, 0); return result; } VkResult Dodo::Rendering::CRenderer::CreateImage(uint32_t width, uint32_t height, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties, VkImage & image, VkDeviceMemory & imageMemory) { VkResult result = VK_ERROR_INITIALIZATION_FAILED; VkImageCreateInfo imageInfo = {}; imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; imageInfo.imageType = VK_IMAGE_TYPE_2D; imageInfo.extent.width = width; imageInfo.extent.height = height; imageInfo.extent.depth = 1; imageInfo.mipLevels = 1; imageInfo.arrayLayers = 1; imageInfo.format = format; imageInfo.tiling = tiling; imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; imageInfo.usage = usage; imageInfo.samples = VK_SAMPLE_COUNT_1_BIT; imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; imageInfo.flags = 0; // Optional result = vkCreateImage(m_pIntegration->device(), &imageInfo, nullptr, &image); CError::CheckError<VkResult>(result); VkMemoryRequirements memRequirements; vkGetImageMemoryRequirements(m_pIntegration->device(), image, &memRequirements); VkMemoryAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.allocationSize = memRequirements.size; allocInfo.memoryTypeIndex = m_pIntegration->FindMemoryType(memRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); result = vkAllocateMemory(m_pIntegration->device(), &allocInfo, nullptr, &imageMemory); CError::CheckError<VkResult>(result); vkBindImageMemory( m_pIntegration->device(), image, imageMemory, 0); return result; } VkResult Dodo::Rendering::CRenderer::TransitionImageLayout(VkImage image, VkFormat format, VkImageLayout oldLayout, VkImageLayout newLayout) { VkResult result = VK_SUCCESS; VkCommandBuffer commandBuffer = BeginSingleTimeCommands(); VkImageMemoryBarrier barrier = {}; barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barrier.oldLayout = oldLayout; barrier.newLayout = newLayout; barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.image = image; if (newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) { barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; if (HasStencilComponent(format)) { barrier.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT; } } else { barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; } barrier.subresourceRange.baseMipLevel = 0; barrier.subresourceRange.levelCount = 1; barrier.subresourceRange.baseArrayLayer = 0; barrier.subresourceRange.layerCount = 1; VkPipelineStageFlags sourceStage; VkPipelineStageFlags destinationStage; if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { barrier.srcAccessMask = 0; barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT; } else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT; destinationStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; } else if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) { barrier.srcAccessMask = 0; barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; destinationStage = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT; } else { throw std::invalid_argument("unsupported layout transition!"); } vkCmdPipelineBarrier( commandBuffer, sourceStage, destinationStage, 0, 0, nullptr, 0, nullptr, 1, &barrier ); EndSingleTimeCommands(commandBuffer); return result; } VkResult Dodo::Rendering::CRenderer::CopyBufferToImage(VkBuffer _buffer, VkImage _image, uint32_t _width, uint32_t _height) { VkResult result = VK_SUCCESS; VkCommandBuffer commandBuffer = BeginSingleTimeCommands(); VkBufferImageCopy region = {}; region.bufferOffset = 0; region.bufferRowLength = 0; region.bufferImageHeight = 0; region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.imageSubresource.mipLevel = 0; region.imageSubresource.baseArrayLayer = 0; region.imageSubresource.layerCount = 1; region.imageOffset = { 0, 0, 0 }; region.imageExtent = { _width, _height, 1 }; vkCmdCopyBufferToImage( commandBuffer, _buffer, _image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region); EndSingleTimeCommands(commandBuffer); return result; } VkResult Dodo::Rendering::CRenderer::CopyBuffer(VkBuffer _srcBuffer, VkBuffer _dstBuffer, VkDeviceSize _size) { VkResult result = VK_ERROR_INITIALIZATION_FAILED; VkCommandBuffer commandBuffer = BeginSingleTimeCommands(); VkBufferCopy copyRegion = {}; copyRegion.srcOffset = 0; copyRegion.dstOffset = 0; copyRegion.size = _size; vkCmdCopyBuffer(commandBuffer, _srcBuffer, _dstBuffer, 1, &copyRegion); EndSingleTimeCommands(commandBuffer); return result; } VkCommandBuffer Dodo::Rendering::CRenderer::BeginSingleTimeCommands() { VkCommandBufferAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandPool = m_vkCommandPool; allocInfo.commandBufferCount = 1; VkCommandBuffer commandBuffer; vkAllocateCommandBuffers(m_pIntegration->device(), &allocInfo, &commandBuffer); VkCommandBufferBeginInfo beginInfo = {}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; vkBeginCommandBuffer(commandBuffer, &beginInfo); return commandBuffer; } void Dodo::Rendering::CRenderer::EndSingleTimeCommands(VkCommandBuffer _buf) { vkEndCommandBuffer(_buf); VkSubmitInfo submitInfo = {}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &_buf; vkQueueSubmit(m_pIntegration->queues().graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE); vkQueueWaitIdle(m_pIntegration->queues().graphicsQueue); vkFreeCommandBuffers(m_pIntegration->device(), m_vkCommandPool, 1, &_buf); } VkResult Dodo::Rendering::CRenderer::UpdateUniformBuffer() { VkResult result = VK_ERROR_INITIALIZATION_FAILED; static auto startTime = std::chrono::high_resolution_clock::now(); auto currentTime = std::chrono::high_resolution_clock::now(); float time = std::chrono::duration<float, std::chrono::seconds::period>(currentTime - startTime).count(); m_dDeltaTime = time; for (int i = 0; i < m_pTransforms.size(); i++) { CMaterial::UniformBufferObject ubo = {}; if (m_pTransforms[i] != nullptr) { ubo.model = m_pTransforms[i]->getComposed(); } else { ubo.model = glm::rotate(glm::mat4(1.0f), time * glm::radians(90.0f), glm::vec3(0.0f, 0.0f, 1.0f)); } ubo.camPos = m_pCamera->cameraPos; ubo.View = m_pCamera->getViewMatrix(); ubo.projection = m_pCamera->getProjectionMatrix(); ubo.projection[1][1] *= -1; void* data; vkMapMemory(m_pIntegration->device(), m_vkUniformBuffersMemory[i], 0, sizeof(ubo), 0, &data); memcpy(data, &ubo, sizeof(ubo)); vkUnmapMemory(m_pIntegration->device(), m_vkUniformBuffersMemory[i]); } std::vector<Components::CLight::LightProperties> props = {}; for (auto& l : m_pLights) { props.push_back(l->GetProperties()); } props[0].position = Vector4f(0.0f, 0.0f, time, 1.0f); void* data; result = vkMapMemory(m_pIntegration->device(), m_vkLightUniformBufferMemory, 0, sizeof(Components::CLight::LightProperties) * props.size(), 0, &data); memcpy(data, props.data(), sizeof(Components::CLight::LightProperties) * props.size()); vkUnmapMemory(m_pIntegration->device(), m_vkLightUniformBufferMemory); return VK_SUCCESS; } VkResult Dodo::Rendering::CRenderer::CleanupSwapChain() { VkResult result = VK_ERROR_INITIALIZATION_FAILED; vkDestroyImageView(m_pIntegration->device(), m_vkDepthImageView, nullptr); vkDestroyImage(m_pIntegration->device(), m_vkDepthImage, nullptr); vkFreeMemory(m_pIntegration->device(), m_vkDepthImageMemory, nullptr); for (size_t i = 0; i < m_vkSwapChainFramebuffers.size(); i++) { vkDestroyFramebuffer(m_pIntegration->device(), m_vkSwapChainFramebuffers[i], nullptr); } vkFreeCommandBuffers(m_pIntegration->device(), m_vkCommandPool, m_vkCommandBuffers.size(), m_vkCommandBuffers.data()); vkDestroyPipeline(m_pIntegration->device(), m_vkGraphicsPipeline, nullptr); vkDestroyPipelineLayout(m_pIntegration->device(), m_vkPipelineLayout, nullptr); vkDestroyRenderPass(m_pIntegration->device(), m_vkRenderPass, nullptr); for (size_t i = 0; i < m_vkSwapChainImageViews.size(); i++) { vkDestroyImageView(m_pIntegration->device(), m_vkSwapChainImageViews[i], nullptr); } vkDestroySwapchainKHR(m_pIntegration->device(), m_vkSwapChain, nullptr); for (size_t i = 0; i < m_pTransforms.size(); i++) { vkDestroyBuffer(m_pIntegration->device(), m_vkUniformBuffers[i], nullptr); vkFreeMemory(m_pIntegration->device(), m_vkUniformBuffersMemory[i], nullptr); } vkDestroyDescriptorPool(m_pIntegration->device(), m_vkDescriptorPool, nullptr); return result; } VkResult Dodo::Rendering::CRenderer::RecreateSwapChain() { VkResult result = VK_ERROR_INITIALIZATION_FAILED; int width = 0, height = 0; while (width == 0 || height == 0) { glfwGetFramebufferSize(m_pWindow->GetWindow(), &width, &height); glfwWaitEvents(); } result = vkDeviceWaitIdle(m_pIntegration->device()); CError::CheckError<VkResult>(result); CleanupSwapChain(); CreateSwapChain(); CreateImageViews(); CreateRenderPass(); CreateGraphicsPipeline(); CreateDepthResources(); CreateFramebuffers(); m_pGui->CreateFramebuffers(m_vkSwapChainImageViews, m_vkDepthImageView, m_vkSwapChainExtent); m_pSkybox->SetRenderPass(m_vkRenderPass); m_pSkybox->SetExtent(m_vkSwapChainExtent); m_pSkybox->CreatePipeline(); CreateUniformBuffers(); CreateDescriptorPool(); CreateDescriptorSets(); CreateCommandBuffers(); return result; } Dodo::Rendering::CRenderer::SwapChainSupportDetails Dodo::Rendering::CRenderer::QuerySwapChainSupport() { SwapChainSupportDetails details = {}; // Get capabilities VkResult result = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(m_pIntegration->physicalDevice(), m_pIntegration->surface(), &details.capabilities); CError::CheckError<VkResult>(result); // Get formats uint32_t formatCount = 0; result = vkGetPhysicalDeviceSurfaceFormatsKHR(m_pIntegration->physicalDevice(), m_pIntegration->surface(), &formatCount, nullptr); if (formatCount != 0) { details.formats.resize(formatCount); result = vkGetPhysicalDeviceSurfaceFormatsKHR(m_pIntegration->physicalDevice(), m_pIntegration->surface(), &formatCount, details.formats.data()); } CError::CheckError<VkResult>(result); // Get present modes uint32_t presentModeCount = 0; result = vkGetPhysicalDeviceSurfacePresentModesKHR(m_pIntegration->physicalDevice(), m_pIntegration->surface(), &presentModeCount, nullptr); if (presentModeCount != 0) { details.presentModes.resize(presentModeCount); result = vkGetPhysicalDeviceSurfacePresentModesKHR(m_pIntegration->physicalDevice(), m_pIntegration->surface(), &presentModeCount, details.presentModes.data()); } CError::CheckError<VkResult>(result); return details; } VkSurfaceFormatKHR Dodo::Rendering::CRenderer::ChooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& _availableFormats) { if (_availableFormats.size() == 1 && _availableFormats[0].format == VK_FORMAT_UNDEFINED) { return{ VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR }; } for (const auto& availableFormat : _availableFormats) { if (availableFormat.format == VK_FORMAT_B8G8R8A8_UNORM && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { return availableFormat; } } return _availableFormats[0]; } VkPresentModeKHR Dodo::Rendering::CRenderer::ChooseSwapPresentMode(const std::vector<VkPresentModeKHR> _availablePresentModes) { VkPresentModeKHR bestMode = VK_PRESENT_MODE_FIFO_KHR; for (const auto& availablePresentMode : _availablePresentModes) { if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) { return availablePresentMode; } else if (availablePresentMode == VK_PRESENT_MODE_IMMEDIATE_KHR) { bestMode = availablePresentMode; } } return bestMode; } VkExtent2D Dodo::Rendering::CRenderer::ChooseSwapExtent(const VkSurfaceCapabilitiesKHR & _capabilities) { if (_capabilities.currentExtent.width != std::numeric_limits<uint32_t>::max() /*UINT32_MAX*/) { return _capabilities.currentExtent; } else { int width, height; glfwGetFramebufferSize(m_pWindow->GetWindow(), &width, &height); VkExtent2D actualExtent = { static_cast<uint32_t>(width), static_cast<uint32_t>(height) }; actualExtent.width = glm::max(_capabilities.minImageExtent.width, glm::min(_capabilities.maxImageExtent.width, actualExtent.width)); actualExtent.height = glm::max(_capabilities.minImageExtent.height, glm::min(_capabilities.maxImageExtent.height, actualExtent.height)); return actualExtent; } } VkFormat Dodo::Rendering::CRenderer::FindSupportedFormat(const std::vector<VkFormat>& _candidates, VkImageTiling _tiling, VkFormatFeatureFlags _features) { for (VkFormat format : _candidates) { VkFormatProperties props; vkGetPhysicalDeviceFormatProperties(m_pIntegration->physicalDevice(), format, &props); if (_tiling == VK_IMAGE_TILING_LINEAR && (props.linearTilingFeatures & _features) == _features) { return format; } else if (_tiling == VK_IMAGE_TILING_OPTIMAL && (props.optimalTilingFeatures & _features) == _features) { return format; } } CLog::Error("Couldnt find supported format"); return VK_FORMAT_END_RANGE; }
36.87244
226
0.786162
TKscoot
5015347f9be70a555833fac14da44b1cb06bd3d8
204
cpp
C++
source/delaunay/delaunay.cpp
Phytolizer/voronoi
654273ebc1b5697aeef902c2fd2e7f2a0d541a87
[ "MIT" ]
null
null
null
source/delaunay/delaunay.cpp
Phytolizer/voronoi
654273ebc1b5697aeef902c2fd2e7f2a0d541a87
[ "MIT" ]
null
null
null
source/delaunay/delaunay.cpp
Phytolizer/voronoi
654273ebc1b5697aeef902c2fd2e7f2a0d541a87
[ "MIT" ]
null
null
null
#include "voronoi/delaunay/delaunay.hpp" vo::delaunay::triangulation vo::delaunay::triangulate(const std::vector<math::point2d>& points) { (void)points; // TODO(kyle): implement return {}; }
22.666667
69
0.691176
Phytolizer
5015a1e38b9238f7e1ed4d2facfb5c2797d1223f
102
cpp
C++
samples/win/stdafx.cpp
keima97/ouzel
e6673e678b4739235371a15ae3863942b692c5fb
[ "BSD-2-Clause" ]
null
null
null
samples/win/stdafx.cpp
keima97/ouzel
e6673e678b4739235371a15ae3863942b692c5fb
[ "BSD-2-Clause" ]
null
null
null
samples/win/stdafx.cpp
keima97/ouzel
e6673e678b4739235371a15ae3863942b692c5fb
[ "BSD-2-Clause" ]
null
null
null
// Copyright (C) 2015 Elviss Strazdins // This file is part of the Ouzel engine. #include "stdafx.h"
20.4
41
0.715686
keima97
5016c829fec8d26f1eeaa7f8a5b6f0f92d39f8ff
665
cpp
C++
Data Structure/Array Or Vector/Search An Element in Sorted Array/SolutionBySuchi.cpp
rajethanm4/Programmers-Community
d16083eb0e84403159d999d4d1a8bbf652ca51f6
[ "MIT" ]
8
2020-11-07T10:29:21.000Z
2020-12-26T16:54:13.000Z
Data Structure/Array Or Vector/Search An Element in Sorted Array/SolutionBySuchi.cpp
rajethanm4/Programmers-Community
d16083eb0e84403159d999d4d1a8bbf652ca51f6
[ "MIT" ]
null
null
null
Data Structure/Array Or Vector/Search An Element in Sorted Array/SolutionBySuchi.cpp
rajethanm4/Programmers-Community
d16083eb0e84403159d999d4d1a8bbf652ca51f6
[ "MIT" ]
2
2019-12-18T13:06:19.000Z
2021-01-05T18:47:18.000Z
#include<iostream> using namespace std; int binsrch(int low,int high,int a[],int no) { if ( low <= high ) { int mid=(low+high)/2; if(no==a[mid]) { return mid; } else if(no<a[mid]) { return binsrch(low,mid-1,a,no); } else if(no>a[mid]) { return binsrch(mid+1,high,a,no); } } return -1; } int main() { int size,no; cin>>size; int *a = new int[size]; for(int i=0;i<size;i++) { cin>>a[i]; } cin >> no; int x=-1; x=binsrch(0,size,a,no); if(x==-1) cout<<"NO"; else cout<<"YES"; return 0; }
17.051282
46
0.439098
rajethanm4
5018af41fe7b65f08e4d739b40101ed699558645
17,945
cpp
C++
handlers/FilmHandlers.cpp
jedimahdi/movie-network
8b11febb3121ea31f94713528d270618b56bd327
[ "MIT" ]
1
2020-09-03T14:53:11.000Z
2020-09-03T14:53:11.000Z
handlers/FilmHandlers.cpp
jedimahdi/movie-network
8b11febb3121ea31f94713528d270618b56bd327
[ "MIT" ]
null
null
null
handlers/FilmHandlers.cpp
jedimahdi/movie-network
8b11febb3121ea31f94713528d270618b56bd327
[ "MIT" ]
null
null
null
#include "FilmHandlers.h" #include "../exceptions/BadRequest.h" #include "../exceptions/PermissionDenied.h" #include "../models/Comment.h" #include "../models/Film.h" #include <sstream> #include <vector> using namespace std; map<string, string> ShowCreateFilm::handle(Request *req) { map<string, string> context; if (req->getSessionId() == "") { throw Server::Exception("Permission Denied!"); } else { User *user = user_controller->get_user(stoi(req->getSessionId())); if (user->is_publisher()) { context["is_publisher"] = "1"; } else { context["is_publisher"] = "0"; } context["logged_user_name"] = user->get_username(); } return context; } CreateFilmHandler::CreateFilmHandler(FilmController *fc, UserController *uc, Recommendation *rc) : film_controller(fc), user_controller(uc), recommendation(rc) {} Response *CreateFilmHandler::callback(Request *req) { if (req->getSessionId() == "") return Response::redirect("/login"); int logged_user_id = stoi(req->getSessionId()); User *user = user_controller->get_user(logged_user_id); if (!user->is_publisher()) { Response *res = Response::redirect("/"); res->setStatus(403); return res; } film_controller->create_film( logged_user_id, req->getBodyParam("name"), stoi(req->getBodyParam("year")), stoi(req->getBodyParam("length")), stoi(req->getBodyParam("price")), req->getBodyParam("summary"), req->getBodyParam("director")); recommendation->on_add_film(); ostringstream message; message << "Publisher " << user->get_username() << " with id " << user->get_id() << "register new film." << endl; vector<User *> followers = user->get_followers(); for (size_t i = 0; i < followers.size(); i++) { followers[i]->notify(message.str()); } return Response::redirect("/films/add"); } Response *ShowFilms::callback(Request *req) { Response *res = new Response(); res->setHeader("Content-Type", "text/html"); ostringstream body; if (req->getSessionId() == "") return Response::redirect("/login"); User *user = user_controller->get_user(stoi(req->getSessionId())); vector<Film *> films; if (user->is_publisher()) { films = film_controller->get_user_films(user->get_id(), req->getQueryParam("name"), req->getQueryParam("rate"), req->getQueryParam("min_year"), req->getQueryParam("price"), req->getQueryParam("max_year"), req->getQueryParam("director")); } else { films = film_controller->get_all_films(req->getQueryParam("name"), req->getQueryParam("rate"), req->getQueryParam("min_year"), req->getQueryParam("price"), req->getQueryParam("max_year"), req->getQueryParam("director")); } body << "<!DOCTYPE html>" << endl; body << "<html lang='en'>" << endl; body << "<head>" << endl; body << " <meta charset='UTF-8'>" << endl; body << " <meta name='viewport' content='width=device-width, initial-scale=1.0'>" << endl; body << " <meta http-equiv='X-UA-Compatible' content='ie=edge'>" << endl; body << " <link rel='stylesheet' href='bootstrap.css'>" << endl; body << " <title>Home | Movie Network</title>" << endl; body << "</head>" << endl; body << "<body>" << endl; body << " <div style='margin-bottom: 0 !important;' class='d-flex flex-column flex-md-row align-items-center p-3 px-md-4 mb-3 bg-white border-bottom shadow-sm'>" << endl; body << " <h5 class='my-0 mr-md-auto font-weight-normal'>Movie Network</h5>" << endl; body << " <nav class='my-2 my-md-0 mr-md-3'>" << endl; body << " <a class='p-2 text-dark' href='/'>Home</a>" << endl; if (user->is_publisher()) { body << " <a class='p-2 text-dark' href='/films/add'>Add Film</a>" << endl; } body << " <a class='p-2 text-dark' href='/profile'>Profile</a>" << endl; body << " </nav>" << endl; body << " <a class='btn btn-outline-primary' href='/logout'>Logout</a>" << endl; body << " </div>" << endl; body << " <div class='album py-5 bg-light'>" << endl; body << " <div class='container'>" << endl; body << "<form method='GET' action='/'>" << endl; body << " <div class='row'>" << endl; body << "<div class='col-md-10 mb-4'><input name='director' type='text' class='form-control' placeholder='Search by director name'> </div>" << endl; body << "<div class='col-md-2 mb-4'><button class='btn btn-secondary' type='submit'>Search</button> </div>" << endl; body << "</div>" << endl; body << "</form>" << endl; body << " <div class='row'>" << endl; for (size_t i = 0; i < films.size(); i++) { body << "<div class='col-md-4'>" << endl; body << "<div class='card mb-4 shadow-sm'>" << endl; body << "<div class='card-body'>" << endl; body << "<h5 class='card-title'>" << films[i]->get_name() << "</h5>" << endl; body << "<p class='card-text'>" << "Director : " << films[i]->get_director() << "<br />" << "Price : " << films[i]->get_price() << "<br />" << "Rate : " << films[i]->get_rate() << "<br />" << "Year : " << films[i]->get_year() << "<br />" << "</p>" << endl; body << "<div class='d-flex justify-content-between align-items-center'>" << endl; body << "<div class='btn-group'>" << endl; body << "<a href='/film?id=" << films[i]->get_id() << "' class='btn btn-sm btn-outline-secondary'>View</a>" << endl; if (user->is_publisher()) { body << "<a href='/delete_film?id=" << films[i]->get_id() << "' class='btn btn-sm btn-outline-secondary'>Delete</a>" << endl; } body << "</div>" << endl; body << "<small class='text-muted'>" << films[i]->get_length() << " mins</small>" << endl; body << "</div>" << endl; body << "</div>" << endl; body << "</div>" << endl; body << "</div>" << endl; } body << " </div>" << endl; body << " </div>" << endl; body << " </div>" << endl; body << "</body>" << endl; body << "</html>" << endl; res->setBody(body.str()); return res; } Response *ShowFilmDetails::callback(Request *req) { if (req->getSessionId() == "") return Response::redirect("/login"); Response *res = new Response(); res->setHeader("Content-Type", "text/html"); ostringstream body; Film *film = film_controller->get_film(stoi(req->getQueryParam("id"))); User *user = user_controller->get_user(stoi(req->getSessionId())); vector<int> film_ids = recommendation->get_films(film->get_id()); body << "<!DOCTYPE html>" << endl; body << "<html lang='en'>" << endl; body << "<head>" << endl; body << " <meta charset='UTF-8'>" << endl; body << " <meta name='viewport' content='width=device-width, initial-scale=1.0'>" << endl; body << " <meta http-equiv='X-UA-Compatible' content='ie=edge'>" << endl; body << " <link rel='stylesheet' href='bootstrap.css'>" << endl; body << " <title>Home | Movie Network</title>" << endl; body << "</head>" << endl; body << "<body class='bg-light'>" << endl; body << " <div style='margin-bottom: 0 !important;' class='d-flex flex-column flex-md-row align-items-center p-3 px-md-4 mb-3 border-bottom shadow-sm'>" << endl; body << " <h5 class='my-0 mr-md-auto font-weight-normal'>Movie Network</h5>" << endl; body << " <nav class='my-2 my-md-0 mr-md-3'>" << endl; body << " <a class='p-2 text-dark' href='/'>Home</a>" << endl; if (user->is_publisher()) { body << " <a class='p-2 text-dark' href='/films/add'>Add Film</a>" << endl; } body << " <a class='p-2 text-dark' href='/profile'>Profile</a>" << endl; body << " </nav>" << endl; body << " <a class='btn btn-outline-primary' href='/logout'>Logout</a>" << endl; body << " </div>" << endl; body << " <div class='container'>" << endl; body << "<div class='d-flex align-items-center p-3 my-3 rounded shadow-sm bg-white'>" << endl; body << "<div class='lh-100'>" << endl; body << "<h2 class='lh-100'>" << film->get_name() << "</h2>" << endl; body << "<p>Production Year: " << film->get_year() << "</p>" << endl; body << "<p>Director: " << film->get_director() << "</p>" << endl; body << "<p>Rate: " << film->get_rate() << "</p>" << endl; body << "<p>Length: " << film->get_length() << " min</p>" << endl; body << "<p>Price: " << film->get_price() << "</p>" << endl; body << "<p>Summary: " << film->get_summary() << "</p>" << endl; if (!film->is_member_of(user->get_purchased_films())) { body << "<form method='POST' action='/buy'>" << endl; body << "<input type='hidden' name='film_id' value='" << film->get_id() << "'>" << endl; body << "<button type='submit' class='btn btn-primary'>Buy</button>" << endl; body << "</form>" << endl; } else { body << "<form method='POST' action='/rate'>" << endl; body << "<input type='hidden' name='film_id' value='" << film->get_id() << "'>" << endl; body << "<input type='text' name='score' class='form-control' placeholder='Score'>" << endl; body << "<button type='submit' class='btn btn-block btn-primary'>Rate</button>" << endl; body << "</form>" << endl; } body << "</div>" << endl; body << "</div>" << endl; body << "<div class='my-3 p-3 bg-white rounded shadow-sm'>" << endl; body << "<h6 class='border-bottom border-gray pb-2 mb-0'>Suggestions</h6>" << endl; Film *f; for (size_t i = 0; i < film_ids.size(); i++) { f = film_controller->get_film(film_ids[i]); body << "<div class='media text-muted pt-3'>" << endl; body << "<div class='media-body pb-3 mb-0 small lh-125 border-bottom border-gray'>" << endl; body << "<div class='d-flex justify-content-between align-items-center w-100'>" << endl; body << "<strong class='text-gray-dark'>" << f->get_name() << " (" << f->get_director() << ")</strong>" << endl; body << "<a href='/film?id=" << f->get_id() << "'>View</a>" << endl; body << "</div>" << endl; body << "<span class='d-block'>" << f->get_length() << " mins</span>" << endl; body << "</div>" << endl; body << "</div>" << endl; } body << "</div>" << endl; body << " </div>" << endl; body << "</body>" << endl; body << "</html>" << endl; res->setBody(body.str()); return res; } Response *DeleteFilmHandler::callback(Request *req) { if (req->getSessionId() == "") return Response::redirect("/login"); int logged_user_id = stoi(req->getSessionId()); User *user = user_controller->get_user(logged_user_id); if (!user->is_publisher()) { Response *res = Response::redirect("/"); res->setStatus(403); return res; } int film_id = stoi(req->getQueryParam("id")); film_controller->delete_film(film_id, logged_user_id); recommendation->on_delete_film(film_id); return Response::redirect("/"); } Response *ShowPurchasedFilms::callback(Request *req) { Response *res = new Response(); res->setHeader("Content-Type", "text/html"); ostringstream body; if (req->getSessionId() == "") return Response::redirect("/login"); User *user = user_controller->get_user(stoi(req->getSessionId())); vector<Film *> films = user->get_purchased_films(); body << "<!DOCTYPE html>" << endl; body << "<html lang='en'>" << endl; body << "<head>" << endl; body << " <meta charset='UTF-8'>" << endl; body << " <meta name='viewport' content='width=device-width, initial-scale=1.0'>" << endl; body << " <meta http-equiv='X-UA-Compatible' content='ie=edge'>" << endl; body << " <link rel='stylesheet' href='bootstrap.css'>" << endl; body << " <title>Home | Movie Network</title>" << endl; body << "</head>" << endl; body << "<body>" << endl; body << " <div style='margin-bottom: 0 !important;' class='d-flex flex-column flex-md-row align-items-center p-3 px-md-4 mb-3 bg-white border-bottom shadow-sm'>" << endl; body << " <h5 class='my-0 mr-md-auto font-weight-normal'>Movie Network</h5>" << endl; body << " <nav class='my-2 my-md-0 mr-md-3'>" << endl; body << " <a class='p-2 text-dark' href='/'>Home</a>" << endl; if (user->is_publisher()) { body << " <a class='p-2 text-dark' href='/films/add'>Add Film</a>" << endl; } body << " <a class='p-2 text-dark' href='/profile'>Profile</a>" << endl; body << " </nav>" << endl; body << " <a class='btn btn-outline-primary' href='/logout'>Logout</a>" << endl; body << " </div>" << endl; body << " <div class='album py-5 bg-light'>" << endl; body << " <div class='container'>" << endl; body << " <form method='POST' action='/money'>" << endl; body << " <div class='row'>" << endl; body << " <div class='col-md-6 mb-4'>" << endl; body << " <h4>Add Money : </h4>" << endl; body << " <div class='row'><div class='col-md-8'>" << endl; body << " <input class='form-control' type='text' name='amount' placeholder='Amount'>" << endl; body << " </div><div class='col-md-4'>" << endl; body << " <button type='submit' class='btn btn-dark'>Add</button>" << endl; body << " </div>" << endl; body << " </div>" << endl; body << " </div>" << endl; body << " <div class='col-md-6 mb-4'>" << endl; body << " <h4>Your Money : </h4>" << user->get_money() << endl; body << " </div>" << endl; body << " </div>" << endl; body << " </form>" << endl; body << " <hr />" << endl; body << " <div class='row'>" << endl; for (size_t i = 0; i < films.size(); i++) { body << "<div class='col-md-4'>" << endl; body << "<div class='card mb-4 shadow-sm'>" << endl; body << "<div class='card-body'>" << endl; body << "<h5 class='card-title'>" << films[i]->get_name() << "</h5>" << endl; body << "<p class='card-text'>" << "Director : " << films[i]->get_director() << "<br />" << "Price : " << films[i]->get_price() << "<br />" << "Rate : " << films[i]->get_rate() << "<br />" << "Year : " << films[i]->get_year() << "<br />" << "</p>" << endl; body << "<div class='d-flex justify-content-between align-items-center'>" << endl; body << "<div class='btn-group'>" << endl; body << "<a href='/film?id=" << films[i]->get_id() << "' class='btn btn-sm btn-outline-secondary'>View</a>" << endl; body << "</div>" << endl; body << "<small class='text-muted'>" << films[i]->get_length() << " mins</small>" << endl; body << "</div>" << endl; body << "</div>" << endl; body << "</div>" << endl; body << "</div>" << endl; } body << " </div>" << endl; body << " </div>" << endl; body << " </div>" << endl; body << "</body>" << endl; body << "</html>" << endl; res->setBody(body.str()); return res; } Response *BuyFilmHandler::callback(Request *req) { if (req->getSessionId() == "") return Response::redirect("/login"); User *user = user_controller->get_user(stoi(req->getSessionId())); Film *film = film_controller->get_film(stoi(req->getBodyParam("film_id"))); if (user->get_money() < film->get_price()) { throw Server::Exception("You don't have enough money to buy this film!"); } user->add_money(-film->get_price()); user->add_purchased_film(film); film->sell(); recommendation->on_buy_film(film->get_id()); ostringstream message; message << "User " << user->get_username() << " with id " << user->get_id() << " buy your film " << film->get_name() << " with id " << film->get_id() << "." << endl; user_controller->get_user(film->get_user_id())->notify(message.str()); return Response::redirect("/film?id=" + req->getBodyParam("film_id")); } Response *RateFilmHandler::callback(Request *req) { if (req->getSessionId() == "") return Response::redirect("/login"); User *user = user_controller->get_user(stoi(req->getSessionId())); Film *film = film_controller->get_film(stoi(req->getBodyParam("film_id"))); if (film->is_member_of(user->get_purchased_films())) { film->rate_film(stoi(req->getBodyParam("score"))); ostringstream message; message << "User " << user->get_username() << " with id " << user->get_id() << " rate your film " << film->get_name() << " with id " << film->get_id() << "." << endl; user_controller->get_user(film->get_user_id())->notify(message.str()); } else { throw Server::Exception("You must first buy this film to rate."); } return Response::redirect("/film?id=" + req->getBodyParam("film_id")); } Response *MoneyHandler::callback(Request *req) { if (req->getSessionId() == "") return Response::redirect("/login"); User *user = user_controller->get_user(stoi(req->getSessionId())); user->add_money(stoi(req->getBodyParam("amount"))); return Response::redirect("/profile"); }
46.25
176
0.531011
jedimahdi
5018b141a2500b20faf3d680e229dcada4d1713c
770
cpp
C++
2020/03/pcapng-parse/main.cpp
NanXiao/code-for-my-blog
c2c4f59e438241696d938354bb14396f36f97748
[ "BSD-3-Clause" ]
5
2020-03-03T21:00:05.000Z
2021-12-17T07:04:14.000Z
2020/03/pcapng-parse/main.cpp
NanXiao/code-for-my-blog
c2c4f59e438241696d938354bb14396f36f97748
[ "BSD-3-Clause" ]
null
null
null
2020/03/pcapng-parse/main.cpp
NanXiao/code-for-my-blog
c2c4f59e438241696d938354bb14396f36f97748
[ "BSD-3-Clause" ]
2
2020-05-10T18:12:21.000Z
2021-12-17T02:40:42.000Z
#include <iostream> #include <PcapFileDevice.h> int main() { std::cout << pcap_lib_version() << '\n'; pcpp::PcapNgFileReaderDevice input_file("/Users/nanxiao/Downloads/capture.pcapng"); if (input_file.open()) { std::cout << "Open successfully\n"; } else { std::cerr << "Open failed\n"; return 1; } std::cout << input_file.getOS() << '\n'; std::cout << input_file.getHardware() << '\n'; std::cout << input_file.getCaptureApplication() << '\n'; std::cout << input_file.getCaptureFileComment() << '\n'; pcpp::RawPacket packet; std::string comment; for (size_t i = 1; i < 10; i++) { if (input_file.getNextPacket(packet, comment)) { std::cout << i << ":" << comment << '\n'; } else { std::cerr << "Get packet failed\n"; return 1; } } }
22.647059
84
0.616883
NanXiao
501b2482b4a90a3a55d5d08380c319c154a03a9a
203
cpp
C++
src/FBStateNormal.cpp
LesmesWasNotHere/Footsketball
d8072eda69a3cab570c5a9094eeef0228582cac1
[ "MIT" ]
null
null
null
src/FBStateNormal.cpp
LesmesWasNotHere/Footsketball
d8072eda69a3cab570c5a9094eeef0228582cac1
[ "MIT" ]
null
null
null
src/FBStateNormal.cpp
LesmesWasNotHere/Footsketball
d8072eda69a3cab570c5a9094eeef0228582cac1
[ "MIT" ]
null
null
null
#include "FBStateNormal.h" #define OWN_DISTANCE = 13 FBStateNormal::FBStateNormal(FootsketBall& gameObject):_GameObject(gameObject) { } bool FBStateNormal::Update(unsigned milis) { return true; }
15.615385
78
0.768473
LesmesWasNotHere
501ba224ebc3cce46a06507b53164c6bd0ab0099
1,178
hpp
C++
include/P12218319/cio/benchmarks/Problem.hpp
p12218319/CIO
b302fec4d1b3e0f6f18bf8b83a4229fadd5091c0
[ "Apache-2.0" ]
null
null
null
include/P12218319/cio/benchmarks/Problem.hpp
p12218319/CIO
b302fec4d1b3e0f6f18bf8b83a4229fadd5091c0
[ "Apache-2.0" ]
null
null
null
include/P12218319/cio/benchmarks/Problem.hpp
p12218319/CIO
b302fec4d1b3e0f6f18bf8b83a4229fadd5091c0
[ "Apache-2.0" ]
null
null
null
/* Copyright 2016 Adam Smith & Fabio Caraffini (Original Java version) 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. email : p12218319@myemail.dmu.ac.uk */ #ifndef P12218319_CIO_PROBLEM_HPP #define P12218319_CIO_PROBLEM_HPP #include <cmath> #include "P12218319\core\core.hpp" namespace P12218319 { namespace cio { template<const uint32_t DIMENTIONS> class P12218319_EXPORT_API Problem { public: typedef double InputArray[DIMENTIONS]; typedef double BoundArray[DIMENTIONS][2]; private: BoundArray mBounds; public: virtual P12218319_CALL ~Problem(){} virtual double P12218319_CALL operator()(InputArray& x) const override throw() = 0; }; }} #endif
31
85
0.758913
p12218319
501fa15b354f1561971befc24bb4b475fb404a90
632
cpp
C++
lang/C++/memory-allocation-1.cpp
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
1
2018-11-09T22:08:38.000Z
2018-11-09T22:08:38.000Z
lang/C++/memory-allocation-1.cpp
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
null
null
null
lang/C++/memory-allocation-1.cpp
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
1
2018-11-09T22:08:40.000Z
2018-11-09T22:08:40.000Z
#include <string> int main() { int* p; p = new int; // allocate a single int, uninitialized delete p; // deallocate it p = new int(2); // allocate a single int, initialized with 2 delete p; // deallocate it std::string* p2; p2 = new std::string; // allocate a single string, default-initialized delete p2; // deallocate it p = new int[10]; // allocate an array of 10 ints, uninitialized delete[] p; // deallocation of arrays must use delete[] p2 = new std::string[10]; // allocate an array of 10 strings, default-initialized delete[] p2; // deallocate it }
26.333333
83
0.618671
ethansaxenian
5020cb34011b78ef32a2f416cc3c13bd6c0cf8cb
82,726
cxx
C++
base/fs/utils/untfs/src/sdchk.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
base/fs/utils/untfs/src/sdchk.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
base/fs/utils/untfs/src/sdchk.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1996-2000 Microsoft Corporation Module Name: sdchk.cxx Abstract: This module implements Security Descriptors Checking. Author: Daniel Chan (danielch) 30-Sept-96 --*/ #include <pch.cxx> #define _NTAPI_ULIB_ #define _UNTFS_MEMBER_ //#define TIMING_ANALYSIS 1 #if defined(TIMING_ANALYSIS) && !defined(_AUTOCHECK_) extern "C" { #include <stdio.h> #include <time.h> } #endif #include "ulib.hxx" #include "ntfssa.hxx" #include "message.hxx" #include "rtmsg.h" #include "ntfsbit.hxx" #include "attrcol.hxx" #include "frsstruc.hxx" #include "attrib.hxx" #include "attrrec.hxx" #include "attrlist.hxx" #include "list.hxx" #include "iterator.hxx" #include "attrdef.hxx" #include "extents.hxx" #include "mft.hxx" #include "mftref.hxx" #include "bootfile.hxx" #include "badfile.hxx" #include "mftfile.hxx" #include "numset.hxx" #include "ifssys.hxx" #include "indxtree.hxx" #include "upcase.hxx" #include "upfile.hxx" #include "frs.hxx" #include "digraph.hxx" #include "logfile.hxx" #include "rcache.hxx" #include "ifsentry.hxx" #include "sdchk.hxx" #include "spaset.hxx" typedef struct _REPAIR_RECORD { ULONG Offset; ULONG Length; }; DEFINE_TYPE(_REPAIR_RECORD, REPAIR_RECORD); ULONG ComputeDefaultSecurityId( PNUMBER_SET SidSet ); VOID ClearSecurityDescriptorEntry( IN OUT PSECURITY_ENTRY Security_entry, IN ULONG SecurityDescriptorSize ); BOOLEAN RecoverSecurityDescriptorsDataStream( IN OUT PNTFS_FILE_RECORD_SEGMENT Frs, IN OUT PNTFS_ATTRIBUTE Attrib, IN ULONG AttributeSize, IN PCHAR Buffer, IN ULONG BufferSize, IN ULONG ClusterSize, IN OUT PNTFS_BITMAP Bitmap, OUT PBOOLEAN DiskHasErrors, IN OUT PNUMBER_SET BadClusters, IN OUT PMESSAGE Message, IN BOOLEAN FixLevel ); BOOLEAN RepairSecurityDescriptorsSegment( IN OUT PNTFS_ATTRIBUTE Attrib, IN PCHAR Buffer, IN ULONG Offset, IN ULONG BytesToProcess, IN OUT PREPAIR_RECORD Record, IN OUT USHORT *RecordCount, IN ULONG ClusterSize ); #if defined( _SETUP_LOADER_ ) BOOLEAN NTFS_SA::ValidateSecurityDescriptors( IN PNTFS_CHKDSK_INFO ChkdskInfo, IN OUT PNTFS_CHKDSK_REPORT ChkdskReport, IN OUT PNTFS_MASTER_FILE_TABLE Mft, IN OUT PNUMBER_SET BadClusters, IN BOOLEAN SkipEntriesScan, IN FIX_LEVEL FixLevel, IN OUT PMESSAGE Message ) /*++ Routine Description: This routine ensures that every file on the disk contains a valid security descriptor. Arguments: ChkdskInfo - Supplies the current chkdsk information. ChkdskReport- Supplies the current chkdsk report. Mft - Supplies a valid MFT. BadClusters - Receives the bad clusters identified by this method. FixLevel - Supplies the fix level. Message - Supplies an outlet for messages Return Value: FALSE - Failure. TRUE - Success. --*/ { // Stub for Setup Loader. return TRUE; } #else // not _SETUP_LOADER_ BOOLEAN NTFS_SA::ValidateSecurityDescriptors( IN PNTFS_CHKDSK_INFO ChkdskInfo, IN OUT PNTFS_CHKDSK_REPORT ChkdskReport, IN OUT PNTFS_MASTER_FILE_TABLE Mft, IN OUT PNUMBER_SET BadClusters, IN BOOLEAN SkipEntriesScan, IN FIX_LEVEL FixLevel, IN OUT PMESSAGE Message ) /*++ Routine Description: This routine ensures that every file on the disk contains a valid security descriptor. If that's not the case, then it expects to find the $SDS data stream in $Secure and each of those files contain a security id. Arguments: ChkdskInfo - Supplies the current chkdsk information. Mft - Supplies a valid MFT. FixLevel - Supplies the fix level. Message - Supplies an outlet for messages Return Value: FALSE - Failure. TRUE - Success. --*/ { NTFS_FILE_RECORD_SEGMENT myfrs; PNTFS_FILE_RECORD_SEGMENT pfrs; NTFS_FILE_RECORD_SEGMENT security_frs; ULONG i, n; ULONG percent; NTFS_ATTRIBUTE attrib; NTFS_ATTRIBUTE SDS_attrib; NTFS_ATTRIBUTE SII_attrib; BOOLEAN error; BOOLEAN hasErrors = FALSE; BOOLEAN diskHasErrors; BOOLEAN chkdskErrCouldNotFix = FALSE; BOOLEAN chkdskCleanUp = FALSE; ULONG cleanup_count; BOOLEAN attribute_need_write = FALSE; BOOLEAN frs_need_flush = FALSE; BOOLEAN index_need_save = FALSE; BOOLEAN attribute_need_resize; BOOLEAN boundary_problem_found; BOOLEAN insufficient_security_desctiptor_block_free_space; BOOLEAN lastblock; BOOLEAN fixing_mirror; ULONG length; ULONG num_bytes; BOOLEAN securityDescriptorStreamPresent = FALSE; BOOLEAN alreadyExists; BOOLEAN new_SII_index = FALSE; BOOLEAN new_SDH_index = FALSE; BOOLEAN alloc_present; DSTRING SII_IndexName; DSTRING SDH_IndexName; DSTRING indexName; ULONG hash, offset; ULONG bytesWritten; BIG_INT hashkey; NUMBER_SET sid_entries, sid_entries2; SPARSE_SET hashkey_entries; NTFS_INDEX_TREE SII_Index; NTFS_INDEX_TREE SDH_Index; ULONG count_sid = 0; ULONG count_hashkey = 0; PCINDEX_ENTRY index_entry; ULONG depth; ULONG securityId; ULONG defaultSecurityId = 0; PSECURITY_ENTRY security_entry = NULL; PSECURITY_ENTRY previous_security_entry; PSECURITY_ENTRY previous_previous_security_entry; PSECURITY_ENTRY initial_security_entry = NULL; PSECURITY_ENTRY endOfBlock; ULONG lengthUptoPreviousBlock; ULONG resizeTo; ULONG remain_length; ULONG bytesToRead; ULONG lengthOfBlock; ULONG align_num_bytes; ULONG se_offset; ULONG total_length; ULONG sdLength; ULONG errFixedStatus = CHKDSK_EXIT_SUCCESS; #if defined(TIMING_ANALYSIS) && !defined(_AUTOCHECK_) time_t time1, time2; PCHAR timestr; #endif DebugPtrAssert(ChkdskInfo); DebugPtrAssert(ChkdskReport); Message->DisplayMsg(MSG_CHK_NTFS_CHECKING_SECURITY, PROGRESS_MESSAGE, NORMAL_VISUAL, "%d%d", 3, GetNumberOfStages()); // Check for existence of $SecurityDescriptorStream in SECURITY_TABLE_NUMBER if (!security_frs.Initialize(SECURITY_TABLE_NUMBER, Mft) || !indexName.Initialize(SecurityDescriptorStreamNameData)) { Message->DisplayMsg(MSG_CHK_NO_MEMORY); return FALSE; } // ??what to do if frs is unreadable or not in use or not a base?? if (security_frs.Read() && security_frs.IsInUse() && security_frs.IsBase()) { securityDescriptorStreamPresent = security_frs.QueryAttribute(&SDS_attrib, &error, $DATA, &indexName) && ChkdskInfo->major >= 2; if (!error && !securityDescriptorStreamPresent && ChkdskInfo->major >= 2) { // delete all $DATA attribute first while (security_frs.QueryAttribute(&SDS_attrib, &error, $DATA, 0)) { Message->DisplayMsg(MSG_CHKLOG_NTFS_UNKNOWN_SECURITY_DATA_STREAM, "%W%I64x", SDS_attrib.GetName(), security_frs.QueryFileNumber().GetLargeInteger()); if (!SDS_attrib.Resize(0, Mft->GetVolumeBitmap()) || !security_frs.PurgeAttribute(SDS_attrib.QueryTypeCode(), SDS_attrib.GetName())) { Message->DisplayMsg(MSG_CHK_NO_MEMORY); return FALSE; } } if (error) { Message->DisplayMsg(MSG_CHK_NO_MEMORY); return FALSE; } Message->LogMsg(MSG_CHKLOG_NTFS_SECURITY_DATA_STREAM_MISSING, "%I64x", security_frs.QueryFileNumber().GetLargeInteger()); // now create the $DATA, $SDS stream if (!SDS_attrib.Initialize(_drive, QueryClusterFactor(), NULL, 0, $DATA, &indexName)) { Message->DisplayMsg(MSG_CHK_NO_MEMORY); return FALSE; } if (!SDS_attrib.InsertIntoFile(&security_frs, Mft->GetVolumeBitmap())) { Message->DisplayMsg(MSG_CHK_NTFS_CANT_PUT_DATA_ATTRIBUTE); return FALSE; } if (FixLevel != CheckOnly && !security_frs.Flush(Mft->GetVolumeBitmap())) { Message->DisplayMsg(MSG_CHK_NTFS_CANT_PUT_DATA_ATTRIBUTE); return FALSE; } errFixedStatus = CHKDSK_EXIT_ERRS_FIXED; hasErrors = TRUE; securityDescriptorStreamPresent = TRUE; } if (!error && securityDescriptorStreamPresent) { if (!SII_IndexName.Initialize(SecurityIdIndexNameData) || !SDH_IndexName.Initialize(SecurityDescriptorHashIndexNameData)) { Message->DisplayMsg(MSG_CHK_NO_MEMORY); return FALSE; } // make sure the $SII index exists // if it does not exists, an empty one will be created if (!SII_Index.Initialize(_drive, QueryClusterFactor(), Mft->GetVolumeBitmap(), Mft->GetUpcaseTable(), security_frs.QuerySize()/2, &security_frs, &SII_IndexName)) { Message->DisplayMsg(MSG_CHK_NTFS_CREATE_INDEX, "%W%d", &SII_IndexName, SECURITY_TABLE_NUMBER); errFixedStatus = CHKDSK_EXIT_ERRS_FIXED; hasErrors = TRUE; if (!SII_Index.Initialize(0, _drive, QueryClusterFactor(), Mft->GetVolumeBitmap(), Mft->GetUpcaseTable(), COLLATION_ULONG, SMALL_INDEX_BUFFER_SIZE, security_frs.QuerySize()/2, &SII_IndexName)) { Message->DisplayMsg(MSG_CHK_NO_MEMORY); return FALSE; } if (FixLevel != CheckOnly && (!SII_Index.Save(&security_frs) || !security_frs.Flush(Mft->GetVolumeBitmap()))) { Message->DisplayMsg(MSG_CHK_NTFS_CANT_FIX_INDEX, "%d%W", security_frs.QueryFileNumber().GetLowPart(), &SII_IndexName); return FALSE; } ChkdskReport->NumIndices += 1; new_SII_index = TRUE; } // make sure the $SDH index exists // if it does not exists, an empty one will be created if (!SDH_Index.Initialize(_drive, QueryClusterFactor(), Mft->GetVolumeBitmap(), Mft->GetUpcaseTable(), security_frs.QuerySize()/2, &security_frs, &SDH_IndexName)) { Message->DisplayMsg(MSG_CHK_NTFS_CREATE_INDEX, "%W%d", &SDH_IndexName, SECURITY_TABLE_NUMBER); errFixedStatus = CHKDSK_EXIT_ERRS_FIXED; hasErrors = TRUE; if (!SDH_Index.Initialize(0, _drive, QueryClusterFactor(), Mft->GetVolumeBitmap(), Mft->GetUpcaseTable(), COLLATION_SECURITY_HASH, SMALL_INDEX_BUFFER_SIZE, security_frs.QuerySize()/2, &SDH_IndexName)) { Message->DisplayMsg(MSG_CHK_NO_MEMORY, "%d%W", security_frs.QueryFileNumber().GetLowPart(), &SDH_IndexName); return FALSE; } if (FixLevel != CheckOnly && (!SDH_Index.Save(&security_frs) || !security_frs.Flush(Mft->GetVolumeBitmap()))) { Message->DisplayMsg(MSG_CHK_NTFS_CANT_FIX_INDEX, "%d%W", security_frs.QueryFileNumber().GetLowPart(), &SDH_IndexName); return FALSE; } ChkdskReport->NumIndices += 1; new_SDH_index = TRUE; } // Read in the security descriptor and validate. length = SDS_attrib.QueryValueLength().GetLowPart(); // allocate space for a block of security descriptors if (SDS_attrib.QueryValueLength().GetHighPart() != 0 || !(initial_security_entry = (SECURITY_ENTRY*) MALLOC(SecurityDescriptorsBlockSize))) { Message->DisplayMsg(MSG_CHK_NO_MEMORY); return FALSE; } if (!RecoverSecurityDescriptorsDataStream( &security_frs, &SDS_attrib, length, (PCHAR)initial_security_entry, SecurityDescriptorsBlockSize, _drive->QuerySectorSize()*QueryClusterFactor(), Mft->GetVolumeBitmap(), &diskHasErrors, BadClusters, Message, FixLevel)) { FREE(initial_security_entry); return FALSE; } else if (diskHasErrors) { errFixedStatus = CHKDSK_EXIT_ERRS_FIXED; hasErrors = TRUE; if (FixLevel == CheckOnly) { // // In case of readonly mode, chkdsk shouldn't continue as it may run into // the unreadable clusters // FREE(initial_security_entry); Message->DisplayMsg(MSG_CHK_NTFS_SECURITY_VERIFICATION_COMPLETED, PROGRESS_MESSAGE); UPDATE_EXIT_STATUS_FIXED(errFixedStatus, ChkdskInfo); if (chkdskErrCouldNotFix) ChkdskInfo->ExitStatus = CHKDSK_EXIT_COULD_NOT_FIX; else if (chkdskCleanUp) { _cleanup_that_requires_reboot = TRUE; if (ChkdskInfo->ExitStatus == CHKDSK_EXIT_SUCCESS) ChkdskInfo->ExitStatus = CHKDSK_EXIT_MINOR_ERRS; } return TRUE; } else if (!security_frs.Flush(Mft->GetVolumeBitmap())) { Message->DisplayMsg(MSG_CHK_READABLE_FRS_UNWRITEABLE, "%d", security_frs.QueryFileNumber().GetLowPart()); FREE(initial_security_entry); return FALSE; } } // get the actual length of the first copy of security descriptor data if (length < SecurityDescriptorsBlockSize) { // Resize the whole thing to zero length Message->LogMsg(MSG_CHKLOG_NTFS_SECURITY_DATA_STREAM_SIZE_TOO_SMALL, "%x%x", length, SecurityDescriptorsBlockSize); attribute_need_resize = TRUE; length = 0; } else { attribute_need_resize = FALSE; length -= SecurityDescriptorsBlockSize; } offset = 0; lengthUptoPreviousBlock = 0; frs_need_flush = FALSE; boundary_problem_found = FALSE; resizeTo = 0; endOfBlock = (PSECURITY_ENTRY)((PCHAR)initial_security_entry+ SecurityDescriptorsBlockSize); remain_length = length; if (!sid_entries.Initialize() || !sid_entries2.Initialize() || !hashkey_entries.Initialize()) { Message->DisplayMsg(MSG_CHK_NO_MEMORY); FREE(initial_security_entry); return FALSE; } for (;length > 0;) { previous_previous_security_entry = previous_security_entry = NULL; attribute_need_write = FALSE; bytesToRead = min(SecurityDescriptorsBlockSize, length); security_entry = initial_security_entry; if (!SDS_attrib.Read(security_entry, offset, bytesToRead, &num_bytes) || num_bytes != bytesToRead) { Message->DisplayMsg(MSG_CHK_NTFS_CANT_READ_SECURITY_DATA_STREAM); FREE(initial_security_entry); return FALSE; } lastblock = length <= SecurityDescriptorsBlockSize; lengthOfBlock = 0; // Validate each security descriptor record in the data stream while (length > 0) { // Check if there is a violation of the guarantee that: // There will be atleast enough space for the // SECURITY_DESCRIPTOR_HEADER at the end of the SD block insufficient_security_desctiptor_block_free_space = ((security_entry != endOfBlock) && ((PCHAR)security_entry-(PCHAR)initial_security_entry+ sizeof(SECURITY_DESCRIPTOR_HEADER) > SecurityDescriptorsBlockSize)); // see if there is a need to move to next security descriptor block if ((security_entry == endOfBlock) || (!insufficient_security_desctiptor_block_free_space && (security_entry->security_descriptor_header.Length == 0 && security_entry->security_descriptor_header.HashKey.SecurityId == 0 && security_entry->security_descriptor_header.HashKey.Hash == 0))) { if (!lastblock && (remain_length >= (SecurityDescriptorsBlockSize<<1))) { lengthOfBlock = (ULONG)((PCHAR)security_entry- (PCHAR)initial_security_entry); if (!RemainingBlockIsZero((PCHAR)security_entry, (ULONG)((PCHAR)endOfBlock-(PCHAR)security_entry))) { MarkEndOfSecurityDescriptorsBlock(security_entry, (ULONG)((PCHAR)endOfBlock-(PCHAR)security_entry)); Message->LogMsg(MSG_CHKLOG_NTFS_REMAINING_SECURITY_DATA_BLOCK_CONTAINS_NON_ZERO, "%x%x", offset+lengthOfBlock, (ULONG)((PCHAR)endOfBlock-(PCHAR)security_entry)); DebugPrint("Clearing till end of the security descriptors block.\n"); attribute_need_write = TRUE; } break; } else boundary_problem_found = TRUE; } if (!insufficient_security_desctiptor_block_free_space) { num_bytes = security_entry->security_descriptor_header.Length; } align_num_bytes = (num_bytes + 0xf) & ~0xf; error = FALSE; if (boundary_problem_found) { // loglog error = TRUE; } else if (insufficient_security_desctiptor_block_free_space) { // do we want to log this? // This condition will be detected and the previous SD will be // deleted to fix this condition in the if(error) block error = TRUE; }else if ((PCHAR)security_entry-(PCHAR)initial_security_entry+ num_bytes > SecurityDescriptorsBlockSize) { Message->LogMsg(MSG_CHKLOG_NTFS_SDS_ENTRY_CROSSES_PAGE_BOUNDARY, "%x%x", offset+((PCHAR)security_entry-(PCHAR)initial_security_entry), num_bytes ); error = TRUE; } else if (num_bytes < sizeof(SECURITY_ENTRY)) { Message->LogMsg(MSG_CHKLOG_NTFS_SDS_ENTRY_LENGTH_TOO_SMALL, "%x%x%x", offset+((PCHAR)security_entry-(PCHAR)initial_security_entry), num_bytes, sizeof(SECURITY_ENTRY)); error = TRUE; } else if (num_bytes > SecurityDescriptorMaxSize) { Message->LogMsg(MSG_CHKLOG_NTFS_SDS_ENTRY_LENGTH_EXCEEDS_PAGE_BOUNDARY, "%x%x%x", offset+((PCHAR)security_entry-(PCHAR)initial_security_entry), num_bytes, SecurityDescriptorMaxSize ); error = TRUE; } else if (length < sizeof(SECURITY_ENTRY)) { Message->LogMsg(MSG_CHKLOG_NTFS_SDS_REMAINING_PAGE_LENGTH_TOO_SMALL, "%x%x%x", offset+((PCHAR)security_entry-(PCHAR)initial_security_entry), length, sizeof(SECURITY_ENTRY)); error = TRUE; } else if (length != num_bytes && length < align_num_bytes) { Message->LogMsg(MSG_CHKLOG_NTFS_SDS_REMAINING_PAGE_LENGTH_TOO_SMALL, "%x%x%x", offset+((PCHAR)security_entry-(PCHAR)initial_security_entry), length, align_num_bytes); error = TRUE; } if (error) { boundary_problem_found = FALSE; if (!lastblock) { if ((PCHAR)security_entry-(PCHAR)initial_security_entry+ sizeof(SECURITY_DESCRIPTOR_HEADER) <= SecurityDescriptorsBlockSize) { MarkEndOfSecurityDescriptorsBlock(security_entry, (ULONG)((PCHAR)endOfBlock- (PCHAR)security_entry)); if (previous_security_entry) lengthOfBlock = (ULONG)((PCHAR)previous_security_entry - (PCHAR)initial_security_entry) + previous_security_entry->security_descriptor_header.Length; else lengthOfBlock = 0; } else if (previous_security_entry) { sid_entries.Remove(previous_security_entry-> security_descriptor_header.HashKey.SecurityId); hashkey.Set(previous_security_entry-> security_descriptor_header.HashKey.Hash, previous_security_entry-> security_descriptor_header.HashKey.SecurityId); hashkey_entries.CheckAndRemove(hashkey); // the index entry will automatically be removed at a later stage MarkEndOfSecurityDescriptorsBlock(previous_security_entry, (ULONG)((PCHAR)endOfBlock- (PCHAR)previous_security_entry)); if (previous_previous_security_entry) { lengthOfBlock = (ULONG)((PCHAR)previous_previous_security_entry - (PCHAR)initial_security_entry) + previous_previous_security_entry-> security_descriptor_header.Length; } else { lengthOfBlock = 0; } } else { DebugAssert(FALSE); // It doesn't make much sense to get here. // If we don't have a previous_security_entry then // security_entry is at the beginning of the block // and should have enough space to include the EOB // mark. } attribute_need_write = TRUE; DebugPrint("Clearing till end of the security descriptors block.\n"); } else { // if lastblock if (previous_security_entry) { DebugAssert(remain_length <= SecurityDescriptorsBlockSize); if (!insufficient_security_desctiptor_block_free_space) { bytesToRead = remain_length = lengthOfBlock = (ULONG)((PCHAR)previous_security_entry- (PCHAR)initial_security_entry+ previous_security_entry-> security_descriptor_header.Length); } else { // delete the previous entry as well to ensure that // there is atleast space for one security descriptor // header bytesToRead = remain_length = lengthOfBlock = (ULONG)((PCHAR)previous_security_entry- (PCHAR)initial_security_entry); } resizeTo = lengthOfBlock + offset; } else { bytesToRead = remain_length = lengthOfBlock = 0; resizeTo = lengthUptoPreviousBlock; DebugAssert(!attribute_need_write); } attribute_need_resize = TRUE; // no need to write attribute DebugPrint("Truncating the security descriptors block.\n"); } break; } // skip over invalidated entries securityId = security_entry->security_descriptor_header.HashKey.SecurityId; if (securityId == SECURITY_ID_INVALID) goto GetNextSDEntry; sdLength = num_bytes - sizeof(SECURITY_DESCRIPTOR_HEADER); if (!IFS_SYSTEM::CheckValidSecurityDescriptor( sdLength, (PISECURITY_DESCRIPTOR)&(security_entry->security)) || sdLength < RtlLengthSecurityDescriptor( &(security_entry->security))) { // the data part is invalid // fill the whole thing with zeros except the length byte in the header Message->LogMsg(MSG_CHKLOG_NTFS_INVALID_SECURITY_DESCRIPTOR_IN_SDS_ENTRY, "%x%x", offset+((PCHAR)security_entry-(PCHAR)initial_security_entry), securityId); ClearSecurityDescriptorEntry(security_entry, sdLength); attribute_need_write = TRUE; DebugPrint("Clearing invalid security descriptor.\n"); goto GetNextSDEntry; } // check to see if we encountered this sid before // also build a set with all the sid encountered if (sid_entries.CheckAndAdd(securityId, &alreadyExists)) { if (alreadyExists) { Message->LogMsg(MSG_CHKLOG_NTFS_DUPLICATE_SID_IN_SDS_ENTRY, "%x%x", offset+((PCHAR)security_entry-(PCHAR)initial_security_entry), securityId); ClearSecurityDescriptorEntry(security_entry, sdLength); attribute_need_write = TRUE; DebugPrint("Clearing duplicate security descriptor.\n"); goto GetNextSDEntry; } } else { Message->DisplayMsg(MSG_CHK_NO_MEMORY); FREE(initial_security_entry); return FALSE; } // check to see if the hash value is good hash = ComputeSecurityDescriptorHash( &(security_entry->security), sdLength); if (security_entry->security_descriptor_header.HashKey.Hash != hash) { Message->LogMsg(MSG_CHKLOG_NTFS_INCORRECT_HASH_IN_SDS_ENTRY, "%x%x%x%x", offset+((PCHAR)security_entry-(PCHAR)initial_security_entry), security_entry->security_descriptor_header.HashKey.Hash, hash, securityId); security_entry->security_descriptor_header.HashKey.Hash = hash; attribute_need_write = TRUE; DebugPrint("Repairing hash value of a security descriptor header.\n"); } // check to see if the offset stored in the security descriptor header is good se_offset = (ULONG)((PCHAR)security_entry - (PCHAR)initial_security_entry + offset); if (security_entry->security_descriptor_header.Offset != se_offset) { Message->LogMsg(MSG_CHKLOG_NTFS_INCORRECT_OFFSET_IN_SDS_ENTRY, "%x%I64x%x%x", offset+((PCHAR)security_entry-(PCHAR)initial_security_entry), security_entry->security_descriptor_header.Offset, se_offset, securityId); security_entry->security_descriptor_header.Offset = se_offset; attribute_need_write = TRUE; DebugPrint("Repairing offset value of a security descriptor header.\n"); } // build a set with all the hashkey encountered hashkey.Set(hash, securityId); if (hashkey_entries.CheckAndAdd(hashkey, &alreadyExists)) { DebugAssert(!alreadyExists); // sid is unique thus hashkey } else { Message->DisplayMsg(MSG_CHK_NO_MEMORY); FREE(initial_security_entry); return FALSE; } // now we know the entry is unique and good // make sure there is a corresponding entry in // SecurityIdIndex and SecurityDescriptorHashIndex // index streams switch (security_frs.FindSecurityIndexEntryAndValidate( &SII_Index, (PVOID)&securityId, sizeof(securityId), &(security_entry->security_descriptor_header), Mft->GetVolumeBitmap(), FixLevel == CheckOnly)) { case NTFS_SECURITY_INDEX_FOUND: // good, entry already exists in the index break; // go onto next entry case NTFS_SECURITY_INDEX_FIXED: case NTFS_SECURITY_INDEX_DATA_ERROR: errFixedStatus = CHKDSK_EXIT_ERRS_FIXED; hasErrors = TRUE; DebugAssert(sizeof(securityId) == sizeof(ULONG)); Message->DisplayMsg(MSG_CHK_NTFS_REPAIRING_INDEX_ENTRY_WITH_ID, "%d%W%d", security_frs.QueryFileNumber().GetLowPart(), &SII_IndexName, securityId); frs_need_flush = TRUE; break; case NTFS_SECURITY_INDEX_ENTRY_MISSING: case NTFS_SECURITY_INDEX_INSERTED: errFixedStatus = CHKDSK_EXIT_ERRS_FIXED; hasErrors = TRUE; DebugAssert(sizeof(securityId) == sizeof(ULONG)); Message->DisplayMsg(MSG_CHK_NTFS_INSERTING_INDEX_ENTRY_WITH_ID, "%d%W%d", security_frs.QueryFileNumber().GetLowPart(), &SII_IndexName, securityId); frs_need_flush = TRUE; break; case NTFS_SECURITY_INSERT_FAILED: chkdskErrCouldNotFix = TRUE; Message->DisplayMsg(MSG_CHK_NTFS_CANT_FIX_INDEX, "%d%W", security_frs.QueryFileNumber().GetLowPart(), &SII_IndexName); break; case NTFS_SECURITY_ERROR: Message->DisplayMsg(MSG_CHK_NO_MEMORY); FREE(initial_security_entry); return FALSE; } switch (security_frs.FindSecurityIndexEntryAndValidate( &SDH_Index, (PVOID)&(security_entry->security_descriptor_header.HashKey), sizeof(security_entry->security_descriptor_header.HashKey), &(security_entry->security_descriptor_header), Mft->GetVolumeBitmap(), FixLevel == CheckOnly)) { case NTFS_SECURITY_INDEX_FOUND: // good, entry already exists in the index break; // go onto next entry case NTFS_SECURITY_INDEX_FIXED: case NTFS_SECURITY_INDEX_DATA_ERROR: //*DiskErrorsFound = TRUE; errFixedStatus = CHKDSK_EXIT_ERRS_FIXED; hasErrors = TRUE; Message->DisplayMsg(MSG_CHK_NTFS_REPAIRING_INDEX_ENTRY_WITH_ID, "%d%W%d", security_frs.QueryFileNumber().GetLowPart(), &SDH_IndexName, security_entry->security_descriptor_header. HashKey.SecurityId); frs_need_flush = TRUE; break; case NTFS_SECURITY_INDEX_ENTRY_MISSING: case NTFS_SECURITY_INDEX_INSERTED: //*DiskErrorsFound = TRUE; errFixedStatus = CHKDSK_EXIT_ERRS_FIXED; hasErrors = TRUE; Message->DisplayMsg(MSG_CHK_NTFS_INSERTING_INDEX_ENTRY_WITH_ID, "%d%W%d", security_frs.QueryFileNumber().GetLowPart(), &SDH_IndexName, security_entry->security_descriptor_header. HashKey.SecurityId); frs_need_flush = TRUE; break; case NTFS_SECURITY_INSERT_FAILED: chkdskErrCouldNotFix = TRUE; Message->DisplayMsg(MSG_CHK_NTFS_CANT_FIX_INDEX, "%d%W", security_frs.QueryFileNumber().GetLowPart(), &SDH_IndexName); break; case NTFS_SECURITY_ERROR: Message->DisplayMsg(MSG_CHK_NO_MEMORY); FREE(initial_security_entry); return FALSE; } GetNextSDEntry: if (length == num_bytes) { lengthOfBlock = (ULONG)((PCHAR)security_entry- (PCHAR)initial_security_entry+ num_bytes); break; // done, leave the while loop } else { length -= align_num_bytes; previous_previous_security_entry = previous_security_entry; previous_security_entry = security_entry; security_entry = (SECURITY_ENTRY*)((char *)security_entry + align_num_bytes); } } // while if (attribute_need_write) { errFixedStatus = CHKDSK_EXIT_ERRS_FIXED; hasErrors = TRUE; if (FixLevel != CheckOnly && (!SDS_attrib.Write(initial_security_entry, offset, bytesToRead, &bytesWritten, Mft->GetVolumeBitmap()) || bytesWritten != bytesToRead)) { chkdskErrCouldNotFix = TRUE; Message->DisplayMsg(MSG_CHK_NTFS_CANT_FIX_SECURITY_DATA_STREAM); } else frs_need_flush = TRUE; } if (lengthOfBlock) lengthUptoPreviousBlock = lengthOfBlock + offset; offset += (SecurityDescriptorsBlockSize<<1); remain_length -= bytesToRead; if (remain_length >= SecurityDescriptorsBlockSize) remain_length -= SecurityDescriptorsBlockSize; else remain_length = 0; length = remain_length; } // for if (attribute_need_resize) { hasErrors = TRUE; errFixedStatus = CHKDSK_EXIT_ERRS_FIXED; if (FixLevel != CheckOnly && !SDS_attrib.Resize(resizeTo + SecurityDescriptorsBlockSize, Mft->GetVolumeBitmap())) { chkdskErrCouldNotFix = TRUE; Message->DisplayMsg(MSG_CHK_NTFS_CANT_FIX_SECURITY_DATA_STREAM); } else { frs_need_flush = TRUE; if (FixLevel != CheckOnly && SDS_attrib.IsStorageModified() && !SDS_attrib.InsertIntoFile(&security_frs, Mft->GetVolumeBitmap())) { chkdskErrCouldNotFix = TRUE; Message->DisplayMsg(MSG_CHK_NTFS_CANT_FIX_SECURITY_DATA_STREAM); } } } if (frs_need_flush) { Message->DisplayMsg(MSG_CHK_NTFS_REPAIRING_SECURITY_FRS); if (FixLevel != CheckOnly && !security_frs.Flush(Mft->GetVolumeBitmap())) { Message->DisplayMsg(MSG_CHK_READABLE_FRS_UNWRITEABLE, "%d", security_frs.QueryFileNumber().GetLowPart()); FREE(initial_security_entry); return FALSE; } } ChkdskInfo->TotalNumSID = sid_entries.QueryCardinality().GetLowPart(); // now make sure each entry in the index has // a corresponding entry in the $SDS data stream index_need_save = FALSE; SII_Index.ResetIterator(); while (index_entry = SII_Index.GetNext(&depth, &error)) { securityId = *(ULONG*)GetIndexEntryValue(index_entry); if (!sid_entries.DoesIntersectSet(securityId, 1)) { index_need_save = TRUE; errFixedStatus = CHKDSK_EXIT_ERRS_FIXED; hasErrors = TRUE; Message->DisplayMsg(MSG_CHK_NTFS_DELETING_INDEX_ENTRY_WITH_ID, "%d%W%d", security_frs.QueryFileNumber().GetLowPart(), SII_Index.GetName(), securityId); if (FixLevel != CheckOnly && !SII_Index.DeleteCurrentEntry()) { Message->DisplayMsg(MSG_CHK_NO_MEMORY); FREE(initial_security_entry); return FALSE; } } else count_sid++; } // while if (index_need_save && FixLevel != CheckOnly) { if (!SII_Index.Save(&security_frs)) { chkdskErrCouldNotFix = TRUE; Message->DisplayMsg(MSG_CHK_NTFS_CANT_FIX_INDEX, "%d%W", security_frs.QueryFileNumber().GetLowPart(), SII_Index.GetName()); } if (!security_frs.Flush(Mft->GetVolumeBitmap())) { Message->DisplayMsg(MSG_CHK_READABLE_FRS_UNWRITEABLE, "%d", security_frs.QueryFileNumber().GetLowPart()); FREE(initial_security_entry); return FALSE; } } index_need_save = FALSE; SDH_Index.ResetIterator(); while (index_entry = SDH_Index.GetNext(&depth, &error)) { if (hashkey_entries.CheckAndRemove( *(BIG_INT*)GetIndexEntryValue(index_entry), &alreadyExists)) { if (!alreadyExists) { index_need_save = TRUE; errFixedStatus = CHKDSK_EXIT_ERRS_FIXED; hasErrors = TRUE; Message->DisplayMsg(MSG_CHK_NTFS_DELETING_INDEX_ENTRY_WITH_ID, "%d%W%d", security_frs.QueryFileNumber().GetLowPart(), SDH_Index.GetName(), ((PSECURITY_HASH_KEY)GetIndexEntryValue(index_entry))->SecurityId); if (FixLevel != CheckOnly && !SDH_Index.DeleteCurrentEntry()) { Message->DisplayMsg(MSG_CHK_NO_MEMORY); FREE(initial_security_entry); return FALSE; } } else count_hashkey++; } else { Message->DisplayMsg(MSG_CHK_NO_MEMORY); FREE(initial_security_entry); return FALSE; } } // while if (index_need_save && FixLevel != CheckOnly) { if (!SDH_Index.Save(&security_frs)) { chkdskErrCouldNotFix = TRUE; Message->DisplayMsg(MSG_CHK_NTFS_CANT_FIX_INDEX, "%d%W", security_frs.QueryFileNumber().GetLowPart(), SDH_Index.GetName()); } if (!security_frs.Flush(Mft->GetVolumeBitmap())) { Message->DisplayMsg(MSG_CHK_READABLE_FRS_UNWRITEABLE, "%d", security_frs.QueryFileNumber().GetLowPart()); FREE(initial_security_entry); return FALSE; } } if (FixLevel != CheckOnly && !chkdskErrCouldNotFix) { DebugAssert(count_hashkey == count_sid); } } else if (error) { Message->DisplayMsg(MSG_CHK_NO_MEMORY); return FALSE; } // if (!error && securityDescriptorStreamPresent) } else { DebugPrintTrace(("Hotfixed security frs still has problems\n")); return FALSE; } // now each valid entry in SecurityDescriptorStream has a corresponding // entry in SecurityIdIndex and SecurityDescriptorHashIndex // Compute the number of file records. n = Mft->GetDataAttribute()->QueryValueLength().GetLowPart() / Mft->QueryFrsSize(); #if defined(TIMING_ANALYSIS) && !defined(_AUTOCHECK_) time(&time1); timestr = ctime(&time1); timestr[strlen(timestr)-1] = 0; Message->DisplayMsg(MSG_CHK_NTFS_MESSAGE, "%s%s", "Before stage 3: ", timestr); #endif if (!StartProcessingSD(n, FixLevel, Mft, ChkdskReport, ChkdskInfo, &security_frs, BadClusters, &errFixedStatus, securityDescriptorStreamPresent, &sid_entries, &sid_entries2, &hasErrors, SkipEntriesScan, &chkdskErrCouldNotFix, Message)) { FREE(initial_security_entry); return FALSE; } #if defined(TIMING_ANALYSIS) && !defined(_AUTOCHECK_) time(&time2); Message->Lock(); Message->Set(MSG_CHK_NTFS_MESSAGE); timestr = ctime(&time2); timestr[strlen(timestr)-1] = 0; Message->Display("%s%s", "After stage 3: ", timestr); Message->Display("%s%d", "Elapsed time in seconds: ", (ULONG)difftime(time2, time1)); Message->Unlock(); #endif if (securityDescriptorStreamPresent) { // now remove those unused sid in the SecurityIdIndex SII_Index.ResetIterator(); // calculate the set of sid that are not in use sid_entries.Remove(&sid_entries2); sid_entries2.RemoveAll(); if (!chkdskErrCouldNotFix && (!hasErrors || (hasErrors && FixLevel != CheckOnly))) { cleanup_count = 0; DebugAssert(sid_entries.QueryCardinality().GetHighPart() == 0); for (i=0; i<sid_entries.QueryCardinality(); i++) { securityId = sid_entries.QueryNumber(i).GetLowPart(); while (index_entry = SII_Index.GetNext(&depth, &error)) { if (*(ULONG*)GetIndexEntryValue(index_entry) == securityId) { cleanup_count++; if (FixLevel != CheckOnly && !SII_Index.DeleteCurrentEntry()) { Message->DisplayMsg(MSG_CHK_NO_MEMORY); FREE(initial_security_entry); return FALSE; } break; } } // while #if DBG if (FixLevel != CheckOnly && !chkdskErrCouldNotFix) DebugAssert(index_entry != NULL); #endif } chkdskCleanUp = chkdskCleanUp || (cleanup_count != 0); if (cleanup_count) { if (ChkdskInfo->Verbose || hasErrors) { Message->DisplayMsg(MSG_CHK_NTFS_DELETING_UNUSED_INDEX_ENTRY, "%d%W%d", security_frs.QueryFileNumber().GetLowPart(), SII_Index.GetName(), cleanup_count); } else { Message->LogMsg(MSG_CHKLOG_NTFS_CLEANUP_INDEX_ENTRIES, "%I64x%W%d", security_frs.QueryFileNumber().GetLargeInteger(), SII_Index.GetName(), cleanup_count); } if (FixLevel != CheckOnly) { if (!SII_Index.Save(&security_frs)) { chkdskErrCouldNotFix = TRUE; Message->DisplayMsg(MSG_CHK_NTFS_CANT_FIX_INDEX, "%d%W", security_frs.QueryFileNumber().GetLowPart(), SII_Index.GetName()); } if (!security_frs.Flush(Mft->GetVolumeBitmap())) { Message->DisplayMsg(MSG_CHK_READABLE_FRS_UNWRITEABLE, "%d", security_frs.QueryFileNumber().GetLowPart()); FREE(initial_security_entry); return FALSE; } } } // // if the SII index is newly created, then include its size into // chkdsk report // if (new_SII_index) { alloc_present = security_frs.QueryAttribute(&attrib, &error, $INDEX_ALLOCATION, SII_Index.GetName()); if (!alloc_present && error) { Message->DisplayMsg(MSG_CHK_NO_MEMORY); FREE(initial_security_entry); return FALSE; } if (alloc_present) { ChkdskReport->BytesInIndices += attrib.QueryAllocatedLength(); } } // now removes those unused entries in SecurityDescriptorHashIndex if (sid_entries.QueryCardinality().GetLowPart()) { cleanup_count = 0; SDH_Index.ResetIterator(); while (index_entry = SDH_Index.GetNext(&depth, &error)) { securityId = ((PSECURITY_HASH_KEY)GetIndexEntryValue(index_entry)) ->SecurityId; if (sid_entries.DoesIntersectSet(securityId, 1)) { cleanup_count++; if (FixLevel != CheckOnly && !SDH_Index.DeleteCurrentEntry()) { Message->DisplayMsg(MSG_CHK_NO_MEMORY); FREE(initial_security_entry); return FALSE; } } } // while chkdskCleanUp = chkdskCleanUp || (cleanup_count != 0); if (cleanup_count) { if (ChkdskInfo->Verbose || hasErrors) { Message->DisplayMsg(MSG_CHK_NTFS_DELETING_UNUSED_INDEX_ENTRY, "%d%W%d", security_frs.QueryFileNumber().GetLowPart(), SDH_Index.GetName(), cleanup_count); } else { Message->LogMsg(MSG_CHKLOG_NTFS_CLEANUP_INDEX_ENTRIES, "%I64x%W%d", security_frs.QueryFileNumber().GetLargeInteger(), SDH_Index.GetName(), cleanup_count); } if (FixLevel != CheckOnly) { if (!SDH_Index.Save(&security_frs)) { chkdskErrCouldNotFix = TRUE; Message->DisplayMsg(MSG_CHK_NTFS_CANT_FIX_INDEX, "%d%W", security_frs.QueryFileNumber().GetLowPart(), SDH_Index.GetName()); } if (!security_frs.Flush(Mft->GetVolumeBitmap())) { Message->DisplayMsg(MSG_CHK_READABLE_FRS_UNWRITEABLE, "%d", security_frs.QueryFileNumber().GetLowPart()); FREE(initial_security_entry); return FALSE; } } } } // if // // if the SDH index is newly created, then include its size into // chkdsk report // if (new_SDH_index) { alloc_present = security_frs.QueryAttribute(&attrib, &error, $INDEX_ALLOCATION, SDH_Index.GetName()); if (!alloc_present && error) { Message->DisplayMsg(MSG_CHK_NO_MEMORY); FREE(initial_security_entry); return FALSE; } if (alloc_present) { ChkdskReport->BytesInIndices += attrib.QueryAllocatedLength(); } } // now null those unused entries in SecurityDescriptorStream if (sid_entries.QueryCardinality().GetLowPart()) { cleanup_count = 0; length = SDS_attrib.QueryValueLength().GetLowPart(); length -= SecurityDescriptorsBlockSize; offset = 0; frs_need_flush = FALSE; endOfBlock = (PSECURITY_ENTRY)((PCHAR)initial_security_entry+ SecurityDescriptorsBlockSize); remain_length = length; for (;length > 0;) { attribute_need_write = FALSE; bytesToRead = min(SecurityDescriptorsBlockSize, length); security_entry = initial_security_entry; if (!SDS_attrib.Read(security_entry, offset, bytesToRead, &num_bytes) || num_bytes != bytesToRead) { Message->DisplayMsg(MSG_CHK_NTFS_CANT_READ_SECURITY_DATA_STREAM); FREE(initial_security_entry); return FALSE; } while (length > 0) { // see if there is a need to move to next security descriptor block if (security_entry == endOfBlock || (security_entry->security_descriptor_header.Length == 0 && security_entry->security_descriptor_header.HashKey.SecurityId == 0 && security_entry->security_descriptor_header.HashKey.Hash == 0)) { break; } num_bytes = security_entry->security_descriptor_header.Length; securityId = security_entry->security_descriptor_header.HashKey.SecurityId; // skip over invalidated entries if (securityId == SECURITY_ID_INVALID) goto GetNextSDEntry2; if (sid_entries.DoesIntersectSet(securityId, 1)) { // fill the whole thing with zeros except the length byte in the header ClearSecurityDescriptorEntry(security_entry, security_entry->security_descriptor_header.Length - sizeof(SECURITY_DESCRIPTOR_HEADER)); attribute_need_write = TRUE; cleanup_count++; } GetNextSDEntry2: if (length == num_bytes) { break; // done, leave the while loop } else { align_num_bytes = (num_bytes + 0xf) & ~0xf; DebugAssert(length > align_num_bytes); length -= align_num_bytes; security_entry = (SECURITY_ENTRY*) ((PCHAR)security_entry + align_num_bytes); } } // while if (attribute_need_write) { DebugAssert(cleanup_count != 0); if (FixLevel != CheckOnly && (!SDS_attrib.Write(initial_security_entry, offset, bytesToRead, &bytesWritten, Mft->GetVolumeBitmap()) || bytesWritten != bytesToRead)) { chkdskErrCouldNotFix = TRUE; Message->DisplayMsg(MSG_CHK_NTFS_CANT_FIX_SECURITY_DATA_STREAM); } else frs_need_flush = TRUE; } offset += (SecurityDescriptorsBlockSize<<1); remain_length -= bytesToRead; if (remain_length >= SecurityDescriptorsBlockSize) remain_length -= SecurityDescriptorsBlockSize; else remain_length = 0; length = remain_length; } // for chkdskCleanUp = chkdskCleanUp || (cleanup_count != 0); if (frs_need_flush) { DebugAssert(cleanup_count != 0); if (ChkdskInfo->Verbose || hasErrors) { Message->DisplayMsg(MSG_CHK_NTFS_CLEANUP_UNUSED_SECURITY_DESCRIPTORS, "%d", cleanup_count); } else { Message->LogMsg(MSG_CHKLOG_NTFS_CLEANUP_UNUSED_SECURITY_DESCRIPTORS, "%d", cleanup_count); } if (FixLevel != CheckOnly && !security_frs.Flush(Mft->GetVolumeBitmap())) { Message->DisplayMsg(MSG_CHK_READABLE_FRS_UNWRITEABLE, "%d", security_frs.QueryFileNumber().GetLowPart()); FREE(initial_security_entry); return FALSE; } } } // if } // if // now make sure the first copy of the security descriptors in the data // stream matches that in the mirror copy FREE(initial_security_entry); if (!(initial_security_entry = (PSECURITY_ENTRY) MALLOC(SecurityDescriptorsBlockSize<<1))) { Message->DisplayMsg(MSG_CHK_NO_MEMORY); return FALSE; } total_length = SDS_attrib.QueryValueLength().GetLowPart(); length = (SecurityDescriptorsBlockSize<<1); fixing_mirror = FALSE; for (offset=0; offset < total_length; offset+=length) { bytesToRead = min(length, total_length-offset); if (!SDS_attrib.Read(initial_security_entry, offset, bytesToRead, &num_bytes) || num_bytes != bytesToRead) { Message->DisplayMsg(MSG_CHK_NTFS_CANT_READ_SECURITY_DATA_STREAM); FREE(initial_security_entry); return FALSE; } bytesToRead -= SecurityDescriptorsBlockSize; if (memcmp((PVOID)initial_security_entry, (PVOID)((PCHAR)initial_security_entry+ SecurityDescriptorsBlockSize), bytesToRead)) { if (hasErrors || ChkdskInfo->Verbose || !chkdskCleanUp) { Message->LogMsg(MSG_CHKLOG_NTFS_INCORRECT_SDS_MIRROR, "%x", offset); } if (hasErrors || !chkdskCleanUp) errFixedStatus = CHKDSK_EXIT_ERRS_FIXED; if (FixLevel != CheckOnly && (!SDS_attrib.Write(initial_security_entry, offset+SecurityDescriptorsBlockSize, bytesToRead, &bytesWritten, Mft->GetVolumeBitmap()) || bytesToRead != bytesWritten)) { chkdskErrCouldNotFix = TRUE; Message->DisplayMsg(MSG_CHK_NTFS_CANT_FIX_SECURITY_DATA_STREAM); } else fixing_mirror = TRUE; } } // for if (fixing_mirror) { if (hasErrors || ChkdskInfo->Verbose || !chkdskCleanUp) { Message->DisplayMsg(MSG_CHK_NTFS_FIXING_SECURITY_DATA_STREAM_MIRROR); } if (FixLevel != CheckOnly && !security_frs.Flush(Mft->GetVolumeBitmap())) { Message->DisplayMsg(MSG_CHK_NTFS_CANT_FIX_SECURITY_DATA_STREAM); FREE(initial_security_entry); return FALSE; } } FREE(initial_security_entry); } // if (securityDescriptorStreamPresent) Message->DisplayMsg(MSG_CHK_NTFS_SECURITY_VERIFICATION_COMPLETED, PROGRESS_MESSAGE); UPDATE_EXIT_STATUS_FIXED(errFixedStatus, ChkdskInfo); if (chkdskErrCouldNotFix) ChkdskInfo->ExitStatus = CHKDSK_EXIT_COULD_NOT_FIX; else if (chkdskCleanUp) { _cleanup_that_requires_reboot = TRUE; if (ChkdskInfo->ExitStatus == CHKDSK_EXIT_SUCCESS) ChkdskInfo->ExitStatus = CHKDSK_EXIT_MINOR_ERRS; } return TRUE; } #endif // _SETUP_LOADER_ ULONG ComputeSecurityDescriptorHash( IN PSECURITY_DESCRIPTOR SecurityDescriptor, IN ULONG Length ) { ULONG hash = 0; ULONG count = Length / 4; PULONG rover = (PULONG)SecurityDescriptor; DebugAssert(rover); if (!rover) return 0; while (count--) { hash = ((hash << 3) | (hash >> (32-3))) + *rover++; } return hash; } ULONG ComputeDefaultSecurityId( PNUMBER_SET SidSet ) { BIG_INT start; BIG_INT length; if (SidSet->QueryCardinality() == 0) return SECURITY_ID_FIRST; SidSet->QueryDisjointRange(0, &start, &length); if (start > SECURITY_ID_FIRST) return SECURITY_ID_FIRST; else { start += length; DebugAssert(start.GetHighPart() == 0); return start.GetLowPart(); } } VOID ClearSecurityDescriptorEntry( IN OUT PSECURITY_ENTRY Security_entry, IN ULONG SecurityDescriptorSize ) { Security_entry->security_descriptor_header.Offset = Security_entry->security_descriptor_header.HashKey.Hash = 0; Security_entry->security_descriptor_header.HashKey.SecurityId = SECURITY_ID_INVALID; memset(&(Security_entry->security), 0, SecurityDescriptorSize); } VOID MarkEndOfSecurityDescriptorsBlock( IN OUT PSECURITY_ENTRY Security_entry, IN ULONG LengthOfBlock ) { // zero the length, hash values, and set invalid SID // also zero the rest of the block memset(Security_entry, 0, LengthOfBlock); DebugAssert(SECURITY_ID_INVALID == 0); } BOOLEAN RemainingBlockIsZero( IN OUT PCHAR Buffer, IN ULONG Size ) { PCHAR endp; endp = Buffer+Size; while (Buffer < endp) if (*Buffer == 0) Buffer++; else return FALSE; return TRUE; } BOOLEAN RecoverSecurityDescriptorsDataStream( IN OUT PNTFS_FILE_RECORD_SEGMENT Frs, IN OUT PNTFS_ATTRIBUTE Attrib, IN ULONG AttributeSize, IN PCHAR Buffer, IN ULONG BufferSize, IN ULONG ClusterSize, IN OUT PNTFS_BITMAP Bitmap, OUT PBOOLEAN DiskHasErrors, IN OUT PNUMBER_SET BadClusters, IN OUT PMESSAGE Message, IN BOOLEAN FixLevel ) /*++ Routine Description: This method replaces all those unreadable clusters with readable one. It grabs data from the mirror copy of the stream for those new clusters. Arguments: Return Value: TRUE upon successful completion. --*/ { PREPAIR_RECORD pRecord, temp; PREPAIR_RECORD pFirstRecord; USHORT recordCount = 0; ULONG repair_record_array_size; NUMBER_SET badClusterNumSet; BIG_INT currentBytesRecovered; ULONG bytesToRead; ULONG offset; ULONG length; ULONG num_bytes; BOOLEAN main_stream_has_errors, mirror_stream_has_errors, unused_space_has_errors; BOOLEAN result = TRUE; // // sanity check // DebugAssert(BufferSize == SecurityDescriptorsBlockSize); *DiskHasErrors = FALSE; main_stream_has_errors = FALSE; mirror_stream_has_errors = FALSE; unused_space_has_errors = FALSE; repair_record_array_size = (SecurityDescriptorsBlockSize/ ClusterSize); if (!badClusterNumSet.Initialize() || !(pRecord = (PREPAIR_RECORD)MALLOC(repair_record_array_size*sizeof(REPAIR_RECORD)))) { Message->DisplayMsg(MSG_CHK_NO_MEMORY); return FALSE; } offset = 0; length = AttributeSize; if (length < SecurityDescriptorsBlockSize) { // doesn't matter as the stream will be zapped FREE(pRecord); if (FixLevel != CheckOnly) { // no need to say disk has errors as its length is invalid anyway result = Attrib->RecoverAttribute(Bitmap, &badClusterNumSet, &currentBytesRecovered); } else { FREE(pRecord); return TRUE; } } else { length -= SecurityDescriptorsBlockSize; while (length > 0) { bytesToRead = min(length, BufferSize); // // check is there are disk errors reading the // main SDS stream // if (!Attrib->Read(Buffer, offset, bytesToRead, &num_bytes)) { RepairSecurityDescriptorsSegment(Attrib, Buffer, offset, bytesToRead, pRecord, &recordCount, ClusterSize); main_stream_has_errors = TRUE; // // We need to grow the REPAIR_RECORD array if // necessary. Every pass of the while loop // can add at most ( clusters per security descriptor // block / 2 ) records. This worst case occurs when // the good and bad clusters occur alternately in the // security descriptor stream x, x+2, x+4 ... and y+1, // y+3, y+5, ... are bad clusters where x and y are // correcponding VCNs in the main and mirror SDS // streams respectively, that is, y = x + 256 Kbytes // if ((repair_record_array_size - recordCount) < ((SecurityDescriptorsBlockSize / ClusterSize) / 2)) { repair_record_array_size += (SecurityDescriptorsBlockSize / ClusterSize) / 2; if (!(temp = (PREPAIR_RECORD)MALLOC(repair_record_array_size*sizeof(REPAIR_RECORD)))) { Message->DisplayMsg(MSG_CHK_NO_MEMORY); return FALSE; } memcpy(temp, pRecord, recordCount*sizeof(REPAIR_RECORD)); FREE(pRecord); pRecord = temp; } } // // check if there are disk errors reading the // unused portion of the main SDS stream // if ((bytesToRead < SecurityDescriptorsBlockSize) && !Attrib->Read(Buffer, offset+bytesToRead, SecurityDescriptorsBlockSize-bytesToRead, &num_bytes)) { unused_space_has_errors = TRUE; } // // check if there are disk errors reading the // mirror SDS stream // if (!Attrib->Read(Buffer, offset+SecurityDescriptorsBlockSize, bytesToRead, &num_bytes)) { mirror_stream_has_errors = TRUE; } offset += (SecurityDescriptorsBlockSize<<1); length -= bytesToRead; if (length > SecurityDescriptorsBlockSize) length -= SecurityDescriptorsBlockSize; else length = 0; } // // Update the return variable so that the caller knows there // were errors // *DiskHasErrors = main_stream_has_errors || mirror_stream_has_errors || unused_space_has_errors; if (*DiskHasErrors) { Message->DisplayMsg(MSG_CHK_NTFS_REPAIRING_UNREADABLE_SECURITY_DATA_STREAM); } else { FREE(pRecord); return TRUE; } // // We have already printed a message - if we cannot fix stuff // because we are not in fix more, exit now // if (FixLevel == CheckOnly) { FREE(pRecord); return TRUE; } // // We do this even if we can read the main SDS stream just fine // (main_stream_has_errors == FALSE), because we want to fix any bad // clusters in the SDS mirror stream as well // if (Attrib->RecoverAttribute(Bitmap, &badClusterNumSet, &currentBytesRecovered)) { if (main_stream_has_errors) { // // We had found errors reading the main SDS stream, so // fix those regions of the main SDS stream with the mirror // pFirstRecord = pRecord; while (recordCount-- > 0) { offset = pFirstRecord->Offset; bytesToRead = pFirstRecord->Length; pFirstRecord++; if (Attrib->Read(Buffer, offset+SecurityDescriptorsBlockSize, bytesToRead, &num_bytes) && num_bytes == bytesToRead) { if (!Attrib->Write(Buffer, offset, bytesToRead, &num_bytes, NULL) || num_bytes != bytesToRead) { Message->DisplayMsg(MSG_CHK_NTFS_CANT_FIX_SECURITY_DATA_STREAM); result = FALSE; break; } } else { Message->DisplayMsg(MSG_CHK_NTFS_CANT_READ_SECURITY_DATA_STREAM); result = FALSE; break; } } // while } } else { // // Could not recover the attribute // result = FALSE; } } if (result && Attrib->IsStorageModified() && !Attrib->InsertIntoFile(Frs, Bitmap)) { Message->DisplayMsg(MSG_CHK_NTFS_CANT_FIX_ATTRIBUTE, "%d%d", $DATA, Frs->QueryFileNumber().GetLowPart()); result = FALSE; } if (!BadClusters->Add(&badClusterNumSet)) { Message->DisplayMsg(MSG_CHK_NO_MEMORY); result = FALSE; } FREE(pRecord); return result; } BOOLEAN RepairSecurityDescriptorsSegment( IN OUT PNTFS_ATTRIBUTE Attrib, IN PCHAR Buffer, IN ULONG Offset, IN ULONG BytesToProcess, IN OUT PREPAIR_RECORD Record, IN OUT USHORT *RecordCount, IN ULONG ClusterSize ) /*++ Routine Description: This method identifies all those records that can be fixed up by reading the data out from the mirror copy. Arguments: Return Value: TRUE if all unreadable records can be recovered with no loss of data. FALSE if not all unreadable records can be recovered with no loss of data. --*/ { ULONG bytesToRead; ULONG num_bytes; BOOLEAN completeRecovery = TRUE; bytesToRead = BytesToProcess/2; if (!Attrib->Read(Buffer, Offset, bytesToRead, &num_bytes) || bytesToRead != num_bytes) { if (!Attrib->Read(Buffer, Offset+SecurityDescriptorsBlockSize, bytesToRead, &num_bytes)) { if (bytesToRead > ClusterSize) { completeRecovery = completeRecovery && RepairSecurityDescriptorsSegment(Attrib, Buffer, Offset, bytesToRead, Record, RecordCount, ClusterSize); } else return FALSE; } else { Record[*RecordCount].Offset = Offset; Record[(*RecordCount)++].Length = bytesToRead; } } bytesToRead = BytesToProcess-bytesToRead; if (!Attrib->Read(Buffer, Offset+bytesToRead, bytesToRead, &num_bytes) || bytesToRead != num_bytes) { if (!Attrib->Read(Buffer, Offset+bytesToRead+SecurityDescriptorsBlockSize, bytesToRead, &num_bytes)) { if (bytesToRead > ClusterSize) { completeRecovery = completeRecovery && RepairSecurityDescriptorsSegment(Attrib, Buffer, Offset+bytesToRead, bytesToRead, Record, RecordCount, ClusterSize); } else return FALSE; } else { Record[*RecordCount].Offset = Offset + bytesToRead; Record[(*RecordCount)++].Length = bytesToRead; } } return completeRecovery; }
43.266736
120
0.456023
npocmaka
5027a961a31bd63de8712839d03c886a036034a1
4,102
cpp
C++
src/test/cpp/test_thread_map.cpp
slaveuser/honest-profiler20190422
211eaa26603286badb4d4f4ad641dd0a3e5342bf
[ "Apache-2.0", "MIT" ]
674
2017-03-26T20:42:58.000Z
2022-03-31T03:54:56.000Z
src/test/cpp/test_thread_map.cpp
slaveuser/honest-profiler20190422
211eaa26603286badb4d4f4ad641dd0a3e5342bf
[ "Apache-2.0", "MIT" ]
88
2017-04-06T08:47:36.000Z
2022-02-21T21:47:11.000Z
src/test/cpp/test_thread_map.cpp
slaveuser/honest-profiler20190422
211eaa26603286badb4d4f4ad641dd0a3e5342bf
[ "Apache-2.0", "MIT" ]
90
2017-03-28T11:40:34.000Z
2022-03-19T15:50:52.000Z
#include "test.h" #ifndef DISABLE_CPP11 #include "../../main/cpp/thread_map.h" #include <memory> #include <thread> #include <vector> #define ptr() std::unique_ptr<JNIEnv>((JNIEnv *)new int(0)) TEST(ThreadMapPutGetDeleteTest) { ThreadMap map; auto p1 = ptr(); auto pid = 999; auto name = "name321"; // map is empty CHECK(!map.get(p1.get()).defined()); map.put(p1.get(), name, pid); // try to create temporary references to the bucket for (int i = 0; i < 4; i++) { ThreadBucketPtr r1 = map.get(p1.get()); CHECK(r1.defined()); CHECK_EQUAL(pid, r1->tid); CHECK_EQUAL(name, r1->name); } map.remove(p1.get()); // map is empty again CHECK(!map.get(p1.get()).defined()); } TEST(ThreadMapUpdateTest) { ThreadMap map; auto p1 = ptr(); auto pid1 = 999, pid2 = 111; auto name1 = "name321", name2 = "name123"; // map is empty CHECK(!map.get(p1.get()).defined()); map.put(p1.get(), name1, pid1); { ThreadBucketPtr r1 = map.get(p1.get()); CHECK(r1.defined()); CHECK_EQUAL(pid1, r1->tid); CHECK_EQUAL(name1, r1->name); } // update map.put(p1.get(), name2, pid2); { ThreadBucketPtr r1 = map.get(p1.get()); CHECK(r1.defined()); CHECK_EQUAL(pid2, r1->tid); CHECK_EQUAL(name2, r1->name); } map.remove(p1.get()); // map is empty again CHECK(!map.get(p1.get()).defined()); } TEST(ThreadMapPutDeleteGetTest) { ThreadMap map; auto p1 = ptr(); auto pid = 999; auto name = "name321"; // map is empty CHECK(!map.get(p1.get()).defined()); map.put(p1.get(), name, pid); { ThreadBucketPtr r1 = map.get(p1.get()), r2 = map.get(p1.get()), r3 = map.get(p1.get()); map.remove(p1.get()); CHECK(!map.get(p1.get()).defined()); CHECK(r1.defined()); CHECK(r2.defined()); CHECK(r3.defined()); CHECK_EQUAL(pid, r2->tid); CHECK_EQUAL(name, r2->name); } CHECK(!map.get(p1.get()).defined()); } TEST(ThreadMapAssignResetTest) { ThreadMap map; auto p1 = ptr(), p2 = ptr(); auto pid1 = 999, pid2 = 111; auto name1 = "name321", name2 = "name123"; // map is empty CHECK(!map.get(p1.get()).defined()); CHECK(!map.get(p2.get()).defined()); map.put(p1.get(), name1, pid1); map.put(p2.get(), name2, pid2); { ThreadBucketPtr r1 = map.get(p1.get()); CHECK(r1.defined()); CHECK_EQUAL(pid1, r1->tid); CHECK_EQUAL(name1, r1->name); map.remove(p1.get()); CHECK(!map.get(p1.get()).defined()); r1 = map.get(p2.get()); CHECK(r1.defined()); CHECK_EQUAL(pid2, r1->tid); CHECK_EQUAL(name2, r1->name); map.remove(p2.get()); CHECK(!map.get(p2.get()).defined()); r1.reset(); CHECK(!r1.defined()); r1.reset(); } // map is empty CHECK(!map.get(p1.get()).defined()); CHECK(!map.get(p2.get()).defined()); } void reader(ThreadMap &map, const int id, JNIEnv *const p, std::atomic_int &read) { ThreadBucketPtr ptr = map.get(p); std::string name("thread-" + std::to_string(id)); while (!ptr.defined()) { sched_yield(); ptr = map.get(p); } read.fetch_add(1, std::memory_order_seq_cst); do { CHECK_EQUAL(name, ptr->name); CHECK_EQUAL(id, ptr->tid); } while ((ptr = map.get(p)).defined()); } TEST(ThreadMapConcurrentTest) { const int sz = 4; ThreadMap map; std::atomic_int read(0); std::vector<std::unique_ptr<JNIEnv>> ps(sz); std::vector<std::thread> tvec(sz); for (auto it = ps.begin(); it != ps.end(); ++it) { *it = ptr(); int id = it - ps.begin(); tvec[id] = std::thread(reader, std::ref(map), id, it->get(), std::ref(read)); } for (auto it = ps.begin(); it != ps.end(); ++it) { int id = it - ps.begin(); std::string name("thread-" + std::to_string(id)); map.put(it->get(), name.c_str(), id); } while (read.load(std::memory_order_acquire) != sz) sched_yield(); for (auto it = ps.begin(); it != ps.end(); ++it) { map.remove(it->get()); } for (auto it = tvec.begin(); it != tvec.end(); ++it) { it->join(); CHECK(!map.get(ps[it - tvec.begin()].get()).defined()); } } #endif // DISABLE_CPP11
21.703704
91
0.586787
slaveuser
502adbbb70f2ae9c1a7186c42445eac4836a4a00
4,895
cpp
C++
src/confseq/boundaries.cpp
gostevehoward/confseq
a4d85ba77ccbde4b10ec4f73530122dc32b45178
[ "MIT" ]
28
2019-09-23T19:19:11.000Z
2022-01-25T18:40:28.000Z
src/confseq/boundaries.cpp
WannabeSmith/confseq
8c847f8915e553c9fd1a7f3f0fec8f36e2074d42
[ "MIT" ]
10
2019-09-23T02:41:12.000Z
2022-01-12T02:14:07.000Z
src/confseq/boundaries.cpp
WannabeSmith/confseq
8c847f8915e553c9fd1a7f3f0fec8f36e2074d42
[ "MIT" ]
4
2019-09-23T01:36:30.000Z
2021-06-24T19:51:03.000Z
#include <pybind11/numpy.h> #include <pybind11/pybind11.h> #include "uniform_boundaries.h" using namespace pybind11::literals; PYBIND11_MODULE(boundaries, m) { m.doc() = R"pbdoc( Uniform boundaries and mixture supermartingales. See package documentation at https://github.com/gostevehoward/confseq. All `*_bound()` functions implement uniform boundaries, and accept intrinsic time `v` at which to evaluate the bound and crossing probability `alpha`. All `*_log_mixture()` functions evaluate the logarithm of the mixture supermartingale, and accept `s`, the value of the underlying martingale, and `v`, the intrinsic time value. All mixture functions accept `v_opt` and optionally `alpha_opt`. The mixtures are then tuned to optimize the uniform boundary with crossing probability `alpha_opt` at intrinsic time `v_opt`. )pbdoc"; m.def("normal_log_mixture", pybind11::vectorize(confseq::normal_log_mixture), R"pbdoc( Logarithm of mixture supermartingale for the one- or two-sided normal mixture. )pbdoc", "s"_a, "v"_a, "v_opt"_a, "alpha_opt"_a=0.05, "is_one_sided"_a=true); m.def("normal_mixture_bound", pybind11::vectorize(confseq::normal_mixture_bound), R"pbdoc( One- or two-sided normal mixture uniform boundary. )pbdoc", "v"_a, "alpha"_a, "v_opt"_a, "alpha_opt"_a=0.05, "is_one_sided"_a=true); m.def("gamma_exponential_log_mixture", pybind11::vectorize(confseq::gamma_exponential_log_mixture), R"pbdoc( Logarithm of mixture supermartingale for the gamma-exponential mixture. `c` is the sub-exponential scale parameter. )pbdoc", "s"_a, "v"_a, "v_opt"_a, "c"_a, "alpha_opt"_a=0.05); m.def("gamma_exponential_mixture_bound", pybind11::vectorize(confseq::gamma_exponential_mixture_bound), R"pbdoc( Gamma-exponential mixture uniform boundary. `c` is the sub-exponential scale parameter. )pbdoc", "v"_a, "alpha"_a, "v_opt"_a, "c"_a, "alpha_opt"_a=0.05); m.def("gamma_poisson_log_mixture", pybind11::vectorize(confseq::gamma_poisson_log_mixture), R"pbdoc( Logarithm of mixture supermartingale for the gamma-Poisson mixture. `c` is the sub-Poisson scale parameter. )pbdoc", "s"_a, "v"_a, "v_opt"_a, "c"_a, "alpha_opt"_a=0.05); m.def("gamma_poisson_mixture_bound", pybind11::vectorize(confseq::gamma_poisson_mixture_bound), R"pbdoc( Gamma-Poisson mixture uniform boundary. `c` is the sub-Poisson scale parameter. )pbdoc", "v"_a, "alpha"_a, "v_opt"_a, "c"_a, "alpha_opt"_a=0.05); m.def("beta_binomial_log_mixture", pybind11::vectorize(confseq::beta_binomial_log_mixture), R"pbdoc( Logarithm of mixture supermartingale for the one- or two-sided beta-binomial mixture. `g` and `h` are the sub-Bernoulli range parameter. )pbdoc", "s"_a, "v"_a, "v_opt"_a, "g"_a, "h"_a, "alpha_opt"_a=0.05, "is_one_sided"_a=true); m.def("beta_binomial_mixture_bound", pybind11::vectorize(confseq::beta_binomial_mixture_bound), R"pbdoc( One- or two-sided beta-binomial mixture uniform boundary. `g` and `h` are the sub-Bernoulli range parameter. )pbdoc", "v"_a, "alpha"_a, "v_opt"_a, "g"_a, "h"_a, "alpha_opt"_a=0.05, "is_one_sided"_a=true); m.def("poly_stitching_bound", pybind11::vectorize(confseq::poly_stitching_bound), R"pbdoc( Polynomial stitched uniform boundary. * `v_min`: optimized-for intrinsic time * `c`: sub-gamma scale parameter * `s`: controls how crossing probability is distribted over epochs * `eta`: controls the spacing of epochs )pbdoc", "v"_a, "alpha"_a, "v_min"_a, "c"_a=0, "s"_a=1.4, "eta"_a=2); m.def("bernoulli_confidence_interval", &confseq::bernoulli_confidence_interval, R"pbdoc( Confidence sequence for [0, 1]-bounded distributions. This function returns confidence bounds for the mean of a Bernoulli distribution, or more generally, any distribution with support in the unit interval [0, 1]. (This applies to any bounded distribution after rescaling.) The confidence bounds form a confidence sequence, so are guaranteed to cover the true mean uniformly over time with probability 1 - `alpha`. * `num_successes`: number of "successful" Bernoulli trials seen so far, or more generally, sum of observed outcomes. * `num_trials`: total number of observations seen so far. )pbdoc", "num_successes"_a, "num_trials"_a, "alpha"_a, "t_opt"_a, "alpha_opt"_a=0.05); }
40.454545
80
0.654137
gostevehoward
df22d6fb0922146e60a9b0e2c2d89d190103a6bf
5,990
cc
C++
uw_cse333/hw/hw3/hw3fsck/fileindexutil.cc
tavaresdong/courses-notes
7fb89103bca679f5ef9b14cbc777152daac1402e
[ "MIT" ]
null
null
null
uw_cse333/hw/hw3/hw3fsck/fileindexutil.cc
tavaresdong/courses-notes
7fb89103bca679f5ef9b14cbc777152daac1402e
[ "MIT" ]
1
2017-07-31T08:15:26.000Z
2017-07-31T08:15:26.000Z
uw_cse333/hw/hw3/hw3fsck/fileindexutil.cc
tavaresdong/courses-notes
7fb89103bca679f5ef9b14cbc777152daac1402e
[ "MIT" ]
1
2019-10-06T16:52:31.000Z
2019-10-06T16:52:31.000Z
/* * Copyright 2011 Steven Gribble * * This file is part of the UW CSE 333 course project sequence * (333proj). * * 333proj 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. * * 333proj 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 333proj. If not, see <http://www.gnu.org/licenses/>. */ #include <assert.h> // for assert() #include <iostream> // for std::cout / std::endl #include "./fileindexutil.h" namespace hw3 { // Initialize the "CRC32::table_is_initialized" static member variable. bool CRC32::table_is_initialized_ = false; // We need this declaration here so we can refer to the table_ below. uint32_t CRC32::table_[256]; static uint32_t CRC32Reflect(uint32_t reflectme, const char c) { uint32_t val = 0; int position; // Swap bit 0 for bit 7, bit 1 For bit 6, etc.... for (position = 1; position < (c + 1); position++) { if (reflectme & 1) { val |= (1 << (c - position)); } reflectme >>= 1; } return val; } CRC32::CRC32(void) { if (!table_is_initialized_) { // Yes, there is a potential race condition if multiple threads // construct the very first CRC32() objects simultaneously. We'll // live with it. ;) Initialize(); table_is_initialized_ = true; } // Prep the CRC32 state. finalized_ = false; crc_state_ = 0xFFFFFFFF; } void CRC32::FoldByteIntoCRC(const uint8_t nextbyte) { assert(finalized_ != true); crc_state_ = (crc_state_ >> 8) ^ this->table_[(crc_state_ & 0xFF) ^ nextbyte]; } uint32_t CRC32::GetFinalCRC(void) { if (!finalized_) { finalized_ = true; crc_state_ ^= 0xffffffff; } return crc_state_; } void CRC32::Initialize(void) { uint32_t polynomial = 0x04C11DB7; uint32_t codes, position; // Initialize the CRC32 lookup table; the table's 256 values // represent ASCII character codes. for (codes = 0; codes <= 0xFF; codes++) { CRC32::table_[codes] = CRC32Reflect(codes, 8) << 24; for (position = 0; position < 8; position++) { table_[codes] = (table_[codes] << 1) ^ ((table_[codes] & (1 << 31)) ? polynomial : 0); } this->table_[codes] = CRC32Reflect(table_[codes], 32); } } FILE *FileDup(FILE *f) { // Duplicate the underlying file descriptor using dup(). int newfd = dup(fileno(f)); assert(newfd != -1); // Use fdopen() to open a new (FILE *) for the dup()'ed descriptor. FILE *retfile = fdopen(newfd, "rb"); assert(retfile != NULL); // Return the new (FILE *). return retfile; } string c1, c2, c3; void UpdateGlobals(string s1, string s2, string s3) { c1 = s1; c2 = s2; c3 = s3; } void PrintContext() { cout << c1 << c2 << c3; if (c1 != string("")) cout << endl; } bool Check16(uint16_t expected, uint16_t actual, string fieldname) { if (expected == actual) return true; PrintContext(); cout << hex; cout << fieldname << ": expected " << expected; cout << ", but actually is " << actual << "."; if (ntohs(actual) == expected) { cout << " Note: you likely "; cout << "forgot an endianness conversion, since ntohs(actual) "; cout << "== expected."; } cout << endl; return false; } bool Check32(uint32_t expected, uint32_t actual, string fieldname) { if (expected == actual) return true; PrintContext(); cout << hex; cout << fieldname << ": expected " << expected; cout << ", but actually is " << actual << "."; if (ntohl(actual) == expected) { cout << " Note: you likely "; cout << "forgot an endianness conversion, since ntohl(actual) "; cout << "== expected."; } cout << endl; return false; } bool Check64(uint64_t expected, uint64_t actual, string fieldname) { if (expected == actual) return true; PrintContext(); cout << hex; cout << fieldname << ": expected " << expected; cout << ", but actually is " << actual << "."; if (ntohll(actual) == expected) { cout << " Note: you likely "; cout << "forgot an endianness conversion, since ntohll(actual) "; cout << "== expected."; } cout << endl; return false; } bool CheckLT16(uint16_t smaller, uint16_t bigger, string fieldname) { if (smaller < bigger) return true; PrintContext(); cout << hex; cout << fieldname << ": expected " << smaller; cout << " < " << bigger << "."; if (ntohs(smaller) == bigger) { cout << " Note: there is a chance that you "; cout << "forgot an endianness conversion, since ntohs(" << smaller; cout << ") = " << ntohs(smaller) << " < " << bigger << "."; } cout << endl; return false; } bool CheckLT32(uint32_t smaller, uint32_t bigger, string fieldname) { if (smaller < bigger) return true; PrintContext(); cout << hex; cout << fieldname << ": expected " << smaller; cout << " < " << bigger << "."; if (ntohl(smaller) == bigger) { cout << " Note: it's possible that you "; cout << "forgot an endianness conversion, since ntohl(" << smaller; cout << ") = " << ntohl(smaller) << " < " << bigger << "."; } cout << endl; return false; } bool CheckLT64(uint64_t smaller, uint64_t bigger, string fieldname) { if (smaller < bigger) return true; PrintContext(); cout << hex; cout << fieldname << ": expected " << smaller; cout << " < " << bigger << "."; if (ntohll(smaller) == bigger) { cout << " Note: it's possible that you "; cout << "forgot an endianness conversion, since ntohll(" << smaller; cout << ") = " << ntohll(smaller) << " < " << bigger << "."; } cout << endl; return false; } } // namespace hw3
26.981982
72
0.621536
tavaresdong
df25ca3b040496c41625f5e1557b0e1f788b29f4
654
cpp
C++
Algorithms/Strings/two-strings.cpp
CodeLogist/hackerrank-solutions
faecc4c9563a017eb61e83f0025aa9eb78fd33a1
[ "MIT" ]
73
2016-09-14T18:20:41.000Z
2022-02-05T14:58:04.000Z
Algorithms/Strings/two-strings.cpp
A-STAR0/hackerrank-solutions-1
518cdd9049477d70c499ba4f51f06ac99178f0ab
[ "MIT" ]
3
2017-03-03T01:12:31.000Z
2020-04-18T16:51:59.000Z
Algorithms/Strings/two-strings.cpp
A-STAR0/hackerrank-solutions-1
518cdd9049477d70c499ba4f51f06ac99178f0ab
[ "MIT" ]
69
2017-03-02T19:03:54.000Z
2022-03-29T12:35:38.000Z
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; bool check(const string& _a, const string& _b) { // O(n*m) lol no thanks // more like O(n+m+52) bool arr[52] = {false}; for(auto& a : _a) arr[a - 'a'] = true; for(auto& b : _b) arr[b - 'a' + 26] = true; for(int i = 0; i < 26; i++) if (arr[i] && arr[i+26]) return true; return false; } int main() { int t; cin >> t; string a, b; while (t-- > 0) { cin >> a >> b; cout << (check(a,b) ? "YES" : "NO") << endl; } return 0; }
19.235294
52
0.472477
CodeLogist
df276a14ee404b07e07c2344fdf9670154d65cc7
13,301
cpp
C++
cisstICP/cisstICP/DirPDTreeNode.cpp
sbillin/IMLP
38cbf6f528747ab5421f02f50b9bc3cd416cff8c
[ "BSD-3-Clause" ]
14
2015-05-15T08:54:19.000Z
2021-12-14T06:16:37.000Z
cisstICP/DirPDTreeNode.cpp
Xingorno/cisstICP
dfa00db642a25500946a0c70a900fbc68e5af248
[ "BSD-3-Clause" ]
3
2017-01-11T15:10:31.000Z
2020-12-28T16:16:32.000Z
cisstICP/DirPDTreeNode.cpp
Xingorno/cisstICP
dfa00db642a25500946a0c70a900fbc68e5af248
[ "BSD-3-Clause" ]
8
2015-01-07T20:28:12.000Z
2018-07-13T15:40:39.000Z
// **************************************************************************** // // Copyright (c) 2014, Seth Billings, Russell Taylor, Johns Hopkins University // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 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 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 <stdio.h> #include <iostream> #include <cisstVector.h> #include <cisstCommon.h> #include <cisstNumerical.h> #include "DirPDTreeNode.h" #include "DirPDTreeBase.h" #include "utilities.h" DirPDTreeNode::DirPDTreeNode( int* pDataIndexArray, int numIndexes, DirPDTreeBase* pTree, DirPDTreeNode* pParent) : Bounds(), pDataIndices(pDataIndexArray), NData(numIndexes), pLEq(NULL), pMore(NULL), pMyTree(pTree), pParent(pParent) { // Compute local coordinate frame for this node // computes local -> global // take inverse to get global -> local F = ComputeCovFrame(0, NData).Inverse(); for (int i = 0; i < NData; i++) { // since we don't know what type of datum we're dealing with // (and since we want the bounds to completely hold all of this datum) // we must place the enlarge bounds function at the tree level where // the datum type is known. pMyTree->EnlargeBounds(F, Datum(i), Bounds); } //std::stringstream ss; //ss << F.Rotation().Row(0) << " " << F.Rotation().Row(1) << " " // << " " << F.Rotation().Row(2) << " " << F.Translation() << std::endl; ////ss << "F:" << F << std::endl; //fprintf(pMyTree->debugFile, "%s", ss.str().c_str()); } DirPDTreeNode::~DirPDTreeNode() { if (pLEq != NULL) delete pLEq; if (pMore != NULL) delete pMore; } // computes a local reference frame for this node based on the // covariances of the datum sort positions; returns a frame // transformation that converts points from local -> global coordinates vctFrm3 DirPDTreeNode::ComputeCovFrame(int i0, int i1) { // returns a frame whose origin is at centroid and whose x-axis // points in the direction of largest point spread vct3 p(0, 0, 0); vctRot3 R; vctDouble3x3 C(0.0); // covariances vctDouble3x3 Q; // Eigen vectors vct3 e; // Eigen values int i; if (i1 <= i0) return vctFrm3(); int N = i1 - i0; if (N < 5) return (pParent != NULL) ? pParent->F : vctFrm3(); for (i = i0; i < i1; i++) AccumulateCentroid(Datum(i), p); p *= (1.0 / (i1 - i0)); for (i = i0; i < i1; i++) { AccumulateVariances(Datum(i), p, C); } // compute eigen decomposition of covariance matrix ComputeCovEigenDecomposition_NonIter(C, e, Q); int j = 0; for (i = 1; i < 3; i++) { if (fabs(e(i)) > fabs(e(j))) j = i; }; switch (j) { case 0: // E[0] is biggest eigen value R = Q; break; case 1: // E[1] is biggest eigen value // by right hand rule, map x->y, y->-x, z->z // (assuming Q is a valid rotation matrix) R.Column(0) = Q.Column(1); R.Column(1) = -Q.Column(0); R.Column(2) = Q.Column(2); break; case 2: // E[2] is biggest eigen value // by right hand rule: x->z, y->y, z->-x R.Column(0) = Q.Column(2); R.Column(1) = Q.Column(1); R.Column(2) = -Q.Column(0); } // SDB: should this be: [R',-R'*p]? // no, because the function that calls this takes the inverse return vctFrm3(R, p); } void DirPDTreeNode::AccumulateCentroid(int datum, vct3 &sum) const { sum += pMyTree->DatumSortPoint(datum); } // NOTE: providing the M argument is not important for the calling function, // it merely helps with speed-up, as memory for the matrix doesn't // have to be re-allocated N times void DirPDTreeNode::AccumulateVariances(int datum, const vct3 &mean, vctDouble3x3 &C) const { static vctDouble3x3 M; vct3 d = pMyTree->DatumSortPoint(datum) - mean; M.OuterProductOf(d, d); C += M; } // returns a value "top", for which datums should be on the pMore side if t>=top int DirPDTreeNode::SortNodeForSplit() { int top = NData; static int callNumber = 0; callNumber++; vct3 Ck; vct3 Ct; vct3 r = F.Rotation().Row(0); double px = F.Translation()[0]; for (int k = 0; k < top; k++) { Ck = pMyTree->DatumSortPoint(Datum(k)); // 3D coordinate of datum in global coord system double kx = r*Ck + px; // compute the x coordinate in local coord system if (kx > 0) { // this one needs to go to the end of the line while ((--top) > k) { Ct = pMyTree->DatumSortPoint(Datum(top)); double tx = r*Ct + px; if (tx <= 0) { int Temp = Datum(k); Datum(k) = Datum(top); Datum(top) = Temp; break; // from the "top" loop }; }; // end of the "t" loop }; // end of the kx>0 case; at this point F*datum.x-coord <= 0 for i=0,...,k }; // end of k loop return top; } DirPDTreeNode* DirPDTreeNode::GetChildSplitNode(const vct3 &datumPos) { // node split occurs along the local x-axis double x_node = F.Rotation().Row(0)*datumPos + F.Translation()[0]; if (x_node > 0) return pMore; else return pLEq; } // computes average orientation and max deviation for this node // returns the running sum of vector orientations vct3 DirPDTreeNode::ComputeOrientationParams() { // avg orientation vct3 Nsum(0.0); for (int i = 0; i < NumData(); i++) { Nsum += pMyTree->DatumNorm(Datum(i)); } if (Nsum.Norm() < 1e-10) { // prevent division by zero Navg.Assign(0.0, 0.0, 1.0); } else { Navg = Nsum.Normalized(); } // max deviation from the avg orientation // cos(theta) = n'*Navg (note n & Navg are unit vectors) dThetaMax = 0.0; vct3 n; double Theta; for (int i = 0; i < NumData(); i++) { n = pMyTree->DatumNorm(Datum(i)); Theta = acos(n.DotProduct(Navg)); if (Theta > dThetaMax) { dThetaMax = Theta; } } #ifdef DebugDirPDTree fprintf(pMyTree->debugFile, " dThetaMax = %f\n", dThetaMax); #endif return Nsum; } // returns tree depth int DirPDTreeNode::ConstructSubtree(int CountThresh, double DiagThresh) { if (NumData() < CountThresh || Bounds.DiagonalLength() < DiagThresh) { // leaf node #ifdef DebugDirPDTree fprintf(pMyTree->debugFile, "Leaf Node: Ndata=%d\tDiagLen=%f\n", NumData(), Bounds.DiagonalLength()); #endif ComputeOrientationParams(); myDepth = 0; return myDepth; } int topLEq = SortNodeForSplit(); if (topLEq == NumData() || topLEq == 0) { // need this in case count threshold = 1 // TODO: avoid this case by NumData()<=CountThresh above #ifdef DebugDirPDTree fprintf(pMyTree->debugFile, "ERROR! all data splits to one node; topLEq=%d\tNdata=%d\tDiagLen=%f\n", topLEq, NumData(), Bounds.DiagonalLength()); #endif ComputeOrientationParams(); myDepth = 0; // stop here and do not split any further return 0; } #ifdef DebugDirPDTree fprintf(pMyTree->debugFile2, "NNodeL=%d\tNNodeR=%d\n", topLEq, NumData() - topLEq); #endif assert (topLEq>0&&topLEq<NumData()); int depthL, depthR; pLEq = new DirPDTreeNode(pDataIndices, topLEq, pMyTree, this); pMyTree->NNodes++; depthL = pLEq->ConstructSubtree(CountThresh, DiagThresh); pMore = new DirPDTreeNode(&pDataIndices[topLEq], NumData() - topLEq, pMyTree, this); pMyTree->NNodes++; depthR = pMore->ConstructSubtree(CountThresh, DiagThresh); myDepth = (depthL > depthR ? depthL : depthR) + 1; ComputeOrientationParams(); // TODO: speed up this one by using NSum from children return myDepth; } // Check if a datum in this node has a lower match error than the error bound // If a lower match error is found, set the new closest point, update error // bound, and return the global datum index of the closest datum. // Otherwise, return -1. int DirPDTreeNode::FindClosestDatum( const vct3 &v, const vct3 &n, vct3 &closestPoint, vct3 &closestPointNorm, double &ErrorBound, unsigned int &numNodesVisited, unsigned int &numNodesSearched) { numNodesVisited++; // fast check if this node may contain a datum with better match error if (pMyTree->pAlgorithm->NodeMightBeCloser(v, n, this, ErrorBound) == 0) { return -1; } // Search points w/in this node int ClosestDatum = -1; numNodesSearched++; if (IsTerminalNode()) { // a leaf node => look at each datum in the node for (int i = 0; i < NData; i++) { int datum = Datum(i); // fast check if this datum might have a lower match error than error bound if (pMyTree->pAlgorithm->DatumMightBeCloser(v, n, datum, ErrorBound)) { // a candidate vct3 candidate; vct3 candidateNorm; // close check if this datum has a lower match error than error bound double err = pMyTree->pAlgorithm->FindClosestPointOnDatum(v, n, candidate, candidateNorm, datum); if (err < ErrorBound) { closestPoint = candidate; closestPointNorm = candidateNorm; ErrorBound = err; ClosestDatum = datum; } } } return ClosestDatum; } // here if not a terminal node => // extend search to both child nodes int ClosestLEq = -1; int ClosestMore = -1; // 1st call to pLEq updates both distance bound and closest point // before 2nd call to pMore. If pMore returns (-1), then pMore had // nothing better than pLEq and the resulting datum should be // the return value of pLEq (whether that is -1 or a closer datum index) ClosestLEq = pLEq->FindClosestDatum(v, n, closestPoint, closestPointNorm, ErrorBound, numNodesVisited, numNodesSearched); ClosestMore = pMore->FindClosestDatum(v, n, closestPoint, closestPointNorm, ErrorBound, numNodesVisited, numNodesSearched); ClosestDatum = (ClosestMore < 0) ? ClosestLEq : ClosestMore; return ClosestDatum; } // find terminal node holding the specified datum int DirPDTreeNode::FindTerminalNode(int datum, DirPDTreeNode **termNode) { if (!IsTerminalNode()) { if (pLEq->FindTerminalNode(datum, termNode)) return 1; if (pMore->FindTerminalNode(datum, termNode)) return 1; return 0; } for (int i = 0; i < NData; i++) { if (Datum(i) == datum) { *termNode = this; return 1; } } return 0; } void DirPDTreeNode::PrintTerminalNodes(std::ofstream &fs) { if (IsTerminalNode()) { fs << "Terminal Node:" << std::endl << " NData = " << NData << std::endl << F << std::endl << " Bounds Min: " << Bounds.MinCorner << std::endl << " Bounds Max: " << Bounds.MaxCorner << std::endl << " Datum Indices: " << std::endl; for (int i = 0; i < NData; i++) { fs << " " << Datum(i) << std::endl; } } else { pLEq->PrintTerminalNodes(fs); pMore->PrintTerminalNodes(fs); } } //void DirPDTreeNode::Print(FILE* chan, int indent) //{ // fprintfBlanks(chan, indent); // fprintf(chan, "NData = %d Bounds = [", NData); fprintfVct3(chan, Bounds.MinCorner); // fprintf(chan, "] ["); fprintfVct3(chan, Bounds.MaxCorner); // fprintf(chan, "]\n"); // fprintfBlanks(chan, indent); // fprintfRodFrame(chan, "F =", F); fprintf(chan, "\n"); // if (IsTerminalNode()) // { // for (int k = 0; k < NData; k++) // { // pMyTree->PrintDatum(chan, indent + 2, Datum(k)); // }; // fprintf(chan, "\n"); // } // else // { // pLEq->Print(chan, indent + 2); // pMore->Print(chan, indent + 2); // }; //} //void DirPDTreeNode::Print(int indent) //{ // printf("NData = %d Bounds = [", NData); fprintfVct3(chan,Bounds.MinCorner); // printf("] ["); fprintfVct3(chan, Bounds.MaxCorner); // printf("]\n"); // std::cout << "F:" << std::endl << F << std::endl; // if (IsTerminalNode()) // { for (int k=0;k<NData;k++) // { pMyTree->PrintDatum(chan,indent+2,Datum(k)); // }; // } // else // { pLEq->Print(chan,indent+2); // pMore->Print(chan,indent+2); // }; //}
31.370283
125
0.636493
sbillin
df28ecaeef52f8de3864c5efcfd6a03cb13d7c34
615
cpp
C++
Engine/Code/Engine/Physics/GravityForceGenerator.cpp
cugone/Abrams2022
54efe5fdd7d2d9697f005ee45a171ecea68d0df8
[ "MIT" ]
null
null
null
Engine/Code/Engine/Physics/GravityForceGenerator.cpp
cugone/Abrams2022
54efe5fdd7d2d9697f005ee45a171ecea68d0df8
[ "MIT" ]
20
2021-11-29T14:09:33.000Z
2022-03-26T20:12:44.000Z
Engine/Code/Engine/Physics/GravityForceGenerator.cpp
cugone/Abrams2022
54efe5fdd7d2d9697f005ee45a171ecea68d0df8
[ "MIT" ]
null
null
null
#include "Engine/Physics/GravityForceGenerator.hpp" #include "Engine/Math/Vector2.hpp" #include "Engine/Physics/RigidBody.hpp" GravityForceGenerator::GravityForceGenerator(const Vector2& gravity) noexcept : ForceGenerator() , m_g(gravity) { /* DO NOTHING */ } void GravityForceGenerator::notify([[maybe_unused]] TimeUtils::FPSeconds deltaSeconds) const noexcept { if(m_g == Vector2::Zero) { return; } for(auto* body : m_observers) { body->ApplyForce(m_g, deltaSeconds); } } void GravityForceGenerator::SetGravity(const Vector2& newGravity) noexcept { m_g = newGravity; }
25.625
103
0.718699
cugone
df2a6844ceb58154b763d1760fd43b7d80a2f324
16,140
hpp
C++
kvm_core/include/kvm_serializer.hpp
pspglb/kvm
2dc3c4cc331dedaf5245e5c8a24bcba02b6ded32
[ "BSD-3-Clause" ]
26
2020-12-03T11:13:42.000Z
2022-03-25T05:36:33.000Z
kvm_core/include/kvm_serializer.hpp
mtlynch/kvm
f0128edd493a758197a683cbb40dd409d16235e5
[ "BSD-3-Clause" ]
4
2021-01-28T19:32:17.000Z
2021-06-01T15:01:42.000Z
kvm_core/include/kvm_serializer.hpp
mtlynch/kvm
f0128edd493a758197a683cbb40dd409d16235e5
[ "BSD-3-Clause" ]
8
2020-12-04T01:30:21.000Z
2021-12-01T11:19:11.000Z
// Copyright 2020 Christopher A. Taylor /* Binary serialization tools */ #pragma once #include "kvm_core.hpp" #include <string.h> namespace kvm { //------------------------------------------------------------------------------ // Byte Order // Swaps byte order in a 16-bit word CORE_INLINE uint16_t ByteSwap16(uint16_t word) { return (word >> 8) | (word << 8); } // Swaps byte order in a 32-bit word CORE_INLINE uint32_t ByteSwap32(uint32_t word) { const uint16_t swapped_old_hi = ByteSwap16(static_cast<uint16_t>(word >> 16)); const uint16_t swapped_old_lo = ByteSwap16(static_cast<uint16_t>(word)); return (static_cast<uint32_t>(swapped_old_lo) << 16) | swapped_old_hi; } // Swaps byte order in a 64-bit word CORE_INLINE uint64_t ByteSwap64(uint64_t word) { const uint32_t swapped_old_hi = ByteSwap32(static_cast<uint32_t>(word >> 32)); const uint32_t swapped_old_lo = ByteSwap32(static_cast<uint32_t>(word)); return (static_cast<uint64_t>(swapped_old_lo) << 32) | swapped_old_hi; } //------------------------------------------------------------------------------ // POD Serialization /** * array[2] = { 0, 1 } * * Little Endian: word = 0x0100 <- first byte is least-significant * Big Endian: word = 0x0001 <- first byte is most-significant **/ /** * word = 0x0102 * * Little Endian: array[2] = { 0x02, 0x01 } * Big Endian: array[2] = { 0x01, 0x02 } **/ // Little-endian 16-bit read CORE_INLINE uint16_t ReadU16_LE(const void* data) { #ifdef CORE_ALIGNED_ACCESSES const uint8_t* u8p = reinterpret_cast<const uint8_t*>(data); return ((uint16_t)u8p[1] << 8) | u8p[0]; #else const uint16_t* word_ptr = reinterpret_cast<const uint16_t*>(data); return *word_ptr; #endif } // Big-endian 16-bit read CORE_INLINE uint16_t ReadU16_BE(const void* data) { return ByteSwap16(ReadU16_LE(data)); } // Little-endian 24-bit read CORE_INLINE uint32_t ReadU24_LE(const void* data) { const uint8_t* u8p = reinterpret_cast<const uint8_t*>(data); return ((uint32_t)u8p[2] << 16) | ((uint32_t)u8p[1] << 8) | u8p[0]; } // Big-endian 24-bit read CORE_INLINE uint32_t ReadU24_BE(const void* data) { const uint8_t* u8p = reinterpret_cast<const uint8_t*>(data); return ((uint32_t)u8p[0] << 16) | ((uint32_t)u8p[1] << 8) | u8p[2]; } // Little-endian 32-bit read CORE_INLINE uint32_t ReadU32_LE(const void* data) { #ifdef CORE_ALIGNED_ACCESSES const uint8_t* u8p = reinterpret_cast<const uint8_t*>(data); return ((uint32_t)u8p[3] << 24) | ((uint32_t)u8p[2] << 16) | ((uint32_t)u8p[1] << 8) | u8p[0]; #else const uint32_t* u32p = reinterpret_cast<const uint32_t*>(data); return *u32p; #endif } // Big-endian 32-bit read CORE_INLINE uint32_t ReadU32_BE(const void* data) { #ifdef CORE_ALIGNED_ACCESSES const uint8_t* u8p = reinterpret_cast<const uint8_t*>(data); return ((uint32_t)u8p[0] << 24) | ((uint32_t)u8p[1] << 16) | ((uint32_t)u8p[2] << 8) | u8p[3]; #else return ByteSwap32(ReadU32_LE(data)); #endif } // Little-endian 64-bit read CORE_INLINE uint64_t ReadU64_LE(const void* data) { #ifdef CORE_ALIGNED_ACCESSES const uint8_t* u8p = reinterpret_cast<const uint8_t*>(data); return ((uint64_t)u8p[7] << 56) | ((uint64_t)u8p[6] << 48) | ((uint64_t)u8p[5] << 40) | ((uint64_t)u8p[4] << 32) | ((uint64_t)u8p[3] << 24) | ((uint64_t)u8p[2] << 16) | ((uint64_t)u8p[1] << 8) | u8p[0]; #else const uint64_t* word_ptr = reinterpret_cast<const uint64_t*>(data); return *word_ptr; #endif } // Big-endian 64-bit read CORE_INLINE uint64_t ReadU64_BE(const void* data) { #ifdef CORE_ALIGNED_ACCESSES const uint8_t* u8p = reinterpret_cast<const uint8_t*>(data); return ((uint64_t)u8p[0] << 56) | ((uint64_t)u8p[1] << 48) | ((uint64_t)u8p[2] << 40) | ((uint64_t)u8p[3] << 32) | ((uint64_t)u8p[4] << 24) | ((uint64_t)u8p[5] << 16) | ((uint64_t)u8p[6] << 8) | u8p[7]; #else return ByteSwap64(ReadU64_LE(data)); #endif } // Little-endian 16-bit write CORE_INLINE void WriteU16_LE(void* data, uint16_t value) { #ifdef CORE_ALIGNED_ACCESSES uint8_t* u8p = reinterpret_cast<uint8_t*>(data); u8p[1] = static_cast<uint8_t>(value >> 8); u8p[0] = static_cast<uint8_t>(value); #else uint16_t* word_ptr = reinterpret_cast<uint16_t*>(data); *word_ptr = value; #endif } // Big-endian 16-bit write CORE_INLINE void WriteU16_BE(void* data, uint16_t value) { #ifdef CORE_ALIGNED_ACCESSES uint8_t* u8p = reinterpret_cast<uint8_t*>(data); u8p[0] = static_cast<uint8_t>(value >> 8); u8p[1] = static_cast<uint8_t>(value); #else uint16_t* word_ptr = reinterpret_cast<uint16_t*>(data); *word_ptr = ByteSwap16(value); #endif } // Little-endian 24-bit write CORE_INLINE void WriteU24_LE(void* data, uint32_t value) { uint8_t* u8p = reinterpret_cast<uint8_t*>(data); u8p[2] = static_cast<uint8_t>(value >> 16); WriteU16_LE(u8p, static_cast<uint16_t>(value)); } // Big-endian 24-bit write CORE_INLINE void WriteU24_BE(void* data, uint32_t value) { uint8_t* u8p = reinterpret_cast<uint8_t*>(data); u8p[0] = static_cast<uint8_t>(value >> 16); WriteU16_BE(u8p + 1, static_cast<uint16_t>(value)); } // Little-endian 32-bit write CORE_INLINE void WriteU32_LE(void* data, uint32_t value) { #ifdef CORE_ALIGNED_ACCESSES uint8_t* u8p = reinterpret_cast<uint8_t*>(data); u8p[3] = (uint8_t)(value >> 24); u8p[2] = static_cast<uint8_t>(value >> 16); u8p[1] = static_cast<uint8_t>(value >> 8); u8p[0] = static_cast<uint8_t>(value); #else uint32_t* word_ptr = reinterpret_cast<uint32_t*>(data); *word_ptr = value; #endif } // Big-endian 32-bit write CORE_INLINE void WriteU32_BE(void* data, uint32_t value) { #ifdef CORE_ALIGNED_ACCESSES uint8_t* u8p = reinterpret_cast<uint8_t*>(data); u8p[0] = (uint8_t)(value >> 24); u8p[1] = static_cast<uint8_t>(value >> 16); u8p[2] = static_cast<uint8_t>(value >> 8); u8p[3] = static_cast<uint8_t>(value); #else uint32_t* word_ptr = reinterpret_cast<uint32_t*>(data); *word_ptr = ByteSwap32(value); #endif } // Little-endian 64-bit write CORE_INLINE void WriteU64_LE(void* data, uint64_t value) { #ifdef CORE_ALIGNED_ACCESSES uint8_t* u8p = reinterpret_cast<uint8_t*>(data); u8p[7] = static_cast<uint8_t>(value >> 56); u8p[6] = static_cast<uint8_t>(value >> 48); u8p[5] = static_cast<uint8_t>(value >> 40); u8p[4] = static_cast<uint8_t>(value >> 32); u8p[3] = static_cast<uint8_t>(value >> 24); u8p[2] = static_cast<uint8_t>(value >> 16); u8p[1] = static_cast<uint8_t>(value >> 8); u8p[0] = static_cast<uint8_t>(value); #else uint64_t* word_ptr = reinterpret_cast<uint64_t*>(data); *word_ptr = value; #endif } // Big-endian 64-bit write CORE_INLINE void WriteU64_BE(void* data, uint64_t value) { #ifdef CORE_ALIGNED_ACCESSES uint8_t* u8p = reinterpret_cast<uint8_t*>(data); u8p[0] = static_cast<uint8_t>(value >> 56); u8p[1] = static_cast<uint8_t>(value >> 48); u8p[2] = static_cast<uint8_t>(value >> 40); u8p[3] = static_cast<uint8_t>(value >> 32); u8p[4] = static_cast<uint8_t>(value >> 24); u8p[5] = static_cast<uint8_t>(value >> 16); u8p[6] = static_cast<uint8_t>(value >> 8); u8p[7] = static_cast<uint8_t>(value); #else uint64_t* word_ptr = reinterpret_cast<uint64_t*>(data); *word_ptr = ByteSwap64(value); #endif } /** * ReadBytes64_LE() * * Little-endian variable-bit read up to 8 bytes into a 64-bit unsigned integer. * * If bytes > 8, the left-most bytes are taken (truncating the MSBs). * * Returns the value, truncated to 64 bits. */ uint64_t ReadBytes64_LE(const void* data, int bytes); /** * WriteBytes64_BE() * * Little-endian variable-bit write up to 8 bytes from a 64-bit unsigned integer. * * WARNING: Does not support more than eight bytes. * * Precondition: 0 <= bytes <= 8 * If 0 bytes is specified, no writes are performed. */ void WriteBytes64_LE(void* data, int bytes, uint64_t value); /** * ReadBytes64_BE() * * Big-endian variable-bit read up to 8 bytes into a 64-bit unsigned integer. * * If bytes > 8, the right-most bytes are taken (truncating the MSBs). * * Returns the value, truncated to 64 bits. */ uint64_t ReadBytes64_BE(const void* data, int bytes); /** * WriteBytes64_BE() * * Big-endian variable-bit write up to 8 bytes from a 64-bit unsigned integer. * * WARNING: Does not support more than eight bytes. * * Precondition: 0 <= bytes <= 8 * If 0 bytes is specified, no writes are performed. */ void WriteBytes64_BE(void* data, int bytes, uint64_t value); //------------------------------------------------------------------------------ // WriteByteStream /// Helper class to serialize POD types to a byte buffer struct WriteByteStream { /// Wrapped data pointer uint8_t* Data = nullptr; /// Number of wrapped buffer bytes int BufferBytes = 0; /// Number of bytes written so far by Write*() functions int WrittenBytes = 0; CORE_INLINE WriteByteStream() { } CORE_INLINE WriteByteStream(const WriteByteStream& other) : Data(other.Data) , BufferBytes(other.BufferBytes) , WrittenBytes(other.WrittenBytes) { } CORE_INLINE WriteByteStream(void* data, int bytes) : Data(reinterpret_cast<uint8_t*>(data)) , BufferBytes(bytes) { CORE_DEBUG_ASSERT(data != nullptr && bytes > 0); } CORE_INLINE uint8_t* Peek() { CORE_DEBUG_ASSERT(WrittenBytes <= BufferBytes); return Data + WrittenBytes; } CORE_INLINE int Remaining() { CORE_DEBUG_ASSERT(WrittenBytes <= BufferBytes); return BufferBytes - WrittenBytes; } CORE_INLINE WriteByteStream& Write8(uint8_t value) { CORE_DEBUG_ASSERT(WrittenBytes + 1 <= BufferBytes); Data[WrittenBytes] = value; WrittenBytes++; return *this; } CORE_INLINE WriteByteStream& Write16_LE(uint16_t value) { CORE_DEBUG_ASSERT(WrittenBytes + 2 <= BufferBytes); WriteU16_LE(Data + WrittenBytes, value); WrittenBytes += 2; return *this; } CORE_INLINE WriteByteStream& Write16_BE(uint16_t value) { CORE_DEBUG_ASSERT(WrittenBytes + 2 <= BufferBytes); WriteU16_BE(Data + WrittenBytes, value); WrittenBytes += 2; return *this; } CORE_INLINE WriteByteStream& Write24_LE(uint32_t value) { CORE_DEBUG_ASSERT(WrittenBytes + 3 <= BufferBytes); WriteU24_LE(Data + WrittenBytes, value); WrittenBytes += 3; return *this; } CORE_INLINE WriteByteStream& Write24_BE(uint32_t value) { CORE_DEBUG_ASSERT(WrittenBytes + 3 <= BufferBytes); WriteU24_BE(Data + WrittenBytes, value); WrittenBytes += 3; return *this; } CORE_INLINE WriteByteStream& Write32_LE(uint32_t value) { CORE_DEBUG_ASSERT(WrittenBytes + 4 <= BufferBytes); WriteU32_LE(Data + WrittenBytes, value); WrittenBytes += 4; return *this; } CORE_INLINE WriteByteStream& Write32_BE(uint32_t value) { CORE_DEBUG_ASSERT(WrittenBytes + 4 <= BufferBytes); WriteU32_BE(Data + WrittenBytes, value); WrittenBytes += 4; return *this; } CORE_INLINE WriteByteStream& Write64_LE(uint64_t value) { CORE_DEBUG_ASSERT(WrittenBytes + 8 <= BufferBytes); WriteU64_LE(Data + WrittenBytes, value); WrittenBytes += 8; return *this; } CORE_INLINE WriteByteStream& Write64_BE(uint64_t value) { CORE_DEBUG_ASSERT(WrittenBytes + 8 <= BufferBytes); WriteU64_BE(Data + WrittenBytes, value); WrittenBytes += 8; return *this; } CORE_INLINE WriteByteStream& WriteBuffer(const void* source, int bytes) { CORE_DEBUG_ASSERT(source != nullptr || bytes == 0); CORE_DEBUG_ASSERT(WrittenBytes + bytes <= BufferBytes); memcpy(Data + WrittenBytes, source, bytes); WrittenBytes += bytes; return *this; } }; //------------------------------------------------------------------------------ // ReadByteStream /// Helper class to deserialize POD types from a byte buffer struct ReadByteStream { /// Wrapped data pointer const uint8_t* const Data; /// Number of wrapped buffer bytes const int BufferBytes; /// Number of bytes read so far by Read*() functions int BytesRead = 0; ReadByteStream(const void* data, int bytes) : Data(reinterpret_cast<const uint8_t*>(data)) , BufferBytes(bytes) { CORE_DEBUG_ASSERT(data != nullptr); } CORE_INLINE const uint8_t* Peek() { CORE_DEBUG_ASSERT(BytesRead <= BufferBytes); return Data + BytesRead; } CORE_INLINE int Remaining() { CORE_DEBUG_ASSERT(BytesRead <= BufferBytes); return BufferBytes - BytesRead; } CORE_INLINE void Skip(int bytes) { CORE_DEBUG_ASSERT(BytesRead + bytes <= BufferBytes); BytesRead += bytes; } CORE_INLINE const uint8_t* Read(int bytes) { const uint8_t* data = Peek(); Skip(bytes); return data; } CORE_INLINE uint8_t Read8() { CORE_DEBUG_ASSERT(BytesRead + 1 <= BufferBytes); uint8_t value = *Peek(); BytesRead++; return value; } CORE_INLINE uint16_t Read16_LE() { CORE_DEBUG_ASSERT(BytesRead + 2 <= BufferBytes); uint16_t value = ReadU16_LE(Peek()); BytesRead += 2; return value; } CORE_INLINE uint16_t Read16_BE() { CORE_DEBUG_ASSERT(BytesRead + 2 <= BufferBytes); uint16_t value = ReadU16_BE(Peek()); BytesRead += 2; return value; } CORE_INLINE uint32_t Read24_LE() { CORE_DEBUG_ASSERT(BytesRead + 3 <= BufferBytes); uint32_t value = ReadU24_LE(Peek()); BytesRead += 3; return value; } CORE_INLINE uint32_t Read24_BE() { CORE_DEBUG_ASSERT(BytesRead + 3 <= BufferBytes); uint32_t value = ReadU24_BE(Peek()); BytesRead += 3; return value; } CORE_INLINE uint32_t Read32_LE() { CORE_DEBUG_ASSERT(BytesRead + 4 <= BufferBytes); uint32_t value = ReadU32_LE(Peek()); BytesRead += 4; return value; } CORE_INLINE uint32_t Read32_BE() { CORE_DEBUG_ASSERT(BytesRead + 4 <= BufferBytes); uint32_t value = ReadU32_BE(Peek()); BytesRead += 4; return value; } CORE_INLINE uint64_t Read64_LE() { CORE_DEBUG_ASSERT(BytesRead + 8 <= BufferBytes); uint64_t value = ReadU64_LE(Peek()); BytesRead += 8; return value; } CORE_INLINE uint64_t Read64_BE() { CORE_DEBUG_ASSERT(BytesRead + 8 <= BufferBytes); uint64_t value = ReadU64_BE(Peek()); BytesRead += 8; return value; } }; //------------------------------------------------------------------------------ // ReadBitStream /// Helper class to deserialize POD types from a bit buffer struct ReadBitStream { /// Based on ReadByteStream ReadByteStream Reader; /// Current workspace for reading uint64_t Workspace = 0; /// Number of unread bits in the workspace int WorkspaceRemaining = 0; ReadBitStream(const void* data, int bytes) : Reader(data, bytes) { } /// Read up to 32 bits. /// Precondition: bits > 0, bits <= 32 uint32_t Read(int bits); }; } // namespace kvm
29.23913
99
0.61171
pspglb
df2aebd6aed1ff09fb6b72d2224ee1957bb37474
757
cpp
C++
Code_Jam/codejam1.cpp
Jonsy13/Competitive-Programming
67e1918488c82b7ab8272b57dd4ffcff9dd4b1ac
[ "MIT" ]
null
null
null
Code_Jam/codejam1.cpp
Jonsy13/Competitive-Programming
67e1918488c82b7ab8272b57dd4ffcff9dd4b1ac
[ "MIT" ]
null
null
null
Code_Jam/codejam1.cpp
Jonsy13/Competitive-Programming
67e1918488c82b7ab8272b57dd4ffcff9dd4b1ac
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main(){ int T; cin>>T; while(T>0){ int N,ele; cin>>N; vector<vector<int>>vec; for(int i=0;i<N;i++){ vector<int>vec2; for(int j=0;j<N;j++){ cin>>ele; vec2.push_back(ele); } vec.push_back(vec2); } int sum = 0; for(int i=0;i<N;i++){ sum +=vec.at(i).at(i); } int flag = 0; for(int i=0;i<N;i++){ auto it = std::unique(vec.at(i).begin(), vec.at(i).end()); flag = ((it == vec.at(i).end()) ? 0 : ++flag); } cout<<"No. of rows having duplicates : "<<flag<<endl; T--; }; }
22.264706
70
0.393659
Jonsy13
df2d731e6db854943d4b41656ef612c5ec01b381
1,357
hpp
C++
mogl/object/shader/shader.hpp
ninnghazad/moGL
041c5a891469eecfce904e170c62c016d0864cb6
[ "MIT" ]
27
2015-02-26T12:27:19.000Z
2022-03-09T22:24:01.000Z
mogl/object/shader/shader.hpp
ninnghazad/moGL
041c5a891469eecfce904e170c62c016d0864cb6
[ "MIT" ]
21
2015-01-07T15:30:55.000Z
2022-03-22T09:58:35.000Z
mogl/object/shader/shader.hpp
ninnghazad/moGL
041c5a891469eecfce904e170c62c016d0864cb6
[ "MIT" ]
6
2015-02-25T13:02:30.000Z
2019-11-29T08:01:15.000Z
//////////////////////////////////////////////////////////////////////////////// /// Modern OpenGL Wrapper /// /// Copyright (c) 2015 Thibault Schueller /// This file is distributed under the MIT License /// /// @file shader.hpp /// @author Thibault Schueller <ryp.sqrt@gmail.com> //////////////////////////////////////////////////////////////////////////////// #ifndef MOGL_SHADER_INCLUDED #define MOGL_SHADER_INCLUDED #include <string> #include <mogl/object/handle.hpp> namespace mogl { class Shader : public Handle<GLuint> { public: Shader(GLenum type); ~Shader(); Shader(const Shader& other) = delete; Shader& operator=(const Shader& other) = delete; public: bool compile(const std::string& source); bool compile(std::istream& sourceFile); const std::string getSource() const; GLenum getType() const; const std::string getLog() const; void get(GLenum property, GLint* value) const; // Direct call to glGetShaderiv() GLint get(GLenum property) const; bool isCompiled() const; bool isValid() const override final; private: const GLenum _type; }; } #include "shader.inl" #endif // MOGL_SHADER_INCLUDED
28.270833
103
0.518791
ninnghazad
df2de002f67906cd3f4a264f95422ec9508ba45a
561
cc
C++
Calibration/EcalTBTools/src/TB06Reco.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
Calibration/EcalTBTools/src/TB06Reco.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
Calibration/EcalTBTools/src/TB06Reco.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include "Calibration/EcalTBTools/interface/TB06Reco.h" /* */ // FIXME ClassImp (TB06Reco) void TB06Reco::reset() { run = 0; event = 0; tableIsMoving = 0; S6ADC = 0; MEXTLindex = 0; MEXTLeta = 0; MEXTLphi = 0; MEXTLenergy = 0.; beamEnergy = 0.; for (int eta = 0; eta < 7; ++eta) for (int phi = 0; phi < 7; ++phi) localMap[eta][phi] = 0.; xECAL = 0.; yECAL = 0.; zECAL = 0.; xHodo = 0.; yHodo = 0.; zHodo = 0.; xSlopeHodo = 0.; ySlopeHodo = 0.; xQualityHodo = 0.; yQualityHodo = 0.; convFactor = 0.; }
15.162162
55
0.554367
ckamtsikis
df2e0e2da10d9b1293c459cb45cae7895500778d
1,150
cpp
C++
problemsets/UVA/UVA10789.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/UVA/UVA10789.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/UVA/UVA10789.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
/** * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * */ #include <cstdio> #include <cstdlib> #include <cstring> #include <cctype> #include <cmath> #include <string> #include <algorithm> #include <sstream> #include <map> #include <set> #include <queue> using namespace std; const int MAX = 25000, LMT = sqrt(MAX)+10; int flag[MAX>>6]; #define ifc(x) (flag[x>>6]&(1<<((x>>1)&31))) #define isc(x) (flag[x>>6]|=(1<<((x>>1)&31))) void sieve() { int i, j, k; for(i = 3; i < LMT; i += 2) if(!ifc(i)) for(j = i*i, k = i<<1; j < MAX; j += k) isc(j); } int F[300]; char S[25000]; int main() { sieve(); int T; scanf("%d", &T); for (int t = 1; t <= T; t++) { if (scanf("%s", S)==EOF) printf("%d",1/0); for (int i = 0; i < 300; i++) F[i] = 0; for (int i = 0; S[i]; i++) F[S[i]]++; printf("Case %d: ", t); bool f = false; for (int i = 0; i < 300; i++) { if (F[i]==2 || (F[i]%2 && F[i]>2 && !ifc(F[i]))) putchar(i), f = true; } if (!f) puts("empty"); else putchar('\n'); } return 0; }
20.175439
60
0.471304
juarezpaulino
df2f7804800329b095763f3c1918977db8572e44
1,683
hpp
C++
xyginext/src/network/NetConf.hpp
fallahn/xygine
c17e7d29bb57a5425a58abd3a05a843d6bac48e3
[ "Unlicense" ]
220
2015-10-22T16:12:13.000Z
2022-03-16T18:51:11.000Z
xyginext/src/network/NetConf.hpp
fallahn/xygine
c17e7d29bb57a5425a58abd3a05a843d6bac48e3
[ "Unlicense" ]
64
2016-05-05T19:17:13.000Z
2021-02-11T19:24:37.000Z
xyginext/src/network/NetConf.hpp
fallahn/xygine
c17e7d29bb57a5425a58abd3a05a843d6bac48e3
[ "Unlicense" ]
33
2016-01-13T16:44:26.000Z
2021-11-05T21:57:24.000Z
/********************************************************************* (c) Matt Marchant 2017 - 2021 http://trederia.blogspot.com xygineXT - Zlib license. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. *********************************************************************/ #ifndef XY_NETCONF_HPP_ #define XY_NETCONF_HPP_ #include <memory> namespace xy { /*! \brief Used to ensure proper startup and shutdown of Enet networking libraries */ class NetConf final { public: NetConf(); ~NetConf(); NetConf(const NetConf&) = delete; NetConf(NetConf&&) = delete; NetConf& operator = (const NetConf&) = delete; NetConf& operator = (NetConf&&) = delete; private: friend class EnetClientImpl; friend class EnetHostImpl; static std::unique_ptr<NetConf> instance; bool m_initOK; }; } #endif //XY_NETCONF_HPP_
28.05
70
0.660131
fallahn
df318fdd648d2c6c3ba1c3ed2e8f9c3443146cf2
2,378
inl
C++
include/memorypool/bufferpool.inl
yesheng86/cpp-utils
36cbf303b820a5c73b34922564be12419bec1e7d
[ "MIT" ]
null
null
null
include/memorypool/bufferpool.inl
yesheng86/cpp-utils
36cbf303b820a5c73b34922564be12419bec1e7d
[ "MIT" ]
null
null
null
include/memorypool/bufferpool.inl
yesheng86/cpp-utils
36cbf303b820a5c73b34922564be12419bec1e7d
[ "MIT" ]
null
null
null
#pragma once #include <functional> #include <map> #include "waitqueue/waitqueue.hpp" #include "log/log.hpp" using namespace util::memorypool; using namespace util::buffer; using namespace util::mt; class BufferPool::Impl { using BufferDescriptorQueue = WaitQueue<BufferDescriptor*>; public: Impl() = default; ~Impl() { for (auto& pair: m_buf_desc_queue_map) { BufferDescriptorQueue& queue = pair.second; queue.stop_queue(); BufferDescriptor* p_desc = NULL; while (queue.try_pop(p_desc)) { if (p_desc->raw_ptr()) { free(p_desc->raw_ptr()); } if (p_desc) { delete(p_desc); } } } THREAD_SAFE_PRINT("BufferPool::~Impl"); } BufferDescriptorPtr alloc(uint32_t size) { return alloc(0, size); } BufferDescriptorPtr alloc(uint32_t alignment, uint32_t size) { BufferDescriptor* p_buf_desc = NULL; uint64_t key = get_map_key(alignment, size); if (!m_buf_desc_queue_map[key].try_pop(p_buf_desc)) { void* buf_ptr = NULL; if (alignment == 0) { buf_ptr = std::malloc(size); } else { buf_ptr = std::aligned_alloc(alignment, size); } if (!buf_ptr) { return nullptr; } p_buf_desc = new BufferDescriptor(buf_ptr, alignment, size); if (!p_buf_desc) { free(buf_ptr); return nullptr; } } return std::shared_ptr<BufferDescriptor>(p_buf_desc, std::bind(&BufferPool::Impl::deleter, this, std::placeholders::_1)); } private: void deleter(BufferDescriptor* p_buf_desc) { if (p_buf_desc == NULL) { return; } uint64_t key = get_map_key(p_buf_desc->alignment(), p_buf_desc->size()); m_buf_desc_queue_map[key].push(p_buf_desc); } inline uint64_t get_map_key(uint32_t alignment, uint32_t size) { uint64_t key = (uint64_t)alignment; key = (key << 32) | (uint64_t)size; return key; } std::map<uint64_t, BufferDescriptorQueue> m_buf_desc_queue_map; }; inline BufferPool::BufferPool() : util::base::MoveOnly(), m_p_impl{ std::make_unique<Impl>() } {} inline BufferPool::~BufferPool() = default; inline BufferDescriptorPtr BufferPool::alloc(uint32_t size) { return m_p_impl->alloc(size); } inline BufferDescriptorPtr BufferPool::alloc(uint32_t alignment, uint32_t size) { return m_p_impl->alloc(alignment, size); }
26.719101
125
0.655593
yesheng86
df3a2b121adfb3d068d1483fb172296cf9822a68
804
hpp
C++
src/interop/include/interop/plugin.hpp
xSHAD0Wx/tiksrv
9d512705e05dd822d41f7cc0e69b9487fb3d286b
[ "Apache-2.0" ]
2
2020-06-08T15:47:25.000Z
2020-06-13T13:34:53.000Z
src/interop/include/interop/plugin.hpp
xSHAD0Wx/tiksrv
9d512705e05dd822d41f7cc0e69b9487fb3d286b
[ "Apache-2.0" ]
null
null
null
src/interop/include/interop/plugin.hpp
xSHAD0Wx/tiksrv
9d512705e05dd822d41f7cc0e69b9487fb3d286b
[ "Apache-2.0" ]
null
null
null
#ifndef TIKSRV_INTEROP_PLUGIN_HPP #define TIKSRV_INTEROP_PLUGIN_HPP #include "interop/command.hpp" #include "services/services_manager.hpp" #include <cstdint> #include <functional> #include <memory> #include <string> #include <vector> namespace ts::interop { class plugin { public: using export_func = std::function<void( std::uint16_t, std::uint16_t, std::unique_ptr<command>)>; virtual ~plugin() = 0; [[nodiscard]] virtual auto name() const noexcept -> const std::string & = 0; [[nodiscard]] virtual auto author() const noexcept -> const std::string & = 0; [[nodiscard]] virtual auto version() const noexcept -> const std::string & = 0; virtual void export_commands(export_func export_cb) noexcept = 0; }; } // namespace ts::interop #endif
21.72973
80
0.685323
xSHAD0Wx
df3d2abefbbefd312b52d50c70c640db674197d6
1,183
cpp
C++
UVA Online Judge/10189 - Minesweeper.cpp
amiraslanaslani/UVA-Solved-Problems
1becb706702789a5f5e0ee86297561fc5b6e5ffc
[ "Unlicense" ]
null
null
null
UVA Online Judge/10189 - Minesweeper.cpp
amiraslanaslani/UVA-Solved-Problems
1becb706702789a5f5e0ee86297561fc5b6e5ffc
[ "Unlicense" ]
null
null
null
UVA Online Judge/10189 - Minesweeper.cpp
amiraslanaslani/UVA-Solved-Problems
1becb706702789a5f5e0ee86297561fc5b6e5ffc
[ "Unlicense" ]
null
null
null
#include <iostream> using namespace std; int main() { int t = 1; while(true){ int io,jo; cin >> io >> jo; if( io == 0 && jo == 0) return 0; if(t != 1) cout << endl; cout << "Field #" << t << ":" << endl; t ++; char m[io][jo]; for(int i = 0;i < io;i ++) for(int j = 0;j < jo;j ++) cin >> m[i][j]; for(int i = 0;i < io;i ++) for(int j = 0;j < jo;j ++){ if(m[i][j] == '*') continue; int c = 0; for(int pi = -1;pi <= 1;pi ++) for(int pj = -1;pj <= 1;pj ++) if(i + pi >= 0 && i + pi < io && j + pj >= 0 && j + pj < jo && m[i + pi][j + pj] == '*') c ++; m[i][j] = c + '0'; } for(int i = 0;i < io;i ++){ for(int j = 0;j < jo;j ++) cout << m[i][j]; cout << '\n'; } //cout << '\n'; } return 0; }
25.170213
52
0.252747
amiraslanaslani
df3e24e0f13467d108e43545baa7d17fdea8dfb1
47,660
cpp
C++
src/cpu.cpp
abstrakct/nessy
41d2a978e50949e244ab70456b77530cdc65f97d
[ "Unlicense" ]
null
null
null
src/cpu.cpp
abstrakct/nessy
41d2a978e50949e244ab70456b77530cdc65f97d
[ "Unlicense" ]
null
null
null
src/cpu.cpp
abstrakct/nessy
41d2a978e50949e244ab70456b77530cdc65f97d
[ "Unlicense" ]
null
null
null
/* * 6502 cpu stuff */ #include <stdio.h> #include "cpu.h" #include "logger.h" #include "machine.h" extern Logger l; CPU::CPU() { using c = CPU; lookupTable = { // CHECKED and OK! // clang-format off { 0x00, "BRK", &c::Implied , 1, 7, }, { 0x01, "ORA", &c::IndirectX, 2, 6, }, { 0x02, "XXX", &c::Implied , 1, 2, }, { 0x03, "XXX", &c::Implied , 1, 2, }, { 0x04, "XXX", &c::Implied , 1, 2, }, { 0x05, "ORA", &c::ZeroPage , 2, 3, }, { 0x06, "ASL", &c::ZeroPage , 2, 5, }, { 0x07, "XXX", &c::Implied , 1, 2, }, { 0x08, "PHP", &c::Implied , 1, 3, }, { 0x09, "ORA", &c::Immediate, 2, 2, }, { 0x0A, "ASL", &c::Implied, 1, 2, }, { 0x0B, "XXX", &c::Implied , 1, 2, }, { 0x0C, "XXX", &c::Implied , 1, 2, }, { 0x0D, "ORA", &c::Absolute , 3, 4, }, { 0x0E, "ASL", &c::Absolute , 3, 6, }, { 0x0F, "XXX", &c::Implied , 1, 2, }, { 0x10, "BPL", &c::Relative , 2, 2, }, { 0x11, "ORA", &c::IndirectY, 2, 5, }, { 0x12, "XXX", &c::Implied , 1, 2, }, { 0x13, "XXX", &c::Implied , 1, 2, }, { 0x14, "XXX", &c::Implied , 1, 2, }, { 0x15, "ORA", &c::ZeroPageX, 2, 4, }, { 0x16, "ASL", &c::ZeroPageX, 2, 6, }, { 0x17, "XXX", &c::Implied , 1, 2, }, { 0x18, "CLC", &c::Implied , 1, 2, }, { 0x19, "ORA", &c::AbsoluteY, 3, 4, }, { 0x1A, "XXX", &c::Implied , 1, 2, }, { 0x1B, "XXX", &c::Implied , 1, 2, }, { 0x1C, "XXX", &c::Implied , 1, 2, }, { 0x1D, "ORA", &c::AbsoluteX, 3, 4, }, { 0x1E, "ASL", &c::AbsoluteX, 3, 7, }, { 0x1F, "XXX", &c::Implied , 1, 2, }, { 0x20, "JSR", &c::Absolute , 3, 6, }, { 0x21, "AND", &c::IndirectX, 2, 6, }, { 0x22, "XXX", &c::Implied , 1, 2, }, { 0x23, "XXX", &c::Implied , 1, 2, }, { 0x24, "BIT", &c::ZeroPage , 2, 3, }, { 0x25, "AND", &c::ZeroPage , 2, 3, }, { 0x26, "ROL", &c::ZeroPage , 2, 5, }, { 0x27, "XXX", &c::Implied , 1, 2, }, { 0x28, "PLP", &c::Implied , 1, 4, }, { 0x29, "AND", &c::Immediate, 2, 2, }, { 0x2A, "ROL", &c::Implied, 1, 2, }, { 0x2B, "XXX", &c::Implied , 1, 2, }, { 0x2C, "BIT", &c::Absolute , 3, 4, }, { 0x2D, "AND", &c::Absolute , 3, 4, }, { 0x2E, "ROL", &c::Absolute , 3, 6, }, { 0x2F, "XXX", &c::Implied , 1, 2, }, { 0x30, "BMI", &c::Relative , 2, 2, }, { 0x31, "AND", &c::IndirectY, 2, 5, }, { 0x32, "XXX", &c::Implied , 1, 2, }, { 0x33, "XXX", &c::Implied , 1, 2, }, { 0x34, "XXX", &c::Implied , 1, 2, }, { 0x35, "AND", &c::ZeroPageX, 2, 4, }, { 0x36, "ROL", &c::ZeroPageX, 2, 6, }, { 0x37, "XXX", &c::Implied , 1, 2, }, { 0x38, "SEC", &c::Implied , 1, 2, }, { 0x39, "AND", &c::AbsoluteY, 3, 4, }, { 0x3A, "XXX", &c::Implied , 1, 2, }, { 0x3B, "XXX", &c::Implied , 1, 2, }, { 0x3C, "XXX", &c::Implied , 1, 2, }, { 0x3D, "AND", &c::AbsoluteX, 3, 4, }, { 0x3E, "ROL", &c::AbsoluteX, 3, 7, }, { 0x3F, "XXX", &c::Implied , 1, 2, }, { 0x40, "RTI", &c::Implied , 1, 6, }, { 0x41, "EOR", &c::IndirectX, 2, 6, }, { 0x42, "XXX", &c::Implied , 1, 2, }, { 0x43, "XXX", &c::Implied , 1, 2, }, { 0x44, "XXX", &c::Implied , 1, 2, }, { 0x45, "EOR", &c::ZeroPage , 2, 3, }, { 0x46, "LSR", &c::ZeroPage , 2, 5, }, { 0x47, "XXX", &c::Implied , 1, 2, }, { 0x48, "PHA", &c::Implied , 1, 3, }, { 0x49, "EOR", &c::Immediate, 2, 2, }, { 0x4A, "LSR", &c::Implied, 1, 2, }, { 0x4B, "XXX", &c::Implied , 1, 2, }, { 0x4C, "JMP", &c::Absolute , 3, 3, }, { 0x4D, "EOR", &c::Absolute , 3, 4, }, { 0x4E, "LSR", &c::Absolute , 3, 6, }, { 0x4F, "XXX", &c::Implied , 1, 2, }, { 0x50, "BVC", &c::Relative , 2, 2, }, { 0x51, "EOR", &c::IndirectY, 2, 5, }, { 0x52, "XXX", &c::Implied , 1, 2, }, { 0x53, "XXX", &c::Implied , 1, 2, }, { 0x54, "XXX", &c::Implied , 1, 2, }, { 0x55, "EOR", &c::ZeroPageX, 2, 4, }, { 0x56, "LSR", &c::ZeroPageX, 2, 6, }, { 0x57, "XXX", &c::Implied , 1, 2, }, { 0x58, "CLI", &c::Implied , 1, 2, }, { 0x59, "EOR", &c::AbsoluteY, 3, 4, }, { 0x5A, "XXX", &c::Implied , 1, 2, }, { 0x5B, "XXX", &c::Implied , 1, 2, }, { 0x5C, "XXX", &c::Implied , 1, 2, }, { 0x5D, "EOR", &c::AbsoluteX, 3, 4, }, { 0x5E, "LSR", &c::AbsoluteX, 3, 7, }, { 0x5F, "XXX", &c::Implied , 1, 2, }, { 0x60, "RTS", &c::Implied , 1, 6, }, { 0x61, "ADC", &c::IndirectX, 2, 6, }, { 0x62, "XXX", &c::Implied , 1, 2, }, { 0x63, "XXX", &c::Implied , 1, 2, }, { 0x64, "XXX", &c::Implied , 1, 2, }, { 0x65, "ADC", &c::ZeroPage, 2, 3, }, { 0x66, "ROR", &c::ZeroPage , 2, 5, }, { 0x67, "XXX", &c::Implied , 1, 2, }, { 0x68, "PLA", &c::Implied , 1, 4, }, { 0x69, "ADC", &c::Immediate, 2, 2, }, { 0x6A, "ROR", &c::Implied, 1, 2, }, { 0x6B, "XXX", &c::Implied , 1, 2, }, { 0x6C, "JMP", &c::Indirect , 3, 5, }, { 0x6D, "ADC", &c::Absolute , 3, 4, }, { 0x6E, "ROR", &c::Absolute , 3, 6, }, { 0x6F, "XXX", &c::Implied , 1, 2, }, { 0x70, "BVS", &c::Relative , 2, 2, }, { 0x71, "ADC", &c::IndirectY, 2, 5, }, { 0x72, "XXX", &c::Implied , 1, 2, }, { 0x73, "XXX", &c::Implied , 1, 2, }, { 0x74, "XXX", &c::Implied , 1, 2, }, { 0x75, "ADC", &c::ZeroPageX, 2, 4, }, { 0x76, "ROR", &c::ZeroPageX, 2, 6, }, { 0x77, "XXX", &c::Implied , 1, 2, }, { 0x78, "SEI", &c::Implied , 1, 2, }, { 0x79, "ADC", &c::AbsoluteY, 3, 4, }, { 0x7A, "XXX", &c::Implied , 1, 2, }, { 0x7B, "XXX", &c::Implied , 1, 2, }, { 0x7C, "XXX", &c::Implied , 1, 2, }, { 0x7D, "ADC", &c::AbsoluteX, 3, 4, }, { 0x7E, "ROR", &c::AbsoluteX, 3, 7, }, { 0x7F, "XXX", &c::Implied , 1, 2, }, { 0x80, "XXX", &c::Implied , 1, 2, }, { 0x81, "STA", &c::IndirectX, 2, 6, }, { 0x82, "XXX", &c::Implied , 1, 2, }, { 0x83, "XXX", &c::Implied , 1, 2, }, { 0x84, "STY", &c::ZeroPage , 2, 3, }, { 0x85, "STA", &c::ZeroPage , 2, 3, }, { 0x86, "STX", &c::ZeroPage , 2, 3, }, { 0x87, "XXX", &c::Implied , 1, 2, }, { 0x88, "DEY", &c::Implied , 1, 2, }, { 0x89, "XXX", &c::Implied , 1, 2, }, { 0x8A, "TXA", &c::Implied , 1, 2, }, { 0x8B, "XXX", &c::Implied , 1, 2, }, { 0x8C, "STY", &c::Absolute , 3, 4, }, { 0x8D, "STA", &c::Absolute , 3, 4, }, { 0x8E, "STX", &c::Absolute , 3, 4, }, { 0x8F, "XXX", &c::Implied , 1, 2, }, { 0x90, "BCC", &c::Relative , 2, 2, }, { 0x91, "STA", &c::IndirectY, 2, 6, }, { 0x92, "XXX", &c::Implied , 1, 2, }, { 0x93, "XXX", &c::Implied , 1, 2, }, { 0x94, "STY", &c::ZeroPageX, 2, 4, }, { 0x95, "STA", &c::ZeroPageX, 2, 4, }, { 0x96, "STX", &c::ZeroPageY, 2, 4, }, { 0x97, "XXX", &c::Implied , 1, 2, }, { 0x98, "TYA", &c::Implied , 1, 2, }, { 0x99, "STA", &c::AbsoluteY, 3, 5, }, { 0x9A, "TXS", &c::Implied , 1, 2, }, { 0x9B, "XXX", &c::Implied , 1, 2, }, { 0x9C, "XXX", &c::Implied , 1, 2, }, { 0x9D, "STA", &c::AbsoluteX, 3, 5, }, { 0x9E, "XXX", &c::Implied , 1, 2, }, { 0x9F, "XXX", &c::Implied , 1, 2, }, { 0xA0, "LDY", &c::Immediate, 2, 2, }, { 0xA1, "LDA", &c::IndirectX, 2, 6, }, { 0xA2, "LDX", &c::Immediate, 2, 2, }, { 0xA3, "XXX", &c::Implied , 1, 2, }, { 0xA4, "LDY", &c::ZeroPage , 2, 3, }, { 0xA5, "LDA", &c::ZeroPage , 2, 3, }, { 0xA6, "LDX", &c::ZeroPage , 2, 3, }, { 0xA7, "XXX", &c::Implied , 1, 2, }, { 0xA8, "TAY", &c::Implied , 1, 2, }, { 0xA9, "LDA", &c::Immediate, 2, 2, }, { 0xAA, "TAX", &c::Implied , 1, 2, }, { 0xAB, "XXX", &c::Implied , 1, 2, }, { 0xAC, "LDY", &c::Absolute , 3, 4, }, { 0xAD, "LDA", &c::Absolute , 3, 4, }, { 0xAE, "LDX", &c::Absolute , 3, 4, }, { 0xAF, "XXX", &c::Implied , 1, 2, }, { 0xB0, "BCS", &c::Relative , 2, 2, }, { 0xB1, "LDA", &c::IndirectY, 2, 5, }, { 0xB2, "XXX", &c::Implied , 1, 2, }, { 0xB3, "XXX", &c::Implied , 1, 2, }, { 0xB4, "LDY", &c::ZeroPageX, 2, 4, }, { 0xB5, "LDA", &c::ZeroPageX, 2, 4, }, { 0xB6, "LDX", &c::ZeroPageY, 2, 4, }, { 0xB7, "XXX", &c::Implied , 1, 2, }, { 0xB8, "CLV", &c::Implied , 1, 2, }, { 0xB9, "LDA", &c::AbsoluteY, 3, 4, }, { 0xBA, "TSX", &c::Implied , 1, 2, }, { 0xBB, "XXX", &c::Implied , 1, 2, }, { 0xBC, "LDY", &c::AbsoluteX, 3, 4, }, { 0xBD, "LDA", &c::AbsoluteX, 3, 4, }, { 0xBE, "LDX", &c::AbsoluteY, 3, 4, }, { 0xBF, "XXX", &c::Implied , 1, 2, }, { 0xC0, "CPY", &c::Immediate, 2, 2, }, { 0xC1, "CMP", &c::IndirectX, 2, 6, }, { 0xC2, "XXX", &c::Implied , 1, 2, }, { 0xC3, "XXX", &c::Implied , 1, 2, }, { 0xC4, "CPY", &c::ZeroPage , 2, 3, }, { 0xC5, "CMP", &c::ZeroPage , 2, 3, }, { 0xC6, "DEC", &c::ZeroPage , 2, 5, }, { 0xC7, "XXX", &c::Implied , 1, 2, }, { 0xC8, "INY", &c::Implied , 1, 2, }, { 0xC9, "CMP", &c::Immediate, 2, 2, }, { 0xCA, "DEX", &c::Implied , 1, 2, }, { 0xCB, "XXX", &c::Implied , 1, 2, }, { 0xCC, "CPY", &c::Absolute , 3, 4, }, { 0xCD, "CMP", &c::Absolute , 3, 4, }, { 0xCE, "DEC", &c::Absolute , 3, 6, }, { 0xCF, "XXX", &c::Implied , 1, 2, }, { 0xD0, "BNE", &c::Relative , 2, 2, }, { 0xD1, "CMP", &c::IndirectY, 2, 5, }, { 0xD2, "XXX", &c::Implied , 1, 2, }, { 0xD3, "XXX", &c::Implied , 1, 2, }, { 0xD4, "XXX", &c::Implied , 1, 2, }, { 0xD5, "CMP", &c::ZeroPageX, 2, 4, }, { 0xD6, "DEC", &c::ZeroPageX, 2, 6, }, { 0xD7, "XXX", &c::Implied , 1, 2, }, { 0xD8, "CLD", &c::Implied , 1, 2, }, { 0xD9, "CMP", &c::AbsoluteY, 3, 4, }, { 0xDA, "XXX", &c::Implied , 1, 2, }, { 0xDB, "XXX", &c::Implied , 1, 2, }, { 0xDC, "XXX", &c::Implied , 1, 2, }, { 0xDD, "CMP", &c::AbsoluteX, 3, 4, }, { 0xDE, "DEC", &c::AbsoluteX, 3, 7, }, { 0xDF, "XXX", &c::Implied , 1, 2, }, { 0xE0, "CPX", &c::Immediate, 2, 2, }, { 0xE1, "SBC", &c::IndirectX, 2, 6, }, { 0xE2, "XXX", &c::Implied , 1, 2, }, { 0xE3, "XXX", &c::Implied , 1, 2, }, { 0xE4, "CPX", &c::ZeroPage , 2, 3, }, { 0xE5, "SBC", &c::ZeroPage , 2, 3, }, { 0xE6, "INC", &c::ZeroPage , 2, 5, }, { 0xE7, "XXX", &c::Implied , 1, 2, }, { 0xE8, "INX", &c::Implied , 1, 2, }, { 0xE9, "SBC", &c::Immediate, 2, 2, }, { 0xEA, "NOP", &c::Implied , 1, 2, }, { 0xEB, "XXX", &c::Implied , 1, 2, }, { 0xEC, "CPX", &c::Absolute , 3, 4, }, { 0xED, "SBC", &c::Absolute , 3, 4, }, { 0xEE, "INC", &c::Absolute , 3, 6, }, { 0xEF, "XXX", &c::Implied , 1, 2, }, { 0xF0, "BEQ", &c::Relative , 2, 2, }, { 0xF1, "SBC", &c::IndirectY, 2, 5, }, { 0xF2, "XXX", &c::Implied , 1, 2, }, { 0xF3, "XXX", &c::Implied , 1, 2, }, { 0xF4, "XXX", &c::Implied , 1, 2, }, { 0xF5, "SBC", &c::ZeroPageX, 2, 4, }, { 0xF6, "INC", &c::ZeroPageX, 2, 6, }, { 0xF7, "XXX", &c::Implied , 1, 2, }, { 0xF8, "SED", &c::Implied , 1, 2, }, { 0xF9, "SBC", &c::AbsoluteY, 3, 4, }, { 0xFA, "XXX", &c::Implied , 1, 2, }, { 0xFB, "XXX", &c::Implied , 1, 2, }, { 0xFC, "XXX", &c::Implied , 1, 2, }, { 0xFD, "SBC", &c::AbsoluteX, 3, 4, }, { 0xFE, "INC", &c::AbsoluteX, 3, 7, }, { 0xFF, "XXX", &c::Implied , 1, 2, }, // clang-format on }; } CPU::~CPU() { } void CPU::write(uint16_t addr, uint8_t data) { nes->cpuWrite(addr, data); } uint8_t CPU::read(uint16_t addr) const { return nes->cpuRead(addr, false); } // push a value onto the stack void CPU::push(uint8_t data, uint16_t offset) { write(offset + sp, data); sp--; } // push a 16 bit value onto the stack void CPU::push16(uint16_t data) { push((data >> 8) & 0x00FF); push(data & 0x00FF); } // pop a value from the stack uint8_t CPU::pop(uint16_t offset) { sp++; return read(sp + offset); } // pop 16 bits from the stack uint16_t CPU::pop16() { uint16_t ret = pop(); ret |= (uint16_t)(pop() << 8); return ret; } void CPU::reset() { a = 0; x = 0; y = 0; pc = ((read(0xFFFD) << 8) | read(0xFFFC)); sp = 0xFD; flags = 0; SetFlag(U); operand = 0; address = 0; cycles = 8; } void CPU::interrupt(uint16_t addr) { push16(pc); SetFlag(B, 0); SetFlag(U, 1); push(flags); pc = ((((uint16_t)read(addr + 1)) << 8) | (uint16_t)read(addr)); SetFlag(I, 1); cycles = 7; } void CPU::irq() { // Are interrupts not disabled? if (!GetFlag(I)) { interrupt(0xFFFE); } } void CPU::nmi() { // NMI cannot be ignored. Reads new PC from 0xFFFA interrupt(0xFFFA); } bool CPU::complete() { return (cycles == 0); } void CPU::clock() { if (cycles == 0) { #if LOG_LEVEL > LOG_LEVEL_NOP uint16_t log_pc; char log[100]; log_pc = pc; #endif // We are ready for the next instruction! // Read next opcode: opcode = read(pc); // Unused flag should always be true SetFlag(U); // Upgrade your PC! pc++; // How many cycles are we doing today? cycles = lookupTable[opcode].cycles; int add1 = (this->*lookupTable[opcode].addrmode)(); int add2 = 0; //(this->*lookupTable[opcode].operate)(); uint16_t value = 0; // THE BIG SWITCH switch (opcode) { case 0x00: // BRK pc++; SetFlag(I, true); push16(pc); SetFlag(B, true); push(flags); pc = (((uint16_t)read(0xFFFF) << 8) | (uint16_t)read(0xFFFE)); break; case 0x01: // ORA case 0x05: // ORA case 0x09: // ORA case 0x0D: // ORA case 0x11: // ORA case 0x15: // ORA case 0x19: // ORA case 0x1D: // ORA fetch(); a |= operand; SetFlag(Z, a == 0x00); SetFlag(N, a & 0x80); add2 = 1; break; case 0x06: // ASL case 0x0A: // ASL case 0x0E: // ASL case 0x16: // ASL case 0x1E: // ASL fetch(); temp = (uint16_t)operand << 1; SetFlag(C, (temp & 0xFF00) > 0); SetFlag(Z, (temp & 0x00FF) == 0x00); SetFlag(N, (temp & 0x0080)); if (lookupTable[opcode].addrmode == &CPU::Implied) a = temp & 0x00FF; else write(address, temp & 0x00FF); break; case 0x08: // PHP // apparently PHP always pushes B as '1' (but doesn't actually set it) push(flags | B | U); SetFlag(B, false); SetFlag(U, false); break; case 0x10: // BPL if (!GetFlag(N)) { cycles++; // Set address to branch to address = pc + address_rel; // Check for page boundary crossed if ((address & 0xFF00) != (pc & 0xFF00)) cycles++; pc = address; } break; case 0x18: // CLC SetFlag(C, false); break; case 0x20: // JSR pc--; push16(pc); pc = address; break; case 0x21: // AND case 0x25: // AND case 0x29: // AND case 0x2D: // AND case 0x31: // AND case 0x35: // AND case 0x39: // AND case 0x3D: // AND fetch(); a = a & operand; SetFlag(Z, a == 0x00); SetFlag(N, a & 0x80); add2 = 1; break; case 0x24: // BIT case 0x2C: // BIT fetch(); temp = a & operand; SetFlag(Z, (temp & 0x00FF) == 0x00); SetFlag(N, operand & 0x80); SetFlag(V, operand & 0x40); break; case 0x26: // ROL case 0x2A: // ROL case 0x2E: // ROL case 0x36: // ROL case 0x3E: // ROL fetch(); temp = (uint16_t)(operand << 1) | GetFlag(C); SetFlag(C, temp & 0xFF00); SetFlag(Z, (temp & 0x00FF) == 0x0000); SetFlag(N, temp & 0x0080); if (lookupTable[opcode].addrmode == &CPU::Implied) a = temp & 0x00FF; else write(address, temp & 0x00FF); break; case 0x28: // PLP flags = pop(); SetFlag(U); break; case 0x30: // BMI if (GetFlag(N)) { cycles++; // Set address to branch to address = pc + address_rel; // Check for page boundary crossed if ((address & 0xFF00) != (pc & 0xFF00)) cycles++; pc = address; } break; case 0x38: // SEC SetFlag(C); break; case 0x40: // RTI flags = pop(); SetFlag(B, false); SetFlag(U, false); pc = pop16(); break; case 0x41: // EOR case 0x45: // EOR case 0x49: // EOR case 0x4D: // EOR case 0x51: // EOR case 0x55: // EOR case 0x59: // EOR case 0x5D: // EOR fetch(); a = a ^ operand; SetFlag(Z, a == 0x00); SetFlag(N, a & 0x80); break; case 0x46: // LSR case 0x4A: // LSR case 0x4E: // LSR case 0x56: // LSR case 0x5E: // LSR fetch(); temp = (uint16_t)operand >> 1; SetFlag(C, operand & 0x0001); SetFlag(Z, (temp & 0x00FF) == 0x00); SetFlag(N, (temp & 0x0080)); if (lookupTable[opcode].addrmode == &CPU::Implied) a = temp & 0x00FF; else write(address, temp & 0x00FF); break; case 0x48: // PHA push(a); break; case 0x4C: // JMP case 0x6C: // JMP pc = address; break; case 0x50: // BVC if (!GetFlag(V)) { cycles++; // Set address to branch to address = pc + address_rel; // Check for page boundary crossed if ((address & 0xFF00) != (pc & 0xFF00)) cycles++; pc = address; } break; case 0x58: // CLI SetFlag(I, false); break; case 0x60: // RTS pc = pop16(); pc++; break; case 0x61: // ADC case 0x65: // ADC case 0x69: // ADC case 0x6D: // ADC case 0x71: // ADC case 0x75: // ADC case 0x79: // ADC case 0x7D: // ADC fetch(); temp = (uint16_t)a + (uint16_t)operand + (uint16_t)(GetFlag(C) ? 1 : 0); SetFlag(C, temp > 255); SetFlag(Z, (temp & 0x00FF) == 0); // I have no idea what's going on here lol // Taken from OneLoneCoder SetFlag(V, (~((uint16_t)a ^ (uint16_t)operand) & ((uint16_t)a ^ (uint16_t)temp)) & 0x0080); SetFlag(N, temp & 0x0080); a = temp & 0x00FF; add2 = 1; break; case 0x66: // ROR case 0x6A: // ROR case 0x6E: // ROR case 0x76: // ROR case 0x7E: // ROR fetch(); temp = (uint16_t)(GetFlag(C) << 7) | (operand >> 1); SetFlag(C, operand & 0x01); SetFlag(Z, (temp & 0x00FF) == 0x00); SetFlag(N, temp & 0x0080); if (lookupTable[opcode].addrmode == &CPU::Implied) a = temp & 0x00FF; else write(address, temp & 0x00FF); break; case 0x68: // PLA a = pop(); SetFlag(Z, a == 0x00); SetFlag(N, a & 0x80); break; case 0x70: // BVS if (GetFlag(V)) { cycles++; // Set address to branch to address = pc + address_rel; // Check for page boundary crossed if ((address & 0xFF00) != (pc & 0xFF00)) cycles++; pc = address; } break; case 0x78: // SEI SetFlag(I); break; case 0x81: // STA case 0x85: // STA case 0x8D: // STA case 0x91: // STA case 0x95: // STA case 0x9D: // STA case 0x99: // STA write(address, a); break; case 0x84: // STY case 0x8C: // STY case 0x94: // STY write(address, y); break; case 0x86: // STX case 0x8E: // STX case 0x96: // STX write(address, x); break; case 0x88: // DEY y--; SetFlag(Z, y == 0x00); SetFlag(N, y & 0x80); break; case 0x8A: // TXA a = x; SetFlag(Z, a == 0x00); SetFlag(N, a & 0x80); break; case 0x98: // TYA a = y; SetFlag(Z, a == 0x00); SetFlag(N, a & 0x80); break; case 0x9A: // TXS sp = x; break; case 0x90: // BCC if (!GetFlag(C)) { // cycles++ if branch succeeds cycles++; // Set address to branch to address = pc + address_rel; // Check for page boundary crossed if ((address & 0xFF00) != (pc & 0xFF00)) cycles++; pc = address; } break; case 0xA0: // LDY case 0xA4: // LDY case 0xAC: // LDY case 0xB4: // LDY case 0xBC: // LDY fetch(); y = operand; SetFlag(Z, y == 0x00); SetFlag(N, y & 0x80); add2 = 1; break; case 0xA1: // LDA case 0xA5: // LDA case 0xA9: // LDA case 0xAD: // LDA case 0xB1: // LDA case 0xB5: // LDA case 0xB9: // LDA case 0xBD: // LDA fetch(); a = operand; SetFlag(Z, a == 0x00); SetFlag(N, a & 0x80); add2 = 1; break; case 0xA2: // LDX case 0xA6: // LDX case 0xAE: // LDX case 0xB6: // LDX case 0xBE: // LDX fetch(); x = operand; SetFlag(Z, x == 0x00); SetFlag(N, x & 0x80); add2 = 1; break; case 0xA8: // TAY y = a; SetFlag(Z, y == 0x00); SetFlag(N, y & 0x80); break; case 0xAA: // TAX x = a; SetFlag(Z, x == 0x00); SetFlag(N, x & 0x80); break; case 0xBA: // TSX x = sp; SetFlag(Z, x == 0x00); SetFlag(N, x & 0x80); break; case 0xB0: // BCS if (GetFlag(C)) { cycles++; // Set address to branch to address = pc + address_rel; // Check for page boundary crossed if ((address & 0xFF00) != (pc & 0xFF00)) cycles++; pc = address; } break; case 0xB8: // CLV SetFlag(V, false); break; case 0xC0: // CPY case 0xC4: // CPY case 0xCC: // CPY fetch(); temp = (uint16_t)y - (uint16_t)operand; SetFlag(C, y >= operand); SetFlag(Z, y == operand); SetFlag(N, temp & 0x0080); add2 = 1; break; case 0xC1: // CMP case 0xC5: // CMP case 0xC9: // CMP case 0xCD: // CMP case 0xD1: // CMP case 0xD5: // CMP case 0xD9: // CMP case 0xDD: // CMP fetch(); temp = (uint16_t)a - (uint16_t)operand; //printf("temp: %04X a: %02X operand: %02X\n", temp, a, operand); SetFlag(C, a >= operand); SetFlag(Z, a == operand); SetFlag(N, temp & 0x0080); add2 = 1; break; case 0xE0: // CPX case 0xE4: // CPX case 0xEC: // CPX fetch(); temp = (uint16_t)x - (uint16_t)operand; SetFlag(C, x >= operand); SetFlag(Z, x == operand); SetFlag(N, temp & 0x0080); add2 = 1; break; case 0xC6: // DEC case 0xCE: // DEC case 0xD6: // DEC case 0xDE: // DEC fetch(); temp = operand - 1; SetFlag(Z, (temp & 0x00FF) == 0x00); SetFlag(N, temp & 0x0080); write(address, temp); break; case 0xC8: // INY y++; SetFlag(Z, y == 0x00); SetFlag(N, y & 0x80); break; case 0xCA: // DEX x--; SetFlag(Z, x == 0x00); SetFlag(N, x & 0x80); break; case 0xD0: // BNE if (!GetFlag(Z)) { cycles++; // Set address to branch to address = pc + address_rel; // Check for page boundary crossed if ((address & 0xFF00) != (pc & 0xFF00)) cycles++; pc = address; } break; case 0xD8: // CLD SetFlag(D, false); break; case 0xE1: // SBC case 0xE5: // SBC case 0xE9: // SBC case 0xED: // SBC case 0xF1: // SBC case 0xF5: // SBC case 0xF9: // SBC case 0xFD: // SBC // Taken from OLC. I haven't made an effort to fully understand it... fetch(); // Invert the bottom 8 bits (makes the operand negative) value = ((uint16_t)operand) ^ 0x00FF; // After that it's exactly the same as ADC ?!?? // (adding a negative number is equal to subtracting the positive equivalent of that number) temp = (uint16_t)a + value + (uint16_t)(GetFlag(C) ? 1 : 0); SetFlag(C, temp & 0xFF00); SetFlag(Z, (temp & 0x00FF) == 0); // I have no idea what's going on here lol SetFlag(V, (temp ^ (uint16_t)a) & (temp ^ value) & 0x0080); SetFlag(N, temp & 0x0080); a = temp & 0x00FF; add2 = 1; break; case 0xE6: // INC case 0xEE: // INC case 0xF6: // INC case 0xFE: // INC fetch(); temp = operand + 1; SetFlag(Z, (temp & 0x00FF) == 0x00); SetFlag(N, temp & 0x0080); write(address, temp); break; case 0xE8: // INX x++; SetFlag(Z, x == 0x00); SetFlag(N, x & 0x80); break; case 0xEA: // NOP break; case 0xF0: // BEQ if (GetFlag(Z)) { cycles++; // Set address to branch to address = pc + address_rel; // Check for page boundary crossed if ((address & 0xFF00) != (pc & 0xFF00)) cycles++; pc = address; } break; case 0xF8: // SED SetFlag(D); break; //case 0x5A: // XXX //case 0x5B: // XXX //case 0x5C: // XXX //case 0x5F: // XXX //case 0x62: // XXX //case 0x63: // XXX //case 0x64: // XXX //case 0x67: // XXX //case 0x6B: // XXX //case 0x6F: // XXX //case 0x72: // XXX //case 0x73: // XXX //case 0x74: // XXX //case 0x77: // XXX //case 0x7A: // XXX //case 0x7B: // XXX //case 0x7C: // XXX //case 0x7F: // XXX //case 0x80: // XXX //case 0x82: // XXX //case 0x83: // XXX //case 0x87: // XXX //case 0x89: // XXX //case 0x8B: // XXX //case 0x8F: // XXX //case 0x92: // XXX //case 0x93: // XXX //case 0x97: // XXX //case 0x9B: // XXX //case 0x9C: // XXX //case 0x9E: // XXX //case 0x9F: // XXX //case 0xA3: // XXX //case 0xA7: // XXX //case 0xAB: // XXX //case 0xAF: // XXX //case 0xB2: // XXX //case 0xB3: // XXX //case 0xB7: // XXX //case 0xBB: // XXX //case 0xBF: // XXX //case 0xC2: // XXX //case 0xC3: // XXX //case 0xC7: // XXX //case 0xCB: // XXX //case 0xCF: // XXX //case 0xD2: // XXX //case 0xD3: // XXX //case 0xD4: // XXX //case 0xD7: // XXX //case 0xDA: // XXX //case 0xDB: // XXX //case 0xDC: // XXX //case 0xDF: // XXX //case 0xE2: // XXX //case 0xE3: // XXX //case 0xE7: // XXX //case 0xEB: // XXX //case 0xEF: // XXX //case 0xF2: // XXX //case 0xF3: // XXX //case 0xF4: // XXX //case 0xF7: // XXX //case 0xFA: // XXX //case 0xFB: // XXX //case 0xFC: // XXX //case 0xFF: // XXX default: printf("Illegal opcode %02X encountered!\n", opcode); add2 = 0; break; } cycles += (add1 & add2); #if LOG_LEVEL > LOG_LEVEL_NOP sprintf(log, "%10ld: PC:%04X [Opcode %02X] A:%02X X:%02X Y:%02X", total_cycles, log_pc, opcode, a, x, y); l.w(std::string(log)); #endif } total_cycles++; cycles--; } uint8_t CPU::Relative() { address_rel = read(pc) & 0x00FF; pc++; if (address_rel & 0x80) address_rel |= 0xFF00; //printf("address_rel set to %04X (%d)\n", address_rel, (int8_t)address_rel); return 0; } uint8_t CPU::AbsoluteX() { address = read(pc); pc++; temp = read(pc); // hi 8 bits address |= (temp << 8); pc++; address += x; if ((address & 0xFF00) != (temp << 8)) return 1; else return 0; } uint8_t CPU::AbsoluteY() { address = read(pc); pc++; temp = read(pc); // hi 8 bits address |= (temp << 8); pc++; address += y; if ((address & 0xFF00) != (temp << 8)) return 1; else return 0; } uint8_t CPU::Indirect() { bool bug = false; temp = read(pc); if (temp == 0x00FF) // we must emulate the hardware bug bug = true; pc++; temp |= (read(pc) << 8); pc++; // now temp == an address // we need to read that address to get the real address // so the JMP instruction can jump to 'address' // if (bug) { address = read(temp) | (read(temp & 0xFF00) << 8); } else { address = read(temp) | (read(temp + 1) << 8); } return 0; } uint8_t CPU::IndirectX() { temp = read(pc); pc++; temp += x; address = (uint16_t)read(temp & 0x00FF) | (uint16_t)(read((temp + 1) & 0x00FF) << 8); //uint16_t lo = read((uint16_t)(temp + (uint16_t)x) & 0x00FF); //uint16_t hi = read((uint16_t)(temp + (uint16_t)x + 1) & 0x00FF); //address = (hi << 8) | lo; return 0; } uint8_t CPU::IndirectY() { temp = read(pc); pc++; uint16_t lo = read(temp & 0x00FF); uint16_t hi = read((temp + 1) & 0x00FF); address = ((hi << 8) | lo) + y; if ((address & 0xFF00) != (hi << 8)) return 1; else return 0; } // Get effective addresses for various modes (for the disassembler) uint16_t CPU::GetAddrZP(uint16_t addr) { return (addr & 0x00FF); } uint16_t CPU::GetAddrZPX(uint16_t addr) { uint16_t ret = 0; ret = (addr + x) & 0x00FF; return ret; } uint16_t CPU::GetAddrZPY(uint16_t addr) { uint16_t ret = 0; ret = (addr + y) & 0x00FF; return ret; } uint16_t CPU::GetAddrIDX(uint16_t addr) { uint16_t ret = 0; temp = read(addr) + x; ret = read(temp & 0x00FF) | (read((temp + 1) & 0x00FF) << 8); return ret; } uint16_t CPU::GetAddrIDY(uint16_t addr) { uint16_t ret = 0; uint16_t lo = read(addr & 0x00FF); uint16_t hi = read((addr + 1) & 0x00FF); ret = ((hi << 8) | lo) + y; return ret; } // Disassembler // Heavily based on OLC's work // TODO: for indirect/indexed addressing show actual values as well! DisassemblyType CPU::disassemble(uint16_t start, uint16_t end) { uint32_t addr = start; uint16_t line = 0, effective_address = 0; uint8_t value = 0, lo = 0, hi = 0; DisassemblyType lines; auto hex = [](uint32_t n, uint8_t d) { std::string s(d, '0'); for (int i = d - 1; i >= 0; i--, n >>= 4) s[i] = "0123456789ABCDEF"[n & 0xF]; return s; }; while (addr <= (uint32_t)end) { line = addr; std::string inst = "$" + hex(addr, 4) + ": "; uint8_t opcode = nes->cpuRead(addr, true); addr++; inst += lookupTable[opcode].mnemonic + " "; if (lookupTable[opcode].addrmode == &CPU::Implied) { inst += " "; } else if (lookupTable[opcode].addrmode == &CPU::Immediate) { value = nes->cpuRead(addr, true); addr++; inst += "#$" + hex(value, 2); } else if (lookupTable[opcode].addrmode == &CPU::ZeroPage) { lo = nes->cpuRead(addr, true); effective_address = GetAddrZP(lo); addr++; inst += "$" + hex(lo, 2) + " [$" + hex(effective_address, 4) + " = $" + hex(nes->cpuRead(effective_address), 2) + "]"; } else if (lookupTable[opcode].addrmode == &CPU::ZeroPageX) { lo = nes->cpuRead(addr, true); effective_address = GetAddrZPX(lo); addr++; inst += "$" + hex(lo, 2) + ", X [$" + hex(effective_address, 4) + " = $" + hex(nes->cpuRead(effective_address), 2) + "]"; } else if (lookupTable[opcode].addrmode == &CPU::ZeroPageY) { lo = nes->cpuRead(addr, true); effective_address = GetAddrZPY(lo); addr++; inst += "$" + hex(lo, 2) + ", Y [$" + hex(effective_address, 4) + " = $" + hex(nes->cpuRead(effective_address), 2) + "]"; } else if (lookupTable[opcode].addrmode == &CPU::IndirectX) { lo = nes->cpuRead(addr, true); effective_address = GetAddrIDX(lo); addr++; inst += "($" + hex(lo, 2) + ", X) [$" + hex(effective_address, 4) + " = $" + hex(nes->cpuRead(effective_address), 2) + "]"; } else if (lookupTable[opcode].addrmode == &CPU::IndirectY) { lo = nes->cpuRead(addr, true); effective_address = GetAddrIDY(lo); addr++; inst += "($" + hex(lo, 2) + "), Y [$" + hex(effective_address, 4) + " = $" + hex(nes->cpuRead(effective_address), 2) + "]"; } else if (lookupTable[opcode].addrmode == &CPU::Absolute) { lo = nes->cpuRead(addr, true); addr++; hi = nes->cpuRead(addr, true); addr++; inst += "$" + hex((uint16_t)(hi << 8) | lo, 4); } else if (lookupTable[opcode].addrmode == &CPU::AbsoluteX) { lo = nes->cpuRead(addr, true); addr++; hi = nes->cpuRead(addr, true); addr++; inst += "$" + hex((uint16_t)(hi << 8) | lo, 4) + ", X"; } else if (lookupTable[opcode].addrmode == &CPU::AbsoluteY) { lo = nes->cpuRead(addr, true); addr++; hi = nes->cpuRead(addr, true); addr++; inst += "$" + hex((uint16_t)(hi << 8) | lo, 4) + ", Y"; } else if (lookupTable[opcode].addrmode == &CPU::Indirect) { lo = nes->cpuRead(addr, true); addr++; hi = nes->cpuRead(addr, true); addr++; inst += "($" + hex((uint16_t)(hi << 8) | lo, 4) + ")"; } else if (lookupTable[opcode].addrmode == &CPU::Relative) { value = nes->cpuRead(addr, true); addr++; inst += "$" + hex(value, 2) + " [$" + hex(addr + (int8_t)value, 4) + "]"; } else { inst += "ERROR: Unknown addressing mode!"; } // lines[line] = inst; std::map<uint16_t, std::string> temp; temp[line] = inst; lines.push_back(temp); } return lines; } // prerequisite: // RAM 0x00 - 0xFF = 0x00 - 0xFF ...... void CPU::TestOpcodes() { opcode = read(pc); printf("PC: %04x - ", pc); if (opcode == lookupTable[opcode].opcode) { printf("Opcode 0x%02x matches index!\n", opcode); } else { printf("Opcode 0x%02x DOES NOT MATCH index!\n", opcode); } pc++; } //std::unordered_map<int, Opcode> CPU::CreateOpcodes() //{ // std::unordered_map<int, Opcode> opcodes; //opcodes[0x69] = Opcode("ADC", 2, 2, "NVbdiZC", Immediate); //opcodes[0x65] = Opcode("ADC", 2, 3, "NVbdiZC", ZeroPage ); //opcodes[0x75] = Opcode("ADC", 2, 4, "NVbdiZC", ZeroPageX); //opcodes[0x6D] = Opcode("ADC", 3, 4, "NVbdiZC", Absolute ); //opcodes[0x7D] = Opcode("ADC", 3, 4, "NVbdiZC", AbsoluteX); //opcodes[0x79] = Opcode("ADC", 3, 4, "NVbdiZC", AbsoluteY); //opcodes[0x61] = Opcode("ADC", 2, 6, "NVbdiZC", IndirectX); //opcodes[0x71] = Opcode("ADC", 2, 5, "NVbdiZC", IndirectY); //opcodes[0x29] = Opcode("AND", 2, 2, "NvbdiZc", Immediate); //opcodes[0x25] = Opcode("AND", 2, 3, "NvbdiZc", ZeroPage ); //opcodes[0x35] = Opcode("AND", 2, 4, "NvbdiZc", ZeroPageX); //opcodes[0x2D] = Opcode("AND", 3, 4, "NvbdiZc", Absolute ); //opcodes[0x3D] = Opcode("AND", 3, 4, "NvbdiZc", AbsoluteX); //opcodes[0x39] = Opcode("AND", 3, 4, "NvbdiZc", AbsoluteY); //opcodes[0x21] = Opcode("AND", 2, 6, "NvbdiZc", IndirectX); //opcodes[0x31] = Opcode("AND", 2, 5, "NvbdiZc", IndirectY); //opcodes[0x0A] = Opcode("ASL", 1, 2, "NvbdiZC", Accumulator); //opcodes[0x06] = Opcode("ASL", 2, 5, "NvbdiZC", ZeroPage ); //opcodes[0x16] = Opcode("ASL", 2, 6, "NvbdiZC", ZeroPageX); //opcodes[0x0E] = Opcode("ASL", 3, 6, "NvbdiZC", Absolute ); //opcodes[0x1E] = Opcode("ASL", 3, 7, "NvbdiZC", AbsoluteX); //opcodes[0x24] = Opcode("BIT", 2, 3, "NVbdiZc", ZeroPage ); //opcodes[0x2C] = Opcode("BIT", 3, 4, "NVbdiZc", Absolute ); //opcodes[0x10] = Opcode("BPL", 2, 3, "nvbdizc", Relative ); //opcodes[0x30] = Opcode("BMI", 2, 3, "nvbdizc", Relative ); //opcodes[0x50] = Opcode("BVC", 2, 3, "nvbdizc", Relative ); //opcodes[0x70] = Opcode("BVS", 2, 3, "nvbdizc", Relative ); //opcodes[0x90] = Opcode("BCC", 2, 3, "nvbdizc", Relative ); //opcodes[0xB0] = Opcode("BCS", 2, 3, "nvbdizc", Relative ); //opcodes[0xD0] = Opcode("BNE", 2, 3, "nvbdizc", Relative ); //opcodes[0xF0] = Opcode("BEQ", 2, 3, "nvbdizc", Relative ); //opcodes[0x00] = Opcode("BRK", 1, 7, "nvBdizc", Implied ); //opcodes[0xC9] = Opcode("CMP", 2, 2, "NvbdiZC", Immediate); //opcodes[0xC5] = Opcode("CMP", 2, 3, "NvbdiZC", ZeroPage ); //opcodes[0xD5] = Opcode("CMP", 2, 4, "NvbdiZC", ZeroPageX); //opcodes[0xCD] = Opcode("CMP", 3, 4, "NvbdiZC", Absolute ); //opcodes[0xDD] = Opcode("CMP", 3, 4, "NvbdiZC", AbsoluteX); //opcodes[0xD9] = Opcode("CMP", 3, 4, "NvbdiZC", AbsoluteY); //opcodes[0xC1] = Opcode("CMP", 2, 6, "NvbdiZC", IndirectX); //opcodes[0xD1] = Opcode("CMP", 2, 5, "NvbdiZC", IndirectY); //opcodes[0xE0] = Opcode("CPX", 2, 2, "NvbdiZC", Immediate); //opcodes[0xE4] = Opcode("CPX", 2, 3, "NvbdiZC", ZeroPage ); //opcodes[0xEC] = Opcode("CPX", 3, 4, "NvbdiZC", Absolute ); //opcodes[0xC0] = Opcode("CPY", 2, 2, "NvbdiZC", Immediate); //opcodes[0xC4] = Opcode("CPY", 2, 3, "NvbdiZC", ZeroPage ); //opcodes[0xCC] = Opcode("CPY", 3, 4, "NvbdiZC", Absolute ); //opcodes[0xC6] = Opcode("DEC", 2, 5, "NvbdiZc", ZeroPage ); //opcodes[0xD6] = Opcode("DEC", 2, 6, "NvbdiZc", ZeroPageX); //opcodes[0xCE] = Opcode("DEC", 3, 6, "NvbdiZc", Absolute ); //opcodes[0xDE] = Opcode("DEC", 3, 7, "NvbdiZc", AbsoluteX); //opcodes[0x49] = Opcode("EOR", 2, 2, "NvbdiZc", Immediate); //opcodes[0x45] = Opcode("EOR", 2, 3, "NvbdiZc", ZeroPage ); //opcodes[0x55] = Opcode("EOR", 2, 4, "NvbdiZc", ZeroPageX); //opcodes[0x4D] = Opcode("EOR", 3, 4, "NvbdiZc", Absolute ); //opcodes[0x5D] = Opcode("EOR", 3, 4, "NvbdiZc", AbsoluteX); //opcodes[0x59] = Opcode("EOR", 3, 4, "NvbdiZc", AbsoluteY); //opcodes[0x41] = Opcode("EOR", 2, 6, "NvbdiZc", IndirectX); //opcodes[0x51] = Opcode("EOR", 2, 5, "NvbdiZc", IndirectY); //// flags are probably wrong here //opcodes[0x18] = Opcode("CLC", 1, 2, "nvbdizc", Implied ); //opcodes[0x38] = Opcode("SEC", 1, 2, "nvbdizc", Implied ); //opcodes[0x58] = Opcode("CLI", 1, 2, "nvbdizc", Implied ); //opcodes[0x78] = Opcode("SEI", 1, 2, "nvbdizc", Implied ); //opcodes[0xB8] = Opcode("CLV", 1, 2, "nvbdizc", Implied ); //opcodes[0xD8] = Opcode("CLD", 1, 2, "nvbdizc", Implied ); //opcodes[0xF8] = Opcode("SED", 1, 2, "nvbdizc", Implied ); //opcodes[0xE6] = Opcode("INC", 2, 5, "NvbdiZc", ZeroPage ); //opcodes[0xF6] = Opcode("INC", 2, 6, "NvbdiZc", ZeroPageX); //opcodes[0xEE] = Opcode("INC", 3, 6, "NvbdiZc", Absolute ); //opcodes[0xFE] = Opcode("INC", 3, 7, "NvbdiZc", AbsoluteX); //opcodes[0x4C] = Opcode("JMP", 3, 3, "nvbdizc", Absolute ); //opcodes[0x6C] = Opcode("JMP", 3, 5, "nvbdizc", Indirect ); //opcodes[0x20] = Opcode("JSR", 3, 6, "nvbdizc", Absolute ); //opcodes[0xA9] = Opcode("LDA", 2, 2, "NvbdiZc", Immediate); //opcodes[0xA5] = Opcode("LDA", 2, 3, "NvbdiZc", ZeroPage ); //opcodes[0xB5] = Opcode("LDA", 2, 4, "NvbdiZc", ZeroPageX); //opcodes[0xAD] = Opcode("LDA", 3, 4, "NvbdiZc", Absolute ); //opcodes[0xBD] = Opcode("LDA", 3, 4, "NvbdiZc", AbsoluteX); //opcodes[0xB9] = Opcode("LDA", 3, 4, "NvbdiZc", AbsoluteY); //opcodes[0xA1] = Opcode("LDA", 2, 6, "NvbdiZc", IndirectX); //opcodes[0xB1] = Opcode("LDA", 2, 5, "NvbdiZc", IndirectY); //opcodes[0xA2] = Opcode("LDX", 2, 2, "NvbdiZc", Immediate); //opcodes[0xA6] = Opcode("LDX", 2, 3, "NvbdiZc", ZeroPage ); //opcodes[0xB6] = Opcode("LDX", 2, 4, "NvbdiZc", ZeroPageY); //opcodes[0xAE] = Opcode("LDX", 3, 4, "NvbdiZc", Absolute ); //opcodes[0xBE] = Opcode("LDX", 3, 4, "NvbdiZc", AbsoluteY); //opcodes[0xA0] = Opcode("LDY", 2, 2, "NvbdiZc", Immediate); //opcodes[0xA4] = Opcode("LDY", 2, 3, "NvbdiZc", ZeroPage ); //opcodes[0xB4] = Opcode("LDY", 2, 4, "NvbdiZc", ZeroPageX); //opcodes[0xAC] = Opcode("LDY", 3, 4, "NvbdiZc", Absolute ); //opcodes[0xBC] = Opcode("LDY", 3, 4, "NvbdiZc", AbsoluteX); //opcodes[0x4A] = Opcode("LSR", 1, 2, "NvbdiZC", Accumulator); //opcodes[0x46] = Opcode("LSR", 2, 5, "NvbdiZC", ZeroPage ); //opcodes[0x56] = Opcode("LSR", 2, 6, "NvbdiZC", ZeroPageX); //opcodes[0x4E] = Opcode("LSR", 3, 6, "NvbdiZC", Absolute ); //opcodes[0x5E] = Opcode("LSR", 3, 7, "NvbdiZC", AbsoluteX); //opcodes[0xEA] = Opcode("NOP", 1, 2, "nvbdizc", Implied ); //opcodes[0x09] = Opcode("ORA", 2, 2, "NvbdiZc", Immediate); //opcodes[0x05] = Opcode("ORA", 2, 3, "NvbdiZc", ZeroPage ); //opcodes[0x15] = Opcode("ORA", 2, 4, "NvbdiZc", ZeroPageX); //opcodes[0x0D] = Opcode("ORA", 3, 4, "NvbdiZc", Absolute ); //opcodes[0x1D] = Opcode("ORA", 3, 4, "NvbdiZc", AbsoluteX); //opcodes[0x19] = Opcode("ORA", 3, 4, "NvbdiZc", AbsoluteY); //opcodes[0x01] = Opcode("ORA", 2, 6, "NvbdiZc", IndirectX); //opcodes[0x11] = Opcode("ORA", 2, 5, "NvbdiZc", IndirectY); //opcodes[0xAA] = Opcode("TAX", 1, 2, "NvbdiZc", Implied ); //opcodes[0x8A] = Opcode("TXA", 1, 2, "NvbdiZc", Implied ); //opcodes[0xCA] = Opcode("DEX", 1, 2, "NvbdiZc", Implied ); //opcodes[0xE8] = Opcode("INX", 1, 2, "NvbdiZc", Implied ); //opcodes[0xA8] = Opcode("TAY", 1, 2, "NvbdiZc", Implied ); //opcodes[0x98] = Opcode("TYA", 1, 2, "NvbdiZc", Implied ); //opcodes[0x88] = Opcode("DEY", 1, 2, "NvbdiZc", Implied ); //opcodes[0xC8] = Opcode("INY", 1, 2, "NvbdiZc", Implied ); //opcodes[0x2A] = Opcode("ROL", 1, 2, "NvbdiZC", Accumulator); //opcodes[0x26] = Opcode("ROL", 2, 5, "NvbdiZC", ZeroPage ); //opcodes[0x36] = Opcode("ROL", 2, 6, "NvbdiZC", ZeroPageX); //opcodes[0x2E] = Opcode("ROL", 3, 6, "NvbdiZC", Absolute ); //opcodes[0x3E] = Opcode("ROL", 3, 7, "NvbdiZC", AbsoluteX); //opcodes[0x6A] = Opcode("ROR", 1, 2, "NvbdiZC", Accumulator); //opcodes[0x66] = Opcode("ROR", 2, 5, "NvbdiZC", ZeroPage ); //opcodes[0x76] = Opcode("ROR", 2, 6, "NvbdiZC", ZeroPageX); //opcodes[0x6E] = Opcode("ROR", 3, 6, "NvbdiZC", Absolute ); //opcodes[0x7E] = Opcode("ROR", 3, 7, "NvbdiZC", AbsoluteX); //opcodes[0x40] = Opcode("RTI", 1, 6, "NVBDIZC", Implied ); //opcodes[0x60] = Opcode("RTS", 1, 6, "nvbdizc", Implied ); //opcodes[0xE9] = Opcode("SBC", 2, 2, "NVbdiZC", Immediate); //opcodes[0xE5] = Opcode("SBC", 2, 3, "NVbdiZC", ZeroPage ); //opcodes[0xF5] = Opcode("SBC", 2, 4, "NVbdiZC", ZeroPageX); //opcodes[0xED] = Opcode("SBC", 3, 4, "NVbdiZC", Absolute ); //opcodes[0xFD] = Opcode("SBC", 3, 4, "NVbdiZC", AbsoluteX); //opcodes[0xF9] = Opcode("SBC", 3, 4, "NVbdiZC", AbsoluteY); //opcodes[0xE1] = Opcode("SBC", 2, 6, "NVbdiZC", IndirectX); //opcodes[0xF1] = Opcode("SBC", 2, 5, "NVbdiZC", IndirectY); //opcodes[0x85] = Opcode("STA", 2, 3, "nvbdizc", ZeroPage ); //opcodes[0x95] = Opcode("STA", 2, 4, "nvbdizc", ZeroPageX); //opcodes[0x8D] = Opcode("STA", 3, 4, "nvbdizc", Absolute ); //opcodes[0x9D] = Opcode("STA", 3, 5, "nvbdizc", AbsoluteX); //opcodes[0x99] = Opcode("STA", 3, 5, "nvbdizc", AbsoluteY); //opcodes[0x81] = Opcode("STA", 2, 6, "nvbdizc", IndirectX); //opcodes[0x91] = Opcode("STA", 2, 6, "nvbdizc", IndirectY); //opcodes[0x9A] = Opcode("TXS", 1, 2, "NvbdiZc", Implied ); //opcodes[0xBA] = Opcode("TSX", 1, 2, "NvbdiZc", Implied ); //opcodes[0x48] = Opcode("PHA", 1, 3, "NvbdiZc", Implied ); //opcodes[0x68] = Opcode("PLA", 1, 4, "NvbdiZc", Implied ); //opcodes[0x08] = Opcode("PHP", 1, 3, "NvbdiZc", Implied ); //opcodes[0x28] = Opcode("PLP", 1, 4, "NvbdiZc", Implied ); //opcodes[0x86] = Opcode("STX", 2, 3, "nvbdizc", ZeroPage ); //opcodes[0x96] = Opcode("STX", 2, 4, "nvbdizc", ZeroPageY); //opcodes[0x8E] = Opcode("STX", 3, 4, "nvbdizc", Absolute ); //opcodes[0x84] = Opcode("STY", 2, 3, "nvbdizc", ZeroPage ); //opcodes[0x94] = Opcode("STY", 2, 4, "nvbdizc", ZeroPageY); //opcodes[0x8C] = Opcode("STY", 3, 4, "nvbdizc", Absolute ); // return opcodes; //} // vim: foldmethod=syntax
34.115963
135
0.456777
abstrakct
df410b003d3a641134686f2e8a87f5cf1df3b292
16,150
cpp
C++
src/utils/regexwrappers.cpp
compiler-explorer/asm-parser
bc69e6bfd3b8b080a6781cc85dc89d127dd15a40
[ "BSD-2-Clause" ]
12
2021-03-23T16:09:11.000Z
2022-02-06T09:04:58.000Z
src/utils/regexwrappers.cpp
compiler-explorer/asm-parser
bc69e6bfd3b8b080a6781cc85dc89d127dd15a40
[ "BSD-2-Clause" ]
15
2020-10-04T16:47:19.000Z
2022-02-05T18:29:39.000Z
src/utils/regexwrappers.cpp
compiler-explorer/asm-parser
bc69e6bfd3b8b080a6781cc85dc89d127dd15a40
[ "BSD-2-Clause" ]
1
2021-01-14T03:33:04.000Z
2021-01-14T03:33:04.000Z
#include "regexwrappers.hpp" #include "regexes.hpp" #include "utils.hpp" #include <fmt/core.h> inline int svtoi(const std::string_view sv) { return std::atoi(sv.data()); } std::pair<int, int> AsmParser::AssemblyTextParserUtils::getSourceRef(const std::string_view line) { const auto match = AsmParser::Regexes::sourceTag(line); if (match) { const auto file_index = svtoi(match.get<1>().to_view()); const auto line_index = svtoi(match.get<2>().to_view()); return { file_index, line_index }; } else { return { 0, 0 }; } } std::optional<AsmParser::asm_file_def> AsmParser::AssemblyTextParserUtils::getFileDef(const std::string_view line) { const auto match = Regexes::fileFind(line); if (match) { const auto file_index = svtoi(match.get<1>().to_view()); const auto file_name = match.get<2>().to_view(); const auto file_name_rest = match.get<4>().to_view(); if (!file_name_rest.empty()) { return asm_file_def{ file_index, fmt::format("{}/{}", file_name, file_name_rest) }; } else { return asm_file_def{ file_index, std::string(file_name) }; } } return std::nullopt; } std::string AsmParser::AssemblyTextParserUtils::expandTabs(const std::string_view line) { std::string expandedLine; const std::string spaces = " "; expandedLine.reserve(line.length()); auto extraChars = 0; for (auto c : line) { if (c == '\t') { const auto total = expandedLine.length() + extraChars; const auto spacesNeeded = (total + 8) & 7; extraChars += spacesNeeded; expandedLine += spaces.substr(spacesNeeded); } else { expandedLine += c; } } return expandedLine; } static inline void rtrim(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) { return !std::isspace(ch); }) .base(), s.end()); } static inline void ltrim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) { return !std::isspace(ch); })); } std::string_view AsmParser::AssemblyTextParserUtils::getLineWithoutComment(const std::string_view line) { bool spacing = false; bool stillStarting = true; auto lastit = line.end(); for (auto it = line.begin(); it != line.end(); it++) { auto c = *it; if (c == ';' || c == '#') { if (!spacing) lastit = it; break; } else if (spacing) { if (!is_whitespace(c)) { spacing = false; } } else if (is_whitespace(c)) { if (!stillStarting) { spacing = true; lastit = it; } } else { stillStarting = false; } } return std::string_view{ line.begin(), lastit }; } std::string_view AsmParser::AssemblyTextParserUtils::getLineWithoutCommentAndStripFirstWord(const std::string_view line) { bool wordstarted = false; bool wordended = false; bool spacing = false; auto lastit = line.end(); auto afterfirstword = line.begin(); for (auto it = line.begin(); it != line.end(); it++) { auto c = *it; if (c == ';' || c == '#') { auto nextit = it + 1; if (nextit != line.end()) { auto nextchar = *nextit; // it's only a comment if the ; or # is followed by a whitespace if (nextchar != ' ' && nextchar != '\t') { continue; } } if (!spacing) lastit = it; break; } else if (!wordstarted && ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) { wordstarted = true; } else if (wordstarted && !wordended && is_whitespace(c)) { wordended = true; afterfirstword = it; } else if (wordended) { if (spacing) { if (!is_whitespace(c)) { lastit = line.end(); spacing = false; } } else if (is_whitespace(c)) { spacing = true; lastit = it; } } } return std::string_view{ afterfirstword, lastit }; } bool AsmParser::AssemblyTextParserUtils::is_probably_label(const std::string_view line) { const auto filtered = getLineWithoutComment(line); return (filtered.ends_with(":")); } std::string AsmParser::AssemblyTextParserUtils::fixLabelIndentation(const std::string_view line) { std::string filtered{ line }; if (is_probably_label(line)) ltrim(filtered); return filtered; } std::vector<AsmParser::asm_label> AsmParser::AssemblyTextParserUtils::getUsedLabelsInLine(const std::string_view line) { std::vector<AsmParser::asm_label> labelsInLine; const auto filteredLine = AssemblyTextParserUtils::getLineWithoutCommentAndStripFirstWord(line); if (filteredLine.find('\"') != std::string_view::npos) { return labelsInLine; } int diffLen = line.length() - filteredLine.length() + 1; int startidx = 0; for (auto match : ctre::range<R"re(([$%]?)([.@A-Z_a-z][.\dA-Z_a-z]*))re">(filteredLine)) { AsmParser::asm_label label{}; label.name = std::string(match.get<2>().to_view()); const auto len = label.name.length(); const auto loc = filteredLine.find(label.name, startidx); startidx += (loc - startidx) + len; label.range.start_col = loc + diffLen; label.range.end_col = loc + diffLen + ustrlen(label.name); labelsInLine.push_back(label); auto prefix = match.get<1>().to_view(); if (!prefix.empty()) { AsmParser::asm_label labelWithPrefix = label; labelWithPrefix.name = prefix; labelWithPrefix.name += label.name; labelWithPrefix.range.start_col--; labelsInLine.push_back(labelWithPrefix); } } return labelsInLine; } bool AsmParser::AssemblyTextParserUtils::hasOpcode(const std::string_view line, bool inNvccCode) { // Remove any leading label definition... const auto match = Regexes::labelDef(line); if (match) { // todo // line = line.substr(match[0].length); } // Strip any comments const auto lineWithoutComment = getLineWithoutComment(line); // .inst generates an opcode, so also counts if (Regexes::instOpcodeRe(lineWithoutComment)) return true; // Detect assignment, that's not an opcode... if (Regexes::assignmentDef(lineWithoutComment)) return false; if (inNvccCode) return !!Regexes::hasNvccOpcodeRe(lineWithoutComment); return !!Regexes::hasOpcodeRe(lineWithoutComment); } bool AsmParser::AssemblyTextParserUtils::isExampleOrStdin(const std::string_view filename) { if (Regexes::stdInLooking(filename)) return true; return false; } std::optional<AsmParser::asm_stabn> AsmParser::AssemblyTextParserUtils::getSourceInfoFromStabs(const std::string_view line) { const auto match = Regexes::sourceStab(line); if (!match) return std::nullopt; const auto type = svtoi(match.get<1>().to_view()); if (type == 68) { const auto line = svtoi(match.get<2>().to_view()); return asm_stabn{ type, line }; } else { return asm_stabn{ type, 0 }; } } std::optional<AsmParser::asm_source_v> AsmParser::AssemblyTextParserUtils::get6502DbgInfo(const std::string_view line) { const auto match = Regexes::source6502Dbg(line); if (match) { const auto file = match.get<1>().to_view(); const auto line = svtoi(match.get<2>().to_view()); // todo check if stdin? return asm_source_v{ .file = file, .line = line, .is_end = false }; } else { const auto matchend = Regexes::source6502DbgEnd(line); if (matchend) { return asm_source_v{ .file = "", .line = 0, .is_end = true }; } } return std::nullopt; } std::optional<AsmParser::asm_source_l> AsmParser::AssemblyTextParserUtils::getD2LineInfo(const std::string_view line) { const auto match = Regexes::sourceD2Tag(line); if (match) { const auto line = svtoi(match.get<1>().to_view()); return asm_source_l{ .line = line }; } return std::nullopt; } std::optional<AsmParser::asm_source_f> AsmParser::AssemblyTextParserUtils::getD2FileInfo(const std::string_view line) { const auto match = Regexes::sourceD2File(line); if (match) { const auto file = match.get<1>().to_view(); return asm_source_f{ .file = file }; } return std::nullopt; } bool AsmParser::AssemblyTextParserUtils::startCommentBlock(const std::string_view line) { if (Regexes::blockCommentStart(line)) return true; return false; } bool AsmParser::AssemblyTextParserUtils::endCommentBlock(const std::string_view line) { if (Regexes::blockCommentStop(line)) return true; return false; } bool AsmParser::AssemblyTextParserUtils::startAppBlock(const std::string_view line) { if (Regexes::startAppBlock(line)) return true; return false; } bool AsmParser::AssemblyTextParserUtils::endAppBlock(const std::string_view line) { if (Regexes::endAppBlock(line)) return true; return false; } bool AsmParser::AssemblyTextParserUtils::startAsmNesting(const std::string_view line) { if (Regexes::startAsmNesting(line)) return true; return false; } bool AsmParser::AssemblyTextParserUtils::endAsmNesting(const std::string_view line) { if (Regexes::endAsmNesting(line)) return true; return false; } bool AsmParser::AssemblyTextParserUtils::startBlock(const std::string_view line) { if (Regexes::startBlock(line)) return true; return false; } bool AsmParser::AssemblyTextParserUtils::endBlock(const std::string_view line) { if (Regexes::endBlock(line)) return true; return false; } std::optional<std::string_view> AsmParser::AssemblyTextParserUtils::getLabel(const std::string_view line) { auto match = Regexes::labelDef(line); if (match) { return match.get<1>().to_view(); } return std::nullopt; } std::optional<std::string_view> AsmParser::AssemblyTextParserUtils::getLabelAssignment(const std::string_view line) { auto matchAssign = Regexes::labelAssignmentDef(line); if (matchAssign) { return matchAssign.get<1>().to_view(); } return std::nullopt; } std::optional<std::string_view> AsmParser::AssemblyTextParserUtils::getAssignmentDef(const std::string_view line) { auto match = Regexes::assignmentDef(line); if (match) return match.get<1>().to_view(); return std::nullopt; } std::optional<std::string_view> AsmParser::AssemblyTextParserUtils::getCudaLabel(const std::string_view line) { auto match = Regexes::cudaBeginDef(line); if (match) return match.get<1>().to_view(); return std::nullopt; } std::optional<std::string_view> AsmParser::AssemblyTextParserUtils::getFunctionTypeDefinedLabel(const std::string_view line) { auto match = Regexes::definesFunctionOrObject(line); if (match) return match.get<1>().to_view(); return std::nullopt; } std::optional<std::string_view> AsmParser::AssemblyTextParserUtils::getWeakDefinedLabel(const std::string_view line) { auto match = Regexes::definesWeak(line); if (match) return match.get<1>().to_view(); return std::nullopt; } std::optional<std::string_view> AsmParser::AssemblyTextParserUtils::getGlobalDefinedLabel(const std::string_view line) { auto match = Regexes::definesGlobal(line); if (match) return match.get<1>().to_view(); return std::nullopt; } std::optional<std::string_view> AsmParser::AssemblyTextParserUtils::getSectionNameDef(const std::string_view line) { auto match = Regexes::sectionDef(line); if (match) { if (match.get<1>().to_view() == "section") { return match.get<2>().to_view(); } else { return match.get<1>().to_view(); } } return std::nullopt; } bool AsmParser::AssemblyTextParserUtils::isJustComments(const std::string_view line) { if (Regexes::commentOnly(line)) return true; return false; } bool AsmParser::AssemblyTextParserUtils::isJustNvccComments(const std::string_view line) { if (Regexes::commentOnlyNvcc(line)) return true; return false; } bool AsmParser::AssemblyTextParserUtils::isCudaEndDef(const std::string_view line) { if (Regexes::cudaEndDef(line)) return true; return false; } bool AsmParser::AssemblyTextParserUtils::isDataDefn(const std::string_view line) { if (Regexes::dataDefn(line)) return true; return false; } bool AsmParser::AssemblyTextParserUtils::isDirective(const std::string_view line) { if (Regexes::directive(line)) return true; return false; } bool AsmParser::AssemblyTextParserUtils::isInstOpcode(const std::string_view line) { if (Regexes::instOpcodeRe(line)) return true; return false; } std::string AsmParser::AssemblyTextParserUtils::squashHorizontalWhitespace(const std::string_view line, bool atStart) { std::string squashed; squashed.reserve(line.length()); enum class HorSpaceState { Start, Second, Stop, JustOne } state; if (atStart) { state = HorSpaceState::Start; } else { state = HorSpaceState::JustOne; } bool justspaces = true; for (auto c : line) { if (state == HorSpaceState::Stop) { if (is_whitespace(c)) { // ignore } else { state = HorSpaceState::JustOne; squashed += c; justspaces = false; } } else if (state == HorSpaceState::JustOne) { if (is_whitespace(c)) { state = HorSpaceState::Stop; squashed += ' '; } else { squashed += c; justspaces = false; } } else if (state == HorSpaceState::Start) { if (is_whitespace(c)) { state = HorSpaceState::Second; squashed += ' '; } else { state = HorSpaceState::Stop; squashed += c; justspaces = false; } } else if (state == HorSpaceState::Second) { if (is_whitespace(c)) { squashed += ' '; } else { squashed += c; justspaces = false; } state = HorSpaceState::Stop; } } if (atStart && justspaces) { squashed.clear(); } return squashed; } std::string AsmParser::AssemblyTextParserUtils::squashHorizontalWhitespaceWithQuotes(const std::string_view line, bool atStart) { const auto quotes = Regexes::findQuotes(line); if (quotes) { return fmt::format("{}{}{}", squashHorizontalWhitespaceWithQuotes(quotes.get<1>().to_view(), atStart), quotes.get<2>().to_view(), squashHorizontalWhitespaceWithQuotes(quotes.get<3>().to_view(), false)); } return squashHorizontalWhitespace(line); }
24.732006
127
0.582663
compiler-explorer
df4cb0ca67799da84ae3cd56b87cccfd8f6f8d64
8,837
hpp
C++
include/murk/crypto/aes.hpp
Cyclic3/murk
fd2f71a4b258be71ef828f1223ddb76cc4ec8254
[ "MIT" ]
2
2019-08-06T21:02:12.000Z
2021-12-22T16:12:38.000Z
include/murk/crypto/aes.hpp
Cyclic3/murk
fd2f71a4b258be71ef828f1223ddb76cc4ec8254
[ "MIT" ]
null
null
null
include/murk/crypto/aes.hpp
Cyclic3/murk
fd2f71a4b258be71ef828f1223ddb76cc4ec8254
[ "MIT" ]
null
null
null
#pragma once #include "murk/data.hpp" #include "murk/flows/bytes.hpp" namespace murk::crypto::aes { constexpr uint8_t sbox[256] = {0x63 ,0x7c ,0x77 ,0x7b ,0xf2 ,0x6b ,0x6f ,0xc5 ,0x30 ,0x01 ,0x67 ,0x2b ,0xfe ,0xd7 ,0xab ,0x76 ,0xca ,0x82 ,0xc9 ,0x7d ,0xfa ,0x59 ,0x47 ,0xf0 ,0xad ,0xd4 ,0xa2 ,0xaf ,0x9c ,0xa4 ,0x72 ,0xc0 ,0xb7 ,0xfd ,0x93 ,0x26 ,0x36 ,0x3f ,0xf7 ,0xcc ,0x34 ,0xa5 ,0xe5 ,0xf1 ,0x71 ,0xd8 ,0x31 ,0x15 ,0x04 ,0xc7 ,0x23 ,0xc3 ,0x18 ,0x96 ,0x05 ,0x9a ,0x07 ,0x12 ,0x80 ,0xe2 ,0xeb ,0x27 ,0xb2 ,0x75 ,0x09 ,0x83 ,0x2c ,0x1a ,0x1b ,0x6e ,0x5a ,0xa0 ,0x52 ,0x3b ,0xd6 ,0xb3 ,0x29 ,0xe3 ,0x2f ,0x84 ,0x53 ,0xd1 ,0x00 ,0xed ,0x20 ,0xfc ,0xb1 ,0x5b ,0x6a ,0xcb ,0xbe ,0x39 ,0x4a ,0x4c ,0x58 ,0xcf ,0xd0 ,0xef ,0xaa ,0xfb ,0x43 ,0x4d ,0x33 ,0x85 ,0x45 ,0xf9 ,0x02 ,0x7f ,0x50 ,0x3c ,0x9f ,0xa8 ,0x51 ,0xa3 ,0x40 ,0x8f ,0x92 ,0x9d ,0x38 ,0xf5 ,0xbc ,0xb6 ,0xda ,0x21 ,0x10 ,0xff ,0xf3 ,0xd2 ,0xcd ,0x0c ,0x13 ,0xec ,0x5f ,0x97 ,0x44 ,0x17 ,0xc4 ,0xa7 ,0x7e ,0x3d ,0x64 ,0x5d ,0x19 ,0x73 ,0x60 ,0x81 ,0x4f ,0xdc ,0x22 ,0x2a ,0x90 ,0x88 ,0x46 ,0xee ,0xb8 ,0x14 ,0xde ,0x5e ,0x0b ,0xdb ,0xe0 ,0x32 ,0x3a ,0x0a ,0x49 ,0x06 ,0x24 ,0x5c ,0xc2 ,0xd3 ,0xac ,0x62 ,0x91 ,0x95 ,0xe4 ,0x79 ,0xe7 ,0xc8 ,0x37 ,0x6d ,0x8d ,0xd5 ,0x4e ,0xa9 ,0x6c ,0x56 ,0xf4 ,0xea ,0x65 ,0x7a ,0xae ,0x08 ,0xba ,0x78 ,0x25 ,0x2e ,0x1c ,0xa6 ,0xb4 ,0xc6 ,0xe8 ,0xdd ,0x74 ,0x1f ,0x4b ,0xbd ,0x8b ,0x8a ,0x70 ,0x3e ,0xb5 ,0x66 ,0x48 ,0x03 ,0xf6 ,0x0e ,0x61 ,0x35 ,0x57 ,0xb9 ,0x86 ,0xc1 ,0x1d ,0x9e ,0xe1 ,0xf8 ,0x98 ,0x11 ,0x69 ,0xd9 ,0x8e ,0x94 ,0x9b ,0x1e ,0x87 ,0xe9 ,0xce ,0x55 ,0x28 ,0xdf ,0x8c ,0xa1 ,0x89 ,0x0d ,0xbf ,0xe6 ,0x42 ,0x68 ,0x41 ,0x99 ,0x2d ,0x0f ,0xb0 ,0x54 ,0xbb ,0x16}; constexpr uint8_t inv_sbox[256] = {0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d}; constexpr size_t state_size = 16; using table_t = std::array<uint8_t, state_size>; using table_ref_t = nonstd::span<uint8_t, state_size>; using round_constant_t = std::array<uint8_t, 4>; inline void sub_bytes(table_ref_t tab) { for (auto& i : tab) i = sbox[i]; } inline void unsub_bytes(table_ref_t tab) { for (auto& i : tab) i = inv_sbox[i]; } inline void shift_rows(table_ref_t tab) { table_t ref; std::copy(tab.begin(), tab.end(), ref.begin()); tab[ 1] = ref[ 5]; tab[ 5] = ref[ 9]; tab[ 9] = ref[13]; tab[13] = ref[ 1]; tab[ 2] = ref[10]; tab[ 6] = ref[14]; tab[10] = ref[ 2]; tab[14] = ref[ 6]; tab[ 3] = ref[15]; tab[ 7] = ref[ 3]; tab[11] = ref[ 7]; tab[15] = ref[11]; } inline void unshift_rows(table_ref_t tab) { table_t ref; std::copy(tab.begin(), tab.end(), ref.begin()); tab[ 5] = ref[ 1]; tab[ 9] = ref[ 5]; tab[13] = ref[ 9]; tab[ 1] = ref[13]; tab[10] = ref[ 2]; tab[14] = ref[ 6]; tab[ 2] = ref[10]; tab[ 6] = ref[14]; tab[15] = ref[ 3]; tab[ 3] = ref[ 7]; tab[ 7] = ref[11]; tab[11] = ref[15]; } inline void mix_columns(table_ref_t tab) { // Thx wikipedia auto* r = tab.data(); unsigned char a[4]; unsigned char b[4]; unsigned char c; unsigned char h; /* The array 'a' is simply a copy of the input array 'r' * The array 'b' is each element of the array 'a' multiplied by 2 * in Rijndael's Galois field * a[n] ^ b[n] is element n multiplied by 3 in Rijndael's Galois field */ for (c = 0; c < 4; c++) { a[c] = r[c]; /* h is 0xff if the high bit of r[c] is set, 0 otherwise */ h = (unsigned char)((signed char)r[c] >> 7); /* arithmetic right shift, thus shifting in either zeros or ones */ b[c] = r[c] << 1; /* implicitly removes high bit because b[c] is an 8-bit char, so we xor by 0x1b and not 0x11b in the next line */ b[c] ^= 0x1B & h; /* Rijndael's Galois field */ } r[0] = b[0] ^ a[3] ^ a[2] ^ b[1] ^ a[1]; /* 2 * a0 + a3 + a2 + 3 * a1 */ r[1] = b[1] ^ a[0] ^ a[3] ^ b[2] ^ a[2]; /* 2 * a1 + a0 + a3 + 3 * a2 */ r[2] = b[2] ^ a[1] ^ a[0] ^ b[3] ^ a[3]; /* 2 * a2 + a1 + a0 + 3 * a3 */ r[3] = b[3] ^ a[2] ^ a[1] ^ b[0] ^ a[0]; /* 2 * a3 + a2 + a1 + 3 * a0 */ } inline void add_round_key(table_ref_t tab, table_ref_t key) { murk::xor_bytes_inplace(tab, key); } /// If you end up using this namespace, something has gone _very_ wrong namespace rcon_detail { /// @param i the 0-indexed round number, but NOT 0!!! constexpr inline void update_round_constant(round_constant_t& prev, uint8_t i) { [[unlikely]] if (i == 1) prev = {1, 0, 0, 0}; else { uint16_t f = prev.front(); f = (f << 1) ^ (0x11b & -(f >> 7)); prev[0] = f; } } constexpr round_constant_t round_constants[11] = { {0x01, 0x00, 0x00, 0x00}, {0x02, 0x00, 0x00, 0x00}, {0x04, 0x00, 0x00, 0x00}, {0x08, 0x00, 0x00, 0x00}, {0x10, 0x00, 0x00, 0x00}, {0x20, 0x00, 0x00, 0x00}, {0x40, 0x00, 0x00, 0x00}, {0x80, 0x00, 0x00, 0x00}, {0x1B, 0x00, 0x00, 0x00}, {0x36, 0x00, 0x00, 0x00} }; inline void rot_word(round_constant_t& rcon) { uint8_t b; b = rcon[0]; rcon[0] = rcon[1]; rcon[1] = rcon[2]; rcon[2] = rcon[3]; rcon[3] = b; } inline void sub_word(round_constant_t& rcon) { rcon[0] = sbox[rcon[0]]; rcon[1] = sbox[rcon[1]]; rcon[2] = sbox[rcon[2]]; rcon[3] = sbox[rcon[3]]; } inline void schedule_core(round_constant_t& rcon, uint8_t i) { rot_word(rcon); sub_word(rcon); rcon[0] ^= round_constants[i - 1][0]; } } template<int KeyBits> constexpr int get_round_count(); template<> constexpr int get_round_count<128>() { return 11; } template<> constexpr int get_round_count<176>() { return 13; } template<> constexpr int get_round_count<256>() { return 15; } template<int KeyBits> using round_keys_t = std::array<table_t, get_round_count<KeyBits>()>; template<int KeyBits> inline void expand_key(round_keys_t<KeyBits>& out, nonstd::span<const uint8_t, KeyBits / 8> key); template<> inline void expand_key<128>(round_keys_t<128>& out, nonstd::span<const uint8_t, 128 / 8> key) { std::copy(key.begin(), key.end(), out.front().begin()); round_constant_t t; for (size_t round = 1; round < get_round_count<128>(); ++round) { auto& out_round = out[round]; for (size_t word_start = 0; word_start < 16;) { if (word_start == 0) { auto& target = out[round - 1]; std::copy(target.begin() + 12, target.end(), t.begin()); rcon_detail::schedule_core(t, round); } else { std::copy(out_round.begin() + word_start - 4, out_round.begin() + word_start, t.begin()); } auto in_round = out[round - 1]; for (size_t a = 0; a < 4; ++a) { out_round[word_start] = in_round[word_start] ^ t[a]; ++word_start; } } } } }
49.094444
1,573
0.565237
Cyclic3
df4d93120720694a875a738746bca74fe828dad6
822
cpp
C++
riddle/tests/test_lexer.cpp
pstlab/oRatio
0ec136fc60240e6cf090c8a6ba5055f84a215ac1
[ "Apache-2.0" ]
6
2020-02-20T14:52:01.000Z
2020-10-08T19:52:41.000Z
riddle/tests/test_lexer.cpp
pstlab/oRatio
0ec136fc60240e6cf090c8a6ba5055f84a215ac1
[ "Apache-2.0" ]
15
2018-01-25T12:37:51.000Z
2021-03-22T14:03:43.000Z
riddle/tests/test_lexer.cpp
pstlab/oRatio
0ec136fc60240e6cf090c8a6ba5055f84a215ac1
[ "Apache-2.0" ]
1
2019-04-29T23:16:57.000Z
2019-04-29T23:16:57.000Z
#include "lexer.h" #include <sstream> #include <cassert> using namespace riddle; void test_lexer_0() { std::stringstream ss("real a = 5 + 2;\nfalse;"); lexer l(ss); token *t0 = l.next(); assert(t0->sym == REAL_ID); token *t1 = l.next(); assert(t1->sym == ID_ID); token *t2 = l.next(); assert(t2->sym == EQ_ID); token *t3 = l.next(); assert(t3->sym == IntLiteral_ID); token *t4 = l.next(); assert(t4->sym == PLUS_ID); token *t5 = l.next(); assert(t5->sym == IntLiteral_ID); token *t6 = l.next(); assert(t6->sym == SEMICOLON_ID); token *t7 = l.next(); assert(t7->sym == FALSE_ID); token *t8 = l.next(); assert(t8->sym == SEMICOLON_ID); token *t9 = l.next(); assert(t9->sym == EOF_ID); } int main(int, char **) { test_lexer_0(); }
22.833333
52
0.558394
pstlab
df54fe9ea960519cc358e317ea5ebfc56d595593
28
cpp
C++
src/StoneCold.3D.Game/InputManager.cpp
krck/StoneCold_3D
5661a96e5167922b0ba555714a6d337acdea48c5
[ "BSD-3-Clause" ]
null
null
null
src/StoneCold.3D.Game/InputManager.cpp
krck/StoneCold_3D
5661a96e5167922b0ba555714a6d337acdea48c5
[ "BSD-3-Clause" ]
null
null
null
src/StoneCold.3D.Game/InputManager.cpp
krck/StoneCold_3D
5661a96e5167922b0ba555714a6d337acdea48c5
[ "BSD-3-Clause" ]
null
null
null
#include "InputManager.hpp"
14
27
0.785714
krck
df5b035b3addb1a074dad1985cb5fb0be699c696
331
cpp
C++
sandbox/sandbox_shared_lib/derived.cpp
VaderY/cereal
b03f237713a7e4aab18c7d9150fb3c9a5e92ea3a
[ "BSD-3-Clause" ]
null
null
null
sandbox/sandbox_shared_lib/derived.cpp
VaderY/cereal
b03f237713a7e4aab18c7d9150fb3c9a5e92ea3a
[ "BSD-3-Clause" ]
null
null
null
sandbox/sandbox_shared_lib/derived.cpp
VaderY/cereal
b03f237713a7e4aab18c7d9150fb3c9a5e92ea3a
[ "BSD-3-Clause" ]
null
null
null
#ifndef CEREAL_DLL_USE #define CEREAL_DLL_MAKE #endif #include "derived.hpp" template void Derived::serialize<cereal::XMLOutputArchive> ( cereal::XMLOutputArchive & ar, const std::uint32_t version ); template void Derived::serialize<cereal::XMLInputArchive> ( cereal::XMLInputArchive & ar, const std::uint32_t version );
30.090909
67
0.770393
VaderY
df5bbde765fee6dac3fc57a6ff711c7e0d1b1575
813
hpp
C++
include/fcppt/log/enabled_levels.hpp
vinzenz/fcppt
3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a
[ "BSL-1.0" ]
null
null
null
include/fcppt/log/enabled_levels.hpp
vinzenz/fcppt
3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a
[ "BSL-1.0" ]
null
null
null
include/fcppt/log/enabled_levels.hpp
vinzenz/fcppt
3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2016. // 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 FCPPT_LOG_ENABLED_LEVELS_HPP_INCLUDED #define FCPPT_LOG_ENABLED_LEVELS_HPP_INCLUDED #include <fcppt/log/enabled_level_array.hpp> #include <fcppt/log/level_fwd.hpp> #include <fcppt/log/detail/symbol.hpp> namespace fcppt { namespace log { /** \brief Creates an array with enabled levels including and above a level \ingroup fcpptlog Creates an \link fcppt::log::enabled_level_array \endlink which has every entry set to true that is greater or equal to \a level. */ FCPPT_LOG_DETAIL_SYMBOL fcppt::log::enabled_level_array enabled_levels( fcppt::log::level level ); } } #endif
21.394737
79
0.760148
vinzenz
df5d3730c5d5676400295283846d06a61df223fb
3,407
hpp
C++
src/route/TopicPublishInfo.hpp
ifplusor/rocketmq-client-cpp
fd301f4b064d5035fc72261023a396e2c9126c53
[ "Apache-2.0" ]
5
2019-04-24T13:37:05.000Z
2021-01-29T16:37:55.000Z
src/route/TopicPublishInfo.hpp
ifplusor/rocketmq-client-cpp
fd301f4b064d5035fc72261023a396e2c9126c53
[ "Apache-2.0" ]
null
null
null
src/route/TopicPublishInfo.hpp
ifplusor/rocketmq-client-cpp
fd301f4b064d5035fc72261023a396e2c9126c53
[ "Apache-2.0" ]
1
2021-02-03T03:11:03.000Z
2021-02-03T03:11:03.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ROCKETMQ_ROUTE_TOPICPUBLISHINFO_HPP_ #define ROCKETMQ_ROUTE_TOPICPUBLISHINFO_HPP_ #include <atomic> // std::atomic #include <memory> // std::shared_ptr #include <mutex> // std::mutex #include <vector> // std::vector #include "MQException.h" #include "MessageQueue.hpp" #include "logging/Logging.hpp" #include "protocol/body/TopicRouteData.hpp" namespace rocketmq { // struct TopicRouteData; class TopicPublishInfo; using TopicPublishInfoPtr = std::shared_ptr<const TopicPublishInfo>; class TopicPublishInfo { public: TopicPublishInfo() = default; TopicPublishInfo(const std::string& topic, std::shared_ptr<TopicRouteData> topic_route_data); bool isOrderTopic() const { return order_topic_; } bool ok() const { return !message_queues_.empty(); } const std::vector<MessageQueue>& getMessageQueueList() const { return message_queues_; } std::atomic<std::size_t>& getSendWhichQueue() const { return send_which_queue_; } const MessageQueue& selectOneMessageQueue(const std::string& lastBrokerName) const { if (!lastBrokerName.empty()) { auto mqSize = message_queues_.size(); if (mqSize <= 1) { if (mqSize == 0) { LOG_ERROR_NEW("[BUG] messageQueueList is empty"); THROW_MQEXCEPTION(MQClientException, "messageQueueList is empty", -1); } return message_queues_[0]; } // NOTE: If it possible, mq in same broker is nonadjacent. auto index = send_which_queue_.fetch_add(1); for (size_t i = 0; i < 2; i++) { auto pos = index++ % message_queues_.size(); const auto& mq = message_queues_[pos]; if (mq.broker_name() != lastBrokerName) { return mq; } } return message_queues_[(index - 2) % message_queues_.size()]; } return selectOneMessageQueue(); } const MessageQueue& selectOneMessageQueue() const { auto index = send_which_queue_.fetch_add(1); auto pos = index % message_queues_.size(); return message_queues_[pos]; } int getQueueIdByBroker(const std::string& broker_name) const { for (const auto& queue_data : topic_route_data_->queue_datas) { if (queue_data.broker_name == broker_name) { return queue_data.write_queue_nums; } } return -1; } private: bool order_topic_{false}; const std::vector<MessageQueue> message_queues_; // no change after build mutable std::atomic<std::size_t> send_which_queue_{0}; std::shared_ptr<TopicRouteData> topic_route_data_; // no change after set }; } // namespace rocketmq #endif // ROCKETMQ_ROUTE_TOPICPUBLISHINFO_HPP_
33.07767
95
0.708248
ifplusor
df5ecbcc497ea0260cb3437fb2d483967e14974f
329
cpp
C++
Arcanist/src/ArcanistApp.cpp
zaub3rfuchs/Arc
19b159bb6ea014b615e16ff13c946b6f93c0f281
[ "Apache-2.0" ]
null
null
null
Arcanist/src/ArcanistApp.cpp
zaub3rfuchs/Arc
19b159bb6ea014b615e16ff13c946b6f93c0f281
[ "Apache-2.0" ]
null
null
null
Arcanist/src/ArcanistApp.cpp
zaub3rfuchs/Arc
19b159bb6ea014b615e16ff13c946b6f93c0f281
[ "Apache-2.0" ]
null
null
null
#include <Arc.h> #include <Arc/Core/EntryPoint.h> #include "EditorLayer.h" namespace ArcEngine { class Arcanist : public Application { public: Arcanist() : Application("Arcanist") { PushLayer(new EditorLayer()); } ~Arcanist() { } }; Application* CreateApplication() { return new Arcanist(); } }
11.344828
36
0.644377
zaub3rfuchs
df60b317eb2fa02f9c96e19a32a654ddc3f77efe
21,560
cpp
C++
src/mongo/db/exhaust_cursor_currentop_integration_test.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/db/exhaust_cursor_currentop_integration_test.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/db/exhaust_cursor_currentop_integration_test.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2018-present MongoDB, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * 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 * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the Server Side Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #include "mongo/platform/basic.h" #include "mongo/client/dbclient_connection.h" #include "mongo/client/dbclient_rs.h" #include "mongo/db/query/cursor_response.h" #include "mongo/logv2/log.h" #include "mongo/rpc/get_status_from_command_result.h" #include "mongo/stdx/future.h" #include "mongo/unittest/integration_test.h" #include "mongo/unittest/unittest.h" #include "mongo/util/system_clock_source.h" #define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kTest namespace mongo { namespace { // Specifies the amount of time we are willing to wait for a parallel operation to complete. const auto parallelWaitTimeoutMS = Milliseconds(5 * 60 * 1000); // Obtain a pointer to the global system clock. Used to enforce timeouts in the parallel thread. auto* const clock = SystemClockSource::get(); const NamespaceString testNSS{"exhaust_cursor_currentop.testColl"}; const StringData testAppName = "curop_exhaust_cursor_test"; std::unique_ptr<DBClientBase> connect(StringData appName = testAppName) { auto swConn = unittest::getFixtureConnectionString().connect(appName.toString()); uassertStatusOK(swConn.getStatus()); return std::move(swConn.getValue()); } const StringData testBackgroundAppName = "curop_exhaust_cursor_test_bg"; void initTestCollection(DBClientBase* conn) { // Drop and recreate the test namespace. conn->dropCollection(testNSS.ns()); for (int i = 0; i < 10; i++) { auto insertCmd = BSON("insert" << testNSS.coll() << "documents" << BSON_ARRAY(BSON("a" << i))); auto reply = conn->runCommand(OpMsgRequest::fromDBAndBody(testNSS.db(), insertCmd)); ASSERT_OK(getStatusFromCommandResult(reply->getCommandReply())); } } void setWaitWithPinnedCursorDuringGetMoreBatchFailpoint(DBClientBase* conn, bool enable) { auto cmdObj = BSON("configureFailPoint" << "waitWithPinnedCursorDuringGetMoreBatch" << "mode" << (enable ? "alwaysOn" : "off") << "data" << BSON("shouldNotdropLock" << true << "shouldContinueOnInterrupt" << true)); auto reply = conn->runCommand(OpMsgRequest::fromDBAndBody("admin", cmdObj)); ASSERT_OK(getStatusFromCommandResult(reply->getCommandReply())); } void setWaitAfterCommandFinishesExecutionFailpoint(DBClientBase* conn, bool enable) { auto cmdObj = BSON("configureFailPoint" << "waitAfterCommandFinishesExecution" << "mode" << (enable ? "alwaysOn" : "off") << "data" << BSON("ns" << testNSS.toString())); auto reply = conn->runCommand(OpMsgRequest::fromDBAndBody("admin", cmdObj)); ASSERT_OK(getStatusFromCommandResult(reply->getCommandReply())); } void setWaitBeforeUnpinningOrDeletingCursorAfterGetMoreBatchFailpoint(DBClientBase* conn, bool enable) { auto cmdObj = BSON("configureFailPoint" << "waitBeforeUnpinningOrDeletingCursorAfterGetMoreBatch" << "mode" << (enable ? "alwaysOn" : "off")); auto reply = conn->runCommand(OpMsgRequest::fromDBAndBody("admin", cmdObj)); ASSERT_OK(getStatusFromCommandResult(reply->getCommandReply())); } bool confirmCurrentOpContents(DBClientBase* conn, BSONObj curOpMatch, bool expectEmptyResult = false, Milliseconds timeoutMS = Milliseconds(5 * 60 * 1000), Milliseconds intervalMS = Milliseconds(200)) { auto curOpCmd = BSON("aggregate" << 1 << "cursor" << BSONObj() << "pipeline" << BSON_ARRAY(BSON("$currentOp" << BSON("idleCursors" << true)) << BSON("$match" << curOpMatch))); const auto startTime = clock->now(); while (clock->now() - startTime < timeoutMS) { auto reply = conn->runCommand(OpMsgRequest::fromDBAndBody("admin", curOpCmd)); auto swCursorRes = CursorResponse::parseFromBSON(reply->getCommandReply()); ASSERT_OK(swCursorRes.getStatus()); if (swCursorRes.getValue().getBatch().empty() == expectEmptyResult) { return true; } sleepFor(intervalMS); } auto currentOp = BSON("currentOp" << BSON("idleCursors" << true)); LOGV2(20606, "confirmCurrentOpContents fails with curOpMatch: {curOpMatch} currentOp: " "{conn_runCommand_OpMsgRequest_fromDBAndBody_admin_currentOp_getCommandReply}", "curOpMatch"_attr = curOpMatch, "conn_runCommand_OpMsgRequest_fromDBAndBody_admin_currentOp_getCommandReply"_attr = conn->runCommand(OpMsgRequest::fromDBAndBody("admin", currentOp))->getCommandReply()); return false; } repl::OpTime getLastAppliedOpTime(DBClientBase* conn) { auto reply = conn->runCommand(OpMsgRequest::fromDBAndBody("admin", BSON("replSetGetStatus" << 1))); ASSERT_OK(getStatusFromCommandResult(reply->getCommandReply())); auto lastAppliedOpTime = reply->getCommandReply()["optimes"]["appliedOpTime"]; return repl::OpTime(lastAppliedOpTime["ts"].timestamp(), lastAppliedOpTime["t"].numberLong()); } // Start an exhaust request with a batchSize of 2 in the initial 'find' and a batchSize of 1 in // subsequent 'getMore's. auto startExhaustQuery( DBClientBase* queryConnection, std::unique_ptr<DBClientCursor>& queryCursor, int queryOptions = 0, Milliseconds awaitDataTimeoutMS = Milliseconds(5000), const boost::optional<repl::OpTime>& lastKnownCommittedOpTime = boost::none) { queryOptions = queryOptions | QueryOption_Exhaust; auto queryThread = stdx::async(stdx::launch::async, [&queryCursor, queryConnection, queryOptions, awaitDataTimeoutMS, lastKnownCommittedOpTime] { const auto projSpec = BSON("_id" << 0 << "a" << 1); // Issue the initial 'find' with a batchSize of 2 and the exhaust flag set. // We then iterate through the first batch and confirm that the results are // as expected. queryCursor = queryConnection->query_DEPRECATED( testNSS, BSONObj{}, Query(), 0, 0, &projSpec, queryOptions, 2); for (int i = 0; i < 2; ++i) { ASSERT_BSONOBJ_EQ(queryCursor->nextSafe(), BSON("a" << i)); } // Having exhausted the two results returned by the initial find, we set the // batchSize to 1 and issue a single getMore via DBClientCursor::more(). // Because the 'exhaust' flag is set, the server will generate a series of // internal getMores and stream them back to the client until the cursor is // exhausted, without the client sending any further getMore requests. We // expect this request to hang at the // 'waitWithPinnedCursorDuringGetMoreBatch' failpoint. queryCursor->setBatchSize(1); if ((queryOptions & QueryOption_CursorTailable) && (queryOptions & QueryOption_AwaitData)) { queryCursor->setAwaitDataTimeoutMS(awaitDataTimeoutMS); if (lastKnownCommittedOpTime) { auto term = lastKnownCommittedOpTime.get().getTerm(); queryCursor->setCurrentTermAndLastCommittedOpTime( term, lastKnownCommittedOpTime); } } ASSERT(queryCursor->more()); }); // Wait until the parallel operation initializes its cursor. const auto startTime = clock->now(); while (!queryCursor && (clock->now() - startTime < parallelWaitTimeoutMS)) { sleepFor(Milliseconds(10)); } ASSERT(queryCursor); LOGV2(20607, "Started exhaust query with cursorId: {queryCursor_getCursorId}", "queryCursor_getCursorId"_attr = queryCursor->getCursorId()); return queryThread; } void runOneGetMore(DBClientBase* conn, const std::unique_ptr<DBClientCursor>& queryCursor, int nDocsReturned) { const auto curOpMatch = BSON("command.collection" << testNSS.coll() << "command.getMore" << queryCursor->getCursorId() << "failpointMsg" << "waitWithPinnedCursorDuringGetMoreBatch" << "cursor.nDocsReturned" << nDocsReturned); // Confirm that the initial getMore appears in the $currentOp output. ASSERT(confirmCurrentOpContents(conn, curOpMatch)); // Airlock the failpoint by releasing it only after we enable a post-getMore failpoint. This // ensures that no subsequent getMores can run before we re-enable the original failpoint. setWaitBeforeUnpinningOrDeletingCursorAfterGetMoreBatchFailpoint(conn, true); setWaitWithPinnedCursorDuringGetMoreBatchFailpoint(conn, false); // Confirm that the getMore completed its batch and hit the post-getMore failpoint. ASSERT(confirmCurrentOpContents( conn, BSON("command.getMore" << queryCursor->getCursorId() << "failpointMsg" << "waitBeforeUnpinningOrDeletingCursorAfterGetMoreBatch"))); // Re-enable the original failpoint to catch the next getMore, and release the current one. setWaitWithPinnedCursorDuringGetMoreBatchFailpoint(conn, true); setWaitBeforeUnpinningOrDeletingCursorAfterGetMoreBatchFailpoint(conn, false); } } // namespace TEST(CurrentOpExhaustCursorTest, CanSeeEachExhaustCursorPseudoGetMoreInCurrentOpOutput) { auto conn = connect(); // We need to set failpoints around getMore which cause it to hang, so only test against a // single server rather than a replica set or mongoS. if (conn->isReplicaSetMember() || conn->isMongos()) { return; } initTestCollection(conn.get()); // Enable a failpoint to block getMore during execution. setWaitWithPinnedCursorDuringGetMoreBatchFailpoint(conn.get(), true); const auto queryConnection = connect(testBackgroundAppName); std::unique_ptr<DBClientCursor> queryCursor; // Execute a query on a separate thread, with the 'exhaust' flag set. auto queryThread = startExhaustQuery(queryConnection.get(), queryCursor); // Ensure that, regardless of whether the test completes or fails, we release all failpoints. ON_BLOCK_EXIT([&conn, &queryThread] { setWaitWithPinnedCursorDuringGetMoreBatchFailpoint(conn.get(), false); setWaitBeforeUnpinningOrDeletingCursorAfterGetMoreBatchFailpoint(conn.get(), false); queryThread.wait(); }); // We expect that the server, having received the first {batchSize: 1} getMore for the parallel // thread's exhaust cursor, will produce a series of pseudo-getMores internally and stream the // results back to the client until the cursor is exhausted. Here, we verify that each of these // pseudo-getMores appear in the $currentOp output. for (int i = 2; i < 10; ++i) { runOneGetMore(conn.get(), queryCursor, i); } } // Test exhaust cursor is cleaned up on client disconnect. By default, the test client disconnects // while the exhaust getMore is running. If disconnectAfterGetMoreBatch is set to true, the test // client disconnects after the exhaust getMore is run but before the server sends out the response. void testClientDisconnect(bool disconnectAfterGetMoreBatch) { auto conn = connect(); // We need to set failpoints around getMore which cause it to hang, so only test against a // single server rather than a replica set or mongoS. if (conn->isReplicaSetMember() || conn->isMongos()) { return; } initTestCollection(conn.get()); // Enable a failpoint to block getMore during execution. setWaitWithPinnedCursorDuringGetMoreBatchFailpoint(conn.get(), true); const auto connStr = unittest::getFixtureConnectionString(); const auto queryConnection = std::make_unique<DBClientConnection>(); uassertStatusOK( queryConnection->connect(connStr.getServers()[0], testBackgroundAppName, boost::none)); std::unique_ptr<DBClientCursor> queryCursor; // Execute a query on a separate thread, with the 'exhaust' flag set. auto queryThread = startExhaustQuery(queryConnection.get(), queryCursor); // Ensure that, regardless of whether the test completes or fails, we release all failpoints. ON_BLOCK_EXIT([&conn, &queryThread] { setWaitWithPinnedCursorDuringGetMoreBatchFailpoint(conn.get(), false); setWaitBeforeUnpinningOrDeletingCursorAfterGetMoreBatchFailpoint(conn.get(), false); queryThread.wait(); }); // This will allow the initial getMore to run. runOneGetMore(conn.get(), queryCursor, 2); // The next getMore will be an exhaust getMore. Confirm that the exhaust getMore appears in the // $currentOp output. auto curOpMatch = BSON("command.collection" << testNSS.coll() << "command.getMore" << queryCursor->getCursorId() << "failpointMsg" << "waitWithPinnedCursorDuringGetMoreBatch" << "cursor.nDocsReturned" << 3); ASSERT(confirmCurrentOpContents(conn.get(), curOpMatch)); if (disconnectAfterGetMoreBatch) { // Allow the exhaust getMore to run but block it before sending out the response. setWaitAfterCommandFinishesExecutionFailpoint(conn.get(), true); setWaitWithPinnedCursorDuringGetMoreBatchFailpoint(conn.get(), false); ASSERT(confirmCurrentOpContents(conn.get(), BSON("command.getMore" << queryCursor->getCursorId() << "failpointMsg" << "waitAfterCommandFinishesExecution"))); } // Kill the client connection while the exhaust getMore is blocked on the failpoint. queryConnection->shutdownAndDisallowReconnect(); LOGV2(20608, "Killed exhaust connection."); if (disconnectAfterGetMoreBatch) { // Disable the failpoint to allow the exhaust getMore to continue sending out the response // after the client disconnects. This will result in a broken pipe error. setWaitAfterCommandFinishesExecutionFailpoint(conn.get(), false); } curOpMatch = BSON("command.collection" << testNSS.coll() << "command.getMore" << queryCursor->getCursorId()); // Confirm that the exhaust getMore was interrupted and does not appear in the $currentOp // output. const bool expectEmptyResult = true; ASSERT(confirmCurrentOpContents(conn.get(), curOpMatch, expectEmptyResult)); setWaitWithPinnedCursorDuringGetMoreBatchFailpoint(conn.get(), false); setWaitBeforeUnpinningOrDeletingCursorAfterGetMoreBatchFailpoint(conn.get(), false); curOpMatch = BSON("type" << "idleCursor" << "cursor.cursorId" << queryCursor->getCursorId()); // Confirm that the cursor was cleaned up and does not appear in the $currentOp idleCursor // output. ASSERT(confirmCurrentOpContents(conn.get(), curOpMatch, expectEmptyResult)); } TEST(CurrentOpExhaustCursorTest, InterruptExhaustCursorPseudoGetMoreOnClientDisconnect) { // Test that an exhaust getMore is interrupted on client disconnect. testClientDisconnect(false /* disconnectAfterGetMoreBatch */); } TEST(CurrentOpExhaustCursorTest, CleanupExhaustCursorOnBrokenPipe) { // Test that exhaust cursor is cleaned up on broken pipe even if the exhaust getMore succeeded. testClientDisconnect(true /* disconnectAfterGetMoreBatch */); } TEST(CurrentOpExhaustCursorTest, ExhaustCursorUpdatesLastKnownCommittedOpTime) { auto fixtureConn = connect(); // We need to test the lastKnownCommittedOpTime in exhaust getMore requests. So we need a // replica set. if (!fixtureConn->isReplicaSetMember()) { return; } // Connect directly to the primary. DBClientBase* conn = &static_cast<DBClientReplicaSet*>(fixtureConn.get())->primaryConn(); ASSERT(conn); conn->dropCollection(testNSS.ns()); // Create a capped collection to run tailable awaitData queries on. conn->createCollection(testNSS.ns(), 1024 /* size of collection */, true /* capped */, 10 /* max number of objects */); // Insert initial records into the capped collection. for (int i = 0; i < 5; i++) { auto insertCmd = BSON("insert" << testNSS.coll() << "documents" << BSON_ARRAY(BSON("a" << i))); auto reply = conn->runCommand(OpMsgRequest::fromDBAndBody(testNSS.db(), insertCmd)); ASSERT_OK(getStatusFromCommandResult(reply->getCommandReply())); } // Get the lastAppliedOpTime after the initial inserts. auto lastAppliedOpTime = getLastAppliedOpTime(conn); // Create a new connection to the primary for the exhaust query. const auto fixtureQueryConn = connect(testBackgroundAppName); DBClientBase* queryConn = &static_cast<DBClientReplicaSet*>(fixtureQueryConn.get())->primaryConn(); std::unique_ptr<DBClientCursor> queryCursor; // Enable a failpoint to block getMore during execution to avoid races between getCursorId() and // receiving new batches. setWaitWithPinnedCursorDuringGetMoreBatchFailpoint(conn, true); // Initiate a tailable awaitData exhaust cursor with lastKnownCommittedOpTime being the // lastAppliedOpTime. auto queryThread = startExhaustQuery(queryConn, queryCursor, QueryOption_CursorTailable | QueryOption_AwaitData, Milliseconds(1000), // awaitData timeout lastAppliedOpTime); // lastKnownCommittedOpTime // Assert non-zero cursorId. auto cursorId = queryCursor->getCursorId(); ASSERT_NE(cursorId, 0LL); // Disable failpoint and allow exhaust queries to run. setWaitWithPinnedCursorDuringGetMoreBatchFailpoint(conn, false); ON_BLOCK_EXIT([&conn, &queryThread] { queryThread.wait(); }); // Test that the cursor's lastKnownCommittedOpTime is eventually advanced to the // lastAppliedOpTime. auto curOpMatch = BSON("command.collection" << testNSS.coll() << "command.getMore" << cursorId << "cursor.lastKnownCommittedOpTime" << lastAppliedOpTime); ASSERT(confirmCurrentOpContents(conn, curOpMatch)); // Inserting more records to unblock awaitData and advance the commit point. for (int i = 5; i < 8; i++) { auto insertCmd = BSON("insert" << testNSS.coll() << "documents" << BSON_ARRAY(BSON("a" << i))); auto reply = conn->runCommand(OpMsgRequest::fromDBAndBody(testNSS.db(), insertCmd)); ASSERT_OK(getStatusFromCommandResult(reply->getCommandReply())); } // Get the new lastAppliedOpTime after the inserts. lastAppliedOpTime = getLastAppliedOpTime(conn); // Test that the cursor's lastKnownCommittedOpTime is eventually advanced to the // new lastAppliedOpTime. curOpMatch = BSON("command.collection" << testNSS.coll() << "command.getMore" << cursorId << "cursor.lastKnownCommittedOpTime" << lastAppliedOpTime); ASSERT(confirmCurrentOpContents(conn, curOpMatch)); } } // namespace mongo
50.023202
100
0.659091
benety
df6118fbe570ec363dfa0fcb232188b47cb84336
1,353
cpp
C++
solutions/usaco/silver/jan_2019/paintbarn.cpp
TanishT/Competitive-Programming
b90fe43d7f92de62ebfd2f4aa1d470711cbe8bf0
[ "MIT" ]
2
2021-02-19T18:15:03.000Z
2021-03-27T20:26:55.000Z
solutions/usaco/silver/jan_2019/paintbarn.cpp
TanishT/Comp-Programming
b90fe43d7f92de62ebfd2f4aa1d470711cbe8bf0
[ "MIT" ]
8
2021-01-17T16:39:08.000Z
2021-03-22T01:27:15.000Z
solutions/usaco/silver/jan_2019/paintbarn.cpp
anaconda121/Competitive-Programming
b90fe43d7f92de62ebfd2f4aa1d470711cbe8bf0
[ "MIT" ]
null
null
null
#include <algorithm> #include <vector> #include <math.h> #include <iostream> #include <stdio.h> #include <climits> using namespace std; int n, k; int grid[1002][1002]; void setIO(string name, bool includeout=false) { // name is nonempty for USACO file I/O ios_base::sync_with_stdio(0); cin.tie(0); // see Fast Input & Output // alternatively, cin.tie(0)->sync_with_stdio(0); freopen((name+".in").c_str(), "r", stdin); // see Input & Output if (includeout) { freopen((name+".out").c_str(), "w", stdout); } } int main() { setIO("paintbarn", true); cin >> n >> k; int minx, miny = INT_MAX; int maxx, maxy = INT_MIN; for (int i = 0; i < n; i++) { int x,y,x2,y2; cin >> x >> y >> x2 >> y2; for (int j = x; j < x2; j++) { for (int k = y; k < y2; k++) { grid[j][k]++; } } minx = min(minx, min(x, x2)); maxx = max(maxx, max(x,x2)); miny = min(miny, min(y,y2)); maxy = max(maxy, max(y,y2)); } //cout << minx << " " << maxx << " " << miny << " " << maxy << endl; int count = 0; for (int i = minx; i < maxx; i++) { for (int j = miny; j < maxy; j++) { if (grid[i][j] == k) { count++; } } } cout << count << endl; return 0; }
26.529412
87
0.473762
TanishT
df62d5005e157b28b4e891feda043cb83077a258
8,473
cc
C++
lang/cimport/packing.cc
meyerj/typelib
e2a8d67d35732ffdd1d586aa8370576033ecc5a6
[ "CECILL-B" ]
null
null
null
lang/cimport/packing.cc
meyerj/typelib
e2a8d67d35732ffdd1d586aa8370576033ecc5a6
[ "CECILL-B" ]
null
null
null
lang/cimport/packing.cc
meyerj/typelib
e2a8d67d35732ffdd1d586aa8370576033ecc5a6
[ "CECILL-B" ]
null
null
null
#include "packing.hh" #include <typelib/typemodel.hh> #include <typelib/typevisitor.hh> #include <boost/lexical_cast.hpp> #include <typelib/typedisplay.hh> //////////////////////////////////////////////////////////////////////////////// // // Check some assumptions we make in the packing code // #include <boost/mpl/size.hpp> #include "packing/tools.tcc" #include "packing/check_arrays.tcc" #include "packing/check_struct_in_struct.tcc" #include "packing/check_size_criteria.tcc" #include <vector> #include <set> #include <map> namespace { struct PackingInfo { size_t size; size_t packing; PackingInfo() : size(0), packing(0) {} }; int const packing_info_size = ::boost::mpl::size<podlist>::type::value; PackingInfo packing_info[packing_info_size]; template<typename T> struct DiscoverCollectionPacking { int8_t v; T collection; static size_t get() { DiscoverCollectionPacking<T> obj; return reinterpret_cast<uint8_t*>(&obj.collection) - reinterpret_cast<uint8_t*>(&obj); } }; struct CollectionPackingInfo { char const* name; size_t packing; }; /** It seems that the following rule apply with struct size rounding: the * size is rounded so that the biggest element in the structure is properly * aligned. */ // To get the size of an empty struct struct EmptyStruct { }; // Rounded size is 24 struct StructSizeDiscovery1 { int64_t a; int64_t z; int8_t end; }; struct StructSizeDiscovery2 { int32_t a; int32_t b; int64_t z; int8_t end; }; // Rounded size is 20 struct StructSizeDiscovery3 { int32_t a; int32_t b; int32_t c; int32_t d; int8_t end; }; struct StructSizeDiscovery4 { int32_t a[4]; int8_t end; }; struct StructSizeDiscovery5 { int16_t a[2]; int32_t b[3]; int8_t end; }; // Rounded size is 18 struct StructSizeDiscovery6 { int16_t a[2]; int16_t b[6]; int8_t end; }; struct StructSizeDiscovery7 { int8_t a[4]; int16_t b[6]; int8_t end; }; // Rounded size is 17 struct StructSizeDiscovery8 { int8_t a[4]; int8_t b[12]; int8_t end; }; BOOST_STATIC_ASSERT( (sizeof(long) == 8 && sizeof(StructSizeDiscovery1) == 24) || (sizeof(long) == 4 && sizeof(StructSizeDiscovery1) == 20)); BOOST_STATIC_ASSERT( (sizeof(long) == 8 && sizeof(StructSizeDiscovery2) == 24) || (sizeof(long) == 4 && sizeof(StructSizeDiscovery2) == 20)); BOOST_STATIC_ASSERT(sizeof(StructSizeDiscovery3) == 20); BOOST_STATIC_ASSERT(sizeof(StructSizeDiscovery4) == 20); BOOST_STATIC_ASSERT(sizeof(StructSizeDiscovery5) == 20); BOOST_STATIC_ASSERT(sizeof(StructSizeDiscovery6) == 18); BOOST_STATIC_ASSERT(sizeof(StructSizeDiscovery7) == 18); BOOST_STATIC_ASSERT(sizeof(StructSizeDiscovery8) == 17); } #include "packing/build_packing_info.tcc" // build_packing_info builds a // PackingInfo[] packing_info // // where the first element is the size to // consider and the second its packing namespace { ////////////////////////////////////////////////////////////////////////// // // Helpers for client code // using namespace Typelib; struct GetPackingSize : public TypeVisitor { int size; GetPackingSize(Type const& base_type) : size(-1) { apply(base_type); } bool visit_(Numeric const& value) { size = value.getSize(); return false; } bool visit_(Enum const& value) { size = value.getSize(); return false; } bool visit_(Pointer const& value) { size = value.getSize(); return false; } bool visit_(Compound const& value) { typedef Compound::FieldList Fields; Fields const& fields(value.getFields()); if (fields.empty()) throw Packing::FoundNullStructure(); // TODO: add a static check for this // we assume that unions are packed as their biggest field int max_size = 0; for (Fields::const_iterator it = fields.begin(); it != fields.end(); ++it) { GetPackingSize recursive(it->getType()); if (recursive.size == -1) throw std::runtime_error("cannot compute the packing size for " + value.getName()); max_size = std::max(max_size, recursive.size); } size = max_size; return true; } bool visit_(Container const& value) { CollectionPackingInfo collection_packing_info[] = { { "/std/vector", DiscoverCollectionPacking< std::vector<uint16_t> >::get() }, { "/std/set", DiscoverCollectionPacking< std::set<uint8_t> >::get() }, { "/std/map", DiscoverCollectionPacking< std::map<uint8_t, uint8_t> >::get() }, { "/std/string", DiscoverCollectionPacking< std::string >::get() }, { 0, 0 } }; for (CollectionPackingInfo* info = collection_packing_info; info->name; ++info) { if (info->name == std::string(value.getName(), 0, std::string(info->name).size())) { size = info->packing; return true; } } throw Packing::PackingUnknown("cannot compute the packing of " + boost::lexical_cast<std::string>(value.getName())); } }; }; #include <iostream> using std::cout; using std::endl; int Typelib::Packing::getOffsetOf(const Field& last_field, const Type& append_field, size_t packing) { if (packing == 0) return 0; int base_offset = last_field.getOffset() + last_field.getType().getSize(); return (base_offset + (packing - 1)) / packing * packing; } int Typelib::Packing::getOffsetOf(Compound const& compound, const Type& append_field, size_t packing) { Compound::FieldList const& fields(compound.getFields()); if (fields.empty()) return 0; return getOffsetOf(fields.back(), append_field, packing); } int Typelib::Packing::getOffsetOf(const Field& last_field, const Type& append_field) { GetPackingSize visitor(append_field); if (visitor.size == -1) throw PackingUnknown("cannot compute the packing of " + boost::lexical_cast<std::string>(append_field.getName())); size_t const size(visitor.size); for (int i = 0; i < packing_info_size; ++i) { if (packing_info[i].size == size) return getOffsetOf(last_field, append_field, packing_info[i].packing); } throw PackingUnknown("cannot compute the packing of " + boost::lexical_cast<std::string>(append_field.getName())); } int Typelib::Packing::getOffsetOf(const Compound& current, const Type& append_field) { Compound::FieldList const& fields(current.getFields()); if (fields.empty()) return 0; return getOffsetOf(fields.back(), append_field); } struct AlignmentBaseTypeVisitor : public TypeVisitor { Type const* result; bool handleType(Type const& type) { if (!result || result->getSize() < type.getSize()) result = &type; return true; } virtual bool visit_ (NullType const& type) { throw UnsupportedType(type, "cannot represent alignment of null types"); } virtual bool visit_ (OpaqueType const& type) { throw UnsupportedType(type, "cannot represent alignment of opaque types"); }; virtual bool visit_ (Numeric const& type) { return handleType(type); } virtual bool visit_ (Enum const& type) { return handleType(type); } virtual bool visit_ (Pointer const& type) { return handleType(type); } virtual bool visit_ (Container const& type) { return handleType(type); } // arrays and compound are handled recursively static Type const* find(Type const& type) { AlignmentBaseTypeVisitor visitor; visitor.result = NULL; visitor.apply(type); return visitor.result; } }; int Typelib::Packing::getSizeOfCompound(Compound const& compound) { // Find the biggest type in the compound Compound::FieldList const& fields(compound.getFields()); if (fields.empty()) return sizeof(EmptyStruct); Type const* biggest_type = AlignmentBaseTypeVisitor::find(compound); return getOffsetOf(compound, *biggest_type); }
32.968872
128
0.619497
meyerj
df647043b80cd16f957121b27129855a843460bf
927
cpp
C++
LeviathanTest/TestFiles/GuiTests.cpp
Higami69/Leviathan
90f68f9f6e5506d6133bcefcf35c8e84f158483b
[ "BSL-1.0" ]
null
null
null
LeviathanTest/TestFiles/GuiTests.cpp
Higami69/Leviathan
90f68f9f6e5506d6133bcefcf35c8e84f158483b
[ "BSL-1.0" ]
null
null
null
LeviathanTest/TestFiles/GuiTests.cpp
Higami69/Leviathan
90f68f9f6e5506d6133bcefcf35c8e84f158483b
[ "BSL-1.0" ]
null
null
null
//! \file Tests for various supporting GUI methods. Doesn't actually //! try any rendering or anything like that #include "GUI/VideoPlayer.h" #include "../PartialEngine.h" #include "catch.hpp" using namespace Leviathan; using namespace Leviathan::Test; using namespace Leviathan::GUI; TEST_CASE("Leviathan VideoPlayer loads correctly", "[gui][video][xrequired]"){ // TODO: add leviathan intro video that can be attempted to be opened // Requires audio SoundDevice sound; PartialEngineWithOgre engine(nullptr, &sound); engine.Log.IgnoreWarnings = true; REQUIRE(sound.Init(false, true)); VideoPlayer player; REQUIRE(player.Play("Data/Videos/SampleVideo.mkv")); CHECK(player.GetDuration() == 10.336f); CHECK(player.GetVideoWidth() == 1920); CHECK(player.GetVideoHeight() == 1080); CHECK(player.IsStreamValid()); player.Stop(); sound.Release(); }
22.609756
78
0.693635
Higami69
df659393908d56903e559bbbd238f30a02b5e6ca
2,926
cxx
C++
inetsrv/query/filters/html/source/titletag.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetsrv/query/filters/html/source/titletag.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetsrv/query/filters/html/source/titletag.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation, 1992 - 1999 // // File: titletag.cxx // // Contents: Parsing algorithm for title tag in Html // // Subclassed from CPropertyText, so as to emit a third copy // of the chunk text as a VALUE chunk, but otherwise as // per the tag table entry. See comment in proptag.cxx. // // Classes: CTitleTag // //---------------------------------------------------------------------------- #include <pch.cxx> #pragma hdrstop //+------------------------------------------------------------------------- // // Method: CTitleTag::CTitleTag // // Synopsis: Constructor // // Arguments: [htmlIFilter] -- Reference to Html filter // [serialStream] -- Reference to input stream // //-------------------------------------------------------------------------- CTitleTag::CTitleTag( CHtmlIFilter& htmlIFilter, CSerialStream& serialStream ) : CPropertyTag(htmlIFilter, serialStream) { } //+------------------------------------------------------------------------- // // Method: CTitleTag::GetValue // // Synopsis: Retrieves value from current chunk // // Arguments: [ppPropValue] -- Value returned here // // History: 09-27-1999 KitmanH Property value is filtered here, // instead of relying on GetText // //-------------------------------------------------------------------------- SCODE CTitleTag::GetValue( VARIANT **ppPropValue ) { switch (_eState) { case FilteringValueProperty: { SCODE sc = CPropertyTag::ReadProperty(); if ( SUCCEEDED(sc) ) { PROPVARIANT *pPropVar = (PROPVARIANT *) CoTaskMemAlloc( sizeof PROPVARIANT ); if ( pPropVar == 0 ) return E_OUTOFMEMORY; pPropVar->vt = VT_LPWSTR; int cb = ( _cPropChars ) * sizeof( WCHAR ); pPropVar->pwszVal = (WCHAR *) CoTaskMemAlloc( cb ); if ( pPropVar->pwszVal == 0 ) { CoTaskMemFree( (void *) pPropVar ); return E_OUTOFMEMORY; } RtlCopyMemory( pPropVar->pwszVal, _xPropBuf.Get(), cb ); *ppPropValue = pPropVar; // reset buffer _cPropChars = 0; _eState = NoMoreValueProperty; return FILTER_S_LAST_VALUES; } else return sc; } case NoMoreValueProperty: return FILTER_E_NO_MORE_VALUES; default: Win4Assert( !"Unknown value of _eState" ); htmlDebugOut(( DEB_ERROR, "CTitleTag::GetValue, unknown value of _eState: %d\n", _eState )); return E_FAIL; } }
28.970297
90
0.455229
npocmaka
df659582d24a157fdf0a3351a454f1291e7053cf
8,833
cpp
C++
src/vm/readytoruninfo.cpp
CyberSys/coreclr-mono
83b2cb83b32faa45b4f790237b5c5e259692294a
[ "MIT" ]
10
2015-11-03T16:35:25.000Z
2021-07-31T16:36:29.000Z
src/vm/readytoruninfo.cpp
CyberSys/coreclr-mono
83b2cb83b32faa45b4f790237b5c5e259692294a
[ "MIT" ]
1
2019-03-05T18:50:09.000Z
2019-03-05T18:50:09.000Z
src/vm/readytoruninfo.cpp
CyberSys/coreclr-mono
83b2cb83b32faa45b4f790237b5c5e259692294a
[ "MIT" ]
4
2015-10-28T12:26:26.000Z
2021-09-04T11:36:04.000Z
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // =========================================================================== // File: ReadyToRunInfo.cpp // // // Runtime support for Ready to Run // =========================================================================== #include "common.h" #include "dbginterface.h" #include "compile.h" using namespace NativeFormat; IMAGE_DATA_DIRECTORY * ReadyToRunInfo::FindSection(DWORD type) { CONTRACTL { GC_NOTRIGGER; NOTHROW; SO_TOLERANT; SUPPORTS_DAC; } CONTRACTL_END; PTR_READYTORUN_SECTION pSections = dac_cast<PTR_READYTORUN_SECTION>(dac_cast<TADDR>(m_pHeader) + sizeof(READYTORUN_HEADER)); for (DWORD i = 0; i < m_pHeader->NumberOfSections; i++) { // Verify that section types are sorted _ASSERTE(i == 0 || (pSections[i-1].Type < pSections[i].Type)); READYTORUN_SECTION * pSection = pSections + i; if (pSection->Type == type) return &pSection->Section; } return NULL; } MethodDesc * ReadyToRunInfo::GetMethodDescForEntryPoint(PCODE entryPoint) { CONTRACTL { GC_NOTRIGGER; NOTHROW; SO_TOLERANT; SUPPORTS_DAC; } CONTRACTL_END; #ifdef _TARGET_AMD64_ // A normal method entry point is always 8 byte aligned, but a funclet can start at an odd address. // Since PtrHashMap can't handle odd pointers, check for this case and return NULL. if ((entryPoint & 0x1) != 0) return NULL; #endif TADDR val = (TADDR)m_entryPointToMethodDescMap.LookupValue(PCODEToPINSTR(entryPoint), (LPVOID)PCODEToPINSTR(entryPoint)); if (val == (TADDR)INVALIDENTRY) return NULL; return dac_cast<PTR_MethodDesc>(val); } PTR_BYTE ReadyToRunInfo::GetDebugInfo(PTR_RUNTIME_FUNCTION pRuntimeFunction) { CONTRACTL { GC_NOTRIGGER; THROWS; MODE_ANY; SUPPORTS_DAC; } CONTRACTL_END; IMAGE_DATA_DIRECTORY * pDebugInfoDir = FindSection(READYTORUN_SECTION_DEBUG_INFO); if (pDebugInfoDir == NULL) return NULL; SIZE_T methodIndex = pRuntimeFunction - m_pRuntimeFunctions; _ASSERTE(methodIndex < m_nRuntimeFunctions); NativeArray debugInfoIndex(&m_nativeReader, pDebugInfoDir->VirtualAddress); uint offset; if (!debugInfoIndex.TryGetAt((DWORD)methodIndex, &offset)) return NULL; uint lookBack; uint debugInfoOffset = m_nativeReader.DecodeUnsigned(offset, &lookBack); if (lookBack != 0) debugInfoOffset = offset - lookBack; return dac_cast<PTR_BYTE>(m_pLayout->GetBase()) + debugInfoOffset; } #ifndef DACCESS_COMPILE BOOL ReadyToRunInfo::IsReadyToRunEnabled() { STANDARD_VM_CONTRACT; static ConfigDWORD configReadyToRun; return configReadyToRun.val(CLRConfig::EXTERNAL_ReadyToRun); } PTR_ReadyToRunInfo ReadyToRunInfo::Initialize(Module * pModule, AllocMemTracker *pamTracker) { STANDARD_VM_CONTRACT; PEFile * pFile = pModule->GetFile(); // Ignore ReadyToRun for introspection-only loads if (pFile->IsIntrospectionOnly()) return NULL; if (!pFile->HasLoadedIL()) return NULL; PEImageLayout * pLayout = pFile->GetLoadedIL(); if (!pLayout->HasReadyToRunHeader()) return NULL; if (!IsReadyToRunEnabled()) return NULL; if (!pLayout->IsNativeMachineFormat()) { #ifdef FEATURE_CORECLR // For CoreCLR, be strict about disallowing machine mismatches. COMPlusThrowHR(COR_E_BADIMAGEFORMAT); #else return NULL; #endif } #ifdef FEATURE_NATIVE_IMAGE_GENERATION // Ignore ReadyToRun during NGen if (IsCompilationProcess() && !IsNgenPDBCompilationProcess()) return NULL; #endif #ifndef CROSSGEN_COMPILE // The file must have been loaded using LoadLibrary if (!pLayout->IsRelocated()) return NULL; #endif READYTORUN_HEADER * pHeader = pLayout->GetReadyToRunHeader(); // Ignore the content if the image major version is higher than the major version currently supported by the runtime if (pHeader->MajorVersion > READYTORUN_MAJOR_VERSION) return NULL; LoaderHeap *pHeap = pModule->GetLoaderAllocator()->GetHighFrequencyHeap(); void * pMemory = pamTracker->Track(pHeap->AllocMem((S_SIZE_T)sizeof(ReadyToRunInfo))); return new (pMemory) ReadyToRunInfo(pModule, pLayout, pHeader); } ReadyToRunInfo::ReadyToRunInfo(Module * pModule, PEImageLayout * pLayout, READYTORUN_HEADER * pHeader) : m_pModule(pModule), m_pLayout(pLayout), m_pHeader(pHeader), m_Crst(CrstLeafLock) { STANDARD_VM_CONTRACT; IMAGE_DATA_DIRECTORY * pRuntimeFunctionsDir = FindSection(READYTORUN_SECTION_RUNTIME_FUNCTIONS); if (pRuntimeFunctionsDir != NULL) { m_pRuntimeFunctions = (RUNTIME_FUNCTION *)pLayout->GetDirectoryData(pRuntimeFunctionsDir); m_nRuntimeFunctions = pRuntimeFunctionsDir->Size / sizeof(RUNTIME_FUNCTION); } else { m_nRuntimeFunctions = 0; } IMAGE_DATA_DIRECTORY * pImportSectionsDir = FindSection(READYTORUN_SECTION_IMPORT_SECTIONS); if (pImportSectionsDir != NULL) { m_pImportSections = (CORCOMPILE_IMPORT_SECTION*)pLayout->GetDirectoryData(pImportSectionsDir); m_nImportSections = pImportSectionsDir->Size / sizeof(CORCOMPILE_IMPORT_SECTION); } else { m_nImportSections = 0; } m_nativeReader = NativeReader((byte *)pLayout->GetBase(), pLayout->GetVirtualSize()); IMAGE_DATA_DIRECTORY * pEntryPointsDir = FindSection(READYTORUN_SECTION_METHODDEF_ENTRYPOINTS); if (pEntryPointsDir != NULL) { m_methodDefEntryPoints = NativeArray(&m_nativeReader, pEntryPointsDir->VirtualAddress); } { LockOwner lock = {&m_Crst, IsOwnerOfCrst}; m_entryPointToMethodDescMap.Init(TRUE, &lock); } } PCODE ReadyToRunInfo::GetEntryPoint(MethodDesc * pMD, BOOL fFixups /*=TRUE*/) { STANDARD_VM_CONTRACT; // READYTORUN: FUTURE: Support for generics if (pMD->HasClassOrMethodInstantiation()) return NULL; mdToken token = pMD->GetMemberDef(); int rid = RidFromToken(token); if (rid == 0) return NULL; uint offset; if (!m_methodDefEntryPoints.TryGetAt(rid - 1, &offset)) return NULL; uint id; offset = m_nativeReader.DecodeUnsigned(offset, &id); if (id & 1) { if (id & 2) { uint val; m_nativeReader.DecodeUnsigned(offset, &val); offset -= val; } if (fFixups) { if (!m_pModule->FixupDelayList(dac_cast<TADDR>(m_pLayout->GetBase()) + offset)) return NULL; } id >>= 2; } else { id >>= 1; } _ASSERTE(id < m_nRuntimeFunctions); PCODE pEntryPoint = dac_cast<TADDR>(m_pLayout->GetBase()) + m_pRuntimeFunctions[id].BeginAddress; { CrstHolder ch(&m_Crst); if (m_entryPointToMethodDescMap.LookupValue(PCODEToPINSTR(pEntryPoint), (LPVOID)PCODEToPINSTR(pEntryPoint)) == (LPVOID)INVALIDENTRY) m_entryPointToMethodDescMap.InsertValue(PCODEToPINSTR(pEntryPoint), pMD); } if (g_pDebugInterface != NULL) { g_pDebugInterface->JITComplete(pMD, pEntryPoint); } return pEntryPoint; } BOOL ReadyToRunInfo::MethodIterator::Next() { STANDARD_VM_CONTRACT; while (++m_methodDefIndex < (int)m_pInfo->m_methodDefEntryPoints.GetCount()) { uint offset; if (m_pInfo->m_methodDefEntryPoints.TryGetAt(m_methodDefIndex, &offset)) return TRUE; } return FALSE; } MethodDesc * ReadyToRunInfo::MethodIterator::GetMethodDesc() { STANDARD_VM_CONTRACT; return MemberLoader::GetMethodDescFromMethodDef(m_pInfo->m_pModule, mdtMethodDef | (m_methodDefIndex + 1), FALSE); } PCODE ReadyToRunInfo::MethodIterator::GetMethodStartAddress() { STANDARD_VM_CONTRACT; PCODE ret = m_pInfo->GetEntryPoint(GetMethodDesc(), FALSE); _ASSERTE(ret != NULL); return ret; } DWORD ReadyToRunInfo::GetFieldBaseOffset(MethodTable * pMT) { STANDARD_VM_CONTRACT; DWORD dwAlignment = DATA_ALIGNMENT; DWORD dwOffsetBias = 0; #ifdef FEATURE_64BIT_ALIGNMENT dwOffsetBias = 4; if (pMT->RequiresAlign8()) dwAlignment = 8; #endif MethodTable * pParentMT = pMT->GetParentMethodTable(); DWORD dwCumulativeInstanceFieldPos = (pParentMT != NULL) ? pParentMT->GetNumInstanceFieldBytes() : 0; dwCumulativeInstanceFieldPos += dwOffsetBias; dwCumulativeInstanceFieldPos = (DWORD)ALIGN_UP(dwCumulativeInstanceFieldPos, dwAlignment); return (DWORD)sizeof(Object) + dwCumulativeInstanceFieldPos - dwOffsetBias; } #endif // DACCESS_COMPILE
27.77673
140
0.676893
CyberSys
df67439f69e0ad36bce2d6fcd74b8dc868f80f71
304
cpp
C++
src/debug20/backtrace.cpp
Tomcus/debug20
4124f83359b49c8b340f957bce1e0b83bffd443e
[ "MIT" ]
null
null
null
src/debug20/backtrace.cpp
Tomcus/debug20
4124f83359b49c8b340f957bce1e0b83bffd443e
[ "MIT" ]
null
null
null
src/debug20/backtrace.cpp
Tomcus/debug20
4124f83359b49c8b340f957bce1e0b83bffd443e
[ "MIT" ]
null
null
null
#include "backtrace.hpp" #include <fmt/os.h> void d20::print_backtrace() noexcept { backtrace_data data; try { data = get_backtrace(); for (auto trace:data) { fmt::print("{}\n", trace); } } catch (const exception& e) { puts(e.what()); } }
20.266667
38
0.523026
Tomcus
df6f519bdaae3b19dd7843d83822c94c2e3394d9
3,872
cpp
C++
Munch/assem.cpp
Compiladori/Tiger-Compiler
d52f92459dac0fa00534162a808376875883446d
[ "MIT" ]
1
2020-12-31T16:05:42.000Z
2020-12-31T16:05:42.000Z
Munch/assem.cpp
Compiladori/Tiger-Compiler
d52f92459dac0fa00534162a808376875883446d
[ "MIT" ]
1
2021-01-27T15:41:18.000Z
2021-05-31T21:47:02.000Z
Munch/assem.cpp
Compiladori/Tiger-Compiler
d52f92459dac0fa00534162a808376875883446d
[ "MIT" ]
null
null
null
#include "assem.h" using namespace assem; /** * Instructions * **/ void Oper::output(std::ostream& os, temp::TempMap temp_map) const { std::string result; for ( auto it = assm.cbegin(); it != assm.cend(); ++it ) { if ( *it == '\'' ) { switch ( *(++it) ) { case 's': { int n = std::atoi(&*(++it)); if ( n >= src.size() ) { std::cout << "ERROR : tried to access element " << n << " of " << src.size() << "-sized src vector. Instruction = "; this->print(); std::cout << std::endl; } else if ( not temp_map.count(src[n]) ) { std::cout << "ERROR : temp_map has no element src[n] = src[" << n << "] = " << src[n].num << std::endl; } std::string s = temp_map.at(src[n]).name; result.append(s); } break; case 'd': { int n = std::atoi(&*(++it)); if ( n >= dst.size() ) { std::cout << "ERROR : tried to access element " << n << " of " << dst.size() << "-sized dst vector. Instruction = "; this->print(); std::cout << std::endl; } else if ( not temp_map.count(dst[n]) ) { std::cout << "ERROR : temp_map has no element dst[n] = dst[" << n << "] = " << dst[n].num << std::endl; } std::string s = temp_map.at(dst[n]).name; result.append(s); } break; case 'j': { int n = std::atoi(&*(++it)); if ( n >= jumps.size() ) { std::cout << "ERROR : tried to access element " << n << " of " << jumps.size() << "-sized jumps vector. Instruction = "; this->print(); std::cout << std::endl; } std::string s = jumps[n].name; result.append(s); } break; case '\'': { result.append(1, *it); } break; } } else { result.append(1, *it); } } os << " " << result << "\n"; } void Label::output(std::ostream& os, temp::TempMap temp_map) const { os << assm << "\n"; } void Move::output(std::ostream& os, temp::TempMap temp_map) const { std::string result; if ( temp_map.at(src[0]).name == temp_map.at(dst[0]).name ) { return; } for ( auto it = assm.cbegin(); it != assm.cend(); ++it ) { if ( *it == '\'' ) { switch ( *(++it) ) { case 's': { int n = std::atoi(&*(++it)); std::string s = temp_map.at(src[n]).name; result.append(s); } break; case 'd': { int n = std::atoi(&*(++it)); std::string s = temp_map.at(dst[n]).name; result.append(s); } break; case '\'': { result.append(1, *it); } break; } } else { result.append(1, *it); } } os << " " << result << "\n"; } void Oper::print() const { std::cout << "Oper( " + assm + " ) ( "; temp::print_templist(src); std::cout << " ) ( "; temp::print_templist(dst); std::cout << " ) ( "; temp::print_labellist(jumps); std::cout << " )"; } void Label::print() const { std::cout << "Label( " + label.name + " )"; } void Move::print() const { std::cout << "Move( " + assm + " ) ( "; temp::print_templist(src); temp::print_templist(dst); std::cout << " )"; }
36.528302
144
0.383781
Compiladori
df73c1eebe1b09c510eb28608abf20db66330d4c
8,710
cpp
C++
Source/Engine/World/Private/Components/Drawable.cpp
CodeLikeCXK/AngieEngine
26f3cfdb1fdef6378ee75b000b8fe966bebb3a6e
[ "MIT" ]
24
2019-07-15T22:48:44.000Z
2021-11-02T04:42:48.000Z
Source/Engine/World/Private/Components/Drawable.cpp
CodeLikeCXK/AngieEngine
26f3cfdb1fdef6378ee75b000b8fe966bebb3a6e
[ "MIT" ]
1
2021-11-02T09:41:31.000Z
2021-11-05T18:35:14.000Z
Source/Engine/World/Private/Components/Drawable.cpp
CodeLikeCXK/AngieEngine
26f3cfdb1fdef6378ee75b000b8fe966bebb3a6e
[ "MIT" ]
3
2020-02-03T08:34:50.000Z
2021-07-28T05:19:22.000Z
/* Angie Engine Source Code MIT License Copyright (C) 2017-2021 Alexander Samusev. This file is part of the Angie Engine Source Code. 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 <World/Public/Components/Drawable.h> #include <World/Public/World.h> #include <Core/Public/IntrusiveLinkedListMacro.h> AN_CLASS_META( ADrawable ) static void EvaluateRaycastResult( SPrimitiveDef * Self, ALevel const * LightingLevel, SMeshVertex const * pVertices, SMeshVertexUV const * pLightmapVerts, int LightmapBlock, unsigned int const * pIndices, Float3 const & HitLocation, Float2 const & HitUV, Float3 * Vertices, Float2 & TexCoord, Float3 & LightmapSample ) { ASceneComponent * primitiveOwner = Self->Owner; Float3x4 const & transform = primitiveOwner->GetWorldTransformMatrix(); Float3 const & v0 = pVertices[pIndices[0]].Position; Float3 const & v1 = pVertices[pIndices[1]].Position; Float3 const & v2 = pVertices[pIndices[2]].Position; // transform triangle vertices to worldspace Vertices[0] = transform * v0; Vertices[1] = transform * v1; Vertices[2] = transform * v2; const float hitW = 1.0f - HitUV[0] - HitUV[1]; Float2 uv0 = pVertices[pIndices[0]].GetTexCoord(); Float2 uv1 = pVertices[pIndices[1]].GetTexCoord(); Float2 uv2 = pVertices[pIndices[2]].GetTexCoord(); TexCoord = uv0 * hitW + uv1 * HitUV[0] + uv2 * HitUV[1]; if ( pLightmapVerts && LightingLevel && LightmapBlock >= 0 ) { Float2 const & lm0 = pLightmapVerts[pIndices[0]].TexCoord; Float2 const & lm1 = pLightmapVerts[pIndices[1]].TexCoord; Float2 const & lm2 = pLightmapVerts[pIndices[2]].TexCoord; Float2 lighmapTexcoord = lm0 * hitW + lm1 * HitUV[0] + lm2 * HitUV[1]; LightmapSample = LightingLevel->SampleLight( LightmapBlock, lighmapTexcoord ); } else { LightmapSample = Float3(0.0f); } } ADrawable::ADrawable() { Bounds.Clear(); WorldBounds.Clear(); OverrideBoundingBox.Clear(); Core::ZeroMem( &Primitive, sizeof( Primitive ) ); Primitive.Owner = this; Primitive.Type = VSD_PRIMITIVE_BOX; Primitive.VisGroup = VISIBILITY_GROUP_DEFAULT; Primitive.QueryGroup = VSD_QUERY_MASK_VISIBLE | VSD_QUERY_MASK_VISIBLE_IN_LIGHT_PASS | VSD_QUERY_MASK_SHADOW_CAST; Primitive.EvaluateRaycastResult = EvaluateRaycastResult; bOverrideBounds = false; bSkinnedMesh = false; bCastShadow = true; bAllowRaycast = false; } void ADrawable::SetVisibilityGroup( int InVisibilityGroup ) { Primitive.VisGroup = InVisibilityGroup; } int ADrawable::GetVisibilityGroup() const { return Primitive.VisGroup; } void ADrawable::SetVisible( bool _Visible ) { if ( _Visible ) { Primitive.QueryGroup |= VSD_QUERY_MASK_VISIBLE; Primitive.QueryGroup &= ~VSD_QUERY_MASK_INVISIBLE; } else { Primitive.QueryGroup &= ~VSD_QUERY_MASK_VISIBLE; Primitive.QueryGroup |= VSD_QUERY_MASK_INVISIBLE; } } bool ADrawable::IsVisible() const { return !!( Primitive.QueryGroup & VSD_QUERY_MASK_VISIBLE ); } void ADrawable::SetHiddenInLightPass( bool _HiddenInLightPass ) { if ( _HiddenInLightPass ) { Primitive.QueryGroup &= ~VSD_QUERY_MASK_VISIBLE_IN_LIGHT_PASS; Primitive.QueryGroup |= VSD_QUERY_MASK_INVISIBLE_IN_LIGHT_PASS; } else { Primitive.QueryGroup |= VSD_QUERY_MASK_VISIBLE_IN_LIGHT_PASS; Primitive.QueryGroup &= ~VSD_QUERY_MASK_INVISIBLE_IN_LIGHT_PASS; } } bool ADrawable::IsHiddenInLightPass() const { return !(Primitive.QueryGroup & VSD_QUERY_MASK_VISIBLE_IN_LIGHT_PASS); } void ADrawable::SetQueryGroup( int _UserQueryGroup ) { Primitive.QueryGroup |= _UserQueryGroup & 0xffff0000; } void ADrawable::SetSurfaceFlags( uint8_t Flags ) { Primitive.Flags = Flags; } uint8_t ADrawable::GetSurfaceFlags() const { return Primitive.Flags; } void ADrawable::SetFacePlane( PlaneF const & _Plane ) { Primitive.Face = _Plane; } PlaneF const & ADrawable::GetFacePlane() const { return Primitive.Face; } void ADrawable::ForceOverrideBounds( bool _OverrideBounds ) { if ( bOverrideBounds == _OverrideBounds ) { return; } bOverrideBounds = _OverrideBounds; UpdateWorldBounds(); } void ADrawable::SetBoundsOverride( BvAxisAlignedBox const & _Bounds ) { OverrideBoundingBox = _Bounds; if ( bOverrideBounds ) { UpdateWorldBounds(); } } BvAxisAlignedBox const & ADrawable::GetBounds() const { return bOverrideBounds ? OverrideBoundingBox : Bounds; } BvAxisAlignedBox const & ADrawable::GetWorldBounds() const { return WorldBounds; } void ADrawable::OnTransformDirty() { Super::OnTransformDirty(); UpdateWorldBounds(); } void ADrawable::InitializeComponent() { Super::InitializeComponent(); GetLevel()->AddPrimitive( &Primitive ); UpdateWorldBounds(); if ( bCastShadow ) { GetWorld()->GetRender().AddShadowCaster( this ); } } void ADrawable::DeinitializeComponent() { Super::DeinitializeComponent(); GetLevel()->RemovePrimitive( &Primitive ); if ( bCastShadow ) { GetWorld()->GetRender().RemoveShadowCaster( this ); } } void ADrawable::SetCastShadow( bool _CastShadow ) { if ( bCastShadow == _CastShadow ) { return; } bCastShadow = _CastShadow; if ( bCastShadow ) { Primitive.QueryGroup |= VSD_QUERY_MASK_SHADOW_CAST; Primitive.QueryGroup &= ~VSD_QUERY_MASK_NO_SHADOW_CAST; } else { Primitive.QueryGroup &= ~VSD_QUERY_MASK_SHADOW_CAST; Primitive.QueryGroup |= VSD_QUERY_MASK_NO_SHADOW_CAST; } if ( IsInitialized() ) { ARenderWorld & RenderWorld = GetWorld()->GetRender(); if ( bCastShadow ) { RenderWorld.AddShadowCaster( this ); } else { RenderWorld.RemoveShadowCaster( this ); } } } void ADrawable::UpdateWorldBounds() { BvAxisAlignedBox const & boundingBox = GetBounds(); WorldBounds = boundingBox.Transform( GetWorldTransformMatrix() ); Primitive.Box = WorldBounds; if ( IsInitialized() ) { GetLevel()->MarkPrimitive( &Primitive ); } } void ADrawable::ForceOutdoor( bool _OutdoorSurface ) { if ( Primitive.bIsOutdoor == _OutdoorSurface ) { return; } Primitive.bIsOutdoor = _OutdoorSurface; if ( IsInitialized() ) { GetLevel()->MarkPrimitive( &Primitive ); } } bool ADrawable::IsOutdoor() const { return Primitive.bIsOutdoor; } void ADrawable::PreRenderUpdate( SRenderFrontendDef const * _Def ) { if ( VisFrame != _Def->FrameNumber ) { VisFrame = _Def->FrameNumber; OnPreRenderUpdate( _Def ); } } bool ADrawable::Raycast( Float3 const & InRayStart, Float3 const & InRayEnd, TPodVector< STriangleHitResult > & Hits ) const { if ( !Primitive.RaycastCallback ) { return false; } Hits.Clear(); return Primitive.RaycastCallback( &Primitive, InRayStart, InRayEnd, Hits ); } bool ADrawable::RaycastClosest( Float3 const & InRayStart, Float3 const & InRayEnd, STriangleHitResult & Hit ) const { if ( !Primitive.RaycastClosestCallback ) { return false; } SMeshVertex const * pVertices; return Primitive.RaycastClosestCallback( &Primitive, InRayStart, InRayEnd, Hit, &pVertices ); }
28.936877
126
0.673479
CodeLikeCXK
df76745843887c5fce7997ba21567a428c020ec3
164
cpp
C++
ext/n7zip/guid.cpp
yagisumi/node-n7zip_native
7e9b5e1ca1e2e0889fee637908f4c70238584bac
[ "MIT" ]
null
null
null
ext/n7zip/guid.cpp
yagisumi/node-n7zip_native
7e9b5e1ca1e2e0889fee637908f4c70238584bac
[ "MIT" ]
1
2020-10-16T17:26:54.000Z
2020-10-16T17:26:54.000Z
ext/n7zip/guid.cpp
yagisumi/node-n7zip_native
7e9b5e1ca1e2e0889fee637908f4c70238584bac
[ "MIT" ]
null
null
null
// #include <Common/MyInitGuid.h> #define INITGUID // #include <7zip/Archive/IArchive.h> // #include <7zip/IStream.h> // #include <7zip/ICoder.h> #include "guid.h"
23.428571
37
0.695122
yagisumi
df7ad6c85627a82ea0a3eaa9fc6138adc3df9da1
7,506
cpp
C++
Source/Game/Collision/CollisionSystem.cpp
gunstarpl/Game-Engine-12-2013
bfc53f5c998311c17e97c1b4d65792d615c51d36
[ "MIT", "Unlicense" ]
6
2017-12-31T17:28:40.000Z
2021-12-04T06:11:34.000Z
Source/Game/Collision/CollisionSystem.cpp
gunstarpl/Game-Engine-12-2013
bfc53f5c998311c17e97c1b4d65792d615c51d36
[ "MIT", "Unlicense" ]
null
null
null
Source/Game/Collision/CollisionSystem.cpp
gunstarpl/Game-Engine-12-2013
bfc53f5c998311c17e97c1b4d65792d615c51d36
[ "MIT", "Unlicense" ]
null
null
null
#include "Precompiled.hpp" #include "CollisionSystem.hpp" #include "CollisionComponent.hpp" #include "Common/Services.hpp" #include "Game/Event/EventDefinitions.hpp" #include "Game/Event/EventSystem.hpp" #include "Game/Entity/EntitySystem.hpp" #include "Game/Component/ComponentSystem.hpp" #include "Game/Transform/TransformComponent.hpp" namespace { void TransformBoundingBox(glm::vec4* boundingBox, const TransformComponent* transform) { assert(boundingBox != nullptr); // Translate by position. boundingBox->x += transform->GetPosition().x; boundingBox->y += transform->GetPosition().y; boundingBox->z += transform->GetPosition().x; boundingBox->w += transform->GetPosition().y; // Todo: Handle rotation and scale. } bool IntersectBoundingBox(const glm::vec4& a, const glm::vec4& b) { // Check if bounding boxes collide. return !(a.x > b.z || a.z < b.x || a.y > b.w || a.w < b.y); } } const float CollisionSystem::Permanent = -1.0f; CollisionSystem::CollisionSystem() : m_initialized(false), m_eventSystem(nullptr), m_entitySystem(nullptr), m_componentSystem(nullptr) { } CollisionSystem::~CollisionSystem() { Cleanup(); } void CollisionSystem::Cleanup() { m_initialized = false; m_eventSystem = nullptr; m_entitySystem = nullptr; m_componentSystem = nullptr; ClearContainer(m_objects); ClearContainer(m_disabled); } bool CollisionSystem::Initialize(const Services& services) { Cleanup(); // Setup scope guard. SCOPE_GUARD_IF(!m_initialized, Cleanup()); // Get required services. m_eventSystem = services.Get<EventSystem>(); if(m_eventSystem == nullptr) return false; m_entitySystem = services.Get<EntitySystem>(); if(m_entitySystem == nullptr) return false; m_componentSystem = services.Get<ComponentSystem>(); if(m_componentSystem == nullptr) return false; // Declare required components. m_componentSystem->Declare<TransformComponent>(); m_componentSystem->Declare<CollisionComponent>(); // Success! return m_initialized = true; } void CollisionSystem::Update(float timeDelta) { assert(m_initialized); // Update timers of disabled collision response pairs. for(auto it = m_disabled.begin(); it != m_disabled.end();) { const EntityHandle& sourceEntity = it->first.first; const EntityHandle& targetEntity = it->first.second; float& time = it->second; // Check if entities are still valid. bool sourceEntityValid = m_entitySystem->IsHandleValid(sourceEntity); bool targetEntityValid = m_entitySystem->IsHandleValid(targetEntity); if(!sourceEntityValid || !targetEntityValid) { m_disabled.erase(it++); continue; } // Skip if it has been disabled permanently. if(time < 0.0f) continue; // Update the timer. time = std::max(0.0f, time - timeDelta); // Erase the element if outdated. if(time == 0.0f) { m_disabled.erase(it++); continue; } // Iterate normally if current element hasn't been removed. ++it; } // Create a list of collision objects. auto componentsBegin = m_componentSystem->Begin<CollisionComponent>(); auto componentsEnd = m_componentSystem->End<CollisionComponent>(); for(auto it = componentsBegin; it != componentsEnd; ++it) { // Check if entity is active. if(!m_entitySystem->IsHandleValid(it->first)) continue; // Get the collision component. CollisionComponent* collision = &it->second; if(!collision->IsEnabled()) continue; // Get the transform component. TransformComponent* transform = m_componentSystem->Lookup<TransformComponent>(it->first); if(transform == nullptr) continue; // Transform the bounding box to world space. glm::vec4 boundingBox = collision->GetBoundingBox(); TransformBoundingBox(&boundingBox, transform); // Add a collision object. CollisionObject object; object.entity = it->first; object.transform = transform; object.collision = collision; object.worldAABB = boundingBox; object.enabled = true; m_objects.push_back(object); } // Process collision objects. for(auto it = m_objects.begin(); it != m_objects.end(); ++it) { // Check if collision object is still enabled. if(!it->enabled) continue; // Check if it collides with other objects. for(auto other = m_objects.begin(); other != m_objects.end(); ++other) { // Don't check against itself. if(other == it) continue; // Check if collision response with other entity has been disabled. // This shouldn't be here before actuall collision calculation, but // we only do a collision response (no physical interaction) so it's // totally fine for now (we skip the expensive calculation). EntityPair pair = { it->entity, other->entity }; if(m_disabled.count(pair) == 1) continue; // Check if collision object is still enabled. if(!other->enabled) continue; // Check if an object can collide with it. if(it->collision->GetMask() & other->collision->GetType()) { // Check if objects physically and logically collide. bool intersects = IntersectBoundingBox(it->worldAABB, other->worldAABB); bool reversed = (it->collision->GetFlags() & CollisionFlags::Reversed) != 0; if(intersects != reversed) { // Dispatch an entity collision event. { GameEvent::EntityCollision event(*it, *other); m_eventSystem->Dispatch(event); } // Check if other collision object is still valid. if(!m_entitySystem->IsHandleValid(other->entity) || !other->collision->IsEnabled()) { other->enabled = false; } // Check if this collision object is still valid. if(!m_entitySystem->IsHandleValid(it->entity) || !it->collision->IsEnabled()) { it->enabled = false; // No point in checking further collisions against this objects. break; } } } } } // Clear intermediate collision object list. m_objects.clear(); } void CollisionSystem::DisableCollisionResponse(EntityHandle sourceEntity, EntityHandle targetEntity, float duration) { assert(m_initialized); // Check if this pair is already disabled. EntityPair pair = { sourceEntity, targetEntity }; auto it = m_disabled.find(pair); if(it != m_disabled.end()) { // Update the duration. float& time = it->second; if(time < duration) { time = duration; } } else { // Insert a new pair. m_disabled.emplace(std::make_pair(pair, duration)); } }
29.785714
116
0.59619
gunstarpl
df7bc70853f767f049300ed1050261a60ee47670
2,111
cxx
C++
Libraries/VtkVgQtUtil/vtkVgQtUtil.cxx
judajake/vivia
ac0bad0dc200b5af25911513edb0ca6fd6e9f622
[ "BSD-3-Clause" ]
1
2017-07-31T07:08:05.000Z
2017-07-31T07:08:05.000Z
Libraries/VtkVgQtUtil/vtkVgQtUtil.cxx
judajake/vivia
ac0bad0dc200b5af25911513edb0ca6fd6e9f622
[ "BSD-3-Clause" ]
null
null
null
Libraries/VtkVgQtUtil/vtkVgQtUtil.cxx
judajake/vivia
ac0bad0dc200b5af25911513edb0ca6fd6e9f622
[ "BSD-3-Clause" ]
null
null
null
/*ckwg +5 * Copyright 2013 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "vtkVgQtUtil.h" #include <QApplication> #include <QThreadStorage> #include <vtkEventQtSlotConnect.h> #include <vtkVgInstance.h> namespace // anonymous { //----------------------------------------------------------------------------- class vtkVgQtConnectionManager : public QObject { public: vtkVgQtConnectionManager() {} virtual ~vtkVgQtConnectionManager() {} vtkEventQtSlotConnect* manager(); protected: typedef vtkVgInstance<vtkEventQtSlotConnect> Manager; QThreadStorage<Manager*> tls; }; Q_GLOBAL_STATIC(vtkVgQtConnectionManager, globalConnectionManager) //----------------------------------------------------------------------------- vtkEventQtSlotConnect* vtkVgQtConnectionManager::manager() { if (!this->tls.hasLocalData()) { this->tls.setLocalData(new Manager); } return *this->tls.localData(); } } // namespace <anonymous> //----------------------------------------------------------------------------- void vtkConnect( vtkObject* sender, unsigned long event, QObject* receiver, const char* slot, Qt::ConnectionType type) { vtkConnect(sender, event, receiver, slot, 0, 0.0f, type); } //----------------------------------------------------------------------------- void vtkConnect( vtkObject* sender, unsigned long event, QObject* receiver, const char* slot, void* data, float priority, Qt::ConnectionType type) { vtkEventQtSlotConnect* m = globalConnectionManager()->manager(); m->Connect(sender, static_cast<vtkCommand::EventIds>(event), receiver, slot, data, priority, type); } //----------------------------------------------------------------------------- void vtkDisconnect( vtkObject* sender, unsigned long event, QObject* receiver, const char* slot, void* data) { vtkEventQtSlotConnect* m = globalConnectionManager()->manager(); m->Disconnect(sender, event, receiver, slot, data); }
28.527027
79
0.598768
judajake
df7e1b2858fb1bfce3a62f7d0bd935063a13508d
56,752
cpp
C++
test/pangraph_test.cpp
rmcolq/pandora
93c541017a5c1ea45f999f5eabdb58be061711e0
[ "MIT" ]
77
2018-07-06T00:13:58.000Z
2021-11-19T03:58:20.000Z
test/pangraph_test.cpp
rmcolq/pandora
93c541017a5c1ea45f999f5eabdb58be061711e0
[ "MIT" ]
215
2018-07-09T16:41:55.000Z
2022-03-29T22:44:36.000Z
test/pangraph_test.cpp
mbhall88/pandora
16de553795267a55af223748b24510a904ca5ef9
[ "MIT" ]
16
2018-07-06T13:09:48.000Z
2022-01-05T15:01:09.000Z
#include "gtest/gtest.h" #include "test_macro.cpp" #include "pangenome/ns.cpp" #include "pangenome_graph_class.h" #include "pangenome/pannode.h" #include "pangenome/panread.h" #include "pangenome/pansample.h" #include "minihit.h" #include "localPRG.h" #include <cstdint> #include <iostream> #include "test_helpers.h" using namespace pangenome; const std::string TEST_CASE_DIR = "../../test/test_cases/"; TEST(PangenomeGraphConstructor, constructors_and_get_sample) { { // testing default constructor PGraphTester pg; std::vector<std::string> expectedSamples = { "sample_1" }; EXPECT_EQ(pg.samples.size(), 1); pg.get_sample("sample_1")->name == "sample_1"; EXPECT_EQ(pg.next_id, 0); EXPECT_EQ(pg.reads.size(), 0); EXPECT_EQ(pg.nodes.size(), 0); } { // testing 1-argument constructor PGraphTester pg({ "test_sample" }); std::vector<std::string> expectedSamples = { "test_sample" }; EXPECT_EQ(pg.samples.size(), 1); pg.get_sample("test_sample")->name == "test_sample"; EXPECT_EQ(pg.next_id, 0); EXPECT_EQ(pg.reads.size(), 0); EXPECT_EQ(pg.nodes.size(), 0); } { // testing 3-argument constructor std::vector<std::string> expectedSamples = { "test1", "test2", "test3" }; PGraphTester pg(expectedSamples); EXPECT_EQ(pg.samples.size(), expectedSamples.size()); pg.get_sample("test1")->name == "test1"; pg.get_sample("test2")->name == "test2"; pg.get_sample("test3")->name == "test3"; EXPECT_EQ(pg.next_id, 0); EXPECT_EQ(pg.reads.size(), 0); EXPECT_EQ(pg.nodes.size(), 0); } } TEST(PangenomeGraphRead, add_read_and_get_read) { PGraphTester pg; uint32_t read_id = 2; // first trivial tests - read is not in the graph EXPECT_EQ(pg.reads.size(), (uint)0); try { pg.get_read(read_id); FAIL() << "pg.get_read(read_id) should throw std::out_of_range\n"; } catch (const std::out_of_range&) { } catch (...) { FAIL() << "pg.get_read(read_id) should throw std::out_of_range\n"; } // add read pg.add_read(read_id); // and test EXPECT_EQ(pg.reads.size(), (uint)1); EXPECT_EQ(pg.get_read(read_id)->id, read_id); // add read again pg.add_read(read_id); // this should not change anything // and test EXPECT_EQ(pg.reads.size(), (uint)1); EXPECT_EQ(pg.get_read(read_id)->id, read_id); // add a different read uint32_t read_id_2 = 10; pg.add_read(read_id_2); // and test EXPECT_EQ(pg.reads.size(), (uint)2); EXPECT_EQ(pg.get_read(read_id)->id, read_id); EXPECT_EQ(pg.reads.size(), (uint)2); EXPECT_EQ(pg.get_read(read_id_2)->id, read_id_2); } TEST(PangenomeGraphNode, add_node_and_get_node) { PGraphTester pg; uint32_t prg_id = 0; auto prg_pointer = std::make_shared<LocalPRG>(prg_id, "", ""); // trivial test - nodes are empty EXPECT_EQ(pg.nodes.size(), (uint)0); try { pg.get_node(prg_id); FAIL() << "pg.get_node() should throw std::out_of_range\n"; } catch (const std::out_of_range&) { } catch (...) { FAIL() << "pg.get_node() should throw std::out_of_range\n"; } try { pg.get_node(prg_pointer); FAIL() << "pg.get_node() should throw std::out_of_range\n"; } catch (const std::out_of_range&) { } catch (...) { FAIL() << "pg.get_node() should throw std::out_of_range\n"; } // add a node pg.add_node(prg_pointer); // test if the node was added EXPECT_EQ(pg.nodes.size(), (uint)1); EXPECT_EQ(pg.get_node(prg_id)->prg_id, prg_id); EXPECT_EQ(pg.get_node(prg_id)->node_id, prg_id); EXPECT_EQ(pg.get_node(prg_pointer)->prg_id, prg_id); EXPECT_EQ(pg.get_node(prg_pointer)->node_id, prg_id); // add the node again - nothing should change pg.add_node(prg_pointer); // test if the node was added EXPECT_EQ(pg.nodes.size(), (uint)1); EXPECT_EQ(pg.get_node(prg_id)->prg_id, prg_id); EXPECT_EQ(pg.get_node(prg_id)->node_id, prg_id); EXPECT_EQ(pg.get_node(prg_pointer)->prg_id, prg_id); EXPECT_EQ(pg.get_node(prg_pointer)->node_id, prg_id); // add a second node uint32_t prg_id_2 = 10; auto prg_pointer_2 = std::make_shared<LocalPRG>(prg_id_2, "", ""); pg.add_node(prg_pointer_2); // test if the node was added EXPECT_EQ(pg.nodes.size(), (uint)2); EXPECT_EQ(pg.get_node(prg_id)->prg_id, prg_id); EXPECT_EQ(pg.get_node(prg_id)->node_id, prg_id); EXPECT_EQ(pg.get_node(prg_pointer)->prg_id, prg_id); EXPECT_EQ(pg.get_node(prg_pointer)->node_id, prg_id); EXPECT_EQ(pg.get_node(prg_id_2)->prg_id, prg_id_2); EXPECT_EQ(pg.get_node(prg_id_2)->node_id, prg_id_2); EXPECT_EQ(pg.get_node(prg_pointer_2)->prg_id, prg_id_2); EXPECT_EQ(pg.get_node(prg_pointer_2)->node_id, prg_id_2); // add a third node, with a prg that was already added, but with a different node_id uint32_t other_node_id_for_prg_pointer = prg_id + 1; pg.add_node(prg_pointer, other_node_id_for_prg_pointer); // test if it was added EXPECT_EQ(pg.nodes.size(), (uint)3); EXPECT_EQ(pg.get_node(prg_id)->prg_id, prg_id); EXPECT_EQ(pg.get_node(prg_id)->node_id, prg_id); EXPECT_EQ(pg.get_node(prg_pointer)->prg_id, prg_id); EXPECT_EQ(pg.get_node(prg_pointer)->node_id, prg_id); EXPECT_EQ(pg.get_node(prg_id_2)->prg_id, prg_id_2); EXPECT_EQ(pg.get_node(prg_id_2)->node_id, prg_id_2); EXPECT_EQ(pg.get_node(prg_pointer_2)->prg_id, prg_id_2); EXPECT_EQ(pg.get_node(prg_pointer_2)->node_id, prg_id_2); EXPECT_EQ(pg.get_node(other_node_id_for_prg_pointer)->prg_id, prg_id); EXPECT_EQ(pg.get_node(other_node_id_for_prg_pointer)->node_id, other_node_id_for_prg_pointer); } // function that will make things easier by setting up MiniRecord, MinimizerHit, cluster // and prg void setup_minimizerhit_cluster_prg_function(uint32_t prg_id, uint32_t read_id, MiniRecord* mr1, MinimizerHitPtr* minimizer_hit, std::shared_ptr<std::set<MinimizerHitPtr, pComp>>* cluster_pointer, std::shared_ptr<LocalPRG>* prg_pointer) { std::deque<Interval> raw_path = { Interval(7, 8), Interval(10, 14) }; prg::Path path; path.initialize(raw_path); Interval interval(0, 5); Minimizer m1(0, interval.start, interval.get_end(), 0); // kmer, start, end, strand (*mr1) = MiniRecord(prg_id, path, prg_id, 0); (*minimizer_hit) = std::make_shared<MinimizerHit>(read_id, m1, *mr1); (*cluster_pointer) = std::make_shared<std::set<MinimizerHitPtr, pComp>>(); (*cluster_pointer)->insert(*minimizer_hit); (*prg_pointer) = std::make_shared<LocalPRG>(prg_id, "", ""); } TEST(PangenomeGraph_add_hits_between_PRG_and_read, AddClusters) { PGraphTester pg; // test 1: add a cluster uint32_t prg_id_1 = 1; uint32_t read_id_1 = 100; MiniRecord mr1; MinimizerHitPtr minimizer_hit_1; std::shared_ptr<std::set<MinimizerHitPtr, pComp>> cluster_pointer_1; std::shared_ptr<LocalPRG> prg_pointer_1; { setup_minimizerhit_cluster_prg_function(prg_id_1, read_id_1, &mr1, &minimizer_hit_1, &cluster_pointer_1, &prg_pointer_1); pg.add_hits_between_PRG_and_read(prg_pointer_1, read_id_1, *cluster_pointer_1); // test if everything is fine EXPECT_EQ(pg.nodes.size(), 1); // is the node really inserted? EXPECT_EQ( pg.get_node(prg_id_1)->node_id, prg_id_1); // is the node really inserted? EXPECT_EQ(pg.get_node(prg_id_1)->covg, 1); // is the coverage of the node 1? EXPECT_EQ(pg.get_node(prg_id_1)->reads.size(), 1); // is the read really inserted in the node? EXPECT_EQ(pg.get_node(prg_id_1)->reads.begin()->get()->id, read_id_1); // is the read really inserted in the node? EXPECT_EQ(pg.reads.size(), 1); EXPECT_EQ(pg.get_read(read_id_1)->id, read_id_1); // is the read really // inserted? EXPECT_EQ(pg.get_read(read_id_1)->get_hits_as_unordered_map().size(), 1); // is the hit really inserted? EXPECT_EQ(*pg.get_read(read_id_1)->get_hits_as_unordered_map()[prg_id_1][0], *minimizer_hit_1); // is the hit really inserted? EXPECT_EQ(pg.get_read(read_id_1) ->get_hits_as_unordered_map()[prg_id_1][0] ->get_kmer_node_id(), prg_id_1); // is the node really inserted in the read? EXPECT_EQ(pg.get_read(read_id_1)->node_orientations.size(), 1); // is the node_orientation was inserted in the read? EXPECT_EQ(pg.get_read(read_id_1)->node_orientations[0], true); // is the node_orientation was inserted in the read? } // test 2: add a cluster with the same read_id, but different prg_id uint32_t prg_id_2 = 2; MiniRecord mr2; MinimizerHitPtr minimizer_hit_2; std::shared_ptr<std::set<MinimizerHitPtr, pComp>> cluster_pointer_2; std::shared_ptr<LocalPRG> prg_pointer_2; { setup_minimizerhit_cluster_prg_function(prg_id_2, read_id_1, &mr2, &minimizer_hit_2, &cluster_pointer_2, &prg_pointer_2); pg.add_hits_between_PRG_and_read(prg_pointer_2, read_id_1, *cluster_pointer_2); // test if everything is fine EXPECT_EQ(pg.nodes.size(), 2); // is the node really inserted? EXPECT_EQ(pg.get_node(prg_id_1)->node_id, prg_id_1); EXPECT_EQ( pg.get_node(prg_id_2)->node_id, prg_id_2); // is the node really inserted? EXPECT_EQ(pg.get_node(prg_id_1)->covg, 1); // is the coverage of the node 1? EXPECT_EQ(pg.get_node(prg_id_2)->covg, 1); // is the coverage of the node 1? EXPECT_EQ(pg.get_node(prg_id_1)->reads.size(), 1); // is the read really inserted in the node? EXPECT_EQ(pg.get_node(prg_id_2)->reads.size(), 1); // is the read really inserted in the node? EXPECT_EQ(pg.get_node(prg_id_1)->reads.begin()->get()->id, read_id_1); // is the read really inserted in the node? EXPECT_EQ(pg.get_node(prg_id_2)->reads.begin()->get()->id, read_id_1); // is the read really inserted in the node? EXPECT_EQ(pg.reads.size(), 1); EXPECT_EQ(pg.get_read(read_id_1)->id, read_id_1); // is the read really // inserted? EXPECT_EQ(pg.get_read(read_id_1)->get_hits_as_unordered_map().size(), 2); // we should have another hit here EXPECT_EQ(*pg.get_read(read_id_1)->get_hits_as_unordered_map()[prg_id_1][0], *minimizer_hit_1); // is the hit really inserted? EXPECT_EQ(*pg.get_read(read_id_1)->get_hits_as_unordered_map()[prg_id_2][0], *minimizer_hit_2); // is the hit really inserted? EXPECT_EQ(pg.get_read(read_id_1)->node_orientations.size(), 2); // is the node_orientation was inserted in the read? EXPECT_EQ(pg.get_read(read_id_1)->node_orientations[0], true); // is the node_orientation was inserted in the read? EXPECT_EQ(pg.get_read(read_id_1)->node_orientations[1], true); // is the node_orientation was inserted in the read? } // test 3: add a cluster with the same prg_id, but different read_id uint32_t read_id_3 = 101; MiniRecord mr3; MinimizerHitPtr minimizer_hit_3; std::shared_ptr<std::set<MinimizerHitPtr, pComp>> cluster_pointer_3; std::shared_ptr<LocalPRG> prg_pointer_3; { setup_minimizerhit_cluster_prg_function(prg_id_1, read_id_3, &mr3, &minimizer_hit_3, &cluster_pointer_3, &prg_pointer_3); pg.add_hits_between_PRG_and_read(prg_pointer_3, read_id_3, *cluster_pointer_3); // test if everything is fine EXPECT_EQ(pg.nodes.size(), 2); // nothing should change from the previous test EXPECT_EQ(pg.get_node(prg_id_1)->node_id, prg_id_1); // nothing should change from the previous test EXPECT_EQ(pg.get_node(prg_id_2)->node_id, prg_id_2); // nothing should change from the previous test EXPECT_EQ(pg.get_node(prg_id_1)->covg, 2); // coverage should change to 2 EXPECT_EQ(pg.get_node(prg_id_2)->covg, 1); // nothing should change from the previous test EXPECT_EQ(pg.get_node(prg_id_1)->reads.size(), 2); // is the read really inserted in the node? EXPECT_EQ(pg.get_node(prg_id_2)->reads.size(), 1); // is the read really inserted in the node? std::vector<ReadPtr> reads_in_node_as_vector( pg.get_node(prg_id_1)->reads.begin(), pg.get_node(prg_id_1)->reads.end()); EXPECT_TRUE((reads_in_node_as_vector[0]->id == read_id_1 && reads_in_node_as_vector[1]->id == read_id_3) || (reads_in_node_as_vector[0]->id == read_id_3 && reads_in_node_as_vector[1]->id == read_id_1)); EXPECT_EQ(pg.reads.size(), 2); EXPECT_EQ(pg.get_read(read_id_3)->id, read_id_3); EXPECT_EQ(pg.get_read(read_id_3)->get_hits_as_unordered_map().size(), 1); EXPECT_EQ(*pg.get_read(read_id_3)->get_hits_as_unordered_map()[prg_id_1][0], *minimizer_hit_3); EXPECT_EQ(pg.get_read(read_id_3)->get_nodes().size(), 1); EXPECT_EQ(pg.get_read(read_id_3)->get_nodes()[0].lock()->node_id, prg_id_1); EXPECT_EQ(pg.get_read(read_id_3)->node_orientations.size(), 1); EXPECT_EQ(pg.get_read(read_id_3)->node_orientations[0], true); } // TODO: improve this? - add the cluster again, add another cluster, other // situations, etc... } TEST(PangenomeGraphAddNode, NodeDoesntAlreadyExist_PangenomeGraphNodesContainsNodeId) { PGraphTester pg; EXPECT_EQ(pg.nodes.size(), (uint)0); uint32_t node_id = 5; uint32_t prg_id = 10; auto prg_pointer = std::make_shared<LocalPRG>(node_id, "prg_name", ""); pg.add_node(prg_pointer, node_id); NodePtr pan_node = std::make_shared<pangenome::Node>(prg_pointer); EXPECT_EQ(*pg.nodes[node_id], *pan_node); EXPECT_EQ(pg.nodes[node_id]->node_id, (uint)node_id); EXPECT_EQ(pg.nodes[node_id]->prg_id, (uint)node_id); EXPECT_EQ(pg.nodes[node_id]->name, "prg_name"); EXPECT_EQ(pg.nodes[node_id]->covg, (uint)0); EXPECT_EQ(pg.nodes[node_id]->reads.size(), (uint)0); EXPECT_EQ(pg.nodes[node_id]->samples.size(), (uint)0); auto result = pg.nodes.find(node_id) != pg.nodes.end(); EXPECT_TRUE(result); result = pg.nodes.find(prg_id) == pg.nodes.end(); EXPECT_TRUE(result); } /* this test is now comprised on TEST(PangenomeGraph_add_hits_between_PRG_and_read, AddClusters) TEST(PangenomeGraphAddCoverage, NodeDoesntAlreadyExist_PangenomeGraphNodeContainsReadPtr) { PGraphTester pg; uint32_t read_id = 2; pg.add_read(read_id); ReadPtr read_ptr = pg.get_read(read_id); std::set<MinimizerHitPtr, pComp> mhs; uint32_t node_id = 0; uint32_t prg_id = 1; NodePtr node_ptr = pg.add_coverage(read_ptr, node_id, prg_id, "0"); auto result = node_ptr->reads.find(read_ptr) != node_ptr->reads.end(); EXPECT_TRUE(result); } */ TEST(PangenomeGraph_add_hits_between_PRG_and_read, AddTheSameClusterTwice) { PGraphTester pg; // test 1: add a cluster uint32_t prg_id_1 = 1; uint32_t read_id_1 = 100; MiniRecord mr1; MinimizerHitPtr minimizer_hit_1; std::shared_ptr<std::set<MinimizerHitPtr, pComp>> cluster_pointer_1; std::shared_ptr<LocalPRG> prg_pointer_1; { setup_minimizerhit_cluster_prg_function(prg_id_1, read_id_1, &mr1, &minimizer_hit_1, &cluster_pointer_1, &prg_pointer_1); pg.add_hits_between_PRG_and_read(prg_pointer_1, read_id_1, *cluster_pointer_1); // test if everything is fine EXPECT_EQ(pg.nodes.size(), 1); // is the node really inserted? EXPECT_EQ( pg.get_node(prg_id_1)->node_id, prg_id_1); // is the node really inserted? EXPECT_EQ(pg.get_node(prg_id_1)->covg, 1); // is the coverage of the node 1? EXPECT_EQ(pg.get_node(prg_id_1)->reads.size(), 1); // is the read really inserted in the node? EXPECT_EQ(pg.get_node(prg_id_1)->reads.begin()->get()->id, read_id_1); // is the read really inserted in the node? EXPECT_EQ(pg.reads.size(), 1); EXPECT_EQ(pg.get_read(read_id_1)->id, read_id_1); // is the read really // inserted? EXPECT_EQ(pg.get_read(read_id_1)->get_hits_as_unordered_map().size(), 1); // is the hit really inserted? EXPECT_EQ(*pg.get_read(read_id_1)->get_hits_as_unordered_map()[prg_id_1][0], *minimizer_hit_1); // is the hit really inserted? EXPECT_EQ(pg.get_read(read_id_1) ->get_hits_as_unordered_map()[prg_id_1][0] ->get_kmer_node_id(), prg_id_1); // is the node really inserted in the read? EXPECT_EQ(pg.get_read(read_id_1)->node_orientations.size(), 1); // is the node_orientation was inserted in the read? EXPECT_EQ(pg.get_read(read_id_1)->node_orientations[0], true); // is the node_orientation was inserted in the read? // add the cluster again ASSERT_EXCEPTION(pg.add_hits_between_PRG_and_read( prg_pointer_1, read_id_1, *cluster_pointer_1), FatalRuntimeError, "Error when adding hits to Pangraph read"); /* EXPECT_EQ(pg.nodes.size(), 1); //should not change EXPECT_EQ(pg.get_node(prg_id_1)->node_id, prg_id_1); //should not change EXPECT_EQ(pg.get_node(prg_id_1)->covg, 2); //coverage should increase (TODO: reflect if this is really what should happen, since the read id is exactly the same) EXPECT_EQ(pg.get_node(prg_id_1)->reads.size(), 2); //we should now have 2 reads EXPECT_EQ(pg.get_node(prg_id_1)->reads.begin()->get()->id, read_id_1); //should not change EXPECT_EQ((++pg.get_node(prg_id_1)->reads.begin())->get()->id, read_id_1); //the new read id should be also read_id_1 EXPECT_EQ(pg.reads.size(), 1); //should not change EXPECT_EQ(pg.get_read(read_id_1)->id, read_id_1); //should not change EXPECT_EQ(pg.get_read(read_id_1)->get_hits_as_unordered_map().size(), 1); //should not change EXPECT_EQ(*pg.get_read(read_id_1)->get_hits_as_unordered_map()[prg_id_1][0], *minimizer_hit_1); //should not change EXPECT_EQ(pg.get_read(read_id_1)->get_hits_as_unordered_map()[prg_id_1][0]->get_kmer_node_id(), prg_id_1); //should not change EXPECT_EQ(pg.get_read(read_id_1)->node_orientations.size(), 1); //should not change EXPECT_EQ(pg.get_read(read_id_1)->node_orientations[0], true); //should not change */ } } /* this test is now comprised on TEST(PangenomeGraph_add_hits_between_PRG_and_read, AddTheSameClusterTwice) TEST(PangenomeGraphAddCoverage, NodeAlreadyExists_PangenomeGraphNodeReadsContainsReadTwice) { PGraphTester pg; uint32_t read_id = 2; pg.add_read(read_id); ReadPtr read_ptr = pg.get_read(read_id); std::set<MinimizerHitPtr, pComp> mhs; uint32_t node_id = 0; uint32_t prg_id = 1; pg.add_coverage(read_ptr, node_id, prg_id, "0"); NodePtr node_ptr = pg.add_coverage(read_ptr, node_id, prg_id, "0"); auto result = node_ptr->reads.count(read_ptr); uint expected = 2; EXPECT_EQ(result, expected); } */ TEST(PangenomeGraphAddNode, AddClusterWrongReadId_AssertCatches) { uint32_t read_id = 1; uint32_t not_read_id = 7; std::deque<Interval> raw_path = { Interval(7, 8), Interval(10, 14) }; prg::Path path; path.initialize(raw_path); Interval interval(0, 5); Minimizer m1(0, interval.start, interval.get_end(), 0); // kmer, start, end, strand uint32_t prg_id = 4; MiniRecord mr1(prg_id, path, 0, 0); MinimizerHitPtr minimizer_hit(std::make_shared<MinimizerHit>(not_read_id, m1, mr1)); std::set<MinimizerHitPtr, pComp> cluster; cluster.insert(minimizer_hit); PGraphTester pg; auto prg_pointer = std::make_shared<LocalPRG>(prg_id, "", ""); ASSERT_EXCEPTION(pg.add_hits_between_PRG_and_read(prg_pointer, read_id, cluster), FatalRuntimeError, "Minimizer hits error: hit should be on read id"); } TEST(PangenomeGraphAddNode, AddClusterWrongPrgId_AssertCatches) { uint32_t read_id = 1; Read read(read_id); std::set<MinimizerHitPtr, pComp> cluster; uint32_t prg_id = 4; uint32_t not_prg_id = 7; Interval interval(0, 5); std::deque<Interval> raw_path = { Interval(7, 8), Interval(10, 14) }; prg::Path path; path.initialize(raw_path); Minimizer m1(0, interval.start, interval.get_end(), 0); // kmer, start, end, strand MiniRecord mr1(not_prg_id, path, 0, 0); MinimizerHitPtr minimizer_hit(std::make_shared<MinimizerHit>(read_id, m1, mr1)); cluster.insert(minimizer_hit); PGraphTester pg; auto prg_pointer = std::make_shared<LocalPRG>(prg_id, "", ""); ASSERT_EXCEPTION(pg.add_hits_between_PRG_and_read(prg_pointer, read_id, cluster), FatalRuntimeError, "Minimizer hits error: hit should be on PRG id"); } /* this test is now comprised in TEST(PangenomeGraphNode, add_node_and_get_node) TEST(PangenomeGraphAddNode, AddNode_PangenomeGraphNodesContainsNodeId) { std::set<MinimizerHitPtr, pComp> mhs; PGraphTester pg; uint32_t node_id = 0; uint32_t read_id = 1; pg.add_node(node_id, "0", read_id, mhs); auto result = pg.nodes.find(node_id) != pg.nodes.end(); EXPECT_TRUE(result); } */ TEST(PangenomeGraphAddNode, AddNode_PangenomeGraphNodeHasRightProperties) { PGraphTester pg; uint32_t node_id = 15; auto prg_pointer = std::make_shared<LocalPRG>(node_id, "prg_name", ""); pg.add_node(prg_pointer); NodePtr pan_node = std::make_shared<pangenome::Node>(prg_pointer); EXPECT_EQ(*pg.nodes[node_id], *pan_node); EXPECT_EQ(pg.nodes[node_id]->node_id, (uint)node_id); EXPECT_EQ(pg.nodes[node_id]->prg_id, (uint)node_id); EXPECT_EQ(pg.nodes[node_id]->name, "prg_name"); EXPECT_EQ(pg.nodes[node_id]->covg, (uint)0); EXPECT_EQ(pg.nodes[node_id]->reads.size(), (uint)0); EXPECT_EQ(pg.nodes[node_id]->samples.size(), (uint)0); // TODO: fix this // EXPECT_EQ(pg.nodes[node_id]->kmer_prg_with_coverage, // KmerGraphWithCoverage(&prg_pointer->kmer_prg)); } TEST(PangenomeGraphAddNode, AddNode_PangenomeGraphReadHasRightProperties) { std::set<MinimizerHitPtr, pComp> dummy_cluster; PGraphTester pg; uint32_t node_id = 0; uint32_t read_id = 1; auto prg_pointer = std::make_shared<LocalPRG>(node_id, "zero", ""); pg.add_hits_between_PRG_and_read(prg_pointer, read_id, dummy_cluster); ReadPtr pr = std::make_shared<Read>(read_id); EXPECT_EQ(pg.reads.size(), (uint)1); EXPECT_EQ(*pg.reads[1], *pr); EXPECT_EQ(pg.reads[1]->get_hits_as_unordered_map().size(), (uint)1); EXPECT_EQ(pg.reads[1]->get_hits_as_unordered_map()[0].size(), (uint)0); } TEST(PangenomeGraphTest, add_node_sample) { // add node and check it's there PGraphTester pg({ "sample", "sample1" }); auto l0 = std::make_shared<LocalPRG>(LocalPRG(0, "zero", "AGCTGCTAGCTTCGGACGCACA")); std::vector<KmerNodePtr> kmp; pg.add_node(l0); pg.add_hits_between_PRG_and_sample(0, "sample", kmp); EXPECT_EQ(pg.nodes.size(), (uint)1); EXPECT_EQ(pg.nodes[0]->node_id, (uint)0); EXPECT_EQ(pg.nodes[0]->prg_id, (uint)0); EXPECT_EQ(pg.nodes[0]->name, "zero"); EXPECT_EQ(pg.nodes[0]->covg, (uint)1); EXPECT_EQ(pg.nodes[0]->reads.size(), (uint)0); EXPECT_EQ(pg.nodes[0]->samples.size(), (uint)1); EXPECT_EQ(pg.samples.size(), (uint)2); EXPECT_EQ(pg.samples["sample"]->name, "sample"); EXPECT_EQ(pg.samples["sample"]->paths.size(), (uint)1); EXPECT_EQ(pg.samples["sample"]->paths[0].size(), (uint)1); EXPECT_EQ(pg.reads.size(), (uint)0); // add a second time pg.add_hits_between_PRG_and_sample(0, "sample", kmp); EXPECT_EQ(pg.nodes.size(), (uint)1); EXPECT_EQ(pg.nodes[0]->node_id, (uint)0); EXPECT_EQ(pg.nodes[0]->prg_id, (uint)0); EXPECT_EQ(pg.nodes[0]->name, "zero"); EXPECT_EQ(pg.nodes[0]->covg, (uint)2); EXPECT_EQ(pg.nodes[0]->reads.size(), (uint)0); EXPECT_EQ(pg.nodes[0]->samples.size(), (uint)1); EXPECT_EQ(pg.samples.size(), (uint)2); EXPECT_EQ(pg.samples["sample"]->name, "sample"); EXPECT_EQ(pg.samples["sample"]->paths.size(), (uint)1); EXPECT_EQ(pg.samples["sample"]->paths[0].size(), (uint)2); EXPECT_EQ(pg.reads.size(), (uint)0); // add a node with a different sample pg.add_hits_between_PRG_and_sample(0, "sample1", kmp); EXPECT_EQ(pg.nodes.size(), (uint)1); EXPECT_EQ(pg.nodes[0]->node_id, (uint)0); EXPECT_EQ(pg.nodes[0]->prg_id, (uint)0); EXPECT_EQ(pg.nodes[0]->name, "zero"); EXPECT_EQ(pg.nodes[0]->covg, (uint)3); EXPECT_EQ(pg.nodes[0]->reads.size(), (uint)0); EXPECT_EQ(pg.nodes[0]->samples.size(), (uint)2); EXPECT_EQ(pg.samples.size(), (uint)2); EXPECT_EQ(pg.samples["sample"]->name, "sample"); EXPECT_EQ(pg.samples["sample"]->paths.size(), (uint)1); EXPECT_EQ(pg.samples["sample"]->paths[0].size(), (uint)2); EXPECT_EQ(pg.samples["sample1"]->name, "sample1"); EXPECT_EQ(pg.samples["sample1"]->paths.size(), (uint)1); EXPECT_EQ(pg.samples["sample1"]->paths[0].size(), (uint)1); EXPECT_EQ(pg.reads.size(), (uint)0); // add a node with a different prg auto l1 = std::make_shared<LocalPRG>(LocalPRG(1, "one", "AGCTGCTAGCTTCGGACGCACA")); pg.add_node(l1); pg.add_hits_between_PRG_and_sample(1, "sample1", kmp); EXPECT_EQ(pg.nodes.size(), (uint)2); EXPECT_EQ(pg.nodes[0]->node_id, (uint)0); EXPECT_EQ(pg.nodes[0]->prg_id, (uint)0); EXPECT_EQ(pg.nodes[0]->name, "zero"); EXPECT_EQ(pg.nodes[0]->covg, (uint)3); EXPECT_EQ(pg.nodes[0]->reads.size(), (uint)0); EXPECT_EQ(pg.nodes[0]->samples.size(), (uint)2); EXPECT_EQ(pg.nodes[1]->node_id, (uint)1); EXPECT_EQ(pg.nodes[1]->prg_id, (uint)1); EXPECT_EQ(pg.nodes[1]->name, "one"); EXPECT_EQ(pg.nodes[1]->covg, (uint)1); EXPECT_EQ(pg.nodes[1]->reads.size(), (uint)0); EXPECT_EQ(pg.nodes[1]->samples.size(), (uint)1); EXPECT_EQ(pg.samples.size(), (uint)2); EXPECT_EQ(pg.samples["sample"]->name, "sample"); EXPECT_EQ(pg.samples["sample"]->paths.size(), (uint)1); EXPECT_EQ(pg.samples["sample"]->paths[0].size(), (uint)2); EXPECT_EQ(pg.samples["sample1"]->name, "sample1"); EXPECT_EQ(pg.samples["sample1"]->paths.size(), (uint)2); EXPECT_EQ(pg.samples["sample1"]->paths[0].size(), (uint)1); EXPECT_EQ(pg.samples["sample1"]->paths[1].size(), (uint)1); EXPECT_EQ(pg.reads.size(), (uint)0); } /* this test is not needed anymore as we don't have a clear function anymore TEST(PangenomeGraphTest, clear) { // read pg std::set<MinimizerHitPtr, pComp> mhs; PGraphTester pg; pg.add_node(0, "0", 1, mhs); EXPECT_EQ(pg.nodes.size(), (uint) 1); EXPECT_EQ(pg.reads.size(), (uint) 1); EXPECT_EQ(pg.samples.size(), (uint) 0); pg.clear(); EXPECT_EQ(pg.nodes.size(), (uint) 0); EXPECT_EQ(pg.reads.size(), (uint) 0); EXPECT_EQ(pg.samples.size(), (uint) 0); // sample pg auto l0 = std::make_shared<LocalPRG>(LocalPRG(0, "zero", "AGCTGCTAGCTTCGGACGCACA")); std::vector<KmerNodePtr> kmp; pg.add_node(0, "zero", "sample", 0, l0, kmp); EXPECT_EQ(pg.reads.size(), (uint) 0); EXPECT_EQ(pg.samples.size(), (uint) 1); pg.clear(); EXPECT_EQ(pg.nodes.size(), (uint) 0); EXPECT_EQ(pg.reads.size(), (uint) 0); EXPECT_EQ(pg.samples.size(), (uint) 0); } */ TEST(PangenomeGraphTest, equals) { auto l0 = std::make_shared<LocalPRG>(LocalPRG(0, "0", "")); auto l1 = std::make_shared<LocalPRG>(LocalPRG(1, "1", "")); auto l2 = std::make_shared<LocalPRG>(LocalPRG(2, "2", "")); auto l3 = std::make_shared<LocalPRG>(LocalPRG(3, "3", "")); PGraphTester pg1; pg1.add_node(l0); pg1.add_node(l1); pg1.add_node(l1); pg1.add_node(l2); PGraphTester pg2; pg2.add_node(l1); pg2.add_node(l0); pg2.add_node(l2); pg2.add_node(l1); // adding nodes in different order should make no difference EXPECT_EQ(pg1, pg1); EXPECT_EQ(pg2, pg2); EXPECT_EQ(pg1, pg2); EXPECT_EQ(pg2, pg1); // should not matter if node_id is different provided prg_id is same pg2.nodes[7] = std::make_shared<pangenome::Node>(l2, 7); pg2.nodes.erase(2); EXPECT_EQ(pg2, pg2); EXPECT_EQ(pg1, pg2); EXPECT_EQ(pg2, pg1); // or one extra node pg2.add_node(l3); EXPECT_EQ((pg1 == pg2), false); EXPECT_EQ((pg2 == pg1), false); // should not break when have a cycle in pangraph pg1.add_node(l0); EXPECT_EQ(pg1, pg1); } TEST(PangenomeGraphTest, not_equals) { auto l0 = std::make_shared<LocalPRG>(LocalPRG(0, "0", "")); auto l1 = std::make_shared<LocalPRG>(LocalPRG(1, "1", "")); auto l2 = std::make_shared<LocalPRG>(LocalPRG(2, "2", "")); auto l3 = std::make_shared<LocalPRG>(LocalPRG(3, "3", "")); PGraphTester pg1; pg1.add_node(l0); pg1.add_node(l1); pg1.add_node(l1); pg1.add_node(l2); PGraphTester pg2; pg2.add_node(l1); pg2.add_node(l0); pg2.add_node(l2); pg2.add_node(l1); // adding nodes in different order should make no difference EXPECT_EQ((pg1 != pg1), false); EXPECT_EQ((pg2 != pg2), false); EXPECT_EQ((pg1 != pg2), false); EXPECT_EQ((pg2 != pg1), false); // or one extra node pg2.add_node(l3); EXPECT_EQ((pg1 != pg2), true); EXPECT_EQ((pg2 != pg1), true); // should not break when have a cycle in pangraph pg1.add_node(l0); EXPECT_EQ((pg1 != pg1), false); } TEST(PangenomeGraphTest, remove_node) { auto l0 = std::make_shared<LocalPRG>(LocalPRG(0, "0", "")); auto l1 = std::make_shared<LocalPRG>(LocalPRG(1, "1", "")); auto l2 = std::make_shared<LocalPRG>(LocalPRG(2, "2", "")); auto l3 = std::make_shared<LocalPRG>(LocalPRG(3, "3", "")); std::set<MinimizerHitPtr, pComp> dummy_cluster; PGraphTester pg1, pg2; // read 0: 0->1->2->3 pg1.add_node(l0); pg1.add_hits_between_PRG_and_read(l0, 0, dummy_cluster); pg1.add_node(l1); pg1.add_hits_between_PRG_and_read(l1, 0, dummy_cluster); pg1.add_node(l2); pg1.add_hits_between_PRG_and_read(l2, 0, dummy_cluster); pg1.add_node(l3); pg1.add_hits_between_PRG_and_read(l3, 0, dummy_cluster); // read 0: 0->1->3 pg2.add_node(l0); pg1.add_hits_between_PRG_and_read(l0, 0, dummy_cluster); pg2.add_node(l1); pg1.add_hits_between_PRG_and_read(l1, 0, dummy_cluster); pg2.add_node(l3); pg1.add_hits_between_PRG_and_read(l3, 0, dummy_cluster); pg1.remove_node(pg1.nodes[2]); EXPECT_EQ(pg1, pg2); } TEST(PangenomeGraphTest, remove_read) { auto l0 = std::make_shared<LocalPRG>(LocalPRG(0, "0", "")); auto l1 = std::make_shared<LocalPRG>(LocalPRG(1, "1", "")); auto l2 = std::make_shared<LocalPRG>(LocalPRG(2, "2", "")); auto l3 = std::make_shared<LocalPRG>(LocalPRG(3, "3", "")); auto l4 = std::make_shared<LocalPRG>(LocalPRG(4, "4", "")); auto l5 = std::make_shared<LocalPRG>(LocalPRG(5, "5", "")); std::set<MinimizerHitPtr, pComp> dummy_cluster; PGraphTester pg1, pg2, pg3; // read 0: 0->1->2->3 pg1.add_node(l0); pg1.add_hits_between_PRG_and_read(l0, 0, dummy_cluster); pg1.add_node(l1); pg1.add_hits_between_PRG_and_read(l1, 0, dummy_cluster); pg1.add_node(l2); pg1.add_hits_between_PRG_and_read(l2, 0, dummy_cluster); pg1.add_node(l3); pg1.add_hits_between_PRG_and_read(l3, 0, dummy_cluster); // read 1: 4->5->0->5 pg1.add_node(l4); pg1.add_hits_between_PRG_and_read(l4, 1, dummy_cluster); pg1.add_node(l5); pg1.add_hits_between_PRG_and_read(l5, 1, dummy_cluster); pg1.add_node(l0); pg1.add_hits_between_PRG_and_read(l0, 1, dummy_cluster); pg1.add_node(l5); pg1.add_hits_between_PRG_and_read(l5, 1, dummy_cluster); // read 1: 4->5->0->5 pg2.add_node(l4); pg2.add_hits_between_PRG_and_read(l4, 1, dummy_cluster); pg2.add_node(l5); pg2.add_hits_between_PRG_and_read(l5, 1, dummy_cluster); pg2.add_node(l0); pg2.add_hits_between_PRG_and_read(l0, 1, dummy_cluster); pg2.add_node(l5); pg2.add_hits_between_PRG_and_read(l5, 1, dummy_cluster); pg1.remove_read(0); EXPECT_EQ(pg1, pg2); EXPECT_EQ(pg1.nodes[4]->covg, pg2.nodes[4]->covg); EXPECT_EQ(pg1.nodes[5]->covg, pg2.nodes[5]->covg); EXPECT_EQ(pg1.nodes[0]->covg, pg2.nodes[0]->covg); EXPECT_EQ(pg1.nodes[4]->reads.size(), pg2.nodes[4]->reads.size()); EXPECT_EQ(pg1.nodes[5]->reads.size(), pg2.nodes[5]->reads.size()); EXPECT_EQ(pg1.nodes[0]->reads.size(), pg2.nodes[0]->reads.size()); pg1.remove_read(1); EXPECT_EQ(pg1, pg3); } TEST(PangenomeGraphTest, remove_low_covg_nodes) { auto l0 = std::make_shared<LocalPRG>(LocalPRG(0, "0", "")); auto l1 = std::make_shared<LocalPRG>(LocalPRG(1, "1", "")); auto l2 = std::make_shared<LocalPRG>(LocalPRG(2, "2", "")); auto l3 = std::make_shared<LocalPRG>(LocalPRG(3, "3", "")); auto l4 = std::make_shared<LocalPRG>(LocalPRG(4, "4", "")); auto l5 = std::make_shared<LocalPRG>(LocalPRG(5, "5", "")); std::set<MinimizerHitPtr, pComp> dummy_cluster; PGraphTester pg1, pg2, pg3; // read 0: 0->1->2->3 pg1.add_node(l0); pg1.add_hits_between_PRG_and_read(l0, 0, dummy_cluster); pg1.add_node(l1); pg1.add_hits_between_PRG_and_read(l1, 0, dummy_cluster); pg1.add_node(l2); pg1.add_hits_between_PRG_and_read(l2, 0, dummy_cluster); pg1.add_node(l3); pg1.add_hits_between_PRG_and_read(l3, 0, dummy_cluster); // read 1: -4 -> -3 -> -1 pg1.add_node(l1); pg1.add_hits_between_PRG_and_read(l1, 1, dummy_cluster); pg1.add_node(l3); pg1.add_hits_between_PRG_and_read(l3, 1, dummy_cluster); pg1.add_node(l4); pg1.add_hits_between_PRG_and_read(l4, 1, dummy_cluster); // read 2: 0 -> 1 -> 3 -> 4 pg1.add_node(l0); pg1.add_hits_between_PRG_and_read(l0, 2, dummy_cluster); pg1.add_node(l1); pg1.add_hits_between_PRG_and_read(l1, 2, dummy_cluster); pg1.add_node(l3); pg1.add_hits_between_PRG_and_read(l3, 2, dummy_cluster); pg1.add_node(l4); pg1.add_hits_between_PRG_and_read(l4, 2, dummy_cluster); // read 3: 0 -> 5 pg1.add_node(l0); pg1.add_hits_between_PRG_and_read(l0, 3, dummy_cluster); pg1.add_node(l5); pg1.add_hits_between_PRG_and_read(l5, 3, dummy_cluster); // read 4: 5 -> 1 pg1.add_node(l5); pg1.add_hits_between_PRG_and_read(l5, 4, dummy_cluster); pg1.add_node(l1); pg1.add_hits_between_PRG_and_read(l1, 4, dummy_cluster); // read 0: 0->1->3 pg2.add_node(l0); pg2.add_hits_between_PRG_and_read(l0, 0, dummy_cluster); pg2.add_node(l1); pg2.add_hits_between_PRG_and_read(l1, 0, dummy_cluster); pg2.add_node(l3); pg2.add_hits_between_PRG_and_read(l3, 0, dummy_cluster); // read 1: -4 -> -3 -> -1 pg2.add_node(l1); pg2.add_hits_between_PRG_and_read(l1, 1, dummy_cluster); pg2.add_node(l3); pg2.add_hits_between_PRG_and_read(l3, 1, dummy_cluster); pg2.add_node(l4); pg2.add_hits_between_PRG_and_read(l4, 1, dummy_cluster); // read 2: 0 -> 1 -> 3 -> 4 pg2.add_node(l0); pg2.add_hits_between_PRG_and_read(l0, 2, dummy_cluster); pg2.add_node(l1); pg2.add_hits_between_PRG_and_read(l1, 2, dummy_cluster); pg2.add_node(l3); pg2.add_hits_between_PRG_and_read(l3, 2, dummy_cluster); pg2.add_node(l4); pg2.add_hits_between_PRG_and_read(l4, 2, dummy_cluster); // read 3: 0 -> 5 pg2.add_node(l0); pg2.add_hits_between_PRG_and_read(l0, 3, dummy_cluster); pg2.add_node(l5); pg2.add_hits_between_PRG_and_read(l5, 3, dummy_cluster); // read 4: 5 -> 1 pg2.add_node(l5); pg2.add_hits_between_PRG_and_read(l5, 4, dummy_cluster); pg2.add_node(l1); pg2.add_hits_between_PRG_and_read(l1, 4, dummy_cluster); pg1.remove_low_covg_nodes(1); EXPECT_EQ(pg1, pg2); // read 0: 0->1->3 pg3.add_node(l0); pg3.add_hits_between_PRG_and_read(l0, 0, dummy_cluster); pg3.add_node(l1); pg3.add_hits_between_PRG_and_read(l1, 0, dummy_cluster); pg3.add_node(l3); pg3.add_hits_between_PRG_and_read(l3, 0, dummy_cluster); // read 1: 1 -> 3 pg3.add_node(l1); pg3.add_hits_between_PRG_and_read(l1, 1, dummy_cluster); pg3.add_node(l3); pg3.add_hits_between_PRG_and_read(l3, 1, dummy_cluster); // read 2: 0 -> 1 -> 3 pg3.add_node(l0); pg3.add_hits_between_PRG_and_read(l0, 2, dummy_cluster); pg3.add_node(l1); pg3.add_hits_between_PRG_and_read(l1, 2, dummy_cluster); pg3.add_node(l3); pg3.add_hits_between_PRG_and_read(l3, 2, dummy_cluster); // read 3: 0 pg3.add_node(l0); pg3.add_hits_between_PRG_and_read(l0, 3, dummy_cluster); // read 4: 1 pg3.add_node(l1); pg3.add_hits_between_PRG_and_read(l1, 4, dummy_cluster); pg1.remove_low_covg_nodes(2); EXPECT_EQ(pg1, pg3); } TEST(PangenomeGraphTest, split_node_by_reads) { auto l0 = std::make_shared<LocalPRG>(LocalPRG(0, "0", "")); auto l1 = std::make_shared<LocalPRG>(LocalPRG(1, "1", "")); auto l2 = std::make_shared<LocalPRG>(LocalPRG(2, "2", "")); auto l3 = std::make_shared<LocalPRG>(LocalPRG(3, "3", "")); auto l4 = std::make_shared<LocalPRG>(LocalPRG(4, "4", "")); auto l5 = std::make_shared<LocalPRG>(LocalPRG(5, "5", "")); std::set<MinimizerHitPtr, pComp> dummy_cluster; PGraphTester pg1, pg2, pg3; // read 0: 0->1->2->3 pg1.add_node(l0); pg1.add_hits_between_PRG_and_read(l0, 0, dummy_cluster); pg1.add_node(l1); pg1.add_hits_between_PRG_and_read(l1, 0, dummy_cluster); pg1.add_node(l2); pg1.add_hits_between_PRG_and_read(l2, 0, dummy_cluster); pg1.add_node(l3); pg1.add_hits_between_PRG_and_read(l3, 0, dummy_cluster); // read 1: 4->5->0->5 pg1.add_node(l4); pg1.add_hits_between_PRG_and_read(l4, 1, dummy_cluster); pg1.add_node(l5); pg1.add_hits_between_PRG_and_read(l5, 1, dummy_cluster); pg1.add_node(l0); pg1.add_hits_between_PRG_and_read(l0, 1, dummy_cluster); pg1.add_node(l5); pg1.add_hits_between_PRG_and_read(l5, 1, dummy_cluster); EXPECT_EQ((uint)6, pg1.nodes.size()); EXPECT_EQ(pg1.nodes[0]->prg_id, (uint)0); EXPECT_EQ(pg1.nodes[0]->covg, (uint)2); EXPECT_EQ(pg1.nodes[1]->prg_id, (uint)1); EXPECT_EQ(pg1.nodes[1]->covg, (uint)1); EXPECT_EQ(pg1.nodes[2]->prg_id, (uint)2); EXPECT_EQ(pg1.nodes[2]->covg, (uint)1); EXPECT_EQ(pg1.nodes[3]->prg_id, (uint)3); EXPECT_EQ(pg1.nodes[3]->covg, (uint)1); EXPECT_EQ(pg1.nodes[4]->prg_id, (uint)4); EXPECT_EQ(pg1.nodes[4]->covg, (uint)1); EXPECT_EQ(pg1.nodes[5]->prg_id, (uint)5); EXPECT_EQ(pg1.nodes[5]->covg, (uint)2); // read 0: 0->1->2->3 pg2.add_node(l0); pg2.add_hits_between_PRG_and_read(l0, 0, dummy_cluster); pg2.add_node(l1); pg2.add_hits_between_PRG_and_read(l1, 0, dummy_cluster); NodePtr n = std::make_shared<pangenome::Node>(l2, 7); pg2.nodes[7] = n; pg2.add_node(l3); pg2.add_hits_between_PRG_and_read(l3, 0, dummy_cluster); // read 1: 4->5->0->5 pg2.add_node(l4); pg2.add_hits_between_PRG_and_read(l4, 1, dummy_cluster); pg2.add_node(l5); pg2.add_hits_between_PRG_and_read(l5, 1, dummy_cluster); pg2.add_node(l0); pg2.add_hits_between_PRG_and_read(l0, 1, dummy_cluster); pg2.add_node(l5); pg2.add_hits_between_PRG_and_read(l5, 1, dummy_cluster); std::unordered_set<ReadPtr> reads = { pg1.reads[0] }; std::vector<uint_least32_t> node_ids = { 1, 2, 3 }; std::vector<uint_least32_t> node_ids_exp = { 1, 6, 3 }; std::vector<bool> node_orients = { 0, 0, 0 }; pg1.split_node_by_reads(reads, node_ids, node_orients, 2); EXPECT_EQ(pg1, pg2); EXPECT_ITERABLE_EQ(std::vector<uint_least32_t>, node_ids_exp, node_ids); EXPECT_EQ((uint)6, pg1.nodes.size()); EXPECT_EQ(pg1.nodes[0]->prg_id, (uint)0); EXPECT_EQ(pg1.nodes[0]->covg, (uint)2); EXPECT_EQ(pg1.nodes[1]->prg_id, (uint)1); EXPECT_EQ(pg1.nodes[1]->covg, (uint)1); EXPECT_EQ(pg1.nodes[6]->prg_id, (uint)2); EXPECT_EQ(pg1.nodes[6]->covg, (uint)0); EXPECT_EQ(pg1.nodes[3]->prg_id, (uint)3); EXPECT_EQ(pg1.nodes[3]->covg, (uint)1); EXPECT_EQ(pg1.nodes[4]->prg_id, (uint)4); EXPECT_EQ(pg1.nodes[4]->covg, (uint)1); EXPECT_EQ(pg1.nodes[5]->prg_id, (uint)5); EXPECT_EQ(pg1.nodes[5]->covg, (uint)2); // read 0: 0->1->2->3 pg3.add_node(l0); pg3.add_hits_between_PRG_and_read(l0, 0, dummy_cluster); pg3.add_node(l1); pg3.add_hits_between_PRG_and_read(l1, 0, dummy_cluster); n = std::make_shared<pangenome::Node>(l2, 7); pg3.nodes[7] = n; pg3.add_node(l3); pg3.add_hits_between_PRG_and_read(l3, 0, dummy_cluster); // read 1: 4->5->0->5 pg3.add_node(l4); pg3.add_hits_between_PRG_and_read(l4, 1, dummy_cluster); n = std::make_shared<pangenome::Node>(l5, 8); pg3.nodes[8] = n; pg3.add_node(l0); pg3.add_hits_between_PRG_and_read(l0, 1, dummy_cluster); pg3.add_node(l5); pg3.add_hits_between_PRG_and_read(l5, 1, dummy_cluster); reads = { pg1.reads[1] }; node_ids = { 5, 0, 5 }; node_ids_exp = { 7, 0, 5 }; pg1.split_node_by_reads(reads, node_ids, node_orients, 5); EXPECT_EQ(pg1, pg3); EXPECT_ITERABLE_EQ(std::vector<uint_least32_t>, node_ids_exp, node_ids); EXPECT_EQ((uint)7, pg1.nodes.size()); EXPECT_EQ(pg1.nodes[0]->prg_id, (uint)0); EXPECT_EQ(pg1.nodes[0]->covg, (uint)2); EXPECT_EQ(pg1.nodes[1]->prg_id, (uint)1); EXPECT_EQ(pg1.nodes[1]->covg, (uint)1); EXPECT_EQ(pg1.nodes[6]->prg_id, (uint)2); EXPECT_EQ(pg1.nodes[6]->covg, (uint)0); EXPECT_EQ(pg1.nodes[3]->prg_id, (uint)3); EXPECT_EQ(pg1.nodes[3]->covg, (uint)1); EXPECT_EQ(pg1.nodes[4]->prg_id, (uint)4); EXPECT_EQ(pg1.nodes[4]->covg, (uint)1); EXPECT_EQ(pg1.nodes[5]->prg_id, (uint)5); EXPECT_EQ(pg1.nodes[5]->covg, (uint)1); EXPECT_EQ(pg1.nodes[7]->prg_id, (uint)5); EXPECT_EQ(pg1.nodes[7]->covg, (uint)0); } TEST(PangenomeGraphTest, add_hits_to_kmergraph) { } TEST(PangenomeGraphTest, save_matrix) { // add node and check it's there std::vector<std::string> names = { "sample1", "sample2", "sample3", "sample4" }; PGraphTester pg(names); auto l0 = std::make_shared<LocalPRG>(LocalPRG(0, "zero", "AGCTGCTAGCTTCGGACGCACA")); auto l1 = std::make_shared<LocalPRG>(LocalPRG(1, "one", "")); auto l2 = std::make_shared<LocalPRG>(LocalPRG(2, "two", "")); std::vector<KmerNodePtr> kmp; pg.add_node(l0); pg.add_node(l1); pg.add_node(l2); pg.add_hits_between_PRG_and_sample(0, "sample1", kmp); pg.add_hits_between_PRG_and_sample(0, "sample1", kmp); pg.add_hits_between_PRG_and_sample(0, "sample2", kmp); pg.add_hits_between_PRG_and_sample(1, "sample1", kmp); pg.add_hits_between_PRG_and_sample(2, "sample3", kmp); pg.save_matrix(TEST_CASE_DIR + "pangraph_test_save.matrix", names); } TEST(PangenomeGraphTest, save_mapped_read_strings) { PGraphTester pg; pangenome::ReadPtr pr; MinimizerHits mhits; std::deque<Interval> d; prg::Path p; // read1 Minimizer m1(0, 1, 6, 0); // kmer, start, end, strand d = { Interval(7, 8), Interval(10, 14) }; p.initialize(d); MiniRecord mr1(0, p, 0, 0); mhits.add_hit(1, m1, mr1); // read 1 Minimizer m2(0, 0, 5, 0); d = { Interval(6, 10), Interval(11, 12) }; p.initialize(d); MiniRecord mr2(0, p, 0, 0); mhits.add_hit(1, m2, mr2); Minimizer m3(0, 0, 5, 0); d = { Interval(6, 10), Interval(12, 13) }; p.initialize(d); MiniRecord mr3(0, p, 0, 0); mhits.add_hit(1, m3, mr3); auto l0 = std::make_shared<LocalPRG>(LocalPRG(0, "zero", "")); pg.add_node(l0); pg.add_hits_between_PRG_and_read(l0, 1, mhits.hits); mhits.clear(); // read 2 Minimizer m4(0, 2, 7, 1); d = { Interval(6, 10), Interval(11, 12) }; p.initialize(d); MiniRecord mr4(0, p, 0, 0); mhits.add_hit(2, m4, mr4); Minimizer m5(0, 5, 10, 1); d = { Interval(6, 10), Interval(12, 13) }; p.initialize(d); MiniRecord mr5(0, p, 0, 0); mhits.add_hit(2, m5, mr5); pg.add_hits_between_PRG_and_read(l0, 2, mhits.hits); std::string expected1 = ">read1 pandora: 1 0:6 + \nshould\n>read2 pandora: 2 2:10 - \nis time \n"; std::string expected2 = ">read2 pandora: 2 2:10 - \nis time \n>read1 pandora: 1 0:6 + \nshould\n"; pg.save_mapped_read_strings(TEST_CASE_DIR + "reads.fa", "save_mapped_read_strings"); std::ifstream ifs("save_mapped_read_strings/zero/zero.reads.fa"); std::string content( (std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); EXPECT_TRUE((content == expected1) or (content == expected2)); pg.save_mapped_read_strings(TEST_CASE_DIR + "reads.fa", "."); std::ifstream ifs2("zero/zero.reads.fa"); std::string content2( (std::istreambuf_iterator<char>(ifs2)), (std::istreambuf_iterator<char>())); EXPECT_TRUE((content2 == expected1) or (content2 == expected2)); } TEST(PangenomeGraphTest, get_node_closest_vcf_reference_no_paths) { uint32_t prg_id = 3, w = 1, k = 3, max_num_kmers_to_average = 100; std::string prg_name = "nested varsite"; auto l3 = std::make_shared<LocalPRG>(prg_id, prg_name, "A 5 G 7 C 8 T 7 6 G 5 T"); auto index = std::make_shared<Index>(); l3->minimizer_sketch(index, w, k); std::string sample_name = "null_test_sample"; pangenome::Graph pangraph({ sample_name }); std::vector<KmerNodePtr> sample_kmer_path = {}; pangraph.add_node(l3); pangraph.add_hits_between_PRG_and_sample(prg_id, sample_name, sample_kmer_path); auto path = pangraph.get_node_closest_vcf_reference( *pangraph.nodes[prg_id], w, *l3, max_num_kmers_to_average); EXPECT_ITERABLE_EQ(std::vector<LocalNodePtr>, path, l3->prg.top_path()); } TEST(PangenomeGraphTest, get_node_closest_vcf_reference_one_path) { uint32_t prg_id = 3, w = 1, k = 3, max_num_kmers_to_average = 100; std::string prg_name = "nested varsite"; auto l3 = std::make_shared<LocalPRG>(prg_id, prg_name, "A 5 G 7 C 8 T 7 6 G 5 T"); auto index = std::make_shared<Index>(); l3->minimizer_sketch(index, w, k); std::string sample_name = "single_test_sample"; pangenome::Graph pangraph({ sample_name }); auto& kg = l3->kmer_prg; std::vector<KmerNodePtr> sample_kmer_path = { kg.nodes[0], kg.nodes[2], kg.nodes[5], kg.nodes[6] }; pangraph.add_node(l3); pangraph.add_hits_between_PRG_and_sample(prg_id, sample_name, sample_kmer_path); auto& node = *pangraph.nodes[prg_id]; auto path = pangraph.get_node_closest_vcf_reference( node, w, *l3, max_num_kmers_to_average); std::vector<LocalNodePtr> exp_path = { l3->prg.nodes[0], l3->prg.nodes[1], l3->prg.nodes[3], l3->prg.nodes[4], l3->prg.nodes[6] }; EXPECT_ITERABLE_EQ(std::vector<LocalNodePtr>, path, exp_path); } TEST(PangenomeGraphTest, get_node_closest_vcf_reference_three_paths) { uint32_t prg_id = 3, w = 1, k = 3, max_num_kmers_to_average = 100; std::string prg_name = "nested varsite"; auto l3 = std::make_shared<LocalPRG>(prg_id, prg_name, "A 5 G 7 C 8 T 7 6 G 5 T"); auto index = std::make_shared<Index>(); l3->minimizer_sketch(index, w, k); pangenome::Graph pangraph({ "test_sample1", "test_sample1_again", "test_sample2" }); auto& kg = l3->kmer_prg; std::string sample_name = "test_sample1"; std::vector<KmerNodePtr> sample_kmer_path = { kg.nodes[0], kg.nodes[2], kg.nodes[5], kg.nodes[6] }; pangraph.add_node(l3); pangraph.add_hits_between_PRG_and_sample(prg_id, sample_name, sample_kmer_path); sample_name = "test_sample1_again"; sample_kmer_path = { kg.nodes[0], kg.nodes[2], kg.nodes[5], kg.nodes[6] }; pangraph.add_hits_between_PRG_and_sample(prg_id, sample_name, sample_kmer_path); sample_name = "test_sample2"; sample_kmer_path = { kg.nodes[0], kg.nodes[4], kg.nodes[6] }; pangraph.add_hits_between_PRG_and_sample(prg_id, sample_name, sample_kmer_path); auto& node = *pangraph.nodes[prg_id]; auto path = pangraph.get_node_closest_vcf_reference( node, w, *l3, max_num_kmers_to_average); std::vector<LocalNodePtr> exp_path = { l3->prg.nodes[0], l3->prg.nodes[1], l3->prg.nodes[3], l3->prg.nodes[4], l3->prg.nodes[6] }; EXPECT_ITERABLE_EQ(std::vector<LocalNodePtr>, path, exp_path); } TEST(PangenomeGraphTest, copy_coverages_to_kmergraphs) { uint32_t prg_id = 3, w = 1, k = 3; std::string prg_name = "nested varsite", sample_name = "sample"; auto l3 = std::make_shared<LocalPRG>(prg_id, prg_name, "A 5 G 7 C 8 T 7 6 G 5 T"); auto index = std::make_shared<Index>(); l3->minimizer_sketch(index, w, k); pangenome::Graph ref_pangraph({ sample_name }); auto sample_id = 0; std::vector<KmerNodePtr> empty = {}; ref_pangraph.add_node(l3); ref_pangraph.add_hits_between_PRG_and_sample(prg_id, sample_name, empty); EXPECT_TRUE(ref_pangraph.nodes.find(prg_id) != ref_pangraph.nodes.end()); auto& kg = *(ref_pangraph.nodes[prg_id]->kmer_prg_with_coverage.kmer_prg); EXPECT_EQ(kg.nodes.size(), (uint)7); auto& kgWithCoverage = ref_pangraph.nodes[prg_id]->kmer_prg_with_coverage; kgWithCoverage.set_reverse_covg(2, 5, sample_id); kgWithCoverage.set_forward_covg(4, 8, sample_id); kgWithCoverage.set_reverse_covg(5, 2, sample_id); kgWithCoverage.set_forward_covg(6, 5, sample_id); pangenome::Graph pangraph({ "sample_0", "sample_1", "sample_2", "sample_3" }); sample_id = 3; pangraph.add_node(l3); pangraph.add_hits_between_PRG_and_sample(prg_id, "sample_3", empty); pangraph.copy_coverages_to_kmergraphs(ref_pangraph, sample_id); for (uint32_t id = 0; id < 3; ++id) { for (const auto& node : pangraph.nodes[prg_id]->kmer_prg_with_coverage.kmer_prg->nodes) { EXPECT_EQ(pangraph.nodes[prg_id]->kmer_prg_with_coverage.get_forward_covg( node->id, id), (uint)0); EXPECT_EQ(pangraph.nodes[prg_id]->kmer_prg_with_coverage.get_reverse_covg( node->id, id), (uint)0); } } auto id = sample_id; EXPECT_EQ(pangraph.nodes[prg_id]->kmer_prg_with_coverage.get_forward_covg(0, id), (uint)0); EXPECT_EQ(pangraph.nodes[prg_id]->kmer_prg_with_coverage.get_reverse_covg(0, id), (uint)0); EXPECT_EQ(pangraph.nodes[prg_id]->kmer_prg_with_coverage.get_forward_covg(1, id), (uint)0); EXPECT_EQ(pangraph.nodes[prg_id]->kmer_prg_with_coverage.get_reverse_covg(1, id), (uint)0); EXPECT_EQ(pangraph.nodes[prg_id]->kmer_prg_with_coverage.get_forward_covg(2, id), (uint)0); EXPECT_EQ(pangraph.nodes[prg_id]->kmer_prg_with_coverage.get_reverse_covg(2, id), (uint)5); EXPECT_EQ(pangraph.nodes[prg_id]->kmer_prg_with_coverage.get_forward_covg(3, id), (uint)0); EXPECT_EQ(pangraph.nodes[prg_id]->kmer_prg_with_coverage.get_reverse_covg(3, id), (uint)0); EXPECT_EQ(pangraph.nodes[prg_id]->kmer_prg_with_coverage.get_forward_covg(4, id), (uint)8); EXPECT_EQ(pangraph.nodes[prg_id]->kmer_prg_with_coverage.get_reverse_covg(4, id), (uint)0); EXPECT_EQ(pangraph.nodes[prg_id]->kmer_prg_with_coverage.get_forward_covg(5, id), (uint)0); EXPECT_EQ(pangraph.nodes[prg_id]->kmer_prg_with_coverage.get_reverse_covg(5, id), (uint)2); EXPECT_EQ(pangraph.nodes[prg_id]->kmer_prg_with_coverage.get_forward_covg(6, id), (uint)5); EXPECT_EQ(pangraph.nodes[prg_id]->kmer_prg_with_coverage.get_reverse_covg(6, id), (uint)0); } TEST(PangenomeGraphTest, infer_node_vcf_reference_path_no_file_strings) { std::vector<std::shared_ptr<LocalPRG>> prgs; std::vector<std::string> prg_strings; prg_strings.push_back( "ATGCCGGTAATTAAAGTACGTGAAAAGAAACTGGCTC 5 A 6 G 5 CGAAAACGCACGCCGCACTCGTCTGTAC"); prg_strings.push_back("A 5 G 7 C 8 T 7 6 G 5 T"); prg_strings.push_back("TC 5 ACTC 7 TAGTCA 8 TTGTGA 7 6 AACTAG 5 AG"); prg_strings.push_back("A 5 G 7 C 8 T 7 T 9 CCG 10 CGG 9 6 G 5 TAT"); std::string sample_name = "sample"; pangenome::Graph pangraph({ sample_name }); std::vector<KmerNodePtr> empty; auto index = std::make_shared<Index>(); uint32_t prg_id = 0, sample_id = 0, w = 1, k = 3, max_num_kmers_to_average = 100; std::unordered_map<std::string, std::string> vcf_refs; std::vector<std::vector<LocalNodePtr>> vcf_ref_paths; for (const auto& prg_string : prg_strings) { std::string prg_name = "prg" + std::to_string(prg_id); prgs.emplace_back( std::make_shared<LocalPRG>(LocalPRG(prg_id, prg_name, prg_string))); prgs.back()->minimizer_sketch(index, w, k); pangraph.add_node(prgs.back()); pangraph.add_hits_between_PRG_and_sample(prg_id, sample_name, empty); vcf_ref_paths.emplace_back( pangraph.infer_node_vcf_reference_path(*pangraph.nodes[prg_id], prgs.back(), w, vcf_refs, max_num_kmers_to_average)); prg_id++; } EXPECT_EQ(vcf_ref_paths.size(), (uint)4); for (uint j = 0; j < vcf_ref_paths.size(); ++j) EXPECT_ITERABLE_EQ( std::vector<LocalNodePtr>, vcf_ref_paths[j], prgs[j]->prg.top_path()); } TEST(PangenomeGraphTest, infer_node_vcf_reference_path_with_file_strings) { std::vector<std::shared_ptr<LocalPRG>> prgs; std::vector<std::string> prg_strings; prg_strings.push_back( "ATGCCGGTAATTAAAGTACGTGAAAAGAAACTGGCTC 5 A 6 G 5 CGAAAACGCACGCCGCACTCGTCTGTAC"); prg_strings.push_back("A 5 G 7 C 8 T 7 6 G 5 T"); prg_strings.push_back("TC 5 ACTC 7 TAGTCA 8 TTGTGA 7 6 AACTAG 5 AG"); prg_strings.push_back("AATTTTTTTGGGGTTGGTTTTAAA 5 GGGGG 7 CCCCCC 8 TTTTTT 7 TTTTTT " "9 CCGCCGCCGCCG 10 CGGCCGCCG 9 6 GGGGG 5 TATAAAAATTTTTT"); std::unordered_map<std::string, std::string> vcf_ref_strings; vcf_ref_strings["prg0"] = "ATGCCGGTAATTAAAGTACGTGAAAAGAAACTGGCTCGCGAAAACGCACGCCGCACTCGTCTGTAC"; // valid vcf_ref_strings["prg1"] = "AGT"; // invalid, too short vcf_ref_strings["prg2"] = "ATGCCGGTAATTAAAGTACGTGAAAAGAAACTGGCTCGCGAAAACGCACGCCGCAC" "TCGTCTGTAC"; // invalid, is not a path through prg vcf_ref_strings["prg3"] = "AATTTTTTTGGGGTTGGTTTTAAAGGGGGTTTTTTTTTTTTCCGCCGCCGCCGTAT" "AAAAATTTTTT"; // valid std::string sample_name = "sample"; pangenome::Graph pangraph({ sample_name }); std::vector<KmerNodePtr> empty; auto index = std::make_shared<Index>(); uint32_t prg_id = 0, sample_id = 0, w = 1, k = 3, max_num_kmers_to_average = 100; std::vector<std::vector<LocalNodePtr>> vcf_ref_paths; for (const auto& prg_string : prg_strings) { std::string prg_name = "prg" + std::to_string(prg_id); prgs.emplace_back( std::make_shared<LocalPRG>(LocalPRG(prg_id, prg_name, prg_string))); prgs.back()->minimizer_sketch(index, w, k); pangraph.add_node(prgs.back()); pangraph.add_hits_between_PRG_and_sample(prg_id, sample_name, empty); vcf_ref_paths.emplace_back( pangraph.infer_node_vcf_reference_path(*pangraph.nodes[prg_id], prgs.back(), w, vcf_ref_strings, max_num_kmers_to_average)); prg_id++; } std::vector<LocalNodePtr> exp_path0 = { prgs[0]->prg.nodes[0], prgs[0]->prg.nodes[2], prgs[0]->prg.nodes[3] }; EXPECT_ITERABLE_EQ(std::vector<LocalNodePtr>, vcf_ref_paths[0], exp_path0); EXPECT_ITERABLE_EQ( std::vector<LocalNodePtr>, vcf_ref_paths[1], prgs[1]->prg.top_path()); EXPECT_ITERABLE_EQ( std::vector<LocalNodePtr>, vcf_ref_paths[2], prgs[2]->prg.top_path()); std::vector<LocalNodePtr> exp_path3 = { prgs[3]->prg.nodes[0], prgs[3]->prg.nodes[1], prgs[3]->prg.nodes[3], prgs[3]->prg.nodes[4], prgs[3]->prg.nodes[5], prgs[3]->prg.nodes[7], prgs[3]->prg.nodes[9] }; EXPECT_ITERABLE_EQ(std::vector<LocalNodePtr>, vcf_ref_paths[3], exp_path3); }
39.798036
103
0.66306
rmcolq
df80bf3ba21fb892c9b0d8953540edfb0d1cbc5d
2,639
cpp
C++
main.cpp
jp-96/microbit-digital-capture2
3058f80f253220f37499b2efa3949f3696c2052f
[ "MIT" ]
null
null
null
main.cpp
jp-96/microbit-digital-capture2
3058f80f253220f37499b2efa3949f3696c2052f
[ "MIT" ]
null
null
null
main.cpp
jp-96/microbit-digital-capture2
3058f80f253220f37499b2efa3949f3696c2052f
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2021 jp-96 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 "inttypes.h" #include "MicroBit.h" #define K (uint64_t)60000000 MicroBit uBit; MicroBitPin sensorPin(MICROBIT_ID_IO_P2, MICROBIT_PIN_P2, PIN_CAPABILITY_DIGITAL); uint64_t lastFallTimestamp=0; uint32_t fallCount=0; MicroBitImage IMG_FALL("1,1,1,0,0\n0,0,1,0,0\n0,0,1,0,0\n0,0,1,0,0\n0,0,1,1,1\n"); uint64_t t[] = {0, 0, 0, 0}; void onEdgeSensorPin(MicroBitEvent e) { int cadence; int speed10; lastFallTimestamp = e.timestamp; fallCount++; t[0]=t[1]; t[1]=t[2]; t[2]=t[3]; t[3] = lastFallTimestamp; if (fallCount>3) { cadence = (int)( K* 3/(t[3]-t[0])); //speed10 = (int)( K*10/(t[3]-t[0])); speed10 = (int)( K* 9/(t[3]-t[0])); } else { cadence = 0; speed10 = 0; } uBit.serial.printf("%" PRIu32 ", %" PRIu32 ", %d, %d\r\n" , fallCount, (uint32_t)e.timestamp, cadence, speed10); } void setup(void) { uBit.serial.printf("#, Timestamp, Cadence, Speed10\r\n"); uBit.messageBus.listen(MICROBIT_ID_IO_P2, MICROBIT_PIN_EVT_FALL, onEdgeSensorPin); sensorPin.getDigitalValue(PullUp); sensorPin.eventOn(MICROBIT_PIN_EVENT_ON_EDGE); uBit.display.scrollAsync("GO!"); } int main() { // Initialise the micro:bit runtime. uBit.init(); create_fiber(setup); // If main exits, there may still be other fibers running or registered event handlers etc. // Simply release this fiber, which will mean we enter the scheduler. Worse case, we then // sit in the idle task forever, in a power efficient sleep. release_fiber(); }
30.333333
95
0.704433
jp-96
df8454f70a2fde833a5775e0ec59d08212a89e63
1,471
cpp
C++
src/filter.cpp
frankplus/Computer-Vision
f04c2bf2320fe8173f56dca2e92f810f68e6333e
[ "MIT" ]
2
2020-07-10T10:37:06.000Z
2020-07-10T11:14:22.000Z
src/filter.cpp
frankplus/Computer-Vision
f04c2bf2320fe8173f56dca2e92f810f68e6333e
[ "MIT" ]
null
null
null
src/filter.cpp
frankplus/Computer-Vision
f04c2bf2320fe8173f56dca2e92f810f68e6333e
[ "MIT" ]
null
null
null
#include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <iostream> #include "filter.h" using namespace std; using namespace cv; // constructor Filter::Filter(cv::Mat input_img, int size) { input_image = input_img; if (size % 2 == 0) size++; filter_size = size; } // for base class do nothing (in derived classes it performs the corresponding filter) void Filter::doFilter() { // it just returns a copy of the input image result_image = input_image.clone(); } // get output of the filter cv::Mat Filter::getResult() { return result_image; } //set window size (it needs to be odd) void Filter::setSize(int size) { if (size % 2 == 0) size++; filter_size = size; } //get window size int Filter::getSize() { return filter_size; } void MedianFilter::doFilter() { medianBlur(input_image, result_image, getSize()); } void GaussianFilter::doFilter() { Size kernel_size = Size(getSize(), getSize()); GaussianBlur(input_image, result_image, kernel_size, sigma, 0); } void GaussianFilter::setSigma(double sigma) { this->sigma = sigma; } void BilateralFilter::doFilter() { bilateralFilter(input_image, result_image, 9, sigma_range, sigma_space); } void BilateralFilter::setSigmaRange(double sigma_range) { this->sigma_range = sigma_range; } void BilateralFilter::setSigmaSpace(double sigma_space) { this->sigma_space = sigma_space; }
21.014286
87
0.690687
frankplus
df86b706c9105a2eef30148fc0e759ff03fd9138
8,130
hpp
C++
include/cellarium/paged_storage.hpp
ortfero/cellarium
32b6d19edb5f4110a22eb74c7f9bead8982be665
[ "MIT" ]
null
null
null
include/cellarium/paged_storage.hpp
ortfero/cellarium
32b6d19edb5f4110a22eb74c7f9bead8982be665
[ "MIT" ]
null
null
null
include/cellarium/paged_storage.hpp
ortfero/cellarium
32b6d19edb5f4110a22eb74c7f9bead8982be665
[ "MIT" ]
null
null
null
/* This file is part of cellarium library * Copyright 2020 Andrei Ilin <ortfero@gmail.com> * * 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. */ #pragma once #include <cmath> #include <filesystem> #include <system_error> #include <memory> #include <type_traits> #include "storage.hpp" #include "file_manager.hpp" namespace cellarium { template<typename T> class paged_storage { public: static_assert(std::is_trivial_v<T>, "Only trivial types can be stored"); using path_type = std::filesystem::path; using storage_type = storage<T>; using storage_ptr = std::unique_ptr<storage_type>; using value_type = T; using size_type = typename storage_type::size_type; using index_type = typename storage_type::index_type; static constexpr index_type no_index = storage_type::no_index; paged_storage() noexcept = default; ~paged_storage() { close(); } paged_storage(paged_storage const&) = delete; paged_storage& operator = (paged_storage const&) = delete; explicit operator bool () const noexcept { return pages_count_ != 0; } bool initialize(path_type const& path, size_type max_pages, header const& specified, std::error_code& ec) noexcept { bool const exists = std::filesystem::exists(path, ec); if(!!ec) return false; if(exists) return open(path, max_pages, specified, ec); else return create(path, max_pages, specified, ec); } bool create(path_type const& path, size_type max_pages, header const& specified, std::error_code& ec) { file_manager_ = file_manager{path}; max_pages_ = max_pages; page_capacity_ = specified.capacity(); if(!file_manager_::remove_all(ec)) return false; pages_ = std::make_unique<storage_ptr[]>(max_pages_); auto storage = std::make_unique<cellarium::storage>(); path_type const path = file_manager_.name_for_page(0); if(!storage->create(path, specified, ec)) return false; pages_[0] = std::move(storage); last_page_ = std::to_address(pages_[0]); last_page_base_ = 0; pages_count_ = 1; return true; } bool open(path_type const& path, size_type max_pages, header const& specified, std::error_code& ec) { file_manager_ = file_manager{path}; max_pages_ = max_pages; auto files = file_manager_.list(ec); if(!!ec) return false; if(files.empty()) return (ec = std::error_code{error::storage_not_found_to_open}), false; pages_ = std::make_unique<storage_ptr[]>(max_pages_); if(files.size() == 1) { auto storage = std::make_unique<storage_type>(); if(!storage->open(path, specified, ec)) return false; page_capacity_ = storage->header()->capacity(); pages_[0] = std::move(storage); } else { size_type total_size = 0; size_type last_storage_capacity = 0; header each_header; size_type each_size; for(auto& each_file: files) { if(!storage_type::read_info(each_file, each_header, each_size, ec)) return false; if(last_storage_capacity != 0 && last_storage_capacity != each_header.capacity()) return (ec = std::error_code{error::merging_incompatible_storages}) total_size += each_size; } files[0] = file_manager_.generate_zero_page_name(); std::filesystem::rename(path, files[0], ec); if(!!ec) return false; size_type const needed_capacity = specified.needed_capacity(total_size); header const merged_header = header::with_capacity(specified, needed_capacity); page_capacity_ = merged_header.capacity(); auto merged_storage = std::make_unique<storage_type>(); if(!merged_storage->create(path, merged_header, ec)) { std::error_code none; std::filesystem::rename(files[0], path, none); return false; } storage_type each_storage; for(auto& each_file: files) { if(!each_storage.open_to_read(each_file, specified, ec)) { std::error_code none; std::filesystem::rename(files[0], path, none); return false; } each_storage.for_each([&](value_type const& value) { merged_storage.try_insert(value); }); each_storage.close(); } for(auto& each_file: files) { std::filesystem::remove(each_file, ec); if(!!ec) return false; } pages_[0] = std::move(merged_storage); } last_page_ = std::to_address(pages_[0]); last_page_base_ = 0; pages_count_ = 1; return true; } void close() noexcept { pages_.reset(); last_page_ = nullptr; last_page_base_ = 0; file_manager_ = file_manager{}; page_capacity_ = 0; max_pages_ = 0; pages_count_ = 0; } index_type try_insert(T const& data) noexcept { index_type const inserted = last_page_->try_insert(data); if(inserted != no_index) return last_page_base_ + inserted; if(!add_page(*last_page_->header())) return no_index; return last_page_base_ + last_page_->try_insert(data); } void remove(index_type index) noexcept { if(pages_count_ == 1) return last_page_->remove(index); index_type base = index / page_capacity_; index_type offset = index % page_capacity_; pages_[base]->remove(offset); } template<typename F> void for_each(F&& f) { for(index_type i = 0; i != pages_count_; ++i) pages_[i]->for_each(std::forward<F>(f)); } template<typename F> void for_each(F&& f) const { for(index_type i = 0; i != pages_count_; ++i) pages_[i]->for_each(std::forward<F>(f)); } private: file_manager file_manager_; size_type page_capacity_{0}; size_type max_pages_{0}; size_type pages_count_{0}; std::unique_ptr<storage_ptr[]> pages_; storage* last_page_{nullptr}; size_type last_page_base_{0}; bool add_page(header const& last_header) { if(pages_count_ == max_pages_) return false; auto storage = std::make_unique<cellarium::storage>(); path_type const path = file_manager_.name_for_page(pages_count_); std::error_code ec; header new_page_header{header::with_page_number(last_header, pages_count_)}; if(!storage->create(path, new_page_header, ec)) return false; pages_[pages_count_] = std::move(storage); last_page_ = std::to_address(pages_[pages_count_]); last_page_base_ = page_capacity_ * pages_count_; ++pages_count_; return true; } }; // paged_storage } // cellarium
32.261905
100
0.628659
ortfero
df894608210b5e437c6d653b3737e4e6fa9dda47
7,153
cc
C++
GeneratorInterface/LHEInterface/plugins/LHESource.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
GeneratorInterface/LHEInterface/plugins/LHESource.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
GeneratorInterface/LHEInterface/plugins/LHESource.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
#include <algorithm> #include <functional> #include <iostream> #include <string> #include <memory> #include <boost/bind.hpp> #include <boost/ptr_container/ptr_deque.hpp> #include "FWCore/Framework/interface/InputSourceMacros.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/EventPrincipal.h" #include "FWCore/Framework/interface/LuminosityBlockPrincipal.h" #include "FWCore/Framework/interface/RunPrincipal.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/Utilities/interface/TypeID.h" #include "DataFormats/Common/interface/OrphanHandle.h" #include "SimDataFormats/GeneratorProducts/interface/LesHouches.h" #include "SimDataFormats/GeneratorProducts/interface/LHERunInfoProduct.h" #include "SimDataFormats/GeneratorProducts/interface/LHEEventProduct.h" #include "GeneratorInterface/LHEInterface/interface/LHERunInfo.h" #include "GeneratorInterface/LHEInterface/interface/LHEEvent.h" #include "GeneratorInterface/LHEInterface/interface/LHEReader.h" #include "LHESource.h" using namespace lhef; LHESource::LHESource(const edm::ParameterSet &params, const edm::InputSourceDescription &desc) : ProducerSourceFromFiles(params, desc, false), reader(new LHEReader(fileNames(), params.getUntrackedParameter<unsigned int>("skipEvents", 0))), wasMerged(false), lheProvenanceHelper_(edm::TypeID(typeid(LHEEventProduct)), edm::TypeID(typeid(LHERunInfoProduct)), productRegistryUpdate()), phid_(), runPrincipal_() { nextEvent(); lheProvenanceHelper_.lheAugment(runInfo.get()); // Initialize metadata, and save the process history ID for use every event. phid_ = lheProvenanceHelper_.lheInit(processHistoryRegistryForUpdate()); // These calls are not wanted, because the principals are used for putting the products. //produces<LHEEventProduct>(); //produces<LHERunInfoProduct, edm::InRun>(); } LHESource::~LHESource() { } void LHESource::endJob() { reader.reset(); } void LHESource::nextEvent() { if (partonLevel) { return; } bool newFileOpened; do { newFileOpened = false; partonLevel = reader->next(&newFileOpened); } while (newFileOpened && !partonLevel); if (!partonLevel) { return; } boost::shared_ptr<LHERunInfo> runInfoThis = partonLevel->getRunInfo(); if (runInfoThis != runInfoLast) { runInfo = runInfoThis; runInfoLast = runInfoThis; } if (runInfo) { std::auto_ptr<LHERunInfoProduct> product( new LHERunInfoProduct(*runInfo->getHEPRUP())); std::for_each(runInfo->getHeaders().begin(), runInfo->getHeaders().end(), boost::bind( &LHERunInfoProduct::addHeader, product.get(), _1)); std::for_each(runInfo->getComments().begin(), runInfo->getComments().end(), boost::bind(&LHERunInfoProduct::addComment, product.get(), _1)); if (!runInfoProducts.empty()) { if (runInfoProducts.front().mergeProduct(*product)) { if (!wasMerged) { runInfoProducts.pop_front(); runInfoProducts.push_front(product); wasMerged = true; } } else { lheProvenanceHelper_.lheAugment(runInfo.get()); // Initialize metadata, and save the process history ID for use every event. phid_ = lheProvenanceHelper_.lheInit(processHistoryRegistryForUpdate()); resetRunAuxiliary(); } } runInfo.reset(); } } // This is the only way we can now access the run principal. void LHESource::readRun_(edm::RunPrincipal& runPrincipal) { runAuxiliary()->setProcessHistoryID(phid_); runPrincipal.fillRunPrincipal(processHistoryRegistryForUpdate()); runPrincipal_ = &runPrincipal; } void LHESource::readLuminosityBlock_(edm::LuminosityBlockPrincipal& lumiPrincipal) { luminosityBlockAuxiliary()->setProcessHistoryID(phid_); lumiPrincipal.fillLuminosityBlockPrincipal(processHistoryRegistryForUpdate()); } void LHESource::beginRun(edm::Run&) { if (runInfoLast) { runInfo = runInfoLast; std::unique_ptr<LHERunInfoProduct> product( new LHERunInfoProduct(*runInfo->getHEPRUP())); std::for_each(runInfo->getHeaders().begin(), runInfo->getHeaders().end(), boost::bind( &LHERunInfoProduct::addHeader, product.get(), _1)); std::for_each(runInfo->getComments().begin(), runInfo->getComments().end(), boost::bind(&LHERunInfoProduct::addComment, product.get(), _1)); // keep a copy around in case of merging runInfoProducts.push_back(new LHERunInfoProduct(*product)); wasMerged = false; std::unique_ptr<edm::WrapperBase> rdp(new edm::Wrapper<LHERunInfoProduct>(std::move(product))); runPrincipal_->put(lheProvenanceHelper_.runProductBranchDescription_, std::move(rdp)); runInfo.reset(); } } void LHESource::endRun(edm::Run&) { if (!runInfoProducts.empty()) { std::unique_ptr<LHERunInfoProduct> product( runInfoProducts.pop_front().release()); std::unique_ptr<edm::WrapperBase> rdp(new edm::Wrapper<LHERunInfoProduct>(std::move(product))); runPrincipal_->put(lheProvenanceHelper_.runProductBranchDescription_, std::move(rdp)); } runPrincipal_ = nullptr; } bool LHESource::setRunAndEventInfo(edm::EventID&, edm::TimeValue_t&, edm::EventAuxiliary::ExperimentType&) { nextEvent(); if (!partonLevel) { // We just finished an input file. See if there is another. nextEvent(); if (!partonLevel) { // No more input files. return false; } } return true; } void LHESource::readEvent_(edm::EventPrincipal& eventPrincipal) { assert(eventCached() || processingMode() != RunsLumisAndEvents); edm::EventAuxiliary aux(eventID(), processGUID(), edm::Timestamp(presentTime()), false); aux.setProcessHistoryID(phid_); eventPrincipal.fillEventPrincipal(aux, processHistoryRegistryForUpdate()); std::unique_ptr<LHEEventProduct> product( new LHEEventProduct(*partonLevel->getHEPEUP(), partonLevel->originalXWGTUP()) ); if (partonLevel->getPDF()) { product->setPDF(*partonLevel->getPDF()); } std::for_each(partonLevel->weights().begin(), partonLevel->weights().end(), boost::bind(&LHEEventProduct::addWeight, product.get(), _1)); product->setScales(partonLevel->scales()); product->setNpLO(partonLevel->npLO()); product->setNpNLO(partonLevel->npNLO()); std::for_each(partonLevel->getComments().begin(), partonLevel->getComments().end(), boost::bind(&LHEEventProduct::addComment, product.get(), _1)); std::unique_ptr<edm::WrapperBase> edp(new edm::Wrapper<LHEEventProduct>(std::move(product))); eventPrincipal.put(lheProvenanceHelper_.eventProductBranchDescription_, std::move(edp), lheProvenanceHelper_.eventProductProvenance_); partonLevel.reset(); resetEventCached(); } DEFINE_FWK_INPUT_SOURCE(LHESource);
33.115741
135
0.694674
pasmuss
df89d2c08fe187fe049d534e8deed96f55c32fb7
11,811
cpp
C++
hip/matrix/dense_kernels.hip.cpp
flipflapflop/ginkgo
876234e142a0f5bb2a85bb1dd2cc488c3c5d6206
[ "BSD-3-Clause" ]
null
null
null
hip/matrix/dense_kernels.hip.cpp
flipflapflop/ginkgo
876234e142a0f5bb2a85bb1dd2cc488c3c5d6206
[ "BSD-3-Clause" ]
null
null
null
hip/matrix/dense_kernels.hip.cpp
flipflapflop/ginkgo
876234e142a0f5bb2a85bb1dd2cc488c3c5d6206
[ "BSD-3-Clause" ]
null
null
null
/*******************************<GINKGO LICENSE>****************************** Copyright (c) 2017-2019, the Ginkgo authors 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 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. ******************************<GINKGO LICENSE>*******************************/ #include "core/matrix/dense_kernels.hpp" #include <hip/hip_complex.h> #include <hip/hip_runtime.h> #include <hip/math_functions.h> #include <ginkgo/core/base/range_accessors.hpp> #include <ginkgo/core/matrix/coo.hpp> #include <ginkgo/core/matrix/csr.hpp> #include <ginkgo/core/matrix/ell.hpp> #include <ginkgo/core/matrix/sellp.hpp> #include "hip/base/hipblas_bindings.hip.hpp" #include "hip/components/uninitialized_array.hip.hpp" namespace gko { namespace kernels { namespace hip { /** * @brief The Dense matrix format namespace. * * @ingroup dense */ namespace dense { constexpr auto default_block_size = 512; template <typename ValueType> void simple_apply(std::shared_ptr<const HipExecutor> exec, const matrix::Dense<ValueType> *a, const matrix::Dense<ValueType> *b, matrix::Dense<ValueType> *c) GKO_NOT_IMPLEMENTED; GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(GKO_DECLARE_DENSE_SIMPLE_APPLY_KERNEL); template <typename ValueType> void apply(std::shared_ptr<const HipExecutor> exec, const matrix::Dense<ValueType> *alpha, const matrix::Dense<ValueType> *a, const matrix::Dense<ValueType> *b, const matrix::Dense<ValueType> *beta, matrix::Dense<ValueType> *c) GKO_NOT_IMPLEMENTED; GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(GKO_DECLARE_DENSE_APPLY_KERNEL); template <typename ValueType> void scale(std::shared_ptr<const HipExecutor> exec, const matrix::Dense<ValueType> *alpha, matrix::Dense<ValueType> *x) GKO_NOT_IMPLEMENTED; GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(GKO_DECLARE_DENSE_SCALE_KERNEL); template <typename ValueType> void add_scaled(std::shared_ptr<const HipExecutor> exec, const matrix::Dense<ValueType> *alpha, const matrix::Dense<ValueType> *x, matrix::Dense<ValueType> *y) GKO_NOT_IMPLEMENTED; GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(GKO_DECLARE_DENSE_ADD_SCALED_KERNEL); template <typename ValueType> void compute_dot(std::shared_ptr<const HipExecutor> exec, const matrix::Dense<ValueType> *x, const matrix::Dense<ValueType> *y, matrix::Dense<ValueType> *result) { if (hipblas::is_supported<ValueType>::value) { // TODO: write a custom kernel which does this more efficiently for (size_type col = 0; col < x->get_size()[1]; ++col) { hipblas::dot(exec->get_hipblas_handle(), x->get_size()[0], x->get_const_values() + col, x->get_stride(), y->get_const_values() + col, y->get_stride(), result->get_values() + col); } } else { // TODO: implement this GKO_NOT_IMPLEMENTED; } } GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(GKO_DECLARE_DENSE_COMPUTE_DOT_KERNEL); namespace kernel { template <typename ValueType> __global__ __launch_bounds__(default_block_size) void compute_sqrt( size_type num_cols, ValueType *__restrict__ work) { const auto tidx = static_cast<size_type>(blockDim.x) * blockIdx.x + threadIdx.x; if (tidx < num_cols) { work[tidx] = sqrt(abs(work[tidx])); } } } // namespace kernel template <typename ValueType> void compute_norm2(std::shared_ptr<const HipExecutor> exec, const matrix::Dense<ValueType> *x, matrix::Dense<ValueType> *result) { if (hipblas::is_supported<ValueType>::value) { for (size_type col = 0; col < x->get_size()[1]; ++col) { hipblas::norm2(exec->get_hipblas_handle(), x->get_size()[0], x->get_const_values() + col, x->get_stride(), result->get_values() + col); } } else { compute_dot(exec, x, x, result); const dim3 block_size(default_block_size, 1, 1); const dim3 grid_size(ceildiv(result->get_size()[1], block_size.x), 1, 1); hipLaunchKernelGGL(kernel::compute_sqrt, dim3(grid_size), dim3(block_size), 0, 0, result->get_size()[1], as_hip_type(result->get_values())); } } GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(GKO_DECLARE_DENSE_COMPUTE_NORM2_KERNEL); template <typename ValueType, typename IndexType> void convert_to_coo(std::shared_ptr<const HipExecutor> exec, matrix::Coo<ValueType, IndexType> *result, const matrix::Dense<ValueType> *source) GKO_NOT_IMPLEMENTED; GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE( GKO_DECLARE_DENSE_CONVERT_TO_COO_KERNEL); template <typename ValueType, typename IndexType> void convert_to_csr(std::shared_ptr<const HipExecutor> exec, matrix::Csr<ValueType, IndexType> *result, const matrix::Dense<ValueType> *source) GKO_NOT_IMPLEMENTED; GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE( GKO_DECLARE_DENSE_CONVERT_TO_CSR_KERNEL); template <typename ValueType, typename IndexType> void convert_to_ell(std::shared_ptr<const HipExecutor> exec, matrix::Ell<ValueType, IndexType> *result, const matrix::Dense<ValueType> *source) GKO_NOT_IMPLEMENTED; GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE( GKO_DECLARE_DENSE_CONVERT_TO_ELL_KERNEL); template <typename ValueType, typename IndexType> void convert_to_hybrid(std::shared_ptr<const HipExecutor> exec, matrix::Hybrid<ValueType, IndexType> *result, const matrix::Dense<ValueType> *source) GKO_NOT_IMPLEMENTED; GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE( GKO_DECLARE_DENSE_CONVERT_TO_HYBRID_KERNEL); template <typename ValueType, typename IndexType> void convert_to_sellp(std::shared_ptr<const HipExecutor> exec, matrix::Sellp<ValueType, IndexType> *result, const matrix::Dense<ValueType> *source) GKO_NOT_IMPLEMENTED; GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE( GKO_DECLARE_DENSE_CONVERT_TO_SELLP_KERNEL); template <typename ValueType, typename IndexType> void convert_to_sparsity_csr(std::shared_ptr<const HipExecutor> exec, matrix::SparsityCsr<ValueType, IndexType> *result, const matrix::Dense<ValueType> *source) GKO_NOT_IMPLEMENTED; GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE( GKO_DECLARE_DENSE_CONVERT_TO_SPARSITY_CSR_KERNEL); template <typename ValueType> void count_nonzeros(std::shared_ptr<const HipExecutor> exec, const matrix::Dense<ValueType> *source, size_type *result) GKO_NOT_IMPLEMENTED; GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(GKO_DECLARE_DENSE_COUNT_NONZEROS_KERNEL); template <typename ValueType> void calculate_max_nnz_per_row(std::shared_ptr<const HipExecutor> exec, const matrix::Dense<ValueType> *source, size_type *result) GKO_NOT_IMPLEMENTED; GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE( GKO_DECLARE_DENSE_CALCULATE_MAX_NNZ_PER_ROW_KERNEL); template <typename ValueType, typename IndexType> void row_permute(std::shared_ptr<const HipExecutor> exec, const Array<IndexType> *permutation_indices, matrix::Dense<ValueType> *row_permuted, const matrix::Dense<ValueType> *orig) GKO_NOT_IMPLEMENTED; GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE(GKO_DECLARE_ROW_PERMUTE_KERNEL); template <typename ValueType, typename IndexType> void column_permute(std::shared_ptr<const HipExecutor> exec, const Array<IndexType> *permutation_indices, matrix::Dense<ValueType> *column_permuted, const matrix::Dense<ValueType> *orig) GKO_NOT_IMPLEMENTED; GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE( GKO_DECLARE_COLUMN_PERMUTE_KERNEL); template <typename ValueType, typename IndexType> void inverse_row_permute(std::shared_ptr<const HipExecutor> exec, const Array<IndexType> *permutation_indices, matrix::Dense<ValueType> *row_permuted, const matrix::Dense<ValueType> *orig) GKO_NOT_IMPLEMENTED; GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE( GKO_DECLARE_INVERSE_ROW_PERMUTE_KERNEL); template <typename ValueType, typename IndexType> void inverse_column_permute(std::shared_ptr<const HipExecutor> exec, const Array<IndexType> *permutation_indices, matrix::Dense<ValueType> *column_permuted, const matrix::Dense<ValueType> *orig) GKO_NOT_IMPLEMENTED; GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE( GKO_DECLARE_INVERSE_COLUMN_PERMUTE_KERNEL); template <typename ValueType> void calculate_nonzeros_per_row(std::shared_ptr<const HipExecutor> exec, const matrix::Dense<ValueType> *source, Array<size_type> *result) GKO_NOT_IMPLEMENTED; GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE( GKO_DECLARE_DENSE_CALCULATE_NONZEROS_PER_ROW_KERNEL); template <typename ValueType> void calculate_total_cols(std::shared_ptr<const HipExecutor> exec, const matrix::Dense<ValueType> *source, size_type *result, size_type stride_factor, size_type slice_size) GKO_NOT_IMPLEMENTED; GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE( GKO_DECLARE_DENSE_CALCULATE_TOTAL_COLS_KERNEL); template <typename ValueType> void transpose(std::shared_ptr<const HipExecutor> exec, matrix::Dense<ValueType> *trans, const matrix::Dense<ValueType> *orig) GKO_NOT_IMPLEMENTED; GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(GKO_DECLARE_TRANSPOSE_KERNEL); template <typename ValueType> void conj_transpose(std::shared_ptr<const HipExecutor> exec, matrix::Dense<ValueType> *trans, const matrix::Dense<ValueType> *orig) GKO_NOT_IMPLEMENTED; GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(GKO_DECLARE_CONJ_TRANSPOSE_KERNEL); } // namespace dense } // namespace hip } // namespace kernels } // namespace gko
36.680124
80
0.698671
flipflapflop
df8e164c1ab2a07de0eca43a3eaa9c989dd42fbf
1,074
hpp
C++
src/Namespace.hpp
degustaf/lisp-compiler
e176d5b07d68456b07fda516b722213b07f46248
[ "MIT" ]
null
null
null
src/Namespace.hpp
degustaf/lisp-compiler
e176d5b07d68456b07fda516b722213b07f46248
[ "MIT" ]
null
null
null
src/Namespace.hpp
degustaf/lisp-compiler
e176d5b07d68456b07fda516b722213b07f46248
[ "MIT" ]
null
null
null
#ifndef NAMESPACE_HPP #define NAMESPACE_HPP #include "Interfaces.hpp" #include <map> #include "AReference.hpp" #include "Symbol.hpp" class Namespace : public AReference, public IReference_inherit<Namespace>, public std::enable_shared_from_this<Namespace> { public: const std::shared_ptr<const Symbol> name; virtual std::string toString(void) const; virtual std::shared_ptr<const IMap> resetMeta(std::shared_ptr<const IMap> m) {IMeta::_meta = m; return m;}; static std::shared_ptr<Namespace> findOrCreate(std::shared_ptr<const Symbol> name); private: std::shared_ptr<const IMap> mappings; std::shared_ptr<const IMap> aliases; static std::map<std::shared_ptr<const Symbol>, std::shared_ptr<Namespace> > namespaces; Namespace(std::shared_ptr<const Symbol> name) : IReference_inherit<Namespace>(name->meta()), name(name), mappings(NULL), aliases(NULL) /* TODO mappings.set(RT.DEFAULT_IMPORTS); aliases.set(RT.map()); */ {}; virtual std::shared_ptr<const Namespace> with_meta_impl(std::shared_ptr<const IMap>) const; }; #endif /* NAMESPACE_HPP */
34.645161
123
0.748603
degustaf
df8f289b23ea2b7ae77d5a04940c2d1055c8af43
1,151
cpp
C++
src/stl_generate/main.cpp
MaksimPopp/STL_practice_UNN_381906-3
83dedf756b170b4ce89e0c74e615bbfd72c4e0a7
[ "Apache-2.0" ]
null
null
null
src/stl_generate/main.cpp
MaksimPopp/STL_practice_UNN_381906-3
83dedf756b170b4ce89e0c74e615bbfd72c4e0a7
[ "Apache-2.0" ]
1
2020-12-12T09:55:31.000Z
2020-12-12T11:04:55.000Z
src/stl_generate/main.cpp
MaksimPopp/STL_practice_UNN_381906-3
83dedf756b170b4ce89e0c74e615bbfd72c4e0a7
[ "Apache-2.0" ]
12
2020-12-12T09:42:22.000Z
2020-12-19T11:44:27.000Z
//Лазарев Алексей //Вместо того чтобы использовать постоянное значение для заполнения //контейнера, иногда желательно вычислить свое значение для каждого элемента //Это можно сделать с помощью алгоритма generate(породить). #include <iostream> #include <string> #include <algorithm> #include <iterator> #include <list> using namespace std; //В качестве третьего параметра этого алгоритма выступает функция или функциональный объект. //Следующая программа помещает значения 10, 12, 16 и 18 в массив а: struct funobj { //можно было использовать функцию вместо функционального объкета, но есть тонкость int i; funobj() : i(8) {} int operator ()() { return i += 2; } }; int fun() { static int i = 8; return i += 2; } int main() { setlocale(LC_ALL, "Russian"); int a[5]; generate(a, a + 5, funobj()); copy(a, a + 5, ostream_iterator<int>(cout, " ")); cout << endl;//вывод: 10 12 14 16 18 //_________________________________________________________________________________________ list<int> b(5); generate_n(b.begin(), 5, fun); copy(b.begin(), b.end(), ostream_iterator<int>(cout, " ")); cout << endl;//вывод: 10 12 14 16 18 return 0; }
28.775
98
0.720243
MaksimPopp
df9b20f5d86c7d0add80f831eeaaa97d55a8983b
1,133
cpp
C++
offer/problem034/Solution.cpp
MyYaYa/leetcode
d779c215516ede594267b15abdfba5a47dc879dd
[ "Apache-2.0" ]
1
2016-09-29T14:23:59.000Z
2016-09-29T14:23:59.000Z
offer/problem034/Solution.cpp
MyYaYa/leetcode
d779c215516ede594267b15abdfba5a47dc879dd
[ "Apache-2.0" ]
null
null
null
offer/problem034/Solution.cpp
MyYaYa/leetcode
d779c215516ede594267b15abdfba5a47dc879dd
[ "Apache-2.0" ]
null
null
null
class Solution { public: vector<int> GetLeastNumbers_Solution(vector<int> input, int k) { if (input.empty() || k == 0 || k > input.size()) return vector<int>(); int left = 0, right = input.size() - 1; int index = Partition(input, left, right); while (index != (k-1)) { if (index < k - 1) { left = index + 1; index = Partition(input, left, right); } else { right = index - 1; index = Partition(input, left, right); } } vector<int> result; for (int i = 0; i < k; i++) { result.push_back(input[i]); } return result; } int Partition(vector<int>& numbers, int left, int right) { int i = left, j = right; int pivot = numbers[left]; while (i < j) { while (i < j && numbers[j] >= pivot) j--; numbers[i] = numbers[j]; while (i < j && numbers[i] < pivot) i++; numbers[j] = numbers[i]; } // assert i == j numbers[i] = pivot; return i; } };
32.371429
79
0.44925
MyYaYa
df9dc069bf88d219dd9444b43c1a0b4a22806ce4
3,363
hpp
C++
Engine/Utilities/UtilityAssert.hpp
jcolwell/ogl
efa8404a25fb7a23bf5951f798a3970134e15386
[ "Unlicense" ]
null
null
null
Engine/Utilities/UtilityAssert.hpp
jcolwell/ogl
efa8404a25fb7a23bf5951f798a3970134e15386
[ "Unlicense" ]
null
null
null
Engine/Utilities/UtilityAssert.hpp
jcolwell/ogl
efa8404a25fb7a23bf5951f798a3970134e15386
[ "Unlicense" ]
null
null
null
#ifndef _ASSERT_UTILITIES_H_ #define _ASSERT_UTILITIES_H_ //================================================================================== // File: UtilityAssert.h // Desc: //================================================================================== //================================================================================== // INCLUDES //================================================================================== #if defined (_WIN32) #include <Windows.h> #endif #include <cassert> #include <string> //================================================================================== // ASSERT //================================================================================== //---------------------------------------------------------------------------------- #if defined(_DEBUG) && defined (_WIN32) //---------------------------------------------------------------------------------- //Windows Platform #include <Windows.h> #define LOG(format, ...)\ {\ {\ char buffer[1024];\ sprintf_s(buffer, 1024, (#format), __VA_ARGS__);\ std::string message;\ message += (buffer);\ message += "\n";\ OutputDebugStringA(message.c_str());\ }\ } //---------------------------------------------------------------------------------- #define ASSERT(condition, format, ...)\ {\ if (!(condition))\ {\ LOG(format, __VA_ARGS__)\ DebugBreak();\ }\ } # //---------------------------------------------------------------------------------- #elif defined(_DEBUG) && defined (__APPLE__ && __MACH__) //---------------------------------------------------------------------------------- // Apple Platform #include <TargetConditionals.h> #if TARGET_IPHONE_SIMULATOR == 1 //---------------------------------------------------------------------------------- // iOS in Xcode simulator #define ASSERT(condition, format, ...) #elif TARGET_OS_IPHONE == 1 //---------------------------------------------------------------------------------- // iOS on iPhone, iPad, etc. #define ASSERT(condition, format, ...) #elif TARGET_OS_MAC == 1 //---------------------------------------------------------------------------------- // OSX #define ASSERT(condition, format, ...) //---------------------------------------------------------------------------------- #endif //---------------------------------------------------------------------------------- #elif defined(_DEBUG) && defined (__linux__) //---------------------------------------------------------------------------------- //Linux Platform! #define ASSERT(condition, format, ...) //---------------------------------------------------------------------------------- #elif defined(_DEBUG) && defined (__Android__) //---------------------------------------------------------------------------------- //Android ! #define ASSERT(condition, format, ...) //---------------------------------------------------------------------------------- #else //---------------------------------------------------------------------------------- #define ASSERT(condition, format, ...) //---------------------------------------------------------------------------------- #endif //---------------------------------------------------------------------------------- //================================================================================== #endif //!_COMMON_UTILITIES_H_
33.29703
84
0.262266
jcolwell
dfa42ef17f2e15beb8be0f47bd78b9ecd471fcb1
7,615
cxx
C++
src/PSdraw.cxx
fermi-lat/gui
d2387b2d9f2bbde3a9310ff8f2cca038a339ebf6
[ "BSD-3-Clause" ]
null
null
null
src/PSdraw.cxx
fermi-lat/gui
d2387b2d9f2bbde3a9310ff8f2cca038a339ebf6
[ "BSD-3-Clause" ]
null
null
null
src/PSdraw.cxx
fermi-lat/gui
d2387b2d9f2bbde3a9310ff8f2cca038a339ebf6
[ "BSD-3-Clause" ]
null
null
null
// $Header: /nfs/slac/g/glast/ground/cvs/GlastRelease-scons/gui/src/PSdraw.cxx,v 1.1.1.1 2001/01/04 01:01:11 burnett Exp $ // PostScript drawer imlementation // created by Hardy, 28 Mar 94 #include "PSdraw.h" #include "gui/DisplayRep.h" #include <cstring> #include <iostream> #include <iomanip> namespace gui { static int markerSize = 10; inline int PSdraw::xwin(float x) { return (int)((x+1)*currentQuad.dx/2) + currentQuad.x; } inline int PSdraw::ywin(float y) { return (int)((y+1)*currentQuad.dy/2) + currentQuad.y; } struct PSdraw::PageFormat { const char *format; int ptXsize; int ptYsize; static const PageFormat *liste; static void lookUp (const char *_format, int *_ptXsize, int *_ptYsize); }; void PSdraw::PageFormat::lookUp (const char *_format, int *_ptXsize, int *_ptYsize) { for (int i=0; liste[i].format; i++) { if (strcmp(liste[i].format, _format)==0) { *_ptXsize = liste[i].ptXsize; *_ptYsize = liste[i].ptYsize; return; } } *_ptXsize = liste[0].ptXsize; *_ptYsize = liste[0].ptYsize; return; } static const PSdraw::PageFormat formatListe[] = { { "DinA4", 2100, 2970 }, { "DinA4-quer", 2970, 2100 }, { 0, 0, 0 } }; const PSdraw::PageFormat *PSdraw::PageFormat::liste = formatListe; static const char *psInitString = "%!PS-Adobe-2.0\n" "%%Title: gui-Display (Portrait A 4)\n" "%%Pages: atend\n" "%%Creator: Hardy's PS-Printer 08.15\n" "%%CreationDate: 94/03/28 10.13\n" "%%EndComments\n" "/s {stroke} def /l {lineto} def /m {moveto} def /t {translate} def\n" "/sw {stringwidth} def /r {rlineto} def /rl {roll} def\n" "/gr {grestore} def\n" "/c {setrgbcolor} def /lw {setlinewidth} def /sd {setdash} def\n" "/cl {closepath} def /sf {scalefont setfont} def\n" "/rgb {setrgbcolor} def\n" "\n" "/Helvetica findfont\n" "30 scalefont\n" // THB: was 10 "setfont\n" "0.28346456 0.28346456 scale\n" // change to 1/10 mm "1 setlinewidth\n" "gsave\n"; static const char *psFlushString = ""; static const char *psCloseString = "\ngrestore\n" "showpage gr\n" "%%Trailer\n" "%%Pages: 1\n" "gr gr\n" "%%EOF\n"; PSdraw::PSdraw (const char *filename, const char *page_format) : psfile( filename ) { // send initstring psfile << psInitString; // get format for mapping PageFormat::lookUp (page_format, &screenWidth, &screenHeight); // preserve aspect ratio flSingle = 1; resize(screenWidth, screenHeight); // no stroke necessary, yest isStrokePending = 0; } PSdraw::~PSdraw() { flush (); psfile << psCloseString; psfile.flush(); } void PSdraw::draw_string (float x, float y, const char *string, int size) { move_to (x,y); draw_string (string, size); } void PSdraw::draw_string (const char* string, int /*size*/) { psfile << "(" << string << ") show\n"; } void PSdraw::move_to (float x, float y) { lastx = xwin(x); lasty = ywin(y); if (isStrokePending) { psfile << " s\n"; isStrokePending = 0; } psfile << " " << lastx << " " << lasty << " m"; } void PSdraw::line_to (float x, float y) { int thisx = xwin(x); int thisy = ywin(y); psfile << " " << thisx << " " << thisy << " l"; isStrokePending = 1; lastx = thisx; lasty = thisy; } void PSdraw::flush () { if (isStrokePending) { psfile << " s\n"; isStrokePending = 0; } psfile << psFlushString; psfile.flush (); } void PSdraw::draw_marker (float x, float y) { if (isStrokePending) { psfile << " s\n"; isStrokePending = 0; } int thisx = xwin(x); int thisy = ywin(y); psfile << " " << thisx-markerSize << " " << thisy+markerSize << " m"; psfile << " " << thisx+markerSize << " " << thisy-markerSize << " l"; psfile << " " << thisx-markerSize << " " << thisy-markerSize << " m"; psfile << " " << thisx+markerSize << " " << thisy+markerSize << " l"; psfile << " " << lastx << " " << lasty << " m"; } void PSdraw::set_quad (int quadnr, const char * title, int /*_selected*/) { if (quadnr==0) { flSingle = 1; currentQuad = screen; } else { flSingle = 0; currentQuad = quadrant [selected = quadnr-1]; } // clear background of view ? // show clipping rectangle psfile << "\ngrestore " << currentQuad.x << ' ' << currentQuad.y << " m " << currentQuad.dx << ' ' << 0 << " r " << 0 << ' ' << currentQuad.dy << " r " << -currentQuad.dx << ' ' << 0 << " r " << " closepath stroke\n"; // set clipping for view psfile << "gsave " << currentQuad.x << ' ' << currentQuad.y << " m " << currentQuad.dx << ' ' << 0 << " r " << 0 << ' ' << currentQuad.dy << " r " << -currentQuad.dx << ' ' << 0 << " r " << " closepath clip\n"; // enter title psfile << xwin(-0.9f) << ' ' << ywin(-0.9f) << " m\n"; // rmoveto\n"; psfile << '('<<title << ") show\n"; // NOTE: should scan for parens } void PSdraw::resize (int xsize, int ysize) { int xoffset = 0; int yoffset = 0; if (ysize > xsize) { yoffset = (ysize-xsize) / 2; ysize = xsize; } else { xoffset = (xsize-ysize) / 2; xsize = ysize; } screen.x = 0; screen.y = 0; screen.dx = xsize; screen.dy = ysize; quadrant[0].x = 0; quadrant[0].y = 0; quadrant[0].dx = xsize/2; quadrant[0].dy = ysize/2; quadrant[1].x = xsize/2+1; quadrant[1].y = 0; quadrant[1].dx = xsize/2; quadrant[1].dy = ysize/2; quadrant[2].x = 0; quadrant[2].y = ysize/2+1; quadrant[2].dx = xsize/2; quadrant[2].dy = ysize/2; quadrant[3].x = xsize/2+1; quadrant[3].y = ysize/2+1; quadrant[3].dx = xsize/2; quadrant[3].dy = ysize/2; screen.x += xoffset; screen.y += yoffset; quadrant[0].x += xoffset; quadrant[0].y += yoffset; quadrant[1].x += xoffset; quadrant[1].y += yoffset; quadrant[2].x += xoffset; quadrant[2].y += yoffset; quadrant[3].x += xoffset; quadrant[3].y += yoffset; if (flSingle) currentQuad = screen; else currentQuad = quadrant[selected]; } void PSdraw::set_defaults () { //XSetLineAttributes(mydisplay, // DefaultGC (mydisplay, myscreen), // 1, // LineSolid, // CapButt, // JoinMiter); //if (useColor) // XSetForeground(mydisplay, DefaultGC(mydisplay,myscreen), color_black.pixel); } void PSdraw::set_line_style (int /*style*/) { //XSetLineAttributes(mydisplay, // DefaultGC (mydisplay, myscreen), // 1, // linewidth // style, // CapButt, // JoinMiter); } //---------------------------------------------------------------- // color //---------------------------------------------------------------- void PSdraw::set_rgb(float r,float g,float b) { psfile << std::setprecision(3) << ' ' << r/255. << ' ' << g/255. << ' ' << b/255. << " rgb\n"; } void PSdraw::set_col_index(int i) { DisplayRep::ColorInfo& cinfo = DisplayRep::pallete[i]; set_rgb(cinfo.r, cinfo.g, cinfo.b ); } }//namespace gui
23.796875
123
0.522521
fermi-lat
dfadbc755bfff32602ea68f8a30f542881f124d2
3,159
cpp
C++
SVIEngine/jni/SVI/Animation/Transition/SVIWizzleEffector.cpp
Samsung/SVIEngine
36964f5b296317a3b7b2825137fef921a8c94973
[ "Apache-2.0" ]
27
2015-04-24T07:14:55.000Z
2020-01-24T16:16:37.000Z
SVIEngine/jni/SVI/Animation/Transition/SVIWizzleEffector.cpp
Lousnote5/SVIEngine
36964f5b296317a3b7b2825137fef921a8c94973
[ "Apache-2.0" ]
null
null
null
SVIEngine/jni/SVI/Animation/Transition/SVIWizzleEffector.cpp
Lousnote5/SVIEngine
36964f5b296317a3b7b2825137fef921a8c94973
[ "Apache-2.0" ]
15
2015-12-08T14:46:19.000Z
2020-01-21T19:26:41.000Z
#include "SVIWizzleEffector.h" #include "SVITransitionEffector.h" #include "../SVIKeyFrameAnimation.h" namespace SVI{ static const SVIBool DEBUG = SVIFALSE; SVIWizzleEffector::SVIWizzleEffector(SVIGLSurface *surface): SVITransitionEffector(surface), mSetEffectTime(0){ } void SVIWizzleEffector::setAnimation(){ setEffectTimeLine(); SVIAnimationSet* fromAniSet = new SVIAnimationSet(mSVIGLSurface); fromAniSet->mDuration = mFullTimeDuration; fromAniSet->mRepeatCount = mRepeatCount; fromAniSet->mOffset = mOffsetDuration + mGlovalOffsetDuration; fromAniSet->mAutoReverse = mAutoReverse; fromAniSet->setInterpolator(SVIAnimation::SINEEASEINOUT); fromAniSet->shareAnimationInfo(true); SVIAnimationSet* toAniSet = new SVIAnimationSet(mSVIGLSurface); toAniSet->mDuration = mFullTimeDuration; toAniSet->mRepeatCount = mRepeatCount; toAniSet->mOffset = mOffsetDuration + mGlovalOffsetDuration; toAniSet->mAutoReverse = mAutoReverse; toAniSet->setInterpolator(SVIAnimation::SINEEASEINOUT); toAniSet->shareAnimationInfo(true); SVIKeyFrameAnimation* fromWizzleAni = SVIKeyFrameAnimation::create(SVIPropertyAnimation::RTE_RATIO, mSVIGLSurface); fromWizzleAni->mDuration = fromAniSet->mDuration; fromWizzleAni->mRepeatCount = fromAniSet->mRepeatCount; fromWizzleAni->mAutoReverse = fromAniSet->mAutoReverse; fromWizzleAni->mOffset = fromAniSet->mOffset; fromWizzleAni->addKeyProperty(SVIKeyFrameProperty(0.0f, SVIVector3(40.0f, 0.0f, 0.0f))); fromWizzleAni->addKeyProperty(SVIKeyFrameProperty(0.25f, SVIVector3(40.0f, 0.005f, mSetEffectTime * 1.0f))); fromWizzleAni->addKeyProperty(SVIKeyFrameProperty(0.5f, SVIVector3(40.0f, 0.01f, mSetEffectTime * 2.0f))); fromWizzleAni->addKeyProperty(SVIKeyFrameProperty(0.75f, SVIVector3(40.0f, 0.005f, mSetEffectTime * 3.0f))); fromWizzleAni->addKeyProperty(SVIKeyFrameProperty(1.0f, SVIVector3(40.0f, 0.0f, mSetEffectTime * 4.0f))); SVIKeyFrameAnimation* toWizzleAni = SVIKeyFrameAnimation::create(SVIPropertyAnimation::RTE_RATIO, mSVIGLSurface); toWizzleAni->mDuration = toAniSet->mDuration; toWizzleAni->mRepeatCount = toAniSet->mRepeatCount; toWizzleAni->mAutoReverse = toAniSet->mAutoReverse; toWizzleAni->mOffset = fromAniSet->mOffset; toWizzleAni->addKeyProperty(SVIKeyFrameProperty(0.0f, SVIVector3(40.0f, 0.00f, 0.0f))); toWizzleAni->addKeyProperty(SVIKeyFrameProperty(0.25f, SVIVector3(40.0f, 0.005f, mSetEffectTime * 1.0f))); toWizzleAni->addKeyProperty(SVIKeyFrameProperty(0.5f, SVIVector3(40.0f, 0.01f, mSetEffectTime * 2.0f))); toWizzleAni->addKeyProperty(SVIKeyFrameProperty(0.75f, SVIVector3(40.0f, 0.005f, mSetEffectTime * 3.0f))); toWizzleAni->addKeyProperty(SVIKeyFrameProperty(1.0f, SVIVector3(40.0f, 0.0f, mSetEffectTime * 4.0f))); fromAniSet->addAnimation(fromWizzleAni); toAniSet->addAnimation(toWizzleAni); addOpacityAnimation(fromAniSet, 1.0f, 0.0f, mFullTimeDuration, mOffsetDuration + mGlovalOffsetDuration); mFromNslide[0][0]->addAnimation(fromAniSet); mToNslide[0][0]->addAnimation(toAniSet); } void SVIWizzleEffector::setEffectTimeLine(){ mSetEffectTime = mFullTimeDuration * 0.000125f; } }
44.492958
117
0.785375
Samsung
dfae754a66d0efea997b031c554bc750df35fb75
353
cpp
C++
soapy/src/driver/HiggsTDMA.cpp
siglabsoss/s-modem
0a259b4f3207dd043c198b76a4bc18c8529bcf44
[ "BSD-3-Clause" ]
null
null
null
soapy/src/driver/HiggsTDMA.cpp
siglabsoss/s-modem
0a259b4f3207dd043c198b76a4bc18c8529bcf44
[ "BSD-3-Clause" ]
null
null
null
soapy/src/driver/HiggsTDMA.cpp
siglabsoss/s-modem
0a259b4f3207dd043c198b76a4bc18c8529bcf44
[ "BSD-3-Clause" ]
null
null
null
#include "driver/HiggsTDMA.hpp" #include <iostream> void HiggsTDMA::reset() { std::cout << "HiggsTDMA reset\n"; found_dead = 0; sent_tdma = 0; lifetime_tx = 0; lifetime_rx = 0; fudge_rx = 0; needs_fudge = 0; epoc_tx = 0; } bool HiggsTDMA::needsUpdate() const { return ((lifetime_tx == 0) && (lifetime_rx == 0)) ; }
19.611111
55
0.603399
siglabsoss
dfb5dd43032185690be0e8dae1132064200a0368
792
hpp
C++
Merlin/Merlin/Platform/OpenGL/opengl_cubemap.hpp
kshatos/MerlinEngine
a7eb9b39b6cb8a02bef0f739db25268a7a06e215
[ "MIT" ]
null
null
null
Merlin/Merlin/Platform/OpenGL/opengl_cubemap.hpp
kshatos/MerlinEngine
a7eb9b39b6cb8a02bef0f739db25268a7a06e215
[ "MIT" ]
null
null
null
Merlin/Merlin/Platform/OpenGL/opengl_cubemap.hpp
kshatos/MerlinEngine
a7eb9b39b6cb8a02bef0f739db25268a7a06e215
[ "MIT" ]
null
null
null
#ifndef OPENGL_CUBEMAP_HPP #define OPENGL_CUBEMAP_HPP #include "Merlin/Render/cubemap.hpp" #include <stdint.h> namespace Merlin { class OpenGLCubemap : public Cubemap { uint32_t m_channel_count; uint32_t m_resolution; uint32_t m_id; public: OpenGLCubemap(const std::vector<std::string>& face_paths); OpenGLCubemap(uint32_t resolution, uint32_t channel_count); ~OpenGLCubemap(); inline virtual uint32_t GetResolution() override { return m_resolution; } inline virtual uint32_t GetChannelCount() override { return m_channel_count; } void Bind(uint32_t slot=0) override; void UnBind(uint32_t slot = 0) override; virtual void SetFaceData(CubeFace face, float* data) override; }; } #endif
28.285714
86
0.694444
kshatos
dfc36dea730e557de3eafa86b5b9c02b16e52d0c
14,211
cpp
C++
reflex/src/win32/defs.cpp
xord/reflexion
7d864267152dca1ffeef757d0584777b16a92ede
[ "MIT" ]
3
2015-12-18T09:04:48.000Z
2022-01-04T22:21:20.000Z
reflex/src/win32/defs.cpp
xord/reflexion
7d864267152dca1ffeef757d0584777b16a92ede
[ "MIT" ]
null
null
null
reflex/src/win32/defs.cpp
xord/reflexion
7d864267152dca1ffeef757d0584777b16a92ede
[ "MIT" ]
null
null
null
#include "defs.h" #include <windowsx.h> #ifndef VK_BROWSER_BACK #define VK_BROWSER_BACK 0xa6 #define VK_BROWSER_FORWARD 0xa7 #define VK_BROWSER_REFRESH 0xa8 #define VK_BROWSER_STOP 0xa9 #define VK_BROWSER_SEARCH 0xaa #define VK_BROWSER_FAVORITES 0xab #define VK_BROWSER_HOME 0xac #define VK_VOLUME_MUTE 0xad #define VK_VOLUME_DOWN 0xae #define VK_VOLUME_UP 0xaf #define VK_MEDIA_NEXT_TRACK 0xb0 #define VK_MEDIA_PREV_TRACK 0xb1 #define VK_MEDIA_STOP 0xb2 #define VK_MEDIA_PLAY_PAUSE 0xb3 #define VK_LAUNCH_MAIL 0xb4 #define VK_LAUNCH_MEDIA_SELECT 0xb5 #define VK_LAUNCH_APP1 0xb6 #define VK_LAUNCH_APP2 0xb7 #endif namespace Reflex { static bool get_modifiers (uint* modifiers) { if (!modifiers) return false; *modifiers |= GetKeyState(VK_SHIFT) ? MOD_SHIFT : 0 | GetKeyState(VK_CONTROL) ? MOD_CONTROL : 0 | GetKeyState(VK_MENU) ? MOD_ALT : 0 | GetKeyState(VK_LWIN) ? MOD_WIN : 0 | GetKeyState(VK_RWIN) ? MOD_WIN : 0 | GetKeyState(VK_CAPITAL) ? MOD_CAPS : 0 | GetKeyState(VK_NUMLOCK) ? MOD_NUMPAD : 0; return true; } static bool get_keypress (Key* key, UINT msg, WPARAM wp, LPARAM lp) { if (!key) return false; String& s = key->chars; int& c = key->code; uint& m = key->modifiers; switch (wp) { case VK_CANCEL: c = KEY_BREAK; return true; case VK_BACK: c = KEY_BACKSPACE; return true; case VK_TAB: c = KEY_TAB; return true; case VK_CLEAR: c = KEY_CLEAR; return true; case VK_RETURN: c = KEY_RETURN; return true; case VK_SHIFT: c = KEY_SHIFT; return true; case VK_CONTROL: c = KEY_CONTROL; return true; case VK_MENU: c = KEY_ALT; return true; case VK_PAUSE: c = KEY_PAUSE; return true; case VK_CAPITAL: c = KEY_CAPSLOCK; return true; case VK_KANA: c = KEY_IME_KANA; return true; case VK_JUNJA: c = KEY_IME_JUNJA; return true; case VK_FINAL: c = KEY_IME_FINAL; return true; case VK_KANJI: c = KEY_IME_KANJI; return true; case VK_ESCAPE: c = KEY_ESCAPE; return true; case VK_CONVERT: c = KEY_IME_CONVERT; return true; case VK_NONCONVERT: c = KEY_IME_NONCONVERT; return true; case VK_ACCEPT: c = KEY_IME_ACCEPT; return true; case VK_MODECHANGE: c = KEY_IME_MODECHANGE; return true; case VK_SPACE: c = KEY_SPACE; return true; case VK_PRIOR: c = KEY_PAGEUP; return true; case VK_NEXT: c = KEY_PAGEDOWN; return true; case VK_END: c = KEY_END; return true; case VK_HOME: c = KEY_HOME; return true; case VK_LEFT: c = KEY_LEFT; return true; case VK_UP: c = KEY_UP; return true; case VK_RIGHT: c = KEY_RIGHT; return true; case VK_DOWN: c = KEY_DOWN; return true; case VK_SELECT: c = KEY_SELECT; return true; case VK_PRINT: c = KEY_PRINT; return true; case VK_EXECUTE: c = KEY_EXECUTE; return true; case VK_SNAPSHOT: c = KEY_PRINTSCREEN; return true; case VK_INSERT: c = KEY_INSERT; return true; case VK_DELETE: c = KEY_DELETE; return true; case VK_HELP: c = KEY_HELP; return true; case VK_LWIN: c = KEY_LWIN; return true; case VK_RWIN: c = KEY_RWIN; return true; case VK_APPS: c = KEY_APPS; return true; case VK_SLEEP: c = KEY_SLEEP; return true; case VK_NUMPAD0: s = "0"; m = MOD_NUMPAD; return true; case VK_NUMPAD1: s = "1"; m = MOD_NUMPAD; return true; case VK_NUMPAD2: s = "2"; m = MOD_NUMPAD; return true; case VK_NUMPAD3: s = "3"; m = MOD_NUMPAD; return true; case VK_NUMPAD4: s = "4"; m = MOD_NUMPAD; return true; case VK_NUMPAD5: s = "5"; m = MOD_NUMPAD; return true; case VK_NUMPAD6: s = "6"; m = MOD_NUMPAD; return true; case VK_NUMPAD7: s = "7"; m = MOD_NUMPAD; return true; case VK_NUMPAD8: s = "8"; m = MOD_NUMPAD; return true; case VK_NUMPAD9: s = "9"; m = MOD_NUMPAD; return true; case VK_MULTIPLY: s = "*"; m = MOD_NUMPAD; return true; case VK_ADD: s = "+"; m = MOD_NUMPAD; return true; case VK_SEPARATOR: s = ":"; m = MOD_NUMPAD; return true; case VK_SUBTRACT: s = "-"; m = MOD_NUMPAD; return true; case VK_DECIMAL: s = "."; m = MOD_NUMPAD; return true; case VK_DIVIDE: s = "/"; m = MOD_NUMPAD; return true; case VK_F1: c = KEY_F1; m = MOD_FUNCTION; return true; case VK_F2: c = KEY_F2; m = MOD_FUNCTION; return true; case VK_F3: c = KEY_F3; m = MOD_FUNCTION; return true; case VK_F4: c = KEY_F4; m = MOD_FUNCTION; return true; case VK_F5: c = KEY_F5; m = MOD_FUNCTION; return true; case VK_F6: c = KEY_F6; m = MOD_FUNCTION; return true; case VK_F7: c = KEY_F7; m = MOD_FUNCTION; return true; case VK_F8: c = KEY_F8; m = MOD_FUNCTION; return true; case VK_F9: c = KEY_F9; m = MOD_FUNCTION; return true; case VK_F10: c = KEY_F10; m = MOD_FUNCTION; return true; case VK_F11: c = KEY_F11; m = MOD_FUNCTION; return true; case VK_F12: c = KEY_F12; m = MOD_FUNCTION; return true; case VK_F13: c = KEY_F13; m = MOD_FUNCTION; return true; case VK_F14: c = KEY_F14; m = MOD_FUNCTION; return true; case VK_F15: c = KEY_F15; m = MOD_FUNCTION; return true; case VK_F16: c = KEY_F16; m = MOD_FUNCTION; return true; case VK_F17: c = KEY_F17; m = MOD_FUNCTION; return true; case VK_F18: c = KEY_F18; m = MOD_FUNCTION; return true; case VK_F19: c = KEY_F19; m = MOD_FUNCTION; return true; case VK_F20: c = KEY_F20; m = MOD_FUNCTION; return true; case VK_F21: c = KEY_F21; m = MOD_FUNCTION; return true; case VK_F22: c = KEY_F22; m = MOD_FUNCTION; return true; case VK_F23: c = KEY_F23; m = MOD_FUNCTION; return true; case VK_F24: c = KEY_F24; m = MOD_FUNCTION; return true; case VK_NUMLOCK: c = KEY_NUMLOCK; return true; case VK_SCROLL: c = KEY_SCROLLLOCK; return true; case VK_LSHIFT: c = KEY_LSHIFT; return true; case VK_RSHIFT: c = KEY_RSHIFT; return true; case VK_LCONTROL: c = KEY_LCONTROL; return true; case VK_RCONTROL: c = KEY_RCONTROL; return true; case VK_LMENU: c = KEY_LALT; return true; case VK_RMENU: c = KEY_RALT; return true; case VK_BROWSER_BACK: c = KEY_BROWSER_BACK; return true; case VK_BROWSER_FORWARD: c = KEY_BROWSER_FORWARD; return true; case VK_BROWSER_REFRESH: c = KEY_BROWSER_REFRESH; return true; case VK_BROWSER_STOP: c = KEY_BROWSER_STOP; return true; case VK_BROWSER_SEARCH: c = KEY_BROWSER_SEARCH; return true; case VK_BROWSER_FAVORITES: c = KEY_BROWSER_FAVORITES; return true; case VK_BROWSER_HOME: c = KEY_BROWSER_HOME; return true; case VK_VOLUME_MUTE: c = KEY_VOLUME_MUTE; return true; case VK_VOLUME_DOWN: c = KEY_VOLUME_DOWN; return true; case VK_VOLUME_UP: c = KEY_VOLUME_UP; return true; case VK_MEDIA_NEXT_TRACK: c = KEY_MEDIA_NEXT_TRACK; return true; case VK_MEDIA_PREV_TRACK: c = KEY_MEDIA_PREV_TRACK; return true; case VK_MEDIA_STOP: c = KEY_MEDIA_STOP; return true; case VK_MEDIA_PLAY_PAUSE: c = KEY_MEDIA_PLAY_PAUSE; return true; case VK_LAUNCH_MAIL: c = KEY_LAUNCH_MAIL; return true; case VK_LAUNCH_MEDIA_SELECT: c = KEY_LAUNCH_MEDIA_SELECT; return true; case VK_LAUNCH_APP1: c = KEY_LAUNCH_APP1; return true; case VK_LAUNCH_APP2: c = KEY_LAUNCH_APP2; return true; #if 0 case VK_OEM_1: s = ","; return true; case VK_OEM_PLUS: s = "},"; return true; case VK_OEM_COMMA: s = ","; return true; case VK_OEM_MINUS: s = "-"; return true; case VK_OEM_PERIOD: s = "."; return true; case VK_OEM_2: s = "/"; return true; case VK_OEM_3: s = "@"; return true; case VK_OEM_4: s = "["; return true; case VK_OEM_5: s = "\\"; return true; case VK_OEM_6: s = "]"; return true; case VK_OEM_7: s = "^"; return true; case VK_OEM_8: c = KEY_OEM_8; return true; case VK_OEM_AX: c = KEY_KEY_OEM_AX; return true; case VK_OEM_102: s = "\\"; return true; case VK_ICO_HELP: c = KEY_ICO_HELP; return true; case VK_ICO_OO: c = KEY_ICO_OO; return true; #endif case VK_PROCESSKEY: c = KEY_IME_PROCESS; return true; #if 0 case VK_ICO_CLEAR: c = KEY_ICO_CLEAR; return true; case VK_PACKET: c = KEY_PACKET; return true; case VK_OEM_RESET: c = KEY_OEM_RESET; return true; case VK_OEM_JUMP: c = KEY_OEM_JUMP; return true; case VK_OEM_PA1: c = KEY_OEM_PA1; return true; case VK_OEM_PA2: c = KEY_OEM_PA2; return true; case VK_OEM_PA3: c = KEY_OEM_PA3; return true; case VK_OEM_WSCTRL: c = KEY_OEM_WSCTRL; return true; case VK_OEM_CUSEL: c = KEY_OEM_CUSEL; return true; case VK_OEM_ATTN: c = KEY_OEM_ATTN; return true; case VK_OEM_FINISH: c = KEY_OEM_FINISH; return true; case VK_OEM_COPY: c = KEY_OEM_COPY; return true; case VK_OEM_AUTO: c = KEY_OEM_AUTO; return true; case VK_OEM_ENLW: c = KEY_OEM_ENLW; return true; case VK_OEM_BACKTAB: c = KEY_OEM_BACKTAB; return true; case VK_ATTN: c = KEY_ATTN; return true; case VK_CRSEL: c = KEY_CRSEL; return true; case VK_EXSEL: c = KEY_EXSEL; return true; case VK_EREOF: c = KEY_EREOF; return true; #endif case VK_PLAY: c = KEY_PLAY; return true; case VK_ZOOM: c = KEY_ZOOM; return true; #if 0 case VK_NONAME: c = KEY_NONAME; return true; case VK_PA1: c = KEY_PA1; return true; case VK_OEM_CLEAR: c = KEY_OEM_CLEAR; return true; #endif } return false; } static bool get_chars (Key* key, UINT msg, WPARAM wp, LPARAM lp) { if (!key) return false; key->chars += (char) wp; return true; } static bool get_key (Key* key, UINT msg, WPARAM wp, LPARAM lp) { if (!key || !get_modifiers(&key->modifiers)) return false; bool ret = true; if ( msg == WM_KEYDOWN || msg == WM_KEYUP || msg == WM_SYSKEYDOWN || msg == WM_SYSKEYUP) { ret &= get_keypress(key, msg, wp, lp); } else if ( msg == WM_CHAR || msg == WM_SYSCHAR || msg == WM_DEADCHAR || msg == WM_SYSDEADCHAR) { ret &= get_chars(key, msg, wp, lp); } key->repeat = lp & 0xff; ret &= get_modifiers(&key->modifiers); return ret; } static int get_points (Points* points, UINT msg, WPARAM wp, LPARAM lp) { if (!points) return false; switch (msg) { case WM_LBUTTONDBLCLK: points->count += 1; case WM_LBUTTONDOWN: case WM_LBUTTONUP: points->type = POINT_MOUSE_LEFT; points->count += 1; break; case WM_RBUTTONDBLCLK: points->count += 1; case WM_RBUTTONDOWN: case WM_RBUTTONUP: points->type = POINT_MOUSE_RIGHT; points->count += 1; break; case WM_MBUTTONDBLCLK: points->count += 1; case WM_MBUTTONDOWN: case WM_MBUTTONUP: points->type = POINT_MOUSE_MIDDLE; points->count += 1; break; } return get_modifiers(&points->modifiers); } Win32Key::Win32Key (UINT msg, WPARAM wp, LPARAM lp) { get_key(this, msg, wp, lp); } Win32Points::Win32Points (UINT msg, WPARAM wp, LPARAM lp) : Points(POINT_NONE, GET_X_LPARAM(lp), GET_Y_LPARAM(lp)) { get_points(this, msg, wp, lp); } }// Reflex
46.746711
75
0.517557
xord
dfc4a1b7b904f4f29f6f2e734ed693b2bc05b654
6,224
cpp
C++
NINJA/TreeBuilderManager.cpp
jebrosen/NINJA
db4f4216fc402e73ae16be65a1fc8e5ecfeef79b
[ "MIT" ]
null
null
null
NINJA/TreeBuilderManager.cpp
jebrosen/NINJA
db4f4216fc402e73ae16be65a1fc8e5ecfeef79b
[ "MIT" ]
null
null
null
NINJA/TreeBuilderManager.cpp
jebrosen/NINJA
db4f4216fc402e73ae16be65a1fc8e5ecfeef79b
[ "MIT" ]
null
null
null
/* * TreeBuilderManager.cpp * * Created on: Feb 7, 2016 * Author: michel */ #include "TreeBuilderManager.hpp" #define LINUX 1 #ifdef LINUX #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #endif //standard constructor TreeBuilderManager::TreeBuilderManager(std::string method, std::string njTmpDir, std::string inFile, FILE* outFile, InputType inType, OutputType outType, AlphabetType alphType, CorrectionType corrType, int threads, bool useSSE){ this->method = method; this->njTmpDir = njTmpDir; this->inFile = inFile; this->outFile = outFile; this->inType = inType; this->outType = outType; this->alphType = alphType; this->corrType = corrType; this->names = NULL; this->chars = "abcdefghijklmonpqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; this->newDistanceMethod = false; this->threads = threads; this->newDistanceMethod = useSSE; } std::string TreeBuilderManager::doJob(){ int** distances = NULL; float** memD = NULL; float* R = NULL; // all for external memory version int pageBlockSize = 1024; //that many ints = 4096 bytes; FILE* diskD = NULL; int rowLength = 0; int firstMemCol = -1; int numCols = 0; //Runtime runtime = Runtime.getRuntime(); long maxMemory = -1; bool ok = true; TreeNode** nodes = NULL; std::string treeString = ""; //NinjaLogWriter.printVersion(); int K=0; /* #ifdef LINUX maxMemory = sysconf(_SC_PAGE_SIZE)*sysconf(_SC_AVPHYS_PAGES); #endif */ SequenceFileReader* seqReader = NULL; if (!this->method.compare("extmem")){ if (maxMemory < 1900000000) { fprintf(stderr,"Warning: using an external-memory variant of NINJA with less than 2GB allocated RAM.\n"); fprintf(stderr,"The data structures of NINJA may not work well if given less than 2GB.\n"); } fprintf(stderr,"Using External Memory...\n"); njTmpDir += "treeBuilderManager"; mkdir(njTmpDir.c_str(), 0700); fprintf(stderr,"created temporary directory for this run of NINJA : %s\n", njTmpDir.c_str()); this->njTmpDir += "/"; DistanceReaderExtMem* reader = NULL; if (inType == alignment) { seqReader = new SequenceFileReader(&(this->inFile),(SequenceFileReader::AlphabetType) this->alphType); std::string** seqs = seqReader->getSeqs(); this->names = seqReader->getNames(); this->alphType = (TreeBuilderManager::AlphabetType) seqReader->getAlphType(); fprintf(stderr,"Calculating distances....\n"); DistanceCalculator* distCalc = new DistanceCalculator(seqs,(DistanceCalculator::AlphabetType) alphType,(DistanceCalculator::CorrectionType) corrType, seqReader->numSeqs, this->newDistanceMethod); K = seqReader->numSeqs; reader = new DistanceReaderExtMem(distCalc, K); } else { fprintf(stderr,"External memory with distances as input not allowed.\n"); Exception::critical(); //reader = new DistanceReaderExtMem(this->inFile); K = reader->K; this->names = new std::string*[K]; for (int i = 0;i<K;i++) this->names[i] = new std::string(); } R = new float[K](); rowLength = (K + K-2); //that's a K*K table for the initial values, plus another K*(K-2) columns for new nodes long maxSize; // max amount of D stored in memory if (TreeBuilderExtMem::useBinPairHeaps) { maxSize = maxMemory / 10; } else { maxSize = maxMemory / 3; } numCols = (int)(maxSize / (4 * K)); int numBlocks = numCols/pageBlockSize; // chops off fractional part if (numBlocks == 0) numBlocks = 1; //for huge inputs, this could result in memD larger than 400MB numCols = numBlocks * pageBlockSize; if (numCols >= 2*K-2) { numCols = 2*K-2; } else { std::string newDir = njTmpDir + "ninja_diskD_tmp"; FILE* tmpFile = fopen(newDir.c_str(),"w+"); diskD = tmpFile; } memD = new float*[K]; for(int i=0;i<K;i++){ memD[i] = new float[numCols]; } firstMemCol = reader->read( names, R, diskD, memD, numCols, rowLength, pageBlockSize); if(this->outType == dist){ fprintf(stderr,"Output distances with external memory not allowed.\n"); Exception::critical(); } }else{ DistanceReader* reader = NULL; if (this->inType == alignment) { seqReader = new SequenceFileReader(&(this->inFile),(SequenceFileReader::AlphabetType) this->alphType); std::string** seqs = seqReader->getSeqs(); this->names = seqReader->getNames(); this->alphType = (TreeBuilderManager::AlphabetType) seqReader->getAlphType(); fprintf(stderr,"Calculating distances....\n"); DistanceCalculator* distCalc = new DistanceCalculator(seqs,(DistanceCalculator::AlphabetType) alphType,(DistanceCalculator::CorrectionType) corrType, seqReader->numSeqs,newDistanceMethod); K = seqReader->numSeqs; reader = new DistanceReader(distCalc, K, this->threads); }else{ reader = new DistanceReader(this->inFile); K = reader->K; this->names = new std::string*[K]; for (int i = 0;i<K;i++) this->names[i] = new std::string(); } distances = new int*[K]; for (int i=0; i<K; i++) { distances[i] = new int[K - i - 1]; } if(this->outType == dist){ if(this->inType != alignment){ fprintf(stderr,"Input and output distances not allowed. What are you trying to do?\n"); Exception::critical(); } reader->readAndWrite(this->names,this->outFile); return ""; }else{ reader->read( this->names, distances); } } fprintf(stderr,"Generating tree....\n"); int nodesSize = 0; TreeBuilderBinHeap* tb = NULL; TreeBuilderExtMem *tb_extmem = NULL; if (!this->method.compare("inmem") or !this->method.compare("default")) { tb = new TreeBuilderBinHeap(this->names, distances, K); nodes = tb->build(); nodesSize = (tb->K*2)-1; } else if (!method.compare("extmem") ) { tb_extmem = new TreeBuilderExtMem(names, K, R, njTmpDir, diskD, memD , numCols, firstMemCol, rowLength, maxMemory); nodes = tb_extmem->build(); nodesSize = (tb_extmem->K*2)-1; } std::string *sb; if (ok && treeString.empty()) { if (nodes != NULL) { sb = new std::string(); *sb = ""; nodes[nodesSize-1]->buildTreeString(sb); treeString = *sb + ";\n"; delete sb; } } if (tb != NULL) delete tb; if (tb_extmem != NULL) delete tb_extmem; if (seqReader != NULL) delete seqReader; delete[] distances; return (treeString); }
29.358491
228
0.677378
jebrosen
dfc6194a7973a9035028ec4014b658ac6667416f
9,918
cpp
C++
Source/VoxelArt/Private/Editor/VoxelModificationWorld.cpp
limness/Voxel-Art
78e3d71f820657568d861983c46ed130fd40f807
[ "MIT" ]
32
2021-04-28T21:11:30.000Z
2022-03-27T15:28:59.000Z
Source/VoxelArt/Private/Editor/VoxelModificationWorld.cpp
limness/Voxel-Art
78e3d71f820657568d861983c46ed130fd40f807
[ "MIT" ]
null
null
null
Source/VoxelArt/Private/Editor/VoxelModificationWorld.cpp
limness/Voxel-Art
78e3d71f820657568d861983c46ed130fd40f807
[ "MIT" ]
5
2021-04-29T03:09:03.000Z
2022-01-26T03:25:47.000Z
// Voxel Art Plugin 2021 ~ Copyright Limit #include "Editor/VoxelModificationWorld.h" #include "Editor/VoxelEditorData.h" #include "DrawDebugHelpers.h" #include "Kismet/KismetMathLibrary.h" //#include "Noise/SimplexNoiseBPLibrary.h" #include "Helpers/VoxelTools.h" #include "Helpers/VoxelSDFUtilities.h" #include "Helpers/VoxelCollisionBox.h" #include "VoxelWorld.h" using namespace VoxelTools; void UVoxelModificationWorld::SpherePainter(UVoxelEditorData* Data, AVoxelWorld* World, FIntVector Position, float Radius) { int VoxelsRadius = FMath::CeilToInt(Radius); FVoxelOctreeDensity* OutOctant = nullptr; World->OctreeMutex.Lock(); bool TerrainEdit = Data->EditorType == EEditorType::TerrainEdit; bool ColorEdit = Data->EditorType == EEditorType::ColorEdit; if (Data->CopyPastOn && Data->CopyingPasting == ECopyingPasting::Pasting) { for (auto& VoxelCopied : Data->CopiedDensity) { World->SetVoxelValue(OutOctant, VoxelCopied.Position, VoxelCopied.Value, VoxelCopied.Color, true, true); } return; } for (int Z = -VoxelsRadius; Z <= VoxelsRadius; Z++) { for (int Y = -VoxelsRadius; Y <= VoxelsRadius; Y++) { for (int X = -VoxelsRadius; X <= VoxelsRadius; X++) { float SphereSDF = FVoxelSDFUtilities::SphereSDF(X, Y, Z, Radius);// Radius - VoxelOffset - FVector(X, Y, Z).Size(); //if (SphereSDF >= -2) if(Data->CopyPastOn) { if (Data->CopyingPasting == ECopyingPasting::Copying) { float OutValue = 0.f; FColor OutColor = FColor(77.f, 77.f, 77.f); World->GetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, OutValue, OutColor); Data->CopiedDensity.Add(FVoxelInfo(FIntVector(X, Y, Z) + Position, OutValue, OutColor)); } } else { float OutValue = 0.f; FColor OutColor = FColor(77.f, 77.f, 77.f); World->GetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, OutValue, OutColor); float Value = 0.f; { if (TerrainEdit) { if (Data->BrushSoftness == EBrushSoftness::Smooth) { } else if (Data->BrushSoftness == EBrushSoftness::Insert) { Value = Data->Dig ? UKismetMathLibrary::FMax(OutValue, SphereSDF) : UKismetMathLibrary::FMin(OutValue, -SphereSDF); } } } World->SetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, Value, Data->BrushColor, TerrainEdit, ColorEdit); } } } } UpdateOverlapOctants(World, Position, FIntVector(1, 1, 1) * VoxelsRadius * 2); World->OctreeMutex.Unlock(); } void UVoxelModificationWorld::CubePainter(UVoxelEditorData* Data, AVoxelWorld* World, FIntVector Position, float Radius) { int VoxelsRadius = FMath::CeilToInt(Radius); FVoxelOctreeDensity* OutOctant = nullptr; World->OctreeMutex.Lock(); for (int Z = -VoxelsRadius; Z <= VoxelsRadius; Z++) { for (int Y = -VoxelsRadius; Y <= VoxelsRadius; Y++) { for (int X = -VoxelsRadius; X <= VoxelsRadius; X++) { float OutValue = 0.f; FColor OutColor = FColor(77.f, 77.f, 77.f); World->GetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, OutValue, OutColor); float Value = Data->Dig ? UKismetMathLibrary::FMax(OutValue, 1.f) : UKismetMathLibrary::FMin(OutValue, -1.f); if (Data->EditorType == EEditorType::TerrainEdit) { World->SetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, Value, FColor(77.f, 77.f, 77.f), true, false); } else if (Data->EditorType == EEditorType::ColorEdit) { World->SetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, -1.f, Data->BrushColor, false, true); } } } } UpdateOverlapOctants(World, Position, FIntVector(1, 1, 1) * (VoxelsRadius + 1) * 2); World->OctreeMutex.Unlock(); } void UVoxelModificationWorld::TorusPainter(UVoxelEditorData* Data, AVoxelWorld* World, FIntVector Position, float Radius, float InnerRadius) { int VoxelsRadius = FMath::CeilToInt(Radius + InnerRadius); FVoxelOctreeDensity* OutOctant = nullptr; World->OctreeMutex.Lock(); for (int Z = -VoxelsRadius; Z <= VoxelsRadius; Z++) { for (int Y = -VoxelsRadius; Y <= VoxelsRadius; Y++) { for (int X = -VoxelsRadius; X <= VoxelsRadius; X++) { float OutValue = 0.f; FColor OutColor = FColor(77.f, 77.f, 77.f); World->GetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, OutValue, OutColor); float TorusSDF = FVoxelSDFUtilities::TorusSDF(X, Y, Z, Radius, InnerRadius); float Value = Data->Dig ? UKismetMathLibrary::FMax(OutValue, TorusSDF) : UKismetMathLibrary::FMin(OutValue, -TorusSDF); if (Data->EditorType == EEditorType::TerrainEdit) { World->SetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, Value, FColor(77.f, 77.f, 77.f), true, false); } else if (Data->EditorType == EEditorType::ColorEdit) { World->SetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, -1.f, Data->BrushColor, false, true); } } } } UpdateOverlapOctants(World, Position, FIntVector(1, 1, 1) * (VoxelsRadius + 1) * 2); World->OctreeMutex.Unlock(); } void UVoxelModificationWorld::ConePainter(UVoxelEditorData* Data, AVoxelWorld* World, FIntVector Position, float Radius, float Height, FVector2D Angle) { int VoxelsRadius = FMath::CeilToInt(Radius + Height); FVoxelOctreeDensity* OutOctant = nullptr; World->OctreeMutex.Lock(); for (int Z = -VoxelsRadius; Z <= VoxelsRadius; Z++) { for (int Y = -VoxelsRadius; Y <= VoxelsRadius; Y++) { for (int X = -VoxelsRadius; X <= VoxelsRadius; X++) { float OutValue = 0.f; FColor OutColor = FColor(77.f, 77.f, 77.f); World->GetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, OutValue, OutColor); float ConeSDF = FVoxelSDFUtilities::ConeSDF(Y, Z - Height / 2, X, Angle, Height); float Value = Data->Dig ? UKismetMathLibrary::FMax(OutValue, ConeSDF) : UKismetMathLibrary::FMin(OutValue, -ConeSDF); if (Data->EditorType == EEditorType::TerrainEdit) { World->SetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, Value, FColor(77.f, 77.f, 77.f), true, false); } else if (Data->EditorType == EEditorType::ColorEdit) { World->SetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, -1.f, Data->BrushColor, false, true); } } } } UpdateOverlapOctants(World, Position, FIntVector(1, 1, 1) * (VoxelsRadius + 1) * 2); World->OctreeMutex.Unlock(); } void UVoxelModificationWorld::CopyPainter(UVoxelEditorData* Data, AVoxelWorld* World, FIntVector Position, float Radius) { int VoxelsRadius = FMath::CeilToInt(Radius); FVoxelOctreeDensity* OutOctant = nullptr; World->OctreeMutex.Lock(); // As soon as we start copying new data - we have to set a new center of coordinates if (Data->CopiedDensity.Num() == 0) { Data->CenterCopy = Position; } for (int Z = -VoxelsRadius; Z <= VoxelsRadius; Z++) { for (int Y = -VoxelsRadius; Y <= VoxelsRadius; Y++) { for (int X = -VoxelsRadius; X <= VoxelsRadius; X++) { float OutValue = 0.f; FColor OutColor = FColor(77.f, 77.f, 77.f); World->GetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, OutValue, OutColor); Data->CopiedDensity.Add(FVoxelInfo(FIntVector(X, Y, Z) + Position - Data->CenterCopy, OutValue, OutColor)); } } } World->OctreeMutex.Unlock(); } void UVoxelModificationWorld::PastPainter(UVoxelEditorData* Data, AVoxelWorld* World, FIntVector Position) { FVoxelOctreeDensity* OutOctant = nullptr; // Before pasting, we must define the boundaries of the changed data // so that we can then update only the affected chunks if (Data->CornerMin == FIntVector(0, 0, 0) && Data->CornerMax == FIntVector(0, 0, 0)) { for (auto& VoxelCopied : Data->CopiedDensity) { if (VoxelCopied.Position.X < Data->CornerMin.X) { Data->CornerMin.X = VoxelCopied.Position.X; } if (VoxelCopied.Position.Y < Data->CornerMin.Y) { Data->CornerMin.Y = VoxelCopied.Position.Y; } if (VoxelCopied.Position.Z < Data->CornerMin.Z) { Data->CornerMin.Z = VoxelCopied.Position.Z; } /////////////////////////////////////////////// /////////////////////////////////////////////// if (VoxelCopied.Position.X > Data->CornerMax.X) { Data->CornerMax.X = VoxelCopied.Position.X; } if (VoxelCopied.Position.Y > Data->CornerMax.Y) { Data->CornerMax.Y = VoxelCopied.Position.Y; } if (VoxelCopied.Position.Z > Data->CornerMax.Z) { Data->CornerMax.Z = VoxelCopied.Position.Z; } } } World->OctreeMutex.Lock(); for (auto& VoxelCopied : Data->CopiedDensity) { World->SetVoxelValue(OutOctant, VoxelCopied.Position + Position + Data->PastOffset, VoxelCopied.Value, VoxelCopied.Color, true, true); } FIntVector MaxBoundBox = FIntVector( FMath::Max(Data->CornerMax.X, Data->CornerMin.X), FMath::Max(Data->CornerMax.Y, Data->CornerMin.Y), FMath::Max(Data->CornerMax.Z, Data->CornerMin.Z) ); UpdateOverlapOctants(World, Position, (MaxBoundBox + FIntVector(1, 1, 1)) * 2); World->OctreeMutex.Unlock(); } float UVoxelModificationWorld::BangPainter(int X, int Y, int Z, float Radius, int octaves, float amplitude, float frequency) { float value = 0.f; float valuefractal = 0.f; // TODO: Tranfer to Fast Noise /* value = Radius - sqrt(X * X + Y * Y + Z * Z); for (int i = 0; i < octaves; i++) { valuefractal += USimplexNoiseBPLibrary::SimplexNoise3D(X * frequency, Y * frequency, Z * frequency) * amplitude; frequency *= 2.f; amplitude *= 0.5f; } */ return value + valuefractal; } void UVoxelModificationWorld::UpdateOverlapOctants(AVoxelWorld* World, FIntVector Position, FIntVector Size) { FVoxelCollisionBox Box = FVoxelCollisionBox(World, Position, Size); TArray<TSharedPtr<FVoxelOctreeData>> OverlapOctants; World->GetOverlapingOctree(Box, World->MainOctree, OverlapOctants); for (auto& Octant : OverlapOctants) { if (Octant->Data != nullptr) { if (IsValid(Octant->Data->Chunk)) { World->PutChunkOnGeneration(Octant->Data); } } } }
31.993548
151
0.672817
limness
dfc66268313230649d3d4ae8246ff9a66e52be3f
975
cpp
C++
tools/flang2/flang2exe/expdf.cpp
kammerdienerb/flang
8cc4a02b94713750f09fe6b756d33daced0b4a74
[ "Apache-2.0" ]
1
2019-12-11T17:43:58.000Z
2019-12-11T17:43:58.000Z
tools/flang2/flang2exe/expdf.cpp
kammerdienerb/flang
8cc4a02b94713750f09fe6b756d33daced0b4a74
[ "Apache-2.0" ]
2
2019-12-29T21:15:40.000Z
2020-06-15T11:21:10.000Z
tools/flang2/flang2exe/expdf.cpp
kammerdienerb/flang
8cc4a02b94713750f09fe6b756d33daced0b4a74
[ "Apache-2.0" ]
3
2019-12-21T06:35:35.000Z
2020-06-07T23:18:58.000Z
/* * Copyright (c) 1993-2017, NVIDIA CORPORATION. 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 "gbldefs.h" #include "global.h" #include "symtab.h" #include "ilm.h" /* need ilmtp.h since expand.h tests #ifdef IM_... */ #include "ilmtp.h" #include "ili.h" #define EXPANDER_DECLARE_INTERNAL #include "expand.h" #include "regutil.h" ILIB ilib; ILTB iltb; BIHB bihb; NMEB nmeb; EXP expb = {0}; RCANDB rcandb; RATB ratb;
23.214286
75
0.718974
kammerdienerb
dfc72e679b0348d8241eda86cc1ac649d09d69dd
580
cpp
C++
Dataset/Leetcode/train/111/521.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/111/521.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/111/521.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: int XXX(TreeNode* root) { if (root == nullptr) return 0; queue<pair<TreeNode*, int>> Q; Q.push(make_pair(root, 1)); while (!Q.empty()) { auto p = Q.front(); Q.pop(); TreeNode* node = p.first; int height = p.second; if (node -> left == nullptr && node -> right == nullptr) return height; // 当前节点是叶子节点 if (node -> left) Q.push(make_pair(node -> left, height + 1)); if (node -> right) Q.push(make_pair(node -> right, height + 1)); } return 0; } };
34.117647
96
0.513793
kkcookies99
dfc760691f5de76168a9b52cd15eaf64f33eeff3
2,169
hpp
C++
src/qtf/frameless/windows10.hpp
Qt-Widgets/qt_frameless_main_window
6b3095518ffaf7cc519c8c5635f173508e8be14d
[ "MIT" ]
2
2020-09-22T01:14:44.000Z
2020-09-22T01:14:47.000Z
src/qtf/frameless/windows10.hpp
w1146869587/qt_frameless_main_window
b2bb8a9b1ac755eb99a3ad956abfd69286af2dc3
[ "MIT" ]
null
null
null
src/qtf/frameless/windows10.hpp
w1146869587/qt_frameless_main_window
b2bb8a9b1ac755eb99a3ad956abfd69286af2dc3
[ "MIT" ]
null
null
null
/** SPDX-License-Identifier: MIT Licensed under the MIT License <http://opensource.org/licenses/MIT>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Copyright 2017 github.com/dfct Copyright 2018 github.com/dan-42 */ #pragma once #ifndef FRAMELESS_WIDGET_H #define FRAMELESS_WIDGET_H #include <QWidget> class QResizeEvent; class QPushButton; namespace qtf { namespace frameless { class windows10 : public QWidget { Q_OBJECT public: /// /// /// explicit windows10(); /// /// /// auto content(QWidget* c) -> void; /// /// /// auto restored() -> void; /// /// /// auto maximized() -> void; /// /// /// auto draggable_widgets() const -> std::vector<QWidget*>; signals: /// /// /// void minimize(); void maximize(); void restore(); void close(); private: /// /// auto resizeEvent(QResizeEvent *event) -> void override; private: QPushButton* button_maximize_; QPushButton* button_minimzie_; QPushButton* button_restore_; QPushButton* button_close_; QWidget* buttons_; QWidget* top_drag_area_; }; } //namespace frameless } //namespace qtf #endif // FRAMELESS_WIDGET_H
22.59375
78
0.714615
Qt-Widgets
dfc7a153e75c3cfc9a922805c0b3278821c8d641
5,231
cpp
C++
pheroes/Game/Dlg_Recruit.cpp
TripleMOMO/pocketheroes
6a6f0726c8ea590592290ac53c38e653cf7f966c
[ "Apache-2.0" ]
3
2015-08-08T09:10:02.000Z
2016-03-21T08:48:19.000Z
pheroes/Game/Dlg_Recruit.cpp
TripleMOMO/pocketheroes
6a6f0726c8ea590592290ac53c38e653cf7f966c
[ "Apache-2.0" ]
null
null
null
pheroes/Game/Dlg_Recruit.cpp
TripleMOMO/pocketheroes
6a6f0726c8ea590592290ac53c38e653cf7f966c
[ "Apache-2.0" ]
1
2015-08-21T23:32:49.000Z
2015-08-21T23:32:49.000Z
/* * This file is a part of Pocket Heroes Game project * http://www.pocketheroes.net * https://code.google.com/p/pocketheroes/ * * Copyright 2004-2010 by Robert Tarasov and Anton Stuk (iO UPG) * * 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 "stdafx.h" #include "Dlg_Recruit.h" #include "Dlg_CreatInfo.h" iDlg_Recruit::iDlg_Recruit(iViewMgr* pViewMgr, iCreatGroup& creats, iArmy& army, PLAYER_ID owner) : iBaseGameDlg(pViewMgr, owner), m_creats(creats), m_army(army), m_avail(0), m_recr(0), m_max(0) { } void iDlg_Recruit::OnCreateDlg() { m_avail = m_creats.Count(); check(m_pid != PID_NEUTRAL); iPlayer* pOwner = gGame.Map().FindPlayer(m_pid); check(pOwner); m_crCost = CREAT_DESC[m_creats.Type()].cost; m_max = iMIN<sint32>(m_avail, pOwner->Minerals().Has(m_crCost)); /* iMineralSet ms = m_crCost; while (m_max < m_avail && pOwner->Minerals().Has(ms)) { ms += m_crCost; ++m_max; }*/ iRect clrc = ClientRect(); // Creature button AddChild(m_pIcnButton = new iIconButton(m_pMgr, this, iRect(clrc.x + (clrc.w/2-22), 34,44,56), PDGG_MINIMON + m_creats.Type(), 201)); // Slider AddChild(m_pSlider = new iPHScrollBar(m_pMgr, this, iRect(clrc.x + (clrc.w/2-80), clrc.y2()-20-10-15,160,15), 101, iScrollBar::Horizontal)); m_pSlider->SetMetrics(m_max+1,1); // Button size 40x15 (3*40+10) iRect rc(clrc.x + (clrc.w/2-65), clrc.y2()-DEF_BTN_HEIGHT, 40, DEF_BTN_HEIGHT); AddChild(new iDlgIconButton(m_pMgr,this,rc,PDGG_BTN_MAX, 100)); rc.x+=45; AddChild(new iTextButton(m_pMgr,this,rc,TRID_OK, DRC_OK)); rc.x+=45; AddChild(new iTextButton(m_pMgr,this,rc,TRID_CANCEL, DRC_CANCEL)); GetChildById(100)->SetEnabled(m_max>0); GetChildById(DRC_OK)->SetEnabled(m_recr>0); } void iDlg_Recruit::DoCompose(const iRect& clRect) { iRect rc(clRect); // title gTextComposer.TextOut(dlgfc_hdr, gApp.Surface(), rc.point(), iFormat(_T("%s %s"), gTextMgr[TRID_RECRUIT], gTextMgr[m_creats.Type()*3+TRID_CREATURE_PEASANT_F3]), rc, AlignTop); rc.DeflateRect(0,20,0,0); // information iRect orc(rc.x + (rc.w/2-100), rc.y, 78, 56); //gApp.Surface().Darken25Rect(orc); //ButtonFrame(gApp.Surface(), orc, 0); iRect trc(orc); trc.DeflateRect(3); gTextComposer.TextOut(dlgfc_splain, gApp.Surface(), trc, iStringT(gTextMgr[TRID_AVAILABLE]) + _T(":"), trc, AlignTop); trc.y += 11; gTextComposer.TextOut(dlgfc_topic, gApp.Surface(), trc, FormatNumber(m_avail), trc, AlignTop); trc.y += 14; gTextComposer.TextOut(dlgfc_splain, gApp.Surface(), trc, iStringT(gTextMgr[TRID_COST_PER_TROOP]) + _T(":"), trc, AlignTop); trc.y += 11; gTextComposer.TextOut(dlgfc_topic, gApp.Surface(), rc.point(), MineralSet2Text(m_crCost), trc, AlignTop); orc.x += 78; orc.w = 42; //BlitIcon(gApp.Surface(), PDGG_MINIMON +m_dwel.CrType(), orc); orc.w = 78; orc.x += 44; //gApp.Surface().Darken25Rect(orc); //ButtonFrame(gApp.Surface(), orc, 0); trc = orc; trc.DeflateRect(3); gTextComposer.TextOut(dlgfc_splain, gApp.Surface(), trc, iStringT(gTextMgr[TRID_RECRUIT]) + _T(":"), trc, AlignTop); trc.y += 11; gTextComposer.TextOut(dlgfc_topic, gApp.Surface(), trc, FormatNumber(m_recr), trc, AlignTop); trc.y += 14; gTextComposer.TextOut(dlgfc_splain, gApp.Surface(), trc, iStringT(gTextMgr[TRID_TOTAL_COST]) + _T(":"), trc, AlignTop); trc.y += 11; iMineralSet ms; ms.Reset(); for(uint32 xx=0; xx<m_recr; ++xx) ms += m_crCost; gTextComposer.TextOut(dlgfc_topic, gApp.Surface(), rc.point(), MineralSet2Text(ms), trc, AlignTop); } iSize iDlg_Recruit::ClientSize() const { return iSize(220,110 + DEF_BTN_HEIGHT); } void iDlg_Recruit::iCMDH_ControlCommand(iView* pView, CTRL_CMD_ID cmd, sint32 param) { if (!IsValidDialog()) return; uint32 uid = pView->GetUID(); if (uid == 101) { m_recr = m_pSlider->CurPos(); GetChildById(DRC_OK)->SetEnabled(m_recr>0); } else if (cmd == CCI_BTNCLICK) { if (uid == 100) { m_pSlider->SetCurPos(m_max); m_recr = m_max; GetChildById(DRC_OK)->SetEnabled(m_recr>0); } else if (uid == 201) { iCreatGroup group(m_creats.Type(),m_avail); iDlg_CreatInfo cidlg(m_pMgr, m_pid, group, iFurtSkills(), false, 0); cidlg.DoModal(); } else if (uid == DRC_OK) { // Check space in target army if (m_army.CanAddGroup(m_creats.Type())) { m_army.AddGroup(m_creats.Type(), m_recr); m_creats.Count() -= m_recr; gGame.Map().FindPlayer(m_pid)->Minerals() -= m_crCost * m_recr; EndDialog(DRC_OK); } else { iTextDlg tdlg(m_pMgr, _T(""), gTextMgr[TRID_MSG_NO_ROOM], m_pid); tdlg.DoModal(); } } else if (uid == DRC_CANCEL) { EndDialog(DRC_CANCEL); } } }
34.873333
177
0.678455
TripleMOMO
dfc87e51f149168db8393d5a93ea223deb25fb37
2,435
cpp
C++
net/homenet/beacon/server/cnatdynamicportmappingservice.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
net/homenet/beacon/server/cnatdynamicportmappingservice.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
net/homenet/beacon/server/cnatdynamicportmappingservice.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include "pch.h" #pragma hdrstop #include "CNATDynamicPortMappingService.h" CNATDynamicPortMappingService::CNATDynamicPortMappingService() { m_pEventSink = NULL; m_pHNetConnection = NULL; } HRESULT CNATDynamicPortMappingService::FinalConstruct() { HRESULT hr = S_OK; return hr; } HRESULT CNATDynamicPortMappingService::FinalRelease() { HRESULT hr = S_OK; if(NULL != m_pHNetConnection) { m_pHNetConnection->Release(); } return hr; } HRESULT CNATDynamicPortMappingService::Initialize(IHNetConnection* pHNetConnection) { HRESULT hr = S_OK; m_pHNetConnection = pHNetConnection; m_pHNetConnection->AddRef(); return hr; } HRESULT CNATDynamicPortMappingService::Advise(IUPnPEventSink* pesSubscriber) { HRESULT hr = S_OK; m_pEventSink = pesSubscriber; m_pEventSink->AddRef(); return hr; } HRESULT CNATDynamicPortMappingService::Unadvise(IUPnPEventSink* pesSubscriber) { HRESULT hr = S_OK; m_pEventSink->Release(); m_pEventSink = NULL; return hr; } HRESULT CNATDynamicPortMappingService::get_DynamicPublicIP(BSTR* pDynamicPublicIP) { *pDynamicPublicIP = NULL; return E_UNEXPECTED; } HRESULT CNATDynamicPortMappingService::get_DynamicPort(ULONG* pulDynamicPort) { return E_UNEXPECTED; } HRESULT CNATDynamicPortMappingService::get_DynamicProtocol(BSTR* pDynamicProtocol) { *pDynamicProtocol = NULL; return E_UNEXPECTED; } HRESULT CNATDynamicPortMappingService::get_DynamicPrivateIP(BSTR* pDynamicPrivateIP) { *pDynamicPrivateIP = NULL; return E_UNEXPECTED; } HRESULT CNATDynamicPortMappingService::get_DynamicLeaseDuration(ULONG* pulDynamicLeaseDuration) { return E_UNEXPECTED; } HRESULT CNATDynamicPortMappingService::CreateDynamicPortMapping(BSTR DynamicPublicIP, ULONG ulDynamicPort, BSTR DynamicProtocol, BSTR DynamicPrivateIP, BSTR DynamicLeaseDuration) { HRESULT hr = S_OK; return hr; } HRESULT CNATDynamicPortMappingService::DeleteDynamicPortMapping(BSTR DynamicPublicIP, ULONG ulDynamicPort, BSTR DynamicProtocol) { HRESULT hr = S_OK; return hr; } HRESULT CNATDynamicPortMappingService::ExtendDynamicPortMapping(BSTR DynamicPublicIP, ULONG ulDynamicPort, BSTR DynamicProtocol, ULONG ulDynamicLeaseDuration) { HRESULT hr = S_OK; return hr; }
21.741071
179
0.728131
npocmaka
dfcba19554376eeba3742efee0004cfe44626c81
3,076
cpp
C++
gtclang/src/gtclang/Support/Logger.cpp
muellch/dawn
4fd055df809ce920ca15ffc6137b2be2aed3a2dd
[ "MIT" ]
20
2017-09-28T14:23:54.000Z
2021-08-23T09:58:26.000Z
gtclang/src/gtclang/Support/Logger.cpp
muellch/dawn
4fd055df809ce920ca15ffc6137b2be2aed3a2dd
[ "MIT" ]
1,018
2017-10-09T13:55:47.000Z
2022-03-14T13:16:38.000Z
gtclang/src/gtclang/Support/Logger.cpp
eddie-c-davis/dawn
4dabcfc72e422f125e6a18fe08d0212d588adf98
[ "MIT" ]
20
2017-09-21T10:35:24.000Z
2021-01-18T09:24:58.000Z
//===--------------------------------------------------------------------------------*- C++ -*-===// // _ _ // | | | | // __ _| |_ ___| | __ _ _ __ __ _ // / _` | __/ __| |/ _` | '_ \ / _` | // | (_| | || (__| | (_| | | | | (_| | // \__, |\__\___|_|\__,_|_| |_|\__, | - GridTools Clang DSL // __/ | __/ | // |___/ |___/ // // // This file is distributed under the MIT License (MIT). // See LICENSE.txt for details. // //===------------------------------------------------------------------------------------------===// #include "gtclang/Support/Logger.h" #include "dawn/Support/Format.h" #include <chrono> #include <sstream> namespace gtclang { dawn::Logger::MessageFormatter makeGTClangMessageFormatter(const std::string& prefix) { return [prefix](const std::string& message, const std::string& file, int line) -> std::string { // Get current date-time (up to ms accuracy) std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); auto now_ms = now.time_since_epoch(); auto now_sec = std::chrono::duration_cast<std::chrono::seconds>(now_ms); auto tm_ms = std::chrono::duration_cast<std::chrono::milliseconds>(now_ms - now_sec); std::time_t currentTime = std::chrono::system_clock::to_time_t(now); struct tm* localTime = std::localtime(&currentTime); auto timeStr = dawn::format("%02i:%02i:%02i.%03i", localTime->tm_hour, localTime->tm_min, localTime->tm_sec, tm_ms.count()); std::stringstream ss; ss << "[" << timeStr << "] "; ss << prefix << " [" << file << ":" << line << "] " << message << "\n"; return ss.str(); }; } dawn::Logger::DiagnosticFormatter makeGTClangDiagnosticFormatter(const std::string& prefix) { return [prefix](const std::string& message, const std::string& file, int line, const std::string& source, dawn::SourceLocation loc) -> std::string { // Get current date-time (up to ms accuracy) std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); auto now_ms = now.time_since_epoch(); auto now_sec = std::chrono::duration_cast<std::chrono::seconds>(now_ms); auto tm_ms = std::chrono::duration_cast<std::chrono::milliseconds>(now_ms - now_sec); std::time_t currentTime = std::chrono::system_clock::to_time_t(now); struct tm* localTime = std::localtime(&currentTime); auto timeStr = dawn::format("%02i:%02i:%02i.%03i", localTime->tm_hour, localTime->tm_min, localTime->tm_sec, tm_ms.count()); std::stringstream ss; ss << "[" << timeStr << "] "; ss << prefix << " [" << file << ":" << line << "] " << source; if(loc.Line) { ss << ":" << loc.Line; } if(loc.Column) { ss << ":" << loc.Column; } ss << " : " << message << "\n"; return ss.str(); }; } } // namespace gtclang
38.45
100
0.516905
muellch
dfd1932a30a21161f6deab54b076cc19ae0b4031
10,438
cpp
C++
source/gfx/gfx_objects.cpp
SaeruHikari/VulkanLittleMaster
204696b0eb87500bc6ed3ed7fca68f1458e698a1
[ "MIT" ]
3
2022-03-16T03:57:49.000Z
2022-03-20T08:05:35.000Z
source/gfx/gfx_objects.cpp
SaeruHikari/VulkanLittleMaster
204696b0eb87500bc6ed3ed7fca68f1458e698a1
[ "MIT" ]
null
null
null
source/gfx/gfx_objects.cpp
SaeruHikari/VulkanLittleMaster
204696b0eb87500bc6ed3ed7fca68f1458e698a1
[ "MIT" ]
null
null
null
#include "gfx/gfx_objects.h" #include <vector> #include <string_view> #include <iostream> void LittleGFXAdapter::queryProperties() { vkPhysDeviceProps.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2; vkGetPhysicalDeviceProperties2(vkPhysicalDevice, &vkPhysDeviceProps); std::cout << vkPhysDeviceProps.properties.deviceName << std::endl; } void LittleGFXAdapter::selectExtensionsAndLayers() { uint32_t ext_count = 0; vkEnumerateDeviceExtensionProperties(vkPhysicalDevice, NULL, &ext_count, NULL); std::vector<VkExtensionProperties> allExtentions(ext_count); vkEnumerateDeviceExtensionProperties(vkPhysicalDevice, NULL, &ext_count, allExtentions.data()); for (auto ext : wanted_device_exts) { for (auto usable_ext : allExtentions) { if (std::string_view(ext) == std::string_view(usable_ext.extensionName)) { deviceExtensions.emplace_back(ext); } } } } void LittleGFXAdapter::selectQueueIndices() { vkGetPhysicalDeviceQueueFamilyProperties(vkPhysicalDevice, &queueFamiliesCount, nullptr); std::vector<VkQueueFamilyProperties> queueProps(queueFamiliesCount); vkGetPhysicalDeviceQueueFamilyProperties(vkPhysicalDevice, &queueFamiliesCount, queueProps.data()); uint32_t queueIdx = 0; for (auto&& queueProp : queueProps) { // select graphics index if (queueProp.queueFlags & VK_QUEUE_GRAPHICS_BIT) { gfxQueueIndex = queueIdx; } queueIdx++; } } bool LittleGFXInstance::Initialize(bool enableDebugLayer) { // volk需要初始化,这个初始化过程其实就是在LoadLibrary("vulkan-1.dll") static VkResult volkInit = volkInitialize(); if (volkInit != VK_SUCCESS) { assert(0 && "Volk Initialize Failed!"); return false; } selectExtensionsAndLayers(enableDebugLayer); VkApplicationInfo appInfo = {}; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pApplicationName = "LittleMaster"; appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.pEngineName = "No Engine"; appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.apiVersion = VK_API_VERSION_1_1; VkInstanceCreateInfo createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; createInfo.pApplicationInfo = &appInfo; // 填写我们上文筛选出的可以打开的层以及扩展 createInfo.enabledLayerCount = (uint32_t)instanceLayers.size(); createInfo.ppEnabledLayerNames = instanceLayers.data(); createInfo.enabledExtensionCount = (uint32_t)instanceExtensions.size(); createInfo.ppEnabledExtensionNames = instanceExtensions.data(); // 创建VkInstance if (vkCreateInstance(&createInfo, nullptr, &vkInstance) != VK_SUCCESS) { assert(0 && "Vulkan: failed to create instance!"); } // 使用volk的动态加载方法,直接加载Instance中的Vulkan函数地址 volkLoadInstance(vkInstance); // 直接获取所有的Adapter/PhysicalDevice供以后使用 fetchAllAdapters(); return true; } bool LittleGFXInstance::Destroy() { vkDestroyInstance(vkInstance, VK_NULL_HANDLE); return true; } void LittleGFXInstance::selectExtensionsAndLayers(bool enableDebugLayer) { // 查询Extension支持并打开它们 { // 这是C API中很常用的一种两段式query法 uint32_t ext_count = 0; // 首先传入NULL Data和一个计数指针,API会返回一个数量 vkEnumerateInstanceExtensionProperties(NULL, &ext_count, NULL); // 随后应用程序可以根据返回的数量来开辟合适的空间 std::vector<VkExtensionProperties> allExtentions(ext_count); // 最后再把空间传回API,获得对应的返回数据 vkEnumerateInstanceExtensionProperties(NULL, &ext_count, allExtentions.data()); for (auto ext : wanted_instance_exts) { for (auto usable_ext : allExtentions) { if (std::string_view(ext) == std::string_view(usable_ext.extensionName)) { instanceExtensions.emplace_back(ext); } } } } // 查询Validation Layer支持并打开它 if (enableDebugLayer) { uint32_t layer_count = 0; vkEnumerateInstanceLayerProperties(&layer_count, NULL); std::vector<VkLayerProperties> allLayers(layer_count); vkEnumerateInstanceLayerProperties(&layer_count, allLayers.data()); for (auto usable_layer : allLayers) { if (std::string_view(validation_layer_name) == std::string_view(usable_layer.layerName)) { instanceLayers.emplace_back(validation_layer_name); } } } } void LittleGFXInstance::fetchAllAdapters() { uint32_t adapter_count = 0; vkEnumeratePhysicalDevices(vkInstance, &adapter_count, nullptr); adapters.resize(adapter_count); std::vector<VkPhysicalDevice> allVkAdapters(adapter_count); vkEnumeratePhysicalDevices(vkInstance, &adapter_count, allVkAdapters.data()); for (uint32_t i = 0; i < allVkAdapters.size(); i++) { adapters[i].gfxInstance = this; adapters[i].vkPhysicalDevice = allVkAdapters[i]; adapters[i].queryProperties(); adapters[i].selectExtensionsAndLayers(); adapters[i].selectQueueIndices(); } } // 队列优先级。概念上是分配不同Queue执行调度优先级的参数。 // 全部给1.f,忽略此参数。 const float queuePriorities[] = { 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, // 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, // 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, // 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, // }; bool LittleGFXDevice::Initialize(LittleGFXAdapter* adapter) { gfxAdapter = adapter; // 要申请的graphics queue VkDeviceQueueCreateInfo queueInfo = {}; queueInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueInfo.queueCount = 1; queueInfo.queueFamilyIndex = adapter->gfxQueueIndex; queueInfo.pQueuePriorities = queuePriorities; VkPhysicalDeviceFeatures deviceFeatures{}; VkDeviceCreateInfo deviceInfo = {}; deviceInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; deviceInfo.queueCreateInfoCount = 1; deviceInfo.pQueueCreateInfos = &queueInfo; deviceInfo.pEnabledFeatures = &deviceFeatures; // 打开需要的扩展和层 deviceInfo.enabledExtensionCount = adapter->deviceExtensions.size(); deviceInfo.ppEnabledExtensionNames = adapter->deviceExtensions.data(); deviceInfo.enabledLayerCount = adapter->deviceLayers.size(); deviceInfo.ppEnabledLayerNames = adapter->deviceLayers.data(); if (vkCreateDevice(adapter->vkPhysicalDevice, &deviceInfo, nullptr, &vkDevice) != VK_SUCCESS) { assert(0 && "failed to create logical device!"); return false; } // 使用volk从device中读出相关的API函数地址 // 这些API被放进volkTable中,因为转发层数很少所以性能有一定提升 volkLoadDeviceTable(&volkTable, vkDevice); return true; } bool LittleGFXDevice::Destroy() { vkDestroyDevice(vkDevice, nullptr); return true; } bool LittleGFXWindow::Initialize(const wchar_t* title, LittleGFXDevice* device, bool enableVsync) { auto succeed = LittleWindow::Initialize(title); gfxDevice = device; createSurface(device->gfxAdapter->gfxInstance); createSwapchainKHR(device, enableVsync); return succeed; } bool LittleGFXWindow::Destroy() { auto succeed = LittleWindow::Destroy(); gfxDevice->volkTable.vkDestroySwapchainKHR(gfxDevice->vkDevice, vkSwapchain, nullptr); vkDestroySurfaceKHR(gfxDevice->gfxAdapter->gfxInstance->vkInstance, vkSurface, nullptr); return succeed; } void LittleGFXWindow::createSurface(LittleGFXInstance* inst) { #if defined(_WIN32) || defined(_WIN64) VkWin32SurfaceCreateInfoKHR create_info = {}; create_info.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR; create_info.pNext = NULL; create_info.flags = 0; create_info.hinstance = GetModuleHandle(NULL); create_info.hwnd = hWnd; if (vkCreateWin32SurfaceKHR(inst->vkInstance, &create_info, nullptr, &vkSurface) != VK_SUCCESS) { assert(0 && "Create VKWin32 Surface Failed!"); } return; #endif assert(0 && "Platform not supported!"); } /* VkPresentModeKHR preferredModeList[] = { VK_PRESENT_MODE_IMMEDIATE_KHR, // normal VK_PRESENT_MODE_MAILBOX_KHR, // low latency VK_PRESENT_MODE_FIFO_RELAXED_KHR, // minimize stuttering VK_PRESENT_MODE_FIFO_KHR // low power consumption }; */ #define clamp(x, min, max) (x) < (min) ? (min) : ((x) > (max) ? (max) : (x)) void LittleGFXWindow::createSwapchainKHR(LittleGFXDevice* device, bool enableVsync) { // 获取surface支持的格式信息 VkSurfaceCapabilitiesKHR caps = { 0 }; vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device->gfxAdapter->vkPhysicalDevice, vkSurface, &caps); // 创建 uint32_t presentQueueFamilyIndex = device->gfxAdapter->gfxQueueIndex; VkExtent2D extent{ clamp(width, caps.minImageExtent.width, caps.maxImageExtent.width), clamp(height, caps.minImageExtent.height, caps.maxImageExtent.height) }; VkSwapchainCreateInfoKHR swapchainInfo = {}; swapchainInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; swapchainInfo.pNext = NULL; swapchainInfo.flags = 0; swapchainInfo.surface = vkSurface; swapchainInfo.minImageCount = enableVsync ? 3 : 2; swapchainInfo.presentMode = enableVsync ? VK_PRESENT_MODE_FIFO_KHR : VK_PRESENT_MODE_IMMEDIATE_KHR; // 因为OGL标准,此format和色彩空间一定是被现在的显卡支持的 swapchainInfo.imageFormat = VK_FORMAT_B8G8R8A8_UNORM; swapchainInfo.imageColorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; swapchainInfo.imageExtent = extent; swapchainInfo.imageArrayLayers = 1; swapchainInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; // 反转缓冲区呈现交换链是一种GPU行为,同样是被Queue执行的。这里指定可以执行Present操作的Queue。 swapchainInfo.queueFamilyIndexCount = 1; swapchainInfo.pQueueFamilyIndices = &presentQueueFamilyIndex; swapchainInfo.clipped = VK_TRUE; // 在这里指定一个老的交换链可以加速创建 swapchainInfo.oldSwapchain = VK_NULL_HANDLE; // 可以在呈现时指定某种变换,比如把图片逆时针旋转90度 swapchainInfo.preTransform = caps.currentTransform; // 是否使用Alpha通道和其它的窗口混合,这里可以实现很多奇特的效果,但是我们不需要。所以设定为OPAQUE(不透明)模式 swapchainInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; VkResult res = device->volkTable.vkCreateSwapchainKHR( device->vkDevice, &swapchainInfo, nullptr, &vkSwapchain); if (VK_SUCCESS != res) { assert(0 && "fatal: vkCreateSwapchainKHR failed!"); } }
37.68231
103
0.705403
SaeruHikari
2545e205869b639b32dce6ec67a8964fd50b4824
2,169
cpp
C++
LeetCode/C++/General/Medium/ExclusiveTimeOfFunctions/solution.cpp
busebd12/InterviewPreparation
e68c41f16f7790e44b10a229548186e13edb5998
[ "MIT" ]
null
null
null
LeetCode/C++/General/Medium/ExclusiveTimeOfFunctions/solution.cpp
busebd12/InterviewPreparation
e68c41f16f7790e44b10a229548186e13edb5998
[ "MIT" ]
null
null
null
LeetCode/C++/General/Medium/ExclusiveTimeOfFunctions/solution.cpp
busebd12/InterviewPreparation
e68c41f16f7790e44b10a229548186e13edb5998
[ "MIT" ]
null
null
null
#include <string> #include <unordered_map> #include <vector> using namespace std; /* Solution: inspired by this blog post --> https://leetcode.com/problems/exclusive-time-of-functions/discuss/1889699/CPP-O(n)-time-using-stack Time complexity: O(n) [where n is the length of logs] Space complexity: O(n) */ class Solution { public: vector<string> parseLog(string log) { vector<string> parts; stringstream ss(log); char delimiter=':'; string token{}; while(getline(ss, token, delimiter)) { parts.emplace_back(token); } return parts; } vector<int> exclusiveTime(int n, vector<string> & logs) { vector<int> result(n, 0); unordered_map<int, int> functionsToExecutionTime; int currentTime=0; deque<int> stack; for(auto log : logs) { auto parts=parseLog(log); int functionId=stoi(parts[0]); int timestamp=stoi(parts[2]); if(parts[1]=="start") { if(!stack.empty()) { functionsToExecutionTime[stack.back()]+=(timestamp - currentTime); } currentTime=timestamp; stack.emplace_back(functionId); } else { functionsToExecutionTime[stack.back()]+=(timestamp - currentTime) + 1; currentTime=timestamp + 1; stack.pop_back(); } } for(auto & [functionId, executionTime] : functionsToExecutionTime) { result[functionId]=executionTime; } return result; } };
27.1125
140
0.423237
busebd12
2547637c7fa4c3af8dc1ca379700190fbfc2dce1
1,878
cc
C++
second-project/solutions/TLM/LT/src/multiplier_LT.cc
elenaramon/Embedded-systems-design-projects
228f50e40a46a4c9fc738d38f910a22663900697
[ "MIT" ]
null
null
null
second-project/solutions/TLM/LT/src/multiplier_LT.cc
elenaramon/Embedded-systems-design-projects
228f50e40a46a4c9fc738d38f910a22663900697
[ "MIT" ]
null
null
null
second-project/solutions/TLM/LT/src/multiplier_LT.cc
elenaramon/Embedded-systems-design-projects
228f50e40a46a4c9fc738d38f910a22663900697
[ "MIT" ]
null
null
null
#include "multiplier_LT.hh" multiplier_LT::multiplier_LT(sc_module_name name_): sc_module(name_), target_socket("target_socket"), pending_transaction(NULL) { target_socket(*this); } void multiplier_LT::b_transport(tlm::tlm_generic_payload & trans, sc_time & t) { timing_annotation = SC_ZERO_TIME; ioDataStruct = *((iostruct*) trans.get_data_ptr()); if (trans.is_write()) { cout << "\t\t[MULTIPLIER:] Received invocation of the b_transport primitive - write" << endl; cout << "\t\t[MULTIPLIER:] Invoking the multiplication_function to calculate the floating point multiplication" << endl; multiplication_function(); ioDataStruct.result = tmp_result; cout << "\t\t[MULTIPLIER:] Returning result: " << tmp_result << endl; *((iostruct*) trans.get_data_ptr()) = ioDataStruct; trans.set_response_status(tlm::TLM_OK_RESPONSE); } else if (trans.is_read()) { cout << "\t\t[MULTIPLIER:] Received invocation of the b_transport primitive - read" << endl; ioDataStruct.result = tmp_result; cout << "\t\t[MULTIPLIER:] Returning result: " << tmp_result << endl; *((iostruct*) trans.get_data_ptr()) = ioDataStruct; } t += timing_annotation; } bool multiplier_LT::get_direct_mem_ptr(tlm::tlm_generic_payload & trans, tlm::tlm_dmi & dmi_data) { return false; } tlm::tlm_sync_enum multiplier_LT::nb_transport_fw(tlm::tlm_generic_payload & trans, tlm::tlm_phase & phase, sc_time & t) { return tlm::TLM_COMPLETED; } unsigned int multiplier_LT::transport_dbg(tlm::tlm_generic_payload & trans) { return 0; } void multiplier_LT:: multiplication_function() { cout << "\t\t[MULTIPLIER:] Calculating multiplication_function ... " << endl; tmp_result = float(ioDataStruct.op1 * ioDataStruct.op2); timing_annotation += sc_time(100, SC_NS); } void multiplier_LT::end_of_elaboration() { } void multiplier_LT::reset() { }
32.37931
129
0.71885
elenaramon
254779133b07ff07a5ad9bb642d5d4b4567dfdb0
244
cpp
C++
Sandbox/src/OtherTests.cpp
Hyxogen/Air-Tester
b495fa1f8cac1086577692aabc2fa21f2d648808
[ "Apache-2.0" ]
1
2021-11-16T14:50:01.000Z
2021-11-16T14:50:01.000Z
Sandbox/src/OtherTests.cpp
Hyxogen/Air-Tester
b495fa1f8cac1086577692aabc2fa21f2d648808
[ "Apache-2.0" ]
null
null
null
Sandbox/src/OtherTests.cpp
Hyxogen/Air-Tester
b495fa1f8cac1086577692aabc2fa21f2d648808
[ "Apache-2.0" ]
null
null
null
#include <AirTester.h> #include <iostream> TEST(other_tests, test_other) { EXPECT_TRUE(false); EXPECT_TRUE(!true); EXPECT_TRUE(!!false); EXPECT_TRUE(!!!!!false); EXPECT_TRUE(false); // std::cout << "This is another test!" << std::endl; }
22.181818
54
0.684426
Hyxogen
254ab8e1dd62bbb70df38566d0eedd2d9be7e406
1,307
cpp
C++
CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab 04(Unsorted List )/unsortedtype(23).cpp
diptu/Teaching
20655bb2c688ae29566b0a914df4a3e5936a2f61
[ "MIT" ]
null
null
null
CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab 04(Unsorted List )/unsortedtype(23).cpp
diptu/Teaching
20655bb2c688ae29566b0a914df4a3e5936a2f61
[ "MIT" ]
null
null
null
CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab 04(Unsorted List )/unsortedtype(23).cpp
diptu/Teaching
20655bb2c688ae29566b0a914df4a3e5936a2f61
[ "MIT" ]
null
null
null
#include "UnsortedType.h" template<class ItemType> UnsortedType<ItemType>::UnsortedType() { length=0; currentPos=-1; } template<class ItemType> void UnsortedType<ItemType>::MakeEmpty() { length =0; } template<class ItemType> bool UnsortedType<ItemType>::IsFull() { return (length == MAX_ITEMS); } template<class ItemType> int UnsortedType<ItemType>::LengthIs() { return length; } template<class ItemType> void UnsortedType<ItemType>::ResetList() { currentPos=-1; } template<class ItemType> void UnsortedType<ItemType>::GetNextItem(ItemType& item) { currentPos++; item = info[currentPos]; } template <class ItemType> void UnsortedType<ItemType>::RetrieveItem(ItemType& item, bool &found) { int location; found = false; for (location = 0; location < length; location++) { if(item == info[location]) { found = true; item = info[location]; break; } } } template<class ItemType> void UnsortedType<ItemType>::InsertItem(ItemType item) { info[length] = item; length++; } template<class ItemType> void UnsortedType<ItemType>::DeleteItem(ItemType item) { int location =0; while(item !=info[location]) location++; info[location]=info[length-1]; length--; }
16.3375
70
0.653405
diptu
255023e849b9bc071d3e5a5cb2a6f0054b4fd1b8
5,366
cpp
C++
ProblemSelect/Control.cpp
kravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
2
2018-04-27T11:07:02.000Z
2020-04-24T06:53:21.000Z
ProblemSelect/Control.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
ProblemSelect/Control.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
//********************************************************* // Control.cpp - Program Control //********************************************************* #include "ProblemSelect.hpp" #include "Utility.hpp" //--------------------------------------------------------- // Program_Control //--------------------------------------------------------- void ProblemSelect::Program_Control (void) { int type; char *str_ptr, *format_ptr, buffer [FIELD_BUFFER]; //---- open network files ---- Demand_Service::Program_Control (); //---- open the plan file ---- str_ptr = Get_Control_String (PROBLEM_FILE); if (str_ptr == NULL) goto control_error; format_ptr = Get_Control_String (PROBLEM_FORMAT); if (format_ptr != NULL) { problem_file.File_Format (format_ptr); } if (Partition ()) { problem_file.Filename (Project_Filename (str_ptr), Partition_Number ()); } else { problem_file.Filename (Project_Filename (str_ptr)); } Print_Filename (2, problem_file.File_Type (), problem_file.Groupname ()); if (!problem_file.Open (0)) { File_Error (problem_file.File_Type (), problem_file.Filename ()); } //---- get the household list ---- str_ptr = Get_Control_String (HOUSEHOLD_LIST); if (str_ptr != NULL) { hh_flag = true; str_ptr = Project_Filename (str_ptr, Extension ()); hhold_file.File_Type ("Household List"); Print_Filename (2, hhold_file.File_Type (), str_ptr); hhold_file.Filename (str_ptr); if (!hhold_file.Open (0)) { File_Error ("Opening Household List", hhold_file.Filename ()); } } //---- get the household list ---- str_ptr = Get_Control_String (NEW_HOUSEHOLD_LIST); if (str_ptr == NULL) goto control_error; str_ptr = Project_Filename (str_ptr, Extension ()); new_hhold_file.File_Type ("New Household List"); new_hhold_file.File_Access (Db_Code::CREATE); Print_Filename (2, new_hhold_file.File_Type (), str_ptr); new_hhold_file.Filename (str_ptr); if (!new_hhold_file.Open (0)) { File_Error ("Opening New Household List", new_hhold_file.Filename ()); } //---- get the select links ---- str_ptr = Get_Control_String (SELECT_LINKS); if (str_ptr != NULL) { Print (2, "Select Links = %s", str_ptr); if (!links.Add_Ranges (str_ptr)) { File_Error ("Link Range", str_ptr); } link_flag = true; if (!Network_File_Flag (LINK) || !Network_File_Flag (NODE)) { Error ("Link and Node files are required for Link-Based Processing"); } } //---- get the select time periods ---- str_ptr = Get_Control_String (SELECT_TIME_PERIODS); if (str_ptr != NULL) { Print (2, "Select Time Periods = %s", str_ptr); //---- get the time of day format ---- format_ptr = Get_Control_String (TIME_OF_DAY_FORMAT); if (format_ptr != NULL) { if (!times.Format (str_ptr)) { Error ("Time of Day Format %s was Unrecognized", format_ptr); } Print (1, "Time of Day Format = %s", format_ptr); } if (!times.Add_Ranges (str_ptr)) { File_Error ("Time Period Range", str_ptr); } time_flag = true; } //---- get the select problem types ---- str_ptr = Get_Control_String (SELECT_PROBLEM_TYPES); if (str_ptr != NULL) { Print (2, "Select Problem Types = %s", str_ptr); while (str_ptr != NULL) { str_ptr = Get_Token (str_ptr, buffer, sizeof (buffer)); if (buffer [0] != '\0') { type = Problem_Code (buffer); str_fmt (buffer, sizeof (buffer), "%d", type); if (!types.Add_Ranges (buffer)) { File_Error ("Problem Types", str_ptr); } type_flag = true; } } } //---- get the select subarea polygon ---- str_ptr = Get_Control_String (SELECT_SUBAREA_POLYGON); if (str_ptr != NULL) { Print (1); select_subarea.File_Type ("Select Subarea Polygon"); select_subarea.Open (Project_Filename (str_ptr)); if (!select_subarea.Read_Record ()) { Error ("Reading %s", select_subarea.File_Type ()); } subarea_flag = true; if (problem_file.Link_Field () > 0) { if (!Network_File_Flag (NODE) || !Network_File_Flag (LINK)) { Error ("Node and Link files are Required for Select Subarea Polygon"); } } if (!Network_File_Flag (ACTIVITY_LOCATION)) { Error ("An Activity Location file is Required for Select Subarea Polygon"); } } //---- get the selection percentage ---- str_ptr = Get_Control_String (SELECTION_PERCENTAGE); if (str_ptr != NULL) { Get_Double (str_ptr, &percent); if (percent < 0.1 || percent > 100.0) { Error ("Selection Percentage %.2lf is Out of Range (0.1-100.0)", percent); } select_flag = (percent != 100.0); } Print (2, "Selection Percentage = %.1lf%%", percent); percent /= 100.0; //---- get the max percent selected ---- str_ptr = Get_Control_String (MAXIMUM_PERCENT_SELECTED); if (str_ptr != NULL) { Get_Double (str_ptr, &max_percent); if (max_percent < 1.0 || max_percent > 100.0) { Error ("Maximum Percent Selected %.1lf is Out of Range (1.0-100.0)", max_percent); } } Print (1, "Maximum Percent Selected = %.1lf%%", max_percent); max_percent /= 100.0; //---- random number seed ---- str_ptr = Get_Control_String (RANDOM_NUMBER_SEED); if (str_ptr != NULL) { random.Seed (atoi (str_ptr)); } if (str_ptr != NULL || percent != 1.0 || max_percent != 1.0) { Print (1, "Random Number Seed = %d", random.Seed ()); } return; //---- error message ---- control_error: Error ("Missing Control Key = %s", Current_Key ()); }
25.074766
85
0.631196
kravitz
25534e17aafff04a64555557f7a5161924630dc5
364
cpp
C++
925. Long Pressed Name.cpp
rajeev-ranjan-au6/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
3
2020-12-30T00:29:59.000Z
2021-01-24T22:43:04.000Z
925. Long Pressed Name.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
925. Long Pressed Name.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
class Solution { public: bool isLongPressedName(string name, string typed) { int a = 0, b = 0, n = name.size(), m = typed.size(); while (a < n && b < m) { if (name[a++] != typed[b++]) return false; while (b > 0 && name[a] != typed[b] && typed[b] == typed[b - 1]) ++b; } return a == n && b == m; } };
30.333333
81
0.445055
rajeev-ranjan-au6