hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b15c5f4324e695b7db2e7ebc8dc2d552fc37b758 | 980 | cc | C++ | src/perf_to_profile.cc | cervantesyu/perf_data_converter | 5fe21942c1db6625963e657f458fea5c30af40e2 | [
"BSD-3-Clause"
] | null | null | null | src/perf_to_profile.cc | cervantesyu/perf_data_converter | 5fe21942c1db6625963e657f458fea5c30af40e2 | [
"BSD-3-Clause"
] | 1 | 2019-10-18T07:50:07.000Z | 2019-10-19T02:14:40.000Z | src/perf_to_profile.cc | cervantesyu/perf_data_converter | 5fe21942c1db6625963e657f458fea5c30af40e2 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2016, Google Inc.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "src/perf_to_profile_lib.h"
#include "src/quipper/base/logging.h"
#include "src/perf_data_converter.h"
int main(int argc, char** argv) {
string input, output;
bool overwriteOutput = false;
if (!ParseArguments(argc, const_cast<const char**>(argv), &input, &output,
&overwriteOutput)) {
PrintUsage();
return EXIT_FAILURE;
}
const auto profiles = StringToProfiles(ReadFileToString(input));
// With kNoOptions, all of the PID profiles should be merged into a
// single one.
if (profiles.size() != 1) {
LOG(FATAL) << "Expected profile vector to have one element.";
}
const auto& profile = profiles[0]->data;
std::ofstream outFile;
CreateFile(output, &outFile, overwriteOutput);
profile.SerializeToOstream(&outFile);
return EXIT_SUCCESS;
}
| 28 | 76 | 0.689796 | cervantesyu |
b15de914bdee652baa0d944113947a99f62db45c | 2,641 | cpp | C++ | src/futz/platforms/FutzGlut.cpp | zibas/futz | 83fc0e1a7489940bb55e2db6ccc8ca7d1ac0719f | [
"MIT"
] | 4 | 2019-01-30T00:14:29.000Z | 2020-05-15T01:14:28.000Z | src/futz/platforms/FutzGlut.cpp | zibas/futz | 83fc0e1a7489940bb55e2db6ccc8ca7d1ac0719f | [
"MIT"
] | null | null | null | src/futz/platforms/FutzGlut.cpp | zibas/futz | 83fc0e1a7489940bb55e2db6ccc8ca7d1ac0719f | [
"MIT"
] | null | null | null | /*
* FutzGlut.cpp
*
* Created on: Nov 3, 2010
* Author: ziba
*/
#if FUTZ_PLATFORM_GLUT
#ifdef _WIN32
#include <Windows.h>
#endif
#ifdef OSX
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#else
#include <GL/gl.h>
#include <GL/glu.h>
#ifdef _WIN32
#include <glut.h>
#else
#include <GL/glut.h>
#endif
#endif
#include "../Futz.h"
#include <stdio.h>
#include "FutzGlut.h"
void FutzGlut::Initialize(int argc, char** argv) {
glutInit(&argc, argv);
glutInitWindowSize(1024, 700);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_ALPHA);
glutCreateWindow("Futz - GLUT");
glutKeyboardFunc(FutzGlut::KeyPressFunc);
glutKeyboardUpFunc(FutzGlut::KeyUpFunc);
glutDisplayFunc(FutzGlut::RenderScene);
glutReshapeFunc(FutzGlut::Reshape);
//glutMouseFunc(MouseFunc);
glutPassiveMotionFunc(FutzGlut::PassiveMotion);
glutTimerFunc(500, FutzGlut::Timer, 1);
Futz* futz = Futz::Instance();
Futz::Instance()->camera->SetViewport(futz->platform->width, futz->platform->height);
Futz::Instance()->renderer->Initialize(futz->platform->width, futz->platform->height);
futz->gameObject->Start();
glutMainLoop();
}
void FutzGlut::Resize(int width, int height){
if (height==0)
height=1;
#ifndef OPENGLES1
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0f,(GLfloat)width/(GLfloat)height,0.1f,500.0f);
glMatrixMode(GL_MODELVIEW);
#endif
}
void FutzGlut::KeyPressFunc(unsigned char key, int x, int y) {
Futz* futz = Futz::Instance();
//futz->inputEventQueue.Push(key);
futz->input.SetDown(key);
}
void FutzGlut::KeyUpFunc(unsigned char key, int x, int y) {
Futz* futz = Futz::Instance();
futz->input.SetUp(key);
}
void FutzGlut::PassiveMotion(int x, int y) {
Futz* futz = Futz::Instance();
//futz->inputEventQueue.PushMouse(x, y);
futz->input.SetMouse(x,y);
}
void FutzGlut::RenderScene(void) {
Futz* futz = Futz::Instance();
futz->Render();
futz->gameObject->RenderLoop();
glutSwapBuffers();
}
void FutzGlut::Timer(int value) {
Futz* futz = Futz::Instance();
futz->Update();
glutPostRedisplay();
glutTimerFunc(5, FutzGlut::Timer, 1);
}
void FutzGlut::Reshape(int Width, int Height) {
Futz* futz = Futz::Instance();
futz->platform->Resize(Width, Height);
}
void FutzGlut::ToggleFullscreen(){
Futz* futz = Futz::Instance();
if(!futz->platform->isFullscreen){
glutFullScreen();
} else {
glutReshapeWindow(futz->platform->width, futz->platform->height);
}
futz->platform->isFullscreen = !futz->platform->isFullscreen;
}
FutzGlut::~FutzGlut() {
// TODO Auto-generated destructor stub
}
#endif | 21.471545 | 87 | 0.706172 | zibas |
b1613bae1ecfdc4f880b98c4a372c4239a7d9013 | 9,964 | cpp | C++ | ui_components/comboex/CheckCombo.cpp | l619534951/monitor_helper_duilib | a0df2a0285bdd37b77a611fba080dee0e55bda4f | [
"BSD-2-Clause",
"MIT"
] | null | null | null | ui_components/comboex/CheckCombo.cpp | l619534951/monitor_helper_duilib | a0df2a0285bdd37b77a611fba080dee0e55bda4f | [
"BSD-2-Clause",
"MIT"
] | null | null | null | ui_components/comboex/CheckCombo.cpp | l619534951/monitor_helper_duilib | a0df2a0285bdd37b77a611fba080dee0e55bda4f | [
"BSD-2-Clause",
"MIT"
] | null | null | null | #include "stdafx.h"
#include "CheckCombo.h"
namespace nim_comp
{
class CCheckComboWnd : public Window
{
public:
void Init(CheckCombo* pOwner);
virtual std::wstring GetWindowClassName() const override;
virtual void OnFinalMessage(HWND hWnd) override;
virtual LRESULT HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam) override;
void OnSeleteItem();
private:
CheckCombo *m_pOwner;
int m_iOldSel;
bool m_bClosing = false;
};
void CCheckComboWnd::Init(CheckCombo* pOwner)
{
m_pOwner = pOwner;
//m_iOldSel = m_pOwner->GetCurSel();
// Position the popup window in absolute space
CSize szDrop = m_pOwner->GetDropBoxSize();
UiRect rcOwner = m_pOwner->GetOrgPos();
UiRect rc = rcOwner;
rc.top = rc.bottom + 1; // 父窗口left、bottom位置作为弹出窗口起点
rc.bottom = rc.top + szDrop.cy; // 计算弹出窗口高度
if (szDrop.cx > 0) rc.right = rc.left + szDrop.cx; // 计算弹出窗口宽度
CSize szAvailable(rc.right - rc.left, rc.bottom - rc.top);
int cyFixed = 0;
for (int it = 0; it < pOwner->GetListBox()->GetCount(); it++) {
Control* pControl = pOwner->GetListBox()->GetItemAt(it);
if (!pControl->IsVisible()) continue;
CSize sz = pControl->EstimateSize(szAvailable);
cyFixed += sz.cy;
}
cyFixed += 2; // VBox 默认的Padding 调整
rc.bottom = rc.top + min(cyFixed, szDrop.cy);
::MapWindowRect(pOwner->GetWindow()->GetHWND(), HWND_DESKTOP, &rc);
MONITORINFO oMonitor = {};
oMonitor.cbSize = sizeof(oMonitor);
::GetMonitorInfo(::MonitorFromWindow(GetHWND(), MONITOR_DEFAULTTOPRIMARY), &oMonitor);
UiRect rcWork = oMonitor.rcWork;
if (rc.bottom > rcWork.bottom || m_pOwner->IsPopupTop()) {
rc.left = rcOwner.left;
rc.right = rcOwner.right;
if (szDrop.cx > 0) rc.right = rc.left + szDrop.cx;
rc.top = rcOwner.top - min(cyFixed, szDrop.cy);
rc.bottom = rcOwner.top;
::MapWindowRect(pOwner->GetWindow()->GetHWND(), HWND_DESKTOP, &rc);
}
Create(pOwner->GetWindow()->GetHWND(), NULL, WS_POPUP, WS_EX_TOOLWINDOW, true, rc);
// HACK: Don't deselect the parent's caption
HWND hWndParent = m_hWnd;
while (::GetParent(hWndParent) != NULL)
hWndParent = ::GetParent(hWndParent);
::ShowWindow(m_hWnd, SW_SHOW);
::SendMessage(hWndParent, WM_NCACTIVATE, TRUE, 0L);
}
std::wstring CCheckComboWnd::GetWindowClassName() const
{
return _T("ComboWnd");
}
void CCheckComboWnd::OnFinalMessage(HWND hWnd)
{
m_pOwner->m_pCheckComboWnd = NULL;
m_pOwner->m_uButtonState = kControlStateNormal;
m_pOwner->Invalidate();
delete this;
}
void CCheckComboWnd::OnSeleteItem()
{
PostMessage(WM_KILLFOCUS);
}
LRESULT CCheckComboWnd::HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if (uMsg == WM_CREATE) {
this->Window::Init(m_hWnd);
Box* pRoot = new Box;
pRoot->SetAutoDestroyChild(false);
pRoot->Add(m_pOwner->GetListBox());
this->AttachDialog(pRoot);
this->SetWindowResourcePath(m_pOwner->GetWindow()->GetWindowResourcePath());
this->SetShadowAttached(false);
return 0;
}
else if (uMsg == WM_CLOSE) {
m_pOwner->SetWindow(m_pOwner->GetWindow(), m_pOwner->GetParent(), false);
m_pOwner->SetPos(m_pOwner->GetPos());
m_pOwner->SetFocus();
}
else if (uMsg == WM_KILLFOCUS) {
if (m_hWnd != (HWND)wParam) {
m_bClosing = true;
PostMessage(WM_CLOSE);
((Box*)this->GetRoot())->RemoveAt(0);
m_pOwner->GetListBox()->PlaceHolder::SetWindow(nullptr, nullptr, false);
}
}
if (m_bClosing) {
return CallWindowProc(uMsg, wParam, lParam);
}
else {
bool handled = false;
LRESULT ret = this->DoHandlMessage(uMsg, wParam, lParam, handled);
if (handled) {
return ret;
}
else {
return CallWindowProc(uMsg, wParam, lParam);
}
}
}
////////////////////////////////////////////////////////
CheckCombo::CheckCombo() :
m_pCheckComboWnd(nullptr),
m_szDropBox(0, 150),
m_uButtonState(kControlStateNormal),
m_sDropBoxAttributes(),
m_bPopupTop(false),
m_iOrgHeight(20)
{
// The trick is to add the items to the new container. Their owner gets
// reassigned by this operation - which is why it is important to reassign
// the items back to the righfull owner/manager when the window closes.
m_pDropList.reset(new ListBox(new VLayout));
m_pDropList->GetLayout()->SetPadding(UiRect(1, 1, 1, 1));
m_pDropList->SetBkColor(L"bk_wnd_lightcolor");
m_pDropList->SetBorderColor(L"splitline_level1");
m_pDropList->SetBorderSize(UiRect(1, 1, 1, 1));
m_pDropList->SetAutoDestroyChild(false);
m_pDropList->EnableScrollBar();
m_pDropList->ApplyAttributeList(GetDropBoxAttributeList());
m_pList.reset(new ListBox(new VLayout));
//m_pList->SetMouseEnabled(false);
m_pList->AttachButtonDown(std::bind(&CheckCombo::OnListButtonDown, this, std::placeholders::_1));
m_pList->SetMouseChildEnabled(false);
//m_pList->SetAutoDestroyChild(false);
m_pList->EnableScrollBar();
Box::Add(m_pList.get());
SetMaxHeight(m_iOrgHeight * 3);
SetMinHeight(m_iOrgHeight);
}
CheckCombo::~CheckCombo()
{
Box::Remove(m_pList.get());
}
bool CheckCombo::Add(Control* pControl)
{
CheckBoxBox *pCheckBoxBox = nullptr;
CheckBox *pCheckBox = dynamic_cast<CheckBox*>(pControl);
if (pCheckBox)
{
pCheckBox->AttachSelect(std::bind(&CheckCombo::OnSelectItem, this, std::placeholders::_1));
pCheckBox->AttachUnSelect(std::bind(&CheckCombo::OnUnSelectItem, this, std::placeholders::_1));
}
else if (pCheckBoxBox = dynamic_cast<CheckBoxBox*>(pControl)) {
pCheckBoxBox->AttachSelect(std::bind(&CheckCombo::OnSelectItem, this, std::placeholders::_1));
pCheckBoxBox->AttachUnSelect(std::bind(&CheckCombo::OnUnSelectItem, this, std::placeholders::_1));
}
else
{
printf("CheckCombo::Add pControl is not CheckBox object\n");
assert(0);
return true;
}
m_pDropList->Add(pControl);
pControl->SetReceivePointerMsg(true);
return true;
}
bool CheckCombo::Remove(Control * pControl)
{
bool ret = m_pDropList->Remove(pControl);
return ret;
}
bool CheckCombo::RemoveAt(std::size_t iIndex)
{
bool ret = m_pDropList->RemoveAt((int)iIndex);
return ret;
}
void CheckCombo::RemoveAll()
{
m_pDropList->RemoveAll();
}
void CheckCombo::Activate()
{
if (!IsActivatable()) return;
if (m_pCheckComboWnd) return;
m_pCheckComboWnd = new CCheckComboWnd();
ASSERT(m_pCheckComboWnd);
m_pCheckComboWnd->Init(this);
if (m_pCheckComboWnd != NULL) m_pCheckComboWnd->SendNotify(this, kEventClick);
Invalidate();
}
void CheckCombo::SetAttribute(const std::wstring& strName, const std::wstring& strValue)
{
if (strName == _T("dropbox")) SetDropBoxAttributeList(strValue);
else if (strName == _T("vscrollbar")) {}
else if (strName == _T("dropboxsize")){
CSize szDropBoxSize;
LPTSTR pstr = NULL;
szDropBoxSize.cx = _tcstol(strValue.c_str(), &pstr, 10); ASSERT(pstr);
szDropBoxSize.cy = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr);
SetDropBoxSize(szDropBoxSize);
}
else if (strName == _T("popuptop")) SetPopupTop(strValue == _T("true"));
else if (strName == _T("height")) {
__super::SetAttribute(strName, strValue);
if (strValue != _T("stretch") && strValue != _T("auto")) {
ASSERT(_ttoi(strValue.c_str()) >= 0);
m_iOrgHeight = _ttoi(strValue.c_str());
SetMaxHeight(m_iOrgHeight * 3);
SetMinHeight(m_iOrgHeight);
}
}
else Box::SetAttribute(strName, strValue);
}
UiRect CheckCombo::GetOrgPos() const
{
UiRect rc = GetPosWithScrollOffset();
rc.bottom = rc.top + m_iOrgHeight;
return UiRect(rc);
}
std::wstring CheckCombo::GetDropBoxAttributeList()
{
return m_sDropBoxAttributes;
}
void CheckCombo::SetDropBoxAttributeList(const std::wstring& pstrList)
{
m_sDropBoxAttributes = pstrList;
}
CSize CheckCombo::GetDropBoxSize() const
{
return m_szDropBox;
}
void CheckCombo::SetDropBoxSize(CSize szDropBox)
{
DpiManager::GetInstance()->ScaleSize(szDropBox);
m_szDropBox = szDropBox;
}
bool CheckCombo::SelectItem(int iIndex)
{
/*if (iIndex < 0 || iIndex >= m_pDropList->GetCount() || m_iCurSel == iIndex)
return false;
m_iCurSel = iIndex;
m_pDropList->SelectItem(m_iCurSel);*/
return true;
}
Control* CheckCombo::GetItemAt(int iIndex)
{
return m_pDropList->GetItemAt(iIndex);
}
bool CheckCombo::OnSelectItem(EventArgs* args)
{
std::string date = args->pSender->GetUTF8DataID();
std::string text = date;
CheckBox *check = dynamic_cast<CheckBox*>(args->pSender);
if (check)
{
text = check->GetUTF8Text();
}
if (date.empty())
{
#ifdef _DEBUG
printf("CheckCombo::OnSelectItem date.empty()\n");
assert(0);
#endif
return true;
}
m_vecDate.push_back(date);
Label *item = new Label;
item->SetFixedWidth(DUI_LENGTH_AUTO);
item->SetFixedHeight(22);
item->SetMargin({ 4, 2, 4, 2 });
item->SetBkColor(L"bk_menuitem_selected");
item->SetTextPadding({ 2, 3, 2, 3 });
item->SetUTF8Name(date);
item->SetUTF8Text(text);
m_pList->Add(item);
SetFixedHeight(m_pList->GetCount() * m_iOrgHeight);
return true;
}
bool CheckCombo::OnUnSelectItem(EventArgs* args)
{
std::string date = args->pSender->GetUTF8DataID();
if (date.empty())
{
#ifdef _DEBUG
printf("CheckCombo::OnSelectItem date.empty()\n");
assert(0);
#endif
return true;
}
assert(std::find(m_vecDate.cbegin(), m_vecDate.cend(), date) != m_vecDate.cend());
if (std::find(m_vecDate.cbegin(), m_vecDate.cend(), date) != m_vecDate.cend())
{
m_vecDate.erase(std::find(m_vecDate.cbegin(), m_vecDate.cend(), date));
}
std::wstring utf16;
StringHelper::MBCSToUnicode(date, utf16, CP_UTF8);
Control *pRemove = m_pList->FindSubControl(utf16);
assert(pRemove);
if (pRemove)
m_pList->Remove(pRemove);
SetFixedHeight(m_pList->GetCount() * m_iOrgHeight);
return true;
}
void CheckCombo::ClearAllDate()
{
m_pList->RemoveAll();
m_pDropList->RemoveAll();
SetFixedHeight(m_iOrgHeight);
m_vecDate.clear();
}
bool CheckCombo::OnListButtonDown(EventArgs* args)
{
Activate();
return true;
}
} | 26.92973 | 101 | 0.691389 | l619534951 |
b161ae5e22605317290fd30b79ce84565cc1f983 | 25,206 | cpp | C++ | src/universal_robot/ur_modern_driver/src/ur_ros_wrapper.cpp | Slifer64/ur5_test_delay | c7e8460a89d967615592471ad5d196900c5e89df | [
"MIT"
] | null | null | null | src/universal_robot/ur_modern_driver/src/ur_ros_wrapper.cpp | Slifer64/ur5_test_delay | c7e8460a89d967615592471ad5d196900c5e89df | [
"MIT"
] | null | null | null | src/universal_robot/ur_modern_driver/src/ur_ros_wrapper.cpp | Slifer64/ur5_test_delay | c7e8460a89d967615592471ad5d196900c5e89df | [
"MIT"
] | null | null | null | #include "ur_modern_driver/ur_ros_wrapper.h"
namespace ur_
{
RosWrapper::RosWrapper(const std::string &robot_ip_address, int reverse_port):
spinner(3), as_(nh_, "follow_joint_trajectory", boost::bind(&RosWrapper::goalCB, this, _1), boost::bind(&RosWrapper::cancelCB, this, _1), false)
{
keep_alive = true;
bool use_sim_time = false;
std::string host = robot_ip_address;
if((reverse_port <= 0) or (reverse_port >= 65535))
{
print_warning("Reverse port value is not valid (Use number between 1 and 65534. Using default value of 50001");
reverse_port = 50001;
}
this->init(host, reverse_port);
spinner.start();
}
RosWrapper::~RosWrapper()
{
this->halt();
spinner.stop();
delete robot_;
}
void RosWrapper::init(std::string host, int reverse_port)
{
io_flag_delay_ = 0.05;
joint_offsets_ = {6, 0.0};
robot_ = new UrDriver(rt_msg_sem, msg_sem, host, reverse_port, 0.03, 300);
std::string joint_prefix = "";
std::vector<std::string> joint_names;
char buf[256];
if (ros::param::get("~prefix", joint_prefix))
{
if (joint_prefix.length() > 0)
{
sprintf(buf, "Setting prefix to %s", joint_prefix.c_str());
print_info(buf);
}
}
joint_names.push_back(joint_prefix + "shoulder_pan_joint");
joint_names.push_back(joint_prefix + "shoulder_lift_joint");
joint_names.push_back(joint_prefix + "elbow_joint");
joint_names.push_back(joint_prefix + "wrist_1_joint");
joint_names.push_back(joint_prefix + "wrist_2_joint");
joint_names.push_back(joint_prefix + "wrist_3_joint");
robot_->setJointNames(joint_names);
use_ros_control_ = false;
ros::param::get("~use_ros_control", use_ros_control_);
if (use_ros_control_) {
hardware_interface_.reset(
new ros_control_ur::UrHardwareInterface(nh_, robot_));
controller_manager_.reset(
new controller_manager::ControllerManager(
hardware_interface_.get(), nh_));
double max_vel_change = 0.12; // equivalent of an acceleration of 15 rad/sec^2
if (ros::param::get("~max_acceleration", max_vel_change)) {
max_vel_change = max_vel_change / 125;
}
sprintf(buf, "Max acceleration set to: %f [rad/sec²]",
max_vel_change * 125);
print_debug(buf);
hardware_interface_->setMaxVelChange(max_vel_change);
}
//Using a very high value in order to not limit execution of trajectories being sent from MoveIt!
max_velocity_ = 10.;
if (ros::param::get("~max_velocity", max_velocity_)) {
sprintf(buf, "Max velocity accepted by ur_driver: %f [rad/s]",
max_velocity_);
print_debug(buf);
}
//Bounds for SetPayload service
//Using a very conservative value as it should be set through the parameter server
double min_payload = 0.;
double max_payload = 1.;
if (ros::param::get("~min_payload", min_payload)) {
sprintf(buf, "Min payload set to: %f [kg]", min_payload);
print_debug(buf);
}
if (ros::param::get("~max_payload", max_payload)) {
sprintf(buf, "Max payload set to: %f [kg]", max_payload);
print_debug(buf);
}
robot_->setMinPayload(min_payload);
robot_->setMaxPayload(max_payload);
sprintf(buf, "Bounds for set_payload service calls: [%f, %f]",
min_payload, max_payload);
print_debug(buf);
double servoj_time = 0.008;
if (ros::param::get("~servoj_time", servoj_time)) {
sprintf(buf, "Servoj_time set to: %f [sec]", servoj_time);
print_debug(buf);
}
robot_->setServojTime(servoj_time);
double servoj_lookahead_time = 0.03;
if (ros::param::get("~servoj_lookahead_time", servoj_lookahead_time)) {
sprintf(buf, "Servoj_lookahead_time set to: %f [sec]", servoj_lookahead_time);
print_debug(buf);
}
robot_->setServojLookahead(servoj_lookahead_time);
double servoj_gain = 300.;
if (ros::param::get("~servoj_gain", servoj_gain)) {
sprintf(buf, "Servoj_gain set to: %f [sec]", servoj_gain);
print_debug(buf);
}
robot_->setServojGain(servoj_gain);
//Base and tool frames
base_frame_ = joint_prefix + "base_link";
tool_frame_ = joint_prefix + "tool0_controller";
if (ros::param::get("~base_frame", base_frame_)) {
sprintf(buf, "Base frame set to: %s", base_frame_.c_str());
print_debug(buf);
}
if (ros::param::get("~tool_frame", tool_frame_)) {
sprintf(buf, "Tool frame set to: %s", tool_frame_.c_str());
print_debug(buf);
}
if (robot_->start())
{
if (use_ros_control_) {
ros_control_thread_ = new std::thread( boost::bind(&RosWrapper::rosControlLoop, this));
print_debug("The control thread for this driver has been started");
} else {
//start actionserver
has_goal_ = false;
as_.start();
//subscribe to the data topic of interest
rt_publish_thread_ = std::thread(std::bind(&RosWrapper::publishRTMsg, this));
print_debug("The action server for this driver has been started");
}
// mb_publish_thread_ = std::thread(std::bind(&RosWrapper::publishMbMsg, this));
speed_sub_ = nh_.subscribe("ur_driver/joint_speed", 1, &RosWrapper::speedInterface, this);
urscript_sub_ = nh_.subscribe("ur_driver/URScript", 1, &RosWrapper::urscriptInterface, this);
io_srv_ = nh_.advertiseService("ur_driver/set_io", &RosWrapper::setIO, this);
payload_srv_ = nh_.advertiseService("ur_driver/set_payload", &RosWrapper::setPayload, this);
}
}
void RosWrapper::halt()
{
keep_alive = false;
robot_->halt();
if (rt_publish_thread_.joinable()) rt_publish_thread_.join();
}
// private
void RosWrapper::trajThread(std::vector<double> timestamps, std::vector<std::vector<double> > positions, std::vector<std::vector<double> > velocities)
{
robot_->doTraj(timestamps, positions, velocities);
if (has_goal_) {
result_.error_code = result_.SUCCESSFUL;
goal_handle_.setSucceeded(result_);
has_goal_ = false;
}
}
void RosWrapper::goalCB(actionlib::ServerGoalHandle<control_msgs::FollowJointTrajectoryAction> gh)
{
std::string buf;
print_info("on_goal");
if (!robot_->sec_interface_->robot_state_.isReady()) {
result_.error_code = -100; //nothing is defined for this...?
if (!robot_->sec_interface_->robot_state_.isPowerOnRobot()) {
result_.error_string =
"Cannot accept new trajectories: Robot arm is not powered on";
gh.setRejected(result_, result_.error_string);
print_error(result_.error_string);
return;
}
if (!robot_->sec_interface_->robot_state_.isRealRobotEnabled()) {
result_.error_string =
"Cannot accept new trajectories: Robot is not enabled";
gh.setRejected(result_, result_.error_string);
print_error(result_.error_string);
return;
}
result_.error_string =
"Cannot accept new trajectories. (Debug: Robot mode is "
+ std::to_string(
robot_->sec_interface_->robot_state_.getRobotMode())
+ ")";
gh.setRejected(result_, result_.error_string);
print_error(result_.error_string);
return;
}
if (robot_->sec_interface_->robot_state_.isEmergencyStopped()) {
result_.error_code = -100; //nothing is defined for this...?
result_.error_string =
"Cannot accept new trajectories: Robot is emergency stopped";
gh.setRejected(result_, result_.error_string);
print_error(result_.error_string);
return;
}
if (robot_->sec_interface_->robot_state_.isProtectiveStopped()) {
result_.error_code = -100; //nothing is defined for this...?
result_.error_string =
"Cannot accept new trajectories: Robot is protective stopped";
gh.setRejected(result_, result_.error_string);
print_error(result_.error_string);
return;
}
actionlib::ActionServer<control_msgs::FollowJointTrajectoryAction>::Goal goal =
*gh.getGoal(); //make a copy that we can modify
if (has_goal_) {
print_warning(
"Received new goal while still executing previous trajectory. Canceling previous trajectory");
has_goal_ = false;
robot_->stopTraj();
result_.error_code = -100; //nothing is defined for this...?
result_.error_string = "Received another trajectory";
goal_handle_.setAborted(result_, result_.error_string);
std::this_thread::sleep_for(std::chrono::milliseconds(250));
}
goal_handle_ = gh;
if (!validateJointNames()) {
std::string outp_joint_names = "";
for (unsigned int i = 0; i < goal.trajectory.joint_names.size();
i++) {
outp_joint_names += goal.trajectory.joint_names[i] + " ";
}
result_.error_code = result_.INVALID_JOINTS;
result_.error_string =
"Received a goal with incorrect joint names: "
+ outp_joint_names;
gh.setRejected(result_, result_.error_string);
print_error(result_.error_string);
return;
}
if (!has_positions()) {
result_.error_code = result_.INVALID_GOAL;
result_.error_string = "Received a goal without positions";
gh.setRejected(result_, result_.error_string);
print_error(result_.error_string);
return;
}
if (!has_velocities()) {
result_.error_code = result_.INVALID_GOAL;
result_.error_string = "Received a goal without velocities";
gh.setRejected(result_, result_.error_string);
print_error(result_.error_string);
return;
}
if (!traj_is_finite()) {
result_.error_string = "Received a goal with infinities or NaNs";
result_.error_code = result_.INVALID_GOAL;
gh.setRejected(result_, result_.error_string);
print_error(result_.error_string);
return;
}
if (!has_limited_velocities()) {
result_.error_code = result_.INVALID_GOAL;
result_.error_string =
"Received a goal with velocities that are higher than "
+ std::to_string(max_velocity_);
gh.setRejected(result_, result_.error_string);
print_error(result_.error_string);
return;
}
reorder_traj_joints(goal.trajectory);
if (!start_positions_match(goal.trajectory, 0.01)) {
result_.error_code = result_.INVALID_GOAL;
result_.error_string = "Goal start doesn't match current pose";
gh.setRejected(result_, result_.error_string);
print_error(result_.error_string);
return;
}
std::vector<double> timestamps;
std::vector<std::vector<double> > positions, velocities;
if (goal.trajectory.points[0].time_from_start.toSec() != 0.) {
print_warning(
"Trajectory's first point should be the current position, with time_from_start set to 0.0 - Inserting point in malformed trajectory");
timestamps.push_back(0.0);
positions.push_back(
robot_->rt_interface_->robot_state_.getQActual());
velocities.push_back(
robot_->rt_interface_->robot_state_.getQdActual());
}
for (unsigned int i = 0; i < goal.trajectory.points.size(); i++) {
timestamps.push_back(
goal.trajectory.points[i].time_from_start.toSec());
positions.push_back(goal.trajectory.points[i].positions);
velocities.push_back(goal.trajectory.points[i].velocities);
}
goal_handle_.setAccepted();
has_goal_ = true;
std::thread(&RosWrapper::trajThread, this, timestamps, positions,
velocities).detach();
}
void RosWrapper::cancelCB(actionlib::ServerGoalHandle<control_msgs::FollowJointTrajectoryAction> gh)
{
// set the action state to preempted
print_info("on_cancel");
if (has_goal_) {
if (gh == goal_handle_) {
robot_->stopTraj();
has_goal_ = false;
}
}
result_.error_code = -100; //nothing is defined for this...?
result_.error_string = "Goal cancelled by client";
gh.setCanceled(result_);
}
bool RosWrapper::setIO(ur_msgs::SetIORequest& req, ur_msgs::SetIOResponse& resp)
{
resp.success = true;
//if (req.fun == ur_msgs::SetIO::Request::FUN_SET_DIGITAL_OUT) {
if (req.fun == 1) {
robot_->setDigitalOut(req.pin, req.state > 0.0 ? true : false);
} else if (req.fun == 2) {
//} else if (req.fun == ur_msgs::SetIO::Request::FUN_SET_FLAG) {
robot_->setFlag(req.pin, req.state > 0.0 ? true : false);
//According to urdriver.py, set_flag will fail if called to rapidly in succession
ros::Duration(io_flag_delay_).sleep();
} else if (req.fun == 3) {
//} else if (req.fun == ur_msgs::SetIO::Request::FUN_SET_ANALOG_OUT) {
robot_->setAnalogOut(req.pin, req.state);
} else if (req.fun == 4) {
//} else if (req.fun == ur_msgs::SetIO::Request::FUN_SET_TOOL_VOLTAGE) {
robot_->setToolVoltage((int) req.state);
} else {
resp.success = false;
}
return resp.success;
}
bool RosWrapper::setPayload(ur_msgs::SetPayloadRequest& req, ur_msgs::SetPayloadResponse& resp)
{
if (robot_->setPayload(req.payload))
resp.success = true;
else
resp.success = true;
return resp.success;
}
bool RosWrapper::validateJointNames()
{
std::vector<std::string> actual_joint_names = robot_->getJointNames();
actionlib::ActionServer<control_msgs::FollowJointTrajectoryAction>::Goal goal =
*goal_handle_.getGoal();
if (goal.trajectory.joint_names.size() != actual_joint_names.size())
return false;
for (unsigned int i = 0; i < goal.trajectory.joint_names.size(); i++) {
unsigned int j;
for (j = 0; j < actual_joint_names.size(); j++) {
if (goal.trajectory.joint_names[i] == actual_joint_names[j])
break;
}
if (goal.trajectory.joint_names[i] == actual_joint_names[j]) {
actual_joint_names.erase(actual_joint_names.begin() + j);
} else {
return false;
}
}
return true;
}
void RosWrapper::reorder_traj_joints(trajectory_msgs::JointTrajectory& traj)
{
/* Reorders trajectory - destructive */
std::vector<std::string> actual_joint_names = robot_->getJointNames();
std::vector<unsigned int> mapping;
mapping.resize(actual_joint_names.size(), actual_joint_names.size());
for (unsigned int i = 0; i < traj.joint_names.size(); i++) {
for (unsigned int j = 0; j < actual_joint_names.size(); j++) {
if (traj.joint_names[i] == actual_joint_names[j])
mapping[j] = i;
}
}
traj.joint_names = actual_joint_names;
std::vector<trajectory_msgs::JointTrajectoryPoint> new_traj;
for (unsigned int i = 0; i < traj.points.size(); i++) {
trajectory_msgs::JointTrajectoryPoint new_point;
for (unsigned int j = 0; j < traj.points[i].positions.size(); j++) {
new_point.positions.push_back(
traj.points[i].positions[mapping[j]]);
new_point.velocities.push_back(
traj.points[i].velocities[mapping[j]]);
if (traj.points[i].accelerations.size() != 0)
new_point.accelerations.push_back(
traj.points[i].accelerations[mapping[j]]);
}
new_point.time_from_start = traj.points[i].time_from_start;
new_traj.push_back(new_point);
}
traj.points = new_traj;
}
bool RosWrapper::has_velocities()
{
actionlib::ActionServer<control_msgs::FollowJointTrajectoryAction>::Goal goal =
*goal_handle_.getGoal();
for (unsigned int i = 0; i < goal.trajectory.points.size(); i++) {
if (goal.trajectory.points[i].positions.size()
!= goal.trajectory.points[i].velocities.size())
return false;
}
return true;
}
bool RosWrapper::has_positions()
{
actionlib::ActionServer<control_msgs::FollowJointTrajectoryAction>::Goal goal =
*goal_handle_.getGoal();
if (goal.trajectory.points.size() == 0)
return false;
for (unsigned int i = 0; i < goal.trajectory.points.size(); i++) {
if (goal.trajectory.points[i].positions.size()
!= goal.trajectory.joint_names.size())
return false;
}
return true;
}
bool RosWrapper::start_positions_match(const trajectory_msgs::JointTrajectory &traj, double eps)
{
for (unsigned int i = 0; i < traj.points[0].positions.size(); i++)
{
std::vector<double> qActual = robot_->rt_interface_->robot_state_.getQActual();
if( fabs(traj.points[0].positions[i] - qActual[i]) > eps )
{
return false;
}
}
return true;
}
bool RosWrapper::has_limited_velocities()
{
actionlib::ActionServer<control_msgs::FollowJointTrajectoryAction>::Goal goal =
*goal_handle_.getGoal();
for (unsigned int i = 0; i < goal.trajectory.points.size(); i++) {
for (unsigned int j = 0;
j < goal.trajectory.points[i].velocities.size(); j++) {
if (fabs(goal.trajectory.points[i].velocities[j])
> max_velocity_)
return false;
}
}
return true;
}
bool RosWrapper::traj_is_finite()
{
actionlib::ActionServer<control_msgs::FollowJointTrajectoryAction>::Goal goal =
*goal_handle_.getGoal();
for (unsigned int i = 0; i < goal.trajectory.points.size(); i++) {
for (unsigned int j = 0;
j < goal.trajectory.points[i].velocities.size(); j++) {
if (!std::isfinite(goal.trajectory.points[i].positions[j]))
return false;
if (!std::isfinite(goal.trajectory.points[i].velocities[j]))
return false;
}
}
return true;
}
void RosWrapper::speedInterface(const trajectory_msgs::JointTrajectory::Ptr& msg)
{
if (msg->points[0].velocities.size() == 6) {
double acc = 100;
if (msg->points[0].accelerations.size() > 0)
acc = *std::max_element(msg->points[0].accelerations.begin(),
msg->points[0].accelerations.end());
robot_->setSpeed(msg->points[0].velocities[0],
msg->points[0].velocities[1], msg->points[0].velocities[2],
msg->points[0].velocities[3], msg->points[0].velocities[4],
msg->points[0].velocities[5], acc);
}
}
void RosWrapper::urscriptInterface(const std_msgs::String::ConstPtr& msg)
{
robot_->rt_interface_->addCommandToQueue(msg->data);
}
void RosWrapper::rosControlLoop()
{
ros::Duration elapsed_time;
struct timespec last_time, current_time;
static const double BILLION = 1000000000.0;
realtime_tools::RealtimePublisher<tf::tfMessage> tf_pub( nh_, "/tf", 1 );
geometry_msgs::TransformStamped tool_transform;
tool_transform.header.frame_id = base_frame_;
tool_transform.child_frame_id = tool_frame_;
tf_pub.msg_.transforms.push_back( tool_transform );
realtime_tools::RealtimePublisher<geometry_msgs::TwistStamped> tool_vel_pub( nh_, "tool_velocity", 1 );
tool_vel_pub.msg_.header.frame_id = base_frame_;
clock_gettime(CLOCK_MONOTONIC, &last_time);
while (ros::ok()) {
while (!robot_->rt_interface_->robot_state_.getControllerUpdated()) {
rt_msg_sem.wait();
}
// Input
hardware_interface_->read();
robot_->rt_interface_->robot_state_.setControllerUpdated();
// Control
clock_gettime(CLOCK_MONOTONIC, ¤t_time);
elapsed_time = ros::Duration(current_time.tv_sec - last_time.tv_sec + (current_time.tv_nsec - last_time.tv_nsec)/ BILLION);
ros::Time ros_time = ros::Time::now();
controller_manager_->update(ros_time, elapsed_time);
last_time = current_time;
// Output
hardware_interface_->write();
// Tool vector: Actual Cartesian coordinates of the tool: (x,y,z,rx,ry,rz), where rx, ry and rz is a rotation vector representation of the tool orientation
std::vector<double> tool_vector_actual = robot_->rt_interface_->robot_state_.getToolVectorActual();
// Compute rotation angle
double rx = tool_vector_actual[3];
double ry = tool_vector_actual[4];
double rz = tool_vector_actual[5];
double angle = std::sqrt(std::pow(rx,2) + std::pow(ry,2) + std::pow(rz,2));
// Broadcast transform
if( tf_pub.trylock() )
{
tf_pub.msg_.transforms[0].header.stamp = ros_time;
if (angle < 1e-16) {
tf_pub.msg_.transforms[0].transform.rotation.x = 0;
tf_pub.msg_.transforms[0].transform.rotation.y = 0;
tf_pub.msg_.transforms[0].transform.rotation.z = 0;
tf_pub.msg_.transforms[0].transform.rotation.w = 1;
} else {
tf_pub.msg_.transforms[0].transform.rotation.x = (rx/angle) * std::sin(angle*0.5);
tf_pub.msg_.transforms[0].transform.rotation.y = (ry/angle) * std::sin(angle*0.5);
tf_pub.msg_.transforms[0].transform.rotation.z = (rz/angle) * std::sin(angle*0.5);
tf_pub.msg_.transforms[0].transform.rotation.w = std::cos(angle*0.5);
}
tf_pub.msg_.transforms[0].transform.translation.x = tool_vector_actual[0];
tf_pub.msg_.transforms[0].transform.translation.y = tool_vector_actual[1];
tf_pub.msg_.transforms[0].transform.translation.z = tool_vector_actual[2];
tf_pub.unlockAndPublish();
}
//Publish tool velocity
std::vector<double> tcp_speed = robot_->rt_interface_->robot_state_.getTcpSpeedActual();
if( tool_vel_pub.trylock() )
{
tool_vel_pub.msg_.header.stamp = ros_time;
tool_vel_pub.msg_.twist.linear.x = tcp_speed[0];
tool_vel_pub.msg_.twist.linear.y = tcp_speed[1];
tool_vel_pub.msg_.twist.linear.z = tcp_speed[2];
tool_vel_pub.msg_.twist.angular.x = tcp_speed[3];
tool_vel_pub.msg_.twist.angular.y = tcp_speed[4];
tool_vel_pub.msg_.twist.angular.z = tcp_speed[5];
tool_vel_pub.unlockAndPublish();
}
}
}
void RosWrapper::publishRTMsg()
{
ros::Publisher joint_pub = nh_.advertise<sensor_msgs::JointState>("joint_states", 1);
ros::Publisher wrench_pub = nh_.advertise<geometry_msgs::WrenchStamped>("wrench", 1);
ros::Publisher tool_vel_pub = nh_.advertise<geometry_msgs::TwistStamped>("tool_velocity", 1);
static tf::TransformBroadcaster br;
while (keep_alive)
{
sensor_msgs::JointState joint_msg;
joint_msg.name = robot_->getJointNames();
geometry_msgs::WrenchStamped wrench_msg;
geometry_msgs::PoseStamped tool_pose_msg;
// while (keep_alive && !robot_->rt_interface_->robot_state_.getDataPublished())
rt_msg_sem.wait();
joint_msg.header.stamp = ros::Time::now();
joint_msg.position = robot_->rt_interface_->robot_state_.getQActual();
for (unsigned int i = 0; i < joint_msg.position.size(); i++) joint_msg.position[i] += joint_offsets_[i];
joint_msg.velocity = robot_->rt_interface_->robot_state_.getQdActual();
joint_msg.effort = robot_->rt_interface_->robot_state_.getIActual();
joint_pub.publish(joint_msg);
std::vector<double> tcp_force = robot_->rt_interface_->robot_state_.getTcpForce();
wrench_msg.header.stamp = joint_msg.header.stamp;
wrench_msg.wrench.force.x = tcp_force[0];
wrench_msg.wrench.force.y = tcp_force[1];
wrench_msg.wrench.force.z = tcp_force[2];
wrench_msg.wrench.torque.x = tcp_force[3];
wrench_msg.wrench.torque.y = tcp_force[4];
wrench_msg.wrench.torque.z = tcp_force[5];
wrench_pub.publish(wrench_msg);
// Tool vector: Actual Cartesian coordinates of the tool: (x,y,z,rx,ry,rz), where rx, ry and rz is a rotation vector representation of the tool orientation
std::vector<double> tool_vector_actual = robot_->rt_interface_->robot_state_.getToolVectorActual();
//Create quaternion
tf::Quaternion quat;
double rx = tool_vector_actual[3];
double ry = tool_vector_actual[4];
double rz = tool_vector_actual[5];
double angle = std::sqrt(std::pow(rx,2) + std::pow(ry,2) + std::pow(rz,2));
if (angle < 1e-16) quat.setValue(0, 0, 0, 1);
else quat.setRotation(tf::Vector3(rx/angle, ry/angle, rz/angle), angle);
//Create and broadcast transform
tf::Transform transform;
transform.setOrigin(tf::Vector3(tool_vector_actual[0], tool_vector_actual[1], tool_vector_actual[2]));
transform.setRotation(quat);
br.sendTransform(tf::StampedTransform(transform, joint_msg.header.stamp, base_frame_, tool_frame_));
//Publish tool velocity
std::vector<double> tcp_speed = robot_->rt_interface_->robot_state_.getTcpSpeedActual();
geometry_msgs::TwistStamped tool_twist;
tool_twist.header.frame_id = base_frame_;
tool_twist.header.stamp = joint_msg.header.stamp;
tool_twist.twist.linear.x = tcp_speed[0];
tool_twist.twist.linear.y = tcp_speed[1];
tool_twist.twist.linear.z = tcp_speed[2];
tool_twist.twist.angular.x = tcp_speed[3];
tool_twist.twist.angular.y = tcp_speed[4];
tool_twist.twist.angular.z = tcp_speed[5];
tool_vel_pub.publish(tool_twist);
robot_->rt_interface_->robot_state_.setDataPublished();
}
}
void RosWrapper::publishMbMsg()
{
bool warned = false;
ros::Publisher io_pub = nh_.advertise<ur_msgs::IOStates>("ur_driver/io_states", 1);
while (ros::ok())
{
ur_msgs::IOStates io_msg;
while (!robot_->sec_interface_->robot_state_.getNewDataAvailable()) msg_sem.wait();
int i_max = 10;
if (robot_->sec_interface_->robot_state_.getVersion() > 3.0)
i_max = 18; // From version 3.0, there are up to 18 inputs and outputs
for (unsigned int i = 0; i < i_max; i++)
{
ur_msgs::Digital digi;
digi.pin = i;
digi.state = ((robot_->sec_interface_->robot_state_.getDigitalInputBits() & (1 << i)) >> i);
io_msg.digital_in_states.push_back(digi);
digi.state = ((robot_->sec_interface_->robot_state_.getDigitalOutputBits() & (1 << i)) >> i);
io_msg.digital_out_states.push_back(digi);
}
ur_msgs::Analog ana;
ana.pin = 0;
ana.state = robot_->sec_interface_->robot_state_.getAnalogInput0();
io_msg.analog_in_states.push_back(ana);
ana.pin = 1;
ana.state = robot_->sec_interface_->robot_state_.getAnalogInput1();
io_msg.analog_in_states.push_back(ana);
ana.pin = 0;
ana.state = robot_->sec_interface_->robot_state_.getAnalogOutput0();
io_msg.analog_out_states.push_back(ana);
ana.pin = 1;
ana.state = robot_->sec_interface_->robot_state_.getAnalogOutput1();
io_msg.analog_out_states.push_back(ana);
io_pub.publish(io_msg);
if (robot_->sec_interface_->robot_state_.isEmergencyStopped()
or robot_->sec_interface_->robot_state_.isProtectiveStopped())
{
if (robot_->sec_interface_->robot_state_.isEmergencyStopped() and !warned)
{
print_error("Emergency stop pressed!");
}
else if (robot_->sec_interface_->robot_state_.isProtectiveStopped() and !warned)
{
print_error("Robot is protective stopped!");
}
if (has_goal_)
{
print_error("Aborting trajectory");
robot_->stopTraj();
result_.error_code = result_.SUCCESSFUL;
result_.error_string = "Robot was halted";
goal_handle_.setAborted(result_, result_.error_string);
has_goal_ = false;
}
warned = true;
}
else warned = false;
robot_->sec_interface_->robot_state_.finishedReading();
}
}
} // namespace ur_
| 34.576132 | 159 | 0.719829 | Slifer64 |
b16a24468a2a1321b48701381e8ee37fa4eda76a | 3,264 | cpp | C++ | getic/ProgressDlg.cpp | circinusX1/getic3d | a9c54c977f2f4fef8bc3a5f91f9d8e99684e5eb5 | [
"BSD-4-Clause"
] | null | null | null | getic/ProgressDlg.cpp | circinusX1/getic3d | a9c54c977f2f4fef8bc3a5f91f9d8e99684e5eb5 | [
"BSD-4-Clause"
] | 1 | 2020-09-01T15:02:02.000Z | 2020-09-01T16:11:07.000Z | getic/ProgressDlg.cpp | circinusX1/getic3d | a9c54c977f2f4fef8bc3a5f91f9d8e99684e5eb5 | [
"BSD-4-Clause"
] | 1 | 2020-09-08T19:14:57.000Z | 2020-09-08T19:14:57.000Z | // ProgressDlg.cpp: implementation of the ProgressDlg class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "z-edmap.h"
#include "ProgressDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// ProgressDlg
ProgressDlg ProgressDlg::GWaitDlg;
size_t ThreadProc(LPVOID pVoid);
//////////////////////////////////////////////////////////////////////////////
HICON __icos[4]={0};
HANDLE ProgressDlg ::event;
HWND ProgressDlg ::hDialog;
BOOL ProgressDlg::_visible;
size_t ProgressDlg::timeStart;
size_t DlgID;
BOOL DialogProc(HWND hw,size_t msg,WPARAM w,LPARAM l)
{
static HWND hEdit;
static int msgs = 0;
static int icoidx=0;
switch(msg)
{
case WM_INITDIALOG:
#ifdef _FREE
::SetWindowPos(hw, HWND_TOPMOST,0,0,0,0,SWP_SHOWWINDOW|SWP_NOMOVE|SWP_NOSIZE);
#endif //
::SetTimer(hw, 369, 60, 0);
ProgressDlg::_visible=FALSE;
ProgressDlg::timeStart=GetTickCount();
ProgressDlg ::hDialog = hw;
SetEvent (ProgressDlg ::event);
hEdit = ::GetDlgItem(hw,EF_OUT);
msgs = 0;
return FALSE;
case WM_TIMER:
::SendDlgItemMessage(hw, ST_ANI_ICON, STM_SETIMAGE,
IMAGE_ICON, (LPARAM)((HICON)__icos[++icoidx%4]));
return TRUE;
case WM_SETTEXT:
if(w==-2)
{
ProgressDlg::_visible=TRUE;
}
::SendMessage(hEdit,WM_SETTEXT,0,l);
return TRUE;
case WM_CTLCOLORSTATIC:
if(DlgID != DLG_WAIT)
{
::SetBkMode((HDC)w, TRANSPARENT);
::SetTextColor((HDC)w,RGB(200,0,64));// theApp._txtcolor);
return (BOOL)(HBRUSH)theApp._slpEditBrush;
}
break;
case WM_DESTROY:
::KillTimer(hw, 369);
ProgressDlg ::hDialog = 0;
SetEvent (ProgressDlg ::event);
return TRUE;
}
return FALSE;
}
void ProgressDlg::Show(int action, LPCSTR text, size_t nDlgID)
{
if(action == -1 && hDialog)
{
EndDialog(hDialog,0);
WaitForSingleObject(event,5000);
m_reffs = 0;
return;
}
if(action == 1)
{
size_t dw;
if(hDialog == 0)
{
strcpy(tstring,text);
DlgID = nDlgID;
CloseHandle(::CreateThread(0,0,
(LPTHREAD_START_ROUTINE)ThreadProc,
(LPVOID)0,0,&dw));
WaitForSingleObject(event,5000);
if(hDialog)//PRIORITYMAX
{
::BringWindowToTop(hDialog);
::ShowWindow(hDialog,SW_SHOW);
}
}
else
action = 2;
m_reffs++;
}
if(!hDialog)
return;
if(action == 0)
{
if(m_reffs)
if(--m_reffs == 0 && hDialog)
{
EndDialog(hDialog,0);
WaitForSingleObject(event,5000);
}
}
if(action == 2) //only text comes
{
strcpy(tstring,text);
}
if(hDialog)
{
SendMessage(hDialog,WM_SETTEXT,-1,(LPARAM)tstring);
}
theApp.PumpMessage(4);
}
size_t ThreadProc(LPVOID pVoid)
{
if(ProgressDlg::hDialog == NULL)
{
DialogBox(AfxGetResourceHandle(),
MAKEINTRESOURCE(DlgID),
NULL,(DLGPROC)DialogProc);
}
return 1;
} | 21.90604 | 91 | 0.553002 | circinusX1 |
b16b49bc8d49d5edd6e5b61b162e26652c379ab6 | 2,291 | cc | C++ | tests/functional_small/expressions/eigen_diag.cc | Pressio/pressio | e07eb1ed71266490217f2f7a3aad5e1acfecfd4a | [
"BSD-3-Clause"
] | 29 | 2019-11-11T13:17:57.000Z | 2022-03-16T01:31:31.000Z | tests/functional_small/expressions/eigen_diag.cc | Pressio/pressio | e07eb1ed71266490217f2f7a3aad5e1acfecfd4a | [
"BSD-3-Clause"
] | 303 | 2019-09-30T10:15:41.000Z | 2022-03-30T08:24:04.000Z | tests/functional_small/expressions/eigen_diag.cc | Pressio/pressio | e07eb1ed71266490217f2f7a3aad5e1acfecfd4a | [
"BSD-3-Clause"
] | 4 | 2020-07-07T03:32:36.000Z | 2022-03-10T05:21:42.000Z |
#include <gtest/gtest.h>
#include "pressio/expressions.hpp"
namespace{
template <typename T>
void test1(T & A)
{
{
const auto diagvals = pressio::diag(A);
EXPECT_EQ( diagvals.extent(0), 4 );
EXPECT_DOUBLE_EQ( diagvals(0), 1.2 );
EXPECT_DOUBLE_EQ( diagvals(1), 6.2 );
EXPECT_DOUBLE_EQ( diagvals(2), 11.2 );
}
}
template <typename T>
void test2(T & A)
{
{
// change some entries
auto diagvals = pressio::diag(A);
EXPECT_EQ( diagvals.extent(0), 4 );
// before changing it
EXPECT_DOUBLE_EQ( diagvals(0), 1.2 );
EXPECT_DOUBLE_EQ( diagvals(1), 6.2 );
EXPECT_DOUBLE_EQ( diagvals(2), 11.2 );
// modify
diagvals(0) = 44.;
diagvals(1) = 6.;
// after
EXPECT_DOUBLE_EQ( diagvals(0), 44. );
EXPECT_DOUBLE_EQ( diagvals(1), 6. );
}
{
// get the native expression
const auto diagvals = pressio::diag(A);
auto &natEx = diagvals.native();
EXPECT_DOUBLE_EQ( natEx(0), 44. );
EXPECT_DOUBLE_EQ( natEx(1), 6. );
}
}
template <typename T>
void testConst(const T & A){
const auto diagvals = pressio::diag(A);
EXPECT_EQ( diagvals.extent(0), 4 );
EXPECT_DOUBLE_EQ( diagvals(0), 44. );
EXPECT_DOUBLE_EQ( diagvals(1), 6. );
EXPECT_DOUBLE_EQ( diagvals(2), 11.2 );
auto & natEx = diagvals.native();
EXPECT_DOUBLE_EQ( natEx(0), 44. );
EXPECT_DOUBLE_EQ( natEx(1), 6. );
}
}
TEST(expressions_eigen, diag)
{
// col-major matrix (which is default in Eigen)
using eigmat_t = Eigen::MatrixXd;
eigmat_t A(4,4);
A(0,0) = 1.2; A(0,1) = 2.; A(0,2) = 3.; A(0,3) = 4.;
A(1,0) = 5.; A(1,1) = 6.2; A(1,2) = 7.; A(1,3) = 8.;
A(2,0) = 9.; A(2,1) = 10.; A(2,2) = 11.2; A(2,3) = 12.;
A(3,0) = 13.; A(3,1) = 14.; A(3,2) = 15.; A(3,3) = 16.;
test1(A);
test2(A);
testConst(A);
}
TEST(expressions_eigen, diagRowMajor)
{
using eigmat_t = Eigen::Matrix<double, -1, -1, Eigen::RowMajor>;
eigmat_t A(4,4);
A(0,0) = 1.2; A(0,1) = 2.; A(0,2) = 3.; A(0,3) = 4.;
A(1,0) = 5.; A(1,1) = 6.2; A(1,2) = 7.; A(1,3) = 8.;
A(2,0) = 9.; A(2,1) = 10.; A(2,2) = 11.2; A(2,3) = 12.;
A(3,0) = 13.; A(3,1) = 14.; A(3,2) = 15.; A(3,3) = 16.;
test1(A);
test2(A);
testConst(A);
}
| 26.034091 | 66 | 0.539939 | Pressio |
b16dbc2861c7692cb9852fe2459715a6185b3df7 | 8,738 | cpp | C++ | src/chronometer.cpp | cbassem/resilient-icnc | 9f94b185358f2af133244fc8c877190bd15ed413 | [
"BSD-3-Clause"
] | 1 | 2018-05-08T18:26:39.000Z | 2018-05-08T18:26:39.000Z | src/chronometer.cpp | cbassem/resilient-icnc | 9f94b185358f2af133244fc8c877190bd15ed413 | [
"BSD-3-Clause"
] | null | null | null | src/chronometer.cpp | cbassem/resilient-icnc | 9f94b185358f2af133244fc8c877190bd15ed413 | [
"BSD-3-Clause"
] | null | null | null | /* *******************************************************************************
* Copyright (c) 2007-2014, Intel Corporation
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Intel Corporation nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
********************************************************************************/
/*
see chronometer.h
*/
#define _CRT_SECURE_NO_DEPRECATE
#include <fstream>
#include <cnc/internal/chronometer.h>
#include <cnc/internal/tls.h>
#include <cnc/internal/tbbcompat.h>
#include <tbb/concurrent_queue.h>
namespace CnC {
namespace Internal {
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
class cr_init
{
public:
cr_init()
: m_chrons(),
m_tls()
{
}
~cr_init()
{
chronometer * _tmp;
while( m_chrons.try_pop( _tmp ) ) {
delete _tmp;
}
}
void reg( chronometer * c )
{
m_chrons.push( c );
}
void dump_log( std::ostream & os )
{
for( tbb::concurrent_queue< chronometer * >::iterator i = m_chrons.unsafe_begin(); i != m_chrons.unsafe_end(); ++ i ) {
(*i)->dump_log( os );
}
}
chronometer * get_chronometer() const
{
return m_tls.get();
}
void set_chronometer( chronometer * c ) const
{
m_tls.set( c );
}
private:
tbb::concurrent_queue< chronometer * > m_chrons;
TLS_static< chronometer * > m_tls;
};
static cr_init s_cinit;
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
unsigned long GetThreadId();
unsigned long GetThreadId()
{
// RRN: Well, this seems to be against the rules. We're
// assuming pthread_t is something that can reasonably be
// cast to an unsigned long.
#if defined( _WIN32 ) || defined( _WIN64 )
return static_cast< unsigned long >( GetCurrentThreadId() );
#else
// RRN: GCC will not allow a static_cast here. It's not safe enough to eschew dynamic checking.
//return static_cast< unsigned long >( pthread_self() );
return (unsigned long)( pthread_self() );
// Greg suggested this:
// return reinterpret_cast< unsigned long >( pthread_self() );
#endif // _WIN32||_WIN64
}
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool chronometer::s_useTBB = false;
void chronometer::init( bool RDTSC_only )
{
s_useTBB = !RDTSC_only;
}
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
chronometer::chronometer()
: m_log( 2048 ), m_threadId( GetThreadId() ), m_curr( 0 )
{
s_cinit.reg( this );
}
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void chronometer::add_record( const std::string & name,
const int id,
const uint64_t sc,
const uint64_t cc,
const uint64_t gcc,
const uint64_t pcc,
const double sec,
const double gsec,
const double psec,
const StepReturnValue_t rt )
{
chronometer * _c = s_cinit.get_chronometer();
if( _c == NULL ) {
_c = new chronometer();
s_cinit.set_chronometer( _c );
}
if( static_cast< unsigned int >( _c->m_curr ) >= _c->m_log.size() ) _c->m_log.resize( 2 * _c->m_curr );
Record_t & _r = _c->m_log[_c->m_curr++];
_r.m_name = &name;
_r.m_startCycle = sc;
_r.m_cycleCount = cc;
_r.m_getCycles = gcc;
_r.m_putCycles = pcc;
_r.m_seconds = sec;
_r.m_getSeconds = gsec;
_r.m_putSeconds = psec;
_r.m_stepId = id;
_r.m_type = rt;
}
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void chronometer::format_record( std::ostream & os, Record_t & r ) const
{
static char const * ExecutionStatusNames[] = { "completed", "requeued", "failed", "error" };
os << "cycle\t" << r.m_startCycle
<< "\tthread\t" << m_threadId
<< "\tstep\t" << (*r.m_name)
<< "\tid\t" << r.m_stepId
<< "\tstatus\t" << ExecutionStatusNames[static_cast< unsigned int >( r.m_type )]
//<< "\t" << r.si->timing_name()
//<< "\t" << r.si->tag()
<< "\tcycles\t" << r.m_cycleCount
<< "\tget-cycles\t" << r.m_getCycles
<< "\tput-cycles\t" << r.m_putCycles;
if( s_useTBB ) {
os << "\ttime[ms]\t" << ( r.m_seconds * 1000.0 )
<< "\tget-time[ms]\t" << ( r.m_getSeconds * 1000.0 )
<< "\tput-time[ms]\t" << ( r.m_putSeconds * 1000.0 );
#ifndef __MIC__
// assembler complaints on MIC, no idea why
os << "\timplied-GHZ\t" << ( r.m_cycleCount / r.m_seconds / 1.0e9 );
#endif
}
os << std::endl;
}
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void chronometer::dump_log( std::ostream & os )
{
for( int i = 0; i < m_curr; ++i ) {
format_record( os, m_log[i] );
}
m_log.clear();
}
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void chronometer::save_log( const std::string& filename )
{
if( filename == "-" ) {
s_cinit.dump_log( std::cout );
} else {
std::ofstream tfile( filename.c_str() );
if (!tfile)
{
std::cerr << " Timer cannot open " << filename << std::endl;
exit(-1);
}
s_cinit.dump_log( tfile );
tfile.close();
}
}
} // namespace Internal
} // namespace CnC
| 39.538462 | 135 | 0.42916 | cbassem |
b16f8ae238fb5a0a3d9fe4685f185719f6bc296d | 2,254 | hpp | C++ | contracts/eoslib/datastream.hpp | cmpt376temper/eos | 74661de324166e0d99ab43c155b640ac0d665a32 | [
"MIT"
] | null | null | null | contracts/eoslib/datastream.hpp | cmpt376temper/eos | 74661de324166e0d99ab43c155b640ac0d665a32 | [
"MIT"
] | null | null | null | contracts/eoslib/datastream.hpp | cmpt376temper/eos | 74661de324166e0d99ab43c155b640ac0d665a32 | [
"MIT"
] | null | null | null | #pragma once
#include <eoslib/system.h>
#include <eoslib/memory.h>
namespace eos {
template<typename T>
class datastream {
public:
datastream( T start, size_t s )
:_start(start),_pos(start),_end(start+s){};
inline void skip( size_t s ){ _pos += s; }
inline bool read( char* d, size_t s ) {
assert( size_t(_end - _pos) >= (size_t)s, "read" );
memcpy( d, _pos, s );
_pos += s;
return true;
}
inline bool write( const char* d, size_t s ) {
assert( _end - _pos >= (int32_t)s, "write" );
memcpy( _pos, d, s );
_pos += s;
return true;
}
inline bool put(char c) {
assert( _pos < _end, "put" );
*_pos = c;
++_pos;
return true;
}
inline bool get( unsigned char& c ) { return get( *(char*)&c ); }
inline bool get( char& c )
{
assert( _pos < _end, "get" );
c = *_pos;
++_pos;
return true;
}
T pos()const { return _pos; }
inline bool valid()const { return _pos <= _end && _pos >= _start; }
inline bool seekp(size_t p) { _pos = _start + p; return _pos <= _end; }
inline size_t tellp()const { return _pos - _start; }
inline size_t remaining()const { return _end - _pos; }
private:
T _start;
T _pos;
T _end;
};
template<>
class datastream<size_t> {
public:
datastream( size_t init_size = 0):_size(init_size){};
inline bool skip( size_t s ) { _size += s; return true; }
inline bool write( const char* ,size_t s ) { _size += s; return true; }
inline bool put(char ) { ++_size; return true; }
inline bool valid()const { return true; }
inline bool seekp(size_t p) { _size = p; return true; }
inline size_t tellp()const { return _size; }
inline size_t remaining()const { return 0; }
private:
size_t _size;
};
} | 31.305556 | 86 | 0.466726 | cmpt376temper |
b1702c0ea9264ff7aa6d3d4f5add84a770c450fa | 378 | cpp | C++ | GradientDescent/GradientDescent/Add.cpp | skostrov/GradientDescent | aed56fa9d1452252f76e8841227283372f2e761d | [
"MIT"
] | null | null | null | GradientDescent/GradientDescent/Add.cpp | skostrov/GradientDescent | aed56fa9d1452252f76e8841227283372f2e761d | [
"MIT"
] | null | null | null | GradientDescent/GradientDescent/Add.cpp | skostrov/GradientDescent | aed56fa9d1452252f76e8841227283372f2e761d | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "Add.h"
Add::Add(AbstractOperation* leftOperand_, AbstractOperation* rightOperand_) :
BinaryOperation("+", leftOperand_, rightOperand_)
{
}
Add::~Add()
{
}
OperationPriority Add::GetPriority() const
{
return OperationPriority::LOW;
}
double Add::Eval(const Point& point) const
{
return leftOperand->Eval(point) + rightOperand->Eval(point);
}
| 16.434783 | 77 | 0.73545 | skostrov |
b170ee095af006f3cd4badce1f32d6f6bb94c275 | 1,572 | cpp | C++ | software_package/testing/old_dev/lib/old/communication/src/Radio/RadioImpl.cpp | scottzach1/Project-Beans | 0c7a257409464d5e44ea7367e439ae0e12fd41f1 | [
"MIT"
] | 5 | 2020-10-21T23:35:18.000Z | 2021-02-02T19:44:46.000Z | software_package/testing/old_dev/lib/old/communication/src/Radio/RadioImpl.cpp | scottzach1/Project-Beans | 0c7a257409464d5e44ea7367e439ae0e12fd41f1 | [
"MIT"
] | null | null | null | software_package/testing/old_dev/lib/old/communication/src/Radio/RadioImpl.cpp | scottzach1/Project-Beans | 0c7a257409464d5e44ea7367e439ae0e12fd41f1 | [
"MIT"
] | 1 | 2020-10-26T05:13:21.000Z | 2020-10-26T05:13:21.000Z | /**
Concrete Implementation which will inherit RadioInterface.
This will communicate with other packages to get info where appropriate.
*/
#include "RadioImpl.h"
#include <iostream>
RadioImpl::RadioImpl() = default;
RadioImpl::~RadioImpl() = default;
int RadioImpl::getPostFlightData() {
std::cout << "This is a summary of your post flight data..." << std::endl;
RadioImpl::getRocketState();
RadioImpl::getCurrentPos();
RadioImpl::pollSensors();
RadioImpl::pollServos();
std::cout << "------------------------" << std::endl;
return 0;
}
int RadioImpl::runDiagnostics() {
std::cout << "Running Diagnostics..." << std::endl;
RadioImpl::getRocketState();
RadioImpl::getCurrentPos();
RadioImpl::pollSensors();
RadioImpl::pollServos();
std::cout << "------------------------" << std::endl;
return 0;
}
int RadioImpl::getInflightData() {
std::cout << "Getting data at current time..." << std::endl;
RadioImpl::getRocketState();
RadioImpl::getCurrentPos();
RadioImpl::pollSensors();
RadioImpl::pollServos();
std::cout << "------------------------" << std::endl;
return 0;
}
int RadioImpl::pollSensors() {
std::cout << "Calling Sensors." << std::endl;
return 0;
}
int RadioImpl::pollServos() {
std::cout << "Calling Servos." << std::endl;
return 0;
}
int RadioImpl::getCurrentPos() {
std::cout << "Getting Current Pos." << std::endl;
return 0;
}
int RadioImpl::getRocketState() {
std::cout << "Getting Current Rocket State." << std::endl;
return 0;
}
| 25.770492 | 78 | 0.610051 | scottzach1 |
b1747a3875794f8faeb601bb8fd61b87e43928b4 | 8,953 | cpp | C++ | src/ExtFilterAddNormalAttribute/ExtFilterAddNormalAttribute.cpp | voxie-viewer/voxie | d2b5e6760519782e9ef2e51f5322a3baa0cb1198 | [
"MIT"
] | 4 | 2016-06-03T18:41:43.000Z | 2020-04-17T20:28:58.000Z | src/ExtFilterAddNormalAttribute/ExtFilterAddNormalAttribute.cpp | voxie-viewer/voxie | d2b5e6760519782e9ef2e51f5322a3baa0cb1198 | [
"MIT"
] | null | null | null | src/ExtFilterAddNormalAttribute/ExtFilterAddNormalAttribute.cpp | voxie-viewer/voxie | d2b5e6760519782e9ef2e51f5322a3baa0cb1198 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2014-2022 The Voxie Authors
*
* 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 <VoxieClient/Array.hpp>
#include <VoxieClient/ClaimedOperation.hpp>
#include <VoxieClient/DBusClient.hpp>
#include <VoxieClient/DBusProxies.hpp>
#include <VoxieClient/DBusTypeList.hpp>
#include <VoxieClient/DBusUtil.hpp>
#include <VoxieClient/Exception.hpp>
#include <VoxieClient/Exceptions.hpp>
#include <VoxieClient/MappedBuffer.hpp>
#include <VoxieClient/QtUtil.hpp>
#include <VoxieClient/RefCountHolder.hpp>
#include <ExtFilterAddNormalAttribute/AddNormalAttribute.hpp>
#include <QtCore/QCommandLineParser>
#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QString>
#include <QDebug>
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusConnectionInterface>
#include <QtDBus/QDBusError>
#include <QtDBus/QDBusPendingReply>
#include <QtGui/QVector3D>
inline QVector3D toQtVector(const vx::TupleVector<double, 3>& vec) {
return QVector3D(std::get<0>(vec), std::get<1>(vec), std::get<2>(vec));
}
int main(int argc, char* argv[]) {
try {
if (argc < 1)
throw vx::Exception(
"de.uni_stuttgart.Voxie.ExtFilterAddNormalAttribute.Error",
"argc is smaller than 1");
QCommandLineParser parser;
parser.setApplicationDescription(
"Filter calculating surface (vertex) normals");
parser.addHelpOption();
parser.addVersionOption();
parser.addOptions(vx::DBusClient::options());
parser.addOptions(vx::ClaimedOperationBase::options());
QStringList args;
for (char** arg = argv; *arg; arg++) args.push_back(*arg);
int argc0 = 1;
char* args0[2] = {argv[0], NULL};
QCoreApplication app(argc0, args0);
parser.process(args);
vx::initDBusTypes();
vx::DBusClient dbusClient(parser);
vx::ClaimedOperation<de::uni_stuttgart::Voxie::ExternalOperationRunFilter>
op(dbusClient,
vx::ClaimedOperationBase::getOperationPath(parser, "RunFilter"));
op.forwardExc([&]() {
auto filterPath = op.op().filterObject();
auto pars = op.op().parameters();
auto properties = vx::dbusGetVariantValue<QMap<QString, QDBusVariant>>(
pars[filterPath]["Properties"]);
auto inSurfacePath = vx::dbusGetVariantValue<QDBusObjectPath>(
properties["de.uni_stuttgart.Voxie.Filter.AddNormalAttribute."
"InputSurface"]);
auto inSurfaceDataPath =
vx::dbusGetVariantValue<QDBusObjectPath>(pars[inSurfacePath]["Data"]);
auto inSurfaceData = makeSharedQObject<
de::uni_stuttgart::Voxie::SurfaceDataTriangleIndexed>(
dbusClient.uniqueName(), inSurfaceDataPath.path(),
dbusClient.connection());
vx::Array2<const float> vertices(HANDLEDBUSPENDINGREPLY(
inSurfaceData->GetVerticesReadonly(QMap<QString, QDBusVariant>())));
vx::Array2<const uint> triangles(HANDLEDBUSPENDINGREPLY(
inSurfaceData->GetTrianglesReadonly(QMap<QString, QDBusVariant>())));
auto method = vx::dbusGetVariantValue<QString>(
properties
["de.uni_stuttgart.Voxie.Filter.AddNormalAttribute.Method"]);
// output surface
auto outputPath = vx::dbusGetVariantValue<QDBusObjectPath>(
properties["de.uni_stuttgart.Voxie.Output"]);
QList<std::tuple<
QString, QString, quint64, std::tuple<QString, quint32, QString>,
QString, QMap<QString, QDBusVariant>, QMap<QString, QDBusVariant>>>
attributes{std::make_tuple(
"de.uni_stuttgart.Voxie.SurfaceAttribute.Normal",
"de.uni_stuttgart.Voxie.SurfaceAttributeKind.Vertex",
3, // componentCount_
std::make_tuple("float", 32, "native"), "Normals",
QMap<QString, QDBusVariant>(), QMap<QString, QDBusVariant>())};
QMap<QString, QDBusVariant> options;
options.insert("Attributes", vx::dbusMakeVariant(attributes));
vx::RefObjWrapper<de::uni_stuttgart::Voxie::SurfaceDataTriangleIndexed>
outputSurface(
dbusClient,
HANDLEDBUSPENDINGREPLY(
dbusClient->CreateSurfaceDataTriangleIndexed(
dbusClient.clientPath(), triangles.size<0>(),
vertices.size<0>(), inSurfaceDataPath, true, options)));
auto outputSurfaceData =
makeSharedQObject<de::uni_stuttgart::Voxie::Data>(
dbusClient.uniqueName(), outputSurface.path().path(),
dbusClient.connection());
vx::RefObjWrapper<de::uni_stuttgart::Voxie::ExternalDataUpdate> update(
dbusClient,
HANDLEDBUSPENDINGREPLY(outputSurfaceData->CreateUpdate(
dbusClient.clientPath(), QMap<QString, QDBusVariant>())));
{
vx::Array2<float> outputNormals(
HANDLEDBUSPENDINGREPLY(outputSurface->GetAttributeWritable(
update.path(), "de.uni_stuttgart.Voxie.SurfaceAttribute.Normal",
QMap<QString, QDBusVariant>())));
vx::Array2<uint> outputTriangles(
HANDLEDBUSPENDINGREPLY(outputSurface->GetTrianglesWritable(
update.path(), QMap<QString, QDBusVariant>())));
for (uint32_t i = 0; i < outputTriangles.size<0>(); i++) {
for (int vertex = 0; vertex < 3; vertex++) {
outputTriangles(i, vertex) = triangles(i, vertex);
}
}
vx::Array2<float> outputVertices(
HANDLEDBUSPENDINGREPLY(outputSurface->GetVerticesWritable(
update.path(), QMap<QString, QDBusVariant>())));
for (uint32_t i = 0; i < outputVertices.size<0>(); i++) {
for (int coord = 0; coord < 3; coord++) {
outputVertices(i, coord) = vertices(i, coord);
}
}
AddNormalAttribute filter;
if (method ==
"de.uni_stuttgart.Voxie.Filter.AddNormalAttribute.Method."
"Triangles") {
filter.compute(vertices, triangles, outputNormals, op);
}
if (method ==
"de.uni_stuttgart.Voxie.Filter.AddNormalAttribute.Method.Volume") {
auto inVolumePath = vx::dbusGetVariantValue<QDBusObjectPath>(
properties["de.uni_stuttgart.Voxie.Filter.AddNormalAttribute."
"InputVolume"]);
auto inVolumeDataPath = vx::dbusGetVariantValue<QDBusObjectPath>(
pars[inVolumePath]["Data"]);
auto inVolumeData =
makeSharedQObject<de::uni_stuttgart::Voxie::VolumeData>(
dbusClient.uniqueName(), inVolumeDataPath.path(),
dbusClient.connection());
auto inVolumeDataVoxel =
makeSharedQObject<de::uni_stuttgart::Voxie::VolumeDataVoxel>(
dbusClient.uniqueName(), inVolumeDataPath.path(),
dbusClient.connection());
vx::Array3<const float> volume(
HANDLEDBUSPENDINGREPLY(inVolumeDataVoxel->GetDataReadonly(
QMap<QString, QDBusVariant>())));
QVector3D spacing = toQtVector(inVolumeDataVoxel->gridSpacing());
QVector3D origin = toQtVector(inVolumeData->volumeOrigin());
filter.compute(vertices, volume, spacing, origin, outputNormals, op);
}
}
// Define Output
QMap<QString, QDBusVariant> outputResult;
outputResult["Data"] =
vx::dbusMakeVariant<QDBusObjectPath>(outputSurface.path());
// vx::dbusMakeVariant<QDBusObjectPath>(inSurfaceDataPath);
QMap<QDBusObjectPath, QMap<QString, QDBusVariant>> result;
result[outputPath] = outputResult;
HANDLEDBUSPENDINGREPLY(
op.op().Finish(result, QMap<QString, QDBusVariant>()));
});
return 0;
} catch (vx::Exception& error) {
QTextStream(stderr) << error.name() << ": " << error.message() << endl
<< flush;
return 1;
}
}
| 40.328829 | 80 | 0.658662 | voxie-viewer |
b179788d3174178cc76d01d256c470769778a70b | 570 | hpp | C++ | fmaspc/include/sym/Plugin.hpp | BenjaminSchulte/fma | df2aa5b0644c75dd34a92defeff9beaa4a32ffea | [
"MIT"
] | 14 | 2018-01-25T10:31:05.000Z | 2022-02-19T13:08:11.000Z | fmaspc/include/sym/Plugin.hpp | BenjaminSchulte/fma | df2aa5b0644c75dd34a92defeff9beaa4a32ffea | [
"MIT"
] | 1 | 2020-12-24T10:10:28.000Z | 2020-12-24T10:10:28.000Z | fmaspc/include/sym/Plugin.hpp | BenjaminSchulte/fma | df2aa5b0644c75dd34a92defeff9beaa4a32ffea | [
"MIT"
] | null | null | null | #ifndef __FMASPC_SYM_PLUGIN_H__
#define __FMASPC_SYM_PLUGIN_H__
#include <fma/plugin/Plugin.hpp>
#include <fma/output/DynamicBuffer.hpp>
namespace FMASPC {
namespace sym {
class SpcOutputPlugin : public FMA::plugin::OutputFileWriterPlugin {
public:
SpcOutputPlugin(FMA::Project *project);
const char *getName() const {
return "SPC symbol file generator";
}
const char *getDescription() const {
return "Generates a SPC symbol file";
}
bool initialize();
void release();
bool generate(FMA::output::OutputAdapter *adapter);
};
}
}
#endif
| 17.8125 | 70 | 0.726316 | BenjaminSchulte |
b17d9ea147acf9435c14db9a227b6f751b6c148c | 672 | cpp | C++ | practise/3-6.cpp | WIZARD-CXY/pl | 22b7f5d81804f4e333d3cff6433364ba1a0ac7ef | [
"Apache-2.0"
] | 1 | 2016-01-20T08:26:34.000Z | 2016-01-20T08:26:34.000Z | practise/3-6.cpp | WIZARD-CXY/pl | 22b7f5d81804f4e333d3cff6433364ba1a0ac7ef | [
"Apache-2.0"
] | 1 | 2015-10-21T05:38:17.000Z | 2015-11-02T07:42:55.000Z | practise/3-6.cpp | WIZARD-CXY/pl | 22b7f5d81804f4e333d3cff6433364ba1a0ac7ef | [
"Apache-2.0"
] | null | null | null | #include <cstdio>
#include <iostream>
#include <string>
using namespace std;
// compare two circular string
int Isless(string &s, int p, int q)
{
int len = s.size();
for (int i = 0; i < len; i++)
{
if (s[(p + i) % len] != s[(q + i) % len])
{
return s[(p + i) % len] < s[(q + i) % len];
}
}
return false;
}
int main()
{
string s;
cin >> s;
int len = s.size();
int ans = 0;
for (int p = 1; p < len; p++)
{
if (Isless(s, p, ans))
{
ans = p;
}
}
for (int i = 0; i < len; i++)
{
printf("%c", s[(i + ans) % len]);
}
printf("\n");
} | 17.230769 | 55 | 0.407738 | WIZARD-CXY |
b17e6e6c24b272a02bfb24d200f1f7edaaa8c98b | 11,951 | cpp | C++ | ElementTest/properties.cpp | iSplasher/gSplasher | c4870b91940a42a2c2a8e384fbe202543b88b87a | [
"Apache-2.0"
] | null | null | null | ElementTest/properties.cpp | iSplasher/gSplasher | c4870b91940a42a2c2a8e384fbe202543b88b87a | [
"Apache-2.0"
] | 9 | 2017-02-23T18:03:41.000Z | 2017-02-27T17:00:20.000Z | ElementTest/properties.cpp | iSplasher/gSplasher | c4870b91940a42a2c2a8e384fbe202543b88b87a | [
"Apache-2.0"
] | null | null | null | #include "element/core.h"
#include "element/property.h"
#include "catch.hpp"
#include <chrono>
#include <thread>
USING_NAMESPACE
SCENARIO("Regular properties", "[Property]") {
Application* app = Application::instance();
if( !app )
app = new Application();
GIVEN("Simple read-write properties can be instantiated") {
Property< std::string > prop1{};
Property< std::string > prop2{ "hello world" };
auto prop3 = Property< std::string >( "hello world 2" );
WHEN("Property value is assigned") {
std::string call1 = prop1;
std::string call2 = prop2;
std::string call3 = prop3;
THEN("Same object is returned") {
REQUIRE(call1 == "");
REQUIRE(call2 == "hello world");
REQUIRE(call3 == "hello world 2");
}
}
WHEN("Property value is assigned to") {
prop1 = "1";
prop2 = "2";
prop3 = "3";
THEN("The assignment is successful") {
REQUIRE(prop1 == "1");
REQUIRE(prop2 == "2");
REQUIRE(prop3 == "3");
}
}
WHEN("Property value is compared to") {
prop1 = "1";
prop2 = "1";
prop3 = "3";
THEN("The comparison is successful") {
REQUIRE(prop1 == prop2);
REQUIRE(prop2 != prop3);
}
}
WHEN("Property value is const-referenced") {
const std::string& call1 = prop1;
const std::string& call2 = prop2;
const std::string& call3 = prop3;
THEN("Same object is returned") {
REQUIRE(call1 == "");
REQUIRE(call2 == "hello world");
REQUIRE(call3 == "hello world 2");
}
}
WHEN("Property connection is made") {
std::string value1 = "";
prop1.changed( [&value1](std::string s) { value1 = s; } );
THEN("connection is called on property change") {
REQUIRE(value1 == "");
prop1 = "new value";
REQUIRE(value1 == "new value");
}
}
WHEN("Two properties dependency sync") {
prop1.changed< ConnectionType::Temporary >( [&prop1, &prop2](std::string s) {
if( prop2 != prop1 ) {
prop2 = "changed";
};
} );
prop2.changed< ConnectionType::Temporary >( [&prop1, &prop2](std::string s) {
if( prop2 != prop1 ) {
prop1 = "changed";
};
} );
THEN("function is called sync on property change") {
REQUIRE(prop1 == "");
REQUIRE(prop2 == "hello world");
prop1 = "test";
REQUIRE(prop1 == "changed");
REQUIRE(prop2 == "changed");
}
}
WHEN("Two properties dependency async") {
prop1.changed< ConnectionType::Temporary >( [&prop1, &prop2](std::string s) {
if( prop2 != prop1 ) {
prop2 = "changed";
};
} );
prop2.changed< ConnectionType::Temporary >( [&prop1, &prop2](std::string s) {
if( prop2 != prop1 ) {
prop1 = "changed";
};
} );
THEN("function is called async on property change") {
REQUIRE(prop1 == "");
REQUIRE(prop2 == "hello world");
prop1 << "test";
prop1.wait();
REQUIRE(prop1 == "changed");
REQUIRE(prop2 == "changed");
}
}
WHEN("Two properties dependency async with sleep") {
prop1.changed< ConnectionType::Temporary >( [&prop1, &prop2](std::string s) {
if( prop2 != prop1 ) {
std::cout << "testing async properties.. sleeping for 1 second.." << std::endl;
std::this_thread::sleep_for( std::chrono::seconds( 1 ) );
prop2 = "changed";
};
} );
prop2.changed< ConnectionType::Temporary >( [&prop1, &prop2](std::string s) {
if( prop2 != prop1 ) {
std::cout << "testing async properties.. sleeping for 1 second.." << std::endl;
std::this_thread::sleep_for( std::chrono::seconds( 1 ) );
prop1 = "changed";
};
} );
THEN("function is called async on property change") {
REQUIRE(prop1 == "");
REQUIRE(prop2 == "hello world");
prop1 << "test";
REQUIRE(prop2 == "hello world");
prop1.wait();
REQUIRE(prop1 == "changed");
REQUIRE(prop2 == "changed");
}
}
WHEN("Property is connected forever to function") {
std::string value1 = "";
prop1.changed( [&value1](std::string s) { value1 = s; } );
THEN("function is called on every property change") {
REQUIRE(value1 == "");
prop1 = "value1";
REQUIRE(value1 == "value1");
prop1 = "value2";
REQUIRE(value1 == "value2");
}
}
WHEN("Property is connected once to function") {
std::string value1 = "";
prop1.changed< ConnectionType::Temporary >( [&value1](std::string s) {
value1 = s;
} );
THEN("function is called on only one property change") {
REQUIRE(value1 == "");
prop1 = "value1";
REQUIRE(value1 == "value1");
prop1 = "value2";
REQUIRE(value1 == "value1");
}
}
WHEN("Property constructs a scoped connection") {
std::string value1 = "";
THEN("function is only called when connection is in scope") { {
auto conn = prop1.changed< ConnectionType::Scoped >( [&value1](std::string s) {
value1 = s;
} );
REQUIRE(value1 == "");
prop1 = "value1";
REQUIRE(value1 == "value1");
prop1 = "value2";
REQUIRE(value1 == "value2");
}
REQUIRE(value1 == "value2");
prop1 = "value3";
REQUIRE(value1 == "value2");
}
}
}
GIVEN("Simple read-only properties can be instantiated") {
WHEN("When declared in class") {
struct Test {
Property< std::string, Test > prop1{};
Property< std::string, Test > prop2{ "hello world" };
void test( std::string s ) { prop1 = s; }
};
THEN( "Can read value" ) {
auto t = Test();
REQUIRE(t.prop1 == "");
std::string v = t.prop2;
REQUIRE(v == "hello world");
}
THEN("Class can change value") {
auto t = Test();
t.test( "prop1" );
REQUIRE(t.prop1 == "prop1");
std::string v = t.prop2;
REQUIRE(v == "hello world");
}
}
}
GIVEN("Property views") {
struct T {
Property< std::string, T > third{ "!" };
};
Property< std::string > first{ "hello " };
Property< std::string > second{ "world" };
T t;
WHEN("A simple std::string based property view is instantiated") {
PropertyView< std::string > view1( [](std::string a, std::string b, std::string c) -> std::string { return a + b + c; },
first, second, t.third );
THEN("PropertyView has the same value as returned by function") {
REQUIRE(view1 == "hello world!");
first = "new ";
REQUIRE(view1 == "new world!");
second = "element++";
REQUIRE(view1 == "new element++!");
first = "hello ";
REQUIRE(view1 == "hello element++!");
}
THEN("PropertyView has the same value as returned by function async") {
// async
first << "new ";
first.wait();
REQUIRE(view1 == "new world!");
second << "element++";
second.wait();
REQUIRE(view1 == "new element++!");
first << "hello ";
first.wait();
REQUIRE(view1 == "hello element++!");
}
THEN("PropertyView connection can also refer to other properties") {
view1.changed( [&first](std::string s) {
if( first != "changed " )
first = "changed ";
} );
REQUIRE(view1 == "hello world!");
first << "async ";
first.wait();
REQUIRE(view1 == "changed world!");
first = "new ";
REQUIRE(view1 == "changed world!"); // reactive applies the value to itself before going through all connections
}
}
WHEN("A PropertyView that differs in type is instantiated") {
first = "0";
second = "0";
PropertyView< int > view2(
[](std::string a, std::string b) -> int { return std::stoi( a ) + std::stoi( b ); },
first, second );
THEN("PropertyView has the same value as returned by function") {
REQUIRE(view2 == 0);
first = "1";
REQUIRE(view2 == 1);
second = "1";
REQUIRE(view2 == 2);
first = "2";
REQUIRE(view2 == 3);
}
}
}
}
SCENARIO("Event streams", "[Property]") {
Application* app = Application::instance();
if( !app )
app = new Application();
GIVEN("Simple event streams can be instantiated") {
std::string eventv1{ "" }, eventv2{ "" };
PropertyEvent< std::string > event1;
event1.changed( [&](std::string v) { eventv1 = v; } );
PropertyEvent< std::string > event2;
event2.changed( [&](std::string v) { eventv2 = v; } );
WHEN("Event is pushed") {
event1 = "hello";
event2 = "world";
THEN("Same object is returned") {
REQUIRE(eventv1 == "hello");
REQUIRE(eventv2 == "world");
}
}
WHEN("Event is pushed async") {
event1 << "hello";
REQUIRE(eventv1 == "");
event2 << "world";
REQUIRE(eventv2 == "");
THEN("Same object is returned") {
event1.wait();
event2.wait();
REQUIRE(eventv1 == "hello");
REQUIRE(eventv2 == "world");
}
}
WHEN("Event is pushed function call") {
event1( "hello" );
event2( "world" );
THEN("Same object is returned") {
REQUIRE(eventv1 == "hello");
REQUIRE(eventv2 == "world");
}
}
WHEN("Event is pushed function call async") {
event1( "hello", true );
REQUIRE(eventv1 == "");
event2( "world", true );
REQUIRE(eventv2 == "");
THEN("Same object is returned") {
event1.wait();
event2.wait();
REQUIRE(eventv1 == "hello");
REQUIRE(eventv2 == "world");
}
}
}
GIVEN("Simple read-only event streams can be instantiated") {
std::string eventv1{ "" };
WHEN("Declared in class") {
struct T {
PropertyEvent< std::string, T > first;
void push() { first( "hello" ); }
};
T t;
t.first.changed( [&](std::string v) { eventv1 = v; } );
THEN("Class can push values") {
REQUIRE(eventv1 == "");
t.push();
REQUIRE(eventv1 == "hello");
}
}
}
GIVEN("Event views") {
std::string eventv1{ "" };
PropertyEvent< std::string > event1;
PropertyEvent< std::string > event2;
PropertyEventView< std::string > eventview1{ event1, event2 };
eventview1.changed( [&](std::string v) {
eventv1 = v;
} );
WHEN("Events are pushed") {
event1( "hello" );
event2( "world" );
THEN("Then the last event value is propogated last") {
REQUIRE(eventv1 == "world");
}
}
WHEN("Events are pushed async") {
event1( "hello", true );
event2( "world", true );
THEN("Then the last async event value is propogated last") {
event2.wait();
REQUIRE(eventv1 == "world");
}
}
WHEN("Some events are pushed async") {
event1( "hello", true );
event2( "world" );
THEN("Then the async event value is propogated last") {
event1.wait();
REQUIRE(eventv1 == "hello");
}
}
}
}
| 24.439673 | 127 | 0.499707 | iSplasher |
b17f637c17fda6b145b1d6db74da5d737a696424 | 1,550 | cpp | C++ | tblock/source/GameStates/GS_Menu.cpp | maximbilan/T-Block | b2eb3701a2567590090947a3c3dfb4afe282695a | [
"MIT"
] | 1 | 2016-03-09T13:03:48.000Z | 2016-03-09T13:03:48.000Z | tblock/source/GameStates/GS_Menu.cpp | maximbilan/T-Block | b2eb3701a2567590090947a3c3dfb4afe282695a | [
"MIT"
] | null | null | null | tblock/source/GameStates/GS_Menu.cpp | maximbilan/T-Block | b2eb3701a2567590090947a3c3dfb4afe282695a | [
"MIT"
] | null | null | null | #include "PlatformPrecomp.h"
#include "GS_Menu.h"
#include "Defines/GUI_IDs.h"
#include "GUI/GUI_MainMenu.h"
#include "Utils/Timer.h"
GS_Menu::GS_Menu() :
m_timer( new Timer() ),
m_startTime( 0.0f ),
m_alpha( 1.0f )
{
m_timer->start();
m_startTime = m_timer->getElapsedTimeInMilliSec();
}
GS_Menu::~GS_Menu()
{
delete m_timer;
}
void GS_Menu::ResumeState()
{
}
void GS_Menu::UpdateState( int frameTime )
{
switch( s_subState )
{
case k_substate_splash_screen:
{
Entity* pEnt = GetEntityRoot()->GetEntityByName( GUI_TEXT_SPLASH_SCREEN_TEXT_ );
if( pEnt )
{
if( m_timer->getElapsedTimeInMilliSec() - m_startTime > 2000.0f )
{
m_startTime = m_timer->getElapsedTimeInMilliSec();
m_alpha = 1.0f;
}
else
{
if( m_alpha > 0.0f )
{
m_alpha -= 0.01f;
}
}
pEnt->GetVar( "alpha" )->Set( Variant( m_alpha ) );
}
pEnt = GetEntityRoot()->GetEntityByName( GUI_IMAGE_SPLASH_SCREEN_TITLE_T_BLOCK );
if( pEnt )
{
pEnt->GetVar( "rotation" )->Set( Variant( SinGamePulseByMS(10000)*1 ) );
}
}
break;
case k_substate_main:
{
Entity* pEnt = GetEntityRoot()->GetEntityByName( GUI_IMAGE_MM_TITLE_T_BLOCK );
if( pEnt )
{
pEnt->GetVar( "rotation" )->Set( Variant( SinGamePulseByMS(10000)*1 ) );
}
}
break;
}
}
void GS_Menu::RenderState()
{
switch( s_subState )
{
case k_substate_splash_screen:
{
}
break;
case k_substate_main:
{
}
break;
}
} | 18.674699 | 85 | 0.604516 | maximbilan |
b189f0c06d794d536cdd618911abf6fc9e9a824e | 2,679 | hpp | C++ | tests/ZsyncRemoteControlFileParser.hpp | azubieta/AppImageUpdaterBridge | b555ad508186c3ca0c285a3de14cde4b76abded6 | [
"BSD-3-Clause"
] | null | null | null | tests/ZsyncRemoteControlFileParser.hpp | azubieta/AppImageUpdaterBridge | b555ad508186c3ca0c285a3de14cde4b76abded6 | [
"BSD-3-Clause"
] | null | null | null | tests/ZsyncRemoteControlFileParser.hpp | azubieta/AppImageUpdaterBridge | b555ad508186c3ca0c285a3de14cde4b76abded6 | [
"BSD-3-Clause"
] | null | null | null | #ifndef ZSYNC_REMOTE_CONTROL_FILE_PARSER_TESTS_HPP_INCLUDED
#define ZSYNC_REMOTE_CONTROL_FILE_PARSER_TESTS_HPP_INCLUDED
#include <QTest>
#include <QSignalSpy>
#include <QNetworkAccessManager>
#include "../include/zsyncremotecontrolfileparser_p.hpp"
/*
* Get the official appimage tool to test it with
* our library.
*/
#define APPIMAGE_TOOL_CONTROL_FILE_URL QUrl("https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-x86_64.AppImage.zsync")
class ZsyncRemoteControlFileParser : public QObject
{
Q_OBJECT
private slots:
void basicZsyncControlFileParsing(void)
{
using AppImageUpdaterBridge::ZsyncRemoteControlFileParserPrivate;
ZsyncRemoteControlFileParserPrivate CFParser(&_pManager);
CFParser.setControlFileUrl(APPIMAGE_TOOL_CONTROL_FILE_URL);
QSignalSpy spyReceiveControlFile(&CFParser, SIGNAL(receiveControlFile(void)));
CFParser.getControlFile();
/*
* Since this is done over the network , lets wait
* atmost 10 seconds.
* If we don't get any signals inside that time frame then
* ZsyncRemoteControlFileParserPrivate did not work properly.
*/
QVERIFY(spyReceiveControlFile.wait(10000) == true);
return;
}
void verifyZsyncControlFileParserData(void)
{
using AppImageUpdaterBridge::ZsyncRemoteControlFileParserPrivate;
ZsyncRemoteControlFileParserPrivate CFParser(&_pManager);
CFParser.setControlFileUrl(APPIMAGE_TOOL_CONTROL_FILE_URL);
QSignalSpy spyReceiveControlFile(&CFParser, SIGNAL(receiveControlFile(void)));
QSignalSpy spyInfo(&CFParser , SIGNAL(zsyncInformation(qint32,qint32,qint32,
qint32,qint32,qint32,
QString,QString,QString,
QUrl,QBuffer*,bool)));
CFParser.getControlFile();
/* Check if we received the control file */
QVERIFY(spyReceiveControlFile.wait(10000) == true);
return;
}
void checkErrorSignal(void)
{
using AppImageUpdaterBridge::ZsyncRemoteControlFileParserPrivate;
ZsyncRemoteControlFileParserPrivate CFParser(&_pManager);
CFParser.setControlFileUrl(QUrl("https://example.com/somecontrolfile.zsync"));
QSignalSpy spyError(&CFParser, SIGNAL(error(short)));
CFParser.getControlFile();
/* Check if we received a error*/
QVERIFY(spyError.wait() == true);
return;
}
void cleanupTestCase(void)
{
emit finished();
return;
}
Q_SIGNALS:
void finished(void);
private:
QNetworkAccessManager _pManager;
};
#endif
| 34.346154 | 150 | 0.698022 | azubieta |
b18c638317a91d7d4e28ebbb93bc81273c479c0b | 581 | cpp | C++ | Data_Structures/Binary_Tree/construction/const_from_preorder_postorder.cpp | abhishekjha786/ds_algo | 38355ca12e8ac20c4baa8baccf8ad189effaa6ae | [
"MIT"
] | 11 | 2020-03-20T17:24:28.000Z | 2022-01-08T02:43:24.000Z | Data_Structures/Binary_Tree/construction/const_from_preorder_postorder.cpp | abhishekjha786/ds_algo | 38355ca12e8ac20c4baa8baccf8ad189effaa6ae | [
"MIT"
] | 1 | 2021-07-25T11:24:46.000Z | 2021-07-25T12:09:25.000Z | Data_Structures/Binary_Tree/construction/const_from_preorder_postorder.cpp | abhishekjha786/ds_algo | 38355ca12e8ac20c4baa8baccf8ad189effaa6ae | [
"MIT"
] | 4 | 2020-03-20T17:24:36.000Z | 2021-12-07T19:22:59.000Z | // https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/
// Given two integer arrays, preorder and postorder where preorder
// is the preorder traversal of a binary tree of distinct values and postorder
// is the postorder traversal of the same tree, reconstruct and return the binary tree.
// If there exist multiple answers, you can return any of them.
// Input: preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]
// Output: [1,2,3,4,5,6,7]
// Solution: -
// In this case it is not possible to construct a distinct answer always.
| 38.733333 | 93 | 0.729776 | abhishekjha786 |
b18c754e3377a7b6ad1eb5fcc1bd04c9dea3f9f6 | 15,706 | cpp | C++ | Source/TitanUMG/Private/STitanVirtualJoystick.cpp | learnMoreCode/UE4_TitanUMG | e01233801502ca0c026b19bf2d8804fc1b991857 | [
"MIT"
] | 18 | 2020-09-09T13:50:48.000Z | 2022-03-08T11:39:29.000Z | Source/TitanUMG/Private/STitanVirtualJoystick.cpp | irajsb/UE4_TitanUMG | e01233801502ca0c026b19bf2d8804fc1b991857 | [
"MIT"
] | null | null | null | Source/TitanUMG/Private/STitanVirtualJoystick.cpp | irajsb/UE4_TitanUMG | e01233801502ca0c026b19bf2d8804fc1b991857 | [
"MIT"
] | 3 | 2021-07-29T16:28:18.000Z | 2022-02-21T01:58:27.000Z | // Copyright Epic Games, Inc. All Rights Reserved.
#include "STitanVirtualJoystick.h"
#include "Rendering/DrawElements.h"
#include "Misc/ConfigCacheIni.h"
#include "TitanJoystick.h"
#include "Framework/Application/SlateApplication.h"
const float OPACITY_LERP_RATE = 3.f;
static FORCEINLINE float GetScaleFactor(const FGeometry& Geometry)
{
const float DesiredWidth = 1024.0f;
float UndoDPIScaling = 1.0f / Geometry.Scale;
return (Geometry.GetDrawSize().GetMax() / DesiredWidth) * UndoDPIScaling;
}
FORCEINLINE FLinearColor STitanVirtualJoystick::GetBaseColor()
{
return (State == State_Active || State == State_CountingDownToInactive) ? Owner->ActiveColor : Owner->DeActiveColor;
}
void STitanVirtualJoystick::Reset()
{
// snap the visual center back to normal (for controls that have a center on touch)
VisualCenter = CorrectedCenter;
}
void STitanVirtualJoystick::Construct( const FArguments& InArgs )
{
State = State_Inactive;
bVisible = true;
// listen for displaymetrics changes to reposition controls
FSlateApplication::Get().GetPlatformApplication()->OnDisplayMetricsChanged().AddSP(this, &STitanVirtualJoystick::HandleDisplayMetricsChanged);
}
void STitanVirtualJoystick::HandleDisplayMetricsChanged(const FDisplayMetrics& NewDisplayMetric)
{
// Mark all controls to be repositioned on next tick
bHasBeenPositioned = false;
}
bool STitanVirtualJoystick::ShouldDisplayTouchInterface()
{
bool bAlwaysShowTouchInterface = false;
GConfig->GetBool(TEXT("/Script/Engine.InputSettings"), TEXT("bAlwaysShowTouchInterface"), bAlwaysShowTouchInterface, GInputIni);
// do we want to show virtual joysticks?
return FPlatformMisc::GetUseVirtualJoysticks() || bAlwaysShowTouchInterface || ( FSlateApplication::Get().IsFakingTouchEvents() && FPlatformMisc::ShouldDisplayTouchInterfaceOnFakingTouchEvents());
}
static int32 ResolveRelativePosition(float Position, float RelativeTo, float ScaleFactor)
{
// absolute from edge
if (Position < -1.0f)
{
return RelativeTo + Position * ScaleFactor;
}
// relative from edge
else if (Position < 0.0f)
{
return RelativeTo + Position * RelativeTo;
}
// relative from 0
else if (Position <= 1.0f)
{
return Position * RelativeTo;
}
// absolute from 0
else
{
return Position * ScaleFactor;
}
}
static bool PositionIsInside(const FVector2D& Center, const FVector2D& Position, const FVector2D& BoxSize)
{
return
Position.X >= Center.X - BoxSize.X * 0.5f &&
Position.X <= Center.X + BoxSize.X * 0.5f &&
Position.Y >= Center.Y - BoxSize.Y * 0.5f &&
Position.Y <= Center.Y + BoxSize.Y * 0.5f;
}
int32 STitanVirtualJoystick::OnPaint( const FPaintArgs& Args, const FGeometry& AllottedGeometry, const FSlateRect& MyCullingRect, FSlateWindowElementList& OutDrawElements, int32 LayerId, const FWidgetStyle& InWidgetStyle, bool bParentEnabled ) const
{
int32 RetLayerId = LayerId;
if (bVisible)
{
if (Owner-> Image2.IsValid())
{
FSlateDrawElement::MakeBox(
OutDrawElements,
RetLayerId++,
AllottedGeometry.ToPaintGeometry(
VisualCenter - FVector2D(CorrectedVisualSize.X * 0.5f, CorrectedVisualSize.Y * 0.5f),
CorrectedVisualSize),
Owner->Image2->GetSlateBrush(),
static_cast<ESlateDrawEffect>(Owner->BackGroundDrawEffect),
CurrentColor
);
}
if (Owner->Image1.IsValid())
{
FSlateDrawElement::MakeBox(
OutDrawElements,
RetLayerId++,
AllottedGeometry.ToPaintGeometry(
VisualCenter + Index1Location - FVector2D(CorrectedThumbSize.X * 0.5f, CorrectedThumbSize.Y * 0.5f),
CorrectedThumbSize),
Owner->Image1->GetSlateBrush(),
static_cast<ESlateDrawEffect>(Owner->ThumbDrawEffect),
CurrentColor
);
}
if(Owner->TextToShow!=FString("NULL"))
{
FSlateDrawElement::MakeText(OutDrawElements,
RetLayerId++,AllottedGeometry.ToPaintGeometry(
VisualCenter -Owner->FontInfo.Size* FVector2D(CorrectedVisualSize.X , CorrectedVisualSize.Y )*Owner->FontCenterCorrection,
CorrectedVisualSize),Owner->TextToShow,Owner->FontInfo,static_cast<ESlateDrawEffect>(Owner->TextDrawEffect),Owner->TextColor);
}
}
return RetLayerId;
}
FVector2D STitanVirtualJoystick::ComputeDesiredSize( float ) const
{
return FVector2D(300, 300);
}
bool STitanVirtualJoystick::SupportsKeyboardFocus() const
{
return false;
}
FReply STitanVirtualJoystick::OnTouchStarted(const FGeometry& MyGeometry, const FPointerEvent& Event)
{
NumofTouches++;
if(Owner->bIsDisabled)
{
Owner->OnClickedWhenDisabled.Broadcast();
return FReply::Unhandled();
}
FVector2D LocalCoord = MyGeometry.AbsoluteToLocal( Event.GetScreenSpacePosition() );
// skip controls already in use
if (CapturedPointerIndex == -1)
{
if (PositionIsInside(CorrectedCenter, LocalCoord, CorrectedInteractionSize))
{
// Align Joystick inside of Screen
AlignBoxIntoScreen(LocalCoord, CorrectedVisualSize, MyGeometry.GetLocalSize());
CapturedPointerIndex = Event.GetPointerIndex();
if (Owner->ActivationDelay == 0.f)
{
CurrentColor = Owner->ActiveColor;
if (!Owner->bPreventRecenter&&(PositionIsInside(CorrectedCenter, LocalCoord, CorrectedInteractionSize*Owner->RecenterSize)))
{
VisualCenter = LocalCoord;
}
if (HandleTouch(0, LocalCoord, MyGeometry.GetLocalSize())) // Never fail!
{
return FReply::Handled().CaptureMouse(SharedThis(this));
}
}
else
{
bNeedUpdatedCenter = true;
ElapsedTime = 0.f;
NextCenter = LocalCoord;
return FReply::Unhandled();
}
}
}
return FReply::Unhandled();
}
FReply STitanVirtualJoystick::OnTouchMoved(const FGeometry& MyGeometry, const FPointerEvent& Event)
{
if(Owner->bIsDisabled&&NumofTouches==0)
{
return FReply::Unhandled();
}
FVector2D LocalCoord = MyGeometry.AbsoluteToLocal( Event.GetScreenSpacePosition() );
// is this control the one captured to this pointer?
if (CapturedPointerIndex == Event.GetPointerIndex())
{
if (bNeedUpdatedCenter)
{
return FReply::Unhandled();
}
else if (HandleTouch(0, LocalCoord, MyGeometry.GetLocalSize()))
{
return FReply::Handled();
}
}
return FReply::Unhandled();
}
FReply STitanVirtualJoystick::OnTouchEnded(const FGeometry& MyGeometry, const FPointerEvent& Event)
{
NumofTouches--;
// is this control the one captured to this pointer?
if ( CapturedPointerIndex == Event.GetPointerIndex() )
{
// release and center the joystick
Index1Location = FVector2D(0, 0);
CapturedPointerIndex = -1;
// send one more joystick update for the centering
HandleEvent = true;
// Pass event as unhandled if time is too short
if ( bNeedUpdatedCenter )
{
bNeedUpdatedCenter = false;
return FReply::Unhandled();
}
return FReply::Handled().ReleaseMouseCapture();
}
return FReply::Unhandled();
}
bool STitanVirtualJoystick::HandleTouch(int32 ControlIndex, const FVector2D& LocalCoord, const FVector2D& ScreenSize)
{
// figure out position around center
FVector2D Offset = LocalCoord -VisualCenter;
//UE_LOG(LogTemp,Log,TEXT("LocalCord %f , %f"),LocalCoord.X,LocalCoord.Y);
// only do work if we aren't at the center
if (Offset == FVector2D(0, 0))
{
Index1Location = Offset;
}
else
{
// clamp to the ellipse of the stick (snaps to the visual size, so, the art should go all the way to the edge of the texture)
float DistanceToTouchSqr = Offset.SizeSquared();
float Angle = FMath::Atan2(Offset.Y, Offset.X);
// length along line to ellipse: L = 1.0 / sqrt(((sin(T)/Rx)^2 + (cos(T)/Ry)^2))
float CosAngle = FMath::Cos(Angle);
float SinAngle = FMath::Sin(Angle);
float XTerm = CosAngle / (CorrectedVisualSize.X * 0.5f);
float YTerm = SinAngle / (CorrectedVisualSize.Y * 0.5f);
float DistanceToEdge = FMath::InvSqrt(XTerm * XTerm + YTerm * YTerm);
//UE_LOG(LogTemp,Log,TEXT("%f Distance to edge"),DistanceToEdge);
// only clamp
if (DistanceToTouchSqr > FMath::Square(DistanceToEdge))
{
Index1Location = FVector2D(DistanceToEdge * CosAngle, DistanceToEdge * SinAngle);
}
else
{
Index1Location = Offset;
}
}
/*FVector2D AbsoluteThumbPos = ThumbPosition + VisualCenter;
//AlignBoxIntoScreen(AbsoluteThumbPos, CorrectedThumbSize, ScreenSize);
ThumbPosition = AbsoluteThumbPos - VisualCenter;
UE_LOG(LogTemp,Log,TEXT("ThumbPosition %f %f "),ThumbPosition.X,ThumbPosition.Y);*/
return true;
}
void STitanVirtualJoystick::Tick( const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime )
{
if (State == State_WaitForStart || State == State_CountingDownToStart)
{
CurrentColor = FLinearColor(0,0,0,0);
}
else
{
// lerp to the desired opacity based on whether the user is interacting with the joystick
// CurrentColor = FMath::Lerp(CurrentOpacity, GetBaseOpacity(), OPACITY_LERP_RATE * InDeltaTime);
CurrentColor= FLinearColor::LerpUsingHSV(CurrentColor,GetBaseColor(),OPACITY_LERP_RATE * InDeltaTime);
}
// count how many controls are active
//TODO remove this
int32 NumActiveControls = 0;
// figure out how much to scale the control sizes
float ScaleFactor = GetScaleFactor(AllottedGeometry);
if (bNeedUpdatedCenter)
{
ElapsedTime += InDeltaTime;
if (ElapsedTime > Owner->ActivationDelay)
{
bNeedUpdatedCenter = false;
CurrentColor = Owner->ActiveColor;
if (!Owner->bPreventRecenter)
{
VisualCenter = NextCenter;
}
HandleTouch(0, NextCenter, AllottedGeometry.GetLocalSize());
}
}
// calculate absolute positions based on geometry
// @todo: Need to manage geometry changing!
if (!bHasBeenPositioned || ScaleFactor != PreviousScalingFactor)
{
// update all the sizes
CorrectedCenter = FVector2D(ResolveRelativePosition(Owner->Center.X, AllottedGeometry.GetLocalSize().X, ScaleFactor), ResolveRelativePosition(Owner->Center.Y, AllottedGeometry.GetLocalSize().Y, ScaleFactor));
VisualCenter = CorrectedCenter;
CorrectedVisualSize = FVector2D(ResolveRelativePosition(Owner->VisualSize.X, AllottedGeometry.GetLocalSize().X, ScaleFactor), ResolveRelativePosition(Owner->VisualSize.Y, AllottedGeometry.GetLocalSize().Y, ScaleFactor));
CorrectedInteractionSize = FVector2D(ResolveRelativePosition(Owner->InteractionSize.X, AllottedGeometry.GetLocalSize().X, ScaleFactor), ResolveRelativePosition(Owner->InteractionSize.Y, AllottedGeometry.GetLocalSize().Y, ScaleFactor));
CorrectedThumbSize = FVector2D(ResolveRelativePosition(Owner->ThumbSize.X, AllottedGeometry.GetLocalSize().X, ScaleFactor), ResolveRelativePosition(Owner->ThumbSize.Y, AllottedGeometry.GetLocalSize().Y, ScaleFactor));
CorrectedInputScale = Owner->InputScale; // *ScaleFactor;
bHasBeenPositioned = true;
}
if (CapturedPointerIndex >= 0 || HandleEvent)
{
//Handle event is for sending one more input
HandleEvent = false;
// Get the corrected thumb offset scale (now allows ellipse instead of assuming square)
FVector2D ThumbScaledOffset = FVector2D(Index1Location.X * 2.0f / CorrectedVisualSize.X, Index1Location.Y * 2.0f / CorrectedVisualSize.Y);
float ThumbSquareSum = ThumbScaledOffset.X * ThumbScaledOffset.X + ThumbScaledOffset.Y * ThumbScaledOffset.Y;
float ThumbMagnitude = FMath::Sqrt(ThumbSquareSum);
FVector2D ThumbNormalized = FVector2D(0.f, 0.f);
if (ThumbSquareSum > SMALL_NUMBER)
{
const float Scale = 1.0f / ThumbMagnitude;
ThumbNormalized = FVector2D(ThumbScaledOffset.X * Scale, ThumbScaledOffset.Y * Scale);
}
// Find the scale to apply to ThumbNormalized vector to project onto unit square
float ToSquareScale = fabs(ThumbNormalized.Y) > fabs(ThumbNormalized.X) ? FMath::Sqrt((ThumbNormalized.X * ThumbNormalized.X) / (ThumbNormalized.Y * ThumbNormalized.Y) + 1.0f)
: ThumbNormalized.X == 0.0f ? 1.0f : FMath::Sqrt((ThumbNormalized.Y * ThumbNormalized.Y) / (ThumbNormalized.X * ThumbNormalized.X) + 1.0f);
// Apply proportional offset corrected for projection to unit square
FVector2D NormalizedOffset = ThumbNormalized * CorrectedInputScale * ThumbMagnitude * ToSquareScale;
// now pass the fake joystick events to the game
//press and release handling
const FGamepadKeyNames::Type XAxis = (Owner->MainInputKey.IsValid() ? Owner->MainInputKey.GetFName() : ( FGamepadKeyNames::LeftAnalogX ));
const FGamepadKeyNames::Type YAxis = (Owner->AltInputKey.IsValid() ? Owner->AltInputKey.GetFName() : (FGamepadKeyNames::LeftAnalogY ));
FSlateApplication::Get().SetAllUserFocusToGameViewport();
FSlateApplication::Get().OnControllerAnalog(XAxis, 0, NormalizedOffset.X);
FSlateApplication::Get().OnControllerAnalog(YAxis, 0, -NormalizedOffset.Y);
if(Owner->PressInputKey.IsValid())
{
if(NumofTouches!=0)
{
const FGamepadKeyNames::Type Press = Owner->PressInputKey.GetFName() ;
FSlateApplication::Get().OnControllerButtonPressed(Press,0,false);
}else
{
const FGamepadKeyNames::Type Press = Owner->PressInputKey.GetFName() ;
FSlateApplication::Get().OnControllerButtonReleased(Press,0,false);
}
}
}
// is this active?
if (CapturedPointerIndex != -1)
{
NumActiveControls++;
}
// we need to store the computed scale factor so we can compare it with the value computed in the following frame and, if necessary, recompute widget position
PreviousScalingFactor = ScaleFactor;
// STATE MACHINE!
if (NumActiveControls > 0 || Owner->bPreventRecenter)
{
// any active control snaps the state to active immediately
State = State_Active;
}
else
{
switch (State)
{
case State_WaitForStart:
{
State = State_CountingDownToStart;
Countdown = Owner->StartupDelay;
}
break;
case State_CountingDownToStart:
// update the countdown
Countdown -= InDeltaTime;
if (Countdown <= 0.0f)
{
State = State_Inactive;
}
break;
case State_Active:
if (NumActiveControls == 0)
{
// start going to inactive
State = State_CountingDownToInactive;
Countdown = Owner->TimeUntilDeactive;
}
break;
case State_CountingDownToInactive:
// update the countdown
Countdown -= InDeltaTime;
if (Countdown <= 0.0f)
{
// should we start counting down to a control reset?
if (Owner->TimeUntilReset > 0.0f)
{
State = State_CountingDownToReset;
Countdown = Owner->TimeUntilReset;
}
else
{
// if not, then just go inactive
State = State_Inactive;
}
}
break;
case State_CountingDownToReset:
Countdown -= InDeltaTime;
if (Countdown <= 0.0f)
{
// reset all the controls
Reset();
// finally, go inactive
State = State_Inactive;
}
break;
}
}
}
void STitanVirtualJoystick::SetJoystickVisibility(const bool bInVisible, const bool bInFade)
{
// if we aren't fading, then just set the current opacity to desired
if (!bInFade)
{
if (bInVisible)
{
CurrentColor = GetBaseColor();
}
else
{
CurrentColor = FLinearColor(0,0,0,0);
}
}
bVisible = bInVisible;
}
void STitanVirtualJoystick::AlignBoxIntoScreen(FVector2D& Position, const FVector2D& Size, const FVector2D& ScreenSize)
{
if ( Size.X > ScreenSize.X || Size.Y > ScreenSize.Y )
{
return;
}
// Align box to fit into screen
if ( Position.X - Size.X * 0.5f < 0.f )
{
Position.X = Size.X * 0.5f;
}
if ( Position.X + Size.X * 0.5f > ScreenSize.X )
{
Position.X = ScreenSize.X - Size.X * 0.5f;
}
if ( Position.Y - Size.Y * 0.5f < 0.f )
{
Position.Y = Size.Y * 0.5f;
}
if ( Position.Y + Size.Y * 0.5f > ScreenSize.Y )
{
Position.Y = ScreenSize.Y - Size.Y * 0.5f;
}
}
| 28.556364 | 249 | 0.715523 | learnMoreCode |
b18eb201b9e8ca428a05f04a2031f06ad3111520 | 1,781 | cpp | C++ | src/hdk/animation/hdTranslationAction.cpp | cdave1/hdk | 7c00dcbb255a48ab4a77d808cda0096c7e0a0fa6 | [
"Zlib"
] | 2 | 2016-06-15T17:47:50.000Z | 2019-07-29T10:33:05.000Z | src/hdk/animation/hdTranslationAction.cpp | cdave1/hdk | 7c00dcbb255a48ab4a77d808cda0096c7e0a0fa6 | [
"Zlib"
] | null | null | null | src/hdk/animation/hdTranslationAction.cpp | cdave1/hdk | 7c00dcbb255a48ab4a77d808cda0096c7e0a0fa6 | [
"Zlib"
] | null | null | null | /*
* Copyright (c) 2014 Hackdirt Ltd.
* Author: David Petrie (david@davidpetrie.com)
*
* 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.
*/
#include "hdTranslationAction.h"
hdTranslationAction::hdTranslationAction()
{
m_start = hdVec3(0, 0, 0);
m_destination = hdVec3(0, 0, 0);
}
void hdTranslationAction::Apply(hdTimeInterval elapsed, hdGameObject* gameObject)
{
hdVec3 current = gameObject->GetTransform().translation;
hdVec3 stepDistance = m_destination;
stepDistance -= m_start;
stepDistance *= (m_progress / m_duration);
hdVec3 newPosition = m_start;
newPosition += stepDistance;
// Add the diff
hdTranslateVertices(gameObject->GetVertices(), gameObject->GetVertexCount(), newPosition-current);
gameObject->ResetAABB();
#ifdef ANIMATION_DEBUG
hdPrintf("Name: %d, Elapsed: %f, Moving to: %f, %f, %f\n", gameObject->GetName(), elapsed,
(float)newPosition.x, (float)newPosition.y, (float)newPosition.z);
#endif
}
| 36.346939 | 102 | 0.733296 | cdave1 |
b18f5ac1472778806890adfd1f0e6b92b5622683 | 170 | hpp | C++ | package/broker/broker/broker_multiton.hpp | mambaru/wfc_io | 953f03831e323b85df05d5e0461444f1879e412c | [
"MIT"
] | null | null | null | package/broker/broker/broker_multiton.hpp | mambaru/wfc_io | 953f03831e323b85df05d5e0461444f1879e412c | [
"MIT"
] | 4 | 2019-12-06T01:02:14.000Z | 2021-04-20T19:46:34.000Z | package/broker/broker/broker_multiton.hpp | mambaru/wfc_io | 953f03831e323b85df05d5e0461444f1879e412c | [
"MIT"
] | null | null | null | #pragma once
#include <wfc/module/component.hpp>
namespace wfc{ namespace io{
class broker_multiton
: public ::wfc::component
{
public:
broker_multiton();
};
}}
| 11.333333 | 35 | 0.705882 | mambaru |
b1924bd0e2db117071ee765812688fb3cb7b5c13 | 128 | cc | C++ | tests/parallel_flat_hash_set_test.cc | phprus/parallel-hashmap | 73be7c2ab267778f64c7383b7a8150788ab7e2ef | [
"Apache-2.0"
] | null | null | null | tests/parallel_flat_hash_set_test.cc | phprus/parallel-hashmap | 73be7c2ab267778f64c7383b7a8150788ab7e2ef | [
"Apache-2.0"
] | null | null | null | tests/parallel_flat_hash_set_test.cc | phprus/parallel-hashmap | 73be7c2ab267778f64c7383b7a8150788ab7e2ef | [
"Apache-2.0"
] | null | null | null | #define THIS_HASH_SET parallel_flat_hash_set
#define THIS_TEST_NAME ParallelFlatHashSet
#include "parallel_hash_set_test.cc"
| 21.333333 | 45 | 0.867188 | phprus |
b196f574873787e5bebaffed631140bc467bab7c | 73,964 | cpp | C++ | src/blas/backends/cublas/cublas_level3.cpp | trosenqu/oneMKL | d06919ca0f1c675b170df94259f319eb1d020d5c | [
"Apache-2.0"
] | null | null | null | src/blas/backends/cublas/cublas_level3.cpp | trosenqu/oneMKL | d06919ca0f1c675b170df94259f319eb1d020d5c | [
"Apache-2.0"
] | null | null | null | src/blas/backends/cublas/cublas_level3.cpp | trosenqu/oneMKL | d06919ca0f1c675b170df94259f319eb1d020d5c | [
"Apache-2.0"
] | 1 | 2022-01-10T16:44:10.000Z | 2022-01-10T16:44:10.000Z | /***************************************************************************
* Copyright (C) Codeplay Software Limited
* 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
*
* For your convenience, a copy of the License has been included in this
* repository.
*
* 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 "cublas_helper.hpp"
#include "cublas_task.hpp"
#include "oneapi/mkl/exceptions.hpp"
#include "oneapi/mkl/blas/detail/cublas/onemkl_blas_cublas.hpp"
namespace oneapi {
namespace mkl {
namespace blas {
namespace cublas {
namespace column_major {
// Buffer APIs
template <typename Func, typename T>
inline void gemm(Func func, cl::sycl::queue &queue, transpose transa, transpose transb, int64_t m,
int64_t n, int64_t k, T alpha, cl::sycl::buffer<T, 1> &a, int64_t lda,
cl::sycl::buffer<T, 1> &b, int64_t ldb, T beta, cl::sycl::buffer<T, 1> &c,
int64_t ldc) {
using cuDataType = typename CudaEquivalentType<T>::Type;
overflow_check(m, n, k, lda, ldb, ldc);
queue.submit([&](cl::sycl::handler &cgh) {
auto a_acc = a.template get_access<cl::sycl::access::mode::read>(cgh);
auto b_acc = b.template get_access<cl::sycl::access::mode::read>(cgh);
auto c_acc = c.template get_access<cl::sycl::access::mode::read_write>(cgh);
onemkl_cublas_host_task(cgh, queue, [=](CublasScopedContextHandler &sc) {
auto handle = sc.get_handle(queue);
auto a_ = sc.get_mem<cuDataType *>(a_acc);
auto b_ = sc.get_mem<cuDataType *>(b_acc);
auto c_ = sc.get_mem<cuDataType *>(c_acc);
cublasStatus_t err;
CUBLAS_ERROR_FUNC(func, err, handle, get_cublas_operation(transa),
get_cublas_operation(transb), m, n, k, (cuDataType *)&alpha, a_, lda,
b_, ldb, (cuDataType *)&beta, c_, ldc);
});
});
}
#define GEMM_LAUNCHER(TYPE, CUBLAS_ROUTINE) \
void gemm(cl::sycl::queue &queue, transpose transa, transpose transb, int64_t m, int64_t n, \
int64_t k, TYPE alpha, cl::sycl::buffer<TYPE, 1> &a, int64_t lda, \
cl::sycl::buffer<TYPE, 1> &b, int64_t ldb, TYPE beta, cl::sycl::buffer<TYPE, 1> &c, \
int64_t ldc) { \
gemm(CUBLAS_ROUTINE, queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); \
}
GEMM_LAUNCHER(float, cublasSgemm)
GEMM_LAUNCHER(double, cublasDgemm)
GEMM_LAUNCHER(std::complex<float>, cublasCgemm)
GEMM_LAUNCHER(std::complex<double>, cublasZgemm)
#undef GEMM_LAUNCHER
template <typename T_A, typename T_B, typename T_C, typename DATATYPE_A, typename DATATYPE_B,
typename DATATYPE_C>
inline void gemm_ex(DATATYPE_A DT_A, DATATYPE_B DT_B, DATATYPE_C DT_C, cl::sycl::queue &queue,
transpose transa, transpose transb, int64_t m, int64_t n, int64_t k, T_C alpha,
cl::sycl::buffer<T_A, 1> &a, int64_t lda, cl::sycl::buffer<T_B, 1> &b,
int64_t ldb, T_C beta, cl::sycl::buffer<T_C, 1> &c, int64_t ldc) {
using cuDataType_A = typename CudaEquivalentType<T_A>::Type;
using cuDataType_B = typename CudaEquivalentType<T_B>::Type;
using cuDataType_C = typename CudaEquivalentType<T_C>::Type;
overflow_check(m, n, k, lda, ldb, ldc);
queue.submit([&](cl::sycl::handler &cgh) {
if (!verify_support<cl::sycl::half, T_A, T_B, T_C>(queue, cl::sycl::aspect::fp16)) {
throw oneapi::mkl::unimplemented(
"blas", "cl::sycl::half",
"half is not supported by the device or the sycl compiler");
}
auto a_acc = a.template get_access<cl::sycl::access::mode::read>(cgh);
auto b_acc = b.template get_access<cl::sycl::access::mode::read>(cgh);
auto c_acc = c.template get_access<cl::sycl::access::mode::read_write>(cgh);
onemkl_cublas_host_task(cgh, queue, [=](CublasScopedContextHandler &sc) {
auto handle = sc.get_handle(queue);
auto a_ = sc.get_mem<cuDataType_A *>(a_acc);
auto b_ = sc.get_mem<cuDataType_B *>(b_acc);
auto c_ = sc.get_mem<cuDataType_C *>(c_acc);
cublasStatus_t err;
CUBLAS_ERROR_FUNC(cublasGemmEx, err, handle, get_cublas_operation(transa),
get_cublas_operation(transb), m, n, k, (cuDataType_C *)&alpha, a_,
DT_A, lda, b_, DT_B, ldb, (cuDataType_C *)&beta, c_, DT_C, ldc, DT_C,
CUBLAS_GEMM_DEFAULT);
});
});
}
#define GEMM_EX_LAUNCHER(TYPE_A, TYPE_B, TYPE_C, CUDADATATYPE_A, CUDADATATYPE_B, CUDADATATYPE_C) \
void gemm(cl::sycl::queue &queue, transpose transa, transpose transb, int64_t m, int64_t n, \
int64_t k, TYPE_C alpha, cl::sycl::buffer<TYPE_A, 1> &a, int64_t lda, \
cl::sycl::buffer<TYPE_B, 1> &b, int64_t ldb, TYPE_C beta, \
cl::sycl::buffer<TYPE_C, 1> &c, int64_t ldc) { \
gemm_ex(CUDADATATYPE_A, CUDADATATYPE_B, CUDADATATYPE_C, queue, transa, transb, m, n, k, \
alpha, a, lda, b, ldb, beta, c, ldc); \
}
GEMM_EX_LAUNCHER(sycl::half, sycl::half, float, CUDA_R_16F, CUDA_R_16F, CUDA_R_32F)
GEMM_EX_LAUNCHER(sycl::half, sycl::half, sycl::half, CUDA_R_16F, CUDA_R_16F, CUDA_R_16F)
#undef GEMM_EX_LAUNCHER
void gemm(cl::sycl::queue &queue, transpose transa, transpose transb, int64_t m, int64_t n,
int64_t k, float alpha, cl::sycl::buffer<bfloat16, 1> &a, int64_t lda,
cl::sycl::buffer<bfloat16, 1> &b, int64_t ldb, float beta, cl::sycl::buffer<float, 1> &c,
int64_t ldc) {
throw unimplemented("blas", "gemm", "for column_major layout");
}
template <typename Func, typename T>
inline void symm(Func func, cl::sycl::queue &queue, side left_right, uplo upper_lower, int64_t m,
int64_t n, T alpha, cl::sycl::buffer<T, 1> &a, int64_t lda,
cl::sycl::buffer<T, 1> &b, int64_t ldb, T beta, cl::sycl::buffer<T, 1> &c,
int64_t ldc) {
using cuDataType = typename CudaEquivalentType<T>::Type;
overflow_check(m, n, lda, ldb, ldc);
queue.submit([&](cl::sycl::handler &cgh) {
auto a_acc = a.template get_access<cl::sycl::access::mode::read>(cgh);
auto b_acc = b.template get_access<cl::sycl::access::mode::read>(cgh);
auto c_acc = c.template get_access<cl::sycl::access::mode::read_write>(cgh);
onemkl_cublas_host_task(cgh, queue, [=](CublasScopedContextHandler &sc) {
auto handle = sc.get_handle(queue);
auto a_ = sc.get_mem<cuDataType *>(a_acc);
auto b_ = sc.get_mem<cuDataType *>(b_acc);
auto c_ = sc.get_mem<cuDataType *>(c_acc);
cublasStatus_t err;
CUBLAS_ERROR_FUNC(func, err, handle, get_cublas_side_mode(left_right),
get_cublas_fill_mode(upper_lower), m, n, (cuDataType *)&alpha, a_,
lda, b_, ldb, (cuDataType *)&beta, c_, ldc);
});
});
}
#define SYMM_LAUNCHER(TYPE, CUBLAS_ROUTINE) \
void symm(cl::sycl::queue &queue, side left_right, uplo upper_lower, int64_t m, int64_t n, \
TYPE alpha, cl::sycl::buffer<TYPE, 1> &a, int64_t lda, cl::sycl::buffer<TYPE, 1> &b, \
int64_t ldb, TYPE beta, cl::sycl::buffer<TYPE, 1> &c, int64_t ldc) { \
symm(CUBLAS_ROUTINE, queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, \
ldc); \
}
SYMM_LAUNCHER(float, cublasSsymm)
SYMM_LAUNCHER(double, cublasDsymm)
SYMM_LAUNCHER(std::complex<float>, cublasCsymm)
SYMM_LAUNCHER(std::complex<double>, cublasZsymm)
#undef SYMM_LAUNCHER
template <typename Func, typename T>
inline void hemm(Func func, cl::sycl::queue &queue, side left_right, uplo upper_lower, int64_t m,
int64_t n, T alpha, cl::sycl::buffer<T, 1> &a, int64_t lda,
cl::sycl::buffer<T, 1> &b, int64_t ldb, T beta, cl::sycl::buffer<T, 1> &c,
int64_t ldc) {
using cuDataType = typename CudaEquivalentType<T>::Type;
overflow_check(m, n, lda, ldb, ldc);
queue.submit([&](cl::sycl::handler &cgh) {
auto a_acc = a.template get_access<cl::sycl::access::mode::read>(cgh);
auto b_acc = b.template get_access<cl::sycl::access::mode::read>(cgh);
auto c_acc = c.template get_access<cl::sycl::access::mode::read_write>(cgh);
onemkl_cublas_host_task(cgh, queue, [=](CublasScopedContextHandler &sc) {
auto handle = sc.get_handle(queue);
auto a_ = sc.get_mem<cuDataType *>(a_acc);
auto b_ = sc.get_mem<cuDataType *>(b_acc);
auto c_ = sc.get_mem<cuDataType *>(c_acc);
cublasStatus_t err;
CUBLAS_ERROR_FUNC(func, err, handle, get_cublas_side_mode(left_right),
get_cublas_fill_mode(upper_lower), m, n, (cuDataType *)&alpha, a_,
lda, b_, ldb, (cuDataType *)&beta, c_, ldc);
});
});
}
#define HEMM_LAUNCHER(TYPE, CUBLAS_ROUTINE) \
void hemm(cl::sycl::queue &queue, side left_right, uplo upper_lower, int64_t m, int64_t n, \
TYPE alpha, cl::sycl::buffer<TYPE, 1> &a, int64_t lda, cl::sycl::buffer<TYPE, 1> &b, \
int64_t ldb, TYPE beta, cl::sycl::buffer<TYPE, 1> &c, int64_t ldc) { \
hemm(CUBLAS_ROUTINE, queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, \
ldc); \
}
HEMM_LAUNCHER(std::complex<float>, cublasChemm)
HEMM_LAUNCHER(std::complex<double>, cublasZhemm)
#undef HEMM_LAUNCHER
template <typename Func, typename T>
inline void syrk(Func func, cl::sycl::queue &queue, uplo upper_lower, transpose trans, int64_t n,
int64_t k, T alpha, cl::sycl::buffer<T, 1> &a, int64_t lda, T beta,
cl::sycl::buffer<T, 1> &c, int64_t ldc) {
using cuDataType = typename CudaEquivalentType<T>::Type;
overflow_check(n, k, lda, ldc);
queue.submit([&](cl::sycl::handler &cgh) {
auto a_acc = a.template get_access<cl::sycl::access::mode::read>(cgh);
auto c_acc = c.template get_access<cl::sycl::access::mode::read_write>(cgh);
onemkl_cublas_host_task(cgh, queue, [=](CublasScopedContextHandler &sc) {
auto handle = sc.get_handle(queue);
auto a_ = sc.get_mem<cuDataType *>(a_acc);
auto c_ = sc.get_mem<cuDataType *>(c_acc);
cublasStatus_t err;
CUBLAS_ERROR_FUNC(func, err, handle, get_cublas_fill_mode(upper_lower),
get_cublas_operation(trans), n, k, (cuDataType *)&alpha, a_, lda,
(cuDataType *)&beta, c_, ldc);
});
});
}
#define SYRK_LAUNCHER(TYPE, CUBLAS_ROUTINE) \
void syrk(cl::sycl::queue &queue, uplo upper_lower, transpose trans, int64_t n, int64_t k, \
TYPE alpha, cl::sycl::buffer<TYPE, 1> &a, int64_t lda, TYPE beta, \
cl::sycl::buffer<TYPE, 1> &c, int64_t ldc) { \
syrk(CUBLAS_ROUTINE, queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc); \
}
SYRK_LAUNCHER(float, cublasSsyrk)
SYRK_LAUNCHER(double, cublasDsyrk)
SYRK_LAUNCHER(std::complex<float>, cublasCsyrk)
SYRK_LAUNCHER(std::complex<double>, cublasZsyrk)
#undef SYRK_LAUNCHER
template <typename Func, typename DataType, typename ScalarType>
inline void herk(Func func, cl::sycl::queue &queue, uplo upper_lower, transpose trans, int64_t n,
int64_t k, ScalarType alpha, cl::sycl::buffer<DataType, 1> &a, int64_t lda,
ScalarType beta, cl::sycl::buffer<DataType, 1> &c, int64_t ldc) {
using cuDataType = typename CudaEquivalentType<DataType>::Type;
using cuScalarType = typename CudaEquivalentType<ScalarType>::Type;
overflow_check(n, k, lda, ldc);
queue.submit([&](cl::sycl::handler &cgh) {
auto a_acc = a.template get_access<cl::sycl::access::mode::read>(cgh);
auto c_acc = c.template get_access<cl::sycl::access::mode::read_write>(cgh);
onemkl_cublas_host_task(cgh, queue, [=](CublasScopedContextHandler &sc) {
auto handle = sc.get_handle(queue);
auto a_ = sc.get_mem<cuDataType *>(a_acc);
auto c_ = sc.get_mem<cuDataType *>(c_acc);
cublasStatus_t err;
CUBLAS_ERROR_FUNC(func, err, handle, get_cublas_fill_mode(upper_lower),
get_cublas_operation(trans), n, k, (cuScalarType *)&alpha, a_, lda,
(cuScalarType *)&beta, c_, ldc);
});
});
}
#define HERK_LAUNCHER(DATA_TYPE, SCALAR_TYPE, CUBLAS_ROUTINE) \
void herk(cl::sycl::queue &queue, uplo upper_lower, transpose trans, int64_t n, int64_t k, \
SCALAR_TYPE alpha, cl::sycl::buffer<DATA_TYPE, 1> &a, int64_t lda, SCALAR_TYPE beta, \
cl::sycl::buffer<DATA_TYPE, 1> &c, int64_t ldc) { \
herk(CUBLAS_ROUTINE, queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc); \
}
HERK_LAUNCHER(std::complex<float>, float, cublasCherk)
HERK_LAUNCHER(std::complex<double>, double, cublasZherk)
#undef HERK_LAUNCHER
template <typename Func, typename T>
inline void syr2k(Func func, cl::sycl::queue &queue, uplo upper_lower, transpose trans, int64_t n,
int64_t k, T alpha, cl::sycl::buffer<T, 1> &a, int64_t lda,
cl::sycl::buffer<T, 1> &b, int64_t ldb, T beta, cl::sycl::buffer<T, 1> &c,
int64_t ldc) {
using cuDataType = typename CudaEquivalentType<T>::Type;
overflow_check(n, k, lda, ldb, ldc);
queue.submit([&](cl::sycl::handler &cgh) {
auto a_acc = a.template get_access<cl::sycl::access::mode::read>(cgh);
auto b_acc = b.template get_access<cl::sycl::access::mode::read>(cgh);
auto c_acc = c.template get_access<cl::sycl::access::mode::read_write>(cgh);
onemkl_cublas_host_task(cgh, queue, [=](CublasScopedContextHandler &sc) {
auto handle = sc.get_handle(queue);
auto a_ = sc.get_mem<cuDataType *>(a_acc);
auto b_ = sc.get_mem<cuDataType *>(b_acc);
auto c_ = sc.get_mem<cuDataType *>(c_acc);
cublasStatus_t err;
CUBLAS_ERROR_FUNC(func, err, handle, get_cublas_fill_mode(upper_lower),
get_cublas_operation(trans), n, k, (cuDataType *)&alpha, a_, lda, b_,
ldb, (cuDataType *)&beta, c_, ldc);
});
});
}
#define SYR2K_LAUNCHER(TYPE, CUBLAS_ROUTINE) \
void syr2k(cl::sycl::queue &queue, uplo upper_lower, transpose trans, int64_t n, int64_t k, \
TYPE alpha, cl::sycl::buffer<TYPE, 1> &a, int64_t lda, \
cl::sycl::buffer<TYPE, 1> &b, int64_t ldb, TYPE beta, cl::sycl::buffer<TYPE, 1> &c, \
int64_t ldc) { \
syr2k(CUBLAS_ROUTINE, queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, \
ldc); \
}
SYR2K_LAUNCHER(float, cublasSsyr2k)
SYR2K_LAUNCHER(double, cublasDsyr2k)
SYR2K_LAUNCHER(std::complex<float>, cublasCsyr2k)
SYR2K_LAUNCHER(std::complex<double>, cublasZsyr2k)
#undef SYR2K_LAUNCHER
template <typename Func, typename DataType, typename ScalarType>
inline void her2k(Func func, cl::sycl::queue &queue, uplo upper_lower, transpose trans, int64_t n,
int64_t k, DataType alpha, cl::sycl::buffer<DataType, 1> &a, int64_t lda,
cl::sycl::buffer<DataType, 1> &b, int64_t ldb, ScalarType beta,
cl::sycl::buffer<DataType, 1> &c, int64_t ldc) {
using cuDataType = typename CudaEquivalentType<DataType>::Type;
using cuScalarType = typename CudaEquivalentType<ScalarType>::Type;
overflow_check(n, k, lda, ldb, ldc);
queue.submit([&](cl::sycl::handler &cgh) {
auto a_acc = a.template get_access<cl::sycl::access::mode::read>(cgh);
auto b_acc = b.template get_access<cl::sycl::access::mode::read>(cgh);
auto c_acc = c.template get_access<cl::sycl::access::mode::read_write>(cgh);
onemkl_cublas_host_task(cgh, queue, [=](CublasScopedContextHandler &sc) {
auto handle = sc.get_handle(queue);
auto a_ = sc.get_mem<cuDataType *>(a_acc);
auto b_ = sc.get_mem<cuDataType *>(b_acc);
auto c_ = sc.get_mem<cuDataType *>(c_acc);
cublasStatus_t err;
CUBLAS_ERROR_FUNC(func, err, handle, get_cublas_fill_mode(upper_lower),
get_cublas_operation(trans), n, k, (cuDataType *)&alpha, a_, lda, b_,
ldb, (cuScalarType *)&beta, c_, ldc);
});
});
}
#define HER2K_LAUNCHER(DATA_TYPE, SCALAR_TYPE, CUBLAS_ROUTINE) \
void her2k(cl::sycl::queue &queue, uplo upper_lower, transpose trans, int64_t n, int64_t k, \
DATA_TYPE alpha, cl::sycl::buffer<DATA_TYPE, 1> &a, int64_t lda, \
cl::sycl::buffer<DATA_TYPE, 1> &b, int64_t ldb, SCALAR_TYPE beta, \
cl::sycl::buffer<DATA_TYPE, 1> &c, int64_t ldc) { \
her2k(CUBLAS_ROUTINE, queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, \
ldc); \
}
HER2K_LAUNCHER(std::complex<float>, float, cublasCher2k)
HER2K_LAUNCHER(std::complex<double>, double, cublasZher2k)
#undef HER2K_LAUNCHER
// NOTE: In cublas TRMM diverted from the netlib blas and for performance
// reason it requires the C matrix to be
// separated from the B matrix. It is possible to use B instead of C, but this
// will slow-down the code.
template <typename Func, typename T>
inline void trmm(Func func, cl::sycl::queue &queue, side left_right, uplo upper_lower,
transpose trans, diag unit_diag, int64_t m, int64_t n, T alpha,
cl::sycl::buffer<T, 1> &a, int64_t lda, cl::sycl::buffer<T, 1> &b, int64_t ldb) {
using cuDataType = typename CudaEquivalentType<T>::Type;
overflow_check(m, n, lda, ldb);
queue.submit([&](cl::sycl::handler &cgh) {
auto a_acc = a.template get_access<cl::sycl::access::mode::read>(cgh);
auto b_acc = b.template get_access<cl::sycl::access::mode::read_write>(cgh);
onemkl_cublas_host_task(cgh, queue, [=](CublasScopedContextHandler &sc) {
auto handle = sc.get_handle(queue);
auto a_ = sc.get_mem<cuDataType *>(a_acc);
auto b_ = sc.get_mem<cuDataType *>(b_acc);
cublasStatus_t err;
CUBLAS_ERROR_FUNC(func, err, handle, get_cublas_side_mode(left_right),
get_cublas_fill_mode(upper_lower), get_cublas_operation(trans),
get_cublas_diag_type(unit_diag), m, n, (cuDataType *)&alpha, a_, lda,
b_, ldb, b_, ldb);
});
});
}
#define TRMM_LAUNCHER(TYPE, CUBLAS_ROUTINE) \
void trmm(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, \
diag unit_diag, int64_t m, int64_t n, TYPE alpha, cl::sycl::buffer<TYPE, 1> &a, \
int64_t lda, cl::sycl::buffer<TYPE, 1> &b, int64_t ldb) { \
trmm(CUBLAS_ROUTINE, queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, \
lda, b, ldb); \
}
TRMM_LAUNCHER(float, cublasStrmm)
TRMM_LAUNCHER(double, cublasDtrmm)
TRMM_LAUNCHER(std::complex<float>, cublasCtrmm)
TRMM_LAUNCHER(std::complex<double>, cublasZtrmm)
#undef TRMM_LAUNCHER
template <typename Func, typename T>
inline void trsm(Func func, cl::sycl::queue &queue, side left_right, uplo upper_lower,
transpose trans, diag unit_diag, int64_t m, int64_t n, T alpha,
cl::sycl::buffer<T, 1> &a, int64_t lda, cl::sycl::buffer<T, 1> &b, int64_t ldb) {
using cuDataType = typename CudaEquivalentType<T>::Type;
overflow_check(m, n, lda, ldb);
queue.submit([&](cl::sycl::handler &cgh) {
auto a_acc = a.template get_access<cl::sycl::access::mode::read>(cgh);
auto b_acc = b.template get_access<cl::sycl::access::mode::read_write>(cgh);
onemkl_cublas_host_task(cgh, queue, [=](CublasScopedContextHandler &sc) {
auto handle = sc.get_handle(queue);
auto a_ = sc.get_mem<cuDataType *>(a_acc);
auto b_ = sc.get_mem<cuDataType *>(b_acc);
cublasStatus_t err;
CUBLAS_ERROR_FUNC(func, err, handle, get_cublas_side_mode(left_right),
get_cublas_fill_mode(upper_lower), get_cublas_operation(trans),
get_cublas_diag_type(unit_diag), m, n, (cuDataType *)&alpha, a_, lda,
b_, ldb);
});
});
}
#define TRSM_LAUNCHER(TYPE, CUBLAS_ROUTINE) \
void trsm(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, \
diag unit_diag, int64_t m, int64_t n, TYPE alpha, cl::sycl::buffer<TYPE, 1> &a, \
int64_t lda, cl::sycl::buffer<TYPE, 1> &b, int64_t ldb) { \
trsm(CUBLAS_ROUTINE, queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, \
lda, b, ldb); \
}
TRSM_LAUNCHER(float, cublasStrsm)
TRSM_LAUNCHER(double, cublasDtrsm)
TRSM_LAUNCHER(std::complex<float>, cublasCtrsm)
TRSM_LAUNCHER(std::complex<double>, cublasZtrsm)
#undef TRSM_LAUNCHER
// USM APIs
template <typename Func, typename T>
inline cl::sycl::event gemm(Func func, cl::sycl::queue &queue, transpose transa, transpose transb,
int64_t m, int64_t n, int64_t k, T alpha, const T *a, int64_t lda,
const T *b, int64_t ldb, T beta, T *c, int64_t ldc,
const std::vector<cl::sycl::event> &dependencies) {
using cuDataType = typename CudaEquivalentType<T>::Type;
overflow_check(m, n, k, lda, ldb, ldc);
auto done = queue.submit([&](cl::sycl::handler &cgh) {
int64_t num_events = dependencies.size();
for (int64_t i = 0; i < num_events; i++) {
cgh.depends_on(dependencies[i]);
}
onemkl_cublas_host_task(cgh, queue, [=](CublasScopedContextHandler &sc) {
auto handle = sc.get_handle(queue);
auto a_ = reinterpret_cast<const cuDataType *>(a);
auto b_ = reinterpret_cast<const cuDataType *>(b);
auto c_ = reinterpret_cast<cuDataType *>(c);
cublasStatus_t err;
CUBLAS_ERROR_FUNC(func, err, handle, get_cublas_operation(transa),
get_cublas_operation(transb), m, n, k, (cuDataType *)&alpha, a_, lda,
b_, ldb, (cuDataType *)&beta, c_, ldc);
});
});
return done;
}
#define GEMM_LAUNCHER_USM(TYPE, CUBLAS_ROUTINE) \
cl::sycl::event gemm(cl::sycl::queue &queue, transpose transa, transpose transb, int64_t m, \
int64_t n, int64_t k, TYPE alpha, const TYPE *a, int64_t lda, \
const TYPE *b, int64_t ldb, TYPE beta, TYPE *c, int64_t ldc, \
const std::vector<cl::sycl::event> &dependencies) { \
return gemm(CUBLAS_ROUTINE, queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, \
c, ldc, dependencies); \
}
GEMM_LAUNCHER_USM(float, cublasSgemm)
GEMM_LAUNCHER_USM(double, cublasDgemm)
GEMM_LAUNCHER_USM(std::complex<float>, cublasCgemm)
GEMM_LAUNCHER_USM(std::complex<double>, cublasZgemm)
#undef GEMM_LAUNCHER_USM
template <typename T_A, typename T_B, typename T_C, typename DATATYPE_A, typename DATATYPE_B,
typename DATATYPE_C>
inline cl::sycl::event gemm_ex_usm(DATATYPE_A DT_A, DATATYPE_B DT_B, DATATYPE_C DT_C,
cl::sycl::queue &queue, transpose transa, transpose transb,
int64_t m, int64_t n, int64_t k, T_C alpha, const T_A *a,
int64_t lda, const T_B *b, int64_t ldb, T_C beta, T_C *c,
int64_t ldc, const std::vector<cl::sycl::event> &dependencies) {
using cuDataType_A = typename CudaEquivalentType<T_A>::Type;
using cuDataType_B = typename CudaEquivalentType<T_B>::Type;
using cuDataType_C = typename CudaEquivalentType<T_C>::Type;
overflow_check(m, n, k, lda, ldb, ldc);
auto done = queue.submit([&](cl::sycl::handler &cgh) {
int64_t num_events = dependencies.size();
for (int64_t i = 0; i < num_events; i++) {
cgh.depends_on(dependencies[i]);
}
onemkl_cublas_host_task(cgh, queue, [=](CublasScopedContextHandler &sc) {
auto handle = sc.get_handle(queue);
auto a_ = reinterpret_cast<const cuDataType_A *>(a);
auto b_ = reinterpret_cast<const cuDataType_B *>(b);
auto c_ = reinterpret_cast<cuDataType_C *>(c);
cublasStatus_t err;
CUBLAS_ERROR_FUNC(cublasGemmEx, err, handle, get_cublas_operation(transa),
get_cublas_operation(transb), m, n, k, (cuDataType_C *)&alpha, a_,
DT_A, lda, b_, DT_B, ldb, (cuDataType_C *)&beta, c_, DT_C, ldc, DT_C,
CUBLAS_GEMM_DEFAULT);
});
});
return done;
}
#define GEMM_EX_LAUNCHER_USM(TYPE_A, TYPE_B, TYPE_C, CUDADATATYPE_A, CUDADATATYPE_B, \
CUDADATATYPE_C) \
cl::sycl::event gemm(cl::sycl::queue &queue, transpose transa, transpose transb, int64_t m, \
int64_t n, int64_t k, TYPE_C alpha, const TYPE_A *a, int64_t lda, \
const TYPE_B *b, int64_t ldb, TYPE_C beta, TYPE_C *c, int64_t ldc, \
const std::vector<cl::sycl::event> &dependencies) { \
return gemm_ex_usm(CUDADATATYPE_A, CUDADATATYPE_B, CUDADATATYPE_C, queue, transa, transb, \
m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); \
}
GEMM_EX_LAUNCHER_USM(sycl::half, sycl::half, float, CUDA_R_16F, CUDA_R_16F, CUDA_R_32F)
GEMM_EX_LAUNCHER_USM(sycl::half, sycl::half, sycl::half, CUDA_R_16F, CUDA_R_16F, CUDA_R_16F)
#undef GEMM_EX_LAUNCHER_USM
cl::sycl::event gemm(cl::sycl::queue &queue, transpose transa, transpose transb, int64_t m,
int64_t n, int64_t k, float alpha, const bfloat16 *a, int64_t lda,
const bfloat16 *b, int64_t ldb, float beta, float *c, int64_t ldc,
const std::vector<cl::sycl::event> &dependencies) {
throw unimplemented("blas", "gemm", "for column_major layout");
}
template <typename Func, typename T>
inline cl::sycl::event symm(Func func, cl::sycl::queue &queue, side left_right, uplo upper_lower,
int64_t m, int64_t n, T alpha, const T *a, int64_t lda, const T *b,
int64_t ldb, T beta, T *c, int64_t ldc,
const std::vector<cl::sycl::event> &dependencies) {
using cuDataType = typename CudaEquivalentType<T>::Type;
overflow_check(m, n, lda, ldb, ldc);
auto done = queue.submit([&](cl::sycl::handler &cgh) {
int64_t num_events = dependencies.size();
for (int64_t i = 0; i < num_events; i++) {
cgh.depends_on(dependencies[i]);
}
onemkl_cublas_host_task(cgh, queue, [=](CublasScopedContextHandler &sc) {
auto handle = sc.get_handle(queue);
auto a_ = reinterpret_cast<const cuDataType *>(a);
auto b_ = reinterpret_cast<const cuDataType *>(b);
auto c_ = reinterpret_cast<cuDataType *>(c);
cublasStatus_t err;
CUBLAS_ERROR_FUNC(func, err, handle, get_cublas_side_mode(left_right),
get_cublas_fill_mode(upper_lower), m, n, (cuDataType *)&alpha, a_,
lda, b_, ldb, (cuDataType *)&beta, c_, ldc);
});
});
return done;
}
#define SYMM_LAUNCHER_USM(TYPE, CUBLAS_ROUTINE) \
cl::sycl::event symm(cl::sycl::queue &queue, side left_right, uplo upper_lower, int64_t m, \
int64_t n, TYPE alpha, const TYPE *a, int64_t lda, const TYPE *b, \
int64_t ldb, TYPE beta, TYPE *c, int64_t ldc, \
const std::vector<cl::sycl::event> &dependencies) { \
return symm(CUBLAS_ROUTINE, queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, \
beta, c, ldc, dependencies); \
}
SYMM_LAUNCHER_USM(float, cublasSsymm)
SYMM_LAUNCHER_USM(double, cublasDsymm)
SYMM_LAUNCHER_USM(std::complex<float>, cublasCsymm)
SYMM_LAUNCHER_USM(std::complex<double>, cublasZsymm)
#undef SYMM_LAUNCHER_USM
template <typename Func, typename T>
inline cl::sycl::event hemm(Func func, cl::sycl::queue &queue, side left_right, uplo upper_lower,
int64_t m, int64_t n, T alpha, const T *a, int64_t lda, const T *b,
int64_t ldb, T beta, T *c, int64_t ldc,
const std::vector<cl::sycl::event> &dependencies) {
using cuDataType = typename CudaEquivalentType<T>::Type;
overflow_check(m, n, lda, ldb, ldc);
auto done = queue.submit([&](cl::sycl::handler &cgh) {
int64_t num_events = dependencies.size();
for (int64_t i = 0; i < num_events; i++) {
cgh.depends_on(dependencies[i]);
}
onemkl_cublas_host_task(cgh, queue, [=](CublasScopedContextHandler &sc) {
auto handle = sc.get_handle(queue);
auto a_ = reinterpret_cast<const cuDataType *>(a);
auto b_ = reinterpret_cast<const cuDataType *>(b);
auto c_ = reinterpret_cast<cuDataType *>(c);
cublasStatus_t err;
CUBLAS_ERROR_FUNC(func, err, handle, get_cublas_side_mode(left_right),
get_cublas_fill_mode(upper_lower), m, n, (cuDataType *)&alpha, a_,
lda, b_, ldb, (cuDataType *)&beta, c_, ldc);
});
});
return done;
}
#define HEMM_LAUNCHER_USM(TYPE, CUBLAS_ROUTINE) \
cl::sycl::event hemm(cl::sycl::queue &queue, side left_right, uplo upper_lower, int64_t m, \
int64_t n, TYPE alpha, const TYPE *a, int64_t lda, const TYPE *b, \
int64_t ldb, TYPE beta, TYPE *c, int64_t ldc, \
const std::vector<cl::sycl::event> &dependencies) { \
return hemm(CUBLAS_ROUTINE, queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, \
beta, c, ldc, dependencies); \
}
HEMM_LAUNCHER_USM(std::complex<float>, cublasChemm)
HEMM_LAUNCHER_USM(std::complex<double>, cublasZhemm)
#undef HEMM_LAUNCHER_USM
template <typename Func, typename T>
inline cl::sycl::event syrk(Func func, cl::sycl::queue &queue, uplo upper_lower, transpose trans,
int64_t n, int64_t k, T alpha, const T *a, int64_t lda, T beta, T *c,
int64_t ldc, const std::vector<cl::sycl::event> &dependencies) {
using cuDataType = typename CudaEquivalentType<T>::Type;
overflow_check(n, k, lda, ldc);
auto done = queue.submit([&](cl::sycl::handler &cgh) {
int64_t num_events = dependencies.size();
for (int64_t i = 0; i < num_events; i++) {
cgh.depends_on(dependencies[i]);
}
onemkl_cublas_host_task(cgh, queue, [=](CublasScopedContextHandler &sc) {
auto handle = sc.get_handle(queue);
auto a_ = reinterpret_cast<const cuDataType *>(a);
auto c_ = reinterpret_cast<cuDataType *>(c);
cublasStatus_t err;
CUBLAS_ERROR_FUNC(func, err, handle, get_cublas_fill_mode(upper_lower),
get_cublas_operation(trans), n, k, (cuDataType *)&alpha, a_, lda,
(cuDataType *)&beta, c_, ldc);
});
});
return done;
}
#define SYRK_LAUNCHER_USM(TYPE, CUBLAS_ROUTINE) \
cl::sycl::event syrk(cl::sycl::queue &queue, uplo upper_lower, transpose trans, int64_t n, \
int64_t k, TYPE alpha, const TYPE *a, int64_t lda, TYPE beta, TYPE *c, \
int64_t ldc, const std::vector<cl::sycl::event> &dependencies) { \
return syrk(CUBLAS_ROUTINE, queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, \
dependencies); \
}
SYRK_LAUNCHER_USM(float, cublasSsyrk)
SYRK_LAUNCHER_USM(double, cublasDsyrk)
SYRK_LAUNCHER_USM(std::complex<float>, cublasCsyrk)
SYRK_LAUNCHER_USM(std::complex<double>, cublasZsyrk)
#undef SYRK_LAUNCHER_USM
template <typename Func, typename DataType, typename ScalarType>
inline cl::sycl::event herk(Func func, cl::sycl::queue &queue, uplo upper_lower, transpose trans,
int64_t n, int64_t k, const ScalarType alpha, const DataType *a,
int64_t lda, const ScalarType beta, DataType *c, int64_t ldc,
const std::vector<cl::sycl::event> &dependencies) {
using cuDataType = typename CudaEquivalentType<DataType>::Type;
using cuScalarType = typename CudaEquivalentType<ScalarType>::Type;
overflow_check(n, k, lda, ldc);
auto done = queue.submit([&](cl::sycl::handler &cgh) {
int64_t num_events = dependencies.size();
for (int64_t i = 0; i < num_events; i++) {
cgh.depends_on(dependencies[i]);
}
onemkl_cublas_host_task(cgh, queue, [=](CublasScopedContextHandler &sc) {
auto handle = sc.get_handle(queue);
auto a_ = reinterpret_cast<const cuDataType *>(a);
auto c_ = reinterpret_cast<cuDataType *>(c);
cublasStatus_t err;
CUBLAS_ERROR_FUNC(func, err, handle, get_cublas_fill_mode(upper_lower),
get_cublas_operation(trans), n, k, (cuScalarType *)&alpha, a_, lda,
(cuScalarType *)&beta, c_, ldc);
});
});
return done;
}
#define HERK_LAUNCHER_USM(DATA_TYPE, SCALAR_TYPE, CUBLAS_ROUTINE) \
cl::sycl::event herk(cl::sycl::queue &queue, uplo upper_lower, transpose trans, int64_t n, \
int64_t k, const SCALAR_TYPE alpha, const DATA_TYPE *a, int64_t lda, \
const SCALAR_TYPE beta, DATA_TYPE *c, int64_t ldc, \
const std::vector<cl::sycl::event> &dependencies) { \
return herk(CUBLAS_ROUTINE, queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, \
dependencies); \
}
HERK_LAUNCHER_USM(std::complex<float>, float, cublasCherk)
HERK_LAUNCHER_USM(std::complex<double>, double, cublasZherk)
#undef HERK_LAUNCHER_USM
template <typename Func, typename T>
inline cl::sycl::event syr2k(Func func, cl::sycl::queue &queue, uplo upper_lower, transpose trans,
int64_t n, int64_t k, T alpha, const T *a, int64_t lda, const T *b,
int64_t ldb, T beta, T *c, int64_t ldc,
const std::vector<cl::sycl::event> &dependencies) {
using cuDataType = typename CudaEquivalentType<T>::Type;
overflow_check(n, k, lda, ldb, ldc);
auto done = queue.submit([&](cl::sycl::handler &cgh) {
int64_t num_events = dependencies.size();
for (int64_t i = 0; i < num_events; i++) {
cgh.depends_on(dependencies[i]);
}
onemkl_cublas_host_task(cgh, queue, [=](CublasScopedContextHandler &sc) {
auto handle = sc.get_handle(queue);
auto a_ = reinterpret_cast<const cuDataType *>(a);
auto b_ = reinterpret_cast<const cuDataType *>(b);
auto c_ = reinterpret_cast<cuDataType *>(c);
cublasStatus_t err;
CUBLAS_ERROR_FUNC(func, err, handle, get_cublas_fill_mode(upper_lower),
get_cublas_operation(trans), n, k, (cuDataType *)&alpha, a_, lda, b_,
ldb, (cuDataType *)&beta, c_, ldc);
});
});
return done;
}
#define SYR2K_LAUNCHER_USM(TYPE, CUBLAS_ROUTINE) \
cl::sycl::event syr2k(cl::sycl::queue &queue, uplo upper_lower, transpose trans, int64_t n, \
int64_t k, TYPE alpha, const TYPE *a, int64_t lda, const TYPE *b, \
int64_t ldb, TYPE beta, TYPE *c, int64_t ldc, \
const std::vector<cl::sycl::event> &dependencies) { \
return syr2k(CUBLAS_ROUTINE, queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, \
c, ldc, dependencies); \
}
SYR2K_LAUNCHER_USM(float, cublasSsyr2k)
SYR2K_LAUNCHER_USM(double, cublasDsyr2k)
SYR2K_LAUNCHER_USM(std::complex<float>, cublasCsyr2k)
SYR2K_LAUNCHER_USM(std::complex<double>, cublasZsyr2k)
#undef SYR2K_LAUNCHER_USM
template <typename Func, typename DataType, typename ScalarType>
inline cl::sycl::event her2k(Func func, cl::sycl::queue &queue, uplo upper_lower, transpose trans,
int64_t n, int64_t k, const DataType alpha, const DataType *a,
int64_t lda, const DataType *b, int64_t ldb, const ScalarType beta,
DataType *c, int64_t ldc,
const std::vector<cl::sycl::event> &dependencies) {
using cuDataType = typename CudaEquivalentType<DataType>::Type;
using cuScalarType = typename CudaEquivalentType<ScalarType>::Type;
overflow_check(n, k, lda, ldb, ldc);
auto done = queue.submit([&](cl::sycl::handler &cgh) {
int64_t num_events = dependencies.size();
for (int64_t i = 0; i < num_events; i++) {
cgh.depends_on(dependencies[i]);
}
onemkl_cublas_host_task(cgh, queue, [=](CublasScopedContextHandler &sc) {
auto handle = sc.get_handle(queue);
auto a_ = reinterpret_cast<const cuDataType *>(a);
auto b_ = reinterpret_cast<const cuDataType *>(b);
auto c_ = reinterpret_cast<cuDataType *>(c);
cublasStatus_t err;
CUBLAS_ERROR_FUNC(func, err, handle, get_cublas_fill_mode(upper_lower),
get_cublas_operation(trans), n, k, (cuDataType *)&alpha, a_, lda, b_,
ldb, (cuScalarType *)&beta, c_, ldc);
});
});
return done;
}
#define HER2K_LAUNCHER_USM(DATA_TYPE, SCALAR_TYPE, CUBLAS_ROUTINE) \
cl::sycl::event her2k(cl::sycl::queue &queue, uplo upper_lower, transpose trans, int64_t n, \
int64_t k, const DATA_TYPE alpha, const DATA_TYPE *a, int64_t lda, \
const DATA_TYPE *b, int64_t ldb, const SCALAR_TYPE beta, DATA_TYPE *c, \
int64_t ldc, const std::vector<cl::sycl::event> &dependencies) { \
return her2k(CUBLAS_ROUTINE, queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, \
c, ldc, dependencies); \
}
HER2K_LAUNCHER_USM(std::complex<float>, float, cublasCher2k)
HER2K_LAUNCHER_USM(std::complex<double>, double, cublasZher2k)
#undef HER2K_LAUNCHER_USM
// NOTE: In cublas TRMM diverted from the netlib blas and for performance
// reason it requires the C matrix to be
// separated from the B matrix. It is possible to use B instead of C, but this
// will slow-down the code.
template <typename Func, typename T>
inline cl::sycl::event trmm(Func func, cl::sycl::queue &queue, side left_right, uplo upper_lower,
transpose trans, diag unit_diag, int64_t m, int64_t n, T alpha,
const T *a, int64_t lda, T *b, int64_t ldb,
const std::vector<cl::sycl::event> &dependencies) {
using cuDataType = typename CudaEquivalentType<T>::Type;
overflow_check(m, n, lda, ldb);
auto done = queue.submit([&](cl::sycl::handler &cgh) {
int64_t num_events = dependencies.size();
for (int64_t i = 0; i < num_events; i++) {
cgh.depends_on(dependencies[i]);
}
onemkl_cublas_host_task(cgh, queue, [=](CublasScopedContextHandler &sc) {
auto handle = sc.get_handle(queue);
auto a_ = reinterpret_cast<const cuDataType *>(a);
auto b_ = reinterpret_cast<cuDataType *>(b);
cublasStatus_t err;
CUBLAS_ERROR_FUNC(func, err, handle, get_cublas_side_mode(left_right),
get_cublas_fill_mode(upper_lower), get_cublas_operation(trans),
get_cublas_diag_type(unit_diag), m, n, (cuDataType *)&alpha, a_, lda,
b_, ldb, b_, ldb);
});
});
return done;
}
#define TRMM_LAUNCHER_USM(TYPE, CUBLAS_ROUTINE) \
cl::sycl::event trmm(cl::sycl::queue &queue, side left_right, uplo upper_lower, \
transpose trans, diag unit_diag, int64_t m, int64_t n, TYPE alpha, \
const TYPE *a, int64_t lda, TYPE *b, int64_t ldb, \
const std::vector<cl::sycl::event> &dependencies) { \
return trmm(CUBLAS_ROUTINE, queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, \
a, lda, b, ldb, dependencies); \
}
TRMM_LAUNCHER_USM(float, cublasStrmm)
TRMM_LAUNCHER_USM(double, cublasDtrmm)
TRMM_LAUNCHER_USM(std::complex<float>, cublasCtrmm)
TRMM_LAUNCHER_USM(std::complex<double>, cublasZtrmm)
#undef TRMM_LAUNCHER_USM
template <typename Func, typename T>
inline cl::sycl::event trsm(Func func, cl::sycl::queue &queue, side left_right, uplo upper_lower,
transpose trans, diag unit_diag, int64_t m, int64_t n, T alpha,
const T *a, int64_t lda, T *b, int64_t ldb,
const std::vector<cl::sycl::event> &dependencies) {
using cuDataType = typename CudaEquivalentType<T>::Type;
overflow_check(m, n, lda, ldb);
auto done = queue.submit([&](cl::sycl::handler &cgh) {
int64_t num_events = dependencies.size();
for (int64_t i = 0; i < num_events; i++) {
cgh.depends_on(dependencies[i]);
}
onemkl_cublas_host_task(cgh, queue, [=](CublasScopedContextHandler &sc) {
auto handle = sc.get_handle(queue);
auto a_ = reinterpret_cast<const cuDataType *>(a);
auto b_ = reinterpret_cast<cuDataType *>(b);
cublasStatus_t err;
CUBLAS_ERROR_FUNC(func, err, handle, get_cublas_side_mode(left_right),
get_cublas_fill_mode(upper_lower), get_cublas_operation(trans),
get_cublas_diag_type(unit_diag), m, n, (cuDataType *)&alpha, a_, lda,
b_, ldb);
});
});
return done;
}
#define TRSM_LAUNCHER_USM(TYPE, CUBLAS_ROUTINE) \
cl::sycl::event trsm(cl::sycl::queue &queue, side left_right, uplo upper_lower, \
transpose trans, diag unit_diag, int64_t m, int64_t n, TYPE alpha, \
const TYPE *a, int64_t lda, TYPE *b, int64_t ldb, \
const std::vector<cl::sycl::event> &dependencies) { \
return trsm(CUBLAS_ROUTINE, queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, \
a, lda, b, ldb, dependencies); \
}
TRSM_LAUNCHER_USM(float, cublasStrsm)
TRSM_LAUNCHER_USM(double, cublasDtrsm)
TRSM_LAUNCHER_USM(std::complex<float>, cublasCtrsm)
TRSM_LAUNCHER_USM(std::complex<double>, cublasZtrsm)
#undef TRSM_LAUNCHER_USM
} // namespace column_major
namespace row_major {
// Buffer APIs
template <typename Func, typename T>
inline void gemm(Func func, cl::sycl::queue &queue, transpose transa, transpose transb, int64_t m,
int64_t n, int64_t k, T alpha, cl::sycl::buffer<T, 1> &a, int64_t lda,
cl::sycl::buffer<T, 1> &b, int64_t ldb, T beta, cl::sycl::buffer<T, 1> &c,
int64_t ldc) {
throw unimplemented("blas", "gemm", "for row_major layout");
}
#define GEMM_LAUNCHER(TYPE, CUBLAS_ROUTINE) \
void gemm(cl::sycl::queue &queue, transpose transa, transpose transb, int64_t m, int64_t n, \
int64_t k, TYPE alpha, cl::sycl::buffer<TYPE, 1> &a, int64_t lda, \
cl::sycl::buffer<TYPE, 1> &b, int64_t ldb, TYPE beta, cl::sycl::buffer<TYPE, 1> &c, \
int64_t ldc) { \
gemm(CUBLAS_ROUTINE, queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); \
}
GEMM_LAUNCHER(float, cublasSgemm)
GEMM_LAUNCHER(double, cublasDgemm)
GEMM_LAUNCHER(std::complex<float>, cublasCgemm)
GEMM_LAUNCHER(std::complex<double>, cublasZgemm)
#undef GEMM_LAUNCHER
template <typename T_A, typename T_B, typename T_C, typename DATATYPE_A, typename DATATYPE_B,
typename DATATYPE_C>
inline void gemm_ex(DATATYPE_A DT_A, DATATYPE_B DT_B, DATATYPE_C DT_C, cl::sycl::queue &queue,
transpose transa, transpose transb, int64_t m, int64_t n, int64_t k, T_C alpha,
cl::sycl::buffer<T_A, 1> &a, int64_t lda, cl::sycl::buffer<T_B, 1> &b,
int64_t ldb, T_C beta, cl::sycl::buffer<T_C, 1> &c, int64_t ldc) {
throw unimplemented("blas", "gemm", "for row_major layout");
}
#define GEMM_EX_LAUNCHER(TYPE_A, TYPE_B, TYPE_C, CUDADATATYPE_A, CUDADATATYPE_B, CUDADATATYPE_C) \
void gemm(cl::sycl::queue &queue, transpose transa, transpose transb, int64_t m, int64_t n, \
int64_t k, TYPE_C alpha, cl::sycl::buffer<TYPE_A, 1> &a, int64_t lda, \
cl::sycl::buffer<TYPE_B, 1> &b, int64_t ldb, TYPE_C beta, \
cl::sycl::buffer<TYPE_C, 1> &c, int64_t ldc) { \
gemm_ex(CUDADATATYPE_A, CUDADATATYPE_B, CUDADATATYPE_C, queue, transa, transb, m, n, k, \
alpha, a, lda, b, ldb, beta, c, ldc); \
}
GEMM_EX_LAUNCHER(sycl::half, sycl::half, float, CUDA_R_16F, CUDA_R_16F, CUDA_R_32F)
GEMM_EX_LAUNCHER(sycl::half, sycl::half, sycl::half, CUDA_R_16F, CUDA_R_16F, CUDA_R_16F)
#undef GEMM_EX_LAUNCHER
void gemm(cl::sycl::queue &queue, transpose transa, transpose transb, int64_t m, int64_t n,
int64_t k, float alpha, cl::sycl::buffer<bfloat16, 1> &a, int64_t lda,
cl::sycl::buffer<bfloat16, 1> &b, int64_t ldb, float beta, cl::sycl::buffer<float, 1> &c,
int64_t ldc) {
throw unimplemented("blas", "gemm", "for row_major layout");
}
template <typename Func, typename T>
inline void symm(Func func, cl::sycl::queue &queue, side left_right, uplo upper_lower, int64_t m,
int64_t n, T alpha, cl::sycl::buffer<T, 1> &a, int64_t lda,
cl::sycl::buffer<T, 1> &b, int64_t ldb, T beta, cl::sycl::buffer<T, 1> &c,
int64_t ldc) {
throw unimplemented("blas", "symm", "for row_major layout");
}
#define SYMM_LAUNCHER(TYPE, CUBLAS_ROUTINE) \
void symm(cl::sycl::queue &queue, side left_right, uplo upper_lower, int64_t m, int64_t n, \
TYPE alpha, cl::sycl::buffer<TYPE, 1> &a, int64_t lda, cl::sycl::buffer<TYPE, 1> &b, \
int64_t ldb, TYPE beta, cl::sycl::buffer<TYPE, 1> &c, int64_t ldc) { \
symm(CUBLAS_ROUTINE, queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, \
ldc); \
}
SYMM_LAUNCHER(float, cublasSsymm)
SYMM_LAUNCHER(double, cublasDsymm)
SYMM_LAUNCHER(std::complex<float>, cublasCsymm)
SYMM_LAUNCHER(std::complex<double>, cublasZsymm)
#undef SYMM_LAUNCHER
template <typename Func, typename T>
inline void hemm(Func func, cl::sycl::queue &queue, side left_right, uplo upper_lower, int64_t m,
int64_t n, T alpha, cl::sycl::buffer<T, 1> &a, int64_t lda,
cl::sycl::buffer<T, 1> &b, int64_t ldb, T beta, cl::sycl::buffer<T, 1> &c,
int64_t ldc) {
throw unimplemented("blas", "hemm", "for row_major layout");
}
#define HEMM_LAUNCHER(TYPE, CUBLAS_ROUTINE) \
void hemm(cl::sycl::queue &queue, side left_right, uplo upper_lower, int64_t m, int64_t n, \
TYPE alpha, cl::sycl::buffer<TYPE, 1> &a, int64_t lda, cl::sycl::buffer<TYPE, 1> &b, \
int64_t ldb, TYPE beta, cl::sycl::buffer<TYPE, 1> &c, int64_t ldc) { \
hemm(CUBLAS_ROUTINE, queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, \
ldc); \
}
HEMM_LAUNCHER(std::complex<float>, cublasChemm)
HEMM_LAUNCHER(std::complex<double>, cublasZhemm)
#undef HEMM_LAUNCHER
template <typename Func, typename T>
inline void syrk(Func func, cl::sycl::queue &queue, uplo upper_lower, transpose trans, int64_t n,
int64_t k, T alpha, cl::sycl::buffer<T, 1> &a, int64_t lda, T beta,
cl::sycl::buffer<T, 1> &c, int64_t ldc) {
throw unimplemented("blas", "syrk", "for row_major layout");
}
#define SYRK_LAUNCHER(TYPE, CUBLAS_ROUTINE) \
void syrk(cl::sycl::queue &queue, uplo upper_lower, transpose trans, int64_t n, int64_t k, \
TYPE alpha, cl::sycl::buffer<TYPE, 1> &a, int64_t lda, TYPE beta, \
cl::sycl::buffer<TYPE, 1> &c, int64_t ldc) { \
syrk(CUBLAS_ROUTINE, queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc); \
}
SYRK_LAUNCHER(float, cublasSsyrk)
SYRK_LAUNCHER(double, cublasDsyrk)
SYRK_LAUNCHER(std::complex<float>, cublasCsyrk)
SYRK_LAUNCHER(std::complex<double>, cublasZsyrk)
#undef SYRK_LAUNCHER
template <typename Func, typename DataType, typename ScalarType>
inline void herk(Func func, cl::sycl::queue &queue, uplo upper_lower, transpose trans, int64_t n,
int64_t k, ScalarType alpha, cl::sycl::buffer<DataType, 1> &a, int64_t lda,
ScalarType beta, cl::sycl::buffer<DataType, 1> &c, int64_t ldc) {
throw unimplemented("blas", "herk", "for row_major layout");
}
#define HERK_LAUNCHER(DATA_TYPE, SCALAR_TYPE, CUBLAS_ROUTINE) \
void herk(cl::sycl::queue &queue, uplo upper_lower, transpose trans, int64_t n, int64_t k, \
SCALAR_TYPE alpha, cl::sycl::buffer<DATA_TYPE, 1> &a, int64_t lda, SCALAR_TYPE beta, \
cl::sycl::buffer<DATA_TYPE, 1> &c, int64_t ldc) { \
herk(CUBLAS_ROUTINE, queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc); \
}
HERK_LAUNCHER(std::complex<float>, float, cublasCherk)
HERK_LAUNCHER(std::complex<double>, double, cublasZherk)
#undef HERK_LAUNCHER
template <typename Func, typename T>
inline void syr2k(Func func, cl::sycl::queue &queue, uplo upper_lower, transpose trans, int64_t n,
int64_t k, T alpha, cl::sycl::buffer<T, 1> &a, int64_t lda,
cl::sycl::buffer<T, 1> &b, int64_t ldb, T beta, cl::sycl::buffer<T, 1> &c,
int64_t ldc) {
throw unimplemented("blas", "syr2k", "for row_major layout");
}
#define SYR2K_LAUNCHER(TYPE, CUBLAS_ROUTINE) \
void syr2k(cl::sycl::queue &queue, uplo upper_lower, transpose trans, int64_t n, int64_t k, \
TYPE alpha, cl::sycl::buffer<TYPE, 1> &a, int64_t lda, \
cl::sycl::buffer<TYPE, 1> &b, int64_t ldb, TYPE beta, cl::sycl::buffer<TYPE, 1> &c, \
int64_t ldc) { \
syr2k(CUBLAS_ROUTINE, queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, \
ldc); \
}
SYR2K_LAUNCHER(float, cublasSsyr2k)
SYR2K_LAUNCHER(double, cublasDsyr2k)
SYR2K_LAUNCHER(std::complex<float>, cublasCsyr2k)
SYR2K_LAUNCHER(std::complex<double>, cublasZsyr2k)
#undef SYR2K_LAUNCHER
template <typename Func, typename DataType, typename ScalarType>
inline void her2k(Func func, cl::sycl::queue &queue, uplo upper_lower, transpose trans, int64_t n,
int64_t k, DataType alpha, cl::sycl::buffer<DataType, 1> &a, int64_t lda,
cl::sycl::buffer<DataType, 1> &b, int64_t ldb, ScalarType beta,
cl::sycl::buffer<DataType, 1> &c, int64_t ldc) {
throw unimplemented("blas", "her2k", "for row_major layout");
}
#define HER2K_LAUNCHER(DATA_TYPE, SCALAR_TYPE, CUBLAS_ROUTINE) \
void her2k(cl::sycl::queue &queue, uplo upper_lower, transpose trans, int64_t n, int64_t k, \
DATA_TYPE alpha, cl::sycl::buffer<DATA_TYPE, 1> &a, int64_t lda, \
cl::sycl::buffer<DATA_TYPE, 1> &b, int64_t ldb, SCALAR_TYPE beta, \
cl::sycl::buffer<DATA_TYPE, 1> &c, int64_t ldc) { \
her2k(CUBLAS_ROUTINE, queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, \
ldc); \
}
HER2K_LAUNCHER(std::complex<float>, float, cublasCher2k)
HER2K_LAUNCHER(std::complex<double>, double, cublasZher2k)
#undef HER2K_LAUNCHER
// NOTE: In cublas TRMM diverted from the netlib blas and for performance
// reason it requires the C matrix to be
// separated from the B matrix. It is possible to use B instead of C, but this
// will slow-down the code.
template <typename Func, typename T>
inline void trmm(Func func, cl::sycl::queue &queue, side left_right, uplo upper_lower,
transpose trans, diag unit_diag, int64_t m, int64_t n, T alpha,
cl::sycl::buffer<T, 1> &a, int64_t lda, cl::sycl::buffer<T, 1> &b, int64_t ldb) {
throw unimplemented("blas", "trmm", "for row_major layout");
}
#define TRMM_LAUNCHER(TYPE, CUBLAS_ROUTINE) \
void trmm(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, \
diag unit_diag, int64_t m, int64_t n, TYPE alpha, cl::sycl::buffer<TYPE, 1> &a, \
int64_t lda, cl::sycl::buffer<TYPE, 1> &b, int64_t ldb) { \
trmm(CUBLAS_ROUTINE, queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, \
lda, b, ldb); \
}
TRMM_LAUNCHER(float, cublasStrmm)
TRMM_LAUNCHER(double, cublasDtrmm)
TRMM_LAUNCHER(std::complex<float>, cublasCtrmm)
TRMM_LAUNCHER(std::complex<double>, cublasZtrmm)
#undef TRMM_LAUNCHER
template <typename Func, typename T>
inline void trsm(Func func, cl::sycl::queue &queue, side left_right, uplo upper_lower,
transpose trans, diag unit_diag, int64_t m, int64_t n, T alpha,
cl::sycl::buffer<T, 1> &a, int64_t lda, cl::sycl::buffer<T, 1> &b, int64_t ldb) {
throw unimplemented("blas", "trsm", "for row_major layout");
}
#define TRSM_LAUNCHER(TYPE, CUBLAS_ROUTINE) \
void trsm(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, \
diag unit_diag, int64_t m, int64_t n, TYPE alpha, cl::sycl::buffer<TYPE, 1> &a, \
int64_t lda, cl::sycl::buffer<TYPE, 1> &b, int64_t ldb) { \
trsm(CUBLAS_ROUTINE, queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, \
lda, b, ldb); \
}
TRSM_LAUNCHER(float, cublasStrsm)
TRSM_LAUNCHER(double, cublasDtrsm)
TRSM_LAUNCHER(std::complex<float>, cublasCtrsm)
TRSM_LAUNCHER(std::complex<double>, cublasZtrsm)
#undef TRSM_LAUNCHER
// USM APIs
template <typename Func, typename T>
inline cl::sycl::event gemm(Func func, cl::sycl::queue &queue, transpose transa, transpose transb,
int64_t m, int64_t n, int64_t k, T alpha, const T *a, int64_t lda,
const T *b, int64_t ldb, T beta, T *c, int64_t ldc,
const std::vector<cl::sycl::event> &dependencies) {
throw unimplemented("blas", "gemm", "for row_major layout");
}
#define GEMM_LAUNCHER_USM(TYPE, CUBLAS_ROUTINE) \
cl::sycl::event gemm(cl::sycl::queue &queue, transpose transa, transpose transb, int64_t m, \
int64_t n, int64_t k, TYPE alpha, const TYPE *a, int64_t lda, \
const TYPE *b, int64_t ldb, TYPE beta, TYPE *c, int64_t ldc, \
const std::vector<cl::sycl::event> &dependencies) { \
return gemm(CUBLAS_ROUTINE, queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, \
c, ldc, dependencies); \
}
GEMM_LAUNCHER_USM(float, cublasSgemm)
GEMM_LAUNCHER_USM(double, cublasDgemm)
GEMM_LAUNCHER_USM(std::complex<float>, cublasCgemm)
GEMM_LAUNCHER_USM(std::complex<double>, cublasZgemm)
#undef GEMM_LAUNCHER_USM
template <typename T_A, typename T_B, typename T_C, typename DATATYPE_A, typename DATATYPE_B,
typename DATATYPE_C>
inline cl::sycl::event gemm_ex_usm(DATATYPE_A DT_A, DATATYPE_B DT_B, DATATYPE_C DT_C,
cl::sycl::queue &queue, transpose transa, transpose transb,
int64_t m, int64_t n, int64_t k, T_C alpha, const T_A *a,
int64_t lda, const T_B *b, int64_t ldb, T_C beta, T_C *c,
int64_t ldc, const std::vector<cl::sycl::event> &dependencies) {
throw unimplemented("blas", "gemm", "for row_major layout");
}
#define GEMM_EX_LAUNCHER_USM(TYPE_A, TYPE_B, TYPE_C, CUDADATATYPE_A, CUDADATATYPE_B, \
CUDADATATYPE_C) \
cl::sycl::event gemm(cl::sycl::queue &queue, transpose transa, transpose transb, int64_t m, \
int64_t n, int64_t k, TYPE_C alpha, const TYPE_A *a, int64_t lda, \
const TYPE_B *b, int64_t ldb, TYPE_C beta, TYPE_C *c, int64_t ldc, \
const std::vector<cl::sycl::event> &dependencies) { \
return gemm_ex_usm(CUDADATATYPE_A, CUDADATATYPE_B, CUDADATATYPE_C, queue, transa, transb, \
m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); \
}
GEMM_EX_LAUNCHER_USM(sycl::half, sycl::half, float, CUDA_R_16F, CUDA_R_16F, CUDA_R_32F)
GEMM_EX_LAUNCHER_USM(sycl::half, sycl::half, sycl::half, CUDA_R_16F, CUDA_R_16F, CUDA_R_16F)
#undef GEMM_EX_LAUNCHER_USM
cl::sycl::event gemm(cl::sycl::queue &queue, transpose transa, transpose transb, int64_t m,
int64_t n, int64_t k, float alpha, const bfloat16 *a, int64_t lda,
const bfloat16 *b, int64_t ldb, float beta, float *c, int64_t ldc,
const std::vector<cl::sycl::event> &dependencies) {
throw unimplemented("blas", "gemm", "for row_major layout");
}
template <typename Func, typename T>
inline cl::sycl::event symm(Func func, cl::sycl::queue &queue, side left_right, uplo upper_lower,
int64_t m, int64_t n, T alpha, const T *a, int64_t lda, const T *b,
int64_t ldb, T beta, T *c, int64_t ldc,
const std::vector<cl::sycl::event> &dependencies) {
throw unimplemented("blas", "symm", "for row_major layout");
}
#define SYMM_LAUNCHER_USM(TYPE, CUBLAS_ROUTINE) \
cl::sycl::event symm(cl::sycl::queue &queue, side left_right, uplo upper_lower, int64_t m, \
int64_t n, TYPE alpha, const TYPE *a, int64_t lda, const TYPE *b, \
int64_t ldb, TYPE beta, TYPE *c, int64_t ldc, \
const std::vector<cl::sycl::event> &dependencies) { \
return symm(CUBLAS_ROUTINE, queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, \
beta, c, ldc, dependencies); \
}
SYMM_LAUNCHER_USM(float, cublasSsymm)
SYMM_LAUNCHER_USM(double, cublasDsymm)
SYMM_LAUNCHER_USM(std::complex<float>, cublasCsymm)
SYMM_LAUNCHER_USM(std::complex<double>, cublasZsymm)
#undef SYMM_LAUNCHER_USM
template <typename Func, typename T>
inline cl::sycl::event hemm(Func func, cl::sycl::queue &queue, side left_right, uplo upper_lower,
int64_t m, int64_t n, T alpha, const T *a, int64_t lda, const T *b,
int64_t ldb, T beta, T *c, int64_t ldc,
const std::vector<cl::sycl::event> &dependencies) {
throw unimplemented("blas", "hemm", "for row_major layout");
}
#define HEMM_LAUNCHER_USM(TYPE, CUBLAS_ROUTINE) \
cl::sycl::event hemm(cl::sycl::queue &queue, side left_right, uplo upper_lower, int64_t m, \
int64_t n, TYPE alpha, const TYPE *a, int64_t lda, const TYPE *b, \
int64_t ldb, TYPE beta, TYPE *c, int64_t ldc, \
const std::vector<cl::sycl::event> &dependencies) { \
return hemm(CUBLAS_ROUTINE, queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, \
beta, c, ldc, dependencies); \
}
HEMM_LAUNCHER_USM(std::complex<float>, cublasChemm)
HEMM_LAUNCHER_USM(std::complex<double>, cublasZhemm)
#undef HEMM_LAUNCHER_USM
template <typename Func, typename T>
inline cl::sycl::event syrk(Func func, cl::sycl::queue &queue, uplo upper_lower, transpose trans,
int64_t n, int64_t k, T alpha, const T *a, int64_t lda, T beta, T *c,
int64_t ldc, const std::vector<cl::sycl::event> &dependencies) {
throw unimplemented("blas", "syrk", "for row_major layout");
}
#define SYRK_LAUNCHER_USM(TYPE, CUBLAS_ROUTINE) \
cl::sycl::event syrk(cl::sycl::queue &queue, uplo upper_lower, transpose trans, int64_t n, \
int64_t k, TYPE alpha, const TYPE *a, int64_t lda, TYPE beta, TYPE *c, \
int64_t ldc, const std::vector<cl::sycl::event> &dependencies) { \
return syrk(CUBLAS_ROUTINE, queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, \
dependencies); \
}
SYRK_LAUNCHER_USM(float, cublasSsyrk)
SYRK_LAUNCHER_USM(double, cublasDsyrk)
SYRK_LAUNCHER_USM(std::complex<float>, cublasCsyrk)
SYRK_LAUNCHER_USM(std::complex<double>, cublasZsyrk)
#undef SYRK_LAUNCHER_USM
template <typename Func, typename DataType, typename ScalarType>
inline cl::sycl::event herk(Func func, cl::sycl::queue &queue, uplo upper_lower, transpose trans,
int64_t n, int64_t k, const ScalarType alpha, const DataType *a,
int64_t lda, const ScalarType beta, DataType *c, int64_t ldc,
const std::vector<cl::sycl::event> &dependencies) {
throw unimplemented("blas", "herk", "for row_major layout");
}
#define HERK_LAUNCHER_USM(DATA_TYPE, SCALAR_TYPE, CUBLAS_ROUTINE) \
cl::sycl::event herk(cl::sycl::queue &queue, uplo upper_lower, transpose trans, int64_t n, \
int64_t k, const SCALAR_TYPE alpha, const DATA_TYPE *a, int64_t lda, \
const SCALAR_TYPE beta, DATA_TYPE *c, int64_t ldc, \
const std::vector<cl::sycl::event> &dependencies) { \
return herk(CUBLAS_ROUTINE, queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, \
dependencies); \
}
HERK_LAUNCHER_USM(std::complex<float>, float, cublasCherk)
HERK_LAUNCHER_USM(std::complex<double>, double, cublasZherk)
#undef HERK_LAUNCHER_USM
template <typename Func, typename T>
inline cl::sycl::event syr2k(Func func, cl::sycl::queue &queue, uplo upper_lower, transpose trans,
int64_t n, int64_t k, T alpha, const T *a, int64_t lda, const T *b,
int64_t ldb, T beta, T *c, int64_t ldc,
const std::vector<cl::sycl::event> &dependencies) {
throw unimplemented("blas", "syr2k", "for row_major layout");
}
#define SYR2K_LAUNCHER_USM(TYPE, CUBLAS_ROUTINE) \
cl::sycl::event syr2k(cl::sycl::queue &queue, uplo upper_lower, transpose trans, int64_t n, \
int64_t k, TYPE alpha, const TYPE *a, int64_t lda, const TYPE *b, \
int64_t ldb, TYPE beta, TYPE *c, int64_t ldc, \
const std::vector<cl::sycl::event> &dependencies) { \
return syr2k(CUBLAS_ROUTINE, queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, \
c, ldc, dependencies); \
}
SYR2K_LAUNCHER_USM(float, cublasSsyr2k)
SYR2K_LAUNCHER_USM(double, cublasDsyr2k)
SYR2K_LAUNCHER_USM(std::complex<float>, cublasCsyr2k)
SYR2K_LAUNCHER_USM(std::complex<double>, cublasZsyr2k)
#undef SYR2K_LAUNCHER_USM
template <typename Func, typename DataType, typename ScalarType>
inline cl::sycl::event her2k(Func func, cl::sycl::queue &queue, uplo upper_lower, transpose trans,
int64_t n, int64_t k, const DataType alpha, const DataType *a,
int64_t lda, const DataType *b, int64_t ldb, const ScalarType beta,
DataType *c, int64_t ldc,
const std::vector<cl::sycl::event> &dependencies) {
throw unimplemented("blas", "her2k", "for row_major layout");
}
#define HER2K_LAUNCHER_USM(DATA_TYPE, SCALAR_TYPE, CUBLAS_ROUTINE) \
cl::sycl::event her2k(cl::sycl::queue &queue, uplo upper_lower, transpose trans, int64_t n, \
int64_t k, const DATA_TYPE alpha, const DATA_TYPE *a, int64_t lda, \
const DATA_TYPE *b, int64_t ldb, const SCALAR_TYPE beta, DATA_TYPE *c, \
int64_t ldc, const std::vector<cl::sycl::event> &dependencies) { \
return her2k(CUBLAS_ROUTINE, queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, \
c, ldc, dependencies); \
}
HER2K_LAUNCHER_USM(std::complex<float>, float, cublasCher2k)
HER2K_LAUNCHER_USM(std::complex<double>, double, cublasZher2k)
#undef HER2K_LAUNCHER_USM
// NOTE: In cublas TRMM diverted from the netlib blas and for performance
// reason it requires the C matrix to be
// separated from the B matrix. It is possible to use B instead of C, but this
// will slow-down the code.
template <typename Func, typename T>
inline cl::sycl::event trmm(Func func, cl::sycl::queue &queue, side left_right, uplo upper_lower,
transpose trans, diag unit_diag, int64_t m, int64_t n, T alpha,
const T *a, int64_t lda, T *b, int64_t ldb,
const std::vector<cl::sycl::event> &dependencies) {
throw unimplemented("blas", "trmm", "for row_major layout");
}
#define TRMM_LAUNCHER_USM(TYPE, CUBLAS_ROUTINE) \
cl::sycl::event trmm(cl::sycl::queue &queue, side left_right, uplo upper_lower, \
transpose trans, diag unit_diag, int64_t m, int64_t n, TYPE alpha, \
const TYPE *a, int64_t lda, TYPE *b, int64_t ldb, \
const std::vector<cl::sycl::event> &dependencies) { \
return trmm(CUBLAS_ROUTINE, queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, \
a, lda, b, ldb, dependencies); \
}
TRMM_LAUNCHER_USM(float, cublasStrmm)
TRMM_LAUNCHER_USM(double, cublasDtrmm)
TRMM_LAUNCHER_USM(std::complex<float>, cublasCtrmm)
TRMM_LAUNCHER_USM(std::complex<double>, cublasZtrmm)
#undef TRMM_LAUNCHER_USM
template <typename Func, typename T>
inline cl::sycl::event trsm(Func func, cl::sycl::queue &queue, side left_right, uplo upper_lower,
transpose trans, diag unit_diag, int64_t m, int64_t n, T alpha,
const T *a, int64_t lda, T *b, int64_t ldb,
const std::vector<cl::sycl::event> &dependencies) {
throw unimplemented("blas", "trsm", "for row_major layout");
}
#define TRSM_LAUNCHER_USM(TYPE, CUBLAS_ROUTINE) \
cl::sycl::event trsm(cl::sycl::queue &queue, side left_right, uplo upper_lower, \
transpose trans, diag unit_diag, int64_t m, int64_t n, TYPE alpha, \
const TYPE *a, int64_t lda, TYPE *b, int64_t ldb, \
const std::vector<cl::sycl::event> &dependencies) { \
return trsm(CUBLAS_ROUTINE, queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, \
a, lda, b, ldb, dependencies); \
}
TRSM_LAUNCHER_USM(float, cublasStrsm)
TRSM_LAUNCHER_USM(double, cublasDtrsm)
TRSM_LAUNCHER_USM(std::complex<float>, cublasCtrsm)
TRSM_LAUNCHER_USM(std::complex<double>, cublasZtrsm)
#undef TRSM_LAUNCHER_USM
} // namespace row_major
} // namespace cublas
} // namespace blas
} // namespace mkl
} // namespace oneapi
| 55.61203 | 100 | 0.572062 | trosenqu |
b198d4947f6c61ffdae52d3bdbf5cc0c348bc882 | 12,185 | cpp | C++ | src/Cip2location_db3.cpp | silgy/ip2loc | 84fc4b0a7f62e2dbe87e6576c08c9afcfb238c40 | [
"MIT"
] | null | null | null | src/Cip2location_db3.cpp | silgy/ip2loc | 84fc4b0a7f62e2dbe87e6576c08c9afcfb238c40 | [
"MIT"
] | null | null | null | src/Cip2location_db3.cpp | silgy/ip2loc | 84fc4b0a7f62e2dbe87e6576c08c9afcfb238c40 | [
"MIT"
] | null | null | null | /* ---------------------------------------------------------------------------
Table access class
Generated on silgy.org on 2020-05-30 11:13:49, generator v.1.0.0
Using C-style strings
Using exceptions
--------------------------------------------------------------------------- */
#include "Cip2location_db3.h"
bool Cip2location_db3::slots_[CDB_MAX_INSTANCES]={0};
/* ---------------------------------------------------------------------------
Constructor
--------------------------------------------------------------------------- */
Cip2location_db3::Cip2location_db3()
{
setInstance(slots_);
table_ = "ip2location_db3";
columnList_ = "ip_from,"
"ip_to,"
"country_code,"
"country_name,"
"region_name,"
"city_name";
if ( !(s_=mysql_stmt_init(dbConn_)) )
ThrowSQL("mysql_stmt_init");
if ( !(sc_=mysql_stmt_init(dbConn_)) )
ThrowSQL("mysql_stmt_init");
if ( !(sGet_=mysql_stmt_init(dbConn_)) )
ThrowSQL("mysql_stmt_init");
if ( !(sUpdate_=mysql_stmt_init(dbConn_)) )
ThrowSQL("mysql_stmt_init");
if ( !(sInsert_=mysql_stmt_init(dbConn_)) )
ThrowSQL("mysql_stmt_init");
if ( !(sDelete_=mysql_stmt_init(dbConn_)) )
ThrowSQL("mysql_stmt_init");
if ( !(sSet_=mysql_stmt_init(dbConn_)) )
ThrowSQL("mysql_stmt_init");
Reset();
}
/* ---------------------------------------------------------------------------
Destructor
--------------------------------------------------------------------------- */
Cip2location_db3::~Cip2location_db3()
{
mysql_stmt_close(s_);
mysql_stmt_close(sGet_);
mysql_stmt_close(sUpdate_);
mysql_stmt_close(sInsert_);
mysql_stmt_close(sDelete_);
mysql_stmt_close(sSet_);
slots_[instance_] = false;
}
/* ---------------------------------------------------------------------------
Get the next record
Return false if end of record set
--------------------------------------------------------------------------- */
bool Cip2location_db3::Fetch()
{
int ret;
ret = mysql_stmt_fetch(s_);
if ( ret != 0 )
{
Reset();
if ( ret == 1 || ret == MYSQL_NO_DATA )
return false;
else
{
Cdb::ThrowSQL("Cip2location_db3::Fetch | mysql_stmt_fetch");
return false;
}
}
convSC();
genDTStrings();
return true;
}
/* ---------------------------------------------------------------------------
Get record by PK
Not Found will return false
--------------------------------------------------------------------------- */
bool Cip2location_db3::Get(unsigned arg_ip_from)
{
int ret;
if ( firstGet_ )
{
char q[SQLBUF];
sprintf(q, "SELECT ip_from,ip_to,country_code,country_name,region_name,city_name FROM ip2location_db3 WHERE ip_from=?");
ret = mysql_stmt_prepare(sGet_, q, strlen(q));
if ( ret != 0 )
Cdb::ThrowSQL("Cip2location_db3::Get | mysql_stmt_prepare");
firstGet_ = false;
}
bindKey(sGet_, arg_ip_from);
if ( mysql_stmt_execute(sGet_) )
Cdb::ThrowSQL("Cip2location_db3::Get | mysql_stmt_execute");
bindOutput(sGet_);
if ( mysql_stmt_store_result(sGet_) )
Cdb::ThrowSQL("Cip2location_db3::Get | mysql_stmt_store_result");
ret = mysql_stmt_fetch(sGet_);
if ( ret != 0 )
{
if ( ret == 1 || ret == MYSQL_NO_DATA )
return false;
else
Cdb::ThrowSQL("Cip2location_db3::Get | mysql_stmt_fetch");
}
convSC();
genDTStrings();
return true;
}
/* ---------------------------------------------------------------------------
Insert record
--------------------------------------------------------------------------- */
unsigned Cip2location_db3::Insert()
{
int ret;
if ( firstInsert_ )
{
char q[SQLBUF];
sprintf(q, "INSERT INTO ip2location_db3 (ip_from,ip_to,country_code,country_name,region_name,city_name) VALUES (?,?,?,?,?,?)");
ret = mysql_stmt_prepare(sInsert_, q, strlen(q));
if ( ret != 0 )
Cdb::ThrowSQL("Cip2location_db3::Insert | mysql_stmt_prepare");
firstInsert_ = false;
}
bindInput(sInsert_);
ret = mysql_stmt_execute(sInsert_);
if ( ret != 0 )
Cdb::ThrowSQL("Cip2location_db3::Insert | mysql_stmt_execute");
return mysql_insert_id(dbConn_);
}
/* ---------------------------------------------------------------------------
Update record by PK
--------------------------------------------------------------------------- */
void Cip2location_db3::Update(unsigned arg_ip_from)
{
int ret;
if ( firstUpdate_ )
{
char q[SQLBUF];
sprintf(q, "UPDATE ip2location_db3 SET ip_from=?,ip_to=?,country_code=?,country_name=?,region_name=?,city_name=? WHERE ip_from=?");
ret = mysql_stmt_prepare(sUpdate_, q, strlen(q));
if ( ret != 0 )
Cdb::ThrowSQL("Cip2location_db3::Update | mysql_stmt_prepare");
firstUpdate_ = false;
}
bindInput(sUpdate_, true, arg_ip_from);
ret = mysql_stmt_execute(sUpdate_);
if ( ret != 0 )
Cdb::ThrowSQL("Cip2location_db3::Update | mysql_stmt_execute");
}
/* ---------------------------------------------------------------------------
Delete record by PK
--------------------------------------------------------------------------- */
void Cip2location_db3::Delete(unsigned arg_ip_from)
{
int ret;
if ( firstDelete_ )
{
char q[SQLBUF];
sprintf(q, "DELETE FROM ip2location_db3 WHERE ip_from=?");
ret = mysql_stmt_prepare(sDelete_, q, strlen(q));
if ( ret != 0 )
Cdb::ThrowSQL("Cip2location_db3::Delete | mysql_stmt_prepare");
firstDelete_ = false;
}
bindKey(sDelete_, arg_ip_from);
ret = mysql_stmt_execute(sDelete_);
if ( ret != 0 )
Cdb::ThrowSQL("Cip2location_db3::Delete | mysql_stmt_execute");
}
/* ---------------------------------------------------------------------------
Insert or update record by PK
--------------------------------------------------------------------------- */
void Cip2location_db3::Set(unsigned arg_ip_from)
{
int ret;
if ( firstSet_ )
{
char q[SQLBUF];
sprintf(q, "SELECT ip_from FROM ip2location_db3 WHERE ip_from=?");
ret = mysql_stmt_prepare(sSet_, q, strlen(q));
if ( ret != 0 )
Cdb::ThrowSQL("Cip2location_db3::Set | mysql_stmt_prepare");
firstSet_ = false;
}
bindKey(sSet_, arg_ip_from);
if ( mysql_stmt_execute(sSet_) )
Cdb::ThrowSQL("Cip2location_db3::Set | mysql_stmt_execute");
bindSetOutput();
if ( mysql_stmt_store_result(sSet_) )
Cdb::ThrowSQL("Cip2location_db3::Set | mysql_stmt_store_result");
ret = mysql_stmt_fetch(sSet_);
if ( ret == 0 ) /* record existed */
{
Update(arg_ip_from);
}
else if ( ret == 1 || ret == MYSQL_NO_DATA ) /* not found ==> insert new */
{
ip_from = arg_ip_from;
Insert();
}
else
Cdb::ThrowSQL("Cip2location_db3::Set | mysql_stmt_fetch");
}
/* ---------------------------------------------------------------------------
Bind key values
--------------------------------------------------------------------------- */
void Cip2location_db3::bindKey(MYSQL_STMT *s, unsigned arg_ip_from)
{
k_ip_from_ = arg_ip_from;
memset(&bndk_, 0, sizeof(bndk_));
bndk_[0].buffer_type = MYSQL_TYPE_LONG;
bndk_[0].buffer = (char*)&k_ip_from_;
bndk_[0].is_unsigned = true;
if ( mysql_stmt_bind_param(s, bndk_) )
Cdb::ThrowSQL("Cip2location_db3::bindKey | mysql_stmt_bind_param");
}
/* ---------------------------------------------------------------------------
Bind input values
--------------------------------------------------------------------------- */
void Cip2location_db3::bindInput(MYSQL_STMT *s, bool withKey, unsigned arg_ip_from)
{
country_code_len_ = strlen(country_code);
country_name_len_ = strlen(country_name);
region_name_len_ = strlen(region_name);
city_name_len_ = strlen(city_name);
memset(&bndi_, 0, sizeof(bndi_));
bndi_[0].buffer_type = MYSQL_TYPE_LONG;
bndi_[0].buffer = (char*)&ip_from;
bndi_[0].is_unsigned = true;
bndi_[1].buffer_type = MYSQL_TYPE_LONG;
bndi_[1].buffer = (char*)&ip_to;
bndi_[1].is_unsigned = true;
bndi_[2].buffer_type = MYSQL_TYPE_STRING;
bndi_[2].buffer = (char*)country_code;
bndi_[2].length = &country_code_len_;
bndi_[3].buffer_type = MYSQL_TYPE_STRING;
bndi_[3].buffer = (char*)country_name;
bndi_[3].length = &country_name_len_;
bndi_[4].buffer_type = MYSQL_TYPE_STRING;
bndi_[4].buffer = (char*)region_name;
bndi_[4].length = ®ion_name_len_;
bndi_[5].buffer_type = MYSQL_TYPE_STRING;
bndi_[5].buffer = (char*)city_name;
bndi_[5].length = &city_name_len_;
if ( withKey ) /* after WHERE */
{
k_ip_from_ = arg_ip_from;
bndi_[6].buffer_type = MYSQL_TYPE_LONG;
bndi_[6].buffer = (char*)&k_ip_from_;
bndi_[6].is_unsigned = true;
}
if ( mysql_stmt_bind_param(s, bndi_) )
Cdb::ThrowSQL("Cip2location_db3::bindInput | mysql_stmt_bind_param");
}
/* ---------------------------------------------------------------------------
Bind output values
--------------------------------------------------------------------------- */
void Cip2location_db3::bindOutput(MYSQL_STMT *s)
{
memset(&bndo_, 0, sizeof(bndo_));
bndo_[0].buffer_type = MYSQL_TYPE_LONG;
bndo_[0].buffer = (char*)&ip_from;
bndo_[0].is_null = &ip_from_is_null_;
bndo_[0].is_unsigned = true;
bndo_[1].buffer_type = MYSQL_TYPE_LONG;
bndo_[1].buffer = (char*)&ip_to;
bndo_[1].is_null = &ip_to_is_null_;
bndo_[1].is_unsigned = true;
bndo_[2].buffer_type = MYSQL_TYPE_STRING;
bndo_[2].buffer = (char*)country_code;
bndo_[2].buffer_length = 3;
bndo_[2].is_null = &country_code_is_null_;
bndo_[3].buffer_type = MYSQL_TYPE_STRING;
bndo_[3].buffer = (char*)country_name;
bndo_[3].buffer_length = 65;
bndo_[3].is_null = &country_name_is_null_;
bndo_[4].buffer_type = MYSQL_TYPE_STRING;
bndo_[4].buffer = (char*)region_name;
bndo_[4].buffer_length = 129;
bndo_[4].is_null = ®ion_name_is_null_;
bndo_[5].buffer_type = MYSQL_TYPE_STRING;
bndo_[5].buffer = (char*)city_name;
bndo_[5].buffer_length = 129;
bndo_[5].is_null = &city_name_is_null_;
if ( mysql_stmt_bind_result(s, bndo_) )
Cdb::ThrowSQL("Cip2location_db3::bindOutput | mysql_stmt_bind_result");
}
/* ---------------------------------------------------------------------------
Bind output value for Set
--------------------------------------------------------------------------- */
void Cip2location_db3::bindSetOutput()
{
static unsigned ip_from; /* to be scrapped anyway */
memset(&bndso_, 0, sizeof(bndso_));
bndso_[0].buffer_type = MYSQL_TYPE_LONG;
bndso_[0].buffer = (char*)&ip_from;
bndso_[0].is_unsigned = true;
if ( mysql_stmt_bind_result(sSet_, bndso_) )
Cdb::ThrowSQL("Cip2location_db3::bindSetOutput | mysql_stmt_bind_result");
}
/* ---------------------------------------------------------------------------
Convert single char values
--------------------------------------------------------------------------- */
void Cip2location_db3::convSC()
{
}
/* ---------------------------------------------------------------------------
Generate date-time strings
--------------------------------------------------------------------------- */
void Cip2location_db3::genDTStrings()
{
}
/* ---------------------------------------------------------------------------
Reset (zero) public variables
--------------------------------------------------------------------------- */
void Cip2location_db3::Reset()
{
ip_from = 0;
ip_to = 0;
country_code[0] = EOS;
country_name[0] = EOS;
region_name[0] = EOS;
city_name[0] = EOS;
}
| 28.738208 | 139 | 0.504473 | silgy |
b198eff6ac64daaa4c2ee7c1636219eddc936459 | 28,522 | cpp | C++ | src/core/NEON/kernels/arm_conv/depthwise/kernels/a64_s8q_packed_to_nhwc_5x5_s1_with_multiplier_output4x2_dot_depthfirst/generic.cpp | MaximMilashchenko/ComputeLibrary | 91ee4d0a9ef128b16936921470a0e3ffef347536 | [
"MIT"
] | 1 | 2022-02-10T11:06:25.000Z | 2022-02-10T11:06:25.000Z | src/core/NEON/kernels/arm_conv/depthwise/kernels/a64_s8q_packed_to_nhwc_5x5_s1_with_multiplier_output4x2_dot_depthfirst/generic.cpp | 0xgpapad/ComputeLibrary | 91ee4d0a9ef128b16936921470a0e3ffef347536 | [
"MIT"
] | null | null | null | src/core/NEON/kernels/arm_conv/depthwise/kernels/a64_s8q_packed_to_nhwc_5x5_s1_with_multiplier_output4x2_dot_depthfirst/generic.cpp | 0xgpapad/ComputeLibrary | 91ee4d0a9ef128b16936921470a0e3ffef347536 | [
"MIT"
] | 1 | 2022-02-04T10:22:53.000Z | 2022-02-04T10:22:53.000Z | /*
* Copyright (c) 2021 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#if defined(__aarch64__)
#include "arm_gemm.hpp"
#include <cstddef>
#include <cstdint>
namespace arm_conv {
namespace depthwise {
void a64_s8q_packed_to_nhwc_5x5_s1_with_multiplier_output4x2_dot_depthfirst_impl(
const int8_t *const *const inptrs,
int8_t *const *const outptrs,
const void *params,
unsigned int n_output_channels,
const arm_gemm::Requantize32& qp
)
{
__asm__ __volatile__(
"movi v15.16b, #0x1\n"
"ldr x21, [%x[inptrs], #0x0]\n"
"add SP, SP, #-0x80\n"
"movi v14.4s, #0x1\n"
"ldr x20, [%x[inptrs], #0x8]\n"
"add x22, %x[qp], %[offsetof_Requantize32_b_offset]\n"
"movi v28.4s, #0x0\n"
"ldr x19, [%x[inptrs], #0x10]\n"
"mov x11, #0x0\n"
"movi v27.4s, #0x0\n"
"ld1 { v13.16b }, [x21]\n"
"mov x10, #0x0\n"
"movi v26.4s, #0x0\n"
"ld1 { v12.16b }, [x20]\n"
"add x9, %x[qp], %[offsetof_Requantize32_c_offset]\n"
"movi v25.4s, #0x0\n"
"ld1 { v7.16b }, [x19]\n"
"add x28, %x[qp], %[offsetof_Requantize32_minval]\n"
"movi v24.4s, #0x0\n"
"ldr x21, [%x[inptrs], #0x18]\n"
"add x27, %x[qp], %[offsetof_Requantize32_maxval]\n"
"mov v18.16b, v13.16b\n"
"ldr x20, [%x[inptrs], #0x20]\n"
"cmp %x[n_channels], #0x4\n"
"ext v18.16b, v18.16b, v18.16b, #0x1\n"
"ldr x19, [%x[inptrs], #0x28]\n"
"mov v17.16b, v12.16b\n"
"ld1 { v6.16b }, [x21]\n"
"ext v17.16b, v17.16b, v17.16b, #0x1\n"
"ld1 { v5.16b }, [x20]\n"
"mov v16.16b, v7.16b\n"
"ld1 { v4.16b }, [x19]\n"
"ext v16.16b, v16.16b, v16.16b, #0x1\n"
"ldr x20, [%x[inptrs], #0x30]\n"
"zip1 v13.2d, v13.2d, v18.2d\n"
"ldr x19, [%x[inptrs], #0x38]\n"
"zip1 v12.2d, v12.2d, v17.2d\n"
"ld1r { v3.4s }, [x22]\n"
"mov v18.16b, v6.16b\n"
"ld1 { v2.16b }, [x20]\n"
"zip1 v7.2d, v7.2d, v16.2d\n"
"ld1 { v1.16b }, [x19]\n"
"ext v18.16b, v18.16b, v18.16b, #0x1\n"
"ldp x26, x25, [%x[outptrs], #0x0]\n"
"mov v17.16b, v5.16b\n"
"ldp x24, x23, [%x[outptrs], #0x10]\n"
"ext v17.16b, v17.16b, v17.16b, #0x1\n"
"ldp x22, x21, [%x[outptrs], #0x20]\n"
"mov v16.16b, v4.16b\n"
"ldp x20, x19, [%x[outptrs], #0x30]\n"
"zip1 v6.2d, v6.2d, v18.2d\n"
"ld1r { v0.4s }, [x9]\n"
"ext v16.16b, v16.16b, v16.16b, #0x1\n"
"ld1r { v31.4s }, [x28]\n"
"zip1 v5.2d, v5.2d, v17.2d\n"
"ld1r { v30.4s }, [x27]\n"
"mov v17.16b, v2.16b\n"
"ldr q29, [%x[params], #0x0]\n"
"ext v17.16b, v17.16b, v17.16b, #0x1\n"
"ldr q8, [%x[params], #0x10]\n"
"zip1 v4.2d, v4.2d, v16.2d\n"
"ldr q9, [%x[params], #0x20]\n"
"mov v16.16b, v1.16b\n"
"ldr q10, [%x[params], #0x30]\n"
"ext v16.16b, v16.16b, v16.16b, #0x1\n"
"ldr q11, [%x[params], #0x40]\n"
"add %x[params], %x[params], #0x50\n"
"zip1 v2.2d, v2.2d, v17.2d\n"
"movi v23.4s, #0x0\n"
"movi v22.4s, #0x0\n"
"zip1 v1.2d, v1.2d, v16.2d\n"
"movi v21.4s, #0x0\n"
"movi v18.4s, #0x0\n"
"movi v17.4s, #0x0\n"
"movi v16.4s, #0x0\n"
"movi v20.4s, #0x0\n"
"movi v19.4s, #0x0\n"
".inst 0x4f8de1fc // sdot v28.4s, v15.16b, v13.4b[0]\n"
".inst 0x4f8de9fb // sdot v27.4s, v15.16b, v13.4b[2]\n"
".inst 0x4f8ce1fa // sdot v26.4s, v15.16b, v12.4b[0]\n"
".inst 0x4f8ce9f9 // sdot v25.4s, v15.16b, v12.4b[2]\n"
".inst 0x4fade1dc // sdot v28.4s, v14.16b, v13.4b[1]\n"
".inst 0x4fade9db // sdot v27.4s, v14.16b, v13.4b[3]\n"
".inst 0x4face1da // sdot v26.4s, v14.16b, v12.4b[1]\n"
".inst 0x4face9d9 // sdot v25.4s, v14.16b, v12.4b[3]\n"
".inst 0x4f87e1f8 // sdot v24.4s, v15.16b, v7.4b[0]\n"
".inst 0x4f87e9f7 // sdot v23.4s, v15.16b, v7.4b[2]\n"
".inst 0x4f86e1f6 // sdot v22.4s, v15.16b, v6.4b[0]\n"
".inst 0x4f86e9f5 // sdot v21.4s, v15.16b, v6.4b[2]\n"
".inst 0x4fa7e1d8 // sdot v24.4s, v14.16b, v7.4b[1]\n"
".inst 0x4fa7e9d7 // sdot v23.4s, v14.16b, v7.4b[3]\n"
".inst 0x4fa6e1d6 // sdot v22.4s, v14.16b, v6.4b[1]\n"
".inst 0x4fa6e9d5 // sdot v21.4s, v14.16b, v6.4b[3]\n"
".inst 0x4f85e1f2 // sdot v18.4s, v15.16b, v5.4b[0]\n"
".inst 0x4f85e9f1 // sdot v17.4s, v15.16b, v5.4b[2]\n"
".inst 0x4f84e1f0 // sdot v16.4s, v15.16b, v4.4b[0]\n"
".inst 0x4f84e9f4 // sdot v20.4s, v15.16b, v4.4b[2]\n"
".inst 0x4fa5e1d2 // sdot v18.4s, v14.16b, v5.4b[1]\n"
".inst 0x4fa5e9d1 // sdot v17.4s, v14.16b, v5.4b[3]\n"
".inst 0x4fa4e1d0 // sdot v16.4s, v14.16b, v4.4b[1]\n"
".inst 0x4fa4e9d4 // sdot v20.4s, v14.16b, v4.4b[3]\n"
".inst 0x4f82e1f3 // sdot v19.4s, v15.16b, v2.4b[0]\n"
"mov v28.16b, v28.16b\n"
"mov v27.16b, v27.16b\n"
"add v28.4s, v28.4s, v26.4s\n"
".inst 0x4fa2e1d3 // sdot v19.4s, v14.16b, v2.4b[1]\n"
"add v27.4s, v27.4s, v25.4s\n"
"add v28.4s, v28.4s, v24.4s\n"
"mov v26.16b, v26.16b\n"
"add v27.4s, v27.4s, v23.4s\n"
"add v28.4s, v28.4s, v22.4s\n"
"mov v25.16b, v25.16b\n"
"add v27.4s, v27.4s, v21.4s\n"
"add v28.4s, v28.4s, v18.4s\n"
"add v26.4s, v26.4s, v24.4s\n"
"add v27.4s, v27.4s, v17.4s\n"
"add v25.4s, v25.4s, v23.4s\n"
"add v26.4s, v26.4s, v22.4s\n"
"mov v24.16b, v24.16b\n"
"add v25.4s, v25.4s, v21.4s\n"
"add v26.4s, v26.4s, v18.4s\n"
"mov v23.16b, v23.16b\n"
"add v25.4s, v25.4s, v17.4s\n"
"add v26.4s, v26.4s, v16.4s\n"
"add v24.4s, v24.4s, v22.4s\n"
"add v25.4s, v25.4s, v20.4s\n"
"add v23.4s, v23.4s, v21.4s\n"
"add v24.4s, v24.4s, v18.4s\n"
"mov v22.16b, v22.16b\n"
"add v23.4s, v23.4s, v17.4s\n"
"add v24.4s, v24.4s, v16.4s\n"
"mov v21.16b, v21.16b\n"
"add v23.4s, v23.4s, v20.4s\n"
"add v24.4s, v24.4s, v19.4s\n"
"add v22.4s, v22.4s, v18.4s\n"
"movi v18.4s, #0x0\n"
".inst 0x4f82e9f2 // sdot v18.4s, v15.16b, v2.4b[2]\n"
"add v21.4s, v21.4s, v17.4s\n"
"movi v17.4s, #0x0\n"
".inst 0x4f81e1f1 // sdot v17.4s, v15.16b, v1.4b[0]\n"
".inst 0x4fa2e9d2 // sdot v18.4s, v14.16b, v2.4b[3]\n"
"add v22.4s, v22.4s, v16.4s\n"
"movi v16.4s, #0x0\n"
".inst 0x4fa1e1d1 // sdot v17.4s, v14.16b, v1.4b[1]\n"
".inst 0x4f81e9f0 // sdot v16.4s, v15.16b, v1.4b[2]\n"
"add v23.4s, v23.4s, v18.4s\n"
"add v21.4s, v21.4s, v20.4s\n"
"add v22.4s, v22.4s, v19.4s\n"
".inst 0x4fa1e9d0 // sdot v16.4s, v14.16b, v1.4b[3]\n"
"add v21.4s, v21.4s, v18.4s\n"
"add v22.4s, v22.4s, v17.4s\n"
"neg v3.4s, v3.4s\n"
"add v21.4s, v21.4s, v16.4s\n"
"mul v28.4s, v28.4s, v3.4s\n"
"str q28, [SP, #0x0]\n"
"mul v27.4s, v27.4s, v3.4s\n"
"mul v26.4s, v26.4s, v3.4s\n"
"str q27, [SP, #0x10]\n"
"mul v25.4s, v25.4s, v3.4s\n"
"mul v24.4s, v24.4s, v3.4s\n"
"str q26, [SP, #0x20]\n"
"mul v23.4s, v23.4s, v3.4s\n"
"str q25, [SP, #0x30]\n"
"mul v22.4s, v22.4s, v3.4s\n"
"mul v21.4s, v21.4s, v3.4s\n"
"str q24, [SP, #0x40]\n"
"add v28.4s, v28.4s, v29.4s\n"
"str q23, [SP, #0x50]\n"
"add v27.4s, v27.4s, v29.4s\n"
"str q22, [SP, #0x60]\n"
"add v26.4s, v26.4s, v29.4s\n"
"add v25.4s, v25.4s, v29.4s\n"
"str q21, [SP, #0x70]\n"
"add v24.4s, v24.4s, v29.4s\n"
"add v23.4s, v23.4s, v29.4s\n"
"add v22.4s, v22.4s, v29.4s\n"
"add v21.4s, v21.4s, v29.4s\n"
"ble 2f\n"
"1:" // Loop
".inst 0x4f8de11c // sdot v28.4s, v8.16b, v13.4b[0]\n"
"ldr q20, [%x[params], #0x60]\n"
"add x11, x11, #0x10\n"
".inst 0x4f8de91b // sdot v27.4s, v8.16b, v13.4b[2]\n"
"ldr q19, [%x[params], #0x70]\n"
"sub %x[n_channels], %x[n_channels], #0x4\n"
".inst 0x4f8ce11a // sdot v26.4s, v8.16b, v12.4b[0]\n"
"ldr q29, [%x[params], #0x80]\n"
"cmp %x[n_channels], #0x4\n"
".inst 0x4f8ce919 // sdot v25.4s, v8.16b, v12.4b[2]\n"
".inst 0x4f87e118 // sdot v24.4s, v8.16b, v7.4b[0]\n"
".inst 0x4f87e917 // sdot v23.4s, v8.16b, v7.4b[2]\n"
".inst 0x4f86e116 // sdot v22.4s, v8.16b, v6.4b[0]\n"
".inst 0x4f86e915 // sdot v21.4s, v8.16b, v6.4b[2]\n"
"ldr q8, [%x[params], #0x0]\n"
".inst 0x4fade13c // sdot v28.4s, v9.16b, v13.4b[1]\n"
".inst 0x4fade93b // sdot v27.4s, v9.16b, v13.4b[3]\n"
".inst 0x4face13a // sdot v26.4s, v9.16b, v12.4b[1]\n"
".inst 0x4face939 // sdot v25.4s, v9.16b, v12.4b[3]\n"
".inst 0x4fa7e138 // sdot v24.4s, v9.16b, v7.4b[1]\n"
".inst 0x4fa7e937 // sdot v23.4s, v9.16b, v7.4b[3]\n"
".inst 0x4fa6e136 // sdot v22.4s, v9.16b, v6.4b[1]\n"
".inst 0x4fa6e935 // sdot v21.4s, v9.16b, v6.4b[3]\n"
"ldr q9, [%x[params], #0x10]\n"
".inst 0x4f8ce15c // sdot v28.4s, v10.16b, v12.4b[0]\n"
".inst 0x4f8ce95b // sdot v27.4s, v10.16b, v12.4b[2]\n"
".inst 0x4f87e15a // sdot v26.4s, v10.16b, v7.4b[0]\n"
".inst 0x4f87e959 // sdot v25.4s, v10.16b, v7.4b[2]\n"
".inst 0x4f86e158 // sdot v24.4s, v10.16b, v6.4b[0]\n"
".inst 0x4f86e957 // sdot v23.4s, v10.16b, v6.4b[2]\n"
".inst 0x4f85e156 // sdot v22.4s, v10.16b, v5.4b[0]\n"
".inst 0x4f85e955 // sdot v21.4s, v10.16b, v5.4b[2]\n"
"ldr q10, [%x[params], #0x20]\n"
".inst 0x4face17c // sdot v28.4s, v11.16b, v12.4b[1]\n"
".inst 0x4face97b // sdot v27.4s, v11.16b, v12.4b[3]\n"
".inst 0x4fa7e17a // sdot v26.4s, v11.16b, v7.4b[1]\n"
".inst 0x4fa7e979 // sdot v25.4s, v11.16b, v7.4b[3]\n"
".inst 0x4fa6e178 // sdot v24.4s, v11.16b, v6.4b[1]\n"
".inst 0x4fa6e977 // sdot v23.4s, v11.16b, v6.4b[3]\n"
".inst 0x4fa5e176 // sdot v22.4s, v11.16b, v5.4b[1]\n"
".inst 0x4fa5e975 // sdot v21.4s, v11.16b, v5.4b[3]\n"
"ldr q11, [%x[params], #0x30]\n"
".inst 0x4f87e11c // sdot v28.4s, v8.16b, v7.4b[0]\n"
".inst 0x4f87e91b // sdot v27.4s, v8.16b, v7.4b[2]\n"
".inst 0x4f86e11a // sdot v26.4s, v8.16b, v6.4b[0]\n"
".inst 0x4f86e919 // sdot v25.4s, v8.16b, v6.4b[2]\n"
".inst 0x4f85e118 // sdot v24.4s, v8.16b, v5.4b[0]\n"
".inst 0x4f85e917 // sdot v23.4s, v8.16b, v5.4b[2]\n"
".inst 0x4f84e116 // sdot v22.4s, v8.16b, v4.4b[0]\n"
".inst 0x4f84e915 // sdot v21.4s, v8.16b, v4.4b[2]\n"
"ldr q8, [%x[params], #0x40]\n"
".inst 0x4fa7e13c // sdot v28.4s, v9.16b, v7.4b[1]\n"
".inst 0x4fa7e93b // sdot v27.4s, v9.16b, v7.4b[3]\n"
".inst 0x4fa6e13a // sdot v26.4s, v9.16b, v6.4b[1]\n"
".inst 0x4fa6e939 // sdot v25.4s, v9.16b, v6.4b[3]\n"
".inst 0x4fa5e138 // sdot v24.4s, v9.16b, v5.4b[1]\n"
".inst 0x4fa5e937 // sdot v23.4s, v9.16b, v5.4b[3]\n"
".inst 0x4fa4e136 // sdot v22.4s, v9.16b, v4.4b[1]\n"
".inst 0x4fa4e935 // sdot v21.4s, v9.16b, v4.4b[3]\n"
"ldr q9, [%x[params], #0x50]\n"
".inst 0x4f86e15c // sdot v28.4s, v10.16b, v6.4b[0]\n"
".inst 0x4f86e95b // sdot v27.4s, v10.16b, v6.4b[2]\n"
".inst 0x4f85e15a // sdot v26.4s, v10.16b, v5.4b[0]\n"
".inst 0x4f85e959 // sdot v25.4s, v10.16b, v5.4b[2]\n"
".inst 0x4f84e158 // sdot v24.4s, v10.16b, v4.4b[0]\n"
".inst 0x4f84e957 // sdot v23.4s, v10.16b, v4.4b[2]\n"
".inst 0x4f82e156 // sdot v22.4s, v10.16b, v2.4b[0]\n"
".inst 0x4f82e955 // sdot v21.4s, v10.16b, v2.4b[2]\n"
"ldr q10, [%x[params], #0xb0]\n"
".inst 0x4fa6e17c // sdot v28.4s, v11.16b, v6.4b[1]\n"
".inst 0x4fa6e97b // sdot v27.4s, v11.16b, v6.4b[3]\n"
".inst 0x4fa5e17a // sdot v26.4s, v11.16b, v5.4b[1]\n"
".inst 0x4fa5e979 // sdot v25.4s, v11.16b, v5.4b[3]\n"
".inst 0x4fa4e178 // sdot v24.4s, v11.16b, v4.4b[1]\n"
".inst 0x4fa4e977 // sdot v23.4s, v11.16b, v4.4b[3]\n"
".inst 0x4fa2e176 // sdot v22.4s, v11.16b, v2.4b[1]\n"
".inst 0x4fa2e975 // sdot v21.4s, v11.16b, v2.4b[3]\n"
"ldr q11, [%x[params], #0xc0]\n"
".inst 0x4f85e11c // sdot v28.4s, v8.16b, v5.4b[0]\n"
".inst 0x4f85e91b // sdot v27.4s, v8.16b, v5.4b[2]\n"
".inst 0x4f84e11a // sdot v26.4s, v8.16b, v4.4b[0]\n"
".inst 0x4f84e919 // sdot v25.4s, v8.16b, v4.4b[2]\n"
".inst 0x4f82e118 // sdot v24.4s, v8.16b, v2.4b[0]\n"
".inst 0x4f82e917 // sdot v23.4s, v8.16b, v2.4b[2]\n"
".inst 0x4f81e116 // sdot v22.4s, v8.16b, v1.4b[0]\n"
".inst 0x4f81e915 // sdot v21.4s, v8.16b, v1.4b[2]\n"
"ldr q8, [%x[params], #0x90]\n"
".inst 0x4fa5e13c // sdot v28.4s, v9.16b, v5.4b[1]\n"
".inst 0x4fa5e93b // sdot v27.4s, v9.16b, v5.4b[3]\n"
".inst 0x4fa4e13a // sdot v26.4s, v9.16b, v4.4b[1]\n"
".inst 0x4fa4e939 // sdot v25.4s, v9.16b, v4.4b[3]\n"
".inst 0x4fa2e138 // sdot v24.4s, v9.16b, v2.4b[1]\n"
".inst 0x4fa2e937 // sdot v23.4s, v9.16b, v2.4b[3]\n"
".inst 0x4fa1e136 // sdot v22.4s, v9.16b, v1.4b[1]\n"
".inst 0x4fa1e935 // sdot v21.4s, v9.16b, v1.4b[3]\n"
"ldr q9, [%x[params], #0xa0]\n"
"add %x[params], %x[params], #0xd0\n"
"sqrdmulh v28.4s, v28.4s, v20.4s\n"
"sqrdmulh v27.4s, v27.4s, v20.4s\n"
"sqrdmulh v26.4s, v26.4s, v20.4s\n"
"sqrdmulh v25.4s, v25.4s, v20.4s\n"
"sqrdmulh v24.4s, v24.4s, v20.4s\n"
"and v18.16b, v28.16b, v19.16b\n"
"and v17.16b, v27.16b, v19.16b\n"
"and v16.16b, v26.16b, v19.16b\n"
"sshr v18.4s, v18.4s, #0x1f\n"
"sshr v17.4s, v17.4s, #0x1f\n"
"sshr v16.4s, v16.4s, #0x1f\n"
"sqadd v28.4s, v28.4s, v18.4s\n"
"sqadd v27.4s, v27.4s, v17.4s\n"
"sqadd v26.4s, v26.4s, v16.4s\n"
"and v16.16b, v25.16b, v19.16b\n"
"srshl v28.4s, v28.4s, v19.4s\n"
"srshl v27.4s, v27.4s, v19.4s\n"
"srshl v26.4s, v26.4s, v19.4s\n"
"sshr v16.4s, v16.4s, #0x1f\n"
"add v28.4s, v28.4s, v0.4s\n"
"add v27.4s, v27.4s, v0.4s\n"
"add v26.4s, v26.4s, v0.4s\n"
"smin v28.4s, v28.4s, v30.4s\n"
"smin v27.4s, v27.4s, v30.4s\n"
"smin v26.4s, v26.4s, v30.4s\n"
"smax v28.4s, v28.4s, v31.4s\n"
"smax v27.4s, v27.4s, v31.4s\n"
"smax v26.4s, v26.4s, v31.4s\n"
"uzp1 v28.16b, v28.16b, v28.16b\n"
"uzp1 v27.16b, v27.16b, v27.16b\n"
"uzp1 v28.16b, v28.16b, v28.16b\n"
"str s28, [x26, x10]\n"
"uzp1 v27.16b, v27.16b, v27.16b\n"
"uzp1 v26.16b, v26.16b, v26.16b\n"
"ldr q28, [SP, #0x0]\n"
"sqadd v25.4s, v25.4s, v16.4s\n"
"str s27, [x25, x10]\n"
"uzp1 v26.16b, v26.16b, v26.16b\n"
"ldr q27, [SP, #0x10]\n"
"and v16.16b, v24.16b, v19.16b\n"
"str s26, [x24, x10]\n"
"sqrdmulh v23.4s, v23.4s, v20.4s\n"
"ldr q26, [SP, #0x20]\n"
"srshl v25.4s, v25.4s, v19.4s\n"
"sshr v16.4s, v16.4s, #0x1f\n"
"sqrdmulh v22.4s, v22.4s, v20.4s\n"
"and v17.16b, v23.16b, v19.16b\n"
"add v25.4s, v25.4s, v0.4s\n"
"sqadd v24.4s, v24.4s, v16.4s\n"
"sshr v17.4s, v17.4s, #0x1f\n"
"smin v25.4s, v25.4s, v30.4s\n"
"and v16.16b, v22.16b, v19.16b\n"
"srshl v24.4s, v24.4s, v19.4s\n"
"smax v25.4s, v25.4s, v31.4s\n"
"sqadd v23.4s, v23.4s, v17.4s\n"
"sshr v16.4s, v16.4s, #0x1f\n"
"uzp1 v25.16b, v25.16b, v25.16b\n"
"add v24.4s, v24.4s, v0.4s\n"
"uzp1 v25.16b, v25.16b, v25.16b\n"
"str s25, [x23, x10]\n"
"smin v24.4s, v24.4s, v30.4s\n"
"srshl v23.4s, v23.4s, v19.4s\n"
"ldr q25, [SP, #0x30]\n"
"sqadd v22.4s, v22.4s, v16.4s\n"
"sqrdmulh v21.4s, v21.4s, v20.4s\n"
"smax v24.4s, v24.4s, v31.4s\n"
"add v23.4s, v23.4s, v0.4s\n"
"srshl v22.4s, v22.4s, v19.4s\n"
"uzp1 v24.16b, v24.16b, v24.16b\n"
"smin v23.4s, v23.4s, v30.4s\n"
"uzp1 v24.16b, v24.16b, v24.16b\n"
"str s24, [x22, x10]\n"
"smax v23.4s, v23.4s, v31.4s\n"
"add v22.4s, v22.4s, v0.4s\n"
"ldr q24, [SP, #0x40]\n"
"and v16.16b, v21.16b, v19.16b\n"
"add v28.4s, v28.4s, v29.4s\n"
"uzp1 v23.16b, v23.16b, v23.16b\n"
"smin v22.4s, v22.4s, v30.4s\n"
"uzp1 v23.16b, v23.16b, v23.16b\n"
"str s23, [x21, x10]\n"
"smax v22.4s, v22.4s, v31.4s\n"
"sshr v16.4s, v16.4s, #0x1f\n"
"ldr q23, [SP, #0x50]\n"
"add v27.4s, v27.4s, v29.4s\n"
"add v26.4s, v26.4s, v29.4s\n"
"uzp1 v22.16b, v22.16b, v22.16b\n"
"sqadd v21.4s, v21.4s, v16.4s\n"
"uzp1 v22.16b, v22.16b, v22.16b\n"
"str s22, [x20, x10]\n"
"add v25.4s, v25.4s, v29.4s\n"
"add v24.4s, v24.4s, v29.4s\n"
"ldr q22, [SP, #0x60]\n"
"srshl v21.4s, v21.4s, v19.4s\n"
"add v23.4s, v23.4s, v29.4s\n"
"add v21.4s, v21.4s, v0.4s\n"
"add v22.4s, v22.4s, v29.4s\n"
"smin v21.4s, v21.4s, v30.4s\n"
"smax v21.4s, v21.4s, v31.4s\n"
"uzp1 v21.16b, v21.16b, v21.16b\n"
"uzp1 v21.16b, v21.16b, v21.16b\n"
"str s21, [x19, x10]\n"
"add x10, x10, #0x4\n"
"ldr q21, [SP, #0x70]\n"
"add v21.4s, v21.4s, v29.4s\n"
"bgt 1b\n"
"2:" // Tail
".inst 0x4f8de11c // sdot v28.4s, v8.16b, v13.4b[0]\n"
"ldr q20, [%x[params], #0x60]\n"
"add x26, x26, x10\n"
".inst 0x4f8de91b // sdot v27.4s, v8.16b, v13.4b[2]\n"
"ldr q19, [%x[params], #0x70]\n"
"add x25, x25, x10\n"
".inst 0x4f8ce11a // sdot v26.4s, v8.16b, v12.4b[0]\n"
"add x24, x24, x10\n"
".inst 0x4f8ce919 // sdot v25.4s, v8.16b, v12.4b[2]\n"
"add x23, x23, x10\n"
".inst 0x4f87e118 // sdot v24.4s, v8.16b, v7.4b[0]\n"
"add x22, x22, x10\n"
".inst 0x4f87e917 // sdot v23.4s, v8.16b, v7.4b[2]\n"
"add x21, x21, x10\n"
".inst 0x4f86e116 // sdot v22.4s, v8.16b, v6.4b[0]\n"
"add x20, x20, x10\n"
".inst 0x4f86e915 // sdot v21.4s, v8.16b, v6.4b[2]\n"
"ldr q8, [%x[params], #0x0]\n"
"add x19, x19, x10\n"
".inst 0x4fade13c // sdot v28.4s, v9.16b, v13.4b[1]\n"
"cmp %x[n_channels], #0x4\n"
".inst 0x4fade93b // sdot v27.4s, v9.16b, v13.4b[3]\n"
".inst 0x4face13a // sdot v26.4s, v9.16b, v12.4b[1]\n"
".inst 0x4face939 // sdot v25.4s, v9.16b, v12.4b[3]\n"
".inst 0x4fa7e138 // sdot v24.4s, v9.16b, v7.4b[1]\n"
".inst 0x4fa7e937 // sdot v23.4s, v9.16b, v7.4b[3]\n"
".inst 0x4fa6e136 // sdot v22.4s, v9.16b, v6.4b[1]\n"
".inst 0x4fa6e935 // sdot v21.4s, v9.16b, v6.4b[3]\n"
"ldr q9, [%x[params], #0x10]\n"
".inst 0x4f8ce15c // sdot v28.4s, v10.16b, v12.4b[0]\n"
".inst 0x4f8ce95b // sdot v27.4s, v10.16b, v12.4b[2]\n"
".inst 0x4f87e15a // sdot v26.4s, v10.16b, v7.4b[0]\n"
".inst 0x4f87e959 // sdot v25.4s, v10.16b, v7.4b[2]\n"
".inst 0x4f86e158 // sdot v24.4s, v10.16b, v6.4b[0]\n"
".inst 0x4f86e957 // sdot v23.4s, v10.16b, v6.4b[2]\n"
".inst 0x4f85e156 // sdot v22.4s, v10.16b, v5.4b[0]\n"
".inst 0x4f85e955 // sdot v21.4s, v10.16b, v5.4b[2]\n"
"ldr q10, [%x[params], #0x20]\n"
".inst 0x4face17c // sdot v28.4s, v11.16b, v12.4b[1]\n"
".inst 0x4face97b // sdot v27.4s, v11.16b, v12.4b[3]\n"
".inst 0x4fa7e17a // sdot v26.4s, v11.16b, v7.4b[1]\n"
".inst 0x4fa7e979 // sdot v25.4s, v11.16b, v7.4b[3]\n"
".inst 0x4fa6e178 // sdot v24.4s, v11.16b, v6.4b[1]\n"
".inst 0x4fa6e977 // sdot v23.4s, v11.16b, v6.4b[3]\n"
".inst 0x4fa5e176 // sdot v22.4s, v11.16b, v5.4b[1]\n"
".inst 0x4fa5e975 // sdot v21.4s, v11.16b, v5.4b[3]\n"
"ldr q11, [%x[params], #0x30]\n"
".inst 0x4f87e11c // sdot v28.4s, v8.16b, v7.4b[0]\n"
".inst 0x4f87e91b // sdot v27.4s, v8.16b, v7.4b[2]\n"
".inst 0x4f86e11a // sdot v26.4s, v8.16b, v6.4b[0]\n"
".inst 0x4f86e919 // sdot v25.4s, v8.16b, v6.4b[2]\n"
".inst 0x4f85e118 // sdot v24.4s, v8.16b, v5.4b[0]\n"
".inst 0x4f85e917 // sdot v23.4s, v8.16b, v5.4b[2]\n"
".inst 0x4f84e116 // sdot v22.4s, v8.16b, v4.4b[0]\n"
".inst 0x4f84e915 // sdot v21.4s, v8.16b, v4.4b[2]\n"
"ldr q8, [%x[params], #0x40]\n"
".inst 0x4fa7e13c // sdot v28.4s, v9.16b, v7.4b[1]\n"
".inst 0x4fa7e93b // sdot v27.4s, v9.16b, v7.4b[3]\n"
".inst 0x4fa6e13a // sdot v26.4s, v9.16b, v6.4b[1]\n"
".inst 0x4fa6e939 // sdot v25.4s, v9.16b, v6.4b[3]\n"
".inst 0x4fa5e138 // sdot v24.4s, v9.16b, v5.4b[1]\n"
".inst 0x4fa5e937 // sdot v23.4s, v9.16b, v5.4b[3]\n"
".inst 0x4fa4e136 // sdot v22.4s, v9.16b, v4.4b[1]\n"
".inst 0x4fa4e935 // sdot v21.4s, v9.16b, v4.4b[3]\n"
"ldr q9, [%x[params], #0x50]\n"
"add %x[params], %x[params], #0x80\n"
".inst 0x4f86e15c // sdot v28.4s, v10.16b, v6.4b[0]\n"
".inst 0x4f86e95b // sdot v27.4s, v10.16b, v6.4b[2]\n"
".inst 0x4f85e15a // sdot v26.4s, v10.16b, v5.4b[0]\n"
".inst 0x4f85e959 // sdot v25.4s, v10.16b, v5.4b[2]\n"
".inst 0x4f84e158 // sdot v24.4s, v10.16b, v4.4b[0]\n"
".inst 0x4f84e957 // sdot v23.4s, v10.16b, v4.4b[2]\n"
".inst 0x4f82e156 // sdot v22.4s, v10.16b, v2.4b[0]\n"
".inst 0x4f82e955 // sdot v21.4s, v10.16b, v2.4b[2]\n"
".inst 0x4fa6e17c // sdot v28.4s, v11.16b, v6.4b[1]\n"
".inst 0x4fa6e97b // sdot v27.4s, v11.16b, v6.4b[3]\n"
".inst 0x4fa5e17a // sdot v26.4s, v11.16b, v5.4b[1]\n"
".inst 0x4fa5e979 // sdot v25.4s, v11.16b, v5.4b[3]\n"
".inst 0x4fa4e178 // sdot v24.4s, v11.16b, v4.4b[1]\n"
".inst 0x4fa4e977 // sdot v23.4s, v11.16b, v4.4b[3]\n"
".inst 0x4fa2e176 // sdot v22.4s, v11.16b, v2.4b[1]\n"
".inst 0x4fa2e975 // sdot v21.4s, v11.16b, v2.4b[3]\n"
".inst 0x4f85e11c // sdot v28.4s, v8.16b, v5.4b[0]\n"
".inst 0x4f85e91b // sdot v27.4s, v8.16b, v5.4b[2]\n"
".inst 0x4f84e11a // sdot v26.4s, v8.16b, v4.4b[0]\n"
".inst 0x4f84e919 // sdot v25.4s, v8.16b, v4.4b[2]\n"
".inst 0x4f82e118 // sdot v24.4s, v8.16b, v2.4b[0]\n"
".inst 0x4f82e917 // sdot v23.4s, v8.16b, v2.4b[2]\n"
".inst 0x4f81e116 // sdot v22.4s, v8.16b, v1.4b[0]\n"
".inst 0x4f81e915 // sdot v21.4s, v8.16b, v1.4b[2]\n"
".inst 0x4fa5e13c // sdot v28.4s, v9.16b, v5.4b[1]\n"
".inst 0x4fa5e93b // sdot v27.4s, v9.16b, v5.4b[3]\n"
".inst 0x4fa4e13a // sdot v26.4s, v9.16b, v4.4b[1]\n"
".inst 0x4fa4e939 // sdot v25.4s, v9.16b, v4.4b[3]\n"
".inst 0x4fa2e138 // sdot v24.4s, v9.16b, v2.4b[1]\n"
".inst 0x4fa2e937 // sdot v23.4s, v9.16b, v2.4b[3]\n"
".inst 0x4fa1e136 // sdot v22.4s, v9.16b, v1.4b[1]\n"
".inst 0x4fa1e935 // sdot v21.4s, v9.16b, v1.4b[3]\n"
"sqrdmulh v28.4s, v28.4s, v20.4s\n"
"sqrdmulh v27.4s, v27.4s, v20.4s\n"
"sqrdmulh v26.4s, v26.4s, v20.4s\n"
"sqrdmulh v25.4s, v25.4s, v20.4s\n"
"and v18.16b, v28.16b, v19.16b\n"
"and v17.16b, v27.16b, v19.16b\n"
"and v16.16b, v26.16b, v19.16b\n"
"sshr v18.4s, v18.4s, #0x1f\n"
"sshr v17.4s, v17.4s, #0x1f\n"
"sshr v16.4s, v16.4s, #0x1f\n"
"sqadd v28.4s, v28.4s, v18.4s\n"
"sqadd v27.4s, v27.4s, v17.4s\n"
"sqadd v26.4s, v26.4s, v16.4s\n"
"and v16.16b, v25.16b, v19.16b\n"
"srshl v28.4s, v28.4s, v19.4s\n"
"srshl v27.4s, v27.4s, v19.4s\n"
"srshl v26.4s, v26.4s, v19.4s\n"
"sshr v16.4s, v16.4s, #0x1f\n"
"add v28.4s, v28.4s, v0.4s\n"
"add v27.4s, v27.4s, v0.4s\n"
"add v26.4s, v26.4s, v0.4s\n"
"smin v28.4s, v28.4s, v30.4s\n"
"smin v27.4s, v27.4s, v30.4s\n"
"smin v26.4s, v26.4s, v30.4s\n"
"smax v28.4s, v28.4s, v31.4s\n"
"smax v27.4s, v27.4s, v31.4s\n"
"smax v26.4s, v26.4s, v31.4s\n"
"uzp1 v28.16b, v28.16b, v28.16b\n"
"uzp1 v27.16b, v27.16b, v27.16b\n"
"uzp1 v28.16b, v28.16b, v28.16b\n"
"uzp1 v27.16b, v27.16b, v27.16b\n"
"uzp1 v26.16b, v26.16b, v26.16b\n"
"sqadd v25.4s, v25.4s, v16.4s\n"
"uzp1 v26.16b, v26.16b, v26.16b\n"
"sqrdmulh v24.4s, v24.4s, v20.4s\n"
"sqrdmulh v23.4s, v23.4s, v20.4s\n"
"srshl v25.4s, v25.4s, v19.4s\n"
"sqrdmulh v22.4s, v22.4s, v20.4s\n"
"and v16.16b, v24.16b, v19.16b\n"
"and v17.16b, v23.16b, v19.16b\n"
"add v25.4s, v25.4s, v0.4s\n"
"sshr v16.4s, v16.4s, #0x1f\n"
"sshr v17.4s, v17.4s, #0x1f\n"
"smin v25.4s, v25.4s, v30.4s\n"
"sqadd v24.4s, v24.4s, v16.4s\n"
"sqadd v23.4s, v23.4s, v17.4s\n"
"smax v25.4s, v25.4s, v31.4s\n"
"and v16.16b, v22.16b, v19.16b\n"
"srshl v24.4s, v24.4s, v19.4s\n"
"uzp1 v25.16b, v25.16b, v25.16b\n"
"srshl v23.4s, v23.4s, v19.4s\n"
"uzp1 v25.16b, v25.16b, v25.16b\n"
"add v24.4s, v24.4s, v0.4s\n"
"sshr v16.4s, v16.4s, #0x1f\n"
"add v23.4s, v23.4s, v0.4s\n"
"smin v24.4s, v24.4s, v30.4s\n"
"sqadd v22.4s, v22.4s, v16.4s\n"
"smin v23.4s, v23.4s, v30.4s\n"
"smax v24.4s, v24.4s, v31.4s\n"
"sqrdmulh v21.4s, v21.4s, v20.4s\n"
"smax v23.4s, v23.4s, v31.4s\n"
"uzp1 v24.16b, v24.16b, v24.16b\n"
"srshl v22.4s, v22.4s, v19.4s\n"
"uzp1 v24.16b, v24.16b, v24.16b\n"
"uzp1 v23.16b, v23.16b, v23.16b\n"
"and v16.16b, v21.16b, v19.16b\n"
"uzp1 v23.16b, v23.16b, v23.16b\n"
"add v22.4s, v22.4s, v0.4s\n"
"sshr v16.4s, v16.4s, #0x1f\n"
"smin v22.4s, v22.4s, v30.4s\n"
"sqadd v21.4s, v21.4s, v16.4s\n"
"smax v22.4s, v22.4s, v31.4s\n"
"srshl v21.4s, v21.4s, v19.4s\n"
"uzp1 v22.16b, v22.16b, v22.16b\n"
"uzp1 v22.16b, v22.16b, v22.16b\n"
"add v21.4s, v21.4s, v0.4s\n"
"smin v21.4s, v21.4s, v30.4s\n"
"smax v21.4s, v21.4s, v31.4s\n"
"uzp1 v21.16b, v21.16b, v21.16b\n"
"uzp1 v21.16b, v21.16b, v21.16b\n"
"blt 3f\n"
"str s28, [x26, #0x0]\n"
"str s27, [x25, #0x0]\n"
"str s26, [x24, #0x0]\n"
"str s25, [x23, #0x0]\n"
"str s24, [x22, #0x0]\n"
"str s23, [x21, #0x0]\n"
"str s22, [x20, #0x0]\n"
"str s21, [x19, #0x0]\n"
"b 4f\n"
"3:" // Tail: Oddments
"st1 { v28.b }[0], [x26], #0x1\n"
"subs %x[n_channels], %x[n_channels], #0x1\n"
"st1 { v27.b }[0], [x25], #0x1\n"
"st1 { v26.b }[0], [x24], #0x1\n"
"st1 { v25.b }[0], [x23], #0x1\n"
"st1 { v24.b }[0], [x22], #0x1\n"
"st1 { v23.b }[0], [x21], #0x1\n"
"st1 { v22.b }[0], [x20], #0x1\n"
"st1 { v21.b }[0], [x19], #0x1\n"
"beq 4f\n"
"st1 { v28.b }[1], [x26], #0x1\n"
"subs %x[n_channels], %x[n_channels], #0x1\n"
"st1 { v27.b }[1], [x25], #0x1\n"
"st1 { v26.b }[1], [x24], #0x1\n"
"st1 { v25.b }[1], [x23], #0x1\n"
"st1 { v24.b }[1], [x22], #0x1\n"
"st1 { v23.b }[1], [x21], #0x1\n"
"st1 { v22.b }[1], [x20], #0x1\n"
"st1 { v21.b }[1], [x19], #0x1\n"
"beq 4f\n"
"st1 { v28.b }[2], [x26], #0x1\n"
"subs %x[n_channels], %x[n_channels], #0x1\n"
"st1 { v27.b }[2], [x25], #0x1\n"
"st1 { v26.b }[2], [x24], #0x1\n"
"st1 { v25.b }[2], [x23], #0x1\n"
"st1 { v24.b }[2], [x22], #0x1\n"
"st1 { v23.b }[2], [x21], #0x1\n"
"st1 { v22.b }[2], [x20], #0x1\n"
"st1 { v21.b }[2], [x19], #0x1\n"
"beq 4f\n"
"st1 { v28.b }[3], [x26], #0x1\n"
"subs %x[n_channels], %x[n_channels], #0x1\n"
"st1 { v27.b }[3], [x25], #0x1\n"
"st1 { v26.b }[3], [x24], #0x1\n"
"st1 { v25.b }[3], [x23], #0x1\n"
"st1 { v24.b }[3], [x22], #0x1\n"
"st1 { v23.b }[3], [x21], #0x1\n"
"st1 { v22.b }[3], [x20], #0x1\n"
"st1 { v21.b }[3], [x19], #0x1\n"
"4:" // Tail: End
"add SP, SP, #0x80\n"
: [n_channels] "+&r" (n_output_channels), [params] "+&r" (params)
: [inptrs] "r" (inptrs), [offsetof_Requantize32_b_offset] "I" (offsetof(arm_gemm::Requantize32, b_offset)), [offsetof_Requantize32_c_offset] "I" (offsetof(arm_gemm::Requantize32, c_offset)), [offsetof_Requantize32_maxval] "I" (offsetof(arm_gemm::Requantize32, maxval)), [offsetof_Requantize32_minval] "I" (offsetof(arm_gemm::Requantize32, minval)), [outptrs] "r" (outptrs), [qp] "r" (&qp)
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31", "x9", "x10", "x11", "x19", "x20", "x21", "x22", "x23", "x24", "x25", "x26", "x27", "x28"
);
}
} // namespace depthwise
} // namespace arm_conv
#endif // defined(__aarch64__)
| 42.890226 | 392 | 0.562478 | MaximMilashchenko |
b1a2f5d4b9059f0b8d6f941dbd7bcb020b3f3f5e | 5,809 | cpp | C++ | src/Factory/Module/Quantizer/Quantizer.cpp | OlivierHartmann/aff3ct | 58c66228b24e09463bd43ea6453ef18bcacd4d8f | [
"MIT"
] | null | null | null | src/Factory/Module/Quantizer/Quantizer.cpp | OlivierHartmann/aff3ct | 58c66228b24e09463bd43ea6453ef18bcacd4d8f | [
"MIT"
] | 4 | 2018-09-27T16:46:31.000Z | 2018-11-22T11:10:41.000Z | src/Factory/Module/Quantizer/Quantizer.cpp | OlivierHartmann/aff3ct | 58c66228b24e09463bd43ea6453ef18bcacd4d8f | [
"MIT"
] | null | null | null | #include <type_traits>
#include "Tools/Exception/exception.hpp"
#include "Module/Quantizer/Pow2/Quantizer_pow2.hpp"
#include "Module/Quantizer/Pow2/Quantizer_pow2_fast.hpp"
#include "Module/Quantizer/Custom/Quantizer_custom.hpp"
#include "Module/Quantizer/NO/Quantizer_NO.hpp"
#include "Quantizer.hpp"
using namespace aff3ct;
using namespace aff3ct::factory;
const std::string aff3ct::factory::Quantizer_name = "Quantizer";
const std::string aff3ct::factory::Quantizer_prefix = "qnt";
Quantizer::parameters
::parameters(const std::string &prefix)
: Factory::parameters(Quantizer_name, Quantizer_name, prefix)
{
}
Quantizer::parameters* Quantizer::parameters
::clone() const
{
return new Quantizer::parameters(*this);
}
void Quantizer::parameters
::get_description(tools::Argument_map_info &args) const
{
auto p = this->get_prefix();
args.add(
{p+"-size", "N"},
tools::Integer(tools::Positive(), tools::Non_zero()),
"number of real to quantize.",
tools::arg_rank::REQ);
args.add(
{p+"-fra", "F"},
tools::Integer(tools::Positive(), tools::Non_zero()),
"set the number of inter frame level to process.");
args.add(
{p+"-type"},
tools::Text(tools::Including_set("POW2", "CUSTOM")),
"type of the quantizer to use in the simulation.");
args.add(
{p+"-implem"},
tools::Text(tools::Including_set("STD", "FAST")),
"select the implementation of quantizer.");
args.add(
{p+"-dec"},
tools::Integer(tools::Positive()),
"the position of the fixed point in the quantified representation.");
args.add(
{p+"-bits"},
tools::Integer(tools::Positive(), tools::Non_zero()),
"the number of bits used for the quantizer.");
args.add(
{p+"-range"},
tools::Real(tools::Positive(), tools::Non_zero()),
"the min/max bound for the tricky quantizer.");
}
void Quantizer::parameters
::store(const tools::Argument_map_value &vals)
{
auto p = this->get_prefix();
if(vals.exist({p+"-range" })) this->range = vals.to_float({p+"-range" });
if(vals.exist({p+"-size", "N"})) this->size = vals.to_int ({p+"-size", "N"});
if(vals.exist({p+"-fra", "F"})) this->n_frames = vals.to_int ({p+"-fra", "F"});
if(vals.exist({p+"-dec" })) this->n_decimals = vals.to_int ({p+"-dec" });
if(vals.exist({p+"-bits" })) this->n_bits = vals.to_int ({p+"-bits" });
if(vals.exist({p+"-type" })) this->type = vals.at ({p+"-type" });
if(vals.exist({p+"-implem" })) this->implem = vals.at ({p+"-implem" });
}
void Quantizer::parameters
::get_headers(std::map<std::string,header_list>& headers, const bool full) const
{
auto p = this->get_prefix();
std::string quantif = "unused";
if (this->type == "CUSTOM")
quantif = "{"+std::to_string(this->n_bits)+", "+std::to_string(this->range)+"f}";
else if (this->type == "POW2")
quantif = "{"+std::to_string(this->n_bits)+", "+std::to_string(this->n_decimals)+"}";
headers[p].push_back(std::make_pair("Type", this->type));
headers[p].push_back(std::make_pair("Implementation", this->implem));
if (full) headers[p].push_back(std::make_pair("Frame size (N)", std::to_string(this->size)));
if (full) headers[p].push_back(std::make_pair("Inter frame level", std::to_string(this->n_frames)));
headers[p].push_back(std::make_pair("Fixed-point config.", quantif));
}
template <typename R, typename Q>
module::Quantizer<R,Q>* Quantizer::parameters
::build() const
{
if (this->type == "POW2" && this->implem == "STD" ) return new module::Quantizer_pow2 <R,Q>(this->size, this->n_decimals, this->n_bits, this->n_frames);
if (this->type == "POW2" && this->implem == "FAST") return new module::Quantizer_pow2_fast<R,Q>(this->size, this->n_decimals, this->n_bits, this->n_frames);
if (this->type == "CUSTOM" && this->implem == "STD" ) return new module::Quantizer_custom <R,Q>(this->size, this->range, this->n_bits, this->n_frames);
if (this->type == "NO" ) return new module::Quantizer_NO <R,Q>(this->size, this->n_frames);
throw tools::cannot_allocate(__FILE__, __LINE__, __func__);
}
template <typename R, typename Q>
module::Quantizer<R,Q>* Quantizer
::build(const parameters& params)
{
return params.template build<R,Q>();
}
// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef AFF3CT_MULTI_PREC
template aff3ct::module::Quantizer<R_8 ,Q_8 >* aff3ct::factory::Quantizer::parameters::build<R_8 ,Q_8 >() const;
template aff3ct::module::Quantizer<R_16,Q_16>* aff3ct::factory::Quantizer::parameters::build<R_16,Q_16>() const;
template aff3ct::module::Quantizer<R_32,Q_32>* aff3ct::factory::Quantizer::parameters::build<R_32,Q_32>() const;
template aff3ct::module::Quantizer<R_64,Q_64>* aff3ct::factory::Quantizer::parameters::build<R_64,Q_64>() const;
template aff3ct::module::Quantizer<R_8 ,Q_8 >* aff3ct::factory::Quantizer::build<R_8 ,Q_8 >(const aff3ct::factory::Quantizer::parameters&);
template aff3ct::module::Quantizer<R_16,Q_16>* aff3ct::factory::Quantizer::build<R_16,Q_16>(const aff3ct::factory::Quantizer::parameters&);
template aff3ct::module::Quantizer<R_32,Q_32>* aff3ct::factory::Quantizer::build<R_32,Q_32>(const aff3ct::factory::Quantizer::parameters&);
template aff3ct::module::Quantizer<R_64,Q_64>* aff3ct::factory::Quantizer::build<R_64,Q_64>(const aff3ct::factory::Quantizer::parameters&);
#else
template aff3ct::module::Quantizer<R,Q>* aff3ct::factory::Quantizer::parameters::build<R,Q>() const;
template aff3ct::module::Quantizer<R,Q>* aff3ct::factory::Quantizer::build<R,Q>(const aff3ct::factory::Quantizer::parameters&);
#endif
// ==================================================================================== explicit template instantiation
| 41.791367 | 159 | 0.659838 | OlivierHartmann |
b1a916adf403f5dca5537e84a501cfe606982722 | 275 | cpp | C++ | integration/src/angelscript-integration/glm/engine-library-math-vector-swizzle-operators-uvec-xyzw.cpp | Robert42/anglescript-integration | 5688bc3916a47c1cb1e7e08c017d01dcfd201097 | [
"MIT"
] | 1 | 2019-03-26T18:44:55.000Z | 2019-03-26T18:44:55.000Z | integration/src/angelscript-integration/glm/engine-library-math-vector-swizzle-operators-uvec-xyzw.cpp | Robert42/anglescript-integration | 5688bc3916a47c1cb1e7e08c017d01dcfd201097 | [
"MIT"
] | null | null | null | integration/src/angelscript-integration/glm/engine-library-math-vector-swizzle-operators-uvec-xyzw.cpp | Robert42/anglescript-integration | 5688bc3916a47c1cb1e7e08c017d01dcfd201097 | [
"MIT"
] | null | null | null | #include "engine-library-math-vector-swizzle-operators.h"
namespace AngelScriptIntegration {
void initVectorLibrary_swizzle_operators_uvec_xyzw(AngelScript::asIScriptEngine* as_engine)
{
int r;
ALL_SWIZZLE_FOR_VEC_XYZW(uvec);
}
} // namespace Angelscriptintegration
| 19.642857 | 91 | 0.818182 | Robert42 |
b1aeaf7c25e1177d262ae832410257749648e474 | 12,273 | cpp | C++ | src/common/classes/misc/string_test.cpp | AlexeyMochalov/firebird | 8b485a455c70d1eaf201192b46b5dd5fdf5ea386 | [
"Condor-1.1"
] | 988 | 2016-03-16T10:27:43.000Z | 2022-03-31T14:52:19.000Z | src/common/classes/misc/string_test.cpp | mistmist/firebird | d31495be14daa8bca46c879bdaf0e30194abd891 | [
"Condor-1.1"
] | 574 | 2016-03-23T15:35:56.000Z | 2022-03-31T07:11:03.000Z | src/common/classes/misc/string_test.cpp | mistmist/firebird | d31495be14daa8bca46c879bdaf0e30194abd891 | [
"Condor-1.1"
] | 241 | 2016-03-17T09:53:16.000Z | 2022-03-29T19:58:29.000Z | char lbl[] = "0123456789";
//#define CHECK_FATAL_RANGE_EXCEPTION
//Don't modify 3 lines upper from this - they are used in file read test
//If you plan to check range exception, you may uncomment it -
//anyway file test should not happen
/*
* PROGRAM: Class library integrity tests
* MODULE: string_test.cpp
* DESCRIPTION: test class Firebird::string
*
* The contents of this file are subject to the Initial
* Developer's Public License Version 1.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.ibphoenix.com/main.nfs?a=ibphoenix&page=ibp_idpl.
*
* Software distributed under the License is distributed AS IS,
* WITHOUT WARRANTY OF ANY KIND, either express or implied.
* See the License for the specific language governing rights
* and limitations under the License.
*
* The Original Code was created by Alexander Peshkoff
* for the Firebird Open Source RDBMS project.
*
* Copyright (c) 2004 Alexander Peshkoff <peshkoff@mail.ru>
* and all contributors signed below.
*
* All Rights Reserved.
* Contributor(s): ______________________________________.
*/
#if defined(FIRESTR) && defined(DEV_BUILD)
#define FULL_FIRE
#endif
#ifdef FIRESTR
#define NAME "Firebird::string"
#include "../common/classes/fb_string.h"
using namespace Firebird;
#else
#define NAME "std::basic_string"
#include <string>
typedef std::basic_string<char> string;
typedef string AbstractString;
#endif
#include <time.h>
#ifdef DEV_BUILD
void CheckStr(const AbstractString& check, const char* want, int line)
{
if (strlen(check.c_str()) != check.length()) {
printf("Length error at %d\n\n", line);
}
if (strcmp(check.c_str(), want)) {
printf("Wanted >%s<,\n got >%s< at %d\n\n", want, check.c_str(), line);
}
}
#define validate(a, b) CheckStr(a, b, __LINE__)
#else
#define validate(a, b)
#define check(a, b)
#endif
void test()
{
{
string a;
validate(a, "");
a = lbl;
string b = a;
validate(b, lbl);
string f = "0123456789";
validate(f, lbl);
string g("0123456789", 5);
validate(g, "01234");
string h(5, '7');
validate(h, "77777");
#ifdef FULL_FIRE
string i('7');
validate(i, "7");
#endif
string j(&lbl[3], &lbl[5]);
validate(j, "34");
}
{
string a = lbl;
string b;
b = a;
validate(b, lbl);
b = lbl;
validate(b, lbl);
a = 'X';
validate(a, "X");
a = b;
for (string::iterator x = b.begin(); x < b.end(); x++)
*x = 'u';
validate(a, lbl);
validate(b, "uuuuuuuuuu");
char y[20], *z = y;
const string c = a;
for (string::const_iterator x1 = c.begin(); x1 < c.end(); x1++)
*z++ = *x1;
*z = 0;
b = y;
validate(b, lbl);
}
#ifdef FULL_FIRE
{
const string a = lbl;
string b = a.at(5);
validate(b, "5");
}
{
string a = lbl;
string b = a.at(5);
validate(b, "5");
}
#endif
// conflict with J. requirement to string class - operator const char*
// {
// string a = lbl;
// char c = a[5];
// a[5] = 'u';
// validate(a, "01234u6789");
// }
{
string a = lbl;
char c = a[5]; // via operator const char*
a.at(5) = 'u';
a.at(7) = c;
validate(a, "01234u6589");
}
#ifdef CHECK_FATAL_RANGE_EXCEPTION
{
const string a = lbl;
string b = a.at(15);
}
#endif
{
string a = lbl;
a.resize(15, 'u');
validate(a, "0123456789uuuuu");
}
{
string a;
string x = lbl;
x += lbl;
x += lbl;
x += lbl;
x += lbl;
x += lbl;
x += lbl;
x += lbl;
x += lbl;
x += lbl;
x += lbl;
x += lbl; //120 bytes
a = x;
validate(a, x.c_str());
x = lbl;
x += lbl;
x += lbl;
x += lbl; //40 bytes
a = x;
validate(a, x.c_str());
}
{
string a = lbl;
const string b = a;
a += b;
validate(a, "01234567890123456789");
a = lbl;
a += lbl;
validate(a, "01234567890123456789");
a = lbl;
a += 'u';
validate(a, "0123456789u");
}
{
string a, b, c;
a = "uuu";
b = lbl;
c = a + b;
validate(c, "uuu0123456789");
c = a + lbl;
validate(c, "uuu0123456789");
c = b + 'u';
validate(c, "0123456789u");
c = lbl + a;
validate(c, "0123456789uuu");
c = 'u' + b;
validate(c, "u0123456789");
validate(a, "uuu");
validate(b, lbl);
}
{
string a = lbl;
const string b = a;
a.append(b);
validate(a, "01234567890123456789");
a = lbl;
a.append(lbl);
validate(a, "01234567890123456789");
a = lbl;
a.append(lbl, 6);
validate(a, "0123456789012345");
a = lbl;
a.append(b, 3, 2);
validate(a, "012345678934");
a = lbl;
a.append(b, 3, 20);
validate(a, "01234567893456789");
a = lbl;
a.append(3, 'u');
validate(a, "0123456789uuu");
a = lbl;
a.append(b.begin(), b.end());
validate(a, "01234567890123456789");
a = lbl;
a.append("Something reaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaally long");
validate(a, "0123456789Something reaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaally long");
a = lbl;
validate(a, lbl);
string c = lbl;
c += lbl;
c += lbl;
c += lbl;
a = lbl;
a.append("Something reaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaally long");
validate(a, "0123456789Something reaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaally long");
a = c;
validate(a, c.c_str());
}
{
string a, b;
b = lbl;
a.assign(3, 'u');
validate(a, "uuu");
a.assign(lbl);
validate(a, lbl);
a.assign(lbl, 2);
validate(a, "01");
a.assign(b, 3, 3);
validate(a, "345");
a.assign(b);
validate(a, lbl);
a = "";
validate(a, "");
string::iterator x = b.begin();
string::iterator y = b.end();
a.assign(x, y);
validate(a, lbl);
}
{
string a, b = lbl;
a = lbl;
a.insert(5, 3, 'u');
validate(a, "01234uuu56789");
a = lbl;
a.insert(3, lbl);
validate(a, "01201234567893456789");
a = lbl;
a.insert(4, lbl, 2);
validate(a, "012301456789");
a = lbl;
a.insert(5, b, 3, 3);
validate(a, "0123434556789");
a = lbl;
a.insert(5, b);
validate(a, "01234012345678956789");
a = lbl;
a.insert(2, "Something reaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaally long");
validate(a, "01Something reaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaally long23456789");
a = lbl;
string::iterator x = a.begin();
x++;
a.insert(x, 5, 'u');
validate(a, "0uuuuu123456789");
a = lbl;
x = a.begin();
x += 2;
string::iterator f = b.begin();
string::iterator t = b.end();
f++; t--;
a.insert(x, f, t);
validate(a, "011234567823456789");
a = lbl;
a.erase();
validate(a, "");
a = lbl;
a.erase(3, 6);
validate(a, "0129");
a = lbl;
a.erase(3, 16);
validate(a, "012");
a = lbl;
a.erase(3);
validate(a, "012");
a = lbl;
x = a.begin();
x += 3;
a.erase(x);
validate(a, "012456789");
a = lbl;
x = a.begin();
x += 3;
string::iterator y = a.end();
y -= 2;
a.erase(x, y);
validate(a, "01289");
}
{
string a;
const string b = lbl;
string::iterator f0, t0;
string::const_iterator f, t;
a = lbl;
a.replace(5, 2, 3, 'u');
validate(a, "01234uuu789");
a = lbl;
f0 = a.begin() + 5;
t0 = f0 + 2;
a.replace(f0, t0, 3, 'u');
validate(a, "01234uuu789");
a = lbl;
a.replace(3, 3, lbl);
validate(a, "01201234567896789");
a = lbl;
f0 = a.begin() + 3;
t0 = f0 + 3;
a.replace(f0, t0, lbl);
validate(a, "01201234567896789");
a = lbl;
a.replace(4, 4, lbl, 2);
validate(a, "01230189");
a = lbl;
f0 = a.begin() + 4;
t0 = f0 + 4;
a.replace(f0, t0, lbl, 2);
validate(a, "01230189");
a = lbl;
a.replace(5, 10, b, 3, 3);
validate(a, "01234345");
a = lbl;
f0 = a.begin() + 5;
t0 = f0 + 10;
f = b.begin() + 3;
t = f + 3;
a.replace(f0, t0, f, t);
validate(a, "01234345");
a = lbl;
a.replace(5, 0, b);
validate(a, "01234012345678956789");
a = lbl;
f0 = a.begin() + 5;
t0 = f0;
a.replace(f0, t0, b);
validate(a, "01234012345678956789");
a = lbl;
a.replace(2, 1, "Something reaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaally long");
validate(a, "01Something reaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaally long3456789");
}
{
string a, b = lbl;
char s[40];
memset(s, 0, 40);
#ifdef FULL_FIRE
b.copyTo(s, 5);
a = s;
validate(a, "0123");
b.copyTo(s, 40);
a = s;
validate(a, lbl);
#endif
// a.swap(b);
// validate(b, "3456789");
// validate(a, lbl);
}
#ifdef DEV_BUILD
#undef check
#define check(a, b) if (a != b) printf("Wanted %d got %d at %d\n\n", b, a, __LINE__)
#endif
{
string a = "012345uuu345678";
// 9
string b = "345";
check(a.find(b), 3);
check(a.find("45"), 4);
check(a.find('5'), 5);
check(a.find("ZZ"), string::npos);
check(a.rfind(b), 9);
check(a.rfind("45"), 10);
check(a.rfind('5'), 11);
check(a.rfind("ZZ"), string::npos);
check(a.find("45", 8), 10);
check(a.find_first_of("aub"), 6);
check(a.find_first_of(b), 3);
check(a.find_first_of("54"), 4);
check(a.find_first_of('5'), 5);
check(a.find_first_of("ZZ"), string::npos);
check(a.find_last_of("aub"), 8);
check(a.find_last_of(b), 11);
check(a.find_last_of("54"), 11);
check(a.find_last_of('5'), 11);
check(a.find_last_of("ZZ"), string::npos);
check(a.find_first_of("45", 8), 10);
b = "010";
check(a.find_first_not_of("aub"), 0);
check(a.find_first_not_of(b), 2);
check(a.find_first_not_of("0102"), 3);
check(a.find_first_not_of('0'), 1);
check(a.find_first_not_of(a), string::npos);
b = "878";
check(a.find_last_not_of("aub"), 14);
check(a.find_last_not_of(b), 12);
check(a.find_last_not_of("78"), 12);
check(a.find_last_not_of('8'), 13);
check(a.find_last_not_of(a), string::npos);
check(a.find_first_not_of("u345", 8), 12);
}
{
string a = lbl;
string b;
b = a.substr(3, 4);
validate(b, "3456");
b = a.substr(5, 20);
validate(b, "56789");
#ifdef FULL_FIRE
b = a.substr(50, 20);
validate(b, "");
#endif
}
#ifdef FULL_FIRE
{
string b;
FILE *x = fopen("string_test.cpp", "rt");
b.LoadFromFile(x);
validate(b, "char lbl[] = \"0123456789\";");
b.LoadFromFile(x);
validate(b, "");
b.LoadFromFile(x);
validate(b, "//#define CHECK_FATAL_RANGE_EXCEPTION");
fclose(x);
}
#endif
{
string a = "Something moderaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaately long";
string a1 = a;
string b = a + a1;
string b1 = b;
string c = b + b1;
string d = c;
string e = c;
string f = c;
string g = c;
string h = c;
string i = c;
string j = c;
string k = c;
string l = c;
string m = c;
string n = c;
string o = c;
string p = c;
}
#ifdef DEV_BUILD
#undef check
#define check(get, want) if ( (get < 0 ? -1 : get > 0 ? 1 : 0) != want)\
printf("Wanted %d got %d at %d\n\n", want, get, __LINE__)
#endif
#ifdef FULL_FIRE
{
PathName c = "Aa";
PathName d = "AB";
check(c.compare(d), -1);
}
#endif
{
string a = lbl;
string b = a;
string c = "Aaa";
string d = "AB";
string e = "Aa";
check(a.compare(b), 0);
check(a.compare(c), -1);
check(c.compare(a), 1);
check(c.compare(d), 1);
check(c.compare(e), 1);
check(a.compare(1, 10, b), 1);
check(a.compare(1, 10, b, 1, 10), 0);
check(a.compare(lbl), 0);
check(a.compare(1, 3, lbl + 1, 3), 0);
}
#ifdef FULL_FIRE
{
string a = " 011100 ", b;
b = a;
b.ltrim();
validate(b, "011100 ");
b = a;
b.rtrim();
validate(b, " 011100");
b = a;
b.trim(" 0");
validate(b, "111");
b = a;
b.alltrim("02 ");
validate(b, "111");
b = a;
b.trim("012");
validate(b, " 011100 ");
validate(a, " 011100 ");
}
{
string a = lbl;
a += '\377';
string b = a;
a += " ";
a.rtrim();
validate(a, b.c_str());
}
{
string a = "AaBbCc", b;
b = a;
b.lower();
validate(b, "aabbcc");
b = a;
b.upper();
validate(b, "AABBCC");
validate(a, "AaBbCc");
}
#endif
}
clock_t t;
void start()
{
t = clock();
}
#ifdef DEV_BUILD
#define TEST_ITEMS 1
#else
#define TEST_ITEMS 100000
#endif
void report()
{
clock_t d = clock();
printf("Test of %d iterations with %s took %d milliseconds.\n",
TEST_ITEMS, NAME, (int) (d - t) * 1000 / CLOCKS_PER_SEC);
}
int main(int ac, char **av)
{
int n = TEST_ITEMS;
start();
while (n--) {
test();
}
report();
#if defined(DEV_BUILD) && defined(FIRESTR)
getDefaultMemoryPool()->print_contents(stdout, 0);
#endif
printf("Press enter to continue\n");
getchar();
return 0;
}
| 18.128508 | 90 | 0.589831 | AlexeyMochalov |
b1aed871b014f19bf3f4ce3d9054d403e3bd5471 | 453 | hpp | C++ | Bonus.hpp | polinaucc/galaga | 6feea0a6a74669c5d3fa6e106653ceacda19b416 | [
"MIT"
] | null | null | null | Bonus.hpp | polinaucc/galaga | 6feea0a6a74669c5d3fa6e106653ceacda19b416 | [
"MIT"
] | null | null | null | Bonus.hpp | polinaucc/galaga | 6feea0a6a74669c5d3fa6e106653ceacda19b416 | [
"MIT"
] | null | null | null | #pragma once
#include "movingobject.hpp"
enum class BonusType
{
life,
score
};
class Bonus : public MovingObject
{
protected:
BonusType m_type;
public:
Bonus(double x, double y, double s, std::shared_ptr<Sprite> sprite, BonusType type):
MovingObject(x, y, 0.0, s, sprite), m_type(type)
{}
virtual BonusType type() const { return m_type; }
static shared_ptr<Bonus> create (double x, double y, double s, BonusType type);
};
| 22.65 | 88 | 0.688742 | polinaucc |
b1b23b1e570ee3407d36e6a469549691513e2688 | 452 | cpp | C++ | solutions/0009.palindrome-number/0009.palindrome-number.1521550303.cpp | nettee/leetcode | 19aa8d54d64cce3679db5878ee0194fad95d8fa1 | [
"MIT"
] | 1 | 2021-01-14T06:01:02.000Z | 2021-01-14T06:01:02.000Z | solutions/0009.palindrome-number/0009.palindrome-number.1521550303.cpp | nettee/leetcode | 19aa8d54d64cce3679db5878ee0194fad95d8fa1 | [
"MIT"
] | 8 | 2018-03-27T11:47:19.000Z | 2018-11-12T06:02:12.000Z | solutions/0009.palindrome-number/0009.palindrome-number.1521550303.cpp | nettee/leetcode | 19aa8d54d64cce3679db5878ee0194fad95d8fa1 | [
"MIT"
] | 2 | 2020-04-30T09:47:01.000Z | 2020-12-03T09:34:08.000Z | class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) {
return false;
}
vector<int> digits;
while (x > 0) {
int d = x % 10;
digits.push_back(d);
x = x / 10;
}
for (int i = 0, j = digits.size() - 1; i < j; i++, j--) {
if (digits[i] != digits[j]) {
return false;
}
}
return true;
}
};
| 21.52381 | 65 | 0.362832 | nettee |
b1b3a11ce454a516918aa04720816b6d84c3958c | 4,803 | cpp | C++ | ToolKit/PropertyGrid/XTPPropertyGridItemFont.cpp | 11Zero/DemoBCG | 8f41d5243899cf1c82990ca9863fb1cb9f76491c | [
"MIT"
] | 2 | 2018-03-30T06:40:08.000Z | 2022-02-23T12:40:13.000Z | ToolKit/PropertyGrid/XTPPropertyGridItemFont.cpp | 11Zero/DemoBCG | 8f41d5243899cf1c82990ca9863fb1cb9f76491c | [
"MIT"
] | null | null | null | ToolKit/PropertyGrid/XTPPropertyGridItemFont.cpp | 11Zero/DemoBCG | 8f41d5243899cf1c82990ca9863fb1cb9f76491c | [
"MIT"
] | 1 | 2020-08-11T05:48:02.000Z | 2020-08-11T05:48:02.000Z | // XTPPropertyGridItemFont.cpp : implementation of the CXTPPropertyGridItemFont class.
//
// This file is a part of the XTREME PROPERTYGRID MFC class library.
// (c)1998-2011 Codejock Software, All Rights Reserved.
//
// THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE
// RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN
// CONSENT OF CODEJOCK SOFTWARE.
//
// THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED
// IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO
// YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A
// SINGLE COMPUTER.
//
// CONTACT INFORMATION:
// support@codejock.com
// http://www.codejock.com
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Common/XTPVC80Helpers.h"
#include "Common/XTPDrawHelpers.h"
#include "XTPPropertyGridInplaceEdit.h"
#include "XTPPropertyGridInplaceButton.h"
#include "XTPPropertyGridInplaceList.h"
#include "XTPPropertyGridItem.h"
#include "XTPPropertyGridItemFont.h"
#include "XTPPropertyGrid.h"
#include "XTPPropertyGridDefines.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CXTPPropertyGridItemFont
IMPLEMENT_DYNAMIC(CXTPPropertyGridItemFont, CXTPPropertyGridItem)
CXTPPropertyGridItemFont::CXTPPropertyGridItemFont(LPCTSTR strCaption, LOGFONT& font)
: CXTPPropertyGridItem(strCaption)
{
SetFont(font);
m_nFlags = xtpGridItemHasExpandButton;
m_clrValue = (COLORREF)-1;
EnableAutomation();
m_strDefaultValue = m_strValue;
}
CXTPPropertyGridItemFont::CXTPPropertyGridItemFont(UINT nID, LOGFONT& font)
: CXTPPropertyGridItem(nID)
{
SetFont(font);
m_nFlags = xtpGridItemHasExpandButton;
m_clrValue = (COLORREF)-1;
EnableAutomation();
m_strDefaultValue = m_strValue;
}
CXTPPropertyGridItemFont::~CXTPPropertyGridItemFont()
{
}
/////////////////////////////////////////////////////////////////////////////
//
void CXTPPropertyGridItemFont::SetFont(LOGFONT& font)
{
MEMCPY_S(&m_lfValue, &font, sizeof(LOGFONT));
m_strValue = FontToString(m_lfValue);
}
CString CXTPPropertyGridItemFont::FontToString(const LOGFONT& lfValue)
{
CWindowDC dc(CWnd::GetDesktopWindow());
int nHeight = -MulDiv(lfValue.lfHeight, 72, dc.GetDeviceCaps(LOGPIXELSY));
CString strValue;
strValue.Format(_T("%s; %ipt"), lfValue.lfFaceName, nHeight);
if (lfValue.lfWeight == FW_BOLD)
strValue += _T("; bold");
return strValue;
}
BOOL CXTPPropertyGridItemFont::OnDrawItemValue(CDC& dc, CRect rcValue)
{
if (m_clrValue == (COLORREF)-1)
return CXTPPropertyGridItem::OnDrawItemValue(dc, rcValue);
COLORREF clr = dc.GetTextColor();
CRect rcSample(rcValue.left - 2, rcValue.top + 1, rcValue.left + 18, rcValue.bottom - 1);
CXTPPenDC pen(dc, clr);
CXTPBrushDC brush(dc, m_clrValue);
dc.Rectangle(rcSample);
CRect rcText(rcValue);
rcText.left += 25;
dc.DrawText(m_strValue, rcText, DT_SINGLELINE | DT_VCENTER);
return TRUE;
}
CRect CXTPPropertyGridItemFont::GetValueRect()
{
CRect rcValue(CXTPPropertyGridItem::GetValueRect());
if (m_clrValue != (COLORREF)-1) rcValue.left += 25;
return rcValue;
}
UINT_PTR CALLBACK CXTPPropertyGridItemFont::FontDlgProc(HWND hWnd, UINT message, WPARAM, LPARAM)
{
// special case for WM_INITDIALOG
if (message == WM_INITDIALOG)
{
HWND hWndCombo = GetDlgItem(hWnd, 1139);
if (hWndCombo)
EnableWindow(hWndCombo, FALSE);
CDialog* pDlg = DYNAMIC_DOWNCAST(CDialog, CWnd::FromHandlePermanent(hWnd));
if (pDlg != NULL)
return (UINT_PTR)pDlg->OnInitDialog();
else
return 1;
}
return 0;
}
void CXTPPropertyGridItemFont::OnInplaceButtonDown(CXTPPropertyGridInplaceButton* pButton)
{
if (m_pGrid->SendNotifyMessage(XTP_PGN_INPLACEBUTTONDOWN, (LPARAM)pButton) == TRUE)
return;
if (!OnRequestEdit())
return;
InternalAddRef();
CFontDialog dlg(&m_lfValue, CF_EFFECTS | CF_SCREENFONTS, NULL, m_pGrid);
if (m_clrValue == (COLORREF)-1)
{
dlg.m_cf.lpfnHook = FontDlgProc;
}
else
{
dlg.m_cf.rgbColors = m_clrValue;
}
if (dlg.DoModal() == IDOK)
{
LOGFONT lf;
dlg.GetCurrentFont(&lf);
CString strValue = FontToString(lf);
if (OnAfterEdit(strValue))
{
SetFont(lf);
if (m_clrValue != (COLORREF)-1)
m_clrValue = dlg.GetColor();
OnValueChanged(strValue);
SAFE_INVALIDATE(m_pGrid);
}
}
else
{
OnCancelEdit();
}
InternalRelease();
}
void CXTPPropertyGridItemFont::SetColor(COLORREF clr)
{
m_clrValue = clr;
SAFE_INVALIDATE(m_pGrid);
}
COLORREF CXTPPropertyGridItemFont::GetColor()
{
return m_clrValue;
}
void CXTPPropertyGridItemFont::GetFont(LOGFONT* lf)
{
ASSERT(lf != NULL);
MEMCPY_S(lf, &m_lfValue, sizeof(LOGFONT));
}
| 23.544118 | 96 | 0.713721 | 11Zero |
04d98ffcbee295d9abca30fd92b2cc6fa7bf997f | 568 | hpp | C++ | Editor/Source/ImGui/Utility/Draw.hpp | AhsanSarwar45/Qombat-OLD | 0247441cf4927733ef0786c6df9a087461b0260b | [
"Apache-2.0"
] | null | null | null | Editor/Source/ImGui/Utility/Draw.hpp | AhsanSarwar45/Qombat-OLD | 0247441cf4927733ef0786c6df9a087461b0260b | [
"Apache-2.0"
] | null | null | null | Editor/Source/ImGui/Utility/Draw.hpp | AhsanSarwar45/Qombat-OLD | 0247441cf4927733ef0786c6df9a087461b0260b | [
"Apache-2.0"
] | null | null | null | #include <stdarg.h>
#include <ImGui/imgui.h>
#include <Qombat/Core.hpp>
#include "Mouse.hpp"
namespace QCreate
{
namespace ImGuiHelper
{
inline void DrawHoverableRect(const ImVec2& a, const ImVec2& b, const ImColor& color, const char* tooltip, ...)
{
ImDrawList* drawList = ImGui::GetWindowDrawList();
drawList->AddRectFilled(a, b, color);
if (ImGuiHelper::IsRectHovered(a, b))
{
va_list args;
va_start(args, tooltip);
ImGui::SetTooltipV(tooltip, args);
va_end(args);
}
}
} // namespace ImGuiHelper
} // namespace QCreate | 19.586207 | 113 | 0.679577 | AhsanSarwar45 |
04e77c5c080e38f14b8cade8354e2fb7c1f493ab | 16,645 | cpp | C++ | src/RenderPrimitives.cpp | Cavantar/SoftRenderer | d6ef9a76ec11088d3af7a59b17c15bb38b5856de | [
"WTFPL"
] | null | null | null | src/RenderPrimitives.cpp | Cavantar/SoftRenderer | d6ef9a76ec11088d3af7a59b17c15bb38b5856de | [
"WTFPL"
] | null | null | null | src/RenderPrimitives.cpp | Cavantar/SoftRenderer | d6ef9a76ec11088d3af7a59b17c15bb38b5856de | [
"WTFPL"
] | null | null | null |
#include "RenderPrimitives.h"
#include <algorithm>
void
TextureBuffer::setPixel(uint32 x, uint32 y, const Vec3f& color)
{
if(x >= 0 && x < dimensions.x &&
y >= 0 && y < dimensions.y)
{
pixelData[x + (uint32)dimensions.x * y] =
(uint32)(color.x) << 24 | (uint32)(color.y) << 16 | (uint32)(color.z) << 8;
}
}
Vec3f
TextureBuffer::getPixel(uint32 x, uint32 y) const
{
uint32 color = pixelData[x + (uint32)dimensions.x * y];
Vec3f result(uint8(color >> 24), uint8(color >> 16), uint8(color >> 8));
return result;
}
Vec3f
TextureBuffer::getPixelUV(const Vec2f& uv) const
{
uint32 x = std::max(fmodf(uv.x, 1.0f), 0.0f) * (real32)dimensions.x;
uint32 y = std::max(fmodf(uv.y, 1.0f), 0.0f) * (real32)dimensions.y;
return getPixel(x, y);
}
void
TextureBuffer::blitTexture(TextureBuffer* dst, TextureBuffer* src, const Vec2i& position)
{
Vec2i srcDimensions = src->dimensions;
for(int y = 0; y < srcDimensions.y; y++)
{
for(int x = 0; x < srcDimensions.x; x++)
{
Vec3f srcColor = src->getPixel(x, y);
dst->setPixel(x + position.x, y + position.y, srcColor);
}
}
}
Polygon2D
Polygon2D::toScreenSpace(const Vec2i& screenDimensions) const
{
real32 aspectRatio = (real32)screenDimensions.x / screenDimensions.y;
real32 halfResX = screenDimensions.x * 0.5f;
real32 halfResY = screenDimensions.y * 0.5f;
uint32 vertexCount = vertices.size();
Polygon2D result;
result.vertices.resize(vertexCount);
for(uint32 i = 0; i < vertexCount; i++)
{
const Vec2f& src = vertices[i];
// std::cout << "src: " << src.x << " " << src.y << std::endl;
Vec2f& dst = result.vertices[i];
// // Transforming Into ScreenSpace
dst.x = (src.x * halfResX) + halfResX;
dst.y = ((-src.y * aspectRatio) * halfResY) + halfResY;
// std::cout << "dst: " << dst.x << " " << dst.y << "\n\n";
}
return result;
}
Polygon2D
Polygon3D::toPolygon2D() const
{
Polygon2D result;
uint32 verticyCount = vertices.size();
result.vertices.resize(vertices.size());
for(int i = 0; i < verticyCount; i++)
{
result.vertices[i] = vertices[i].toVec2();
}
return result;
}
MappedVertex
MappedVertex::operator-(const MappedVertex& vertex) const
{
MappedVertex result = *this;
result.position -= vertex.position;
result.uv -= vertex.uv;
result.normal -= vertex.normal;
return result;
}
MappedVertex
MappedVertex::operator+(const MappedVertex& vertex) const
{
MappedVertex result = *this;
result.position += vertex.position;
result.uv += vertex.uv;
result.normal += vertex.normal;
return result;
}
MappedVertex
MappedVertex::operator*(real32 scalar) const
{
MappedVertex result = *this;
result.position *= scalar;
result.uv *= scalar;
result.normal *= scalar;
return result;
}
MappedVertex
MappedVertex::lerp(const MappedVertex& v1, const MappedVertex& v2, real32 t)
{
MappedVertex result;
MappedVertex deltaVertex = v2 - v1;
result = v1 + (deltaVertex * t);
return result;
}
Polygon3D
Polygon3D::clip(real32 nearZ) const
{
Polygon3D result;
uint32 verticyCount = vertices.size();
for(auto i = 0; i < verticyCount; i++)
{
const Vec3f& v1 = vertices[i];
const Vec3f& v2 = vertices[(i + 1)%verticyCount];
// result.vertices.push_back(v1);
// continue;
// Ignore if both
if(v1.z >= nearZ && v2.z >= nearZ)
{
result.vertices.push_back(v1);
}
else if(v1.z >= nearZ && v2.z < nearZ)
{
result.vertices.push_back(v1);
real32 t = (v1.z - nearZ) / (v1.z - v2.z);
// std::cout << "tf: " << t << std::endl;
Vec3f delta = v2 - v1;
Vec3f addedVertex = v1 + (delta * t);
result.vertices.push_back(addedVertex);
}
// v1.z < nearZ && v2 >= nearZ
else if(v1.z < nearZ && v2.z >= nearZ)
{
real32 t = (v2.z - nearZ) / (v2.z - v1.z);
// std::cout << "t: " << t << std::endl;
Vec3f delta = v1 - v2;
Vec3f addedVertex = v2 + (delta * t);
result.vertices.push_back(addedVertex);
}
}
return result;
}
MappedPolygon
MappedTriangle::toPolygon() const
{
MappedPolygon polygon;
polygon.vertices.resize(3);
for(int i = 0; i < 3; i++)
{
polygon.vertices[i] = vertices[i];
}
return polygon;
}
MappedPolygon
MappedPolygon::clipNear(const MappedPolygon& polygon, real32 nearZ)
{
MappedPolygon result;
std::vector<MappedVertex> dstVertices;
const std::vector<MappedVertex>& srcVertices = polygon.vertices;
uint32 vertexCount = srcVertices.size();
for(auto i = 0; i < vertexCount; i++)
{
uint32 nextVertexIndex = (i + 1)%vertexCount;
const Vec3f& v1 = srcVertices[i].position;
const Vec3f& v2 = srcVertices[nextVertexIndex].position;
// Ignore if both
if(v1.z >= nearZ && v2.z >= nearZ)
{
dstVertices.push_back(srcVertices[i]);
}
else if(v1.z >= nearZ && v2.z < nearZ)
{
dstVertices.push_back(srcVertices[i]);
real32 deltaZ = v1.z - v2.z;
real32 t = (v1.z - nearZ) / deltaZ;
MappedVertex addedVertex = MappedVertex::lerp(srcVertices[i], srcVertices[nextVertexIndex], t);
dstVertices.push_back(addedVertex);
}
else if(v1.z < nearZ && v2.z >= nearZ)
{
real32 deltaZ = v2.z - v1.z;
real32 t = (v2.z - nearZ) / deltaZ;
MappedVertex addedVertex = MappedVertex::lerp(srcVertices[nextVertexIndex], srcVertices[i], t);
dstVertices.push_back(addedVertex);
}
}
result.vertices = dstVertices;
return result;
}
MappedPolygon
MappedPolygon::clipSide(const MappedPolygon& polygon, real32 dfc)
{
MappedPolygon result;
std::vector<MappedVertex> dstVertices;
const std::vector<MappedVertex>& srcVertices = polygon.vertices;
uint32 vertexCount = srcVertices.size();
real32 a1 = dfc * -1.0f;
for(auto i = 0; i < vertexCount; i++)
{
uint32 nextVertexIndex = (i + 1)%vertexCount;
const Vec3f& v1 = srcVertices[i].position;
const Vec3f& v2 = srcVertices[nextVertexIndex].position;
// x is conventional x in linear equation, z is my result
real32 minZV1 = a1 * v1.x;
real32 minZV2 = a1 * v2.x;
// Ignore if both
if(v1.z >= minZV1 && v2.z >= minZV2)
{
dstVertices.push_back(srcVertices[i]);
}
else if(v1.z >= minZV1 && v2.z < minZV2)
{
dstVertices.push_back(srcVertices[i]);
real32 dx = v1.x - v2.x;
real32 dz = v1.z - v2.z;
real32 a2 = 0;
real32 t = 0;
real32 z = 0;
real32 x = 0;
// If it's not aligned horizontally or vertically
if(dx != 0 && dz != 0)
{
a2 = dz/dx;
const Vec3f& startPosition = v2;
x = ((-a2*startPosition.x) + startPosition.z) / (a1 - a2);
t = (v1.x - x) / dx;
}
else
{
if(dx == 0)
{
// Vertical Alignment
x = v1.x; // Both Vertices have the same x
// LinearEquation
z = a1 * x;
t = (v1.z - z) / dz;
}
else
{
// Horizontal Alignment
z = v1.z; // Both Vertices have the same z
// LinearEquation - Solved For X
x = z / a1;
t = (v1.x - x) / dx;
}
}
MappedVertex addedVertex = MappedVertex::lerp(srcVertices[i], srcVertices[nextVertexIndex], t);
dstVertices.push_back(addedVertex);
}
else if(v1.z < minZV1 && v2.z >= minZV2)
{
real32 dx = (v2.x - v1.x);
real32 dz = (v2.z - v1.z);
real32 a2 = 0;
real32 t = 0;
real32 z = 0;
real32 x = 0;
const Vec3f& startPosition = v1;
if(dx != 0 && dz != 0)
{
a2 = dz/dx;
x = ((-a2*startPosition.x) + startPosition.z) / (a1 - a2);
t = (v2.x - x) / dx;
}
else
{
if(dx == 0)
{
// Vertical Alignment
x = startPosition.x;
z = a1 * x;
t = (v2.z - z) / dz;
}
else
{
z = startPosition.z;
x = z / a1;
t = (v2.x - x) / dx;
}
}
MappedVertex addedVertex = MappedVertex::lerp(srcVertices[nextVertexIndex], srcVertices[i], t);
dstVertices.push_back(addedVertex);
}
}
result.vertices = dstVertices;
return result;
}
MappedPolygon
MappedPolygon::clip(real32 nearZ, real32 dfc) const
{
MappedPolygon nearClipped = clipNear(*this, nearZ);
// sdfc *= 1.1f;
MappedPolygon leftClipped = clipSide(nearClipped, dfc);
leftClipped = clipSide(leftClipped, -dfc);
return leftClipped;
}
Polygon2D
MappedPolygon::toPolygon2D() const
{
Polygon2D result;
uint32 verticyCount = vertices.size();
result.vertices.resize(vertices.size());
for(int i = 0; i < verticyCount; i++)
{
result.vertices[i] = vertices[i].position.toVec2();
}
return result;
}
MappedPolygon
MappedPolygon::toScreenSpace(const Vec2i& screenDimensions) const
{
real32 aspectRatio = (real32)screenDimensions.x / screenDimensions.y;
uint32 vertexCount = vertices.size();
MappedPolygon result;
result.vertices.resize(vertexCount);
for(uint32 i = 0; i != vertexCount; i++)
{
const Vec3f& src = vertices[i].position;
result.vertices[i] = vertices[i];
Vec3f& dst = result.vertices[i].position;
// // Transforming Into ScreenSpace
dst.x = (src.x * screenDimensions.x * 0.5) + screenDimensions.x * 0.5;
dst.y = ((-src.y * aspectRatio) * screenDimensions.y * 0.5) + screenDimensions.y * 0.5;
}
return result;
}
Range2d
MathHelper::getRange2d(const Vertices2D& vertices)
{
Range2d result = {};
if(vertices.size() == 0) return result;
result.x.max = vertices[0].x;
result.x.min = vertices[0].x;
result.y.max = vertices[0].y;
result.y.min = vertices[0].y;
for(auto it = vertices.begin()+1; it != vertices.end(); it++)
{
const Vec2f& currentVector = *it;
result.x.max = std::max(currentVector.x, result.x.max);
result.x.min = std::min(currentVector.x, result.x.min);
result.y.max = std::max(currentVector.y, result.y.max);
result.y.min = std::min(currentVector.y, result.y.min);
}
return result;
}
Range2d
MathHelper::getRange2d(const MappedVertices& vertices)
{
Range2d result = {};
if(vertices.size() == 0) return result;
result.x.max = vertices[0].position.x;
result.x.min = vertices[0].position.x;
result.y.max = vertices[0].position.y;
result.y.min = vertices[0].position.y;
for(auto it = vertices.begin()+1; it != vertices.end(); it++)
{
const Vec3f& currentVector = it->position;
result.x.max = std::max(currentVector.x, result.x.max);
result.x.min = std::min(currentVector.x, result.x.min);
result.y.max = std::max(currentVector.y, result.y.max);
result.y.min = std::min(currentVector.y, result.y.min);
}
return result;
}
Vec3f
MeshHelper::getCrossProduct(const Vertices& vertices, const IndexedTriangle& indexedTriangle)
{
Vec3f v1 = vertices[indexedTriangle.indexes[1]] - vertices[indexedTriangle.indexes[0]];
Vec3f v2 = vertices[indexedTriangle.indexes[2]] - vertices[indexedTriangle.indexes[0]];
Vec3f result = Vec3f::cross(v1, v2);
return result;
}
Vec3f
MeshHelper::getCrossProduct(const MappedTriangle& triangle)
{
Vec3f v1 = triangle.vertices[1].position - triangle.vertices[0].position;
Vec3f v2 = triangle.vertices[2].position - triangle.vertices[0].position;
Vec3f result = Vec3f::cross(v1, v2);
return result;
}
Vec3f
MeshHelper::castVertex(const Vec3f& position, real32 dfc)
{
Vec3f result;
result.x = (position.x / position.z) * dfc;
result.y = (position.y / position.z) * dfc;
result.z = position.z;
return result;
}
Vec3f
MeshHelper::getCrossProductCasted(const MappedTriangle& triangle, real32 dfc)
{
MappedTriangle castedTriangle = triangle;
Vec3f result;
for(int i = 0; i < 3; i++)
{
Vec3f& position = castedTriangle.vertices[i].position;
position = castVertex(position, dfc);
}
result = getCrossProduct(castedTriangle);
return result;
}
TriangleVector
MeshHelper::getTrianglesFromIndices(const TriangleIndices& triangleIndexes, const Vertices& vertices)
{
TriangleVector triangles;
const uint32 triangleCount = triangleIndexes.size();
triangles.resize(triangleCount);
for(int i = 0; i < triangleCount; i++)
{
const IndexedTriangle& indexedTriangle = triangleIndexes[i];
triangles[i].vertices[0] = vertices[indexedTriangle.indexes[0]];
triangles[i].vertices[1] = vertices[indexedTriangle.indexes[1]];
triangles[i].vertices[2] = vertices[indexedTriangle.indexes[2]];
}
return triangles;
}
MappedTriangles
MeshHelper::getTrianglesFromIndices(const TriangleIndices& triangleIndexes, const MappedVertices& vertices)
{
MappedTriangles triangles;
const uint32 triangleCount = triangleIndexes.size();
triangles.resize(triangleCount);
for(int i = 0; i < triangleCount; i++)
{
const IndexedTriangle& indexedTriangle = triangleIndexes[i];
triangles[i].vertices[0] = vertices[indexedTriangle.indexes[0]];
triangles[i].vertices[1] = vertices[indexedTriangle.indexes[1]];
triangles[i].vertices[2] = vertices[indexedTriangle.indexes[2]];
}
return triangles;
}
Polygons
MeshHelper::trianglesToPolys(const TriangleVector& triangles)
{
Polygons result;
for(auto it = triangles.begin(); it != triangles.end(); it++)
{
const Triangle& triangle = *it;
Polygon3D poly;
poly.vertices.resize(3);
poly.vertices[0] = triangle.vertices[0];
poly.vertices[1] = triangle.vertices[1];
poly.vertices[2] = triangle.vertices[2];
result.push_back(poly);
}
return result;
}
MappedPolygons
MeshHelper::trianglesToPolys(const MappedTriangles& triangles)
{
MappedPolygons result;
for(auto it = triangles.begin(); it != triangles.end(); it++)
{
const MappedTriangle& triangle = *it;
MappedPolygon polygon;
polygon.vertices.resize(3);
for(int i = 0; i < 3; i++)
{
polygon.vertices[i] = triangle.vertices[i];
}
result.push_back(polygon);
}
return result;
}
void
MeshHelper::rotateVertices(Vertices& vertices, const Vec3f& angles)
{
Vec3f radAngles = angles.degToRad();
for(auto it = vertices.begin(); it != vertices.end(); it++)
{
Vec3f& vertex = *it;
vertex.rotateAroundY(radAngles.y);
vertex.rotateAroundX(radAngles.x);
vertex.rotateAroundZ(radAngles.z);
}
}
void
MeshHelper::rotateVertices(MappedVertices& vertices, const Vec3f& angles)
{
Vec3f radAngles = angles.degToRad();
for(auto it = vertices.begin(); it != vertices.end(); it++)
{
Vec3f& vertex = it->position;
Vec3f& normal = it->normal;
vertex.rotateAroundY(radAngles.y);
normal.rotateAroundY(radAngles.y);
vertex.rotateAroundX(radAngles.x);
normal.rotateAroundX(radAngles.x);
vertex.rotateAroundZ(radAngles.z);
normal.rotateAroundZ(radAngles.z);
}
}
void
MeshHelper::translateVertices(Vertices& vertices, const Vec3f& translationVector)
{
for(auto it = vertices.begin(); it != vertices.end(); it++)
{
Vec3f& vertex = *it;
vertex += translationVector;
}
}
void
MeshHelper::translateVertices(MappedVertices& vertices, const Vec3f& translationVector)
{
for(auto it = vertices.begin(); it != vertices.end(); it++)
{
Vec3f& vertex = it->position;
vertex += translationVector;
}
}
Vec3f
MeshHelper::getFaceNormal(const MappedVertices& vertices, const IndexedTriangle& indexedTriangle)
{
Vec3f result;
Vec3f v1 = vertices[indexedTriangle.indexes[1]].position - vertices[indexedTriangle.indexes[0]].position;
Vec3f v2 = vertices[indexedTriangle.indexes[2]].position - vertices[indexedTriangle.indexes[0]].position;
result = Vec3f::cross(v1, v2);
result = Vec3f::normalize(result);
return result;
}
void
MeshHelper::calculateNormals(MappedVertices& vertices, const TriangleIndices& triangleIndices)
{
uint32 triangleCount = triangleIndices.size();
Vertices normals(triangleCount);
// Calculating Face Normals
for(uint32 i = 0; i != triangleCount; i++)
{
const IndexedTriangle& indexedTriangle = triangleIndices[i];
normals[i] = getFaceNormal(vertices, indexedTriangle);
}
// Checking What Face Normals belongs to what vertex
uint32 vertexCount = vertices.size();
for(int i = 0; i != vertexCount; i++)
{
MappedVertex& vertex = vertices[i];
Vec3f directionSum;
for(int j = 0; j < triangleCount; j++)
{
if(triangleIndices[j].indexes[0] == i ||
triangleIndices[j].indexes[1] == i ||
triangleIndices[j].indexes[2] == i )
{
directionSum += normals[j];
}
}
// Normalizing direction sum
vertex.normal = Vec3f::normalize(directionSum);
}
}
| 24.370425 | 107 | 0.642716 | Cavantar |
04e92e8d1599101bc89a2c2e8ed2fb2c5c531376 | 1,991 | cpp | C++ | NearestNeighbor/Tests/TestLinearNeighborSearchSubset.cpp | jingtangliao/ff | d308fe62045e241a4822bb855df97ee087420d9b | [
"Apache-2.0"
] | 39 | 2015-01-01T07:59:51.000Z | 2021-10-01T18:11:46.000Z | NearestNeighbor/Tests/TestLinearNeighborSearchSubset.cpp | jingtangliao/ff | d308fe62045e241a4822bb855df97ee087420d9b | [
"Apache-2.0"
] | 1 | 2019-04-24T09:56:15.000Z | 2019-04-24T14:45:46.000Z | NearestNeighbor/Tests/TestLinearNeighborSearchSubset.cpp | jingtangliao/ff | d308fe62045e241a4822bb855df97ee087420d9b | [
"Apache-2.0"
] | 18 | 2015-01-11T15:10:23.000Z | 2022-02-24T20:02:10.000Z | #include <iostream>
#include <boost/graph/grid_graph.hpp>
#include "NearestNeighbor/topological_search.hpp"
int main(int argc, char *argv[])
{
typedef boost::grid_graph<2> GraphType;
const unsigned int dimension = 5;
boost::array<std::size_t, 2> lengths = { { dimension, dimension } };
GraphType graph(lengths);
typedef boost::graph_traits<GraphType>::vertex_descriptor VertexDescriptor;
VertexDescriptor v = { { 0, 1 } };
typedef boost::hypercube_topology<6, boost::minstd_rand> TopologyType;
TopologyType myTopology;
typedef TopologyType::point_type PointType;
std::vector<PointType> vertexData(dimension * dimension);
// This is an "exterior property" of the grid_graph
typedef boost::property_map<GraphType, boost::vertex_index_t>::const_type IndexMapType;
IndexMapType indexMap(get(boost::vertex_index, graph));
typedef boost::iterator_property_map<std::vector<PointType>::iterator, IndexMapType> MapType;
MapType myMap(vertexData.begin(), indexMap);
typedef linear_neighbor_search<> SearchType;
// Add vertices to the graph and corresponding points increasin integer points to the tree.
// The experiment here is to query the nearest neighbor of a point like (5.2, 5.2, 5.1, 5.3, 5.2, 5.1)
// and ensure we get back (5,5,5,5,5,5)
unsigned int numberOfVertices = 100;
for(unsigned int vertexId = 0; vertexId < numberOfVertices; ++vertexId)
{
PointType p;
for(unsigned int dim = 0; dim < dimension; ++dim)
{
p[dim] = vertexId;
}
boost::put(myMap, v, p);
};
PointType queryPoint;
for(unsigned int dim = 0; dim < dimension; ++dim)
{
queryPoint[dim] = 5.2;
}
SearchType search;
//VertexDescriptor nearestNeighbor = search(queryPoint, graph, myTopology, myMap);
VertexDescriptor nearestNeighbor = search.operator()<GraphType, TopologyType, MapType>(queryPoint, graph, myTopology, myMap);
std::cout << "nearestNeighbor[0]: " << nearestNeighbor[0] << std::endl;
return 0;
}
| 31.603175 | 127 | 0.713712 | jingtangliao |
04ec5bcd4269f64a55221478fb714ccc3cbd2cbd | 2,783 | cpp | C++ | src/Pathfinding/visualizer_test.cpp | jonahbardos/PY2020 | af4f61b86ae5013e58faf4842bf20863b3de3957 | [
"Apache-2.0"
] | null | null | null | src/Pathfinding/visualizer_test.cpp | jonahbardos/PY2020 | af4f61b86ae5013e58faf4842bf20863b3de3957 | [
"Apache-2.0"
] | null | null | null | src/Pathfinding/visualizer_test.cpp | jonahbardos/PY2020 | af4f61b86ae5013e58faf4842bf20863b3de3957 | [
"Apache-2.0"
] | null | null | null | #include "Visualizer.h"
#include "ObstacleMap.h"
#include <iostream>
using namespace cv;
void runTest(std::string description, const std::vector<PointXY>& obstacles, PointXY dest) {
Visualizer sim;
Pather2 pather;
pather.updateMap(obstacles, 0.0, 0.0);
std::cout << "Text version of map:\n";
pather.obsMap.print();
sim.drawMap(pather.obsMap.obstacle_map);
std::queue<PointXY> path = pather.BFS(dest);
sim.drawPath(path);
sim.drawRobot();
sim.drawDestination();
imshow("Visualizer test: " + description, sim.img);
waitKey(0);
destroyAllWindows();
}
int main(void) {
// robot location for all tests: (0.0f, 0.0f)
// Test1:
std::vector<PointXY> points1 = {}; // supposed to be PointXY
runTest("empty map", points1, PointXY{10.0f, 10.0f});
// Test2:
std::vector<PointXY> points2 = {
PointXY{1.0f, 1.0f},
PointXY{2.0f, 2.0f},
PointXY{3.0f, 3.0f},
PointXY{4.0f, 4.0f},
PointXY{5.0f, 5.0f},
PointXY{6.0f, 6.0f},
PointXY{7.0f, 7.0f},
PointXY{8.0f, 8.0f},
PointXY{9.0f, 9.0f},
PointXY{10.0f, 10.0f}
};
runTest("diagonal obstacles", points2, PointXY{10.0f, 10.0f});
// Test3:
std::vector<PointXY> points3 = {
PointXY{2.0f, 2.0f},
PointXY{-2.0f, -2.0f},
PointXY{-3.0f, 3.0f},
PointXY{3.0f, -3.0f},
PointXY{5.0f, -5.0f},
PointXY{1.0f, 1.0f}
};
runTest("irregular obstacles", points3, PointXY{10.0f, 10.0f});
// Test4:
std::vector<PointXY> points4 = {
PointXY{1.0f, 1.0f},
PointXY{2.0f, 2.0f},
PointXY{3.0f, 3.0f},
PointXY{4.0f, 4.0f},
PointXY{5.0f, 5.0f},
PointXY{6.0f, 6.0f},
PointXY{7.0f, 7.0f},
PointXY{8.0f, 8.0f},
PointXY{9.0f, 9.0f},
PointXY{10.0f, 10.0f}
};
runTest("different goal", points4, PointXY{10.0f, 7.0f});
// Test5:
std::vector<PointXY> points5 = {
PointXY{1.0f, 1.0f},
PointXY{2.0f, 2.0f},
PointXY{3.0f, 3.0f},
PointXY{4.0f, 4.0f},
PointXY{5.0f, 5.0f},
PointXY{6.0f, 6.0f},
PointXY{7.0f, 7.0f},
PointXY{8.0f, 8.0f},
PointXY{9.0f, 9.0f},
PointXY{10.0f, 10.0f}
};
runTest("another different goal", points5, PointXY{7.0f, 10.0f});
// Test6:
std::vector<PointXY> points6 = {
PointXY{1.0f, 1.0f},
PointXY{2.0f, 2.0f},
PointXY{3.0f, 3.0f},
PointXY{4.0f, 4.0f},
PointXY{5.0f, 5.0f},
PointXY{2.0f, 4.0f},
PointXY{3.0f, 7.0f},
PointXY{5.0f, 2.0f},
PointXY{6.0f, 4.0f},
PointXY{1.0f, 3.0f}
};
runTest("more irregular obstacles", points6, PointXY{5.0f, 5.0f});
}
| 27.554455 | 92 | 0.541861 | jonahbardos |
04ee35860e1b30246d19c26e7d2e86c0094c5e31 | 4,262 | hpp | C++ | master/core/third/boost/geometry/strategies/spherical/ssf.hpp | importlib/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 198 | 2015-01-13T05:47:18.000Z | 2022-03-09T04:46:46.000Z | master/core/third/boost/geometry/strategies/spherical/ssf.hpp | isuhao/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 197 | 2017-07-06T16:53:59.000Z | 2019-05-31T17:57:51.000Z | master/core/third/boost/geometry/strategies/spherical/ssf.hpp | isuhao/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 139 | 2015-01-15T20:09:31.000Z | 2022-01-31T15:21:16.000Z | // Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_STRATEGIES_SPHERICAL_SSF_HPP
#define BOOST_GEOMETRY_STRATEGIES_SPHERICAL_SSF_HPP
#include <boost/mpl/if.hpp>
#include <boost/type_traits.hpp>
#include <boost/geometry/core/cs.hpp>
#include <boost/geometry/core/access.hpp>
#include <boost/geometry/core/radian_access.hpp>
#include <boost/geometry/util/select_coordinate_type.hpp>
#include <boost/geometry/util/math.hpp>
#include <boost/geometry/strategies/side.hpp>
//#include <boost/geometry/strategies/concepts/side_concept.hpp>
namespace boost { namespace geometry
{
namespace strategy { namespace side
{
/*!
\brief Check at which side of a Great Circle segment a point lies
left of segment (> 0), right of segment (< 0), on segment (0)
\ingroup strategies
\tparam CalculationType \tparam_calculation
*/
template <typename CalculationType = void>
class spherical_side_formula
{
public :
template <typename P1, typename P2, typename P>
static inline int apply(P1 const& p1, P2 const& p2, P const& p)
{
typedef typename boost::mpl::if_c
<
boost::is_void<CalculationType>::type::value,
// Select at least a double...
typename select_most_precise
<
typename select_most_precise
<
typename select_most_precise
<
typename coordinate_type<P1>::type,
typename coordinate_type<P2>::type
>::type,
typename coordinate_type<P>::type
>::type,
double
>::type,
CalculationType
>::type coordinate_type;
// Convenient shortcuts
typedef coordinate_type ct;
ct const lambda1 = get_as_radian<0>(p1);
ct const delta1 = get_as_radian<1>(p1);
ct const lambda2 = get_as_radian<0>(p2);
ct const delta2 = get_as_radian<1>(p2);
ct const lambda = get_as_radian<0>(p);
ct const delta = get_as_radian<1>(p);
// Create temporary points (vectors) on unit a sphere
ct const cos_delta1 = cos(delta1);
ct const c1x = cos_delta1 * cos(lambda1);
ct const c1y = cos_delta1 * sin(lambda1);
ct const c1z = sin(delta1);
ct const cos_delta2 = cos(delta2);
ct const c2x = cos_delta2 * cos(lambda2);
ct const c2y = cos_delta2 * sin(lambda2);
ct const c2z = sin(delta2);
// (Third point is converted directly)
ct const cos_delta = cos(delta);
// Apply the "Spherical Side Formula" as presented on my blog
ct const dist
= (c1y * c2z - c1z * c2y) * cos_delta * cos(lambda)
+ (c1z * c2x - c1x * c2z) * cos_delta * sin(lambda)
+ (c1x * c2y - c1y * c2x) * sin(delta);
ct zero = ct();
return dist > zero ? 1
: dist < zero ? -1
: 0;
}
};
#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS
namespace services
{
/*template <typename CalculationType>
struct default_strategy<spherical_polar_tag, CalculationType>
{
typedef spherical_side_formula<CalculationType> type;
};*/
template <typename CalculationType>
struct default_strategy<spherical_equatorial_tag, CalculationType>
{
typedef spherical_side_formula<CalculationType> type;
};
template <typename CalculationType>
struct default_strategy<geographic_tag, CalculationType>
{
typedef spherical_side_formula<CalculationType> type;
};
}
#endif
}} // namespace strategy::side
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_STRATEGIES_SPHERICAL_SSF_HPP
| 31.109489 | 80 | 0.601595 | importlib |
04ef575493ef883169e2906e3647678ce7086341 | 540 | cpp | C++ | Problems/rod.cpp | anand434/-Algorithm-And-DataStructures | e4197db5342def163a8bd22de4187b90bc5ff1d3 | [
"MIT"
] | null | null | null | Problems/rod.cpp | anand434/-Algorithm-And-DataStructures | e4197db5342def163a8bd22de4187b90bc5ff1d3 | [
"MIT"
] | null | null | null | Problems/rod.cpp | anand434/-Algorithm-And-DataStructures | e4197db5342def163a8bd22de4187b90bc5ff1d3 | [
"MIT"
] | null | null | null | // dynamic programing
#include <bits/stdc++.h>
using namespace std;
int calc(int a[] , int l){
int s = sizeof(a)/sizeof(a[0]);
int dp[s][l+1];
for(int i = 1; i <= s; ++i){
for(int j = 0; j <= l; ++j){
if(i == 0)
dp[i][j] = j;
else if(j == 0)
dp[i][j] = i;
else if(j >= i)
dp[i][j] = max(dp[i-1][j] , a[i-1] + dp[i][j-i]);
else
dp[i][j] = dp[i-1][j];
}
}
return dp[s][l];
}
int main(){
int len = 5;
int val[] = {2 , 5 , 7 , 8};
int profit = calc(val , len);
cout << profit ;
return 0;
} | 16.363636 | 53 | 0.457407 | anand434 |
04f6fcc33c80c183514a66a1ab37f628b573f849 | 3,874 | cpp | C++ | bulletgba/generator/data/code/__system/3way-laser.cpp | pqrs-org/BulletGBA | a294007902970242b496f2528b4762cfef22bc86 | [
"Unlicense"
] | 5 | 2020-03-24T07:44:49.000Z | 2021-08-30T14:43:31.000Z | bulletgba/generator/data/code/__system/3way-laser.cpp | pqrs-org/BulletGBA | a294007902970242b496f2528b4762cfef22bc86 | [
"Unlicense"
] | null | null | null | bulletgba/generator/data/code/__system/3way-laser.cpp | pqrs-org/BulletGBA | a294007902970242b496f2528b4762cfef22bc86 | [
"Unlicense"
] | null | null | null | // XXX uniqID XXX 5aa05dce2cc2c392ac12214081381a73 XXX
#include <gba_types.h>
#include "bullet.hpp"
#include "fixed.hpp"
#include "__system/3way-laser.hpp"
extern const BulletStepFunc bullet_0e9cb1a61061b85c007db56fc11fa063_5aa05dce2cc2c392ac12214081381a73[] = {
stepfunc_bbf4d4d1a84fe518316ecf2f20d6a516_5aa05dce2cc2c392ac12214081381a73,
stepfunc_bbf4d4d1a84fe518316ecf2f20d6a516_5aa05dce2cc2c392ac12214081381a73,
stepfunc_bbf4d4d1a84fe518316ecf2f20d6a516_5aa05dce2cc2c392ac12214081381a73,
stepfunc_bbf4d4d1a84fe518316ecf2f20d6a516_5aa05dce2cc2c392ac12214081381a73,
stepfunc_bbf4d4d1a84fe518316ecf2f20d6a516_5aa05dce2cc2c392ac12214081381a73,
stepfunc_bbf4d4d1a84fe518316ecf2f20d6a516_5aa05dce2cc2c392ac12214081381a73,
stepfunc_bbf4d4d1a84fe518316ecf2f20d6a516_5aa05dce2cc2c392ac12214081381a73,
stepfunc_bbf4d4d1a84fe518316ecf2f20d6a516_5aa05dce2cc2c392ac12214081381a73,
stepfunc_bbf4d4d1a84fe518316ecf2f20d6a516_5aa05dce2cc2c392ac12214081381a73,
stepfunc_bbf4d4d1a84fe518316ecf2f20d6a516_5aa05dce2cc2c392ac12214081381a73,
stepfunc_dae2cf81747ffb5070f05c8837b1d568_5aa05dce2cc2c392ac12214081381a73,
NULL};
extern const BulletStepFunc bullet_1f06afe44fe9fc66eb4bef5bfe15894d_5aa05dce2cc2c392ac12214081381a73[] = {
stepfunc_11697f4cf8a3fdfad9e846b2dcf785fe_5aa05dce2cc2c392ac12214081381a73,
stepfunc_11697f4cf8a3fdfad9e846b2dcf785fe_5aa05dce2cc2c392ac12214081381a73,
stepfunc_11697f4cf8a3fdfad9e846b2dcf785fe_5aa05dce2cc2c392ac12214081381a73,
stepfunc_11697f4cf8a3fdfad9e846b2dcf785fe_5aa05dce2cc2c392ac12214081381a73,
stepfunc_11697f4cf8a3fdfad9e846b2dcf785fe_5aa05dce2cc2c392ac12214081381a73,
stepfunc_dae2cf81747ffb5070f05c8837b1d568_5aa05dce2cc2c392ac12214081381a73,
NULL};
void stepfunc_bbf4d4d1a84fe518316ecf2f20d6a516_5aa05dce2cc2c392ac12214081381a73(BulletInfo *p) {
{
BulletInfo *bi; p->lastBulletAngle = p->getAngle() + (FixedPointNum::degree2angle(0.0)); p->lastBulletSpeed = (2.0); bi = ListBullets::makeNewBullet(); if (bi != NULL) { bi->initialize(p->getType() << 1, p->getPosX(), p->getPosY(), p->lastBulletAngle, p->lastBulletSpeed, StepFunc::nullStepFuncList);
}
}
p->wait = static_cast<u16>(3.0);
}
void stepfunc_dae2cf81747ffb5070f05c8837b1d568_5aa05dce2cc2c392ac12214081381a73(BulletInfo *p) {
ListBullets::stepFuncDrop(p);}
void stepfunc_11697f4cf8a3fdfad9e846b2dcf785fe_5aa05dce2cc2c392ac12214081381a73(BulletInfo *p) {
{
BulletInfo *bi; p->lastBulletAngle = SelfPos::getAngle(p) + (FixedPointNum::degree2angle(0.0)); p->lastBulletSpeed = (0.1); bi = ListBullets::makeNewBullet(); if (bi != NULL) { bi->initialize(p->getType() << 1, p->getPosX(), p->getPosY(), p->lastBulletAngle, p->lastBulletSpeed, bullet_0e9cb1a61061b85c007db56fc11fa063_5aa05dce2cc2c392ac12214081381a73);
}
}
{
BulletInfo *bi; p->lastBulletAngle = SelfPos::getAngle(p) + (FixedPointNum::degree2angle(-10.0)); p->lastBulletSpeed = (0.1); bi = ListBullets::makeNewBullet(); if (bi != NULL) { bi->initialize(p->getType() << 1, p->getPosX(), p->getPosY(), p->lastBulletAngle, p->lastBulletSpeed, bullet_0e9cb1a61061b85c007db56fc11fa063_5aa05dce2cc2c392ac12214081381a73);
}
}
{
BulletInfo *bi; p->lastBulletAngle = SelfPos::getAngle(p) + (FixedPointNum::degree2angle(10.0)); p->lastBulletSpeed = (0.1); bi = ListBullets::makeNewBullet(); if (bi != NULL) { bi->initialize(p->getType() << 1, p->getPosX(), p->getPosY(), p->lastBulletAngle, p->lastBulletSpeed, bullet_0e9cb1a61061b85c007db56fc11fa063_5aa05dce2cc2c392ac12214081381a73);
}
}
p->wait = static_cast<u16>(60.0);
}
BulletInfo *genBulletFunc_5aa05dce2cc2c392ac12214081381a73(FixedPointNum posx, FixedPointNum posy) { BulletInfo * bi; bi = ListBullets::makeNewBullet(); if (bi != NULL) { bi->initialize(BULLET_TYPE_ROOT, posx, posy, BulletInfo::DEFAULT_ANGLE, 0, bullet_1f06afe44fe9fc66eb4bef5bfe15894d_5aa05dce2cc2c392ac12214081381a73);
}
return bi;}
| 62.483871 | 365 | 0.824729 | pqrs-org |
04f80736a2c3d3c9c5b039e15ef358de796909dd | 1,793 | hpp | C++ | 2d-platform-game/Fase2.hpp | hadryansalles/random-projects | 2c97fcb407acd2605a6c46ccc184a86f8130b56f | [
"MIT"
] | 3 | 2021-04-02T02:26:47.000Z | 2021-05-18T01:56:18.000Z | 2d-platform-game/Fase2.hpp | hadryans/random-projects | 2c97fcb407acd2605a6c46ccc184a86f8130b56f | [
"MIT"
] | null | null | null | 2d-platform-game/Fase2.hpp | hadryans/random-projects | 2c97fcb407acd2605a6c46ccc184a86f8130b56f | [
"MIT"
] | null | null | null | #pragma once
#include "Std.hpp"
#include "Fase.hpp"
#include "Janela.hpp"
#include "Ladrao.hpp"
#include "Demonio.hpp"
class Fase2 : public Fase{
private:
// local onde o jogador encerra a fase
sf::RectangleShape _portal_fim_fase;
// cenario em segundo plano
sf::RectangleShape _cenario_dinamico;
sf::Texture _t_portal_fim_fase;
sf::Texture _t_cenario_dinamico;
std::vector<sf::Vector2f> _pos_esqueletos_roupa;
std::vector<sf::Vector2f> _pos_esqueletos_nu;
std::vector<sf::Vector2f> _pos_fantasmas;
std::vector<sf::Vector2f> _pos_ladroes;
std::vector<sf::Vector2f> _pos_espinhos;
std::vector<sf::Vector2f> _pos_caixas;
sf::Texture* _espinho;
static const int AlturaChao;
static const sf::Vector2f SpawnJogador1;
static const sf::Vector2f SpawnJogador2;
// Spawnar as entidades pelo cenario
void spawnarInimigos();
void spawnarFantasmas();
void spawnarLadroes();
void spawnarEsqueletosRoupa();
void spawnarEsqueletosNu();
void spawnarCaixasMadeira();
void spawnarEspinhos();
Fantasma* criarFantasma(sf::Vector2f posicao = sf::Vector2f(0,0));
Ladrao* criarLadrao(sf::Vector2f posicao = sf::Vector2f(0,0));
Projetil* criarEspinho(sf::Vector2f posicao = sf::Vector2f(0,0));
// Sorteia onde os esqueletos deveram spawnar
void sorteiaPosicaoEntidades();
// Carregar as texturas do cenario
void carregarCenario();
// Carregar o jogo de um arquivo
bool carregar();
public:
Fase2 (std::string jogador1, std::string jogador2, Janela* janela);
Fase2 (Janela* janela);
~Fase2();
void draw(sf::RenderTarget& target, sf::RenderStates states) const;
// chama os metodos expecificos dessa fase
void atualizar();
// salva a fase em arquivo
void salvar();
};
| 27.166667 | 71 | 0.709426 | hadryansalles |
04f8bb24964c293785510004ff2ec82bff01ab3a | 1,933 | cc | C++ | src/curses.cc | lollek/chip8curses | 3f62e01d1f4411a084cc74edc331d75c32ef4e0f | [
"MIT"
] | null | null | null | src/curses.cc | lollek/chip8curses | 3f62e01d1f4411a084cc74edc331d75c32ef4e0f | [
"MIT"
] | null | null | null | src/curses.cc | lollek/chip8curses | 3f62e01d1f4411a084cc74edc331d75c32ef4e0f | [
"MIT"
] | null | null | null | #include <curses.h>
#include <iostream>
#include "curses.h"
using namespace std;
namespace chip8curses {
namespace curses {
Emulator* emulator_ptr{nullptr};
bool double_width;
namespace {
void write_pixel(int x, int y, bool black) {
if (double_width) {
mvaddch(y, x*2, (black ? ' ' | A_STANDOUT : ' '));
mvaddch(y, x*2 + 1, (black ? ' ' | A_STANDOUT : ' '));
} else {
mvaddch(y, x, (black ? ' ' | A_STANDOUT : ' '));
}
}
void flush() {
refresh();
}
void callback() {
byte const* graphics_ptr{emulator_ptr->getGraphicsData()};
for (unsigned line{0}; line < Emulator::screen_rows; ++line) {
for (unsigned column{0}; column < Emulator::screen_columns; ++column) {
byte data = graphics_ptr[line * 8 + column];
write_pixel(column * 8 + 0, line, (data & 0x80) != 0 );
write_pixel(column * 8 + 1, line, (data & 0x40) != 0 );
write_pixel(column * 8 + 2, line, (data & 0x20) != 0 );
write_pixel(column * 8 + 3, line, (data & 0x10) != 0 );
write_pixel(column * 8 + 4, line, (data & 0x08) != 0 );
write_pixel(column * 8 + 5, line, (data & 0x04) != 0 );
write_pixel(column * 8 + 6, line, (data & 0x02) != 0 );
write_pixel(column * 8 + 7, line, (data & 0x01) != 0 );
}
}
flush();
}
} // anonymous namespace
bool start(int min_lines, int min_columns, bool wide) {
double_width = wide;
initscr();
if (double_width) {
min_columns *= 2;
}
if (LINES < min_lines || COLS < min_columns) {
cerr << "Screen was too small! Need at least " << min_lines
<< " lines and " << min_columns << " columns\n";
stop();
return false;
}
raw();
noecho();
timeout(0);
curs_set(0);
return true;
}
void stop() {
endwin();
emulator_ptr = nullptr;
}
void attach(Emulator* emulator) {
emulator_ptr = emulator;
emulator->onGraphics = callback;
}
int get_char() {
return getch();
}
} // curses
} // chip8curses
| 21.719101 | 75 | 0.58924 | lollek |
04f94bf3ec5a3f1f5deec0c720be63e2bfdb8713 | 476 | cpp | C++ | src/TEMA DIVIZIBILITATE/64/main.cpp | andrew-miroiu/Cpp-projects | d0917a7f78aef929c25dc9b019e910951c2050ac | [
"MIT"
] | 2 | 2021-11-27T18:29:32.000Z | 2021-11-28T14:35:47.000Z | src/TEMA DIVIZIBILITATE/64/main.cpp | andrew-miroiu/Cpp-projects | d0917a7f78aef929c25dc9b019e910951c2050ac | [
"MIT"
] | null | null | null | src/TEMA DIVIZIBILITATE/64/main.cpp | andrew-miroiu/Cpp-projects | d0917a7f78aef929c25dc9b019e910951c2050ac | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
//Prob. 64
int main()
{
int n, d, s=0, dn;
cout<<"Numarul n= ";
cin>>n;
dn=2*n;
for (d=1; d*d<=n; d++)
{
if (n%d==0)
{
s=s+d;
if (d*d<n)
{
s=s+n/d;
}
}
}
if (dn==s)
{
cout<<"Numarul este perfect."<<endl;
}
else
{
cout<<"Numarul nu este perfect."<<endl;
}
return 0;
}
| 12.205128 | 47 | 0.357143 | andrew-miroiu |
04ff2de91fc7b68d7fc026cf06db3e76205eef92 | 8,488 | hh | C++ | include/qpdf/PointerHolder.hh | m-holger/qpdf | f1a9ba0c622deee0ed05004949b34f0126b12b6a | [
"Apache-2.0"
] | null | null | null | include/qpdf/PointerHolder.hh | m-holger/qpdf | f1a9ba0c622deee0ed05004949b34f0126b12b6a | [
"Apache-2.0"
] | 3 | 2021-11-19T15:59:21.000Z | 2021-12-10T20:44:33.000Z | include/qpdf/PointerHolder.hh | m-holger/qpdf | f1a9ba0c622deee0ed05004949b34f0126b12b6a | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2005-2022 Jay Berkenbilt
//
// This file is part of qpdf.
//
// 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.
//
// Versions of qpdf prior to version 7 were released under the terms
// of version 2.0 of the Artistic License. At your option, you may
// continue to consider qpdf to be licensed under those terms. Please
// see the manual for additional information.
#ifndef POINTERHOLDER_HH
#define POINTERHOLDER_HH
#define POINTERHOLDER_IS_SHARED_POINTER
#ifndef POINTERHOLDER_TRANSITION
// #define POINTERHOLDER_TRANSITION 0 to suppress this warning, and see below.
// See also https://qpdf.readthedocs.io/en/stable/design.html#smart-pointers
# warning "POINTERHOLDER_TRANSITION is not defined -- see qpdf/PointerHolder.hh"
// undefined = define as 0 and issue a warning
// 0 = no deprecation warnings, backward-compatible API
// 1 = make PointerHolder<T>(T*) explicit
// 2 = warn for use of getPointer() and getRefcount()
// 3 = warn for all use of PointerHolder
// 4 = don't define PointerHolder at all
# define POINTERHOLDER_TRANSITION 0
#endif // !defined(POINTERHOLDER_TRANSITION)
#if POINTERHOLDER_TRANSITION < 4
// *** WHAT IS HAPPENING ***
// In qpdf 11, PointerHolder was replaced with std::shared_ptr
// wherever it appeared in the qpdf API. The PointerHolder object is
// now derived from std::shared_ptr to provide a backward-compatible
// interface and is mutually assignable with std::shared_ptr. Code
// that uses containers of PointerHolder will require adjustment.
// *** HOW TO TRANSITION ***
// The symbol POINTERHOLDER_TRANSITION can be defined to help you
// transition your code away from PointerHolder. You can define it
// before including any qpdf header files or including its definition
// in your build configuration. If not defined, it automatically gets
// defined to 0 (with a warning), which enables full backward
// compatibility. That way, you don't have to take action for your
// code to continue to work.
// If you want to work gradually to transition your code away from
// PointerHolder, you can define POINTERHOLDER_TRANSITION and fix the
// code so it compiles without warnings and works correctly. If you
// want to be able to continue to support old qpdf versions at the
// same time, you can write code like this:
// #ifndef POINTERHOLDER_IS_SHARED_POINTER
// ... use PointerHolder as before 10.6
// #else
// ... use PointerHolder or shared_ptr as needed
// #endif
// Each level of POINTERHOLDER_TRANSITION exposes differences between
// PointerHolder and std::shared_ptr. The easiest way to transition is
// to increase POINTERHOLDER_TRANSITION in steps of 1 so that you can
// test and handle changes incrementally.
// POINTERHOLDER_TRANSITION = 1
//
// PointerHolder<T> has an implicit constructor that takes a T*, so
// you can replace a PointerHolder<T>'s pointer by directly assigning
// a T* to it or pass a T* to a function that expects a
// PointerHolder<T>. std::shared_ptr does not have this (risky)
// behavior. When POINTERHOLDER_TRANSITION = 1, PointerHolder<T>'s T*
// constructor is declared explicit. For compatibility with
// std::shared_ptr, you can still assign nullptr to a PointerHolder.
// Constructing all your PointerHolder<T> instances explicitly is
// backward compatible, so you can make this change without
// conditional compilation and still use the changes with older qpdf
// versions.
//
// Also defined is a make_pointer_holder method that acts like
// std::make_shared. You can use this as well, but it is not
// compatible with qpdf prior to 10.6 and not necessary with qpdf
// newer than 10.6.3. Like std::make_shared<T>, make_pointer_holder<T>
// can only be used when the constructor implied by its arguments is
// public. If you previously used this, you can replace it width
// std::make_shared now.
// POINTERHOLDER_TRANSITION = 2
//
// std::shared_ptr has get() and use_count(). PointerHolder has
// getPointer() and getRefcount(). In 10.6.0, get() and use_count()
// were added as well. When POINTERHOLDER_TRANSITION = 2, getPointer()
// and getRefcount() are deprecated. Fix deprecation warnings by
// replacing with get() and use_count(). This breaks compatibility
// with qpdf older than 10.6. Search for CONST BEHAVIOR for an
// additional note.
//
// Once your code is clean at POINTERHOLDER_TRANSITION = 2, the only
// remaining issues that prevent simple replacement of PointerHolder
// with std::shared_ptr are shared arrays and containers, and neither
// of these are used in the qpdf API.
// POINTERHOLDER_TRANSITION = 3
//
// Warn for all use of PointerHolder<T>. This helps you remove all use
// of PointerHolder from your code and use std::shared_ptr instead.
// You will also have to transition any containers of PointerHolder in
// your code.
// POINTERHOLDER_TRANSITION = 4
//
// Suppress definition of the PointerHolder<T> type entirely.
// CONST BEHAVIOR
// PointerHolder<T> has had a long-standing bug in its const behavior.
// const PointerHolder<T>'s getPointer() method returns a T const*.
// This is incorrect and is not how regular pointers or standard
// library smart pointers behave. Making a PointerHolder<T> const
// should prevent reassignment of its pointer but not affect the thing
// it points to. For that, use PointerHolder<T const>. The new get()
// method behaves correctly in this respect and is therefore slightly
// different from getPointer(). This shouldn't break any correctly
// written code. If you are relying on the incorrect behavior, use
// PointerHolder<T const> instead.
# include <cstddef>
# include <memory>
template <class T>
class PointerHolder: public std::shared_ptr<T>
{
public:
# if POINTERHOLDER_TRANSITION >= 3
[[deprecated("use std::shared_ptr<T> instead")]]
# endif // POINTERHOLDER_TRANSITION >= 3
PointerHolder(std::shared_ptr<T> other) :
std::shared_ptr<T>(other)
{
}
# if POINTERHOLDER_TRANSITION >= 3
[[deprecated("use std::shared_ptr<T> instead")]]
# if POINTERHOLDER_TRANSITION >= 1
explicit
# endif // POINTERHOLDER_TRANSITION >= 1
# endif // POINTERHOLDER_TRANSITION >= 3
PointerHolder(T* pointer = 0) :
std::shared_ptr<T>(pointer)
{
}
// Create a shared pointer to an array
# if POINTERHOLDER_TRANSITION >= 3
[[deprecated("use std::shared_ptr<T> instead")]]
# endif // POINTERHOLDER_TRANSITION >= 3
PointerHolder(bool, T* pointer) :
std::shared_ptr<T>(pointer, std::default_delete<T[]>())
{
}
virtual ~PointerHolder() = default;
# if POINTERHOLDER_TRANSITION >= 2
[[deprecated("use PointerHolder<T>::get() instead of getPointer()")]]
# endif // POINTERHOLDER_TRANSITION >= 2
T*
getPointer()
{
return this->get();
}
# if POINTERHOLDER_TRANSITION >= 2
[[deprecated("use PointerHolder<T>::get() instead of getPointer()")]]
# endif // POINTERHOLDER_TRANSITION >= 2
T const*
getPointer() const
{
return this->get();
}
# if POINTERHOLDER_TRANSITION >= 2
[[deprecated("use PointerHolder<T>::get() instead of getPointer()")]]
# endif // POINTERHOLDER_TRANSITION >= 2
int
getRefcount() const
{
return static_cast<int>(this->use_count());
}
PointerHolder&
operator=(decltype(nullptr))
{
std::shared_ptr<T>::operator=(nullptr);
return *this;
}
T const&
operator*() const
{
return *(this->get());
}
T&
operator*()
{
return *(this->get());
}
T const*
operator->() const
{
return this->get();
}
T*
operator->()
{
return this->get();
}
};
template <typename T, typename... _Args>
inline PointerHolder<T>
make_pointer_holder(_Args&&... __args)
{
return PointerHolder<T>(new T(__args...));
}
template <typename T>
PointerHolder<T>
make_array_pointer_holder(size_t n)
{
return PointerHolder<T>(true, new T[n]);
}
#endif // POINTERHOLDER_TRANSITION < 4
#endif // POINTERHOLDER_HH
| 34.504065 | 80 | 0.719015 | m-holger |
04ffd4107bf79ab03580413b737ec61845049efa | 103 | cpp | C++ | softbody/engine/ui/image.cpp | legsonwings/SoftBody | c918d67338b5677bfb095f3849873bda684f9447 | [
"MIT"
] | null | null | null | softbody/engine/ui/image.cpp | legsonwings/SoftBody | c918d67338b5677bfb095f3849873bda684f9447 | [
"MIT"
] | null | null | null | softbody/engine/ui/image.cpp | legsonwings/SoftBody | c918d67338b5677bfb095f3849873bda684f9447 | [
"MIT"
] | null | null | null | #include "image.h"
gfx::resourcelist ui::image::createresources()
{
return gfx::resourcelist();
}
| 14.714286 | 46 | 0.68932 | legsonwings |
ca00485766f3cf9d916b10ed1d4ae47b064f1162 | 2,381 | cpp | C++ | src/extension-examples/show_image.cpp | 104-Berlin/universal-software-kit | d542d3e3fd01954c1c68ba81e7251926889c9e65 | [
"MIT"
] | 1 | 2021-06-19T12:37:10.000Z | 2021-06-19T12:37:10.000Z | src/extension-examples/show_image.cpp | 104-Berlin/universal-software-kit | d542d3e3fd01954c1c68ba81e7251926889c9e65 | [
"MIT"
] | 46 | 2021-03-26T22:11:59.000Z | 2022-03-29T20:13:59.000Z | src/extension-examples/show_image.cpp | 104-Berlin/universal-software-kit | d542d3e3fd01954c1c68ba81e7251926889c9e65 | [
"MIT"
] | null | null | null | #include "editor_extension.h"
using namespace Engine;
using namespace Graphics;
using namespace Renderer;
E_STORAGE_STRUCT(ImageLayer,
(bool, Visible),
(EResourceLink, resourceLink, "Image"),
(EString, SomeString)
)
class ImageLayerView : public EUIField
{
private:
EUnorderedMap<ERegister::Entity, EWeakRef<EUIImageView>> fImageViews;
public:
ImageLayerView()
: EUIField("ImageView")
{
shared::Events().AddComponentCreateEventListener(ImageLayer::_dsc, [this](ERegister::Entity handle){
ImageLayer imageLayer;
if (shared::GetValue<ImageLayer>(handle, &imageLayer))
{
ERef<EUIImageView> newImageView = EMakeRef<EUIImageView>();
newImageView->SetSize(250, 250);
fImageViews[handle] = newImageView;
AddChild(newImageView);
}
}, this);
shared::Events().AddComponentDeleteEventListener(ImageLayer::_dsc, [this](ERegister::Entity handle){
EUnorderedMap<ERegister::Entity, EWeakRef<EUIImageView>>::iterator it = fImageViews.find(handle);
if (it != fImageViews.end())
{
RemoveChild(it->second);
fImageViews.erase(it);
}
}, this);
shared::Events().AddEntityChangeEventListener("ImageLayer.resourceLink", [this](ERegister::Entity handle, const EString&){
ImageLayer imageLayer;
if (shared::GetValue<ImageLayer>(handle, &imageLayer))
{
ERef<EResourceData> data = shared::GetResource(imageLayer.resourceLink.ResourceId);
if (data && fImageViews.find(handle) != fImageViews.end())
{
Editor::EImageUserData* userData = (Editor::EImageUserData*)data->UserData;
if (userData)
{
fImageViews[handle].lock()->SetTextureData(data->Data, userData->width, userData->height);
}
}
}
}, this);
}
};
APP_ENTRY
{
ERef<EUIPanel> showPanel = EMakeRef<EUIPanel>("Show Panel");
showPanel->AddChild(EMakeRef<ImageLayerView>());
info.PanelRegister->RegisterItem(extensionName, showPanel);
}
EXT_ENTRY
{
info.GetComponentRegister().RegisterStruct<ImageLayer>(extensionName);
}
| 30.922078 | 130 | 0.600168 | 104-Berlin |
ca036a16e4c555f1a4fc244dfdc76612f5fa844c | 1,549 | hpp | C++ | include/caffe/layers/faceEvaluateLayer.hpp | yuqj1990/deepano_train | c7247801ccea4c3a5c0be9c9091fc91876dbf279 | [
"Unlicense"
] | 21 | 2019-11-28T06:11:17.000Z | 2020-06-15T00:45:46.000Z | include/caffe/layers/faceEvaluateLayer.hpp | yuqj1990/deepano_train | c7247801ccea4c3a5c0be9c9091fc91876dbf279 | [
"Unlicense"
] | 12 | 2019-11-20T01:38:28.000Z | 2020-06-30T06:29:40.000Z | include/caffe/layers/faceEvaluateLayer.hpp | yuqj1990/deepano_train | c7247801ccea4c3a5c0be9c9091fc91876dbf279 | [
"Unlicense"
] | 10 | 2019-11-26T00:50:06.000Z | 2020-06-20T05:43:45.000Z | #ifndef CAFFE_DETECTION_EVALUATE_LAYER_HPP_
#define CAFFE_DETECTION_EVALUATE_LAYER_HPP_
#include <utility>
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe {
/**
* @brief Generate the detection evaluation based on DetectionOutputLayer and
* ground truth bounding box labels.
*
* Intended for use with MultiBox detection method.
*
* NOTE: does not implement Backwards operation.
*/
template <typename Dtype>
class FaceAttriEvaluateLayer : public Layer<Dtype> {
public:
explicit FaceAttriEvaluateLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual inline const char* type() const { return "FaceEvaluate"; }
virtual inline int ExactBottomBlobs() const { return 2; }
virtual inline int ExactNumTopBlobs() const { return 1; }
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
/// @brief Not implemented
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
NOT_IMPLEMENTED;
}
int num_gender_;
int num_glasses_;
int num_headpose_;
int num_facepoints_;
FaceEvaluateParameter_FaceType facetype_;
};
} // namespace caffe
#endif // CAFFE_DETECTION_EVALUATE_LAYER_HPP_
| 29.226415 | 79 | 0.737895 | yuqj1990 |
ca03e02f13a17c8571526769a65935c787a8c3ca | 19,358 | cpp | C++ | src/tools/lvr2_viewer/widgets/LVRLabelDialog.cpp | uos/lvr | 9bb03a30441b027c39db967318877e03725112d5 | [
"BSD-3-Clause"
] | 38 | 2019-06-19T15:10:35.000Z | 2022-02-16T03:08:24.000Z | src/tools/lvr2_viewer/widgets/LVRLabelDialog.cpp | uos/lvr | 9bb03a30441b027c39db967318877e03725112d5 | [
"BSD-3-Clause"
] | 9 | 2019-06-19T16:19:51.000Z | 2021-09-17T08:31:25.000Z | src/tools/lvr2_viewer/widgets/LVRLabelDialog.cpp | uos/lvr | 9bb03a30441b027c39db967318877e03725112d5 | [
"BSD-3-Clause"
] | 13 | 2019-04-16T11:50:32.000Z | 2020-11-26T07:47:44.000Z | /**
* Copyright (c) 2018, University Osnabrück
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University Osnabrück 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 University Osnabrück 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.
*/
/**
* LVRCorrespondanceDialog.cpp
*
* @date Feb 18, 2014
* @author Thomas Wiemann
*/
#include "LVRLabelDialog.hpp"
#include "LVRPointCloudItem.hpp"
#include "LVRItemTypes.hpp"
#include <vtkSmartPointer.h>
#include <vtkCubeSource.h>
#include <boost/make_shared.hpp>
#include <QMessageBox>
#include <QFont>
#include <QFileDialog>
#include <QInputDialog>
#include <QColorDialog>
#include <QButtonGroup>
#include <vtkSelectEnclosedPoints.h>
#include <vtkPolyDataMapper.h>
#include <vtkPointData.h>
#include <vector>
#include <algorithm>
#include <vtkLookupTable.h>
#include <vtkExtractGeometry.h>
#include "lvr2/io/descriptions/HDF5Kernel.hpp"
#include <fstream>
using std::ifstream;
using std::ofstream;
namespace lvr2
{
LVRLabelDialog::LVRLabelDialog(QTreeWidget* treeWidget) :
m_treeWidget(treeWidget)
{
m_dialog = new QDialog(treeWidget);
m_ui = new Ui_LabelDialog;
m_ui->setupUi(m_dialog);
// m_ui->treeWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
QObject::connect(m_ui->newLabelButton, SIGNAL(pressed()), this, SLOT(addNewLabel()));
QObject::connect(m_ui->loadLabeledPoints, SIGNAL(pressed()), this, SLOT(loadLabels()));
QObject::connect(m_ui->newInstanceButton, SIGNAL(pressed()), this, SLOT(addNewInstance()));
QObject::connect(m_ui->treeWidget, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), this, SLOT(cellSelected(QTreeWidgetItem*, int)));
QObject::connect(m_ui->selectedLabelComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(comboBoxIndexChanged(int)));
QObject::connect(m_ui->treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(visibilityChanged(QTreeWidgetItem*, int)));
// QObject::connect(m_ui->labelSelectedPoints, SIGNAL(pressed()), this, SLOT(labelPoints()));
//
}
LVRLabelDialog::~LVRLabelDialog()
{
delete m_ui;
delete m_dialog;
// TODO Auto-generated destructor stub
}
void LVRLabelDialog::showEvent()
{
}
void LVRLabelDialog::visibilityChanged(QTreeWidgetItem* changedItem, int column)
{
if(column != LABEL_VISIBLE_COLUMN)
{
return;
}
//check if Instance or whole label changed
if (changedItem->parent())
{
//parent exists item is an instance
Q_EMIT(hidePoints(changedItem->data(LABEL_ID_COLUMN,0).toInt(), changedItem->checkState(LABEL_VISIBLE_COLUMN)));
} else
{
//Check if unlabeled item
for (int i = 0; i < changedItem->childCount(); i++)
{
QTreeWidgetItem* childItem = changedItem->child(i);
//sets child elements checkbox on toplevel box value if valuechanged a singal will be emitted and handeled
childItem->setCheckState(LABEL_VISIBLE_COLUMN, changedItem->checkState(LABEL_VISIBLE_COLUMN));
}
}
}
void LVRLabelDialog::cellSelected(QTreeWidgetItem* item, int column)
{
if(column == LABEL_NAME_COLUMN)
{
//Edit Label name
bool accepted;
QString label_name = QInputDialog::getText(m_dialog, tr("Select Label Name"),
tr("Label name:"), QLineEdit::Normal,
item->text(LABEL_NAME_COLUMN), &accepted);
if (accepted && !label_name.isEmpty())
{
item->setText(LABEL_NAME_COLUMN, label_name);
if (!item->parent())
{
//Toplevel item nothing else to do
return;
}
int comboBoxPos = m_ui->selectedLabelComboBox->findData(item->data(LABEL_ID_COLUMN, 0).toInt());
if (comboBoxPos >= 0)
{
m_ui->selectedLabelComboBox->setItemText(comboBoxPos, label_name);
}
return;
}
}else if(column == LABEL_ID_COLUMN)
{
//Change
QColor label_color = QColorDialog::getColor(Qt::red, m_dialog, tr("Choose Label Color"));
if (label_color.isValid())
{
item->setData(LABEL_ID_COLUMN, 1, label_color);
if(item->parent())
{
//Update Color In picker
Q_EMIT(labelAdded(item));
return;
}
else
{
//ask if all childs Should be updated
QMessageBox colorUpdateDialog;
colorUpdateDialog.setText("Labelclass default color changed. Shall all instance colors be updated?");
colorUpdateDialog.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
colorUpdateDialog.setDefaultButton(QMessageBox::Yes);
int returnValue = colorUpdateDialog.exec();
if (returnValue == QMessageBox::Yes)
{
//update All Childs
for (int i = 0; i < item->childCount(); i++)
{
item->child(i)->setData(LABEL_ID_COLUMN, 1, label_color);
Q_EMIT(labelAdded(item->child(i)));
}
}
}
}
}
}
void LVRLabelDialog::updatePointCount(uint16_t id, int selectedPointCount)
{
int topItemCount = m_ui->treeWidget->topLevelItemCount();
for (int i = 0; i < topItemCount; i++)
{
QTreeWidgetItem* topLevelItem = m_ui->treeWidget->topLevelItem(i);
int childCount = topLevelItem->childCount();
for (int j = 0; j < childCount; j++)
{
if(id == topLevelItem->child(j)->data(LABEL_ID_COLUMN, 0).toInt())
{
int pointCountDifference = selectedPointCount - topLevelItem->child(j)->text(LABELED_POINT_COLUMN).toInt();
topLevelItem->child(j)->setText(LABELED_POINT_COLUMN, QString::number(selectedPointCount));
//Add points to toplevel points
topLevelItem->setText(LABELED_POINT_COLUMN, QString::number(pointCountDifference + topLevelItem->text(LABELED_POINT_COLUMN).toInt()));
return;
}
}
}
}
void LVRLabelDialog::loadLabels()
{
//TODO: What should be done if elements exists?
QString fileName = QFileDialog::getOpenFileName(m_dialog,
tr("Open HDF5 File"), QDir::homePath(), tr("HDF5 files (*.h5)"));
if(!QFile::exists(fileName))
{
return;
}
HDF5Kernel kernel(fileName.toStdString());
std::vector<std::string> pointCloudNames;
kernel.subGroupNames("pointclouds", pointCloudNames);
for (auto pointcloudName : pointCloudNames)
{
//pointclouds
boost::filesystem::path classGroup = (boost::filesystem::path("pointclouds") / boost::filesystem::path(pointcloudName) / boost::filesystem::path("labels"));
std::vector<std::string> labelClasses;
kernel.subGroupNames(classGroup.string(), labelClasses);
for (auto labelClass : labelClasses)
{
//Get TopLevel Item for tree view
QTreeWidgetItem * item = new QTreeWidgetItem();
item->setText(0, QString::fromStdString(labelClass));
item->setText(LABELED_POINT_COLUMN, QString::number(0));
item->setCheckState(LABEL_VISIBLE_COLUMN, Qt::Checked);
if (m_ui->treeWidget->topLevelItemCount() == 0)
{
m_ui->newInstanceButton->setEnabled(true);
}
m_ui->treeWidget->addTopLevelItem(item);
//pointclouds/$name/labels/$labelname
boost::filesystem::path instanceGroup = (classGroup / boost::filesystem::path(labelClass));
std::vector<std::string> labelInstances;
kernel.subGroupNames(instanceGroup.string(), labelInstances);
for (auto instance : labelInstances)
{
int id = 0;
boost::filesystem::path finalGroup = instanceGroup;
//pointclouds/$name/labels/$labelname/instance
finalGroup = (instanceGroup / boost::filesystem::path(instance));
if (labelClass != "Unlabeled")
{
id = m_id_hack++;
}
//Get Color and IDs
boost::shared_array<int> rgbData;
std::vector<size_t> rgbDim;
boost::shared_array<int> idData;
std::vector<size_t> idDim;
idData = kernel.loadArray<int>(finalGroup.string(), "IDs", idDim);
rgbData = kernel.loadArray<int>(finalGroup.string(), "Color", rgbDim);
//Add Child to top Level
QTreeWidgetItem * childItem = new QTreeWidgetItem();
childItem->setText(LABELED_POINT_COLUMN, QString::number(0));
childItem->setText(0, QString::fromStdString(instance));
QColor label_color(rgbData[0], rgbData[1], rgbData[2]);
childItem->setData(LABEL_ID_COLUMN, 1, label_color);
childItem->setData(LABEL_ID_COLUMN, 0, id);
item->addChild(childItem);
Q_EMIT(labelAdded(childItem));
std::vector<int> out(idData.get(), idData.get() + idDim[0]);
Q_EMIT(labelLoaded(id, out));
if (labelClass != "Unlabeled")
{
m_ui->selectedLabelComboBox->addItem(childItem->text(LABEL_NAME_COLUMN), id);
}
}
}
}
}
void LVRLabelDialog::responseLabels(std::vector<uint16_t> labeledPoints)
{
std::map<uint16_t,std::vector<int>> idMap;
for (int i = 0; i < labeledPoints.size(); i++)
{
if(idMap.find(labeledPoints[i]) == idMap.end())
{
//first occurence of id add new entry
idMap[labeledPoints[i]] = {};
}
idMap[labeledPoints[i]].push_back(i);
}
QFileDialog dialog;
dialog.setDirectory(QDir::homePath());
dialog.setFileMode(QFileDialog::AnyFile);
QString strFile = dialog.getSaveFileName(m_dialog, "Creat New HDF5 File","","");
HDF5Kernel label_hdf5kernel((strFile + QString(".h5")).toStdString());
int topItemCount = m_ui->treeWidget->topLevelItemCount();
//TODO This should be for all Pointclouds
boost::filesystem::path pointcloudName(m_points.begin()->first);
auto points = m_points.begin()->second;
double* pointsData = new double[points->GetNumberOfPoints() * 3];
// const size_t point_number = points->GetNumberOfPoints();
// std::array<std::array<float, 3>, point_number> test;
for (int i = 0; i < points->GetNumberOfPoints(); i++)
{
auto point = points->GetPoint(i);
pointsData[(3 * i)] = point[0];
pointsData[(3 * i) + 1] = point[1];
pointsData[(3 * i) + 2] = point[2];
}
std::vector<size_t> pointsDimension = {3, points->GetNumberOfPoints()};
boost::shared_array<double> sharedPoints(pointsData);
//Unlabeled top item
QTreeWidgetItem* unlabeledItem;
boost::filesystem::path pointGroup = (boost::filesystem::path("pointclouds") / pointcloudName);
label_hdf5kernel.saveDoubleArray(pointGroup.string(), "Points" , pointsDimension, sharedPoints);
for (int i = 0; i < topItemCount; i++)
{
QTreeWidgetItem* topLevelItem = m_ui->treeWidget->topLevelItem(i);
if(topLevelItem->text(LABEL_NAME_COLUMN) == "Unlabeled")
{
unlabeledItem = topLevelItem;
}
boost::filesystem::path topLabel = topLevelItem->text(LABEL_NAME_COLUMN).toStdString();
int childCount = topLevelItem->childCount();
for (int j = 0; j < childCount; j++)
{
int childID = topLevelItem->child(j)->data(LABEL_ID_COLUMN, 0).toInt();
int* sharedArrayData = new int[idMap[childID].size()];
std::memcpy(sharedArrayData, idMap[childID].data(), idMap[childID].size() * sizeof(int));
boost::shared_array<int> data(sharedArrayData);
std::vector<size_t> dimension = {idMap[childID].size()};
if(idMap.find(childID) != idMap.end())
{
boost::filesystem::path childLabel = (topLevelItem->child(j)->text(LABEL_NAME_COLUMN)).toStdString();
boost::filesystem::path completeGroup = (pointGroup / boost::filesystem::path("labels") / topLabel / childLabel);
label_hdf5kernel.saveArray(completeGroup.string(), "IDs" , dimension, data);
int* rgbSharedData = new int[3];
(topLevelItem->child(j)->data(LABEL_ID_COLUMN, 1)).value<QColor>().getRgb(&rgbSharedData[0], &rgbSharedData[1], &rgbSharedData[2]);
boost::shared_array<int> rgbData(rgbSharedData);
std::vector<size_t> rgbDimension = {3};
label_hdf5kernel.saveArray(completeGroup.string(), "Color" , rgbDimension, rgbData);
}
}
}
}
void LVRLabelDialog::addNewLabel()
{
//Ask For the Label name
bool accepted;
QString label_name = QInputDialog::getText(m_dialog, tr("Select Label Name"),
tr("Label name:"), QLineEdit::Normal,
tr("LabelName") , &accepted);
if (!accepted || label_name.isEmpty())
{
//No valid Input
return;
}
QColor label_color = QColorDialog::getColor(Qt::red, m_dialog, tr("Choose default Label Color for label Class(willbe used for first isntance)"));
if (!label_color.isValid())
{
//Non Valid Color Return
return;
}
if (m_ui->treeWidget->topLevelItemCount() == 0)
{
//Setting up Top Label
QTreeWidgetItem * item = new QTreeWidgetItem();
item->setText(0, "Unlabeled");
item->setText(LABELED_POINT_COLUMN, QString::number(0));
item->setCheckState(LABEL_VISIBLE_COLUMN, Qt::Checked);
item->setData(LABEL_ID_COLUMN, 1, QColor(Qt::red));
//Setting up new child item
QTreeWidgetItem * childItem = new QTreeWidgetItem();
childItem->setText(LABEL_NAME_COLUMN, QString("Unlabeled") + QString::number(1));
childItem->setText(LABELED_POINT_COLUMN, QString::number(0));
childItem->setCheckState(LABEL_VISIBLE_COLUMN, Qt::Checked);
childItem->setData(LABEL_ID_COLUMN, 1, QColor(Qt::red));
childItem->setData(LABEL_ID_COLUMN, 0, 0);
item->addChild(childItem);
m_ui->treeWidget->addTopLevelItem(item);
//Added first Top Level item enable instance button
m_ui->newInstanceButton->setEnabled(true);
Q_EMIT(labelAdded(childItem));
}
int id = m_id_hack++;
//Setting up new Toplevel item
QTreeWidgetItem * item = new QTreeWidgetItem();
item->setText(0, label_name);
item->setText(LABELED_POINT_COLUMN, QString::number(0));
item->setCheckState(LABEL_VISIBLE_COLUMN, Qt::Checked);
item->setData(LABEL_ID_COLUMN, 1, label_color);
//Setting up new child item
QTreeWidgetItem * childItem = new QTreeWidgetItem();
childItem->setText(LABEL_NAME_COLUMN, label_name + QString::number(1));
childItem->setText(LABELED_POINT_COLUMN, QString::number(0));
childItem->setCheckState(LABEL_VISIBLE_COLUMN, Qt::Checked);
childItem->setData(LABEL_ID_COLUMN, 1, label_color);
childItem->setData(LABEL_ID_COLUMN, 0, id);
item->addChild(childItem);
m_ui->treeWidget->addTopLevelItem(item);
//Add label to combo box
m_ui->selectedLabelComboBox->addItem(childItem->text(LABEL_NAME_COLUMN), id);
Q_EMIT(labelAdded(childItem));
}
void LVRLabelDialog::addNewInstance()
{
QInputDialog topLevelDialog;
QStringList topLabels;
if (m_ui->treeWidget->topLevelItemCount() == 0)
{
return;
}
for (int i = 0; i < m_ui->treeWidget->topLevelItemCount(); i++)
{
if (m_ui->treeWidget->topLevelItem(i)->text(LABEL_NAME_COLUMN) != "Unlabeled")
{
topLabels << m_ui->treeWidget->topLevelItem(i)->text(LABEL_NAME_COLUMN);
}
}
topLevelDialog.setComboBoxItems(topLabels);
topLevelDialog.setWindowTitle("Create new Instance");
if (QDialog::Accepted != topLevelDialog.exec())
{
return;
}
QString choosenLabel = topLevelDialog.textValue();
QList<QTreeWidgetItem*> selectedTopLevelItem = m_ui->treeWidget->findItems(choosenLabel, Qt::MatchExactly);
if (selectedTopLevelItem.count() != 1)
{
return;
}
bool accepted;
QString instance_name = QInputDialog::getText(m_dialog, tr("Choose Name for new Instance"),
tr("Instance name:"), QLineEdit::Normal,
QString(choosenLabel + QString::number(selectedTopLevelItem[0]->childCount() + 1)) , &accepted);
if (!accepted || instance_name.isEmpty())
{
//No valid Input
return;
}
QColor label_color = QColorDialog::getColor(selectedTopLevelItem[0]->data(3,1).value<QColor>(), m_dialog, tr("Choose Label Color for first instance"));
if (!label_color.isValid())
{
//Non Valid Color Return
return;
}
int id = m_id_hack++;
QTreeWidgetItem * childItem = new QTreeWidgetItem();
childItem->setText(LABEL_NAME_COLUMN, instance_name);
childItem->setText(LABELED_POINT_COLUMN, QString::number(0));
childItem->setCheckState(LABEL_VISIBLE_COLUMN, Qt::Checked);
childItem->setData(LABEL_ID_COLUMN, 1, label_color);
childItem->setData(LABEL_ID_COLUMN, 0, id);
selectedTopLevelItem[0]->addChild(childItem);
//Add label to combo box
m_ui->selectedLabelComboBox->addItem(childItem->text(LABEL_NAME_COLUMN), id);
Q_EMIT(labelAdded(childItem));
}
void LVRLabelDialog::comboBoxIndexChanged(int index)
{
Q_EMIT(labelChanged(m_ui->selectedLabelComboBox->itemData(index).toInt()));
}
void LVRLabelDialog::setPoints(const std::string pointcloudName, const vtkSmartPointer<vtkPolyData> points)
{
m_points[pointcloudName] = points;
}
}
/* namespace lvr2 */
| 37.661479 | 164 | 0.638392 | uos |
ca1581293fe58f00e56c910efe420fdfa0932f6a | 1,388 | hpp | C++ | src/process.hpp | cbeck88/HexWarfare | 94a70b1889afc2fbd990892ed66be874ac70d1b4 | [
"Apache-2.0"
] | null | null | null | src/process.hpp | cbeck88/HexWarfare | 94a70b1889afc2fbd990892ed66be874ac70d1b4 | [
"Apache-2.0"
] | null | null | null | src/process.hpp | cbeck88/HexWarfare | 94a70b1889afc2fbd990892ed66be874ac70d1b4 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2014 Kristina Simpson <sweet.kristas@gmail.com>
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.
*/
#pragma once
#include "SDL.h"
#include "engine_fwd.hpp"
namespace process
{
enum class ProcessPriority {
input = 100,
ai = 200,
collision = 600,
action = 700,
world = 800,
gui = 850,
render = 900
};
// abstract system interface
class process
{
public:
explicit process(ProcessPriority priority);
virtual ~process();
virtual void start() {}
virtual void end() {}
virtual void update(engine& eng, double t, const entity_list& elist) = 0;
bool process_event(const SDL_Event& evt);
ProcessPriority get_priority() const { return priority_; }
private:
process();
virtual bool handle_event(const SDL_Event& evt) { return false; }
ProcessPriority priority_;
};
typedef std::shared_ptr<process> process_ptr;
}
| 25.236364 | 75 | 0.711816 | cbeck88 |
ca20024b441ffa9c64706c6f9000c4337c7d0249 | 4,154 | cpp | C++ | src/utils/string_helper.cpp | ppearson/sitemon2 | 22b5eaa03e9036c32b08a485917a3477078e6a57 | [
"Apache-2.0"
] | null | null | null | src/utils/string_helper.cpp | ppearson/sitemon2 | 22b5eaa03e9036c32b08a485917a3477078e6a57 | [
"Apache-2.0"
] | null | null | null | src/utils/string_helper.cpp | ppearson/sitemon2 | 22b5eaa03e9036c32b08a485917a3477078e6a57 | [
"Apache-2.0"
] | null | null | null | /*
Sitemon
Copyright 2010-2019 Peter Pearson.
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 "string_helper.h"
#include <time.h>
#include <stdlib.h>
#include <string.h> // for memset
#include <algorithm>
static const std::string kBase64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
void StringHelpers::split(const std::string& str, std::vector<std::string>& tokens, const std::string& sep)
{
int lastPos = str.find_first_not_of(sep, 0);
int pos = str.find_first_of(sep, lastPos);
while (lastPos != -1 || pos != -1)
{
tokens.push_back(str.substr(lastPos, pos - lastPos));
lastPos = str.find_first_not_of(sep, pos);
pos = str.find_first_of(sep, lastPos);
}
}
void StringHelpers::toLower(std::string& str)
{
unsigned int size = str.size();
for (unsigned int i = 0; i < size; i++)
str[i] = tolower(str[i]);
}
std::string StringHelpers::formatSize(size_t amount)
{
char szMemAvailable[16];
std::string units;
unsigned int size = 0;
char szDecimalSize[12];
if (amount >= 1024 * 1024 * 1024) // GB
{
size = amount / (1024 * 1024);
float fSize = (float)size / 1024.0f;
sprintf(szDecimalSize, "%.2f", fSize);
units = "GB";
}
else if (amount >= 1024 * 1024) // MB
{
size = amount / 1024;
float fSize = (float)size / 1024.0f;
sprintf(szDecimalSize, "%.2f", fSize);
units = "MB";
}
else if (amount >= 1024) // KB
{
size = amount;
float fSize = (float)size / 1024.0f;
sprintf(szDecimalSize, "%.1f", fSize);
units = "KB";
}
else
{
sprintf(szDecimalSize, "0");
units = "B"; // just so it makes sense
}
sprintf(szMemAvailable, "%s %s", szDecimalSize, units.c_str());
std::string final(szMemAvailable);
return final;
}
std::string StringHelpers::formatNumberThousandsSeparator(size_t value)
{
char szRawNumber[32];
sprintf(szRawNumber, "%zu", value);
std::string temp(szRawNumber);
std::string final;
int i = temp.size() - 1;
unsigned int count = 0;
for (; i >= 0; i--)
{
final += temp[i];
if (count++ == 2 && i != 0)
{
final += ",";
count = 0;
}
}
std::reverse(final.begin(), final.end());
return final;
}
std::string StringHelpers::base64Encode(const std::string& inputString)
{
std::string outputString;
int val0 = 0;
int val1 = -6;
for (unsigned int i = 0; i < inputString.size(); i++)
{
const char& c = inputString[i];
val0 = (val0 << 8) + c;
val1 += 8;
while (val1 >= 0)
{
outputString.push_back(kBase64Chars[(val0 >> val1) & 0x3F]);
val1 -= 6;
}
}
if (val1 > -6)
{
outputString.push_back(kBase64Chars[((val0 << 8) >> (val1 + 8)) & 0x3F]);
}
while (outputString.size() % 4)
{
outputString += "=";
}
return outputString;
}
std::string StringHelpers::base64Decode(const std::string& inputString)
{
std::string outputString;
// TODO: doing this each time is obviously inefficient...
std::vector<int> temp(256, -1);
for (unsigned int i = 0; i < 64; i++)
{
temp[kBase64Chars[i]] = i;
}
int val0 = 0;
int val1 = -8;
for (unsigned int i = 0; i < inputString.size(); i++)
{
const char& c = inputString[i];
if (temp[c] == -1)
break;
val0 = (val0 << 6) + temp[c];
val1 += 6;
if (val1 >= 0)
{
outputString.push_back((char)(val0 >> val1) & 0xFF);
val1 -= 8;
}
}
return outputString;
}
std::string StringHelpers::generateRandomASCIIString(unsigned int length)
{
srand(time(NULL));
char szRandomString[9];
memset(szRandomString, 0, 9);
for (unsigned int i = 0; i < 8; i++)
{
unsigned int index = rand() % 56;
szRandomString[i] = kBase64Chars[index] ;
}
return std::string(szRandomString);
}
| 21.523316 | 107 | 0.643476 | ppearson |
ca244e287288abc707731d63c571095c3162952d | 6,497 | cpp | C++ | d912pxy/d3d9_proxy_dll.cpp | febryjp/d912pxy | 208f741135ca108bc4742c69430dc5eb95578480 | [
"MIT"
] | 1,076 | 2019-01-11T02:04:35.000Z | 2022-03-24T19:00:46.000Z | d912pxy/d3d9_proxy_dll.cpp | NaturalBoy/d912pxy | ecca0dfdf8ae58cfb7b0ab9b1d9096acf3d8c829 | [
"MIT"
] | 398 | 2019-01-16T07:58:30.000Z | 2022-02-26T11:53:46.000Z | d912pxy/d3d9_proxy_dll.cpp | NaturalBoy/d912pxy | ecca0dfdf8ae58cfb7b0ab9b1d9096acf3d8c829 | [
"MIT"
] | 140 | 2019-01-25T09:58:31.000Z | 2022-03-24T10:56:41.000Z | /*
Original work: https://github.com/iorlas/D3D9Proxy
*/
//FIXME: correct this to be right, as i'm not shure
/*
MIT License
Copyright(c) 2018-2019 megai2
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 "stdafx.h"
#pragma pack(1)
HINSTANCE hlThis = 0;
HINSTANCE hlD3D9 = 0;
d3d9ProxyCB_OnDevCreate pxCb_devCreate = NULL;
d3d9ProxyCB_OnDevDestroy pxCb_devDestroy = NULL;
//megai2: added for win10 update compat
typedef void(*d3d9_ordinal_fn)();
#ifdef _DEBUG
#define d3d9_ordinal_export_passthru(a) d3d9_ordinal_fn d3d9_ordinal_ptr_##a; void d3d9_Ordinal##a() { return; }
#else
#define d3d9_ordinal_export_passthru(a) d3d9_ordinal_fn d3d9_ordinal_ptr_##a; void d3d9_Ordinal##a() { d3d9_ordinal_ptr_##a(); return; }
#endif
#define d3d9_ordinal_get_orig_adr(a) d3d9_ordinal_ptr_##a = (d3d9_ordinal_fn)GetProcAddress(hlD3D9, MAKEINTRESOURCEA(a))
#define d3d9_ordinal_gen_macro(a) a(16); a(17); a(18); a(19); a(20); a(21); a(22); a(23);
bool loadD3D9dll();
d3d9_ordinal_gen_macro(d3d9_ordinal_export_passthru);
//
bool loadD3D9dll()
{
//Get path to the original d3d9.dll
wchar_t infoBuf[4096];
GetSystemDirectory(infoBuf, 4096);
lstrcatW(infoBuf, L"\\d3d9.dll");
//megai2: moved first init here, due to static dll load DllMain crashes
d912pxy_first_init();
hlD3D9 = LoadLibrary(infoBuf);
if (!hlD3D9) {
MessageBox(NULL, L"Cannot find original d3d9.dll in the system directory!", L"D3D9 Proxy DLL error", MB_OK | MB_ICONERROR);
return FALSE;
}
else {
d3d9_ordinal_gen_macro(d3d9_ordinal_get_orig_adr);
return TRUE;
}
}
bool d3d9_proxy_dll_main(HINSTANCE hInst, DWORD reason, LPVOID)
{
if (reason == DLL_PROCESS_ATTACH)
{
hlThis = hInst;
}
else if (reason == DLL_PROCESS_DETACH) {
}
return TRUE;
}
void D3D9ProxyCb_set_OnDevCreate(d3d9ProxyCB_OnDevCreate pxFun) {
pxCb_devCreate = pxFun;
}
d3d9ProxyCB_OnDevCreate D3D9ProxyCb_get_OnDevCreate() {
return pxCb_devCreate;
}
//Direct3DCreate9
extern "C" IDirect3D9* WINAPI Direct3DCreate9(UINT SDKVersion) {
//Recall original function
typedef IDirect3D9* (WINAPI* Direct3DCreate9Func)(UINT sdkver);
if (!hlD3D9)
loadD3D9dll();
Direct3DCreate9Func origDirect3DCreate9 = (Direct3DCreate9Func)GetProcAddress(hlD3D9, "Direct3DCreate9");
IDirect3D9* res = origDirect3DCreate9(SDKVersion);
return new IDirect3D9Proxy(res);
}
extern "C" HRESULT WINAPI Direct3DCreate9Ex(
_In_ UINT SDKVersion,
_Out_ IDirect3D9Ex **ppD3D
)
{
typedef HRESULT (WINAPI* Direct3DCreate9Ex_t)(UINT SDKVersion, IDirect3D9Ex ** ppD3D);
static Direct3DCreate9Ex_t _imp_Direct3DCreate9Ex = NULL;
if (!hlD3D9)
loadD3D9dll();
if (hlD3D9 && !_imp_Direct3DCreate9Ex) {
_imp_Direct3DCreate9Ex = (Direct3DCreate9Ex_t)GetProcAddress(hlD3D9, "Direct3DCreate9Ex");
}
if (_imp_Direct3DCreate9Ex)
return _imp_Direct3DCreate9Ex(SDKVersion, ppD3D);
return D3DERR_NOTAVAILABLE;
}
extern "C" int WINAPI D3DPERF_BeginEvent(D3DCOLOR col, LPCWSTR wszName)
{
typedef int (WINAPI* BeginEvent_t)(D3DCOLOR, LPCWSTR);
static BeginEvent_t _imp_BeginEvent = NULL;
if (!hlD3D9)
loadD3D9dll();
if (hlD3D9 && !_imp_BeginEvent)
_imp_BeginEvent = (BeginEvent_t)GetProcAddress(hlD3D9, "D3DPERF_BeginEvent");
if (_imp_BeginEvent)
return _imp_BeginEvent(col, wszName);
return D3DERR_NOTAVAILABLE;
}
extern "C" int WINAPI D3DPERF_EndEvent(void)
{
typedef int (WINAPI* EndEvent_t)(void);
static EndEvent_t _imp_EndEvent = NULL;
if (!hlD3D9)
loadD3D9dll();
if (hlD3D9 && !_imp_EndEvent)
_imp_EndEvent = (EndEvent_t)GetProcAddress(hlD3D9, "D3DPERF_EndEvent");
if (_imp_EndEvent)
return _imp_EndEvent();
return D3DERR_NOTAVAILABLE;
}
extern "C" void WINAPI D3DPERF_SetMarker(D3DCOLOR col, LPCWSTR wszName)
{
typedef VOID(WINAPI* Direct3DSet_t)(D3DCOLOR, LPCWSTR);
static Direct3DSet_t _imp_SetMarker = NULL;
if (!hlD3D9)
loadD3D9dll();
if (hlD3D9 && !_imp_SetMarker)
_imp_SetMarker = (Direct3DSet_t)GetProcAddress(hlD3D9, "D3DPERF_SetMarker");
if (_imp_SetMarker)
_imp_SetMarker(col, wszName);
}
extern "C" void WINAPI D3DPERF_SetRegion(D3DCOLOR col, LPCWSTR wszName)
{
typedef VOID(WINAPI* Direct3DSet_t)(D3DCOLOR, LPCWSTR);
static Direct3DSet_t _imp_SetRegion = NULL;
if (!hlD3D9)
loadD3D9dll();
if (hlD3D9 && !_imp_SetRegion)
_imp_SetRegion = (Direct3DSet_t)GetProcAddress(hlD3D9, "D3DPERF_SetRegion");
if (_imp_SetRegion)
_imp_SetRegion(col, wszName);
}
extern "C" BOOL WINAPI D3DPERF_QueryRepeatFrame(void)
{
typedef BOOL(WINAPI* QueryRepeatFrame_t)(void);
static QueryRepeatFrame_t _imp_QueryRepeatFrame = NULL;
if (!hlD3D9)
loadD3D9dll();
if (hlD3D9 && !_imp_QueryRepeatFrame)
_imp_QueryRepeatFrame = (QueryRepeatFrame_t)GetProcAddress(hlD3D9, "D3DPERF_QueryRepeatFrame");
if (_imp_QueryRepeatFrame)
return _imp_QueryRepeatFrame();
return FALSE;
}
extern "C" void WINAPI D3DPERF_SetOptions(DWORD dwOptions)
{
typedef void (WINAPI* SetOptions_t)(DWORD);
static SetOptions_t _imp_SetOptions = NULL;
if (!hlD3D9)
loadD3D9dll();
if (hlD3D9 && !_imp_SetOptions)
_imp_SetOptions = (SetOptions_t)GetProcAddress(hlD3D9, "D3DPERF_SetOptions");
if (_imp_SetOptions)
_imp_SetOptions(dwOptions);
}
extern "C" DWORD WINAPI D3DPERF_GetStatus(void)
{
typedef DWORD(WINAPI* GetStatus_t)(void);
static GetStatus_t _imp_GetStatus = NULL;
if (!hlD3D9)
loadD3D9dll();
if (hlD3D9 && !_imp_GetStatus)
_imp_GetStatus = (GetStatus_t)GetProcAddress(hlD3D9, "D3DPERF_GetStatus");
if (_imp_GetStatus)
return _imp_GetStatus();
return 0;
}
| 25.182171 | 136 | 0.765276 | febryjp |
ca27e8edb38f080deeb5feba82d5cddf7f7985c4 | 1,387 | hpp | C++ | benchmark/include/uBLAS/convolution.hpp | bebuch/Mitrax | bc33a1b93058886daab3e4ef736ef9b519111454 | [
"BSL-1.0"
] | null | null | null | benchmark/include/uBLAS/convolution.hpp | bebuch/Mitrax | bc33a1b93058886daab3e4ef736ef9b519111454 | [
"BSL-1.0"
] | null | null | null | benchmark/include/uBLAS/convolution.hpp | bebuch/Mitrax | bc33a1b93058886daab3e4ef736ef9b519111454 | [
"BSL-1.0"
] | null | null | null | //-----------------------------------------------------------------------------
// Copyright (c) 2016 Benjamin Buch
//
// https://github.com/bebuch/mitrax
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
//-----------------------------------------------------------------------------
#ifndef _mitrax__uBLAS__convolution__hpp_INCLUDED_
#define _mitrax__uBLAS__convolution__hpp_INCLUDED_
#include <boost/numeric/ublas/matrix.hpp>
namespace uBLAS{
namespace ublas = boost::numeric::ublas;
template < typename M1, typename M2 >
inline auto convolution(M1 const& m, M2 const& k){
int kc = k.size1();
int kr = k.size2();
int res_c = m.size1() - kc + 1;
int res_r = m.size2() - kr + 1;
using value_type = typename M2::value_type;
ublas::matrix< value_type > res(res_c, res_r);
for(int my = 0; my < res_r; ++my){
for(int mx = 0; mx < res_c; ++mx){
value_type b = 0;
for(int ky = 0; ky < kr; ++ky){
for(int kx = 0; kx < kc; ++kx){
b += m(mx + kx, my + ky) * k(kx, ky);
}
}
res(mx, my) = b;
}
}
return res;
}
template < typename TM, typename V1, typename V2 >
inline auto convolution(
ublas::matrix< TM > const& m,
V1 const& vc,
V2 const& vr
){
return convolution(convolution(m, vr), vc);
}
}
#endif
| 22.370968 | 79 | 0.561644 | bebuch |
ca2ba9e3c132322d4f1e76698384f02df89c995b | 2,108 | cpp | C++ | Minigin/Game/TileTexture.cpp | DaanRavelingien/2DGameEngine | d1c9f4864c4183d1e4d8a15c986f2b0ab032f73b | [
"MIT"
] | null | null | null | Minigin/Game/TileTexture.cpp | DaanRavelingien/2DGameEngine | d1c9f4864c4183d1e4d8a15c986f2b0ab032f73b | [
"MIT"
] | null | null | null | Minigin/Game/TileTexture.cpp | DaanRavelingien/2DGameEngine | d1c9f4864c4183d1e4d8a15c986f2b0ab032f73b | [
"MIT"
] | null | null | null | #include "TileTexture.h"
#include <ResourceManager.h>
#include "HexGrid.h"
#include <Render.h>
#include <Transform.h>
#include <GameObject.h>
#include <Texture2D.h>
Comp::TileTexture::TileTexture(const std::string& filePath)
:m_FileName{filePath}
{
GetNeededComponents();
m_NeedsUpdate = true;
}
void Comp::TileTexture::Initialize()
{
if(!HasAllComponents())
GetNeededComponents();
}
void Comp::TileTexture::Update()
{
if (!HasAllComponents())
return;
if (!m_NeedsUpdate)
return;
std::vector<std::vector<bool>> grid = m_pHexGridComp->GetGrid();
//remove the old textures form the render component and add the new ones
if (m_pTileTexture)
m_pRenderComp->RemoveTextures(m_pTileTexture);
for (int i{}; i< m_pHexGridComp->GetGridDimentions().x;++i)
{
for (int j{}; j<m_pHexGridComp->GetGridDimentions().y; j++)
{
//check if the current tile is a valid tile
if (grid.at(i).at(j))
{
glm::vec4 destRect{ m_pHexGridComp->AxialToPxl(glm::vec2{i,j})
,m_pHexGridComp->GetTileSize().x * m_pTransformComp->GetScale().x
,m_pHexGridComp->GetTileSize().y * m_pTransformComp->GetScale().y };
//create the new texture that needs to be rendered
CreateTexture();
m_pTileTexture->SetSrcRect(m_SrcRect);
m_pTileTexture->SetDestRect(destRect);
//add the new texture to the render component so its rendered
m_pRenderComp->AddTexture(m_pTileTexture);
}
}
}
m_NeedsUpdate = false;
}
void Comp::TileTexture::SetSrcRect(const glm::vec4& srcRect)
{
m_SrcRect = srcRect;
m_NeedsUpdate = true;
}
void Comp::TileTexture::GetNeededComponents()
{
Component::GetNeededComponents();
if (m_pGameObject.lock())
{
m_pRenderComp = m_pGameObject.lock()->GetComponent<Comp::RenderComp>();
m_pHexGridComp = m_pGameObject.lock()->GetComponent<Comp::HexGrid>();
}
}
bool Comp::TileTexture::HasAllComponents() const
{
if (!m_pHexGridComp)
return false;
if (!m_pRenderComp)
return false;
return true;
}
void Comp::TileTexture::CreateTexture()
{
m_pTileTexture = dae::ResourceManager::GetInstance().LoadTexture(m_FileName);
m_NeedsUpdate = true;
} | 23.422222 | 78 | 0.718691 | DaanRavelingien |
ca2ec71a057171ee721eead2933a80fa4babca1b | 31,288 | cpp | C++ | client/Rendering/WaterRenderer.cpp | gitdnd/NovusCore-Client | 51e76ffe579734cb93a76b6f6d6db8bec8855676 | [
"MIT"
] | null | null | null | client/Rendering/WaterRenderer.cpp | gitdnd/NovusCore-Client | 51e76ffe579734cb93a76b6f6d6db8bec8855676 | [
"MIT"
] | null | null | null | client/Rendering/WaterRenderer.cpp | gitdnd/NovusCore-Client | 51e76ffe579734cb93a76b6f6d6db8bec8855676 | [
"MIT"
] | null | null | null | #include "WaterRenderer.h"
#include "DebugRenderer.h"
#include "../Utils/ServiceLocator.h"
#include "../Utils/MapUtils.h"
#include "RenderResources.h"
#include "CVar/CVarSystem.h"
#include "Camera.h"
#include "RenderUtils.h"
#include <filesystem>
#include <GLFW/glfw3.h>
#include <InputManager.h>
#include <Renderer/Renderer.h>
#include <Renderer/RenderGraph.h>
#include <Utils/FileReader.h>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/euler_angles.hpp>
#include <tracy/TracyVulkan.hpp>
#include "../ECS/Components/Singletons/MapSingleton.h"
#include "../ECS/Components/Singletons/NDBCSingleton.h"
#include "../ECS/Components/Singletons/TextureSingleton.h"
namespace fs = std::filesystem;
AutoCVar_Int CVAR_WaterCullingEnabled("water.cullEnable", "enable culling of water", 1, CVarFlags::EditCheckbox);
AutoCVar_Int CVAR_WaterLockCullingFrustum("water.lockCullingFrustum", "lock frustrum for water culling", 0, CVarFlags::EditCheckbox);
AutoCVar_Int CVAR_WaterDrawBoundingBoxes("water.drawBoundingBoxes", "draw bounding boxes for water", 0, CVarFlags::EditCheckbox);
AutoCVar_Int CVAR_WaterOcclusionCullEnabled("water.occlusionCullEnable", "enable culling of water", 1, CVarFlags::EditCheckbox);
AutoCVar_Float CVAR_WaterVisibilityRange("water.visibilityRange", "How far underwater you should see", 3.0f, CVarFlags::EditFloatDrag);
WaterRenderer::WaterRenderer(Renderer::Renderer* renderer, DebugRenderer* debugRenderer)
: _renderer(renderer)
, _debugRenderer(debugRenderer)
{
CreatePermanentResources();
}
WaterRenderer::~WaterRenderer()
{
}
void WaterRenderer::Update(f32 deltaTime)
{
f32 waterProgress = deltaTime * 30.0f;
_drawConstants.currentTime = std::fmodf(_drawConstants.currentTime + waterProgress, 30.0f);
// Update arealight water color
{
entt::registry* registry = ServiceLocator::GetGameRegistry();
MapSingleton& mapSingleton = registry->ctx<MapSingleton>();
i32 lockLight = *CVarSystem::Get()->GetIntCVar("lights.lock");
if (!lockLight)
{
const AreaUpdateLightColorData& lightColor = mapSingleton.GetLightColorData();
_drawConstants.shallowOceanColor = lightColor.shallowOceanColor;
_drawConstants.deepOceanColor = lightColor.deepOceanColor;
_drawConstants.shallowRiverColor = lightColor.shallowRiverColor;
_drawConstants.deepRiverColor = lightColor.deepRiverColor;
}
}
_drawConstants.waterVisibilityRange = Math::Max(CVAR_WaterVisibilityRange.GetFloat(), 1.0f);
bool drawBoundingBoxes = CVAR_WaterDrawBoundingBoxes.Get() == 1;
if (drawBoundingBoxes)
{
_boundingBoxes.ReadLock([&](const std::vector<AABB>& boundingBoxes)
{
for (const AABB& boundingBox : boundingBoxes)
{
vec3 center = (vec3(boundingBox.min) + vec3(boundingBox.max)) * 0.5f;
vec3 extents = vec3(boundingBox.max) - center;
_debugRenderer->DrawAABB3D(center, extents, 0xff00ffff);
}
});
}
u32 numDrawCalls = static_cast<u32>(_drawCalls.Size());
_numSurvivingDrawCalls = numDrawCalls;
_numSurvivingTriangles = _numTriangles;
const bool cullingEnabled = CVAR_WaterCullingEnabled.Get();
if (cullingEnabled && numDrawCalls > 0)
{
// Drawcalls
{
u32* count = static_cast<u32*>(_renderer->MapBuffer(_culledDrawCountReadBackBuffer));
if (count != nullptr)
{
_numSurvivingDrawCalls = *count;
}
_renderer->UnmapBuffer(_culledDrawCountReadBackBuffer);
}
// Triangles
{
u32* count = static_cast<u32*>(_renderer->MapBuffer(_culledTriangleCountReadBackBuffer));
if (count != nullptr)
{
_numSurvivingTriangles = *count;
}
_renderer->UnmapBuffer(_culledTriangleCountReadBackBuffer);
}
}
}
void WaterRenderer::LoadWater(SafeVector<u16>& chunkIDs)
{
RegisterChunksToBeLoaded(chunkIDs);
ExecuteLoad();
}
void WaterRenderer::Clear()
{
_drawCalls.Clear();
_drawCallDatas.Clear();
_vertices.Clear();
_indices.Clear();
_boundingBoxes.Clear();
_waterTextureInfos.clear();
_renderer->UnloadTexturesInArray(_waterTextures, 0);
}
void WaterRenderer::AddCullingPass(Renderer::RenderGraph* renderGraph, RenderResources& resources, u8 frameIndex)
{
u32 numDrawCalls = static_cast<u32>(_drawCalls.Size());
if (numDrawCalls == 0)
return;
const bool cullingEnabled = CVAR_WaterCullingEnabled.Get();
if (!cullingEnabled)
return;
const bool lockFrustum = CVAR_WaterLockCullingFrustum.Get();
struct WaterCullingPassData
{
Renderer::RenderPassMutableResource depth;
};
renderGraph->AddPass<WaterCullingPassData>("Water Culling",
[=](WaterCullingPassData& data, Renderer::RenderGraphBuilder& builder)
{
data.depth = builder.Write(resources.depth, Renderer::RenderGraphBuilder::WriteMode::RENDERTARGET, Renderer::RenderGraphBuilder::LoadMode::LOAD);
return true; // Return true from setup to enable this pass, return false to disable it
},
[=](WaterCullingPassData& data, Renderer::RenderGraphResources& graphResources, Renderer::CommandList& commandList)
{
GPU_SCOPED_PROFILER_ZONE(commandList, WaterCullingPass);
// Update constants
if (!lockFrustum)
{
Camera* camera = ServiceLocator::GetCamera();
memcpy(_cullConstants.frustumPlanes, camera->GetFrustumPlanes(), sizeof(vec4[6]));
_cullConstants.cameraPos = camera->GetPosition();
}
// Reset the counters
commandList.FillBuffer(_culledDrawCountBuffer, 0, 4, 0);
commandList.FillBuffer(_culledTriangleCountBuffer, 0, 4, 0);
commandList.PipelineBarrier(Renderer::PipelineBarrierType::TransferDestToComputeShaderRW, _culledDrawCountBuffer);
commandList.PipelineBarrier(Renderer::PipelineBarrierType::TransferDestToComputeShaderRW, _culledTriangleCountBuffer);
Renderer::ComputePipelineDesc cullingPipelineDesc;
graphResources.InitializePipelineDesc(cullingPipelineDesc);
Renderer::ComputeShaderDesc shaderDesc;
shaderDesc.path = "waterCulling.cs.hlsl";
cullingPipelineDesc.computeShader = _renderer->LoadShader(shaderDesc);
Renderer::ComputePipelineID pipeline = _renderer->CreatePipeline(cullingPipelineDesc);
commandList.BeginPipeline(pipeline);
// Make a framelocal copy of our cull constants
CullConstants* cullConstants = graphResources.FrameNew<CullConstants>();
memcpy(cullConstants, &_cullConstants, sizeof(CullConstants));
cullConstants->maxDrawCount = numDrawCalls;
cullConstants->occlusionCull = CVAR_WaterOcclusionCullEnabled.Get();
commandList.PushConstant(cullConstants, 0, sizeof(CullConstants));
_cullingDescriptorSet.Bind("_depthPyramid"_h, resources.depthPyramid);
commandList.BindDescriptorSet(Renderer::DescriptorSetSlot::PER_PASS, &_cullingDescriptorSet, frameIndex);
commandList.BindDescriptorSet(Renderer::DescriptorSetSlot::GLOBAL, &resources.globalDescriptorSet, frameIndex);
commandList.Dispatch((numDrawCalls + 31) / 32, 1, 1);
commandList.EndPipeline(pipeline);
});
}
void WaterRenderer::AddWaterPass(Renderer::RenderGraph* renderGraph, RenderResources& resources, u8 frameIndex)
{
u32 numDrawCalls = static_cast<u32>(_drawCalls.Size());
if (numDrawCalls == 0)
return;
const bool cullingEnabled = CVAR_WaterCullingEnabled.Get();
struct WaterPassData
{
Renderer::RenderPassMutableResource transparency;
Renderer::RenderPassMutableResource transparencyWeights;
Renderer::RenderPassMutableResource depth;
};
renderGraph->AddPass<WaterPassData>("Water OIT Pass",
[=](WaterPassData& data, Renderer::RenderGraphBuilder& builder)
{
data.transparency = builder.Write(resources.transparency, Renderer::RenderGraphBuilder::WriteMode::RENDERTARGET, Renderer::RenderGraphBuilder::LoadMode::LOAD);
data.transparencyWeights = builder.Write(resources.transparencyWeights, Renderer::RenderGraphBuilder::WriteMode::RENDERTARGET, Renderer::RenderGraphBuilder::LoadMode::LOAD);
data.depth = builder.Write(resources.depth, Renderer::RenderGraphBuilder::WriteMode::RENDERTARGET, Renderer::RenderGraphBuilder::LoadMode::LOAD);
return true; // Return true from setup to enable this pass, return false to disable it
},
[=](WaterPassData& data, Renderer::RenderGraphResources& graphResources, Renderer::CommandList& commandList)
{
GPU_SCOPED_PROFILER_ZONE(commandList, WaterPass);
commandList.PushMarker("Water", Color::White);
RenderUtils::CopyDepthToColorRT(_renderer, graphResources, commandList, frameIndex, resources.depth, resources.depthColorCopy, 0);
commandList.ImageBarrier(resources.transparency);
commandList.ImageBarrier(resources.transparencyWeights);
if (cullingEnabled)
{
commandList.PipelineBarrier(Renderer::PipelineBarrierType::ComputeWriteToIndirectArguments, _culledDrawCallsBuffer);
commandList.PipelineBarrier(Renderer::PipelineBarrierType::ComputeWriteToIndirectArguments, _culledDrawCountBuffer);
}
Renderer::GraphicsPipelineDesc pipelineDesc;
graphResources.InitializePipelineDesc(pipelineDesc);
// Shaders
Renderer::VertexShaderDesc vertexShaderDesc;
vertexShaderDesc.path = "water.vs.hlsl";
pipelineDesc.states.vertexShader = _renderer->LoadShader(vertexShaderDesc);
Renderer::PixelShaderDesc pixelShaderDesc;
pixelShaderDesc.path = "water.ps.hlsl";
pipelineDesc.states.pixelShader = _renderer->LoadShader(pixelShaderDesc);
// Depth state
pipelineDesc.states.depthStencilState.depthEnable = true;
pipelineDesc.states.depthStencilState.depthFunc = Renderer::ComparisonFunc::GREATER;
// Rasterizer state
pipelineDesc.states.rasterizerState.cullMode = Renderer::CullMode::BACK;
pipelineDesc.states.rasterizerState.frontFaceMode = Renderer::Settings::FRONT_FACE_STATE;
// Blend state
pipelineDesc.states.blendState.independentBlendEnable = true;
pipelineDesc.states.blendState.renderTargets[0].blendEnable = true;
pipelineDesc.states.blendState.renderTargets[0].blendOp = Renderer::BlendOp::ADD;
pipelineDesc.states.blendState.renderTargets[0].srcBlend = Renderer::BlendMode::ONE;
pipelineDesc.states.blendState.renderTargets[0].destBlend = Renderer::BlendMode::ONE;
pipelineDesc.states.blendState.renderTargets[0].srcBlendAlpha = Renderer::BlendMode::ONE;
pipelineDesc.states.blendState.renderTargets[0].destBlendAlpha = Renderer::BlendMode::ONE;
pipelineDesc.states.blendState.renderTargets[0].blendOpAlpha = Renderer::BlendOp::ADD;
pipelineDesc.states.blendState.renderTargets[1].blendEnable = true;
pipelineDesc.states.blendState.renderTargets[1].blendOp = Renderer::BlendOp::ADD;
pipelineDesc.states.blendState.renderTargets[1].srcBlend = Renderer::BlendMode::ZERO;
pipelineDesc.states.blendState.renderTargets[1].destBlend = Renderer::BlendMode::INV_SRC_COLOR;
pipelineDesc.states.blendState.renderTargets[1].srcBlendAlpha = Renderer::BlendMode::ZERO;
pipelineDesc.states.blendState.renderTargets[1].destBlendAlpha = Renderer::BlendMode::INV_SRC_ALPHA;
pipelineDesc.states.blendState.renderTargets[1].blendOpAlpha = Renderer::BlendOp::ADD;
// Render targets
pipelineDesc.renderTargets[0] = data.transparency;
pipelineDesc.renderTargets[1] = data.transparencyWeights;
pipelineDesc.depthStencil = data.depth;
// Set pipeline
Renderer::GraphicsPipelineID pipeline = _renderer->CreatePipeline(pipelineDesc); // This will compile the pipeline and return the ID, or just return ID of cached pipeline
commandList.BeginPipeline(pipeline);
_passDescriptorSet.Bind("_depthRT"_h, resources.depthColorCopy);
commandList.BindDescriptorSet(Renderer::DescriptorSetSlot::GLOBAL, &resources.globalDescriptorSet, frameIndex);
commandList.BindDescriptorSet(Renderer::DescriptorSetSlot::PER_PASS, &_passDescriptorSet, frameIndex);
DrawConstants* constants = graphResources.FrameNew<DrawConstants>();
memcpy(constants, &_drawConstants, sizeof(DrawConstants));
commandList.PushConstant(constants, 0, sizeof(DrawConstants));
commandList.SetIndexBuffer(_indices.GetBuffer(), Renderer::IndexFormat::UInt16);
if (cullingEnabled)
{
commandList.DrawIndexedIndirectCount(_culledDrawCallsBuffer, 0, _culledDrawCountBuffer, 0, numDrawCalls);
}
else
{
commandList.DrawIndexedIndirect(_drawCalls.GetBuffer(), 0, numDrawCalls);
}
commandList.PopMarker();
commandList.EndPipeline(pipeline);
// Copy from our draw count buffer to the readback buffer
commandList.PipelineBarrier(Renderer::PipelineBarrierType::TransferDestToTransferSrc, _culledDrawCountBuffer);
commandList.CopyBuffer(_culledDrawCountReadBackBuffer, 0, _culledDrawCountBuffer, 0, 4);
commandList.PipelineBarrier(Renderer::PipelineBarrierType::TransferDestToTransferSrc, _culledDrawCountReadBackBuffer);
commandList.PipelineBarrier(Renderer::PipelineBarrierType::ComputeWriteToTransferSrc, _culledTriangleCountBuffer);
commandList.CopyBuffer(_culledTriangleCountReadBackBuffer, 0, _culledTriangleCountBuffer, 0, 4);
commandList.PipelineBarrier(Renderer::PipelineBarrierType::ComputeWriteToTransferSrc, _culledTriangleCountReadBackBuffer);
});
}
void WaterRenderer::CreatePermanentResources()
{
Renderer::TextureArrayDesc textureArrayDesc;
textureArrayDesc.size = 1024;
_waterTextures = _renderer->CreateTextureArray(textureArrayDesc);
_passDescriptorSet.Bind("_textures"_h, _waterTextures);
Renderer::SamplerDesc samplerDesc;
samplerDesc.enabled = true;
samplerDesc.filter = Renderer::SamplerFilter::ANISOTROPIC;//Renderer::SamplerFilter::SAMPLER_FILTER_MIN_MAG_LINEAR_MIP_POINT;
samplerDesc.addressU = Renderer::TextureAddressMode::WRAP;
samplerDesc.addressV = Renderer::TextureAddressMode::WRAP;
samplerDesc.addressW = Renderer::TextureAddressMode::CLAMP;
samplerDesc.shaderVisibility = Renderer::ShaderVisibility::PIXEL;
samplerDesc.maxAnisotropy = 8;
_sampler = _renderer->CreateSampler(samplerDesc);
_passDescriptorSet.Bind("_sampler"_h, _sampler);
Renderer::SamplerDesc occlusionSamplerDesc;
occlusionSamplerDesc.filter = Renderer::SamplerFilter::MINIMUM_MIN_MAG_MIP_LINEAR;
occlusionSamplerDesc.addressU = Renderer::TextureAddressMode::CLAMP;
occlusionSamplerDesc.addressV = Renderer::TextureAddressMode::CLAMP;
occlusionSamplerDesc.addressW = Renderer::TextureAddressMode::CLAMP;
occlusionSamplerDesc.minLOD = 0.f;
occlusionSamplerDesc.maxLOD = 16.f;
occlusionSamplerDesc.mode = Renderer::SamplerReductionMode::MIN;
_occlusionSampler = _renderer->CreateSampler(occlusionSamplerDesc);
_cullingDescriptorSet.Bind("_depthSampler"_h, _occlusionSampler);
}
bool WaterRenderer::RegisterChunksToBeLoaded(SafeVector<u16>& chunkIDs)
{
DebugHandler::Print("Loading Water");
entt::registry* registry = ServiceLocator::GetGameRegistry();
MapSingleton& mapSingleton = registry->ctx<MapSingleton>();
NDBCSingleton& ndbcSingleton = registry->ctx<NDBCSingleton>();
NDBC::File* liquidTypesNDBC = ndbcSingleton.GetNDBCFile("LiquidTypes"_h);
StringTable*& liquidTypesStringTable = liquidTypesNDBC->GetStringTable();
Terrain::Map& currentMap = mapSingleton.GetCurrentMap();
_numTriangles = 0;
chunkIDs.ReadLock([&](const std::vector<u16>& chunkIDsVector)
{
SafeVectorScopedWriteLock verticesLock(_vertices);
std::vector<WaterVertex>& vertices = verticesLock.Get();
SafeVectorScopedWriteLock indicesLock(_indices);
std::vector<u16>& indices = indicesLock.Get();
SafeVectorScopedWriteLock drawCallsLock(_drawCalls);
std::vector<DrawCall>& drawCalls = drawCallsLock.Get();
SafeVectorScopedWriteLock drawCallDatasLock(_drawCallDatas);
std::vector<DrawCallData>& drawCallDatas = drawCallDatasLock.Get();
SafeVectorScopedWriteLock boundingBoxesLock(_boundingBoxes);
std::vector<AABB>& boundingBoxes = boundingBoxesLock.Get();
for (const u16& chunkID : chunkIDsVector)
{
Terrain::Chunk& chunk = currentMap.chunks[chunkID];
u16 chunkX = chunkID % Terrain::MAP_CHUNKS_PER_MAP_STRIDE;
u16 chunkY = chunkID / Terrain::MAP_CHUNKS_PER_MAP_STRIDE;
vec2 chunkPos = Terrain::MapUtils::GetChunkPosition(chunkID);
vec3 chunkBasePos = Terrain::MAP_HALF_SIZE - vec3(Terrain::MAP_CHUNK_SIZE * chunkY, Terrain::MAP_CHUNK_SIZE * chunkX, Terrain::MAP_HALF_SIZE);
if (chunk.liquidHeaders.size() == 0)
continue;
u32 liquidInfoOffset = 0;
for (u32 i = 0; i < chunk.liquidHeaders.size(); i++)
{
Terrain::CellLiquidHeader& liquidHeader = chunk.liquidHeaders[i];
bool hasAttributes = liquidHeader.attributesOffset > 0; // liquidHeader.packedData >> 7;
u8 numInstances = liquidHeader.layerCount; // liquidHeader.packedData & 0x7F;
if (numInstances == 0)
continue;
u16 cellX = i % Terrain::MAP_CELLS_PER_CHUNK_SIDE;
u16 cellY = i / Terrain::MAP_CELLS_PER_CHUNK_SIDE;
vec3 liquidBasePos = chunkBasePos - vec3(Terrain::MAP_CELL_SIZE * cellY, Terrain::MAP_CELL_SIZE * cellX, 0);
const vec2 cellPos = Terrain::MapUtils::GetCellPosition(chunkPos, i);
for (u32 j = 0; j < numInstances; j++)
{
Terrain::CellLiquidInstance& liquidInstance = chunk.liquidInstances[liquidInfoOffset + j];
// Packed Format
// Bit 1-6 (liquidVertexFormat)
// Bit 7 (hasBitMaskForPatches)
// Bit 8 (hasVertexData)
bool hasVertexData = liquidInstance.vertexDataOffset > 0; // liquidInstance.packedData >> 7;
bool hasBitMaskForPatches = liquidInstance.bitmapExistsOffset > 0; // (liquidInstance.packedData >> 6) & 0x1;
u16 liquidVertexFormat = liquidInstance.liquidVertexFormat; // liquidInstance.packedData & 0x3F;
u8 posY = liquidInstance.yOffset; //liquidInstance.packedOffset & 0xf;
u8 posX = liquidInstance.xOffset; //liquidInstance.packedOffset >> 4;
u8 height = liquidInstance.height; // liquidInstance.packedSize & 0xf;
u8 width = liquidInstance.width; // liquidInstance.packedSize >> 4;
u32 vertexCount = (width + 1) * (height + 1);
f32* heightMap = nullptr;
if (hasVertexData)
{
if (liquidVertexFormat == 0) // LiquidVertexFormat_Height_Depth
{
heightMap = reinterpret_cast<f32*>(&chunk.liquidBytes[liquidInstance.vertexDataOffset]);
}
else if (liquidVertexFormat == 1) // LiquidVertexFormat_Height_UV
{
heightMap = reinterpret_cast<f32*>(&chunk.liquidBytes[liquidInstance.vertexDataOffset]);
}
else if (liquidVertexFormat == 3) // LiquidVertexFormat_Height_UV_Depth
{
heightMap = reinterpret_cast<f32*>(&chunk.liquidBytes[liquidInstance.vertexDataOffset]);
}
}
DrawCall& drawCall = drawCalls.emplace_back();
drawCall.instanceCount = 1;
drawCall.vertexOffset = static_cast<u32>(vertices.size());
drawCall.firstIndex = static_cast<u32>(indices.size());
drawCall.firstInstance = static_cast<u32>(drawCalls.size()) - 1;
DrawCallData& drawCallData = drawCallDatas.emplace_back();
drawCallData.chunkID = chunkID;
drawCallData.cellID = i;
NDBC::LiquidType* liquidType = liquidTypesNDBC->GetRowById<NDBC::LiquidType>(liquidInstance.liquidType);
const std::string& liquidTexture = liquidTypesStringTable->GetString(liquidType->texture);
u32 liquidTextureHash = liquidTypesStringTable->GetStringHash(liquidType->texture);
u32 textureIndex;
if (!TryLoadTexture(liquidTexture, liquidTextureHash, liquidType->numTextureFrames, textureIndex))
{
DebugHandler::PrintFatal("WaterRenderer::RegisterChunksToBeLoaded : failed to load texture %s", liquidTexture.c_str());
}
drawCallData.textureStartIndex = static_cast<u16>(textureIndex);
drawCallData.textureCount = liquidType->numTextureFrames;
drawCallData.hasDepth = liquidType->hasDepthEnabled;
vec3 min = vec3(100000, 100000, 100000);
vec3 max = vec3(-100000, -100000, -100000);
for (u8 y = 0; y <= height; y++)
{
// This represents World (Forward/Backward) in other words, our X axis
f32 offsetY = -(static_cast<f32>(posY + y) * Terrain::MAP_PATCH_SIZE);
for (u8 x = 0; x <= width; x++)
{
// This represents World (West/East) in other words, our Y axis
f32 offsetX = -(static_cast<f32>(posX + x) * Terrain::MAP_PATCH_SIZE);
f32 vertexHeight = liquidBasePos.z - liquidInstance.minHeightLevel;
u32 vertexIndex = x + (y * (width + 1));
if (heightMap && liquidInstance.liquidType != 2 && liquidVertexFormat != 2)
{
vertexHeight = heightMap[vertexIndex];
}
WaterVertex vertex;
vertex.xCellOffset = y + liquidInstance.yOffset; // These are intended to be flipped, we are going from 2D to 3D
vertex.yCellOffset = x + liquidInstance.xOffset;
vertex.height = f16(vertexHeight);
vertex.uv = hvec2(static_cast<f32>(x) / 2.0f, static_cast<f32>(y) / 2.0f);
vertices.push_back(vertex);
// Calculate worldspace pos for AABB usage
vec3 pos = liquidBasePos - vec3(Terrain::MAP_PATCH_SIZE * (y + liquidInstance.yOffset), Terrain::MAP_PATCH_SIZE * (x + liquidInstance.xOffset), 0.0f);
pos.z = vertexHeight;
min = glm::min(min, pos);
max = glm::max(max, pos);
if (y < height && x < width)
{
u16 topLeftVert = x + (y * (width + 1));
u16 topRightVert = topLeftVert + 1;
u16 bottomLeftVert = topLeftVert + (width + 1);
u16 bottomRightVert = bottomLeftVert + 1;
indices.push_back(topLeftVert);
indices.push_back(bottomLeftVert);
indices.push_back(topRightVert);
indices.push_back(topRightVert);
indices.push_back(bottomLeftVert);
indices.push_back(bottomRightVert);
drawCall.indexCount += 6;
}
}
}
_numTriangles += drawCall.indexCount / 3;
// The water could literally be a flat plane, so we have to add offsets to min.z and max.z
min.z -= 1.0f;
max.z += 1.0f;
AABB& boundingBox = boundingBoxes.emplace_back();
boundingBox.min = vec4(min, 0.0f);
boundingBox.max = vec4(max, 0.0f);
}
liquidInfoOffset += numInstances;
}
}
});
DebugHandler::Print("Water: Loaded (%u, %u) Vertices/Indices", _vertices.Size(), _indices.Size());
return true;
}
void WaterRenderer::ExecuteLoad()
{
// Sync DrawCalls to GPU
{
_drawCalls.SetDebugName("WaterDrawCalls");
_drawCalls.SetUsage(Renderer::BufferUsage::INDIRECT_ARGUMENT_BUFFER | Renderer::BufferUsage::STORAGE_BUFFER);
_drawCalls.SyncToGPU(_renderer);
_cullingDescriptorSet.Bind("_drawCalls"_h, _drawCalls.GetBuffer());
}
// Sync DrawCallDatas to GPU
{
_drawCallDatas.SetDebugName("WaterDrawCallDatas");
_drawCallDatas.SetUsage(Renderer::BufferUsage::STORAGE_BUFFER);
_drawCallDatas.SyncToGPU(_renderer);
_passDescriptorSet.Bind("_drawCallDatas"_h, _drawCallDatas.GetBuffer());
}
// Sync Vertices to GPU
{
_vertices.SetDebugName("WaterVertices");
_vertices.SetUsage(Renderer::BufferUsage::STORAGE_BUFFER);
_vertices.SyncToGPU(_renderer);
_passDescriptorSet.Bind("_vertices"_h, _vertices.GetBuffer());
}
// Sync Indices to GPU
{
_indices.SetDebugName("WaterIndices");
_indices.SetUsage(Renderer::BufferUsage::INDEX_BUFFER);
_indices.SyncToGPU(_renderer);
}
// Sync BoundingBoxes to GPU
{
_boundingBoxes.SetDebugName("WaterBoundingBoxes");
_boundingBoxes.SetUsage(Renderer::BufferUsage::STORAGE_BUFFER);
_boundingBoxes.SyncToGPU(_renderer);
_cullingDescriptorSet.Bind("_boundingBoxes"_h, _boundingBoxes.GetBuffer());
}
// Create CulledDrawCallsBuffer
{
Renderer::BufferDesc desc;
desc.name = "WaterCulledDrawcalls";
desc.size = sizeof(DrawCall) * _drawCalls.Size();
desc.usage = Renderer::BufferUsage::INDIRECT_ARGUMENT_BUFFER | Renderer::BufferUsage::STORAGE_BUFFER | Renderer::BufferUsage::TRANSFER_DESTINATION;
_culledDrawCallsBuffer = _renderer->CreateBuffer(_culledDrawCallsBuffer, desc);
_cullingDescriptorSet.Bind("_culledDrawCalls", _culledDrawCallsBuffer);
}
// Create CulledDrawCountBuffer
{
Renderer::BufferDesc desc;
desc.name = "WaterDrawCountBuffer";
desc.size = sizeof(u32);
desc.usage = Renderer::BufferUsage::INDIRECT_ARGUMENT_BUFFER | Renderer::BufferUsage::STORAGE_BUFFER | Renderer::BufferUsage::TRANSFER_DESTINATION | Renderer::BufferUsage::TRANSFER_SOURCE;
_culledDrawCountBuffer = _renderer->CreateBuffer(_culledDrawCountBuffer, desc);
_cullingDescriptorSet.Bind("_drawCount", _culledDrawCountBuffer);
desc.name = "WaterDrawCountRBBuffer";
desc.usage = Renderer::BufferUsage::STORAGE_BUFFER | Renderer::BufferUsage::TRANSFER_DESTINATION;
desc.cpuAccess = Renderer::BufferCPUAccess::ReadOnly;
_culledDrawCountReadBackBuffer = _renderer->CreateBuffer(_culledDrawCountReadBackBuffer, desc);
}
// Create CulledTriangleCountBuffer
{
Renderer::BufferDesc desc;
desc.name = "WaterTriangleCountBuffer";
desc.size = sizeof(u32);
desc.usage = Renderer::BufferUsage::STORAGE_BUFFER | Renderer::BufferUsage::TRANSFER_DESTINATION | Renderer::BufferUsage::TRANSFER_SOURCE;
_culledTriangleCountBuffer = _renderer->CreateBuffer(_culledTriangleCountBuffer, desc);
_cullingDescriptorSet.Bind("_triangleCount", _culledTriangleCountBuffer);
desc.name = "WaterTriangleCountRBBuffer";
desc.usage = Renderer::BufferUsage::STORAGE_BUFFER | Renderer::BufferUsage::TRANSFER_DESTINATION;
desc.cpuAccess = Renderer::BufferCPUAccess::ReadOnly;
_culledTriangleCountReadBackBuffer = _renderer->CreateBuffer(_culledTriangleCountReadBackBuffer, desc);
}
}
bool WaterRenderer::TryLoadTexture(const std::string& textureName, u32 textureHash, u32 numTextures, u32& textureIndex)
{
auto itr = _waterTextureInfos.find(textureHash);
WaterTextureInfo* waterTextureInfo = nullptr;
if (itr != _waterTextureInfos.end())
{
waterTextureInfo = &itr->second;
if (numTextures <= waterTextureInfo->numTextures)
{
textureIndex = waterTextureInfo->textureArrayIndex;
return true;
}
}
else
{
waterTextureInfo = &_waterTextureInfos[textureHash];
}
Renderer::TextureDesc desc;
u32 index;
char tempTextureNameBuffer[1024];
for (u32 i = 1; i <= numTextures; i++)
{
i32 length = StringUtils::FormatString(tempTextureNameBuffer, 1024, textureName.c_str(), i);
if (length == 0)
return false;
u32 tempTextureHash = StringUtils::fnv1a_32(tempTextureNameBuffer, length);
entt::registry* registry = ServiceLocator::GetGameRegistry();
TextureSingleton& textureSingleton = registry->ctx<TextureSingleton>();
desc.path = textureSingleton.textureHashToPath[tempTextureHash];
_renderer->LoadTextureIntoArray(desc, _waterTextures, index);
}
textureIndex = (index + 1) - numTextures;
waterTextureInfo->textureArrayIndex = textureIndex;
waterTextureInfo->numTextures = numTextures;
return true;
}
| 44.633381 | 196 | 0.642706 | gitdnd |
ca30cef1cede85822d078168f8789e1a61f01055 | 946 | cpp | C++ | CK2ToEU4/Source/Mappers/ProvinceTitleMapper/ProvinceTitleGrabber.cpp | Grave461/CK2ToEU4 | 659cf5406c7d683649f9c888bc674424a312d10d | [
"MIT"
] | 1 | 2021-05-09T16:49:23.000Z | 2021-05-09T16:49:23.000Z | CK2ToEU4/Source/Mappers/ProvinceTitleMapper/ProvinceTitleGrabber.cpp | PKZB/CK2ToEU4 | 48e7d7a954079e48c74496745f703cd6d128d133 | [
"MIT"
] | null | null | null | CK2ToEU4/Source/Mappers/ProvinceTitleMapper/ProvinceTitleGrabber.cpp | PKZB/CK2ToEU4 | 48e7d7a954079e48c74496745f703cd6d128d133 | [
"MIT"
] | null | null | null | #include "ProvinceTitleGrabber.h"
#include "CommonFunctions.h"
#include "OSCompatibilityLayer.h"
#include "ParserHelpers.h"
mappers::ProvinceTitleGrabber::ProvinceTitleGrabber(const std::string& provincePath)
{
if (!commonItems::DoesFileExist(provincePath))
throw std::runtime_error(provincePath + " does not exist?");
registerKeys();
parseFile(provincePath);
clearRegisteredKeywords();
const auto path = trimPath(provincePath);
try
{
provID = std::stoi(path);
}
catch (std::exception& e)
{
Log(LogLevel::Warning) << "Province filename " << provincePath << " is not a valid name, skipping this province: " << e.what();
}
}
void mappers::ProvinceTitleGrabber::registerKeys()
{
registerKeyword("title", [this](const std::string& unused, std::istream& theStream) {
const commonItems::singleString titleStr(theStream);
title = titleStr.getString();
});
registerRegex(commonItems::catchallRegex, commonItems::ignoreItem);
} | 28.666667 | 129 | 0.739958 | Grave461 |
ca32298bf218d33165c64faf7d3505221adcc82a | 6,654 | cpp | C++ | games/snake/Snake_mouli.cpp | Sinjide/cpp_arcade | c6a9dc54ed10ea5300d7bf972c5ee2bee2e58116 | [
"MIT"
] | null | null | null | games/snake/Snake_mouli.cpp | Sinjide/cpp_arcade | c6a9dc54ed10ea5300d7bf972c5ee2bee2e58116 | [
"MIT"
] | null | null | null | games/snake/Snake_mouli.cpp | Sinjide/cpp_arcade | c6a9dc54ed10ea5300d7bf972c5ee2bee2e58116 | [
"MIT"
] | null | null | null | //
// Snake_mouli.cpp for in /home/doremi/rendu/cpp/cpp_arcade/games/snake
//
// Made by Guillaume
// Login <doremi@epitech.net>
//
// Started on Mon Apr 3 20:15:30 2017 Guillaume
// Last update Sat Apr 8 10:10:49 2017 Guillaume Doremieux
//
#include "../../my.hpp"
#include "../../Protocol.hpp"
#include <stdlib.h>
#include <unistd.h>
#include <ctime>
#include <vector>
#include <map>
#include <cmath>
#include "../my_read.hpp"
void show_get_map(map *map, arcade::CommandType com)
{
my_read mread;
arcade::GetMap *gmap = new arcade::GetMap[sizeof(arcade::CommandType) + sizeof(uint16_t) * 2 + map->height * map->width * sizeof(arcade::TileType)];
int x = 0;
int y = 0;
int index = 0;
gmap->type = com;
gmap->width = map->width;
gmap->height = map->height;
while (x < map->height)
{
y = 0;
while (y < map->width)
{
index = x * map->width + y;
if (map->map[x][y] == EMPTY)
gmap->tile[index] = arcade::TileType::EMPTY;
else if (map->map[x][y] == BLOCK)
gmap->tile[index] = arcade::TileType::BLOCK;
else if (map->map[x][y] == ITEM)
gmap->tile[index] = arcade::TileType::POWERUP;
y++;
}
x++;
}
mread.my_write_mouli(1, gmap, sizeof(arcade::CommandType) + sizeof(uint16_t) * 2 + map->height * map->width * sizeof(arcade::TileType));
}
void show_where_an_i(map *map, arcade::CommandType com)
{
my_read mread;
arcade::WhereAmI *where = new arcade::WhereAmI[sizeof(arcade::CommandType) + sizeof(uint16_t) + (sizeof(arcade::Position) * map->player.size())];
int i = 0;
arcade::Position pos;
where->type = com;
where->lenght = map->player.size();
for (std::vector<character>::iterator node = map->player.begin(); node != map->player.end(); ++node)
{
pos.x = (*node).x;
pos.y = (*node).y;
where->position[i] = pos;
i++;
}
mread.my_write_mouli(1, where, sizeof(arcade::CommandType) + sizeof(uint16_t) + (sizeof(arcade::Position) * map->player.size()));
}
event go_Up(map *map, event _dir)
{
if (_dir != DOWN)
_dir = UP;
return (_dir);
}
event go_Down(map *map, event _dir)
{
if (_dir != UP)
_dir = DOWN;
return (_dir);
}
event go_Left(map *map, event _dir)
{
if (_dir != RIGHT)
_dir = LEFT;
return (_dir);
}
event go_Right(map *map, event _dir)
{
if (_dir != LEFT)
_dir = RIGHT;
return (_dir);
}
void gen_Item(map *map)
{
int status = 1;
int state = 0;
int x;
int y;
while (status == 1)
{
y = rand() % 15 + 1;
x = rand() % 15 + 1;
state = 0;
for (std::vector<character>::iterator node = map->player.begin(); node != map->player.end(); ++node)
{
if ((*node).x == x && (*node).y == y)
state = 1;
}
if (state == 0)
{
map->map[y][x] = ITEM;
status = 0;
}
}
}
void check_Map(map *map)
{
character player;
int x;
int y;
int count = 0;;
srand(time(NULL));
y = 0;
while (y < map->height)
{
x = 0;
while (x < map->width)
{
if (map->map[y][x] == ITEM)
count++;
x++;
}
y++;
}
if (count == 0)
gen_Item(map);
if (map->player.front().x == 0 || map->player.front().x == 16 || map->player.front().y == 0 || map->player.front().y == 16)
{
map->hasLost = true;
}
count = 0;
for (std::vector<character>::iterator node = map->player.begin(); node != map->player.end(); ++node)
{
if (count > 2 && map->player.front().x == (*node).x && map->player.front().y == (*node).y)
{
map->hasLost = true;
}
count++;
}
}
void run_Game(map *map, event _dir)
{
character player;
if (map->hasWon == false && map->hasLost == false)
{
player = map->player.back();
player.dir = _dir;
player.x = map->player.front().x;
player.y = map->player.front().y;
if (_dir == UP)
player.y = map->player.front().y - 1;
else if (_dir == DOWN)
player.y = map->player.front().y + 1;
else if (_dir == LEFT)
player.x = map->player.front().x - 1;
else if (_dir == RIGHT)
player.x = map->player.front().x + 1;
player.xf = player.x;
player.yf = player.y;
if (map->map[player.y][player.x] == ITEM)
{
map->map[player.y][player.x] = EMPTY;
map->player.push_back(map->player.back());
map->current_score.score += 50;
}
map->player.insert(map->player.begin(), player);
map->player.pop_back();
check_Map(map);
}
}
map *create_Map()
{
map *nmap;
int i;
int j;
nmap = new map();
nmap->map = new map_content *[17];
i = 0;
while (i < 17)
{
j = 0;
nmap->map[i] = new map_content[17];
while (j < 17)
{
if (i == 0 || i == 16 || j == 0 || j == 16)
nmap->map[i][j] = BLOCK;
else
nmap->map[i][j] = EMPTY;
j++;
}
i++;
}
character player1;
character player2;
character player3;
character player4;
player1.x = 5;
player1.y = 11;
player1.xf = 5.0;
player1.yf = 11.0;
player1.dir = RIGHT;
player1.type = PLAYER;
player1.hasBonus = 0;
player2.x = 6;
player2.y = 11;
player2.xf = 6.0;
player2.yf = 11.0;
player2.dir = RIGHT;
player2.type = PLAYER;
player2.hasBonus = 0;
player3.x = 7;
player3.y = 11;
player3.xf = 7.0;
player3.yf = 11.0;
player3.dir = RIGHT;
player3.type = PLAYER;
player3.hasBonus = 0;
player4.x = 8;
player4.y = 11;
player4.xf = 8.0;
player4.yf = 11.0;
player4.dir = RIGHT;
player4.type = PLAYER;
player4.hasBonus = 0;
nmap->player.push_back(player4);
nmap->player.push_back(player3);
nmap->player.push_back(player2);
nmap->player.push_back(player1);
nmap->startTime = clock();
nmap->height = 17;
nmap->width = 17;
nmap->current_score.score = 0;
nmap->hasWon = false;
nmap->hasLost = false;
nmap->save = false;
check_Map(nmap);
return nmap;
}
extern "C"
void Play()
{
my_read mread;
arcade::CommandType command;
map *map;
event _dir = RIGHT;
map = create_Map();
while (mread.my_read_mouli(0, &command, sizeof(arcade::CommandType)))
{
if (command == arcade::CommandType::WHERE_AM_I)
show_where_an_i(map, command);
else if (command == arcade::CommandType::GET_MAP)
show_get_map(map, command);
else if (command == arcade::CommandType::GO_UP)
_dir = go_Up(map, _dir);
else if (command == arcade::CommandType::GO_DOWN)
_dir = go_Down(map, _dir);
else if (command == arcade::CommandType::GO_LEFT)
_dir = go_Left(map, _dir);
else if (command == arcade::CommandType::GO_RIGHT)
_dir = go_Right(map, _dir);
else if (command == arcade::CommandType::PLAY)
run_Game(map, _dir);
}
}
| 21.745098 | 150 | 0.575894 | Sinjide |
ca33ddff8fd05f2da62ec22d62c7879e2d382cea | 125 | cc | C++ | src/example.cc | eddiehoyle/sevengine | 4f5bd2b16b1179784c831ef8a0d57ccecee0a92e | [
"MIT"
] | 1 | 2019-08-21T05:06:04.000Z | 2019-08-21T05:06:04.000Z | src/example.cc | eddiehoyle/sevengine | 4f5bd2b16b1179784c831ef8a0d57ccecee0a92e | [
"MIT"
] | null | null | null | src/example.cc | eddiehoyle/sevengine | 4f5bd2b16b1179784c831ef8a0d57ccecee0a92e | [
"MIT"
] | null | null | null | //
// Created by Eddie Hoyle on 5/08/16.
//
#include <cstdio>
#include "example.hh"
void hello() {
printf( "Hey\n" );
} | 12.5 | 37 | 0.592 | eddiehoyle |
ca35bc10244d90a19133d258fedfae9f551b5063 | 720 | cpp | C++ | codeforces/round-273/div-2/random_teams.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | 1 | 2020-07-16T01:46:38.000Z | 2020-07-16T01:46:38.000Z | codeforces/round-273/div-2/random_teams.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | null | null | null | codeforces/round-273/div-2/random_teams.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | 1 | 2020-05-27T14:30:43.000Z | 2020-05-27T14:30:43.000Z | #include <iostream>
using namespace std;
inline
void use_io_optimizations()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
}
inline
unsigned long long pairs(unsigned long long people)
{
return people * (people - 1) / 2;
}
int main()
{
use_io_optimizations();
unsigned long long participants;
unsigned long long teams;
cin >> participants >> teams;
unsigned long long minimum {
(teams - participants % teams) * pairs(participants / teams) +
(participants % teams) * pairs(participants / teams + 1)
};
unsigned long long maximum {
pairs(participants - teams + 1)
};
cout << minimum << ' ' << maximum << '\n';
return 0;
}
| 18 | 72 | 0.620833 | Rkhoiwal |
ca433727af55d48ca0bc58a45e42eb870e845f20 | 68,757 | cpp | C++ | compiler/luci/logex/src/FormattedGraph.cpp | dev-hue/ONE | a4ca4318c1f9331a102a7ab8c544794a108cffbf | [
"Apache-2.0"
] | null | null | null | compiler/luci/logex/src/FormattedGraph.cpp | dev-hue/ONE | a4ca4318c1f9331a102a7ab8c544794a108cffbf | [
"Apache-2.0"
] | 1 | 2022-02-10T04:18:26.000Z | 2022-02-10T04:18:26.000Z | compiler/luci/logex/src/FormattedGraph.cpp | dev-hue/ONE | a4ca4318c1f9331a102a7ab8c544794a108cffbf | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2020 Samsung Electronics Co., Ltd. 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 "luci/FormattedGraph.h"
#include <luci/IR/CircleDialect.h>
#include <luci/IR/CircleNodes.h>
#include <pepper/str.h>
#include <cassert>
#include <sstream>
#include <vector>
/**
* @brief dump std::vector<int64_t> values to stream
*/
std::ostream &operator<<(std::ostream &os, const std::vector<int64_t> &vi64)
{
for (auto vi : vi64)
{
os << vi << " ";
}
return os;
}
// For TF lite
namespace
{
const char *to_str(loco::DataType type)
{
switch (type)
{
case loco::DataType::U8:
return "UINT8";
case loco::DataType::U16:
return "UINT16";
case loco::DataType::U32:
return "UINT32";
case loco::DataType::U64:
return "UINT64";
case loco::DataType::S8:
return "INT8";
case loco::DataType::S16:
return "INT16";
case loco::DataType::S32:
return "INT32";
case loco::DataType::S64:
return "INT64";
case loco::DataType::FLOAT16:
return "FLOAT16";
case loco::DataType::FLOAT32:
return "FLOAT32";
case loco::DataType::FLOAT64:
return "FLOAT64";
case loco::DataType::BOOL:
return "BOOL";
default:
return "Error";
}
}
const char *to_str(bool value) { return value ? "true" : "false"; }
const char *to_str(luci::FusedActFunc fused)
{
switch (fused)
{
case luci::FusedActFunc::NONE:
return "NONE";
case luci::FusedActFunc::RELU:
return "RELU";
case luci::FusedActFunc::RELU_N1_TO_1:
return "RELU_N1_TO_1";
case luci::FusedActFunc::RELU6:
return "RELU6";
case luci::FusedActFunc::TANH:
return "TANH";
case luci::FusedActFunc::SIGN_BIT:
return "SIGN_BIT";
default:
return "Error";
}
}
const char *to_str(luci::Padding padding)
{
switch (padding)
{
case luci::Padding::SAME:
return "SAME";
case luci::Padding::VALID:
return "VALID";
default:
return "Error";
}
}
const char *to_str(luci::MirrorPadMode mode)
{
switch (mode)
{
case luci::MirrorPadMode::REFLECT:
return "REFLECT";
case luci::MirrorPadMode::SYMMETRIC:
return "SYMMETRIC";
default:
return "Error";
}
}
std::string to_str(const luci::Stride *stride)
{
return pepper::str(stride->h(), ",", stride->w());
}
std::string to_str(const luci::Filter *filter)
{
return pepper::str(filter->h(), ",", filter->w());
}
std::string circle_opname(uint32_t opnum)
{
static const std::string prefix{"circle."};
switch (static_cast<luci::CircleOpcode>(opnum))
{
#define CIRCLE_NODE(OPCODE, CLASS) \
case luci::CircleOpcode::OPCODE: \
return prefix + #OPCODE;
#include <luci/IR/CircleNodes.lst>
#undef CIRCLE_NODE
default:
break;
};
return prefix + "Invalid";
}
// CircleNodeSummaryBuilder with default implementation
class CircleNodeSummaryBuilderBase : public locop::NodeSummaryBuilder
{
public:
CircleNodeSummaryBuilderBase(const locop::SymbolTable *tbl) : _tbl{tbl}
{
// DO NOTHING
}
public:
bool build(const loco::Node *, locop::NodeSummary &s) const final;
protected:
#define CIRCLE_NODE(OPCODE, CLASS) \
virtual bool summary(const CLASS *, locop::NodeSummary &s) const \
{ \
s.comments().append("Emitted by Default CircleNodeSummaryBuilder"); \
s.state(locop::NodeSummary::State::PartiallyKnown); \
return true; \
}
#include <luci/IR/CircleNodes.lst>
#undef CIRCLE_NODE
protected:
const locop::SymbolTable *tbl(void) const { return _tbl; }
// Please do not use _tbl directly and use tbl().
// This will be changed to private in near future.
protected:
const locop::SymbolTable *_tbl;
};
class CircleNodeSummaryBuilder final : public CircleNodeSummaryBuilderBase
{
public:
CircleNodeSummaryBuilder(const locop::SymbolTable *tbl) : CircleNodeSummaryBuilderBase(tbl)
{
// DO NOTHING
}
private:
#define IMPLEMENT(CLASS) bool summary(const CLASS *, locop::NodeSummary &) const final;
IMPLEMENT(luci::CircleAbs)
IMPLEMENT(luci::CircleAdd)
IMPLEMENT(luci::CircleAddN)
IMPLEMENT(luci::CircleArgMax)
IMPLEMENT(luci::CircleArgMin)
IMPLEMENT(luci::CircleAveragePool2D)
IMPLEMENT(luci::CircleBatchMatMul)
IMPLEMENT(luci::CircleBatchToSpaceND)
IMPLEMENT(luci::CircleBidirectionalSequenceLSTM)
IMPLEMENT(luci::CircleCast)
IMPLEMENT(luci::CircleCeil)
IMPLEMENT(luci::CircleConcatenation)
IMPLEMENT(luci::CircleConst)
IMPLEMENT(luci::CircleConv2D)
IMPLEMENT(luci::CircleCos)
IMPLEMENT(luci::CircleCustom)
IMPLEMENT(luci::CircleDepthToSpace)
IMPLEMENT(luci::CircleDepthwiseConv2D)
IMPLEMENT(luci::CircleDequantize)
IMPLEMENT(luci::CircleDiv)
IMPLEMENT(luci::CircleElu)
IMPLEMENT(luci::CircleExp)
IMPLEMENT(luci::CircleExpandDims)
IMPLEMENT(luci::CircleFakeQuant)
IMPLEMENT(luci::CircleFill)
IMPLEMENT(luci::CircleFloor)
IMPLEMENT(luci::CircleFloorDiv)
IMPLEMENT(luci::CircleFloorMod)
IMPLEMENT(luci::CircleFullyConnected)
IMPLEMENT(luci::CircleGather)
IMPLEMENT(luci::CircleGatherNd)
IMPLEMENT(luci::CircleGreater)
IMPLEMENT(luci::CircleGreaterEqual)
IMPLEMENT(luci::CircleIf)
IMPLEMENT(luci::CircleL2Normalize)
IMPLEMENT(luci::CircleLeakyRelu)
IMPLEMENT(luci::CircleLess)
IMPLEMENT(luci::CircleLessEqual)
IMPLEMENT(luci::CircleLocalResponseNormalization)
IMPLEMENT(luci::CircleLog)
IMPLEMENT(luci::CircleLogicalAnd)
IMPLEMENT(luci::CircleLogicalNot)
IMPLEMENT(luci::CircleLogicalOr)
IMPLEMENT(luci::CircleLogistic)
IMPLEMENT(luci::CircleLogSoftmax)
IMPLEMENT(luci::CircleMatrixDiag)
IMPLEMENT(luci::CircleMatrixSetDiag)
IMPLEMENT(luci::CircleMaximum)
IMPLEMENT(luci::CircleMaxPool2D)
IMPLEMENT(luci::CircleMean)
IMPLEMENT(luci::CircleMinimum)
IMPLEMENT(luci::CircleMirrorPad)
IMPLEMENT(luci::CircleMul)
IMPLEMENT(luci::CircleNeg)
IMPLEMENT(luci::CircleNonMaxSuppressionV4)
IMPLEMENT(luci::CircleNonMaxSuppressionV5)
IMPLEMENT(luci::CircleNotEqual)
IMPLEMENT(luci::CircleOneHot)
IMPLEMENT(luci::CirclePack)
IMPLEMENT(luci::CirclePad)
IMPLEMENT(luci::CirclePadV2)
IMPLEMENT(luci::CirclePow)
IMPLEMENT(luci::CirclePRelu)
IMPLEMENT(luci::CircleRange)
IMPLEMENT(luci::CircleRank)
IMPLEMENT(luci::CircleReduceAny)
IMPLEMENT(luci::CircleReduceMax)
IMPLEMENT(luci::CircleReduceMin)
IMPLEMENT(luci::CircleReduceProd)
IMPLEMENT(luci::CircleRelu)
IMPLEMENT(luci::CircleRelu6)
IMPLEMENT(luci::CircleReluN1To1)
IMPLEMENT(luci::CircleReshape)
IMPLEMENT(luci::CircleResizeBilinear)
IMPLEMENT(luci::CircleResizeNearestNeighbor)
IMPLEMENT(luci::CircleReverseSequence)
IMPLEMENT(luci::CircleReverseV2)
IMPLEMENT(luci::CircleRound)
IMPLEMENT(luci::CircleRsqrt)
IMPLEMENT(luci::CircleScatterNd)
IMPLEMENT(luci::CircleSegmentSum)
IMPLEMENT(luci::CircleSelect)
IMPLEMENT(luci::CircleSelectV2)
IMPLEMENT(luci::CircleShape)
IMPLEMENT(luci::CircleSin)
IMPLEMENT(luci::CircleSlice)
IMPLEMENT(luci::CircleSoftmax)
IMPLEMENT(luci::CircleSpaceToBatchND)
IMPLEMENT(luci::CircleSpaceToDepth)
IMPLEMENT(luci::CircleSparseToDense)
IMPLEMENT(luci::CircleSplit)
IMPLEMENT(luci::CircleSplitV)
IMPLEMENT(luci::CircleSqrt)
IMPLEMENT(luci::CircleSquare)
IMPLEMENT(luci::CircleSquaredDifference)
IMPLEMENT(luci::CircleSqueeze)
IMPLEMENT(luci::CircleStridedSlice)
IMPLEMENT(luci::CircleSub)
IMPLEMENT(luci::CircleSum)
IMPLEMENT(luci::CircleTanh)
IMPLEMENT(luci::CircleTile)
IMPLEMENT(luci::CircleTopKV2)
IMPLEMENT(luci::CircleTranspose)
IMPLEMENT(luci::CircleTransposeConv)
IMPLEMENT(luci::CircleUnidirectionalSequenceLSTM)
IMPLEMENT(luci::CircleUnique)
IMPLEMENT(luci::CircleUnpack)
IMPLEMENT(luci::CircleWhere)
IMPLEMENT(luci::CircleWhile)
IMPLEMENT(luci::CircleZerosLike)
// Circle Only
IMPLEMENT(luci::CircleBCQFullyConnected)
IMPLEMENT(luci::CircleBCQGather)
IMPLEMENT(luci::CircleInstanceNorm)
// Virtual nodes
IMPLEMENT(luci::CircleInput)
IMPLEMENT(luci::CircleOutput)
IMPLEMENT(luci::CircleIfOut)
IMPLEMENT(luci::CircleNonMaxSuppressionV4Out)
IMPLEMENT(luci::CircleNonMaxSuppressionV5Out)
IMPLEMENT(luci::CircleSplitOut)
IMPLEMENT(luci::CircleSplitVOut)
IMPLEMENT(luci::CircleTopKV2Out)
IMPLEMENT(luci::CircleUniqueOut)
IMPLEMENT(luci::CircleUnpackOut)
IMPLEMENT(luci::CircleWhileOut)
#undef IMPLEMENT
};
template <class CIRCLENODE>
bool use_x(const locop::SymbolTable *tbl, const CIRCLENODE *node, locop::NodeSummary &s)
{
s.args().append("x", tbl->lookup(node->x()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
template <class CIRCLENODE>
bool use_input(const locop::SymbolTable *tbl, const CIRCLENODE *node, locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
template <class CIRCLENODE>
bool use_features(const locop::SymbolTable *tbl, const CIRCLENODE *node, locop::NodeSummary &s)
{
s.args().append("features", tbl->lookup(node->features()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
template <class CIRCLENODE>
bool use_xy(const locop::SymbolTable *tbl, const CIRCLENODE *node, locop::NodeSummary &s)
{
s.args().append("x", tbl->lookup(node->x()));
s.args().append("y", tbl->lookup(node->y()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
template <class CIRCLENODE>
bool use_xy_act(const locop::SymbolTable *tbl, const CIRCLENODE *node, locop::NodeSummary &s)
{
assert(node->fusedActivationFunction() != luci::FusedActFunc::UNDEFINED);
s.args().append("x", tbl->lookup(node->x()));
s.args().append("y", tbl->lookup(node->y()));
s.args().append("fused_activation_function", to_str(node->fusedActivationFunction()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
template <class CIRCLENODE>
bool use_reducer(const locop::SymbolTable *tbl, const CIRCLENODE *node, locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("reduction_indices", tbl->lookup(node->reduction_indices()));
s.args().append("keep_dims", node->keep_dims() ? "true" : "false");
s.state(locop::NodeSummary::State::Complete);
return true;
}
template <class CIRCLENODE>
bool use_ido(const locop::SymbolTable *tbl, const CIRCLENODE *node, locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("dimension", tbl->lookup(node->dimension()));
s.args().append("output_type", to_str(node->output_type()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleAddN *node,
locop::NodeSummary &s)
{
for (uint32_t i = 0; i < node->arity(); ++i)
s.args().append("inputs", tbl->lookup(node->inputs(i)));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleAveragePool2D *node,
locop::NodeSummary &s)
{
assert(node->fusedActivationFunction() != luci::FusedActFunc::UNDEFINED);
s.args().append("value", tbl->lookup(node->value()));
s.args().append("filter(h,w)", to_str(node->filter()));
s.args().append("stride(h,w)", to_str(node->stride()));
s.args().append("padding", to_str(node->padding()));
s.args().append("fused", to_str(node->fusedActivationFunction()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleBatchMatMul *node,
locop::NodeSummary &s)
{
s.args().append("x", tbl->lookup(node->x()));
s.args().append("y", tbl->lookup(node->y()));
s.args().append("adj_x", to_str(node->adj_x()));
s.args().append("adj_y", to_str(node->adj_y()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleBatchToSpaceND *node,
locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("block_shape", tbl->lookup(node->block_shape()));
s.args().append("crops", tbl->lookup(node->crops()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleBidirectionalSequenceLSTM *node,
locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("fw_input_to_input_weights", tbl->lookup(node->fw_input_to_input_weights()));
s.args().append("fw_input_to_forget_weights", tbl->lookup(node->fw_input_to_forget_weights()));
s.args().append("fw_input_to_cell_weights", tbl->lookup(node->fw_input_to_cell_weights()));
s.args().append("fw_input_to_output_weights", tbl->lookup(node->fw_input_to_output_weights()));
s.args().append("fw_recurrent_to_input_weights",
tbl->lookup(node->fw_recurrent_to_input_weights()));
s.args().append("fw_recurrent_to_forget_weights",
tbl->lookup(node->fw_recurrent_to_forget_weights()));
s.args().append("fw_recurrent_to_cell_weights",
tbl->lookup(node->fw_recurrent_to_cell_weights()));
s.args().append("fw_recurrent_to_output_weights",
tbl->lookup(node->fw_recurrent_to_output_weights()));
s.args().append("fw_cell_to_input_weights", tbl->lookup(node->fw_cell_to_input_weights()));
s.args().append("fw_cell_to_forget_weights", tbl->lookup(node->fw_cell_to_forget_weights()));
s.args().append("fw_cell_to_output_weights", tbl->lookup(node->fw_cell_to_output_weights()));
s.args().append("fw_input_gate_bias", tbl->lookup(node->fw_input_gate_bias()));
s.args().append("fw_forget_gate_bias", tbl->lookup(node->fw_forget_gate_bias()));
s.args().append("fw_cell_gate_bias", tbl->lookup(node->fw_cell_gate_bias()));
s.args().append("fw_output_gate_bias", tbl->lookup(node->fw_output_gate_bias()));
s.args().append("fw_projection_weights", tbl->lookup(node->fw_projection_weights()));
s.args().append("fw_projection_bias", tbl->lookup(node->fw_projection_bias()));
s.args().append("bw_input_to_input_weights", tbl->lookup(node->bw_input_to_input_weights()));
s.args().append("bw_input_to_forget_weights", tbl->lookup(node->bw_input_to_forget_weights()));
s.args().append("bw_input_to_cell_weights", tbl->lookup(node->bw_input_to_cell_weights()));
s.args().append("bw_input_to_output_weights", tbl->lookup(node->bw_input_to_output_weights()));
s.args().append("bw_recurrent_to_input_weights",
tbl->lookup(node->bw_recurrent_to_input_weights()));
s.args().append("bw_recurrent_to_forget_weights",
tbl->lookup(node->bw_recurrent_to_forget_weights()));
s.args().append("bw_recurrent_to_cell_weights",
tbl->lookup(node->bw_recurrent_to_cell_weights()));
s.args().append("bw_recurrent_to_output_weights",
tbl->lookup(node->bw_recurrent_to_output_weights()));
s.args().append("bw_cell_to_input_weights", tbl->lookup(node->bw_cell_to_input_weights()));
s.args().append("bw_cell_to_forget_weights", tbl->lookup(node->bw_cell_to_forget_weights()));
s.args().append("bw_cell_to_output_weights", tbl->lookup(node->bw_cell_to_output_weights()));
s.args().append("bw_input_gate_bias", tbl->lookup(node->bw_input_gate_bias()));
s.args().append("bw_forget_gate_bias", tbl->lookup(node->bw_forget_gate_bias()));
s.args().append("bw_cell_gate_bias", tbl->lookup(node->bw_cell_gate_bias()));
s.args().append("bw_output_gate_bias", tbl->lookup(node->bw_output_gate_bias()));
s.args().append("bw_projection_weights", tbl->lookup(node->bw_projection_weights()));
s.args().append("bw_projection_bias", tbl->lookup(node->bw_projection_bias()));
s.args().append("fw_activation_state", tbl->lookup(node->fw_activation_state()));
s.args().append("fw_cell_state", tbl->lookup(node->fw_cell_state()));
s.args().append("bw_activation_state", tbl->lookup(node->bw_activation_state()));
s.args().append("bw_cell_state", tbl->lookup(node->bw_cell_state()));
s.args().append("auxillary_input", tbl->lookup(node->auxillary_input()));
s.args().append("fw_auxillary_input_to_input_weights",
tbl->lookup(node->fw_auxillary_input_to_input_weights()));
s.args().append("fw_auxillary_input_to_forget_weights",
tbl->lookup(node->fw_auxillary_input_to_forget_weights()));
s.args().append("fw_auxillary_input_to_cell_weights",
tbl->lookup(node->fw_auxillary_input_to_cell_weights()));
s.args().append("fw_auxillary_input_to_output_weights",
tbl->lookup(node->fw_auxillary_input_to_output_weights()));
s.args().append("bw_auxillary_input_to_input_weights",
tbl->lookup(node->bw_auxillary_input_to_input_weights()));
s.args().append("bw_auxillary_input_to_forget_weights",
tbl->lookup(node->bw_auxillary_input_to_forget_weights()));
s.args().append("bw_auxillary_input_to_cell_weights",
tbl->lookup(node->bw_auxillary_input_to_cell_weights()));
s.args().append("bw_auxillary_input_to_output_weights",
tbl->lookup(node->bw_auxillary_input_to_output_weights()));
s.args().append("cell_clip", to_str(node->cell_clip()));
s.args().append("proj_clip", to_str(node->proj_clip()));
s.args().append("merge_outputs", to_str(node->merge_outputs()));
s.args().append("time_major", to_str(node->time_major()));
s.args().append("asymmetric_quantize_inputs", to_str(node->asymmetric_quantize_inputs()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleCast *node,
locop::NodeSummary &s)
{
s.args().append("x", tbl->lookup(node->x()));
s.args().append("in_data_type", to_str(node->in_data_type()));
s.args().append("out_data_type", to_str(node->out_data_type()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleConcatenation *node,
locop::NodeSummary &s)
{
assert(node->fusedActivationFunction() != luci::FusedActFunc::UNDEFINED);
for (uint32_t i = 0; i < node->numValues(); ++i)
s.args().append("values", tbl->lookup(node->values(i)));
s.args().append("axis", pepper::str(node->axis()));
s.args().append("fused", to_str(node->fusedActivationFunction()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleConv2D *node,
locop::NodeSummary &s)
{
assert(node->fusedActivationFunction() != luci::FusedActFunc::UNDEFINED);
assert(node->padding() != luci::Padding::UNDEFINED);
s.args().append("input", tbl->lookup(node->input()));
s.args().append("filter", tbl->lookup(node->filter()));
s.args().append("bias", tbl->lookup(node->bias()));
s.args().append("stride(h,w)", to_str(node->stride()));
s.args().append("dilation(h,w)", to_str(node->dilation()));
s.args().append("padding", to_str(node->padding()));
s.args().append("fused", to_str(node->fusedActivationFunction()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleCustom *node,
locop::NodeSummary &s)
{
for (uint32_t i = 0; i < node->numInputs(); i++)
{
s.args().append("input" + std::to_string(i), tbl->lookup(node->inputs(i)));
}
s.args().append("custom_code", node->custom_code());
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleDepthToSpace *node,
locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("block_size", std::to_string(node->block_size()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleDepthwiseConv2D *node,
locop::NodeSummary &s)
{
assert(node->fusedActivationFunction() != luci::FusedActFunc::UNDEFINED);
assert(node->padding() != luci::Padding::UNDEFINED);
s.args().append("input", tbl->lookup(node->input()));
s.args().append("filter", tbl->lookup(node->filter()));
s.args().append("bias", tbl->lookup(node->bias()));
s.args().append("stride(h,w)", to_str(node->stride()));
s.args().append("dilation(h,w)", to_str(node->dilation()));
s.args().append("padding", to_str(node->padding()));
s.args().append("depthMultiplier", std::to_string(node->depthMultiplier()));
s.args().append("fused", to_str(node->fusedActivationFunction()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleExpandDims *node,
locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("axis", tbl->lookup(node->axis()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleFakeQuant *node,
locop::NodeSummary &s)
{
s.args().append("inputs", tbl->lookup(node->inputs()));
s.args().append("min", pepper::str(node->min()));
s.args().append("max", pepper::str(node->max()));
s.args().append("num_bits", pepper::str(node->num_bits()));
s.args().append("narrow_range", node->narrow_range() ? "true" : "false");
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleFill *node,
locop::NodeSummary &s)
{
s.args().append("dims", tbl->lookup(node->dims()));
s.args().append("value", tbl->lookup(node->value()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleFullyConnected *node,
locop::NodeSummary &s)
{
assert(node->fusedActivationFunction() != luci::FusedActFunc::UNDEFINED);
s.args().append("input", tbl->lookup(node->input()));
s.args().append("weights", tbl->lookup(node->weights()));
s.args().append("bias", tbl->lookup(node->bias()));
s.args().append("fused", to_str(node->fusedActivationFunction()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleGather *node,
locop::NodeSummary &s)
{
s.args().append("params", tbl->lookup(node->params()));
s.args().append("indices", tbl->lookup(node->indices()));
s.args().append("axis", pepper::str(node->axis()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleGatherNd *node,
locop::NodeSummary &s)
{
s.args().append("params", tbl->lookup(node->params()));
s.args().append("indices", tbl->lookup(node->indices()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleIf *node, locop::NodeSummary &s)
{
s.args().append("cond", tbl->lookup(node->cond()));
for (uint32_t i = 0; i < node->input_count(); ++i)
s.args().append("input", tbl->lookup(node->input(i)));
if (node->then_graph() != nullptr)
s.args().append("then_graph", node->then_graph()->name());
else
s.args().append("then_branch", pepper::str(node->then_branch()));
if (node->else_graph() != nullptr)
s.args().append("else_graph", node->else_graph()->name());
else
s.args().append("else_branch", pepper::str(node->else_branch()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleL2Normalize *node,
locop::NodeSummary &s)
{
s.args().append("x", tbl->lookup(node->x()));
s.args().append("fused_activation_function", to_str(node->fusedActivationFunction()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleLeakyRelu *node,
locop::NodeSummary &s)
{
s.args().append("features", tbl->lookup(node->features()));
s.args().append("alpha", std::to_string(node->alpha()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleLocalResponseNormalization *node,
locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("radius", pepper::str(node->radius()));
s.args().append("bias", pepper::str(node->bias()));
s.args().append("alpha", pepper::str(node->alpha()));
s.args().append("beta", pepper::str(node->beta()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleLogSoftmax *node,
locop::NodeSummary &s)
{
s.args().append("logits", tbl->lookup(node->logits()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleMatrixDiag *node,
locop::NodeSummary &s)
{
s.args().append("diagonal", tbl->lookup(node->diagonal()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleMatrixSetDiag *node,
locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("diagonal", tbl->lookup(node->diagonal()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleMaxPool2D *node,
locop::NodeSummary &s)
{
assert(node->fusedActivationFunction() != luci::FusedActFunc::UNDEFINED);
s.args().append("value", tbl->lookup(node->value()));
s.args().append("filter(h,w)", to_str(node->filter()));
s.args().append("stride(h,w)", to_str(node->stride()));
s.args().append("padding", to_str(node->padding()));
s.args().append("fused", to_str(node->fusedActivationFunction()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleMirrorPad *node,
locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("paddings", tbl->lookup(node->paddings()));
s.args().append("mode", to_str(node->mode()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleNonMaxSuppressionV4 *node,
locop::NodeSummary &s)
{
s.args().append("boxes", tbl->lookup(node->boxes()));
s.args().append("scores", tbl->lookup(node->scores()));
s.args().append("max_output_size", tbl->lookup(node->max_output_size()));
s.args().append("iou_threshold", tbl->lookup(node->iou_threshold()));
s.args().append("score_threshold", tbl->lookup(node->score_threshold()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleNonMaxSuppressionV5 *node,
locop::NodeSummary &s)
{
s.args().append("boxes", tbl->lookup(node->boxes()));
s.args().append("scores", tbl->lookup(node->scores()));
s.args().append("max_output_size", tbl->lookup(node->max_output_size()));
s.args().append("iou_threshold", tbl->lookup(node->iou_threshold()));
s.args().append("score_threshold", tbl->lookup(node->score_threshold()));
s.args().append("soft_nms_sigma", tbl->lookup(node->soft_nms_sigma()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleOneHot *node,
locop::NodeSummary &s)
{
s.args().append("indices", tbl->lookup(node->indices()));
s.args().append("depth", tbl->lookup(node->depth()));
s.args().append("on_value", tbl->lookup(node->on_value()));
s.args().append("off_value", tbl->lookup(node->off_value()));
s.args().append("axis", pepper::str(node->axis()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CirclePack *node,
locop::NodeSummary &s)
{
for (uint32_t i = 0; i < node->values_count(); ++i)
s.args().append("values", tbl->lookup(node->values(i)));
s.args().append("values_count", pepper::str(node->values_count()));
s.args().append("axis", pepper::str(node->axis()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CirclePad *node, locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("paddings", tbl->lookup(node->paddings()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CirclePadV2 *node,
locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("paddings", tbl->lookup(node->paddings()));
s.args().append("constant_values", tbl->lookup(node->constant_values()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CirclePRelu *node,
locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("alpha", tbl->lookup(node->alpha()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleRange *node,
locop::NodeSummary &s)
{
s.args().append("start", tbl->lookup(node->start()));
s.args().append("limit", tbl->lookup(node->limit()));
s.args().append("delta", tbl->lookup(node->delta()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleReshape *node,
locop::NodeSummary &s)
{
s.args().append("tensor", tbl->lookup(node->tensor()));
s.args().append("shape", tbl->lookup(node->shape()));
// TODO Show newShape info
s.state(locop::NodeSummary::State::PartiallyKnown);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleResizeBilinear *node,
locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("size", tbl->lookup(node->size()));
s.args().append("align_corners", node->align_corners() ? "true" : "false");
s.args().append("half_pixel_centers", node->half_pixel_centers() ? "true" : "false");
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleResizeNearestNeighbor *node,
locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("size", tbl->lookup(node->size()));
s.args().append("align_corners", node->align_corners() ? "true" : "false");
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleReverseSequence *node,
locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("seq_lengths", tbl->lookup(node->seq_lengths()));
s.args().append("seq_axis", std::to_string(node->seq_axis()));
s.args().append("batch_axis", std::to_string(node->batch_axis()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleReverseV2 *node,
locop::NodeSummary &s)
{
s.args().append("tensor", tbl->lookup(node->tensor()));
s.args().append("axis", tbl->lookup(node->axis()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleScatterNd *node,
locop::NodeSummary &s)
{
s.args().append("indices", tbl->lookup(node->indices()));
s.args().append("updates", tbl->lookup(node->updates()));
s.args().append("shape", tbl->lookup(node->shape()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleSegmentSum *node,
locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("segment_ids", tbl->lookup(node->segment_ids()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleSelect *node,
locop::NodeSummary &s)
{
s.args().append("condition", tbl->lookup(node->condition()));
s.args().append("t", tbl->lookup(node->t()));
s.args().append("e", tbl->lookup(node->e()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleSelectV2 *node,
locop::NodeSummary &s)
{
s.args().append("condition", tbl->lookup(node->condition()));
s.args().append("t", tbl->lookup(node->t()));
s.args().append("e", tbl->lookup(node->e()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleShape *node,
locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("out_type", to_str(node->out_type()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleSlice *node,
locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("begin", tbl->lookup(node->begin()));
s.args().append("size", tbl->lookup(node->size()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleSoftmax *node,
locop::NodeSummary &s)
{
s.args().append("logits", tbl->lookup(node->logits()));
s.args().append("beta", pepper::str(node->beta()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleSpaceToBatchND *node,
locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("block_shape", tbl->lookup(node->block_shape()));
s.args().append("paddings", tbl->lookup(node->paddings()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleSpaceToDepth *node,
locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("block_size", pepper::str(node->block_size()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleSparseToDense *node,
locop::NodeSummary &s)
{
s.args().append("indices", tbl->lookup(node->indices()));
s.args().append("output_shape", tbl->lookup(node->output_shape()));
s.args().append("values", tbl->lookup(node->values()));
s.args().append("default_value", tbl->lookup(node->default_value()));
s.args().append("Validate_indices", pepper::str(node->validate_indices()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleSplit *node,
locop::NodeSummary &s)
{
s.args().append("split_dim", tbl->lookup(node->split_dim()));
s.args().append("input", tbl->lookup(node->input()));
s.args().append("num_split", pepper::str(node->num_split()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleSplitV *node,
locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("size_splits", tbl->lookup(node->size_splits()));
s.args().append("split_dim", tbl->lookup(node->split_dim()));
s.args().append("num_split", pepper::str(node->num_split()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleSqueeze *node,
locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
std::stringstream ss{"("};
for (size_t i = 0; i < node->squeeze_dims().size(); ++i)
{
if (i != 0)
ss << ", ";
ss << node->squeeze_dims()[i];
}
ss << ")";
s.args().append("squeeze_dims", ss.str());
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleStridedSlice *node,
locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("begin", tbl->lookup(node->begin()));
s.args().append("end", tbl->lookup(node->end()));
s.args().append("strides", tbl->lookup(node->strides()));
s.args().append("begin_mask", pepper::str(node->begin_mask()));
s.args().append("end_mask", pepper::str(node->end_mask()));
s.args().append("ellipsis_mask", pepper::str(node->ellipsis_mask()));
s.args().append("new_axis_mask", pepper::str(node->new_axis_mask()));
s.args().append("shrink_axis_mask", pepper::str(node->shrink_axis_mask()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleTile *node,
locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("multiples", tbl->lookup(node->multiples()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleTopKV2 *node,
locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("k", tbl->lookup(node->k()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleTranspose *node,
locop::NodeSummary &s)
{
s.args().append("a", tbl->lookup(node->a()));
s.args().append("perm", tbl->lookup(node->perm()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleTransposeConv *node,
locop::NodeSummary &s)
{
assert(node->padding() != luci::Padding::UNDEFINED);
s.args().append("inputSizes", tbl->lookup(node->inputSizes()));
s.args().append("filter", tbl->lookup(node->filter()));
s.args().append("outBackprop", tbl->lookup(node->outBackprop()));
s.args().append("bias", tbl->lookup(node->bias()));
s.args().append("stride(h,w)", to_str(node->stride()));
s.args().append("padding", to_str(node->padding()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleUnidirectionalSequenceLSTM *node,
locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("input_to_input_weights", tbl->lookup(node->input_to_input_weights()));
s.args().append("input_to_forget_weights", tbl->lookup(node->input_to_forget_weights()));
s.args().append("input_to_cell_weights", tbl->lookup(node->input_to_cell_weights()));
s.args().append("input_to_output_weights", tbl->lookup(node->input_to_output_weights()));
s.args().append("recurrent_to_input_weights", tbl->lookup(node->recurrent_to_input_weights()));
s.args().append("recurrent_to_forget_weights", tbl->lookup(node->recurrent_to_forget_weights()));
s.args().append("recurrent_to_cell_weights", tbl->lookup(node->recurrent_to_cell_weights()));
s.args().append("recurrent_to_output_weights", tbl->lookup(node->recurrent_to_output_weights()));
s.args().append("cell_to_input_weights", tbl->lookup(node->cell_to_input_weights()));
s.args().append("cell_to_forget_weights", tbl->lookup(node->cell_to_forget_weights()));
s.args().append("cell_to_output_weights", tbl->lookup(node->cell_to_output_weights()));
s.args().append("input_gate_bias", tbl->lookup(node->input_gate_bias()));
s.args().append("forget_gate_bias", tbl->lookup(node->forget_gate_bias()));
s.args().append("cell_gate_bias", tbl->lookup(node->cell_gate_bias()));
s.args().append("output_gate_bias", tbl->lookup(node->output_gate_bias()));
s.args().append("projection_weights", tbl->lookup(node->projection_weights()));
s.args().append("projection_bias", tbl->lookup(node->projection_bias()));
s.args().append("activation_state", tbl->lookup(node->activation_state()));
s.args().append("cell_state", tbl->lookup(node->cell_state()));
s.args().append("input_layer_norm_coefficients",
tbl->lookup(node->input_layer_norm_coefficients()));
s.args().append("forget_layer_norm_coefficients",
tbl->lookup(node->forget_layer_norm_coefficients()));
s.args().append("cell_layer_norm_coefficients",
tbl->lookup(node->cell_layer_norm_coefficients()));
s.args().append("output_layer_norm_coefficients",
tbl->lookup(node->output_layer_norm_coefficients()));
s.args().append("cell_clip", to_str(node->cell_clip()));
s.args().append("proj_clip", to_str(node->proj_clip()));
s.args().append("time_major", to_str(node->time_major()));
s.args().append("asymmetric_quantize_inputs", to_str(node->asymmetric_quantize_inputs()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleUnique *node,
locop::NodeSummary &s)
{
s.args().append("input", tbl->lookup(node->input()));
s.args().append("idx_out_type", to_str(node->idx_out_type()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleUnpack *node,
locop::NodeSummary &s)
{
s.args().append("value", tbl->lookup(node->value()));
s.args().append("num", pepper::str(node->num()));
s.args().append("axis", pepper::str(node->axis()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleWhere *node,
locop::NodeSummary &s)
{
s.args().append("condition", tbl->lookup(node->condition()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleWhile *node,
locop::NodeSummary &s)
{
for (uint32_t i = 0; i < node->input_count(); ++i)
s.args().append("input", tbl->lookup(node->input(i)));
if (node->cond_graph() != nullptr)
s.args().append("cond_graph", node->cond_graph()->name());
else
s.args().append("cond_branch", pepper::str(node->cond_branch()));
if (node->body_graph() != nullptr)
s.args().append("body_graph", node->body_graph()->name());
else
s.args().append("body_branch", pepper::str(node->body_branch()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleTopKV2Out *node,
locop::NodeSummary &s)
{
s.args().append("topkv2", tbl->lookup(node->input()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleUniqueOut *node,
locop::NodeSummary &s)
{
s.args().append("unique", tbl->lookup(node->input()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleUnpackOut *node,
locop::NodeSummary &s)
{
s.args().append("unpack", tbl->lookup(node->input()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleWhileOut *node,
locop::NodeSummary &s)
{
s.args().append("while", tbl->lookup(node->input()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleOutput *node,
locop::NodeSummary &s)
{
s.args().append("from", tbl->lookup(node->from()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleBCQFullyConnected *node,
locop::NodeSummary &s)
{
assert(node->fusedActivationFunction() != luci::FusedActFunc::UNDEFINED);
s.args().append("input", tbl->lookup(node->input()));
s.args().append("weights_scales", tbl->lookup(node->weights_scales()));
s.args().append("weights_binary", tbl->lookup(node->weights_binary()));
s.args().append("bias", tbl->lookup(node->bias()));
s.args().append("weights_clusters", tbl->lookup(node->weights_clusters()));
s.args().append("fused", to_str(node->fusedActivationFunction()));
s.args().append("weights_hidden_size", pepper::str(node->weights_hidden_size()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleBCQGather *node,
locop::NodeSummary &s)
{
s.args().append("input_scales", tbl->lookup(node->input_scales()));
s.args().append("input_binary", tbl->lookup(node->input_binary()));
s.args().append("indices", tbl->lookup(node->indices()));
s.args().append("input_clusters", tbl->lookup(node->input_clusters()));
s.args().append("axis", pepper::str(node->axis()));
s.args().append("input_hidden_size", pepper::str(node->input_hidden_size()));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool summary_node(const locop::SymbolTable *tbl, const luci::CircleInstanceNorm *node,
locop::NodeSummary &s)
{
auto fused = node->fusedActivationFunction();
assert(fused != luci::FusedActFunc::UNDEFINED);
s.args().append("input", tbl->lookup(node->input()));
s.args().append("gamma", tbl->lookup(node->gamma()));
s.args().append("beta", tbl->lookup(node->beta()));
s.args().append("epsilon", pepper::str(node->epsilon()));
s.args().append("fused_activation_function", to_str(fused));
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool CircleNodeSummaryBuilderBase::build(const loco::Node *node, locop::NodeSummary &s) const
{
if (node->dialect() != luci::CircleDialect::get())
return false;
auto ptr_to_str = [](const void *ptr) {
std::stringstream ss;
ss << ptr;
return ss.str();
};
#define CIRCLE_NODE(OPCODE, CLASS) \
if (dynamic_cast<const CLASS *>(node)) \
{ \
s.opname(circle_opname(node->opnum())); \
s.comments().append("Mem = " + ptr_to_str(node)); \
return summary(dynamic_cast<const CLASS *>(node), s); \
}
#include <luci/IR/CircleNodes.lst>
#undef CIRCLE_NODE
return false;
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleAbs *node, locop::NodeSummary &s) const
{
return use_x(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleAdd *node, locop::NodeSummary &s) const
{
return use_xy_act(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleAddN *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleArgMax *node, locop::NodeSummary &s) const
{
return use_ido(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleArgMin *node, locop::NodeSummary &s) const
{
return use_ido(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleAveragePool2D *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleBatchMatMul *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleBatchToSpaceND *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleBidirectionalSequenceLSTM *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleCast *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleCeil *node, locop::NodeSummary &s) const
{
return use_x(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleConcatenation *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleConst *, locop::NodeSummary &s) const
{
s.state(locop::NodeSummary::State::PartiallyKnown);
return true;
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleConv2D *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleCos *node, locop::NodeSummary &s) const
{
return use_x(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleCustom *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleDepthToSpace *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleDepthwiseConv2D *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleDequantize *node,
locop::NodeSummary &s) const
{
return use_input(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleDiv *node, locop::NodeSummary &s) const
{
return use_xy(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleElu *node, locop::NodeSummary &s) const
{
return use_features(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleExp *node, locop::NodeSummary &s) const
{
return use_x(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleExpandDims *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleFakeQuant *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleFill *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleFloor *node, locop::NodeSummary &s) const
{
return use_x(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleFloorDiv *node,
locop::NodeSummary &s) const
{
return use_xy(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleFloorMod *node,
locop::NodeSummary &s) const
{
return use_xy(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleFullyConnected *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleGather *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleGatherNd *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleGreater *node, locop::NodeSummary &s) const
{
return use_xy(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleGreaterEqual *node,
locop::NodeSummary &s) const
{
return use_xy(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleIf *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleL2Normalize *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleLess *node, locop::NodeSummary &s) const
{
return use_xy(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleLessEqual *node,
locop::NodeSummary &s) const
{
return use_xy(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleLeakyRelu *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleLocalResponseNormalization *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleLog *node, locop::NodeSummary &s) const
{
return use_x(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleLogicalAnd *node,
locop::NodeSummary &s) const
{
return use_xy(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleLogicalNot *node,
locop::NodeSummary &s) const
{
return use_x(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleLogicalOr *node,
locop::NodeSummary &s) const
{
return use_xy(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleLogistic *node,
locop::NodeSummary &s) const
{
return use_x(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleLogSoftmax *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleMatrixDiag *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleMatrixSetDiag *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleMaximum *node, locop::NodeSummary &s) const
{
return use_xy(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleMaxPool2D *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleMean *node, locop::NodeSummary &s) const
{
return use_reducer(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleMinimum *node, locop::NodeSummary &s) const
{
return use_xy(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleMirrorPad *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleMul *node, locop::NodeSummary &s) const
{
return use_xy_act(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleNeg *node, locop::NodeSummary &s) const
{
return use_x(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleNonMaxSuppressionV4 *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleNonMaxSuppressionV5 *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleNotEqual *node,
locop::NodeSummary &s) const
{
return use_xy(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleOneHot *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CirclePack *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CirclePad *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CirclePadV2 *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CirclePow *node, locop::NodeSummary &s) const
{
return use_xy(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CirclePRelu *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleRange *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleRank *node, locop::NodeSummary &s) const
{
return use_input(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleReduceAny *node,
locop::NodeSummary &s) const
{
return use_reducer(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleReduceMax *node,
locop::NodeSummary &s) const
{
return use_reducer(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleReduceMin *node,
locop::NodeSummary &s) const
{
return use_reducer(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleReduceProd *node,
locop::NodeSummary &s) const
{
return use_reducer(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleRelu *node, locop::NodeSummary &s) const
{
return use_features(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleRelu6 *node, locop::NodeSummary &s) const
{
return use_features(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleReluN1To1 *node,
locop::NodeSummary &s) const
{
return use_features(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleReshape *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleResizeBilinear *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleResizeNearestNeighbor *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleReverseSequence *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleReverseV2 *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleRound *node, locop::NodeSummary &s) const
{
return use_x(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleRsqrt *node, locop::NodeSummary &s) const
{
return use_x(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleScatterNd *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleSegmentSum *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleSelect *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleSelectV2 *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleShape *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleSin *node, locop::NodeSummary &s) const
{
return use_x(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleSlice *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleSoftmax *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleSpaceToBatchND *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleSpaceToDepth *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleSparseToDense *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleSplit *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleSplitV *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleSqrt *node, locop::NodeSummary &s) const
{
return use_x(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleSquare *node, locop::NodeSummary &s) const
{
return use_x(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleSquaredDifference *node,
locop::NodeSummary &s) const
{
return use_xy(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleSqueeze *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleStridedSlice *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleSub *node, locop::NodeSummary &s) const
{
return use_xy(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleSum *node, locop::NodeSummary &s) const
{
return use_reducer(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleTanh *node, locop::NodeSummary &s) const
{
return use_x(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleTile *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleTopKV2 *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleTranspose *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleTransposeConv *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleUnidirectionalSequenceLSTM *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleUnique *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleUnpack *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleWhere *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleWhile *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleZerosLike *node,
locop::NodeSummary &s) const
{
return use_input(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleSplitOut *node,
locop::NodeSummary &s) const
{
return use_input(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleSplitVOut *node,
locop::NodeSummary &s) const
{
return use_input(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleTopKV2Out *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleUniqueOut *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleUnpackOut *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleIfOut *node, locop::NodeSummary &s) const
{
return use_input(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleNonMaxSuppressionV4Out *node,
locop::NodeSummary &s) const
{
return use_input(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleNonMaxSuppressionV5Out *node,
locop::NodeSummary &s) const
{
return use_input(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleWhileOut *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleInput *, locop::NodeSummary &s) const
{
s.state(locop::NodeSummary::State::Complete);
return true;
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleOutput *node, locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleBCQFullyConnected *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleBCQGather *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
bool CircleNodeSummaryBuilder::summary(const luci::CircleInstanceNorm *node,
locop::NodeSummary &s) const
{
return summary_node(tbl(), node, s);
}
} // namespace
namespace luci
{
bool NodeSummaryBuilder::build(const loco::Node *node, locop::NodeSummary &s) const
{
if (locop::CanonicalNodeSummaryBuilder(_tbl).build(node, s))
{
return true;
}
if (CircleNodeSummaryBuilder(_tbl).build(node, s))
{
return true;
}
return false;
}
} // namespace luci
| 34.241534 | 100 | 0.672659 | dev-hue |
ca4339fe6506211ed23e5a4aff5781c112080817 | 2,595 | cpp | C++ | tests/test_shortest_path.cpp | JohnPapagiannakos/graphcpp | 32291f895c68477d256609d97cf66135926262a4 | [
"MIT"
] | null | null | null | tests/test_shortest_path.cpp | JohnPapagiannakos/graphcpp | 32291f895c68477d256609d97cf66135926262a4 | [
"MIT"
] | null | null | null | tests/test_shortest_path.cpp | JohnPapagiannakos/graphcpp | 32291f895c68477d256609d97cf66135926262a4 | [
"MIT"
] | null | null | null | #include "GraphCpp.hpp"
#include <cassert>
int main()
{
// Example #1
WeightedVertex<int, int> S0(0);
WeightedVertex<int, int> S1(1);
WeightedVertex<int, int> S2(2);
WeightedVertex<int, int> S3(3);
WeightedVertex<int, int> S4(4);
UndirectedWeightedGraph<int, int> testWeightedGraph;
testWeightedGraph.AddPair(S0, S1, 10);
testWeightedGraph.AddPair(S0, S4, 20);
testWeightedGraph.AddPair(S1, S2, 30);
testWeightedGraph.AddPair(S1, S3, 40);
testWeightedGraph.AddPair(S1, S4, 50);
testWeightedGraph.AddPair(S2, S3, 60);
testWeightedGraph.AddPair(S3, S4, 70);
// Show Graph
testWeightedGraph.Print();
std::cout << std::endl << std::endl;
ShortestPath<int,int> testDijstra(testWeightedGraph);
testDijstra.DijkstraShortestPath(S0);
std::cout << std::endl << std::endl;
// Example #2
WeightedVertex<int, double> E0(0);
WeightedVertex<int, double> E1(1);
WeightedVertex<int, double> E2(2);
WeightedVertex<int, double> E3(3);
WeightedVertex<int, double> E4(4);
Matrix<double> M(5, 5);
double M2[5][5] = {{0, 2, 3, 0, 0}, {2, 0, 15, 2, 0}, {3, 15, 0, 0, 13}, {0, 2, 0, 0, 9}, {0, 0, 13, 9, 0}};
M.CopyData(M2[0], 5, 5);
std::vector<WeightedVertex<int, double> *> V = {&E0, &E1, &E2, &E3, &E4};
UndirectedWeightedGraphAdj<int, double> testWeightedGraph2(V, M);
// Show Graph
testWeightedGraph2.Print();
std::cout << std::endl << std::endl;
ShortestPath<int, double> testDijstra2(testWeightedGraph2);
testDijstra2.DijkstraShortestPath(E0);
std::cout << std::endl << std::endl;
// Example #3 -- Directed Weighted Graph
WeightedVertex<char, double> A('A');
WeightedVertex<char, double> B('B');
WeightedVertex<char, double> C('C');
WeightedVertex<char, double> S('S');
WeightedVertex<char, double> T('T');
WeightedVertex<char, double> F('F');
UndirectedWeightedGraph<char, double> testWeightedGraph3;
testWeightedGraph3.AddPair(S, A, 3);
testWeightedGraph3.AddPair(S, B, 4);
testWeightedGraph3.AddPair(B, F, 5);
testWeightedGraph3.AddPair(A, B, 6);
testWeightedGraph3.AddPair(A, F, 7);
testWeightedGraph3.AddPair(A, C, 2);
testWeightedGraph3.AddPair(C, F, 1);
testWeightedGraph3.AddPair(C, T, 8);
testWeightedGraph3.AddPair(F, T, 4);
// Show Graph
testWeightedGraph3.Print();
std::cout << std::endl << std::endl;
ShortestPath<char, double> testDijstra3(testWeightedGraph3);
testDijstra3.DijkstraShortestPath(S);
std::cout << std::endl << std::endl;
} | 30.529412 | 112 | 0.647399 | JohnPapagiannakos |
ca4536e54a4c45a4f1018e1cb736391991d15223 | 12,420 | cpp | C++ | Form_DLL/Source_Files/Form.cpp | SebastienKeroack/MyEA | 5130056735199595c28c274cf67e7addb280aabc | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | Form_DLL/Source_Files/Form.cpp | SebastienKeroack/MyEA | 5130056735199595c28c274cf67e7addb280aabc | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | Form_DLL/Source_Files/Form.cpp | SebastienKeroack/MyEA | 5130056735199595c28c274cf67e7addb280aabc | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /* Copyright 2020 Sébastien Kéroack. 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 "stdafx.hpp"
#include <Form.hpp>
#include <Form/Form__Neural_Network.h>
#include <Files/File.hpp>
#include <msclr\auto_gcroot.h>
namespace MyEA
{
namespace Form
{
template<typename FORM>
struct struct_Thread_Form
{
bool Allocate(void);
bool Deallocate(void);
static int Run(FORM^ ptr_FORM_received);
HANDLE handle_thread = NULL;
HANDLE handle_initialized = NULL;
msclr::auto_gcroot<FORM^> ptr_GC_Form = nullptr;
};
template<typename FORM>
DWORD THREAD_FORM_START_ROUTINE(LPVOID lp_struct_Thread_Form)
{
struct struct_Thread_Form<FORM> *tmp_ptr_struct_Thread_Form(reinterpret_cast<struct struct_Thread_Form<FORM>*>(lp_struct_Thread_Form));
tmp_ptr_struct_Thread_Form->ptr_GC_Form = gcnew FORM();
// Telling the thread is initialized.
SetEvent(tmp_ptr_struct_Thread_Form->handle_initialized);
struct_Thread_Form<FORM>::Run(tmp_ptr_struct_Thread_Form->ptr_GC_Form.get());
tmp_ptr_struct_Thread_Form->ptr_GC_Form.reset();
return(0ul);
}
template<typename FORM>
int struct_Thread_Form<FORM>::Run(FORM^ ptr_FORM_received)
{
// Enabling Windows XP visual effects before any controls are created
//Application::EnableVisualStyles();
//Application::SetCompatibleTextRenderingDefault(false);
Application::Run(ptr_FORM_received);
return(0);
}
template<typename FORM>
bool struct_Thread_Form<FORM>::Allocate(void)
{
if(safe_cast<FORM^>(this->ptr_GC_Form.get()) == nullptr)
{
// Create event for telling if the thread is initialized.
this->handle_initialized = CreateEvent(NULL, FALSE, FALSE, NULL);
// Create a thread containing the form.
if((this->handle_thread = CreateThread(NULL,
0,
reinterpret_cast<LPTHREAD_START_ROUTINE>(THREAD_FORM_START_ROUTINE<FORM>),
reinterpret_cast<LPVOID>(this),
0,
NULL)) == NULL)
{ return(false); }
// Waiting thread to initialize.
WaitForSingleObject(this->handle_initialized, INFINITE);
// Initialization finish. Close the handle (event).
CloseHandle(this->handle_initialized);
}
else { return(false); }
return(true);
}
template<typename FORM>
bool struct_Thread_Form<FORM>::Deallocate(void)
{
if(safe_cast<FORM^>(this->ptr_GC_Form.get()) != nullptr)
{
// Close form.
this->ptr_GC_Form->Close();
// Waiting thread
WaitForSingleObject(this->handle_thread, INFINITE);
// Close thread
CloseHandle(this->handle_thread);
return(true);
}
return(false);
}
struct struct_Thread_Form<Form_Neural_Network> *global_ptr_Form_Neural_Network = nullptr;
DLL_API bool API__Form__Is_Loaded(void) { return(true); }
DLL_API void API__Form__Neural_Network__Allocate(void)
{
if(global_ptr_Form_Neural_Network == nullptr)
{
global_ptr_Form_Neural_Network = new struct struct_Thread_Form<Form_Neural_Network>;
if(global_ptr_Form_Neural_Network->Allocate() == false)
{
PRINT_FORMAT("%s: ERROR: Can not allocate 'global_ptr_Form_Neural_Network'." NEW_LINE, __FUNCTION__);
SAFE_DELETE(global_ptr_Form_Neural_Network);
}
}
}
DLL_API void API__Form__Neural_Network__Chart_Use_Datapoint_Training(bool const use_datapoint_training_received)
{
if(global_ptr_Form_Neural_Network != nullptr)
{ global_ptr_Form_Neural_Network->ptr_GC_Form->Chart_Use_Datapoint_Training(use_datapoint_training_received); }
}
DLL_API void API__Form__Neural_Network__Chart_Initialize(unsigned int const type_chart_received, unsigned int const number_series_received)
{
if(global_ptr_Form_Neural_Network != nullptr)
{ global_ptr_Form_Neural_Network->ptr_GC_Form->Chart_Initialize(type_chart_received, number_series_received); }
}
DLL_API void API__Form__Neural_Network__Chart_Total_Means(unsigned int const total_means_received)
{
if(global_ptr_Form_Neural_Network != nullptr)
{ global_ptr_Form_Neural_Network->ptr_GC_Form->Chart_Total_Means(total_means_received); }
}
DLL_API void API__Form__Neural_Network__Chart_Reset(unsigned int const type_chart_received)
{
if(global_ptr_Form_Neural_Network != nullptr)
{ global_ptr_Form_Neural_Network->ptr_GC_Form->Chart_Reset(type_chart_received); }
}
DLL_API void API__Form__Neural_Network__Chart_Rescale(unsigned int const type_chart_received)
{
if(global_ptr_Form_Neural_Network != nullptr)
{ global_ptr_Form_Neural_Network->ptr_GC_Form->Chart_Rescale(type_chart_received); }
}
DLL_API void API__Form__Neural_Network__Chart_Add_Point(unsigned int const type_chart_received,
unsigned int const index_series_received,
unsigned int const type_loss_received,
double const x_received,
double const y_received)
{
if(global_ptr_Form_Neural_Network != nullptr)
{
global_ptr_Form_Neural_Network->ptr_GC_Form->Chart_Add_Point(type_chart_received,
index_series_received,
type_loss_received,
x_received,
y_received);
}
}
DLL_API void API__Form__Neural_Network__Chart_Grid_Search_Add_Column(std::string const &ref_value_received)
{
if(global_ptr_Form_Neural_Network != nullptr)
{
global_ptr_Form_Neural_Network->ptr_GC_Form->Chart_Grid_Search_Add_Column(gcnew System::String(ref_value_received.c_str()));
}
}
DLL_API void API__Form__Neural_Network__Chart_Grid_Search_Add_Row(unsigned int const cell_index_received, std::string const &ref_value_received)
{
if(global_ptr_Form_Neural_Network != nullptr)
{
global_ptr_Form_Neural_Network->ptr_GC_Form->Chart_Grid_Search_Add_Row(cell_index_received, gcnew System::String(ref_value_received.c_str()));
}
}
DLL_API void API__Form__Neural_Network__Chart_Loss_Diff(unsigned int const index_series_received,
unsigned int const type_received,
double const x_received)
{
if(global_ptr_Form_Neural_Network != nullptr)
{
global_ptr_Form_Neural_Network->ptr_GC_Form->Chart_Loss_Diff(index_series_received,
type_received,
x_received);
}
}
DLL_API void API__Form__Neural_Network__Chart_Scale(unsigned int const type_chart_received,
unsigned int const index_series_received,
unsigned int const type_loss_received,
bool const scale_y_axis_received,
double const x_received,
double const y_received)
{
/*
if(global_ptr_Form_Neural_Network != nullptr)
{
global_ptr_Form_Neural_Network->ptr_GC_Form->Chart_Add_Point(type_chart_received,
index_series_received,
type_loss_received,
x_received,
y_received);
}
*/
}
DLL_API void API__Form__Neural_Network__Deallocate(void)
{
if(global_ptr_Form_Neural_Network != nullptr)
{
global_ptr_Form_Neural_Network->Deallocate();
SAFE_DELETE(global_ptr_Form_Neural_Network);
}
}
DLL_API bool API__Form__Neural_Network__Get_Signal_Training_Stop(void)
{
if(global_ptr_Form_Neural_Network != nullptr) { return(global_ptr_Form_Neural_Network->ptr_GC_Form->Get__Signal_Training_Stop()); }
return(false);
}
DLL_API bool API__Form__Neural_Network__Get_Signal_Training_Menu(void)
{
if(global_ptr_Form_Neural_Network != nullptr) { return(global_ptr_Form_Neural_Network->ptr_GC_Form->Get__Signal_Training_Menu()); }
return(false);
}
DLL_API bool API__Form__Neural_Network__Reset_Signal_Training_Menu(void)
{
if(global_ptr_Form_Neural_Network != nullptr)
{
global_ptr_Form_Neural_Network->ptr_GC_Form->Reset__Signal_Training_Menu();
return(true);
}
return(false);
}
}
} | 46.343284 | 165 | 0.496618 | SebastienKeroack |
ca49acb3a7702340d3e0d74edf3d833d9c4e0624 | 5,703 | hpp | C++ | Graphics/GraphicsEngineVulkan/include/EngineVkImplTraits.hpp | MikhailGorobets/DiligentCore | 340064e521a6012cb6230564fb9d2e3a263b6911 | [
"Apache-2.0"
] | 398 | 2016-04-21T03:38:50.000Z | 2022-03-23T15:27:31.000Z | Graphics/GraphicsEngineVulkan/include/EngineVkImplTraits.hpp | MikhailGorobets/DiligentCore | 340064e521a6012cb6230564fb9d2e3a263b6911 | [
"Apache-2.0"
] | 275 | 2017-12-27T04:11:55.000Z | 2022-03-30T07:35:11.000Z | Graphics/GraphicsEngineVulkan/include/EngineVkImplTraits.hpp | MikhailGorobets/DiligentCore | 340064e521a6012cb6230564fb9d2e3a263b6911 | [
"Apache-2.0"
] | 139 | 2017-09-13T06:19:49.000Z | 2022-03-28T15:01:20.000Z | /*
* Copyright 2019-2021 Diligent Graphics LLC
* Copyright 2015-2019 Egor Yusov
*
* 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.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#pragma once
/// \file
/// Declaration of Diligent::EngineVkImplTraits struct
#include "RenderDeviceVk.h"
#include "PipelineStateVk.h"
#include "ShaderResourceBindingVk.h"
#include "BufferVk.h"
#include "BufferViewVk.h"
#include "TextureVk.h"
#include "TextureViewVk.h"
#include "ShaderVk.h"
#include "SamplerVk.h"
#include "FenceVk.h"
#include "QueryVk.h"
#include "RenderPassVk.h"
#include "FramebufferVk.h"
#include "CommandList.h"
#include "BottomLevelASVk.h"
#include "TopLevelASVk.h"
#include "ShaderBindingTableVk.h"
#include "PipelineResourceSignature.h"
#include "DeviceMemoryVk.h"
#include "CommandQueueVk.h"
#include "DeviceContextVk.h"
namespace Diligent
{
class RenderDeviceVkImpl;
class DeviceContextVkImpl;
class PipelineStateVkImpl;
class ShaderResourceBindingVkImpl;
class BufferVkImpl;
class BufferViewVkImpl;
class TextureVkImpl;
class TextureViewVkImpl;
class ShaderVkImpl;
class SamplerVkImpl;
class FenceVkImpl;
class QueryVkImpl;
class RenderPassVkImpl;
class FramebufferVkImpl;
class CommandListVkImpl;
class BottomLevelASVkImpl;
class TopLevelASVkImpl;
class ShaderBindingTableVkImpl;
class PipelineResourceSignatureVkImpl;
class DeviceMemoryVkImpl;
class FixedBlockMemoryAllocator;
class ShaderResourceCacheVk;
class ShaderVariableManagerVk;
struct PipelineResourceAttribsVk;
struct EngineVkImplTraits
{
using RenderDeviceInterface = IRenderDeviceVk;
using DeviceContextInterface = IDeviceContextVk;
using PipelineStateInterface = IPipelineStateVk;
using ShaderResourceBindingInterface = IShaderResourceBindingVk;
using BufferInterface = IBufferVk;
using BufferViewInterface = IBufferViewVk;
using TextureInterface = ITextureVk;
using TextureViewInterface = ITextureViewVk;
using ShaderInterface = IShaderVk;
using SamplerInterface = ISamplerVk;
using FenceInterface = IFenceVk;
using QueryInterface = IQueryVk;
using RenderPassInterface = IRenderPassVk;
using FramebufferInterface = IFramebufferVk;
using CommandListInterface = ICommandList;
using BottomLevelASInterface = IBottomLevelASVk;
using TopLevelASInterface = ITopLevelASVk;
using ShaderBindingTableInterface = IShaderBindingTableVk;
using PipelineResourceSignatureInterface = IPipelineResourceSignature;
using CommandQueueInterface = ICommandQueueVk;
using DeviceMemoryInterface = IDeviceMemoryVk;
using RenderDeviceImplType = RenderDeviceVkImpl;
using DeviceContextImplType = DeviceContextVkImpl;
using PipelineStateImplType = PipelineStateVkImpl;
using ShaderResourceBindingImplType = ShaderResourceBindingVkImpl;
using BufferImplType = BufferVkImpl;
using BufferViewImplType = BufferViewVkImpl;
using TextureImplType = TextureVkImpl;
using TextureViewImplType = TextureViewVkImpl;
using ShaderImplType = ShaderVkImpl;
using SamplerImplType = SamplerVkImpl;
using FenceImplType = FenceVkImpl;
using QueryImplType = QueryVkImpl;
using RenderPassImplType = RenderPassVkImpl;
using FramebufferImplType = FramebufferVkImpl;
using CommandListImplType = CommandListVkImpl;
using BottomLevelASImplType = BottomLevelASVkImpl;
using TopLevelASImplType = TopLevelASVkImpl;
using ShaderBindingTableImplType = ShaderBindingTableVkImpl;
using PipelineResourceSignatureImplType = PipelineResourceSignatureVkImpl;
using DeviceMemoryImplType = DeviceMemoryVkImpl;
using BuffViewObjAllocatorType = FixedBlockMemoryAllocator;
using TexViewObjAllocatorType = FixedBlockMemoryAllocator;
using ShaderResourceCacheImplType = ShaderResourceCacheVk;
using ShaderVariableManagerImplType = ShaderVariableManagerVk;
using PipelineResourceAttribsType = PipelineResourceAttribsVk;
};
} // namespace Diligent
| 40.446809 | 89 | 0.716114 | MikhailGorobets |
ca4a3b59709f41f392d1270ee057df2939511ebe | 1,345 | cpp | C++ | Rev/cpp/revMaterialLoader.cpp | YIMonge/Rev | db3b71a27659a2652bdd50069a881702b3ae059e | [
"MIT"
] | null | null | null | Rev/cpp/revMaterialLoader.cpp | YIMonge/Rev | db3b71a27659a2652bdd50069a881702b3ae059e | [
"MIT"
] | null | null | null | Rev/cpp/revMaterialLoader.cpp | YIMonge/Rev | db3b71a27659a2652bdd50069a881702b3ae059e | [
"MIT"
] | null | null | null | #include "revMaterialLoader.h"
const uint32 DATA_VERSION = 1;
revMaterialLoader::revMaterialLoader()
{}
revMaterialLoader::~revMaterialLoader()
{}
bool revMaterialLoader::LoadFromFile(const char* path, revMaterial* material)
{
if (!revResourceLoader::LoadFromFile(path, material)) return false;
uint32 offset = 0;
uint32 dataVer;
offset = file.ReadData(&dataVer, sizeof(uint32), offset);
if (dataVer != DATA_VERSION) {
// if need upgrade, write here
file.Close();
return false;
}
uint32 propertyCount;
offset = file.ReadData(&propertyCount, sizeof(uint32), offset);
material->properties.resize(propertyCount);
for (uint32 i = 0; i < propertyCount; ++i) {
offset = file.ReadData(&material->properties[i], sizeof(revMaterial::Property), offset);
}
file.Close();
return true;
}
#ifdef _WINDOWS
void revMaterialLoader::WriteMaterial(const char* path, const revMaterial& material)
{
DeleteFileA(path);
File writingFile;
writingFile.Open(path, FileMode::WriteBinary);
writingFile.WriteAppend(&DATA_VERSION, sizeof(uint32));
uint32 propertyCount = static_cast<uint32>(material.properties.size());
writingFile.WriteAppend(&propertyCount, sizeof(uint32));
for (uint32 i = 0; i < propertyCount; ++i) {
writingFile.WriteAppend(&material.properties[i], sizeof(revMaterial::Property));
}
writingFile.Close();
}
#endif
| 27.44898 | 90 | 0.744981 | YIMonge |
ca4e292a63712fdf69e6acf422d0e42b0b8ac282 | 123 | cpp | C++ | examples/simple_library/sources/simple_library.cpp | Liastre/CMakeExtended | 806951169ad340afb3d15060dacacf8e19c7facc | [
"MIT"
] | null | null | null | examples/simple_library/sources/simple_library.cpp | Liastre/CMakeExtended | 806951169ad340afb3d15060dacacf8e19c7facc | [
"MIT"
] | null | null | null | examples/simple_library/sources/simple_library.cpp | Liastre/CMakeExtended | 806951169ad340afb3d15060dacacf8e19c7facc | [
"MIT"
] | null | null | null | #include <simple_library.hpp>
#include <iostream>
void Simple::hello() {
std::cout << "Hello World!" << std::endl;
}
| 15.375 | 45 | 0.634146 | Liastre |
ca4ed8dfef3c1c1a2b6bc60b5eb09456ddc1867d | 677 | hpp | C++ | CocoaPhoenix/include/PHXCocoaClassDefs.hpp | phoenix-engine/phoenix | c3285482ee507b566a1c38da071439dab507a877 | [
"MIT"
] | 2 | 2019-05-04T19:33:26.000Z | 2019-06-29T13:19:33.000Z | CocoaPhoenix/include/PHXCocoaClassDefs.hpp | phoenix-engine/phoenix | c3285482ee507b566a1c38da071439dab507a877 | [
"MIT"
] | 13 | 2019-05-05T12:40:54.000Z | 2020-02-29T20:32:11.000Z | CocoaPhoenix/include/PHXCocoaClassDefs.hpp | phoenix-engine/phoenix | c3285482ee507b566a1c38da071439dab507a877 | [
"MIT"
] | 4 | 2018-09-15T21:59:08.000Z | 2019-05-04T20:19:07.000Z | //
// PHXCocoaClassDefns.h
// CocoaPhoenix
//
// PHXCocoaClassDefns includes the necessary internal headers defining
// CocoaPhoenix components, such as view delegates, view controllers, and
// responders. The actual implementations vary by target platform.
//
// Created by Bodie Solomon on 4/8/19.
//
#ifndef PHXCocoaClassDefs_hpp
#define PHXCocoaClassDefs_hpp
#include "cocoa_phx/PHXShaders.h"
#include "cocoa_phx/PHXRenderer.hpp"
#include "cocoa_phx/PHXResourceManager.hpp"
#include "cocoa_phx/PHXDrawer.hpp"
#include "cocoa_phx/PHXViewDelegate.hpp"
#include "cocoa_phx/PHXViewController.hpp"
#include "cocoa_phx/PHXResponder.hpp"
#endif /* PHXCocoaClassDefs_hpp */
| 28.208333 | 73 | 0.790251 | phoenix-engine |
ca53907e2fcb003dff4f612891b4ee7c42bde0d9 | 593 | hpp | C++ | include/Utility.hpp | Yunxiang-Li/SFML_Space-Shooter-Game | f6bf9753d2109e1a206efb7dc5a0b1b6e421ce52 | [
"MIT"
] | null | null | null | include/Utility.hpp | Yunxiang-Li/SFML_Space-Shooter-Game | f6bf9753d2109e1a206efb7dc5a0b1b6e421ce52 | [
"MIT"
] | null | null | null | include/Utility.hpp | Yunxiang-Li/SFML_Space-Shooter-Game | f6bf9753d2109e1a206efb7dc5a0b1b6e421ce52 | [
"MIT"
] | null | null | null | #ifndef UTILITY_HPP
#define UTILITY_HPP
// Include standard library C++ libraries.
#include <sstream>
// Forward declaration of sf::Sprite class and sf::Text class.
namespace sf
{
class Sprite;
class Text;
}
// Since std::to_string doesn't work on MinGW we have to implement
// our own to support all platforms.
template <typename T>
std::string toString(const T& value);
// Set sprite's origin to be its center position.
void centerOrigin(sf::Sprite& sprite);
// Set text's origin to be its center position.
void centerOrigin(sf::Text& text);
#include "Utility.inl"
#endif // UTILITY_HPP | 23.72 | 66 | 0.745363 | Yunxiang-Li |
ca547177c2aeb395793ee233c33b6a7779ff043f | 902 | hpp | C++ | src/fhmdot/include/utils.hpp | nokx5/fhmdot | 53a92804a18c98537964cd7cb09a60896d5d3744 | [
"MIT"
] | null | null | null | src/fhmdot/include/utils.hpp | nokx5/fhmdot | 53a92804a18c98537964cd7cb09a60896d5d3744 | [
"MIT"
] | null | null | null | src/fhmdot/include/utils.hpp | nokx5/fhmdot | 53a92804a18c98537964cd7cb09a60896d5d3744 | [
"MIT"
] | null | null | null | #include <boost/type_traits/is_complex.hpp>
#include <complex>
#ifndef FLOAT_PRECISION
using data_t = double;
#else
using data_t = float;
#endif
namespace fhmdot {
namespace utils {
template <typename T> constexpr bool is_complex() {
return boost::is_complex<T>::value;
}
template <typename T> constexpr bool is_float() {
if (is_complex<T>()) {
return std::is_same<typename std::complex<float>, T>::value;
} else {
return std::is_same<float, T>::value;
}
}
template <typename T> constexpr char num_character() {
if (std::is_same<float, T>::value) {
return 'F';
} else if (std::is_same<double, T>::value) {
return 'D';
} else if (std::is_same<typename std::complex<float>, T>::value) {
return 'C';
} else if (std::is_same<typename std::complex<double>, T>::value) {
return 'Z';
} else {
return '?';
};
};
} // namespace utils
} // namespace fhmdot
| 21.47619 | 69 | 0.651885 | nokx5 |
ca54c3245dd4c4ae395b7697343d6ed728c24ac2 | 3,439 | hpp | C++ | viz/SurfaceGeode.hpp | skasperski/slam-maps | 916c2ab77573162a17df2567cf6df16c300538bc | [
"BSD-2-Clause"
] | null | null | null | viz/SurfaceGeode.hpp | skasperski/slam-maps | 916c2ab77573162a17df2567cf6df16c300538bc | [
"BSD-2-Clause"
] | null | null | null | viz/SurfaceGeode.hpp | skasperski/slam-maps | 916c2ab77573162a17df2567cf6df16c300538bc | [
"BSD-2-Clause"
] | null | null | null | //
// Copyright (c) 2015-2017, Deutsches Forschungszentrum für Künstliche Intelligenz GmbH.
// Copyright (c) 2015-2017, University of Bremen
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#ifndef __VIZKIT_SURFACEGEODE_HPP__
#define __VIZKIT_SURFACEGEODE_HPP__
#include <osg/Geometry>
#include <osg/Geode>
#include <Eigen/Geometry>
#include <Eigen/StdVector>
#include <base-logging/Logging.hpp>
namespace vizkit3d {
class SurfaceGeode : public osg::Geode
{
public:
SurfaceGeode(float x_res, float y_res);
void setColor(const osg::Vec4& color);
void setColorHSVA(float hue, float sat, float lum, float alpha);
void showCycleColor(bool cycle_color);
void setCycleColorInterval(float cycle_color_interval);
void setUncertaintyScale(double uncertainty_scale);
void setShowPatchExtents(bool enable = true) { showPatchExtents = enable; };
void setShowNormals(bool enable = true) { showNormals = enable; };
void setShowUncertainty(bool enable = true) { showUncertainty = enable; }
void drawLines();
void addVertex(const osg::Vec3& p, const osg::Vec3& n, const float & stdev = 0.f);
void closeTriangleStrip(){
geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLE_STRIP,vertex_index,vertices->size()-vertex_index));
vertex_index = vertices->size();
}
private:
osg::ref_ptr<osg::Vec3Array> vertices;
osg::ref_ptr<osg::Vec3Array> normals;
osg::ref_ptr<osg::Vec4Array> colors;
osg::ref_ptr<osg::Geometry> geom;
osg::ref_ptr<osg::Vec3Array> var_vertices;
size_t vertex_index;
float xp, yp; // position of current patch
float xs, ys; // grid resolution
float hue;
float sat;
float alpha;
float lum;
osg::Vec4 color;
bool showNormals;
bool showPatchExtents;
bool showUncertainty;
bool cycle_color;
float cycle_color_interval;
double uncertaintyScale;
void updateColor();
};
}
#endif // __VIZKIT_PATCHESGEODE_HPP__
| 35.091837 | 133 | 0.701076 | skasperski |
ca55e88543c640a25adf7ee12b247b8dd1948e7d | 858 | cpp | C++ | libraries/tests/net/cellular/sms/common/smstest.cpp | hakehuang/mbed | 04b488dcc418f0317cdee1781b27a59295909c77 | [
"Apache-2.0"
] | 1 | 2019-05-07T15:01:19.000Z | 2019-05-07T15:01:19.000Z | libraries/tests/net/cellular/sms/common/smstest.cpp | suparit/mbed | 49df530ae72ce97ccc773d1f2c13b38e868e6abd | [
"Apache-2.0"
] | null | null | null | libraries/tests/net/cellular/sms/common/smstest.cpp | suparit/mbed | 49df530ae72ce97ccc773d1f2c13b38e868e6abd | [
"Apache-2.0"
] | null | null | null | #include "CellularModem.h"
#include "smstest.h"
void smstest(CellularModem& modem)
{
modem.power(true);
Thread::wait(1000);
#ifdef DESTINATION_NUMBER
modem.sendSM(DESINATION_NUMBER, "Hello from mbed:)");
#endif
while(true)
{
char num[17];
char msg[64];
size_t count;
int ret = modem.getSMCount(&count);
if(ret)
{
printf("getSMCount returned %d\n", ret);
Thread::wait(3000);
continue;
}
if( count > 0)
{
printf("%d SMS to read\n", count);
ret = modem.getSM(num, msg, 64);
if(ret)
{
printf("getSM returned %d\n", ret);
Thread::wait(3000);
continue;
}
printf("%s : %s\n", num, msg);
}
Thread::wait(3000);
}
}
| 20.428571 | 57 | 0.481352 | hakehuang |
ca583476bd54c47392209ea474030d4180cafa27 | 2,660 | cpp | C++ | src/utilities.cpp | KerryL/SystemID | d1d4ff61db06ed79c1e1e5f7fd05ab2d1b879498 | [
"MIT"
] | 1 | 2019-12-08T03:07:02.000Z | 2019-12-08T03:07:02.000Z | src/utilities.cpp | KerryL/SystemID | d1d4ff61db06ed79c1e1e5f7fd05ab2d1b879498 | [
"MIT"
] | 1 | 2021-12-02T01:23:27.000Z | 2021-12-02T01:23:27.000Z | src/utilities.cpp | KerryL/SystemID | d1d4ff61db06ed79c1e1e5f7fd05ab2d1b879498 | [
"MIT"
] | null | null | null | // File: utilities.cpp
// Date: 8/4/2016
// Auth: K. Loux
// Desc: Tire data modeling utilities.
// Standard C++ headers
#include <limits>
#include <sstream>
#include <iomanip>
// Local headers
#include "utilities.h"
//==========================================================================
// Namespace: Utilities
// Function: ComputeCoefficientOfDetermination
//
// Description: Computes the r^2 value for the given data.
//
// Input Arguments:
// observedValues = const std::vector<double>&
// fitValues = const std::vector<double>&
//
// Output Arguments:
// None
//
// Return Value:
// double
//
//==========================================================================
double Utilities::ComputeCoefficientOfDetermination(
const std::vector<double>& observedValues,
const std::vector<double>& fitValues)
{
assert(observedValues.size() > 1);
assert(observedValues.size() == fitValues.size());
double totalSumSquares(0.0);
double residualSumSquares(0.0);
const double mean(ComputeMean(observedValues));
unsigned int i;
for (i = 0; i < observedValues.size(); i++)
{
totalSumSquares += (observedValues[i] - mean) * (observedValues[i] - mean);
residualSumSquares += (observedValues[i] - fitValues[i]) * (observedValues[i] - fitValues[i]);
}
return 1.0 - residualSumSquares / totalSumSquares;
}
//==========================================================================
// Namespace: Utilities
// Function: ComputeStanardErrorOfRegression
//
// Description: Computes the standard error of the regression for the
// given data.
//
// Input Arguments:
// observedValues = const std::vector<double>&
// fitValues = const std::vector<double>&
//
// Output Arguments:
// None
//
// Return Value:
// double
//
//==========================================================================
double Utilities::ComputeStanardErrorOfRegression(
const std::vector<double>& observedValues,
const std::vector<double>& fitValues)
{
assert(observedValues.size() > 0);
assert(observedValues.size() == fitValues.size());
double residualSumSquares(0.0);
unsigned int i;
for (i = 0; i < observedValues.size(); i++)
residualSumSquares += (observedValues[i] - fitValues[i]) * (observedValues[i] - fitValues[i]);
return std::sqrt(residualSumSquares / observedValues.size());
}
std::string Utilities::ReplaceAllOccurrences(std::string s,
const std::string& pattern, const std::string& newString)
{
std::string::size_type position(0);
while (position = s.find(pattern, position), position != std::string::npos)
{
s.replace(position, pattern.length(), newString);
position += newString.length();
}
return s;
}
| 27.42268 | 96 | 0.62218 | KerryL |
3ed35e570fbcb03fd0c1985284a9011f20702b1f | 866 | cpp | C++ | ZOJ/4014/implementation.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2018-02-14T01:59:31.000Z | 2018-03-28T03:30:45.000Z | ZOJ/4014/implementation.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | null | null | null | ZOJ/4014/implementation.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2017-12-30T02:46:35.000Z | 2018-03-28T03:30:49.000Z | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <string>
#include <cstring>
#include <iomanip>
#include <climits>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <functional>
#include <iterator>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
int caseNum;
cin >> caseNum;
while (caseNum--)
{
int row, column, a, b;
cin >> row >> column >> a >> b;
int ans = 0;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
int cnt;
cin >> cnt;
if (cnt < a || cnt > b)
ans++;
}
}
if (a > b)
cout << "No Solution" << endl;
else
cout << ans << endl;
}
return 0;
}
| 18.826087 | 44 | 0.461894 | codgician |
3ed66912d664ac4cdc51e4d44ff3b6e1b78f3024 | 4,257 | hpp | C++ | src/vec/func/trig.hpp | Thhethssmuz/mmm | ee91a990fba3849db1fc2b6df0e89004e2df466f | [
"MIT"
] | 1 | 2017-03-14T20:45:54.000Z | 2017-03-14T20:45:54.000Z | src/vec/func/trig.hpp | Thhethssmuz/mmm | ee91a990fba3849db1fc2b6df0e89004e2df466f | [
"MIT"
] | 1 | 2017-03-08T17:14:03.000Z | 2017-03-08T23:40:35.000Z | src/vec/func/trig.hpp | Thhethssmuz/mmm | ee91a990fba3849db1fc2b6df0e89004e2df466f | [
"MIT"
] | null | null | null | #pragma once
// all trigonometric functions are only defined for floating point types and
// floating vector types.
template <typename T, typename = typefu::for_arithmetic<T>>
constexpr typefu::promotef<T> radians(T degrees);
template <typename T, size_t N, typename = typefu::for_floating<T>>
constexpr tvec<T, N> radians(const tvec<T, N>& degrees);
template <typename T, size_t N, typename A, typename = typefu::for_floating<T>>
constexpr tvec<T, N> radians(const vecType<T, N, A>& degrees);
template <typename T, typename = typefu::for_arithmetic<T>>
constexpr typefu::promotef<T> degrees(T radians);
template <typename T, size_t N, typename = typefu::for_floating<T>>
constexpr tvec<T, N> degrees(const tvec<T, N>& radians);
template <typename T, size_t N, typename A, typename = typefu::for_floating<T>>
constexpr tvec<T, N> degrees(const vecType<T, N, A>& radians);
template <typename T, typename = typefu::for_arithmetic<T>>
constexpr typefu::promotef<T> sin(T angle);
template <typename T, size_t N, typename = typefu::for_floating<T>>
constexpr tvec<T, N> sin(const tvec<T, N>& angle);
template <typename T, size_t N, typename A, typename = typefu::for_floating<T>>
constexpr tvec<T, N> sin(const vecType<T, N, A>& angle);
template <typename T, typename = typefu::for_arithmetic<T>>
constexpr typefu::promotef<T> cos(T angle);
template <typename T, size_t N, typename = typefu::for_floating<T>>
constexpr tvec<T, N> cos(const tvec<T, N>& angle);
template <typename T, size_t N, typename A, typename = typefu::for_floating<T>>
constexpr tvec<T, N> cos(const vecType<T, N, A>& angle);
template <typename T, typename = typefu::for_arithmetic<T>>
constexpr typefu::promotef<T> tan(T angle);
template <typename T, size_t N, typename = typefu::for_floating<T>>
constexpr tvec<T, N> tan(const tvec<T, N>& angle);
template <typename T, size_t N, typename A, typename = typefu::for_floating<T>>
constexpr tvec<T, N> tan(const vecType<T, N, A>& angle);
template <typename T, typename = typefu::for_arithmetic<T>>
constexpr typefu::promotef<T> asin(T x);
template <typename T, size_t N, typename = typefu::for_floating<T>>
constexpr tvec<T, N> asin(const tvec<T, N>& x);
template <typename T, size_t N, typename A, typename = typefu::for_floating<T>>
constexpr tvec<T, N> asin(const vecType<T, N, A>& x);
template <typename T, typename = typefu::for_arithmetic<T>>
constexpr typefu::promotef<T> acos(T x);
template <typename T, size_t N, typename = typefu::for_floating<T>>
constexpr tvec<T, N> acos(const tvec<T, N>& x);
template <typename T, size_t N, typename A, typename = typefu::for_floating<T>>
constexpr tvec<T, N> acos(const vecType<T, N, A>& x);
template <typename T, typename = typefu::for_arithmetic<T>>
constexpr typefu::promotef<T> atan(T y_over_x);
template <typename T, size_t N, typename = typefu::for_floating<T>>
constexpr tvec<T, N> atan(const tvec<T, N>& y_over_x);
template <typename T, size_t N, typename A, typename = typefu::for_floating<T>>
constexpr tvec<T, N> atan(const vecType<T, N, A>& y_over_x);
template <typename T, typename = typefu::for_floating<T>>
constexpr T atan(T y, T x);
template <typename T, typename U, typename = typefu::for_arithmetic<T, U>>
constexpr typefu::promotef<T, U> atan(T y, U x);
template <typename T, size_t N, typename = typefu::for_floating<T>>
constexpr tvec<T, N> atan(T y, const tvec<T, N>& x);
template <typename T, typename U, size_t N, typename A,
typename = typefu::for_floating<T>,
typename = typefu::for_arithmetic<U>>
constexpr tvec<T, N> atan(U y, const vecType<T, N, A>& x);
template <typename T, size_t N, typename = typefu::for_floating<T>>
constexpr tvec<T, N> atan(const tvec<T, N>& y, T x);
template <typename T, typename U, size_t N, typename A,
typename = typefu::for_floating<T>,
typename = typefu::for_arithmetic<U>>
constexpr tvec<T, N> atan(const vecType<T, N, A>& y, U x);
template <typename T, size_t N, typename = typefu::for_floating<T>>
constexpr tvec<T, N> atan(const tvec<T, N>& y, const tvec<T, N>& x);
template <typename T, size_t N, typename A, typename B,
typename = typefu::for_floating<T>>
constexpr tvec<T, N> atan(const vecType<T, N, A>& y, const vecType<T, N, B>& x);
| 37.342105 | 80 | 0.709655 | Thhethssmuz |
3ed75ac2540d9a81cdd0d224888fdfd86366de14 | 444 | c++ | C++ | xp_comm_proj/rd_vrml/vrml2geo/qv/src/QvWWWInline.c++ | avs/express-community | c699a68330d3b678b7e6bcea823e0891b874049c | [
"Apache-2.0"
] | 3 | 2020-08-03T08:52:20.000Z | 2021-04-10T11:55:49.000Z | xp_comm_proj/rd_vrml/vrml2geo/qv/src/QvWWWInline.c++ | avs/express-community | c699a68330d3b678b7e6bcea823e0891b874049c | [
"Apache-2.0"
] | null | null | null | xp_comm_proj/rd_vrml/vrml2geo/qv/src/QvWWWInline.c++ | avs/express-community | c699a68330d3b678b7e6bcea823e0891b874049c | [
"Apache-2.0"
] | 1 | 2021-06-08T18:16:45.000Z | 2021-06-08T18:16:45.000Z | #include <QvWWWInline.h>
QV_NODE_SOURCE(QvWWWInline);
QvWWWInline::QvWWWInline()
{
QV_NODE_CONSTRUCTOR(QvWWWInline);
isBuiltIn = TRUE;
QV_NODE_ADD_FIELD(name);
QV_NODE_ADD_FIELD(bboxSize);
QV_NODE_ADD_FIELD(bboxCenter);
name.value = "";
bboxSize.value[0] = bboxSize.value[0] = bboxSize.value[0] = 0.0;
bboxCenter.value[0] = bboxCenter.value[0] = bboxCenter.value[0] = 0.0;
}
QvWWWInline::~QvWWWInline()
{
}
| 20.181818 | 74 | 0.691441 | avs |
3ed9d61e7928f8f10a762f9161ed9b2ba354d31b | 7,663 | cpp | C++ | src/common/expression/PredicateExpression.cpp | linkensphere201/nebula-common-personal | e31b7e88326195a08ac0460fd469326455df6417 | [
"Apache-2.0"
] | null | null | null | src/common/expression/PredicateExpression.cpp | linkensphere201/nebula-common-personal | e31b7e88326195a08ac0460fd469326455df6417 | [
"Apache-2.0"
] | null | null | null | src/common/expression/PredicateExpression.cpp | linkensphere201/nebula-common-personal | e31b7e88326195a08ac0460fd469326455df6417 | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2020 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "common/expression/PredicateExpression.h"
#include "common/expression/ExprVisitor.h"
namespace nebula {
std::unordered_map<std::string, PredicateExpression::Type> PredicateExpression::typeMap_ = {
{"all", Type::ALL},
{"any", Type::ANY},
{"single", Type::SINGLE},
{"none", Type::NONE},
};
const Value& PredicateExpression::evalExists(ExpressionContext& ctx) {
DCHECK(collection_->kind() == Expression::Kind::kAttribute ||
collection_->kind() == Expression::Kind::kSubscript);
auto* attributeExpr = static_cast<BinaryExpression*>(collection_.get());
auto& container = attributeExpr->left()->eval(ctx);
auto& key = attributeExpr->right()->eval(ctx);
switch (container.type()) {
case Value::Type::VERTEX: {
result_ = container.getVertex().contains(key);
break;
}
case Value::Type::EDGE: {
result_ = container.getEdge().contains(key);
break;
}
case Value::Type::MAP: {
result_ = container.getMap().contains(key);
break;
}
case Value::Type::NULLVALUE: {
result_ = Value::kNullValue;
break;
}
default: {
result_ = Value::kNullBadType;
}
}
return result_;
}
const Value& PredicateExpression::eval(ExpressionContext& ctx) {
if (*name_ == "exists") {
return evalExists(ctx);
}
Type type;
auto iter = typeMap_.find(*name_);
if (iter != typeMap_.end()) {
type = iter->second;
} else {
result_ = Value::kNullBadType;
return result_;
}
auto& listVal = collection_->eval(ctx);
if (listVal.isNull() || listVal.empty()) {
result_ = listVal;
return result_;
}
if (!listVal.isList()) {
result_ = Value::kNullBadType;
return result_;
}
auto& list = listVal.getList();
switch (type) {
case Type::ALL: {
result_ = true;
for (size_t i = 0; i < list.size(); ++i) {
auto& v = list[i];
ctx.setVar(*innerVar_, v);
auto& filterVal = filter_->eval(ctx);
if (!filterVal.empty() && !filterVal.isNull() && !filterVal.isBool()) {
return Value::kNullBadType;
}
if (filterVal.empty() || filterVal.isNull() || !filterVal.getBool()) {
result_ = false;
return result_;
}
}
return result_;
}
case Type::ANY: {
result_ = false;
for (size_t i = 0; i < list.size(); ++i) {
auto& v = list[i];
ctx.setVar(*innerVar_, v);
auto& filterVal = filter_->eval(ctx);
if (!filterVal.empty() && !filterVal.isNull() && !filterVal.isBool()) {
return Value::kNullBadType;
}
if (filterVal.isBool() && filterVal.getBool()) {
result_ = true;
return result_;
}
}
return result_;
}
case Type::SINGLE: {
result_ = false;
for (size_t i = 0; i < list.size(); ++i) {
auto& v = list[i];
ctx.setVar(*innerVar_, v);
auto& filterVal = filter_->eval(ctx);
if (!filterVal.empty() && !filterVal.isNull() && !filterVal.isBool()) {
return Value::kNullBadType;
}
if (filterVal.isBool() && filterVal.getBool()) {
if (result_ == false) {
result_ = true;
} else {
result_ = false;
return result_;
}
}
}
return result_;
}
case Type::NONE: {
result_ = true;
for (size_t i = 0; i < list.size(); ++i) {
auto& v = list[i];
ctx.setVar(*innerVar_, v);
auto& filterVal = filter_->eval(ctx);
if (!filterVal.empty() && !filterVal.isNull() && !filterVal.isBool()) {
return Value::kNullBadType;
}
if (filterVal.isBool() && filterVal.getBool()) {
result_ = false;
return result_;
}
}
return result_;
}
// no default so the compiler will warning when lack
}
result_ = Value::kNullBadType;
return result_;
}
bool PredicateExpression::operator==(const Expression& rhs) const {
if (kind() != rhs.kind()) {
return false;
}
const auto& expr = static_cast<const PredicateExpression&>(rhs);
if (*name_ != *expr.name_) {
return false;
}
if (hasInnerVar() != expr.hasInnerVar()) {
return false;
}
if (hasInnerVar()) {
if (*innerVar_ != *expr.innerVar_) {
return false;
}
}
if (*collection_ != *expr.collection_) {
return false;
}
if (hasFilter() != expr.hasFilter()) {
return false;
}
if (hasFilter()) {
if (*filter_ != *expr.filter_) {
return false;
}
}
return true;
}
std::unique_ptr<Expression> PredicateExpression::clone() const {
auto expr = std::make_unique<PredicateExpression>(
new std::string(*name_),
innerVar_ == nullptr ? nullptr : new std::string(*innerVar_),
collection_->clone().release(),
filter_ != nullptr ? filter_->clone().release() : nullptr);
if (originString_ != nullptr) {
expr->setOriginString(new std::string(*originString_));
}
return expr;
}
void PredicateExpression::writeTo(Encoder& encoder) const {
encoder << kind_;
encoder << Value(hasInnerVar());
encoder << Value(hasFilter());
encoder << Value(hasOriginString());
encoder << name_.get();
if (hasInnerVar()) {
encoder << innerVar_.get();
}
encoder << *collection_;
if (hasFilter()) {
encoder << *filter_;
}
if (hasOriginString()) {
encoder << originString_.get();
}
}
void PredicateExpression::resetFrom(Decoder& decoder) {
bool hasInnerVar = decoder.readValue().getBool();
bool hasFilter = decoder.readValue().getBool();
bool hasString = decoder.readValue().getBool();
name_ = decoder.readStr();
if (hasInnerVar) {
innerVar_ = decoder.readStr();
}
collection_ = decoder.readExpression();
if (hasFilter) {
filter_ = decoder.readExpression();
}
if (hasString) {
originString_ = decoder.readStr();
}
}
std::string PredicateExpression::toString() const {
if (originString_ != nullptr) {
return *originString_;
}
return makeString();
}
std::string PredicateExpression::makeString() const {
std::string buf;
buf.reserve(256);
buf += *name_;
buf += "(";
if (*name_ != "exists") {
buf += *innerVar_;
buf += " IN ";
buf += collection_->toString();
buf += " WHERE ";
buf += filter_->toString();
} else {
buf += collection_->toString();
}
buf += ")";
return buf;
}
void PredicateExpression::accept(ExprVisitor* visitor) {
visitor->visit(this);
}
} // namespace nebula
| 28.381481 | 92 | 0.517813 | linkensphere201 |
3edb23a8859aa4f922f741373da9a0a04c10eb93 | 388 | hpp | C++ | Dialogs/AboutDialog.hpp | rafaelgc/EasyReceipt | c4dae474fff0bba14f0f64ff485e3e3e19a9f399 | [
"MIT"
] | 1 | 2021-07-12T06:36:10.000Z | 2021-07-12T06:36:10.000Z | Dialogs/AboutDialog.hpp | rafaelgc/SplitQt | c4dae474fff0bba14f0f64ff485e3e3e19a9f399 | [
"MIT"
] | null | null | null | Dialogs/AboutDialog.hpp | rafaelgc/SplitQt | c4dae474fff0bba14f0f64ff485e3e3e19a9f399 | [
"MIT"
] | null | null | null | #ifndef ABOUTDIALOG_HPP
#define ABOUTDIALOG_HPP
#include <QDialog>
#include <QDebug>
#include "Version.hpp"
#include "Config.hpp"
#include "ui_aboutform.h"
class AboutDialog : public QDialog
{
Q_OBJECT
private:
Ui::AboutForm *ui;
public:
explicit AboutDialog(Config *config, QWidget *parent = 0);
~AboutDialog();
signals:
public slots:
};
#endif // ABOUTDIALOG_HPP
| 14.37037 | 62 | 0.719072 | rafaelgc |
3edf3e17b9792f3d5c121c17738c73d53346999f | 1,778 | cpp | C++ | programs/C++/infix_to_postfix.cpp | siddhantgore/hacktoberfest | d9b2e0483414d0b124e2c8c7c347aef46683d968 | [
"Apache-2.0"
] | 3 | 2021-10-03T17:03:41.000Z | 2022-02-15T15:18:32.000Z | programs/C++/infix_to_postfix.cpp | siddhantgore/hacktoberfest | d9b2e0483414d0b124e2c8c7c347aef46683d968 | [
"Apache-2.0"
] | 8 | 2021-10-02T14:09:31.000Z | 2021-10-08T07:54:15.000Z | programs/C++/infix_to_postfix.cpp | siddhantgore/hacktoberfest | d9b2e0483414d0b124e2c8c7c347aef46683d968 | [
"Apache-2.0"
] | 25 | 2021-10-02T10:30:12.000Z | 2021-10-10T04:01:56.000Z | #include<iostream>
#define n 100
using namespace std;
class stack
{
public:
char stack_arr[n+1];
int top;
stack(){
top=-1;
}
bool overflow(int top){
if(top==n){
return 1;
}
return 0;
}
bool underflow(){
if(top==-1){
return 1;
}
return 0;
}
void push(char value){
if(overflow(top)){
cout<<"Stack is full. Nothing can be pushed into it."<<endl;
}
else{
top++;
stack_arr[top] = value;
}
}
char pop(){
if(underflow()){
cout<<"Stack is empty, so nothing can be poped."<<endl;
return -1;
}
else{
char temp = stack_arr[top];
top--;
return temp;
}
}
int size(){
return top+1;
}
char top_element(){
char temp = stack_arr[top];
return temp;
}
};
bool isOperator(char ch){
if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='^'||ch=='('){
return 1;
}
return 0;
}
int precedence(char ch)
{
if(ch=='^')return 3;
else if(ch=='*'||ch=='/')return 2;
else if(ch=='+'||ch=='-')return 1;
}
int main(){
stack obj;
string s;
cout<<"Enter infix expression which will then be converted into postfix:";
cin>>s;
string output;
for(int i=0;i<s.length();i++){
if(!isOperator(s[i])){
output.push_back(s[i]);
}
else if(s[i]=='('){
obj.push(s[i]);
}
else if(s[i]==')'){
while(obj.top_element()!='('){
output.push_back(obj.top_element());
obj.pop();
}
obj.pop();
}
else{
if(obj.underflow()){
obj.push(s[i]);
}
else if(precedence(s[i])>precedence(obj.top_element())){
obj.push(s[i]);
}
else if(precedence(s[i])==precedence(obj.top_element())&&s[i]=='^'){
obj.push(s[i]);
}
else{
while(!obj.underflow() && precedence(s[i])<=precedence(obj.top_element())){
output.push_back(obj.top_element());
obj.pop();
}
obj.push(s[i]);
}
}
}
while(!obj.underflow()){
output.push_back(obj.pop());
}
cout<<output<<endl;
return 0;
}
| 15.067797 | 76 | 0.591676 | siddhantgore |
3ee1f4a1030a49307036c3c9967498f36f837073 | 980 | hpp | C++ | QFsm/Front/Operations.hpp | krzysztof-jusiak/qfsm | b339f8bdb7f4d2c65dc943cc84e0e0038552190c | [
"BSL-1.0"
] | 1 | 2020-12-18T20:43:20.000Z | 2020-12-18T20:43:20.000Z | QFsm/Front/Operations.hpp | krzysztof-jusiak/qfsm | b339f8bdb7f4d2c65dc943cc84e0e0038552190c | [
"BSL-1.0"
] | null | null | null | QFsm/Front/Operations.hpp | krzysztof-jusiak/qfsm | b339f8bdb7f4d2c65dc943cc84e0e0038552190c | [
"BSL-1.0"
] | null | null | null | //
// Copyright (c) 2011-2012 Krzysztof Jusiak (krzysztof at jusiak dot net)
//
// 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 QFSM_FRONT_OPERATIONS_HPP
#define QFSM_FRONT_OPERATIONS_HPP
#include "QFsm/Front/Operations/And.hpp"
#include "QFsm/Front/Operations/Bind.hpp"
#include "QFsm/Front/Operations/Defer.hpp"
#include "QFsm/Front/Operations/Else.hpp"
#include "QFsm/Front/Operations/Interrupt.hpp"
#include "QFsm/Front/Operations/IsFinished.hpp"
#include "QFsm/Front/Operations/None.hpp"
#include "QFsm/Front/Operations/Not.hpp"
#include "QFsm/Front/Operations/OnEntry.hpp"
#include "QFsm/Front/Operations/OnExit.hpp"
#include "QFsm/Front/Operations/Or.hpp"
#include "QFsm/Front/Operations/SendInternalEvent.hpp"
#include "QFsm/Front/Operations/Seq.hpp"
#include "QFsm/Front/Operations/Terminate.hpp"
#include "QFsm/Front/Operations/Transition.hpp"
#endif
| 35 | 90 | 0.787755 | krzysztof-jusiak |
3ee2dd0f7a2e43e7858553a1c968c1d5b302cb85 | 1,179 | hpp | C++ | Libraries/Widget/Utility.hpp | RyanTylerRae/WelderEngineRevamp | 3efdad59dd1821ddb1c09b59520e8e2d7023bb10 | [
"MIT"
] | 1 | 2019-07-13T03:36:11.000Z | 2019-07-13T03:36:11.000Z | Libraries/Widget/Utility.hpp | RyanTylerRae/WelderEngineRevamp | 3efdad59dd1821ddb1c09b59520e8e2d7023bb10 | [
"MIT"
] | null | null | null | Libraries/Widget/Utility.hpp | RyanTylerRae/WelderEngineRevamp | 3efdad59dd1821ddb1c09b59520e8e2d7023bb10 | [
"MIT"
] | null | null | null | // MIT Licensed (see LICENSE.md).
#pragma once
namespace Zero
{
class ColorBlock : public Widget
{
public:
ColorBlock(Composite* parent, AttachType::Enum attachType = AttachType::Normal) : Widget(parent, attachType)
{
}
void RenderUpdate(
ViewBlock& viewBlock, FrameBlock& frameBlock, Mat4Param parentTx, ColorTransform colorTx, WidgetRect clipRect)
{
Texture* texture = TextureManager::FindOrNull("White");
if (texture == nullptr)
return;
Widget::RenderUpdate(viewBlock, frameBlock, parentTx, colorTx, clipRect);
Vec4 color = mColor * colorTx.ColorMultiply;
Vec3 pos0 = Vec3(0.0f);
Vec3 pos1 = Vec3(mSize, 0.0f);
Vec2 uv0 = Vec2(0.0f);
Vec2 uv1 = Vec2(1.0f);
ViewNode& viewNode = AddRenderNodes(viewBlock, frameBlock, clipRect, texture);
frameBlock.mRenderQueues->AddStreamedQuad(viewNode, pos0, pos1, uv0, uv1, color);
}
};
inline ColorBlock* CreateBlackOut(Composite* composite, AttachType::Enum attach = AttachType::Normal)
{
ColorBlock* block = new ColorBlock(composite, attach);
block->SetSize(composite->GetSize());
block->SetColor(Vec4(0, 0, 0, 0.8f));
return block;
}
} // namespace Zero | 26.2 | 116 | 0.703986 | RyanTylerRae |
3ee37edb73684a536091234b68cba7c93d402561 | 34,130 | cpp | C++ | src/gromacs/mdrun/rerun.cpp | gromacs/gromacs | 6cea3ac02b633e99167ce572f563368516853349 | [
"BSD-2-Clause"
] | 384 | 2015-01-02T19:44:15.000Z | 2022-03-27T15:13:15.000Z | src/gromacs/mdrun/rerun.cpp | gromacs/gromacs | 6cea3ac02b633e99167ce572f563368516853349 | [
"BSD-2-Clause"
] | 9 | 2015-04-07T20:48:00.000Z | 2022-01-24T21:29:26.000Z | src/gromacs/mdrun/rerun.cpp | gromacs/gromacs | 6cea3ac02b633e99167ce572f563368516853349 | [
"BSD-2-Clause"
] | 258 | 2015-01-19T11:19:57.000Z | 2022-03-18T08:59:52.000Z | /*
* This file is part of the GROMACS molecular simulation package.
*
* Copyright (c) 2018,2019,2020,2021, by the GROMACS development team, led by
* Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
* and including many others, as listed in the AUTHORS file in the
* top-level source directory and at http://www.gromacs.org.
*
* GROMACS is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* GROMACS 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GROMACS; if not, see
* http://www.gnu.org/licenses, or write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* If you want to redistribute modifications to GROMACS, please
* consider that scientific software is very special. Version
* control is crucial - bugs must be traceable. We will be happy to
* consider code for inclusion in the official distribution, but
* derived work must not be called official GROMACS. Details are found
* in the README & COPYING files - if they are missing, get the
* official version at http://www.gromacs.org.
*
* To help us fund GROMACS development, we humbly ask that you cite
* the research papers on the package. Check out http://www.gromacs.org.
*/
/*! \internal \file
*
* \brief Implements the loop for simulation reruns
*
* \author Pascal Merz <pascal.merz@colorado.edu>
* \ingroup module_mdrun
*/
#include "gmxpre.h"
#include <cinttypes>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <memory>
#include "gromacs/applied_forces/awh/awh.h"
#include "gromacs/commandline/filenm.h"
#include "gromacs/domdec/collect.h"
#include "gromacs/domdec/dlbtiming.h"
#include "gromacs/domdec/domdec.h"
#include "gromacs/domdec/domdec_network.h"
#include "gromacs/domdec/domdec_struct.h"
#include "gromacs/domdec/localtopologychecker.h"
#include "gromacs/domdec/mdsetup.h"
#include "gromacs/domdec/partition.h"
#include "gromacs/essentialdynamics/edsam.h"
#include "gromacs/ewald/pme_load_balancing.h"
#include "gromacs/ewald/pme_pp.h"
#include "gromacs/fileio/trxio.h"
#include "gromacs/gmxlib/network.h"
#include "gromacs/gmxlib/nrnb.h"
#include "gromacs/gpu_utils/gpu_utils.h"
#include "gromacs/listed_forces/listed_forces.h"
#include "gromacs/math/functions.h"
#include "gromacs/math/utilities.h"
#include "gromacs/math/vec.h"
#include "gromacs/math/vectypes.h"
#include "gromacs/mdlib/checkpointhandler.h"
#include "gromacs/mdlib/compute_io.h"
#include "gromacs/mdlib/constr.h"
#include "gromacs/mdlib/ebin.h"
#include "gromacs/mdlib/enerdata_utils.h"
#include "gromacs/mdlib/energyoutput.h"
#include "gromacs/mdlib/expanded.h"
#include "gromacs/mdlib/force.h"
#include "gromacs/mdlib/force_flags.h"
#include "gromacs/mdlib/forcerec.h"
#include "gromacs/mdlib/freeenergyparameters.h"
#include "gromacs/mdlib/md_support.h"
#include "gromacs/mdlib/mdatoms.h"
#include "gromacs/mdlib/mdoutf.h"
#include "gromacs/mdlib/membed.h"
#include "gromacs/mdlib/resethandler.h"
#include "gromacs/mdlib/sighandler.h"
#include "gromacs/mdlib/simulationsignal.h"
#include "gromacs/mdlib/stat.h"
#include "gromacs/mdlib/stophandler.h"
#include "gromacs/mdlib/tgroup.h"
#include "gromacs/mdlib/trajectory_writing.h"
#include "gromacs/mdlib/update.h"
#include "gromacs/mdlib/vcm.h"
#include "gromacs/mdlib/vsite.h"
#include "gromacs/mdrunutility/handlerestart.h"
#include "gromacs/mdrunutility/multisim.h"
#include "gromacs/mdrunutility/printtime.h"
#include "gromacs/mdtypes/awh_history.h"
#include "gromacs/mdtypes/awh_params.h"
#include "gromacs/mdtypes/commrec.h"
#include "gromacs/mdtypes/df_history.h"
#include "gromacs/mdtypes/energyhistory.h"
#include "gromacs/mdtypes/forcebuffers.h"
#include "gromacs/mdtypes/forcerec.h"
#include "gromacs/mdtypes/group.h"
#include "gromacs/mdtypes/inputrec.h"
#include "gromacs/mdtypes/interaction_const.h"
#include "gromacs/mdtypes/md_enums.h"
#include "gromacs/mdtypes/mdatom.h"
#include "gromacs/mdtypes/mdrunoptions.h"
#include "gromacs/mdtypes/observableshistory.h"
#include "gromacs/mdtypes/observablesreducer.h"
#include "gromacs/mdtypes/simulation_workload.h"
#include "gromacs/mdtypes/state.h"
#include "gromacs/mimic/utilities.h"
#include "gromacs/pbcutil/pbc.h"
#include "gromacs/pulling/output.h"
#include "gromacs/pulling/pull.h"
#include "gromacs/swap/swapcoords.h"
#include "gromacs/timing/wallcycle.h"
#include "gromacs/timing/walltime_accounting.h"
#include "gromacs/topology/atoms.h"
#include "gromacs/topology/idef.h"
#include "gromacs/topology/mtop_util.h"
#include "gromacs/topology/topology.h"
#include "gromacs/trajectory/trajectoryframe.h"
#include "gromacs/utility/basedefinitions.h"
#include "gromacs/utility/cstringutil.h"
#include "gromacs/utility/fatalerror.h"
#include "gromacs/utility/logger.h"
#include "gromacs/utility/real.h"
#include "legacysimulator.h"
#include "replicaexchange.h"
#include "shellfc.h"
using gmx::SimulationSignaller;
using gmx::VirtualSitesHandler;
/*! \brief Copy the state from \p rerunFrame to \p globalState and, if requested, construct vsites
*
* \param[in] rerunFrame The trajectory frame to compute energy/forces for
* \param[in,out] globalState The global state container
* \param[in] constructVsites When true, vsite coordinates are constructed
* \param[in] vsite Vsite setup, can be nullptr when \p constructVsites = false
*/
static void prepareRerunState(const t_trxframe& rerunFrame,
t_state* globalState,
bool constructVsites,
const VirtualSitesHandler* vsite)
{
auto x = makeArrayRef(globalState->x);
auto rerunX = arrayRefFromArray(reinterpret_cast<gmx::RVec*>(rerunFrame.x), globalState->natoms);
std::copy(rerunX.begin(), rerunX.end(), x.begin());
copy_mat(rerunFrame.box, globalState->box);
if (constructVsites)
{
GMX_ASSERT(vsite, "Need valid vsite for constructing vsites");
vsite->construct(globalState->x, globalState->v, globalState->box, gmx::VSiteOperation::PositionsAndVelocities);
}
}
void gmx::LegacySimulator::do_rerun()
{
// TODO Historically, the EM and MD "integrators" used different
// names for the t_inputrec *parameter, but these must have the
// same name, now that it's a member of a struct. We use this ir
// alias to avoid a large ripple of nearly useless changes.
// t_inputrec is being replaced by IMdpOptionsProvider, so this
// will go away eventually.
const t_inputrec* ir = inputrec;
double t;
bool isLastStep = false;
bool doFreeEnergyPerturbation = false;
unsigned int force_flags;
tensor force_vir, shake_vir, total_vir, pres;
t_trxstatus* status = nullptr;
rvec mu_tot;
t_trxframe rerun_fr;
ForceBuffers f;
gmx_global_stat_t gstat;
gmx_shellfc_t* shellfc;
double cycles;
SimulationSignals signals;
// Most global communnication stages don't propagate mdrun
// signals, and will use this object to achieve that.
SimulationSignaller nullSignaller(nullptr, nullptr, nullptr, false, false);
GMX_LOG(mdlog.info)
.asParagraph()
.appendText(
"Note that it is planned that the command gmx mdrun -rerun will "
"be available in a different form in a future version of GROMACS, "
"e.g. gmx rerun -f.");
if (ir->efep != FreeEnergyPerturbationType::No
&& (mdAtoms->mdatoms()->nMassPerturbed > 0 || (constr && constr->havePerturbedConstraints())))
{
gmx_fatal(FARGS,
"Perturbed masses or constraints are not supported by rerun. "
"Either make a .tpr without mass and constraint perturbation, "
"or use GROMACS 2018.4, 2018.5 or later 2018 version.");
}
if (ir->bExpanded)
{
gmx_fatal(FARGS, "Expanded ensemble not supported by rerun.");
}
if (ir->bSimTemp)
{
gmx_fatal(FARGS, "Simulated tempering not supported by rerun.");
}
if (ir->bDoAwh)
{
gmx_fatal(FARGS, "AWH not supported by rerun.");
}
if (replExParams.exchangeInterval > 0)
{
gmx_fatal(FARGS, "Replica exchange not supported by rerun.");
}
if (opt2bSet("-ei", nfile, fnm) || observablesHistory->edsamHistory != nullptr)
{
gmx_fatal(FARGS, "Essential dynamics not supported by rerun.");
}
if (ir->bIMD)
{
gmx_fatal(FARGS, "Interactive MD not supported by rerun.");
}
if (isMultiSim(ms))
{
gmx_fatal(FARGS, "Multiple simulations not supported by rerun.");
}
if (std::any_of(ir->opts.annealing, ir->opts.annealing + ir->opts.ngtc, [](SimulatedAnnealing i) {
return i != SimulatedAnnealing::No;
}))
{
gmx_fatal(FARGS, "Simulated annealing not supported by rerun.");
}
/* Rerun can't work if an output file name is the same as the input file name.
* If this is the case, the user will get an error telling them what the issue is.
*/
if (strcmp(opt2fn("-rerun", nfile, fnm), opt2fn("-o", nfile, fnm)) == 0
|| strcmp(opt2fn("-rerun", nfile, fnm), opt2fn("-x", nfile, fnm)) == 0)
{
gmx_fatal(FARGS,
"When using mdrun -rerun, the name of the input trajectory file "
"%s cannot be identical to the name of an output file (whether "
"given explicitly with -o or -x, or by default)",
opt2fn("-rerun", nfile, fnm));
}
/* Settings for rerun */
{
// TODO: Avoid changing inputrec (#3854)
auto* nonConstInputrec = const_cast<t_inputrec*>(inputrec);
nonConstInputrec->nstlist = 1;
nonConstInputrec->nstcalcenergy = 1;
nonConstInputrec->nstxout_compressed = 0;
}
int nstglobalcomm = 1;
const bool bNS = true;
ObservablesReducer observablesReducer = observablesReducerBuilder->build();
const SimulationGroups* groups = &top_global.groups;
if (ir->eI == IntegrationAlgorithm::Mimic)
{
auto* nonConstGlobalTopology = const_cast<gmx_mtop_t*>(&top_global);
nonConstGlobalTopology->intermolecularExclusionGroup = genQmmmIndices(top_global);
}
int* fep_state = MASTER(cr) ? &state_global->fep_state : nullptr;
gmx::ArrayRef<real> lambda = MASTER(cr) ? state_global->lambda : gmx::ArrayRef<real>();
initialize_lambdas(fplog,
ir->efep,
ir->bSimTemp,
*ir->fepvals,
ir->simtempvals->temperatures,
gmx::arrayRefFromArray(ir->opts.ref_t, ir->opts.ngtc),
MASTER(cr),
fep_state,
lambda);
const bool simulationsShareState = false;
gmx_mdoutf* outf = init_mdoutf(fplog,
nfile,
fnm,
mdrunOptions,
cr,
outputProvider,
mdModulesNotifiers,
ir,
top_global,
oenv,
wcycle,
StartingBehavior::NewSimulation,
simulationsShareState,
ms);
gmx::EnergyOutput energyOutput(mdoutf_get_fp_ene(outf),
top_global,
*ir,
pull_work,
mdoutf_get_fp_dhdl(outf),
true,
StartingBehavior::NewSimulation,
simulationsShareState,
mdModulesNotifiers);
gstat = global_stat_init(ir);
/* Check for polarizable models and flexible constraints */
shellfc = init_shell_flexcon(fplog,
top_global,
constr ? constr->numFlexibleConstraints() : 0,
ir->nstcalcenergy,
haveDDAtomOrdering(*cr),
runScheduleWork->simulationWork.useGpuPme);
{
double io = compute_io(ir, top_global.natoms, *groups, energyOutput.numEnergyTerms(), 1);
if ((io > 2000) && MASTER(cr))
{
fprintf(stderr, "\nWARNING: This run will generate roughly %.0f Mb of data\n\n", io);
}
}
if (haveDDAtomOrdering(*cr))
{
// Local state only becomes valid now.
dd_init_local_state(*cr->dd, state_global, state);
/* Distribute the charge groups over the nodes from the master node */
dd_partition_system(fplog,
mdlog,
ir->init_step,
cr,
TRUE,
1,
state_global,
top_global,
*ir,
imdSession,
pull_work,
state,
&f,
mdAtoms,
top,
fr,
vsite,
constr,
nrnb,
nullptr,
FALSE);
}
else
{
state_change_natoms(state_global, state_global->natoms);
/* Copy the pointer to the global state */
state = state_global;
mdAlgorithmsSetupAtomData(cr, *ir, top_global, top, fr, &f, mdAtoms, constr, vsite, shellfc);
}
auto* mdatoms = mdAtoms->mdatoms();
fr->longRangeNonbondeds->updateAfterPartition(*mdatoms);
// NOTE: The global state is no longer used at this point.
// But state_global is still used as temporary storage space for writing
// the global state to file and potentially for replica exchange.
// (Global topology should persist.)
update_mdatoms(mdatoms, state->lambda[FreeEnergyPerturbationCouplingType::Mass]);
if (ir->efep != FreeEnergyPerturbationType::No && ir->fepvals->nstdhdl != 0)
{
doFreeEnergyPerturbation = true;
}
int64_t step = ir->init_step;
int64_t step_rel = 0;
{
int cglo_flags = CGLO_GSTAT;
bool bSumEkinhOld = false;
t_vcm* vcm = nullptr;
compute_globals(gstat,
cr,
ir,
fr,
ekind,
makeConstArrayRef(state->x),
makeConstArrayRef(state->v),
state->box,
mdatoms,
nrnb,
vcm,
nullptr,
enerd,
force_vir,
shake_vir,
total_vir,
pres,
&nullSignaller,
state->box,
&bSumEkinhOld,
cglo_flags,
step,
&observablesReducer);
// Clean up after pre-step use of compute_globals()
observablesReducer.markAsReadyToReduce();
}
if (MASTER(cr))
{
fprintf(stderr,
"starting md rerun '%s', reading coordinates from"
" input trajectory '%s'\n\n",
*(top_global.name),
opt2fn("-rerun", nfile, fnm));
if (mdrunOptions.verbose)
{
fprintf(stderr,
"Calculated time to finish depends on nsteps from "
"run input file,\nwhich may not correspond to the time "
"needed to process input trajectory.\n\n");
}
fprintf(fplog, "\n");
}
walltime_accounting_start_time(walltime_accounting);
wallcycle_start(wcycle, WallCycleCounter::Run);
print_start(fplog, cr, walltime_accounting, "mdrun");
/***********************************************************
*
* Loop over MD steps
*
************************************************************/
if (constr)
{
GMX_LOG(mdlog.info)
.asParagraph()
.appendText("Simulations has constraints. Rerun does not recalculate constraints.");
}
rerun_fr.natoms = 0;
if (MASTER(cr))
{
isLastStep = !read_first_frame(oenv, &status, opt2fn("-rerun", nfile, fnm), &rerun_fr, TRX_NEED_X);
if (rerun_fr.natoms != top_global.natoms)
{
gmx_fatal(FARGS,
"Number of atoms in trajectory (%d) does not match the "
"run input file (%d)\n",
rerun_fr.natoms,
top_global.natoms);
}
if (ir->pbcType != PbcType::No)
{
if (!rerun_fr.bBox)
{
gmx_fatal(FARGS,
"Rerun trajectory frame step %" PRId64
" time %f "
"does not contain a box, while pbc is used",
rerun_fr.step,
rerun_fr.time);
}
if (max_cutoff2(ir->pbcType, rerun_fr.box) < gmx::square(fr->rlist))
{
gmx_fatal(FARGS,
"Rerun trajectory frame step %" PRId64
" time %f "
"has too small box dimensions",
rerun_fr.step,
rerun_fr.time);
}
}
}
GMX_LOG(mdlog.info)
.asParagraph()
.appendText(
"Rerun does not report kinetic energy, total energy, temperature, virial and "
"pressure.");
if (PAR(cr))
{
rerun_parallel_comm(cr, &rerun_fr, &isLastStep);
}
if (ir->pbcType != PbcType::No)
{
/* Set the shift vectors.
* Necessary here when have a static box different from the tpr box.
*/
calc_shifts(rerun_fr.box, fr->shift_vec);
}
auto stopHandler = stopHandlerBuilder->getStopHandlerMD(
compat::not_null<SimulationSignal*>(&signals[eglsSTOPCOND]),
false,
MASTER(cr),
ir->nstlist,
mdrunOptions.reproducible,
nstglobalcomm,
mdrunOptions.maximumHoursToRun,
ir->nstlist == 0,
fplog,
step,
bNS,
walltime_accounting);
// we don't do counter resetting in rerun - finish will always be valid
walltime_accounting_set_valid_finish(walltime_accounting);
const DDBalanceRegionHandler ddBalanceRegionHandler(cr);
/* and stop now if we should */
isLastStep = (isLastStep || (ir->nsteps >= 0 && step_rel > ir->nsteps));
while (!isLastStep)
{
wallcycle_start(wcycle, WallCycleCounter::Step);
if (rerun_fr.bStep)
{
step = rerun_fr.step;
step_rel = step - ir->init_step;
}
if (rerun_fr.bTime)
{
t = rerun_fr.time;
}
else
{
t = step;
}
if (ir->efep != FreeEnergyPerturbationType::No && MASTER(cr))
{
if (rerun_fr.bLambda)
{
ir->fepvals->init_lambda = rerun_fr.lambda;
}
else
{
if (rerun_fr.bFepState)
{
state->fep_state = rerun_fr.fep_state;
}
}
state_global->lambda = currentLambdas(step, *(ir->fepvals), state->fep_state);
}
if (MASTER(cr))
{
const bool constructVsites = ((vsite != nullptr) && mdrunOptions.rerunConstructVsites);
if (constructVsites && haveDDAtomOrdering(*cr))
{
gmx_fatal(FARGS,
"Vsite recalculation with -rerun is not implemented with domain "
"decomposition, "
"use a single rank");
}
prepareRerunState(rerun_fr, state_global, constructVsites, vsite);
}
isLastStep = isLastStep || stopHandler->stoppingAfterCurrentStep(bNS);
if (haveDDAtomOrdering(*cr))
{
/* Repartition the domain decomposition */
const bool bMasterState = true;
dd_partition_system(fplog,
mdlog,
step,
cr,
bMasterState,
nstglobalcomm,
state_global,
top_global,
*ir,
imdSession,
pull_work,
state,
&f,
mdAtoms,
top,
fr,
vsite,
constr,
nrnb,
wcycle,
mdrunOptions.verbose);
}
if (MASTER(cr))
{
EnergyOutput::printHeader(fplog, step, t); /* can we improve the information printed here? */
}
if (ir->efep != FreeEnergyPerturbationType::No)
{
update_mdatoms(mdatoms, state->lambda[FreeEnergyPerturbationCouplingType::Mass]);
}
fr->longRangeNonbondeds->updateAfterPartition(*mdatoms);
force_flags = (GMX_FORCE_STATECHANGED | GMX_FORCE_DYNAMICBOX | GMX_FORCE_ALLFORCES
| GMX_FORCE_VIRIAL | // TODO: Get rid of this once #2649 and #3400 are solved
GMX_FORCE_ENERGY | (doFreeEnergyPerturbation ? GMX_FORCE_DHDL : 0));
if (shellfc)
{
/* Now is the time to relax the shells */
relax_shell_flexcon(fplog,
cr,
ms,
mdrunOptions.verbose,
enforcedRotation,
step,
ir,
imdSession,
pull_work,
bNS,
force_flags,
top,
constr,
enerd,
state->natoms,
state->x.arrayRefWithPadding(),
state->v.arrayRefWithPadding(),
state->box,
state->lambda,
&state->hist,
&f.view(),
force_vir,
*mdatoms,
fr->longRangeNonbondeds.get(),
nrnb,
wcycle,
shellfc,
fr,
runScheduleWork,
t,
mu_tot,
vsite,
ddBalanceRegionHandler);
}
else
{
/* The coordinates (x) are shifted (to get whole molecules)
* in do_force.
* This is parallellized as well, and does communication too.
* Check comments in sim_util.c
*/
Awh* awh = nullptr;
gmx_edsam* ed = nullptr;
do_force(fplog,
cr,
ms,
*ir,
awh,
enforcedRotation,
imdSession,
pull_work,
step,
nrnb,
wcycle,
top,
state->box,
state->x.arrayRefWithPadding(),
&state->hist,
&f.view(),
force_vir,
mdatoms,
enerd,
state->lambda,
fr,
runScheduleWork,
vsite,
mu_tot,
t,
ed,
fr->longRangeNonbondeds.get(),
GMX_FORCE_NS | force_flags,
ddBalanceRegionHandler);
}
/* Now we have the energies and forces corresponding to the
* coordinates at time t.
*/
{
const bool isCheckpointingStep = false;
const bool doRerun = true;
const bool bSumEkinhOld = false;
do_md_trajectory_writing(fplog,
cr,
nfile,
fnm,
step,
step_rel,
t,
ir,
state,
state_global,
observablesHistory,
top_global,
fr,
outf,
energyOutput,
ekind,
f.view().force(),
isCheckpointingStep,
doRerun,
isLastStep,
mdrunOptions.writeConfout,
bSumEkinhOld);
}
stopHandler->setSignal();
{
const bool doInterSimSignal = false;
const bool doIntraSimSignal = true;
bool bSumEkinhOld = false;
t_vcm* vcm = nullptr;
SimulationSignaller signaller(&signals, cr, ms, doInterSimSignal, doIntraSimSignal);
int cglo_flags = CGLO_GSTAT | CGLO_ENERGY;
compute_globals(gstat,
cr,
ir,
fr,
ekind,
makeConstArrayRef(state->x),
makeConstArrayRef(state->v),
state->box,
mdatoms,
nrnb,
vcm,
wcycle,
enerd,
force_vir,
shake_vir,
total_vir,
pres,
&signaller,
state->box,
&bSumEkinhOld,
cglo_flags,
step,
&observablesReducer);
// Clean up after pre-step use of compute_globals()
observablesReducer.markAsReadyToReduce();
}
/* Note: this is OK, but there are some numerical precision issues with using the convergence of
the virial that should probably be addressed eventually. state->veta has better properies,
but what we actually need entering the new cycle is the new shake_vir value. Ideally, we could
generate the new shake_vir, but test the veta value for convergence. This will take some thought. */
/* Output stuff */
if (MASTER(cr))
{
const bool bCalcEnerStep = true;
energyOutput.addDataAtEnergyStep(doFreeEnergyPerturbation,
bCalcEnerStep,
t,
mdatoms->tmass,
enerd,
ir->fepvals.get(),
ir->expandedvals.get(),
state->box,
PTCouplingArrays({ state->boxv,
state->nosehoover_xi,
state->nosehoover_vxi,
state->nhpres_xi,
state->nhpres_vxi }),
state->fep_state,
total_vir,
pres,
ekind,
mu_tot,
constr);
const bool do_ene = true;
const bool do_log = true;
Awh* awh = nullptr;
const bool do_dr = ir->nstdisreout != 0;
const bool do_or = ir->nstorireout != 0;
EnergyOutput::printAnnealingTemperatures(do_log ? fplog : nullptr, groups, &(ir->opts));
energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf),
do_ene,
do_dr,
do_or,
do_log ? fplog : nullptr,
step,
t,
fr->fcdata.get(),
awh);
if (ir->bPull)
{
pull_print_output(pull_work, step, t);
}
if (do_per_step(step, ir->nstlog))
{
if (fflush(fplog) != 0)
{
gmx_fatal(FARGS, "Cannot flush logfile - maybe you are out of disk space?");
}
}
}
/* Print the remaining wall clock time for the run */
if (isMasterSimMasterRank(ms, MASTER(cr)) && (mdrunOptions.verbose || gmx_got_usr_signal()))
{
if (shellfc)
{
fprintf(stderr, "\n");
}
print_time(stderr, walltime_accounting, step, ir, cr);
}
/* Ion/water position swapping.
* Not done in last step since trajectory writing happens before this call
* in the MD loop and exchanges would be lost anyway. */
if ((ir->eSwapCoords != SwapType::No) && (step > 0) && !isLastStep
&& do_per_step(step, ir->swap->nstswap))
{
const bool doRerun = true;
do_swapcoords(cr,
step,
t,
ir,
swap,
wcycle,
rerun_fr.x,
rerun_fr.box,
MASTER(cr) && mdrunOptions.verbose,
doRerun);
}
if (MASTER(cr))
{
/* read next frame from input trajectory */
isLastStep = !read_next_frame(oenv, status, &rerun_fr);
}
if (PAR(cr))
{
rerun_parallel_comm(cr, &rerun_fr, &isLastStep);
}
cycles = wallcycle_stop(wcycle, WallCycleCounter::Step);
if (haveDDAtomOrdering(*cr) && wcycle)
{
dd_cycles_add(cr->dd, cycles, ddCyclStep);
}
if (!rerun_fr.bStep)
{
/* increase the MD step number */
step++;
step_rel++;
}
observablesReducer.markAsReadyToReduce();
}
/* End of main MD loop */
/* Closing TNG files can include compressing data. Therefore it is good to do that
* before stopping the time measurements. */
mdoutf_tng_close(outf);
/* Stop measuring walltime */
walltime_accounting_end_time(walltime_accounting);
if (MASTER(cr))
{
close_trx(status);
}
if (!thisRankHasDuty(cr, DUTY_PME))
{
/* Tell the PME only node to finish */
gmx_pme_send_finish(cr);
}
done_mdoutf(outf);
done_shellfc(fplog, shellfc, step_rel);
walltime_accounting_set_nsteps_done(walltime_accounting, step_rel);
}
| 37.629548 | 120 | 0.48995 | gromacs |
3ee3a709218539929cfdca64e5c12cb8997f0fae | 9,360 | cpp | C++ | src/cpp/DatasetBuilder.cpp | aflorio81/Amazon-MIT-RoutingChallenge | cbacc7b62a41b81c3e4b9ffde0f8dea0f81d3f5a | [
"Apache-2.0"
] | 3 | 2022-03-24T20:56:52.000Z | 2022-03-28T22:55:18.000Z | src/cpp/DatasetBuilder.cpp | aflorio81/Amazon-MIT-RoutingChallenge | cbacc7b62a41b81c3e4b9ffde0f8dea0f81d3f5a | [
"Apache-2.0"
] | null | null | null | src/cpp/DatasetBuilder.cpp | aflorio81/Amazon-MIT-RoutingChallenge | cbacc7b62a41b81c3e4b9ffde0f8dea0f81d3f5a | [
"Apache-2.0"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <random>
#include "DatasetBuilder.h"
#include "JSONParser.h"
using namespace std;
using namespace rapidjson;
DatasetBuilder::DatasetBuilder(const string& actualseqs,
const string& invalidseqscrs, const string& packagedata,
const string& routedata, const string& traveltimes,
const string& newactualseqs, const string& newinvalidseqscrs,
const string& newpackagedata, const string& newroutedata,
const string& newtraveltimes) {
cout<<"loading original dataset ..."<<endl;
actualseqsdom=JSONParser::parse(actualseqs);
invalidseqscrsdom=JSONParser::parse(invalidseqscrs);
routedatadom=JSONParser::parse(routedata);
packagedatadom=JSONParser::parse(packagedata);
traveltimesdom=JSONParser::parse(traveltimes);
/*
// load existing validation data
newactualseqsdom=JSONParser::parse(newactualseqs);
newinvalidseqscrsdom=JSONParser::parse(newinvalidseqscrs);
newroutedatadom=JSONParser::parse(newroutedata);
newpackagedatadom=JSONParser::parse(newpackagedata);
newtraveltimesdom=JSONParser::parse(newtraveltimes);
*/
// this will overwrite existing validation data
newactualseqsdom.Parse("{}");
newinvalidseqscrsdom.Parse("{}");
newroutedatadom.Parse("{}");
newpackagedatadom.Parse("{}");
newtraveltimesdom.Parse("{}");
}
void DatasetBuilder::convertToValidation() {
// select initially all high score routes
auto routes=highScoreRoutes();
cout<<routes.size()<<" high scores routes"<<endl;
// stratified route sampling based on macro zones
auto tomove=sampleRoutes(routes, 3, 0.10);
cout<<tomove.size()<<" routes sampled to move to validation set"<<endl;
// update DOMs accordingly
updateActualSeqs(tomove);
updateInvalidSeqScores(tomove);
updateRouteData(tomove);
updatePackageData(tomove);
updateTravelTimes(tomove);
}
vector<TrainingRoute> DatasetBuilder::highScoreRoutes() const {
vector<TrainingRoute> routes;
for (const auto& route : routedatadom.GetObject()) {
TrainingRoute rt(route.name.GetString());
const auto& routeinfo=route.value;
rt.setScore(routeinfo["route_score"].GetString());
if (rt.score()!=TrainingRoute::Score::high)
continue;
rt.setStation(routeinfo["station_code"].GetString());
for (const auto& stop : routeinfo["stops"].GetObject()) {
rt.addStop(stop.name.GetString());
Stop& st=rt.getStop(stop.name.GetString());
const auto& stopinfo=stop.value;
st.setType(stopinfo["type"].GetString());
if (stopinfo["zone_id"].IsString())
st.setNanoZone(rt.station()+":"
+stopinfo["zone_id"].GetString());
}
routes.push_back(move(rt));
}
return routes;
}
vector<string> DatasetBuilder::sampleHighScoreRoutes(
const unordered_map<string, TrainingRoute>& routes, size_t thresh,
double prop) {
vector<TrainingRoute> high;
for (const auto& kv : routes)
if (kv.second.score()==TrainingRoute::Score::high)
high.push_back(kv.second);
return sampleRoutes(high, thresh, prop);
}
vector<pair<string, int>> DatasetBuilder::sampleHighScoreRoutes(
const unordered_map<string, TrainingRoute>& routes, size_t thresh,
double prop, double cv_ratio) {
vector<TrainingRoute> high;
for (const auto& kv : routes)
if (kv.second.score()==TrainingRoute::Score::high)
high.push_back(kv.second);
return sampleRoutes(high, thresh, prop, cv_ratio);
}
vector<string> DatasetBuilder::sampleRoutes(
const vector<TrainingRoute>& routes, size_t thresh, double prop) {
// organize routes by macro zones
unordered_map<string, vector<string>> map;
for (const auto& r : routes)
map[r.mainMacroZone()].push_back(r.id());
// shuffle all route ids within each macro zone bucket
random_device rd;
mt19937 g(rd());
for (auto& kv : map)
shuffle(kv.second.begin(), kv.second.end(), g);
unordered_map<string, vector<string>> tomove;
vector<string> sampled_ids;
for (const auto& kv : map)
if (kv.second.size()>=thresh) {
size_t n=max(1ul, (size_t)(prop*kv.second.size()+0.5));
for (size_t i=0; i<n; ++i) {
tomove[kv.first].push_back(kv.second[i]);
sampled_ids.push_back(kv.second[i]);
}
}
for (const auto& kv : map)
cout<<kv.first<<": "<<tomove[kv.first].size()<<"/"<<kv.second.size()
<<endl;
return sampled_ids;
}
vector<pair<string, int>> DatasetBuilder::sampleRoutes(
const vector<TrainingRoute>& routes, size_t thresh, double prop,
double cv_ratio) {
// organize routes by macro zones
unordered_map<string, vector<string>> map;
for (const auto& r : routes)
map[r.mainMacroZone()].push_back(r.id());
// shuffle all route ids within each macro zone bucket
random_device rd;
mt19937 g(rd());
for (auto& kv : map)
shuffle(kv.second.begin(), kv.second.end(), g);
unordered_map<string, vector<string>> tomove;
vector<pair<string, int>> sampled_ids;
const size_t cv_int=1/cv_ratio+0.5;
cout<<"reserving 1 every "<<cv_int<<" routes to cross-validation"<<endl;
size_t k=0;
for (const auto& kv : map)
if (kv.second.size()>=thresh) {
const size_t n=max(1ul, (size_t)(prop*kv.second.size()+0.5));
for (size_t i=0; i<n&&i<kv.second.size(); ++i) {
tomove[kv.first].push_back(kv.second[i]);
sampled_ids.push_back({kv.second[i], k++%cv_int==0?1:0});
}
}
for (const auto& kv : map)
cout<<kv.first<<": "<<tomove[kv.first].size()<<"/"<<kv.second.size()
<<endl;
return sampled_ids;
}
void DatasetBuilder::saveDataset(const string& actualseqs,
const string& invalidseqscrs, const string& packagedata,
const string& routedata, const string& traveltimes,
const string& newactualseqs, const string& newinvalidseqscrs,
const string& newpackagedata, const string& newroutedata,
const string& newtraveltimes) const {
cout<<"saving development dataset ..."<<endl;
JSONParser::save(actualseqsdom, actualseqs);
JSONParser::save(invalidseqscrsdom, invalidseqscrs);
JSONParser::save(routedatadom, routedata);
JSONParser::save(packagedatadom, packagedata);
JSONParser::save(traveltimesdom, traveltimes);
JSONParser::save(newactualseqsdom, newactualseqs);
JSONParser::save(newinvalidseqscrsdom, newinvalidseqscrs);
JSONParser::save(newroutedatadom, newroutedata);
JSONParser::save(newpackagedatadom, newpackagedata);
JSONParser::save(newtraveltimesdom, newtraveltimes);
}
void DatasetBuilder::updateActualSeqs(const vector<string>& tomove) {
for (const auto& id : tomove) {
Value v(id.c_str(), newactualseqsdom.GetAllocator());
newactualseqsdom.AddMember(v.Move(), actualseqsdom[id.c_str()],
newactualseqsdom.GetAllocator());
actualseqsdom.RemoveMember(id.c_str());
}
}
void DatasetBuilder::updateInvalidSeqScores(const vector<string>& tomove) {
for (const auto& id : tomove) {
Value v(id.c_str(), newinvalidseqscrsdom.GetAllocator());
newinvalidseqscrsdom.AddMember(v.Move(), invalidseqscrsdom[id.c_str()],
newinvalidseqscrsdom.GetAllocator());
invalidseqscrsdom.RemoveMember(id.c_str());
}
}
void DatasetBuilder::updatePackageData(const vector<string>& tomove) {
// first we remove 'scan_status' from the (originally) training data
for (const auto& id : tomove) {
auto& r=packagedatadom[id.c_str()];
for (auto it_stop=r.MemberBegin(); it_stop!=r.MemberEnd(); ++it_stop) {
auto& packs=it_stop->value;
for (auto it_p=packs.MemberBegin(); it_p!=packs.MemberEnd(); ++it_p)
it_p->value.RemoveMember("scan_status");
}
}
// decided not to remove duplicated packages
// now we just move as usual
for (const auto& id : tomove) {
Value v(id.c_str(), newpackagedatadom.GetAllocator());
newpackagedatadom.AddMember(v.Move(), packagedatadom[id.c_str()],
newpackagedatadom.GetAllocator());
packagedatadom.RemoveMember(id.c_str());
}
}
void DatasetBuilder::updateRouteData(const vector<string>& tomove) {
// first we remove 'route_score' from the (originally) training data
for (const auto& id : tomove)
routedatadom[id.c_str()].RemoveMember("route_score");
// now we just move as usual
for (const auto& id : tomove) {
Value v(id.c_str(), newroutedatadom.GetAllocator());
newroutedatadom.AddMember(v.Move(), routedatadom[id.c_str()],
newroutedatadom.GetAllocator());
routedatadom.RemoveMember(id.c_str());
}
}
void DatasetBuilder::updateTravelTimes(const vector<string>& tomove) {
for (const auto& id : tomove) {
Value v(id.c_str(), newtraveltimesdom.GetAllocator());
newtraveltimesdom.AddMember(v.Move(), traveltimesdom[id.c_str()],
newtraveltimesdom.GetAllocator());
traveltimesdom.RemoveMember(id.c_str());
}
}
| 40.171674 | 80 | 0.657799 | aflorio81 |
3ee8adbd50ddb5ad2ef4b81a7f715c3fee353540 | 44,101 | cpp | C++ | glib-adv/nmobj.cpp | ksemer/snap | 0084126c30ad49a4437bc8ea30be78484f8c58d7 | [
"BSD-3-Clause"
] | 1,805 | 2015-01-06T20:01:35.000Z | 2022-03-29T16:12:51.000Z | glib-adv/nmobj.cpp | lizhaoqing/snap | 907c34aac6bcddc7c2f8efb64be76e87dd7e4ea5 | [
"BSD-3-Clause"
] | 168 | 2015-01-07T22:57:29.000Z | 2022-03-15T01:20:24.000Z | glib-adv/nmobj.cpp | lizhaoqing/snap | 907c34aac6bcddc7c2f8efb64be76e87dd7e4ea5 | [
"BSD-3-Clause"
] | 768 | 2015-01-09T02:28:45.000Z | 2022-03-30T00:53:46.000Z | /////////////////////////////////////////////////
// Includes
#include "nmobj.h"
/////////////////////////////////////////////////
// Named-Objects
TNmObjBs::TNmObjBs(
const TSwSetType& SwSetType, const PSIn& CustSwSetSIn,
const PSIn& NrWordBsSIn, const PSIn& WordTypeBsSIn, const TStr& MteFNm):
ChDef(),
WordStrToNrH(),
WordStrVToNmObjAttrSetH(),
NmObjWordStrVToNrH(),
NmObjWordStrVToDocIdVH(),
DocNmToNmObjDocH(){
// get character set
ChDef=THtmlLxChDef::GetChDef();
// standard-stopwords
SwSet=TSwSet::GetSwSet(SwSetType);
// custom-stopwords
LoadCustSwSet(CustSwSetSIn);
// load word normalizations
LoadNrWordBs(NrWordBsSIn);
// load phrase aliases & types
LoadNmObjTypeBs(WordTypeBsSIn);
// load MulTextEast
if (!MteFNm.Empty()){
/*MteLex=TMteLex::LoadBin(MteFNm);*/}
}
TStr TNmObjBs::PeriodTagStr="<.>";
TStr TNmObjBs::BreakTagStr="<br>";
TStr TNmObjBs::ParagraphTagStr="<p>";
TStr TNmObjBs::EofTagStr="<eof>";
void TNmObjBs::LoadCustSwSet(const PSIn& SIn){
if (SIn.Empty()){return;}
TILx Lx(SIn, TFSet(iloCmtAlw, iloRetEoln, iloExcept));
// traverse lines
Lx.GetSym(syLn, syEof);
while (Lx.Sym!=syEof){
// get stop-phrase string
TStr WordStrVStr=Lx.Str;
// split phrase to words
TStrV WordStrV; WordStrVStr.SplitOnWs(WordStrV);
if (!WordStrV.Empty()){
// define phrase as stop-word
WordStrVToNmObjAttrSetH.AddDat(WordStrV).Incl(noaIgnore);
}
// get next symbol
Lx.GetSym(syLn, syEof);
}
}
void TNmObjBs::LoadNrWordBs(const PSIn& SIn){
if (SIn.Empty()){return;}
TILx Lx(SIn, TFSet(iloCmtAlw, iloRetEoln, iloExcept));
// traverse lines
Lx.GetSym(syQStr, syEoln, syEof);
while (Lx.Sym!=syEof){
if (Lx.Sym==syQStr){
// get normalized word
TStr NrWordStr=Lx.Str;
// get inflected words
Lx.GetSym(syColon);
Lx.GetSym(syQStr, syEoln);
while (Lx.Sym!=syEoln){
// get inflected word
TStr WordStr=Lx.Str;
// test if inflected word already exists
if (WordStrToNrH.IsKey(WordStr)){
printf("Word already normalized (%s)", WordStr.CStr());}
// add inflected word and corresponding normalized word
WordStrToNrH.AddDat(WordStr, NrWordStr);
//printf("'%s' ->'%s'\n", WordStr.CStr(), NrWordStr.CStr());
Lx.GetSym(syQStr, syEoln);
}
Lx.GetSym(syQStr, syEoln, syEof);
} else
if (Lx.Sym==syEoln){
// empty line
Lx.GetSym(syQStr, syEoln, syEof);
} else {
Fail;
}
}
}
TStr TNmObjBs::GetNrWordStr(const TStr& _WordStr) const {
// remove underline
TStr WordStr=_WordStr;
if (WordStr.IsChIn('_')){
WordStr.ChangeChAll('_', '$');
}
// check custom word-normalization table
TStr NrWordStr;
if (WordStrToNrH.IsKeyGetDat(WordStr, NrWordStr)){
// normalization found
return NrWordStr;
} else
if (MteLex.Empty()){
return WordStr;
} else {
// check MulTextEast word-normalization table
TStr UcWordStr=ChDef->GetUcStr(WordStr); // get upper-case word
TStr NrUcWordStr;
if (MteLex->IsInfWord(UcWordStr, NrUcWordStr)){
// normalization found
if (UcWordStr==NrUcWordStr){
// normalization word same as inflected word
return WordStr;
} else
if (IsAllCapWordStr(WordStr)){
// original word is in upper-case
return NrUcWordStr;
} else
if (IsFirstCapWordStr(WordStr)){
// original word has capitalization
TChA NrWordChA(NrUcWordStr);
ChDef->GetLcChA(NrWordChA);
if (NrWordChA.Len()>0){
NrWordChA.PutCh(0, ChDef->GetUc(NrWordChA[0]));}
return NrWordChA;
} else {
// original word is in lower-case
TStr NrLcWordStr=ChDef->GetLcStr(NrUcWordStr);
return NrLcWordStr;
}
} else {
// no normalization
return WordStr;
}
}
}
TNmObjAttr TNmObjBs::GetNmObjTypeFromStr(const TStr& Str){
if (Str=="Ignore"){return noaIgnore;}
if (Str=="Standalone"){return noaStandalone;}
if (Str=="AsCapitalized"){return noaAsCapitalized;}
if (Str=="Unperiod"){return noaUnperiod;}
if (Str=="Acronym"){return noaAcronym;}
if (Str=="FirstName"){return noaFirstName;}
if (Str=="Person"){return noaPerson;}
if (Str=="Company"){return noaCompany;}
if (Str=="Organization"){return noaOrganization;}
if (Str=="Country"){return noaCountry;}
if (Str=="Geography"){return noaGeography;}
TExcept::Throw("Invalid Named-Object name.", Str);
return noaIgnore;
}
void TNmObjBs::LoadNmObjTypeBs(const PSIn& SIn){
if (SIn.Empty()){return;}
TILx Lx(SIn, TFSet(iloCmtAlw, iloRetEoln, iloExcept));
// traverse lines
Lx.GetSym(syQStr, syIdStr, syEoln, syEof);
while (Lx.Sym!=syEof){
if ((Lx.Sym==syQStr)||(Lx.Sym==syIdStr)){
TVec<TStrV> NmObjWordStrVV;
TB32Set NmObjAttrSet;
while ((Lx.Sym==syQStr)||(Lx.Sym==syIdStr)){
if (Lx.Sym==syQStr){
// named-object word-string
TStr WordStrVStr=Lx.Str;
TStrV WordStrV; WordStrVStr.SplitOnWs(WordStrV);
NmObjWordStrVV.Add(WordStrV);
} else
if (Lx.Sym==syIdStr){
// named-object attribute
TNmObjAttr NmObjAttr=TNmObjBs::GetNmObjTypeFromStr(Lx.Str);
NmObjAttrSet.Incl(NmObjAttr);
} else {
Fail;
}
Lx.GetSym(syQStr, syIdStr, syEoln, syEof);
}
// assign 'defined' attribute if 'not ignore'
if (!NmObjAttrSet.In(noaIgnore)){
NmObjAttrSet.Incl(noaDefined);}
// assign attribute-sets to word-vectors
for (int NmObjN=0; NmObjN<NmObjWordStrVV.Len(); NmObjN++){
WordStrVToNmObjAttrSetH.AddDat(NmObjWordStrVV[NmObjN])|=NmObjAttrSet;
}
// assign aliases
{for (int NmObjN=1; NmObjN<NmObjWordStrVV.Len(); NmObjN++){
NmObjWordStrVToNrH.AddDat(NmObjWordStrVV[NmObjN], NmObjWordStrVV[0]);
}}
// get eoln
} else
if (Lx.Sym==syEoln){
// empty line
Lx.GetSym(syQStr, syEoln, syEof);
} else {
Fail;
}
}
}
bool TNmObjBs::IsNmObjAttr(const TStr& WordStr, const TNmObjAttr& NmObjAttr) const {
TStrV WordStrV; WordStrV.Add(WordStr);
return IsNmObjAttr(WordStrV, NmObjAttr);
}
bool TNmObjBs::IsNmObjAttr(const TStrV& WordStrV, const TNmObjAttr& NmObjAttr) const {
int WordStrVToNmObjAttrSetP=WordStrVToNmObjAttrSetH.GetKeyId(WordStrV);
if (WordStrVToNmObjAttrSetP==-1){return false;}
else {return WordStrVToNmObjAttrSetH[WordStrVToNmObjAttrSetP].In(NmObjAttr);}
}
bool TNmObjBs::IsFirstCapWordStr(const TStr& Str) const {
if (Str.Empty()){return false;}
char FirstCh=Str[0];
if (!ChDef->IsAlpha(FirstCh)){return false;}
if (!ChDef->IsUc(FirstCh)){return false;}
return true;
}
bool TNmObjBs::IsAllCapWordStr(const TStr& Str) const {
TChA ChA=Str;
for (int ChN=0; ChN<ChA.Len(); ChN++){
if (!ChDef->IsUc(ChA[ChN])){return false;}
}
return true;
}
bool TNmObjBs::IsNumStr(const TStr& Str) const {
if (Str.Empty()){return false;}
char FirstCh=Str[0];
if (!ChDef->IsNum(FirstCh)){return false;}
return true;
}
bool TNmObjBs::IsTagStr(const TStr& Str) const {
return (!Str.Empty())&&(Str[0]=='<');
}
bool TNmObjBs::IsMatchPfx(
const TStr& Str1, const TStr& Str2,
const int& MnPfxLen, const int& MxSfxLen) const {
// copy strings to character-array
TChA ChA1=Str1; TChA ChA2=Str2;
// match prefix of strings
int ChN=0;
forever {
if (ChN>=ChA1.Len()){break;}
if (ChN>=ChA2.Len()){break;}
if (ChA1[ChN]!=ChA2[ChN]){break;}
ChN++;
}
if (ChN+1<=MnPfxLen){return false;}
//
if (ChA1.Len()-ChN+1>MxSfxLen){return false;}
if (ChA2.Len()-ChN+1>MxSfxLen){return false;}
//printf("[%s]=[%s]\n", ChA1.CStr(), ChA2.CStr());
return true;
}
int TNmObjBs::GetNmObjId(const TStrV& WordStrV, const bool& DefP){
int NmObjId=-1;
if (DefP){
NmObjId=NmObjWordStrVToDocIdVH.AddKey(WordStrV);
} else {
NmObjId=NmObjWordStrVToDocIdVH.GetKeyId(WordStrV);
}
return NmObjId;
}
TStr TNmObjBs::GetWordStrVStr(const TStrV& WordStrV, const char& SepCh) const {
TChA WordChA;
for (int WordStrN=0; WordStrN<WordStrV.Len(); WordStrN++){
if (WordStrN>0){WordChA+=SepCh;}
WordChA+=WordStrV[WordStrN];
}
return WordChA;
}
void TNmObjBs::GetNrNmObjStrV(const TStrV& NmObjStrV, TStrV& NrNmObjStrV) const {
int NmObjWordStrVToNrP=NmObjWordStrVToNrH.GetKeyId(NmObjStrV);
if (NmObjWordStrVToNrP==-1){NrNmObjStrV=NmObjStrV;}
else {NrNmObjStrV=NmObjWordStrVToNrH[NmObjWordStrVToNrP];}
}
void TNmObjBs::ExtrCandWordStrV(
const TStr& HtmlStr, TStrV& CandWordStrV, const bool& DumpP){
// prepare named-object vector
CandWordStrV.Clr();
// prepare html parsing
PSIn HtmlSIn=TStrIn::New(HtmlStr);
PHtmlDoc HtmlDoc=THtmlDoc::New(HtmlSIn, hdtAll, false);
PHtmlTok Tok;
THtmlLxSym Sym; TStr Str; TStr NrStr;
CandWordStrV.Add(PeriodTagStr);
bool InTitle=false; bool InScript=false; int LastNmObjTokN=-1;
// traverse html tokens
if (DumpP){printf("Tokens: ");}
for (int TokN=0; TokN<HtmlDoc->GetToks(); TokN++){
PHtmlTok Tok=HtmlDoc->GetTok(TokN);
HtmlDoc->GetTok(TokN, Sym, Str);
switch (Sym){
case hsyUndef: break;
case hsyStr:
case hsyNum:
if (InTitle){break;}
if (InScript){break;}
NrStr=GetNrWordStr(Str);
if (DumpP){
if (Str==NrStr){printf("%s ", Str.CStr());}
else {printf("%s(%s) ", Str.CStr(), NrStr.CStr());}
}
if (IsFirstCapWordStr(NrStr)||IsNmObjAttr(NrStr, noaAsCapitalized)){
if ((LastNmObjTokN!=-1)&&(LastNmObjTokN<TokN-1)){
if (CandWordStrV.Last()!=PeriodTagStr){
CandWordStrV.Add(BreakTagStr);
}
}
CandWordStrV.Add(NrStr); LastNmObjTokN=TokN;
}
break;
case hsySSym:
if (InTitle){break;}
if (InScript){break;}
if (DumpP){
printf("%s ", Str.CStr());}
if (
(Str==".")||(Str=="!")||(Str=="?")||
(Str=="\"")||(Str=="-")||(Str=="/")||
(Str==":")||(Str==";")){
if (CandWordStrV.Last()!=PeriodTagStr){
CandWordStrV.Add(PeriodTagStr);
}
}
break;
case hsyBTag:
case hsyETag:
if (Str=="<TITLE>"){
InTitle=(Sym==hsyBTag);
} else
if (Str=="<SCRIPT>"){
InScript=(Sym==hsyBTag);
} else
if (Str=="<P>"){
if ((!CandWordStrV.Empty())&&(CandWordStrV.Last()!=ParagraphTagStr)){
CandWordStrV.Add(ParagraphTagStr);
CandWordStrV.Add(PeriodTagStr);
}
} else
if ((Str=="<TD>")||(Str=="<BR>")){
CandWordStrV.Add(PeriodTagStr);
}
break;
case hsyEof: break;
default: break;
}
}
CandWordStrV.Add(EofTagStr);
if (DumpP){printf("\n");}
if (DumpP){
printf("Candidates: ");
for (int CandWordStrN=0; CandWordStrN<CandWordStrV.Len(); CandWordStrN++){
printf("%s ", CandWordStrV[CandWordStrN].CStr());}
printf("\n");
}
}
void TNmObjBs::FilterCandToNmObjIdV(
const TStrV& CandWordStrV, TIntV& NmObjIdV, const bool& DumpP){
// prepare candidate traversal
TVec<TStrV> NmObjIdWordStrVV;
int CandWordStrN=0; int CandWordStrs=CandWordStrV.Len();
while (CandWordStrN<CandWordStrs){
// get candidate
TStr WordStr=CandWordStrV[CandWordStrN];
//printf("%s ", WordStr.CStr());
// simple filters
if (WordStr.Len()<=1){CandWordStrN++; continue;}
if (WordStr==ParagraphTagStr){CandWordStrN++; continue;}
if (WordStr==BreakTagStr){CandWordStrN++; continue;}
if (WordStr==EofTagStr){CandWordStrN++; break;}
if (IsNumStr(WordStr)){CandWordStrN++; continue;}
TStr UcWordStr=ChDef->GetUcStr(WordStr);
//if (SwSet->IsIn(UcWordStr, true)){
// CandWordStrN++; continue;}
if ((WordStr==UcWordStr)&&((WordStr.Len()>4)&&(!IsNmObjAttr(WordStr, noaAcronym)))){
CandWordStrN++; continue;}
// unperiod
if (IsNmObjAttr(WordStr, noaUnperiod)&&(CandWordStrV[CandWordStrN+1]==PeriodTagStr)){
CandWordStrN+=1;
}
// period
if (WordStr==PeriodTagStr){
CandWordStrN++; WordStr=CandWordStrV[CandWordStrN];
if (IsTagStr(WordStr)){continue;}
if (IsNmObjAttr(WordStr, noaDefined)){
continue;
} else
if ((CandWordStrN>1)&&(IsNmObjAttr(CandWordStrV[CandWordStrN-2], noaUnperiod))){
continue;
} else {
TStr NextWordStr=CandWordStrV[CandWordStrN+1];
if (IsFirstCapWordStr(NextWordStr)||IsNmObjAttr(NextWordStr, noaAsCapitalized)){
continue;
} else
if (!IsNmObj(WordStr)){
CandWordStrN++; continue;
}
}
}
// if (WordStr=="British"){
// printf("");}
// ignore
if (IsNmObjAttr(WordStr, noaIgnore)){
CandWordStrN++; continue;
}
// collect named-object words
TStrV WordStrV;
forever {
WordStrV.Add(WordStr);
CandWordStrN++; WordStr=CandWordStrV[CandWordStrN];
if (IsTagStr(WordStr)){break;}
if (WordStr.Len()<=1){break;}
if (IsNmObjAttr(WordStr, noaIgnore)){CandWordStrN++; break;}
if (IsNmObjAttr(WordStr, noaStandalone)){break;}
if (IsNmObjAttr(WordStrV, noaStandalone)){break;}
}
// get normalized version of named-object
TStrV NrWordStrV; GetNrNmObjStrV(WordStrV, NrWordStrV);
// simple filters
if (IsNmObjAttr(NrWordStrV, noaIgnore)){continue;}
if (IsNmObjAttr(NrWordStrV, noaFirstName)){continue;}
if (NrWordStrV.Len()>5){
while (NrWordStrV.Len()>2){NrWordStrV.Del(0);}}
if (NrWordStrV.Len()==1){
TStr UcWordStr=ChDef->GetUcStr(NrWordStrV[0]);
if (SwSet->IsIn(UcWordStr, true)){continue;}
}
// add named object
NmObjIdWordStrVV.Add(NrWordStrV);
}
// merge similar words
for (int NmObjN=0; NmObjN<NmObjIdWordStrVV.Len(); NmObjN++){
TStrV& WordStrV=NmObjIdWordStrVV[NmObjN];
if (WordStrV.Len()==1){
// merge single words
for (int SubNmObjN=0; SubNmObjN<NmObjIdWordStrVV.Len(); SubNmObjN++){
TStrV& SubWordStrV=NmObjIdWordStrVV[SubNmObjN];
if (SubWordStrV.Len()==1){
if (WordStrV[0]!=SubWordStrV[0]){
if (IsMatchPfx(WordStrV[0], SubWordStrV[0], 3, 4)){
// normalize to shorter string
if (WordStrV[0].Len()<SubWordStrV[0].Len()){SubWordStrV=WordStrV;}
else {WordStrV=SubWordStrV;}
}
}
}
}
} else
if (WordStrV.Len()>=2){
TStr LastNm=WordStrV.Last();
for (int SubNmObjN=0; SubNmObjN<NmObjIdWordStrVV.Len(); SubNmObjN++){
TStrV& SubWordStrV=NmObjIdWordStrVV[SubNmObjN];
if (SubWordStrV.Len()==1){
// merge last-name with [first-name,last-name] pairs
TStr SubLastNm=SubWordStrV[0];
if (LastNm!=SubLastNm){
if (IsMatchPfx(LastNm, SubLastNm, 3, 4)){
if (LastNm.Len()<SubLastNm.Len()){SubWordStrV=WordStrV;}
else {WordStrV=SubWordStrV;}
}
}
} else
if (false&&(SubWordStrV.Len()==2)){
// merge [first-name,last-name] with [first-name,last-name] pairs
if ((WordStrV[0]!=SubWordStrV[0])||(WordStrV[1]!=SubWordStrV[1])){
if ((IsMatchPfx(WordStrV[0], SubWordStrV[0], 3, 4))&&
(IsMatchPfx(WordStrV[1], SubWordStrV[1], 3, 4))){
// normalize to shorter string (first word)
if (WordStrV[0].Len()<SubWordStrV[0].Len()){
SubWordStrV[0]=WordStrV[0];}
else {WordStrV[0]=SubWordStrV[0];}
// normalize to shorter string (second word)
if (WordStrV[1].Len()<SubWordStrV[1].Len()){
SubWordStrV[1]=WordStrV[1];}
else {WordStrV[1]=SubWordStrV[1];}
}
}
}
}
}
}
// get named-objects-ids
NmObjIdV.Gen(NmObjIdWordStrVV.Len(), 0);
{for (int NmObjN=0; NmObjN<NmObjIdWordStrVV.Len(); NmObjN++){
TStrV& NmObjWordStrV=NmObjIdWordStrVV[NmObjN];
int NmObjId=GetNmObjId(NmObjWordStrV, true);
NmObjIdV.Add(NmObjId);
}}
// dump
if (DumpP){
printf("Named-Objects: ");
for (int NmObjN=0; NmObjN<NmObjIdV.Len(); NmObjN++){
int NmObjId=NmObjIdV[NmObjN];
TStr NmObjStr=GetNmObjStr(NmObjId);
printf("%s ", NmObjStr.CStr());
}
printf("\n");
}
}
PNmObjBs TNmObjBs::GetFromStrQuV(
const TStrQuV& IdTitleSrcHtmlQuV,
const TSwSetType& SwSetType, const TStr& CustSwSetFNm,
const TStr& NrWordBsFNm, const TStr& WordTypeBsFNm, const TStr& MteFNm,
const int& MxDocs, const bool& DumpP){
// custom-stop-words
PSIn CustSwSetSIn;
if (!CustSwSetFNm.Empty()&&(TFile::Exists(CustSwSetFNm))){
CustSwSetSIn=TFIn::New(CustSwSetFNm);}
// normalized-words
PSIn NrWordBsSIn;
if (!NrWordBsFNm.Empty()&&(TFile::Exists(NrWordBsFNm))){
NrWordBsSIn=TFIn::New(NrWordBsFNm);}
// word-types
PSIn WordTypeBsSIn;
if (!WordTypeBsFNm.Empty()&&(TFile::Exists(WordTypeBsFNm))){
WordTypeBsSIn=TFIn::New(WordTypeBsFNm);}
// create named-objects-base
PNmObjBs NmObjBs=
TNmObjBs::New(SwSetType, CustSwSetSIn, NrWordBsSIn, WordTypeBsSIn, MteFNm);
// traverse compact-documents
for (int DocN=0; DocN<IdTitleSrcHtmlQuV.Len(); DocN++){
if ((MxDocs!=-1)&&(DocN>MxDocs)){break;}
TStr DocNm=IdTitleSrcHtmlQuV[DocN].Val1;
TStr TitleStr=IdTitleSrcHtmlQuV[DocN].Val2;
TStr HtmlStr=IdTitleSrcHtmlQuV[DocN].Val4;
//if (!DocNm.IsStrIn("1998-06-18-z1b9.")){continue;}
if (DumpP){
printf("===============================================\n");
printf("%s\n", DocNm.CStr());
}
// extract candidate named-objects
TStrV CandWordStrV; NmObjBs->ExtrCandWordStrV(HtmlStr, CandWordStrV, DumpP);
// extract final named-objects from candidates
TIntV NmObjIdV; NmObjBs->FilterCandToNmObjIdV(CandWordStrV, NmObjIdV, DumpP);
// create document and add named-objects
NmObjBs->AddDoc(DocNm, "", NmObjIdV);
}
// get merged named-objects
TIntV NewNmObjIdV; NmObjBs->GetMergedNmObj(NewNmObjIdV);
// apply merged named-objects
NmObjBs->PutMergedNmObj(NewNmObjIdV);
// return named-objects-base
return NmObjBs;
}
PNmObjBs TNmObjBs::GetFromCpd(
const PSIn& _CpdSIn,
const TSwSetType& SwSetType, const PSIn& CustSwSetSIn,
const PSIn& NrWordBsSIn, const PSIn& WordTypeBsSIn, const TStr& MteFNm,
const int& MxDocs, const bool& DumpP){
// create named-objects-base
PNmObjBs NmObjBs=
TNmObjBs::New(SwSetType, CustSwSetSIn, NrWordBsSIn, WordTypeBsSIn, MteFNm);
// traverse compact-documents
PSIn CpdSIn=TCpDoc::FFirstCpd(_CpdSIn); PCpDoc CpDoc; int Docs=0;
while (TCpDoc::FNextCpd(CpdSIn, CpDoc)){
if ((MxDocs!=-1)&&(Docs>MxDocs)){break;}
TStr DocNm=CpDoc->GetDocNm();
TStr DateStr=CpDoc->GetDateStr();
TStr HtmlStr=CpDoc->GetTxtStr();
Docs++; printf("%d %s\r", Docs, DocNm.CStr());
//if (!DocNm.IsStrIn("1998-06-18-z1b9.")){continue;}
if (DumpP){
printf("===============================================\n");
printf("%s\n", DocNm.CStr());
}
// extract candidate named-objects
TStrV CandWordStrV; NmObjBs->ExtrCandWordStrV(HtmlStr, CandWordStrV, DumpP);
// extract final named-objects from candidates
TIntV NmObjIdV; NmObjBs->FilterCandToNmObjIdV(CandWordStrV, NmObjIdV, DumpP);
// create document and add named-objects
NmObjBs->AddDoc(DocNm, DateStr, NmObjIdV);
}
// get merged named-objects
TIntV NewNmObjIdV; NmObjBs->GetMergedNmObj(NewNmObjIdV);
// apply merged named-objects
NmObjBs->PutMergedNmObj(NewNmObjIdV);
// return named-objects-base
return NmObjBs;
}
PNmObjBs TNmObjBs::GetFromCpd(
const TStr& CpdFNm,
const TSwSetType& SwSetType, const TStr& CustSwSetFNm,
const TStr& NrWordBsFNm, const TStr& WordTypeBsFNm, const TStr& MteFNm,
const int& MxDocs, const bool& DumpP){
// cpd file
PSIn CpdSIn=TFIn::New(CpdFNm);
// custom-stop-words
PSIn CustSwSetSIn;
if (!CustSwSetFNm.Empty()&&(TFile::Exists(CustSwSetFNm))){
CustSwSetSIn=TFIn::New(CustSwSetFNm);}
// normalized-words
PSIn NrWordBsSIn;
if (!NrWordBsFNm.Empty()&&(TFile::Exists(NrWordBsFNm))){
NrWordBsSIn=TFIn::New(NrWordBsFNm);}
// word-types
PSIn WordTypeBsSIn;
if (!WordTypeBsFNm.Empty()&&(TFile::Exists(WordTypeBsFNm))){
WordTypeBsSIn=TFIn::New(WordTypeBsFNm);}
return TNmObjBs::GetFromCpd(
CpdSIn, SwSetType, CustSwSetSIn, NrWordBsSIn, WordTypeBsSIn, MteFNm,
MxDocs, DumpP);
}
void TNmObjBs::GetMergedNmObj(TIntV& NewNmObjIdV){
// matching constraints
int MnPfxLen=3; int MxSfxLen=2;
// create transformation vector
int NmObjs=NmObjWordStrVToDocIdVH.Len();
NewNmObjIdV.Gen(NmObjs); NewNmObjIdV.PutAll(-1);
// merging single words
// merging statistics
{int SingleWords=0; int ReducedSingleWords=0;
// collect single words according to prefix
TStrIntVH PfxStrToNmObjIdVH;
for (int NmObjId=0; NmObjId<NmObjs; NmObjId++){
if (NewNmObjIdV[NmObjId]!=-1){continue;}
const TStrV& WordStrV=NmObjWordStrVToDocIdVH.GetKey(NmObjId);
if (WordStrV.Len()==1){
TStr PfxStr=WordStrV[0].GetSubStr(0, 2);
PfxStrToNmObjIdVH.AddDat(PfxStr).Add(NmObjId);
SingleWords++;
}
}
// traverse word-groups with the same prefix
int Pfxs=PfxStrToNmObjIdVH.Len();
for (int PfxId=0; PfxId<Pfxs; PfxId++){
// get & traverse word-group
TIntV& NmObjIdV=PfxStrToNmObjIdVH[PfxId];
for (int NmObjIdN=0; NmObjIdN<NmObjIdV.Len(); NmObjIdN++){
int NmObjId=NmObjIdV[NmObjIdN];
if (NewNmObjIdV[NmObjId]!=-1){continue;}
NewNmObjIdV[NmObjId]=NmObjId;
const TStr& WordStr=NmObjWordStrVToDocIdVH.GetKey(NmObjId)[0];
int Fq=NmObjWordStrVToDocIdVH[NmObjId].Len();
TIntPrV FqNmObjIdPrV(NmObjIdV.Len(), 0);
FqNmObjIdPrV.Add(TIntPr(Fq, NmObjId));
// traverse rest of the word-group for matching words
for (int SubNmObjIdN=NmObjIdN+1; SubNmObjIdN<NmObjIdV.Len(); SubNmObjIdN++){
int SubNmObjId=NmObjIdV[SubNmObjIdN];
if (NewNmObjIdV[SubNmObjId]!=-1){continue;}
const TStr& SubWordStr=NmObjWordStrVToDocIdVH.GetKey(SubNmObjId)[0];
// test matching
if (IsMatchPfx(WordStr, SubWordStr, MnPfxLen, MxSfxLen)){
NewNmObjIdV[SubNmObjId]=NmObjId;
int SubFq=NmObjWordStrVToDocIdVH[SubNmObjId].Len();
FqNmObjIdPrV.Add(TIntPr(SubFq, SubNmObjId));
//printf("%s -> %s\n", WordStr.CStr(), SubWordStr.CStr());
}
}
// increment number of equivalence word-groups
ReducedSingleWords++;
// collapse matching words into most frequent word
if (FqNmObjIdPrV.Len()>1){
FqNmObjIdPrV.Sort(false);
int MainNmObjId=FqNmObjIdPrV[0].Val2;
NewNmObjIdV[MainNmObjId]=MainNmObjId;
TStr MainWordStr=NmObjWordStrVToDocIdVH.GetKey(MainNmObjId)[0];
//printf("[%s:", MainWordStr.CStr());
for (int FqNmObjIdPrN=1; FqNmObjIdPrN<FqNmObjIdPrV.Len(); FqNmObjIdPrN++){
int SubNmObjId=FqNmObjIdPrV[FqNmObjIdPrN].Val2;
NewNmObjIdV[SubNmObjId]=MainNmObjId;
//TStr& SubWordStr=NmObjWordStrVToDocIdVH.GetKey(SubNmObjId)[0];
//printf(" %s", SubWordStr.CStr());
}
//printf("]\n");
}
}
}
// print statistics
//printf("SingleWords:%d ReducedSingleWords:%d\n",
// SingleWords, ReducedSingleWords);
}
// merging double words
// merging statistics
{int DoubleWords=0; int ReducedDoubleWords=0;
// collect double words according to prefix
TStrIntVH PfxStrToNmObjIdVH;
for (int NmObjId=0; NmObjId<NmObjs; NmObjId++){
if (NewNmObjIdV[NmObjId]!=-1){continue;}
const TStrV& WordStrV=NmObjWordStrVToDocIdVH.GetKey(NmObjId);
if (WordStrV.Len()==2){
TStr PfxStr=WordStrV[0].GetSubStr(0, 2)+WordStrV[1].GetSubStr(0, 2);
PfxStrToNmObjIdVH.AddDat(PfxStr).Add(NmObjId);
DoubleWords++;
}
}
// traverse word-groups with the same prefix
int Pfxs=PfxStrToNmObjIdVH.Len();
for (int PfxId=0; PfxId<Pfxs; PfxId++){
// get & traverse word-group
TIntV& NmObjIdV=PfxStrToNmObjIdVH[PfxId];
for (int NmObjIdN=0; NmObjIdN<NmObjIdV.Len(); NmObjIdN++){
int NmObjId=NmObjIdV[NmObjIdN];
if (NewNmObjIdV[NmObjId]!=-1){continue;}
NewNmObjIdV[NmObjId]=NmObjId;
const TStr& WordStr1=NmObjWordStrVToDocIdVH.GetKey(NmObjId)[0];
const TStr& WordStr2=NmObjWordStrVToDocIdVH.GetKey(NmObjId)[1];
int Fq=NmObjWordStrVToDocIdVH[NmObjId].Len();
TIntPrV FqNmObjIdPrV(NmObjIdV.Len(), 0);
FqNmObjIdPrV.Add(TIntPr(Fq, NmObjId));
// traverse rest of the word-group for matching words
for (int SubNmObjIdN=NmObjIdN+1; SubNmObjIdN<NmObjIdV.Len(); SubNmObjIdN++){
int SubNmObjId=NmObjIdV[SubNmObjIdN];
if (NewNmObjIdV[SubNmObjId]!=-1){continue;}
const TStr& SubWordStr1=NmObjWordStrVToDocIdVH.GetKey(SubNmObjId)[0];
const TStr& SubWordStr2=NmObjWordStrVToDocIdVH.GetKey(SubNmObjId)[1];
// test matching
if (IsMatchPfx(WordStr1, SubWordStr1, MnPfxLen, MxSfxLen+1)&&
IsMatchPfx(WordStr2, SubWordStr2, MnPfxLen, MxSfxLen+1)){
NewNmObjIdV[SubNmObjId]=NmObjId;
int SubFq=NmObjWordStrVToDocIdVH[SubNmObjId].Len();
FqNmObjIdPrV.Add(TIntPr(SubFq, SubNmObjId));
//printf("%s_%s -> %s_%s\n",
// WordStr1.CStr(), WordStr2.CStr(),
// SubWordStr1.CStr(), SubWordStr2.CStr());
}
}
// increment number of equivalence word-groups
ReducedDoubleWords++;
// collapse matching words into most frequent word
if (FqNmObjIdPrV.Len()>1){
FqNmObjIdPrV.Sort(false);
int MainNmObjId=FqNmObjIdPrV[0].Val2;
NewNmObjIdV[MainNmObjId]=MainNmObjId;
TStr MainWordStr1=NmObjWordStrVToDocIdVH.GetKey(MainNmObjId)[0];
TStr MainWordStr2=NmObjWordStrVToDocIdVH.GetKey(MainNmObjId)[1];
//printf("[%s_%s:", MainWordStr1.CStr(), MainWordStr2.CStr());
for (int FqNmObjIdPrN=1; FqNmObjIdPrN<FqNmObjIdPrV.Len(); FqNmObjIdPrN++){
int SubNmObjId=FqNmObjIdPrV[FqNmObjIdPrN].Val2;
NewNmObjIdV[SubNmObjId]=MainNmObjId;
//TStr& SubWordStr1=NmObjWordStrVToDocIdVH.GetKey(SubNmObjId)[0];
//TStr& SubWordStr2=NmObjWordStrVToDocIdVH.GetKey(SubNmObjId)[1];
//printf(" %s_%s", SubWordStr1.CStr(), SubWordStr2.CStr());
}
//printf("]\n");
}
}
}
// print statistics
//printf("DoubleWords:%d ReducedDoubleWords:%d\n",
// DoubleWords, ReducedDoubleWords);
}
// merging triples to doubles
// ... (prefix, first-name, last-name) to (first-name, last-name)
// merging statistics
{int TripleWords=0; int ReducedTripleWords=0;
// collect single words according to prefix
TStrIntVH PfxStrToNmObjIdVH;
for (int NmObjId=0; NmObjId<NmObjs; NmObjId++){
if (NewNmObjIdV[NmObjId]!=-1){continue;}
const TStrV& WordStrV=NmObjWordStrVToDocIdVH.GetKey(NmObjId);
if (WordStrV.Len()==3){
TripleWords++;
TStrV DbWordStrV(2, 0);
DbWordStrV.Add(WordStrV[1]); DbWordStrV.Add(WordStrV[2]);
int DbNmObjId=NmObjWordStrVToDocIdVH.GetKeyId(DbWordStrV);
if (DbNmObjId!=-1){
ReducedTripleWords++;
int NewDbNmObjId=NewNmObjIdV[DbNmObjId];
NewNmObjIdV[NmObjId]=NewDbNmObjId;
//TStr NmObjStr=GetNmObjStr(NmObjId);
//TStr DbNmObjStr=GetNmObjStr(DbNmObjId);
//TStr NewDbNmObjStr=GetNmObjStr(NewDbNmObjId);
//printf("%s -> %s -> %s\n",
// NmObjStr.CStr(), DbNmObjStr.CStr(), NewDbNmObjStr.CStr());
}
}
}
//printf("TripleWords:%d ReducedTripleWords:%d\n",
// TripleWords, ReducedTripleWords);
}
// merging triple words
// merging statistics
{int TripleWords=0; int ReducedTripleWords=0;
// collect triple words according to prefix
TStrIntVH PfxStrToNmObjIdVH;
for (int NmObjId=0; NmObjId<NmObjs; NmObjId++){
if (NewNmObjIdV[NmObjId]!=-1){continue;}
const TStrV& WordStrV=NmObjWordStrVToDocIdVH.GetKey(NmObjId);
if (WordStrV.Len()==3){
TStr PfxStr=WordStrV[0].GetSubStr(0, 2)+WordStrV[1].GetSubStr(0, 2)+WordStrV[2].GetSubStr(0, 2);
PfxStrToNmObjIdVH.AddDat(PfxStr).Add(NmObjId);
TripleWords++;
}
}
// traverse word-groups with the same prefix
int Pfxs=PfxStrToNmObjIdVH.Len();
for (int PfxId=0; PfxId<Pfxs; PfxId++){
// get & traverse word-group
TIntV& NmObjIdV=PfxStrToNmObjIdVH[PfxId];
for (int NmObjIdN=0; NmObjIdN<NmObjIdV.Len(); NmObjIdN++){
int NmObjId=NmObjIdV[NmObjIdN];
if (NewNmObjIdV[NmObjId]!=-1){continue;}
NewNmObjIdV[NmObjId]=NmObjId;
const TStr& WordStr1=NmObjWordStrVToDocIdVH.GetKey(NmObjId)[0];
const TStr& WordStr2=NmObjWordStrVToDocIdVH.GetKey(NmObjId)[1];
const TStr& WordStr3=NmObjWordStrVToDocIdVH.GetKey(NmObjId)[2];
int Fq=NmObjWordStrVToDocIdVH[NmObjId].Len();
TIntPrV FqNmObjIdPrV(NmObjIdV.Len(), 0);
FqNmObjIdPrV.Add(TIntPr(Fq, NmObjId));
// traverse rest of the word-group for matching words
for (int SubNmObjIdN=NmObjIdN+1; SubNmObjIdN<NmObjIdV.Len(); SubNmObjIdN++){
int SubNmObjId=NmObjIdV[SubNmObjIdN];
if (NewNmObjIdV[SubNmObjId]!=-1){continue;}
const TStr& SubWordStr1=NmObjWordStrVToDocIdVH.GetKey(SubNmObjId)[0];
const TStr& SubWordStr2=NmObjWordStrVToDocIdVH.GetKey(SubNmObjId)[1];
const TStr& SubWordStr3=NmObjWordStrVToDocIdVH.GetKey(SubNmObjId)[2];
// test matching
if (IsMatchPfx(WordStr1, SubWordStr1, MnPfxLen, MxSfxLen+1)&&
IsMatchPfx(WordStr2, SubWordStr2, MnPfxLen, MxSfxLen+1)&&
IsMatchPfx(WordStr3, SubWordStr3, MnPfxLen, MxSfxLen+1)){
NewNmObjIdV[SubNmObjId]=NmObjId;
int SubFq=NmObjWordStrVToDocIdVH[SubNmObjId].Len();
FqNmObjIdPrV.Add(TIntPr(SubFq, SubNmObjId));
//printf("%s_%s_%s -> %s_%s_%s\n",
// WordStr1.CStr(), WordStr2.CStr(), WordStr3.CStr(),
// SubWordStr1.CStr(), SubWordStr2.CStr(), SubWordStr3.CStr());
}
}
// increment number of equivalence word-groups
ReducedTripleWords++;
// collapse matching words into most frequent word
if (FqNmObjIdPrV.Len()>1){
FqNmObjIdPrV.Sort(false);
int MainNmObjId=FqNmObjIdPrV[0].Val2;
NewNmObjIdV[MainNmObjId]=MainNmObjId;
TStr MainWordStr1=NmObjWordStrVToDocIdVH.GetKey(MainNmObjId)[0];
TStr MainWordStr2=NmObjWordStrVToDocIdVH.GetKey(MainNmObjId)[1];
TStr MainWordStr3=NmObjWordStrVToDocIdVH.GetKey(MainNmObjId)[2];
//printf("[%s_%s_%s:", MainWordStr1.CStr(), MainWordStr2.CStr(), MainWordStr3.CStr());
for (int FqNmObjIdPrN=1; FqNmObjIdPrN<FqNmObjIdPrV.Len(); FqNmObjIdPrN++){
int SubNmObjId=FqNmObjIdPrV[FqNmObjIdPrN].Val2;
NewNmObjIdV[SubNmObjId]=MainNmObjId;
//TStr& SubWordStr1=NmObjWordStrVToDocIdVH.GetKey(SubNmObjId)[0];
//TStr& SubWordStr2=NmObjWordStrVToDocIdVH.GetKey(SubNmObjId)[1];
//TStr& SubWordStr3=NmObjWordStrVToDocIdVH.GetKey(SubNmObjId)[2];
//printf(" %s_%s_%s", SubWordStr1.CStr(), SubWordStr2.CStr(), SubWordStr3.CStr());
}
//printf("]\n");
}
}
}
// print statistics
//printf("TripleWords:%d ReducedTripleWords:%d\n",
// TripleWords, ReducedTripleWords);
}
}
void TNmObjBs::PutMergedNmObj(const TIntV& NewNmObjIdV){
// create temporary table of new named-objects
TStrVIntVH NewNmObjWordStrVToDocIdVH;
for (int NmObjId=0; NmObjId<NewNmObjIdV.Len(); NmObjId++){
if (NewNmObjIdV[NmObjId]!=NmObjId){continue;}
// take data for new named-object from old definition
const TStrV& WordStrV=NmObjWordStrVToDocIdVH.GetKey(NmObjId);
// define new named-object
NewNmObjWordStrVToDocIdVH.AddDat(WordStrV);
}
//printf("Old Named-Objects: %d\n", NmObjWordStrVToDocIdVH.Len());
//printf("New Named-Objects: %d\n", NewNmObjWordStrVToDocIdVH.Len());
// obsolete named-object define as aliases
{for (int NmObjId=0; NmObjId<NewNmObjIdV.Len(); NmObjId++){
if (NewNmObjIdV[NmObjId]==NmObjId){continue;}
// take data for obsolete named-object from old definition
const TStrV& WordStrV=NmObjWordStrVToDocIdVH.GetKey(NmObjId);
// define alias for obsolete named-object
int NrNmObjId=NewNmObjIdV[NmObjId];
if (NrNmObjId!=-1){
const TStrV& NrWordStrV=NmObjWordStrVToDocIdVH.GetKey(NrNmObjId);
NmObjWordStrVToNrH.AddDat(WordStrV, NrWordStrV);
}
}}
// redefine documents
int Docs=GetDocs();
for (int DocId=0; DocId<Docs; DocId++){
TIntPrV& NmObjIdFqPrV=GetDoc_NmObjIdFqPrV(DocId);
// create temporary-document: new-named-object to frequency table
TIntIntH NewNmObjIdToFqH(NmObjIdFqPrV.Len());
for (int NmObjN=0; NmObjN<NmObjIdFqPrV.Len(); NmObjN++){
// get obsolete named-object data
int NmObjId=NmObjIdFqPrV[NmObjN].Val1;
int Fq=NmObjIdFqPrV[NmObjN].Val2;
// get named-document-id for normalized named-object
int NrNmObjId=NewNmObjIdV[NmObjId];
if (NrNmObjId!=-1){
// get normalized version of word-vector
const TStrV& NrWordStrV=NmObjWordStrVToDocIdVH.GetKey(NrNmObjId);
// get new named-object-id
int NewNmObjId=NewNmObjWordStrVToDocIdVH.GetKeyId(NrWordStrV);
// add new named-object-id and term-frequency to temporary-document
NewNmObjIdToFqH.AddDat(NewNmObjId)+=Fq;
}
}
// transfere new-named-object data to document
NmObjIdFqPrV.Gen(NewNmObjIdToFqH.Len(), 0);
for (int NmObjP=0; NmObjP<NewNmObjIdToFqH.Len(); NmObjP++){
int NewNmObjId=NewNmObjIdToFqH.GetKey(NmObjP);
int Fq=NewNmObjIdToFqH[NmObjP];
// add named-object and increment by term-frequency
NmObjIdFqPrV.Add(TIntPr(NewNmObjId, Fq));
// merge document-ids
NewNmObjWordStrVToDocIdVH[NewNmObjId].Add(DocId);
}
NmObjIdFqPrV.Sort();
}
// assign new named-objects
NmObjWordStrVToDocIdVH=NewNmObjWordStrVToDocIdVH;
}
void TNmObjBs::GetNmObjStrFqPrV(TStrIntPrV& NmObjStrFqPrV, const int& MnFq) const {
int NmObjs=GetNmObjs();
NmObjStrFqPrV.Gen(NmObjs, 0);
for (int NmObjId=0; NmObjId<NmObjs; NmObjId++){
TStrIntPr NmObjStrFqPr;
NmObjStrFqPr.Val1=GetNmObjStr(NmObjId);
NmObjStrFqPr.Val2=GetNmObjDocs(NmObjId);
if (NmObjStrFqPr.Val2>=MnFq){
NmObjStrFqPrV.Add(NmObjStrFqPr);}
}
}
void TNmObjBs::GetNmObjFqStrPrV(TIntStrPrV& NmObjFqStrPrV, const int& MnFq) const {
int NmObjs=GetNmObjs();
NmObjFqStrPrV.Gen(NmObjs, 0);
for (int NmObjId=0; NmObjId<NmObjs; NmObjId++){
TIntStrPr NmObjFqStrPr;
NmObjFqStrPr.Val1=GetNmObjDocs(NmObjId);
NmObjFqStrPr.Val2=GetNmObjStr(NmObjId);
if (NmObjFqStrPr.Val1>=MnFq){
NmObjFqStrPrV.Add(NmObjFqStrPr);}
}
}
void TNmObjBs::GetNmObjDIdV(
const PBowDocBs& BowDocBs, TIntV& BowDIdV,
const TStr& NmObjStr1, const TStr& NmObjStr2) const {
// get first named-object-id
int NmObjId1=GetNmObjId(NmObjStr1);
TIntV NmObjDocIdV1; GetNmObjDocIdV(NmObjId1, NmObjDocIdV1);
NmObjDocIdV1.Sort();
// get second named-object-id
TIntV NmObjDocIdV2;
if (!NmObjStr2.Empty()){
int NmObjId2=GetNmObjId(NmObjStr2);
GetNmObjDocIdV(NmObjId2, NmObjDocIdV2);
NmObjDocIdV2.Sort();
}
// create joint doc-id-vector
TIntV NmObjDocIdV;
if (NmObjDocIdV2.Empty()){
NmObjDocIdV=NmObjDocIdV1;
} else {
NmObjDocIdV1.Intrs(NmObjDocIdV2, NmObjDocIdV);
}
// traverse named-object-documents to collect bow-document-ids
BowDIdV.Gen(NmObjDocIdV.Len(), 0);
for (int NmObjDocIdN=0; NmObjDocIdN<NmObjDocIdV.Len(); NmObjDocIdN++){
TStr DocNm=GetDocNm(NmObjDocIdV[NmObjDocIdN]);
int DId=BowDocBs->GetDId(DocNm);
if (DId!=-1){
BowDIdV.Add(DId);
}
}
}
PBowSpV TNmObjBs::GetNmObjConcept(
const PBowDocBs& BowDocBs, const PBowDocWgtBs& BowDocWgtBs,
const TStr& NmObjStr1, const TStr& NmObjStr2) const {
// get doc-ids
TIntV BowDIdV; GetNmObjDIdV(BowDocBs, BowDIdV, NmObjStr1, NmObjStr2);
// get concept vector
PBowSpV ConceptSpV=TBowClust::GetConceptSpV(BowDocWgtBs, NULL, BowDIdV);
// return concept vector
return ConceptSpV;
}
void TNmObjBs::GetFqNmObjIdPrV(
const TStr& TargetNmObjStr, TIntPrV& FqNmObjIdPrV) const {
//printf("Searching %s ...", TargetNmObjStr.CStr());
// get target named-object-id
int TargetNmObjId=GetNmObjId(TargetNmObjStr);
// collect target named-object frequencies
TIntIntH NmObjIdToFqH;
// traverse target named-object documents
int NmObjDocs=GetNmObjDocs(TargetNmObjId);
for (int NmObjDocIdN=0; NmObjDocIdN<NmObjDocs; NmObjDocIdN++){
// get document-id
int DocId=GetNmObjDocId(TargetNmObjId, NmObjDocIdN);
// traverse named-object in document
int DocNmObjs=GetDocNmObjs(DocId);
for (int DocNmObjN=0; DocNmObjN<DocNmObjs; DocNmObjN++){
// get named-object & frequency
int NmObjId; int TermFq;
GetDocNmObjId(DocId, DocNmObjN, NmObjId, TermFq);
// increment named-object document frequency
NmObjIdToFqH.AddDat(NmObjId)++;
}
}
// get & sort frequency table
FqNmObjIdPrV.Clr(); NmObjIdToFqH.GetDatKeyPrV(FqNmObjIdPrV);
FqNmObjIdPrV.Sort(false);
}
int TNmObjBs::AddDoc(const TStr& DocNm, const TStr& DateStr, const TIntV& NmObjIdV){
// create named-object-id to frequency table
TIntIntH NmObjIdToFqH(NmObjIdV.Len());
for (int NmObjN=0; NmObjN<NmObjIdV.Len(); NmObjN++){
int NmObjId=NmObjIdV[NmObjN];
NmObjIdToFqH.AddDat(NmObjId)++;
}
// create document
IAssert(!IsDoc(DocNm));
int DocId=DocNmToNmObjDocH.AddKey(DocNm);
DocNmToNmObjDocH[DocId]=TNmObjDoc::New();
DocNmToNmObjDocH[DocId]->DateStr=DateStr;
TIntPrV& NmObjIdFqPrV=GetDoc_NmObjIdFqPrV(DocId);
for (int NmObjP=0; NmObjP<NmObjIdToFqH.Len(); NmObjP++){
int NmObjId=NmObjIdToFqH.GetKey(NmObjP);
int Fq=NmObjIdToFqH[NmObjP];
NmObjIdFqPrV.Add(TIntPr(NmObjId, Fq));
NmObjWordStrVToDocIdVH[NmObjId].AddSorted(DocId);
}
NmObjIdFqPrV.Sort();
// return doc-id
return DocId;
}
TStr TNmObjBs::GetDoc_NmObjStrVStr(const int& DocId, const char& SepCh) const {
TChA NmObjStrVChA;
TIntPrV& NmObjIdFqPrV=GetDoc_NmObjIdFqPrV(DocId);
for (int NmObjIdN=0; NmObjIdN<NmObjIdFqPrV.Len(); NmObjIdN++){
if (NmObjIdN>0){NmObjStrVChA+=SepCh;}
int NmObjId=NmObjIdFqPrV[NmObjIdN].Val1;
TStr NmObjStr=GetNmObjStr(NmObjId);
NmObjStrVChA+=NmObjStr;
}
return NmObjStrVChA;
}
PBowDocBs TNmObjBs::GetBowDocBs(const int& MnNmObjFq) const {
printf("Generating Bag-Of-Words...\n");
// create bag-of-words
PBowDocBs BowDocBs=TBowDocBs::New();
// traverse documents
for (int DocId=0; DocId<GetDocs(); DocId++){
if (DocId%100==0){printf("%d\r", DocId);}
TStr DocNm=GetDocNm(DocId);
TStr DateStr=GetDocDateStr(DocId);
TStrV WordStrV;
int DocNmObjs=GetDocNmObjs(DocId);
for (int DocNmObjN=0; DocNmObjN<DocNmObjs; DocNmObjN++){
int NmObjId; int TermFq; GetDocNmObjId(DocId, DocNmObjN, NmObjId, TermFq);
if ((MnNmObjFq==-1)||(GetNmObjDocs(NmObjId)>=MnNmObjFq)){
TStr NmObjStr=GetNmObjStr(NmObjId);
for (int TermOccN=0; TermOccN<TermFq; TermOccN++){
WordStrV.Add(NmObjStr);
}
}
}
if (!WordStrV.Empty()){
int DId=BowDocBs->AddDoc(DocNm, TStrV(), WordStrV);
BowDocBs->PutDateStr(DId, DateStr);
}
}
// return bag-of-words
BowDocBs->AssertOk();
printf("\nDone.\n");
return BowDocBs;
}
PBowDocBs TNmObjBs::GetNmBowDocBs(
const PBowDocBs& BowDocBs, const PBowDocWgtBs& BowDocWgtBs, const int& MnNmObjFq) const {
int NmObjs=GetNmObjs();
for (int NmObjId=0; NmObjId<NmObjs; NmObjId++){
printf("%d/%d\r", (1+NmObjId), NmObjs);
TStr NmObjStr=GetNmObjStr(NmObjId);
PBowSpV BowSpV=GetNmObjConcept(BowDocBs, BowDocWgtBs, NmObjStr);
}
printf("\n");
return NULL;
}
PBowDocBs TNmObjBs::GetRelBowDocBs(const PBowDocBs& BowDocBs, const PBowDocWgtBs& BowDocWgtBs, const int& MnNmObjFq) const {
return NULL;
}
void TNmObjBs::SaveTxtNmObj(const TStr& FqFNm, const TStr& SwFNm,
const TStr& AbcFNm, const TStr& DocFNm) const {
// get sorted frequency/named-object vector
TIntStrVPrV FqWordStrVPrV(NmObjWordStrVToDocIdVH.Len(), 0);
TStrVIntPrV WordStrVFqPrV(NmObjWordStrVToDocIdVH.Len(), 0);
for (int NmObjId=0; NmObjId<NmObjWordStrVToDocIdVH.Len(); NmObjId++){
int Fq=NmObjWordStrVToDocIdVH[NmObjId].Len();
const TStrV& WordStrV=NmObjWordStrVToDocIdVH.GetKey(NmObjId);
FqWordStrVPrV.Add(TIntStrVPr(Fq, WordStrV));
WordStrVFqPrV.Add(TStrVIntPr(WordStrV, Fq));
}
FqWordStrVPrV.Sort(false);
WordStrVFqPrV.Sort();
// save by frequency
if (!FqFNm.Empty()){
printf("Saving by frequency to '%s' ...", FqFNm.CStr());
TFOut SOut(FqFNm); FILE* fOut=SOut.GetFileId();
for (int PrN=0; PrN<FqWordStrVPrV.Len(); PrN++){
int Fq=FqWordStrVPrV[PrN].Val1;
TStrV& WordStrV=FqWordStrVPrV[PrN].Val2;
TStr WordStrVStr=GetWordStrVStr(WordStrV);
fprintf(fOut, "%d - %s\n", Fq, WordStrVStr.CStr());
}
printf(" Done.\n");
}
// save for stopword
if (!SwFNm.Empty()){
printf("Saving by frequency for stop-words proposal to '%s' ...", SwFNm.CStr());
TFOut SOut(SwFNm); FILE* fOut=SOut.GetFileId();
for (int PrN=0; PrN<FqWordStrVPrV.Len(); PrN++){
TStrV& WordStrV=FqWordStrVPrV[PrN].Val2;
TStr WordStrVStr=GetWordStrVStr(WordStrV, ' ');
fprintf(fOut, "%s\n", WordStrVStr.CStr());
}
printf(" Done.\n");
}
// save by alphabet
if (!AbcFNm.Empty()){
printf("Saving by alphabet to '%s' ...", AbcFNm.CStr());
TFOut SOut(AbcFNm); FILE* fOut=SOut.GetFileId();
for (int PrN=0; PrN<WordStrVFqPrV.Len(); PrN++){
TStrV& WordStrV=WordStrVFqPrV[PrN].Val1;
int Fq=WordStrVFqPrV[PrN].Val2;
TStr WordStrVStr=GetWordStrVStr(WordStrV);
fprintf(fOut, "%s - %d [", WordStrVStr.CStr(), Fq);
int NmObjId=GetNmObjId(WordStrV);
TIntV DocIdV;
GetNmObjDocIdV(NmObjId, DocIdV);
for (int DocIdN=0; DocIdN<DocIdV.Len(); DocIdN++){
TStr DocNm=GetDocNm(DocIdV[DocIdN]);
fprintf(fOut, "'%s' ", DocNm.CStr());
}
fprintf(fOut, "]\n");
}
printf(" Done.\n");
}
// save by documents
if (!DocFNm.Empty()){
printf("Saving by documents to '%s' ...", DocFNm.CStr());
TFOut SOut(DocFNm); FILE* fOut=SOut.GetFileId();
for (int DocId=0; DocId<GetDocs(); DocId++){
TStr DocNm=GetDocNm(DocId);
fprintf(fOut, "'%s'(%d):", DocNm.CStr(), DocId);
TStr DateStr=GetDocDateStr(DocId);
if (!DateStr.Empty()){
fprintf(fOut, "[%s]", DateStr.CStr());}
int DocNmObjs=GetDocNmObjs(DocId);
for (int DocNmObjN=0; DocNmObjN<DocNmObjs; DocNmObjN++){
int NmObjId; int TermFq; GetDocNmObjId(DocId, DocNmObjN, NmObjId, TermFq);
TStr NmObjStr=GetNmObjStr(NmObjId);
fprintf(fOut, " [%s:%d]", NmObjStr.CStr(), TermFq);
}
fprintf(fOut, "\n");
}
printf(" Done.\n");
}
}
| 37.278952 | 125 | 0.64062 | ksemer |
3eeae9b0cd211ccec05d48cc18791723593f9628 | 6,867 | cpp | C++ | ui/viewmodel/wallet/info_view.cpp | Webonnix/beam-ui | 65b6120e0d013db84d6bd863295f074830cae96c | [
"Apache-2.0"
] | null | null | null | ui/viewmodel/wallet/info_view.cpp | Webonnix/beam-ui | 65b6120e0d013db84d6bd863295f074830cae96c | [
"Apache-2.0"
] | null | null | null | ui/viewmodel/wallet/info_view.cpp | Webonnix/beam-ui | 65b6120e0d013db84d6bd863295f074830cae96c | [
"Apache-2.0"
] | null | null | null | // Copyright 2018 The Beam Team
//
// 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 "info_view.h"
#include "model/app_model.h"
namespace {
inline beam::Asset::ID assetIdxToId(int idx) {
return idx < 1 ? beam::Asset::s_BeamID : beam::Asset::ID(idx);
}
}
InfoViewModel::InfoViewModel()
: _wallet(*AppModel::getInstance().getWalletModel())
, _amgr(AppModel::getInstance().getAssets())
, _selectedAssetID(-1)
{
connect(&_wallet, &WalletModel::walletStatusChanged, this, &InfoViewModel::onWalletStatus);
connect(_amgr.get(), &AssetsManager::assetInfo, this, &InfoViewModel::onAssetInfo);
connect(&_ermgr, &ExchangeRatesManager::rateUnitChanged, this, &InfoViewModel::assetChanged);
connect(&_ermgr, &ExchangeRatesManager::activeRateChanged, this, &InfoViewModel::assetChanged);
updateProgress();
_wallet.getAsync()->getWalletStatus();
}
InfoViewModel::~InfoViewModel()
{
}
QString InfoViewModel::assetAvailable() const
{
const auto amount = _wallet.getAvailable(assetIdxToId(_selectedAssetID));
return beamui::AmountBigToUIString(amount);
}
QString InfoViewModel::assetIcon() const
{
return _amgr->getIcon(assetIdxToId(_selectedAssetID));
}
QString InfoViewModel::assetUnitName() const
{
return _amgr->getUnitName(assetIdxToId(_selectedAssetID), false);
}
QString InfoViewModel::assetName() const
{
return _amgr->getName(assetIdxToId(_selectedAssetID));
}
void InfoViewModel::onAssetInfo(beam::Asset::ID assetId)
{
bool found = std::find_if(_progress.begin(), _progress.end(), [&assetId](const auto& inp) {
return inp.assetId == assetId;
}) != _progress.end();
if (assetId == beam::Asset::ID(_selectedAssetID) || found)
{
updateProgress();
emit assetChanged();
}
}
QString InfoViewModel::getRateUnit() const
{
return _selectedAssetID < 1 ? beamui::getCurrencyUnitName(_ermgr.getRateUnitRaw()) : "";
}
QString InfoViewModel::getRate() const
{
auto rate = _ermgr.getRate(beam::wallet::ExchangeRate::Currency::Beam);
return _selectedAssetID < 1 ? beamui::AmountToUIString(rate) : "0";
}
int InfoViewModel::getSelectedAsset() const
{
return _selectedAssetID;
}
void InfoViewModel::setSelectedAsset(int newAsset)
{
if (_selectedAssetID != newAsset)
{
_selectedAssetID = newAsset;
updateProgress();
emit assetChanged();
}
}
void InfoViewModel::onWalletStatus()
{
updateProgress();
emit assetChanged();
}
QList<InProgress> InfoViewModel::getProgress() const
{
return _progress;
}
InProgress InfoViewModel::getProgressTotal() const
{
return _progressTotals;
}
void InfoViewModel::updateProgress()
{
using namespace beam::wallet;
_progress.clear();
_progressTotals = InProgress();
beam::AmountBig::Type sendingTotal = Zero;
beam::AmountBig::Type receivingTotal = Zero;
beam::AmountBig::Type changeTotal = Zero;
beam::AmountBig::Type incomingTotal = Zero;
beam::AmountBig::Type lockedTotal = Zero;
beam::AmountBig::Type maturingTotal = Zero;
beam::AmountBig::Type maturingMPTotal = Zero;
QString receivingUnit;
auto assets = _wallet.getAssetsNZ();
for(auto& asset: assets)
{
InProgress progress;
progress.assetId = asset;
auto sending = _wallet.getSending(asset);
auto receiving = _wallet.getReceiving(asset);
auto change = _wallet.getReceivingChange(asset);
auto incoming = _wallet.getReceivingIncoming(asset);
auto maturing = _wallet.getMaturing(asset);
auto maturingMP = _wallet.getMatutingMP(asset);
auto locked = maturing; locked += maturingMP;
if (sending != Zero || receiving != Zero || change != Zero || incoming != Zero || locked != Zero || maturing != Zero || maturingMP != Zero)
{
progress.sending = beamui::AmountBigToUIString(sending);
progress.receiving = beamui::AmountBigToUIString(receiving);
progress.receivingChange = beamui::AmountBigToUIString(change);
progress.receivingIncoming = beamui::AmountBigToUIString(incoming);
progress.locked = beamui::AmountBigToUIString(locked);
progress.lockedMaturing = beamui::AmountBigToUIString(maturing);
progress.lockedMaturingMP = beamui::AmountBigToUIString(maturingMP);
progress.icon = _amgr->getIcon(asset);
progress.unitName = _amgr->getUnitName(asset, false);
if (asset == 0)
{
progress.rate = beamui::AmountToUIString(_ermgr.getRate(ExchangeRate::Currency::Beam));
progress.rateUnit = beamui::getCurrencyUnitName(_ermgr.getRateUnitRaw());
}
else
{
progress.rate = "0";
}
_progress.push_back(progress);
sendingTotal += sending;
if (receiving != Zero)
{
receivingUnit = receivingTotal == Zero ? progress.unitName : "ASSETS";
}
receivingTotal += receiving;
changeTotal += change;
incomingTotal += incoming;
lockedTotal += locked;
maturingTotal += maturing;
maturingMPTotal += maturingMP;
}
}
_progressTotals.sending = beamui::AmountBigToUIString(sendingTotal);
_progressTotals.receiving = beamui::AmountBigToUIString(receivingTotal);
_progressTotals.receivingChange = beamui::AmountBigToUIString(changeTotal);
_progressTotals.receivingIncoming = beamui::AmountBigToUIString(incomingTotal);
_progressTotals.locked = beamui::AmountBigToUIString(lockedTotal);
_progressTotals.lockedMaturing = beamui::AmountBigToUIString(maturingTotal);
_progressTotals.lockedMaturingMP = beamui::AmountBigToUIString(maturingMPTotal);
_progressTotals.receivingUnit = receivingUnit;
_progressTotals.unitName = _progress.length() == 1 ? _progress[0].unitName : "ASSETS";
_progressTotals.rate = _progress.length() == 1 ? _progress[0].rate : "0";
_progressTotals.icon = _progress.length() == 1 ? _progress[0].icon : "";
}
| 34.681818 | 147 | 0.659968 | Webonnix |
3eeb92f32f748efc4895b2271aca660e3d674cbc | 1,454 | cpp | C++ | C++/0045_jump_gamp.cpp | lazybing/leetcode | f12e593cfdebe357887e8b6f169d573e273e27a2 | [
"BSD-2-Clause"
] | 1 | 2020-07-07T14:06:27.000Z | 2020-07-07T14:06:27.000Z | C++/0045_jump_gamp.cpp | lazybing/leetcode | f12e593cfdebe357887e8b6f169d573e273e27a2 | [
"BSD-2-Clause"
] | null | null | null | C++/0045_jump_gamp.cpp | lazybing/leetcode | f12e593cfdebe357887e8b6f169d573e273e27a2 | [
"BSD-2-Clause"
] | null | null | null | /*
* Given an array of non-negative integers, you are initially positioned at the first index of the array.
* Each element in the array represents your maximum jump length at that position.
* Your goal is to reach the last index in the minimum number of jumps.
*
* Example:
* Input:[2, 3, 1, 1, 4]
* Output:2
* Explanation: The minimum number of jumps to reach the last index is 2.
* Jump 1 step from index 0 to 1, then 3 steps to the last index.
*
* Note:
* You can assume that you can always reach the last index.
*/
class Solution {
public:
int jump(vector<int>& nums) {
int n = nums.size(), step = 0, start = 0, end = 0;
while (end < n - 1) {
step++;
int maxend = end + 1;
for (int i = start; i <= end; i++) {
if (i + numn[i] >= n - 1) return step;
maxend = max(maxend, i + nums[i]);
}
start = end + 1;
end = maxend;
}
return step;
}
int jump2(vector<int>& nums) {
int far = 0, res = 0, MAX = 0;
for (int i = 0; i < nums.size() - 1; i++) {
MAX = max(MAX, i + nums[i]);
if (far <= i) {
res++;
far = MAX;
MAX = 0;
}
}
return res;
}
};
| 30.291667 | 106 | 0.450481 | lazybing |
3eedb0568560b7ebaa2030eff541a4186b71104e | 1,784 | cpp | C++ | test/src/init.cpp | beroso/godot-cpp | eafe6d96226da5ebf02ec35ca1599a45dd794cfc | [
"MIT"
] | 17 | 2021-02-01T21:00:19.000Z | 2021-11-08T09:41:00.000Z | test/src/init.cpp | beroso/godot-cpp | eafe6d96226da5ebf02ec35ca1599a45dd794cfc | [
"MIT"
] | 29 | 2021-04-07T07:24:52.000Z | 2022-03-03T21:22:22.000Z | test/src/init.cpp | beroso/godot-cpp | eafe6d96226da5ebf02ec35ca1599a45dd794cfc | [
"MIT"
] | 1 | 2021-08-28T14:14:20.000Z | 2021-08-28T14:14:20.000Z | #include <Godot.hpp>
#include <Reference.hpp>
using namespace godot;
class SimpleClass : public Reference {
GODOT_CLASS(SimpleClass, Reference);
public:
SimpleClass() {}
/** `_init` must exist as it is called by Godot. */
void _init() {
_name = String("SimpleClass");
_value = 0;
}
void test_void_method() {
Godot::print("This is test");
}
Variant method(Variant arg) {
Variant ret;
ret = arg;
return ret;
}
static void _register_methods() {
register_method("method", &SimpleClass::method);
/**
* The line below is equivalent to the following GDScript export:
* export var _name = "SimpleClass"
**/
register_property<SimpleClass, String>("name", &SimpleClass::_name, String("SimpleClass"));
/** Alternatively, with getter and setter methods: */
register_property<SimpleClass, int>("value", &SimpleClass::set_value, &SimpleClass::get_value, 0);
/** Registering a signal: **/
register_signal<SimpleClass>("signal_name0"); // windows: error C2668: 'godot::register_signal': ambiguous call to overloaded function
register_signal<SimpleClass>("signal_name1", "string_argument", GODOT_VARIANT_TYPE_STRING);
}
String _name;
int _value;
void set_value(int p_value) {
_value = p_value;
}
int get_value() const {
return _value;
}
};
/** GDNative Initialize **/
extern "C" void GDN_EXPORT godot_gdnative_init(godot_gdnative_init_options *o) {
godot::Godot::gdnative_init(o);
}
/** GDNative Terminate **/
extern "C" void GDN_EXPORT godot_gdnative_terminate(godot_gdnative_terminate_options *o) {
godot::Godot::gdnative_terminate(o);
}
/** NativeScript Initialize **/
extern "C" void GDN_EXPORT godot_nativescript_init(void *handle) {
godot::Godot::nativescript_init(handle);
godot::register_class<SimpleClass>();
}
| 24.108108 | 136 | 0.71861 | beroso |
3eeee3aa150cfd347545a6d7a9b570b26f26fd84 | 4,568 | cc | C++ | spec/image_expand_spec.cc | fweiss/mcu-gif | aefe64ffcfe6e5c5ff80524c0f131cbc0e24fb49 | [
"MIT"
] | null | null | null | spec/image_expand_spec.cc | fweiss/mcu-gif | aefe64ffcfe6e5c5ff80524c0f131cbc0e24fb49 | [
"MIT"
] | null | null | null | spec/image_expand_spec.cc | fweiss/mcu-gif | aefe64ffcfe6e5c5ff80524c0f131cbc0e24fb49 | [
"MIT"
] | null | null | null | #include "ccspec/core.h"
#include "ccspec/expectation.h"
#include "ccspec/matchers.h"
using ccspec::core::describe;
using ccspec::core::before;
using ccspec::core::it;
using ccspec::expect;
using ccspec::matchers::eq;
#include "helpers/fake_file.h"
#include "helpers/pack.h"
extern "C" {
#include "gd.h"
#include "gd_internal.h"
}
#include <vector>
#include <functional>
namespace simple {
const size_t outputSize = 1024; // fixme max output size for a sub block?
typedef std::vector<uint8_t> code_stream_t;
auto image_expand_spec =
describe("expand image indexes", [] {
static gd_index_t output[outputSize];
static gd_expand_codes_t expand;
static uint16_t outputLength;
// clever use of lambda instead of define
auto expand_codes_stream = [&] (std::vector<uint16_t> codes) {
for (uint16_t code : codes) {
gd_image_expand_code(&expand, code);
}
};
before("each", [] {
// N.B. 'output' must be the array, not a pointer
memset(output, 0, sizeof(output));
expand.codeSize = 3;
expand.output = output;
expand.outputLength = 0;
});
// 1's will output index one-for-one
describe("simple uncompressed", [&] {
describe("code sequence 8 1's", [&] {
before("each", [&] {
expand_codes_stream({ 4, 1, 1, 1, 1, 1, 1, 1, 1, 5});
});
it("output count", [&] {
expect(expand.outputLength).to(eq(8));
});
it("output [1]", [&] {
expect(expand.output[1]).to(eq(1));
});
it("output [7]", [&] {
expect(expand.output[7]).to(eq(1));
});
it("code size", [&] {
expect((uint16_t)expand.codeSize).to(eq(4));
});
});
describe("code sequence 12 1's", [&] {
before("each", [&] {
expand_codes_stream({ 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5});
});
it("code size", [&] {
expect((uint16_t)expand.codeSize).to(eq(5));
});
});
describe("code sequence 28 1's", [&] {
before("each", [&] {
gd_image_expand_code(&expand, 4);
for (int i=0; i<28; i++) {
gd_image_expand_code(&expand, 1);
}
gd_image_expand_code(&expand, 5);
});
it("code size", [&] {
expect((uint16_t)expand.codeSize).to(eq(6));
});
});
});
describe("simple", [&] {
it("works", [&] {
expand_codes_stream({ 4, 0, 5 });
expect(expand.outputLength).to(eq(1));
expect(expand.output[0]).to(eq(0));
expect((short)expand.codeSize).to(eq(3));
});
});
describe("code size changed", [&] {
it("to 4", [&] {
// expand_codes_stream({ 4, 1, 6, 6, 2, 5 });
uint16_t codes[] = { 4, 1, 6, 6, 2, 5};
for (auto code : codes) {
gd_image_expand_code(&expand, code);
}
// expect(expand.string_table.length).to(eq(6));
expect((uint16_t)expand.codeSize).to(eq(4));
});
});
describe("full example", [&] {
before("each", [&] {
// expand_codes_stream({ 4, 1, 6, 6, 2, 9, 9, 7, 8, 10, 2, 12, 1, 14, 15, 6, 0, 21, 0, 10, 7, 22, 23, 18, 26, 7, 10, 29, 13, 24, 12, 18, 16, 36, 12, 5});
uint16_t codes[] = { 4, 1, 6, 6, 2, 9, 9, 7, 8, 10, 2, 12, 1, 14, 15, 6, 0, 21, 0, 10, 7, 22, 23, 18, 26, 7, 10, 29, 13, 24, 12, 18, 16, 36, 12, 5};
for (auto code : codes) {
gd_image_expand_code(&expand, code);
}
});
it("output count 100", [&] {
expect(expand.outputLength).to(eq(100));
});
it("output [4] 1", [&] {
expect(expand.output[4]).to(eq(1));
});
it("output [5] 2", [&] {
expect(expand.output[5]).to(eq(2));
});
it("output [9] 2", [&] {
expect(expand.output[5]).to(eq(2));
});
it("output [19] 2", [&] {
expect(expand.output[5]).to(eq(2));
});
it("output [30] 1", [&] {
expect(expand.output[99]).to(eq(1));
});
it("output [32] 1", [&] {
expect(expand.output[99]).to(eq(1));
});
it("output [99] 1", [&] {
expect(expand.output[99]).to(eq(1));
});
});
});
} // namespace simple
| 30.453333 | 164 | 0.468695 | fweiss |
3eef36b856da4184d01a4502ebbbdcb6983d6282 | 1,507 | cpp | C++ | foo_dotnet_component_host/ui/ui_preferences.cpp | TheQwertiest/foo_dotnet_component_host | f849849b591a5d85b4bc12790123dc40aaf24f93 | [
"MIT"
] | 4 | 2021-12-01T18:54:26.000Z | 2022-03-30T13:16:17.000Z | foo_dotnet_component_host/ui/ui_preferences.cpp | TheQwertiest/foo_dotnet_component_host | f849849b591a5d85b4bc12790123dc40aaf24f93 | [
"MIT"
] | 1 | 2021-11-29T13:25:14.000Z | 2022-01-16T22:54:57.000Z | foo_dotnet_component_host/ui/ui_preferences.cpp | TheQwertiest/foo_dotnet_component_host | f849849b591a5d85b4bc12790123dc40aaf24f93 | [
"MIT"
] | null | null | null | #include <stdafx.h>
#include "ui_preferences.h"
#include <convert/to_net.h>
#include <ui/ui_preferences_form.h>
namespace Qwr::DotnetHost
{
ComponentInterface::PreferencesPageInfo Preferences::GetInfo()
{
PreferencesPageInfo info;
info.Name = DNET_NAME;
info.Guid = Convert::ToNet::ToValue( Guids::ui_preferences );
info.ParentGuid = Convert::ToNet::ToValue( preferences_page::guid_components );
info.HelpUrl = "https://theqwertiest.github.io/foo_dotnet_component_host/";
return info;
}
void Preferences::Initialize( IntPtr parentHandle, IPreferencesPageCallback ^ callback )
{
preferencesCallback_ = callback;
_impl = gcnew PreferencesForm( this );
SetParent( (HWND)_impl->Handle.ToPointer(), (HWND)parentHandle.ToPointer() );
_impl->Anchor = ( AnchorStyles::Left | AnchorStyles::Top | AnchorStyles::Right | AnchorStyles::Bottom );
_impl->Show();
}
void Preferences::Reset()
{
}
void Preferences::Apply()
{
assert( _impl );
_impl->Apply();
}
PreferencesPageState Preferences::State()
{
assert( _impl );
PreferencesPageState state = PreferencesPageState::HasNoChanges;
if ( _impl->HasComponentChanges() )
{
state = PreferencesPageState::HasChanged | PreferencesPageState::NeedsFb2kRestart;
}
return state;
}
IntPtr Preferences::Handle()
{
assert( _impl );
return _impl->Handle;
}
IPreferencesPageCallback ^ Preferences::Callback()
{
return preferencesCallback_;
}
} // namespace Qwr::DotnetHost
| 22.161765 | 108 | 0.713338 | TheQwertiest |
3eefa692eaf66833c6752afa9285ad9067ae3210 | 943 | ipp | C++ | Siv3D/include/Siv3D/detail/UnicodeConverter.ipp | tas9n/OpenSiv3D | c561cba1d88eb9cd9606ba983fcc1120192d5615 | [
"MIT"
] | 2 | 2021-11-22T00:52:48.000Z | 2021-12-24T09:33:55.000Z | Siv3D/include/Siv3D/detail/UnicodeConverter.ipp | tas9n/OpenSiv3D | c561cba1d88eb9cd9606ba983fcc1120192d5615 | [
"MIT"
] | 32 | 2021-10-09T10:04:11.000Z | 2022-02-25T06:10:13.000Z | Siv3D/include/Siv3D/detail/UnicodeConverter.ipp | tas9n/OpenSiv3D | c561cba1d88eb9cd9606ba983fcc1120192d5615 | [
"MIT"
] | 1 | 2021-12-31T05:08:00.000Z | 2021-12-31T05:08:00.000Z | //-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2022 Ryo Suzuki
// Copyright (c) 2016-2022 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
namespace s3d
{
inline char32 UTF8toUTF32_Converter::get() const noexcept
{
return m_result;
}
inline char32 UTF16toUTF32_Converter::get() const noexcept
{
return m_result;
}
inline const std::array<char8, 4>& UTF32toUTF8_Converter::get() const noexcept
{
return m_buffer;
}
inline std::array<char8, 4>::const_iterator UTF32toUTF8_Converter::begin() const noexcept
{
return m_buffer.begin();
}
inline const std::array<char16, 2>& UTF32toUTF16_Converter::get() const noexcept
{
return m_buffer;
}
inline std::array<char16, 2>::const_iterator UTF32toUTF16_Converter::begin() const noexcept
{
return m_buffer.begin();
}
}
| 20.5 | 92 | 0.64263 | tas9n |
3ef08b68456eb0d9b1bb3a17df25f057246f652f | 1,246 | cpp | C++ | Onboard-SDK-ROS/dji_sdk_demo/src/stereo_utility/point_cloud_viewer.cpp | NMMI/aerial-alter-ego | ba6517ecc1986e4808f6c17df3348dc5637d9cf7 | [
"BSD-3-Clause"
] | 6 | 2020-08-16T07:31:14.000Z | 2022-02-17T06:24:47.000Z | src/Onboard-SDK-ROS-3.6/dji_sdk_demo/src/stereo_utility/point_cloud_viewer.cpp | isuran/droneautomation | c53017f8c8d4c03e3095ec7b6269d5a2659489e5 | [
"MIT"
] | 1 | 2021-08-18T08:14:19.000Z | 2021-08-18T08:14:19.000Z | src/Onboard-SDK-ROS-3.6/dji_sdk_demo/src/stereo_utility/point_cloud_viewer.cpp | isuran/droneautomation | c53017f8c8d4c03e3095ec7b6269d5a2659489e5 | [
"MIT"
] | 2 | 2021-05-18T07:04:23.000Z | 2021-05-23T13:22:13.000Z | #include "stereo_utility/point_cloud_viewer.hpp"
PointCloudViewer* PointCloudViewer::single_instance_ = new PointCloudViewer("Point Cloud Viewer");
PointCloudViewer::PointCloudViewer(const std::string &name)
: viewer_(name)
, view_pos_(-1.0, -2.0, -3.0)
, view_point_(0, 0, 0)
, view_y_dir_(0, 1, 0)
, world_coordinate_(.3)
{
cv::Affine3d view_pose = cv::viz::makeCameraPose(view_pos_,
view_point_,
view_y_dir_);
viewer_.setViewerPose(view_pose);
world_coordinate_.setRenderingProperty(cv::viz::LINE_WIDTH, 2.0);
viewer_.showWidget("World", world_coordinate_);
cv::Affine3d M = cv::Affine3d::Identity();
viewer_.setWidgetPose("World", M );
}
PointCloudViewer::~PointCloudViewer()
{
}
PointCloudViewer&
PointCloudViewer::instance()
{
return *PointCloudViewer::single_instance_;
}
PointCloudViewer*
PointCloudViewer::instancePtr()
{
return PointCloudViewer::single_instance_;
}
void
PointCloudViewer::showPointCloud(cv::viz::WCloud &cloud)
{
PointCloudViewer *this_ptr = PointCloudViewer::instancePtr();
cloud.setRenderingProperty( cv::viz::POINT_SIZE, 3);
this_ptr->viewer_.showWidget("Cloud", cloud);
} | 25.958333 | 98 | 0.691011 | NMMI |
3ef89c6d8023cad4347a80cceb00b2842e18c870 | 45,101 | cpp | C++ | Source/MaestroMakeFlux.cpp | XinlongSBU/MAESTROeX | bda189af39390fc09bb0ebb8321971b9d7688fd7 | [
"BSD-3-Clause"
] | null | null | null | Source/MaestroMakeFlux.cpp | XinlongSBU/MAESTROeX | bda189af39390fc09bb0ebb8321971b9d7688fd7 | [
"BSD-3-Clause"
] | null | null | null | Source/MaestroMakeFlux.cpp | XinlongSBU/MAESTROeX | bda189af39390fc09bb0ebb8321971b9d7688fd7 | [
"BSD-3-Clause"
] | null | null | null |
#include <Maestro.H>
using namespace amrex;
const int pred_rhoh = 0;
const int pred_rhohprime = 1;
const int pred_h = 2;
const int pred_T_then_rhohprime = 3;
const int pred_T_then_h = 4;
const int pred_hprime = 5;
const int pred_Tprime_then_h = 6;
const int pred_rhoprime_and_X = 1;
const int pred_rhoX = 2;
const int pred_rho_and_X = 3;
void
Maestro::MakeRhoXFlux (const Vector<MultiFab>& state,
Vector<std::array< MultiFab, AMREX_SPACEDIM > >& sflux,
Vector<MultiFab>& etarhoflux,
Vector<std::array< MultiFab, AMREX_SPACEDIM > >& sedge,
const Vector<std::array< MultiFab, AMREX_SPACEDIM > >& umac,
const Vector<std::array< MultiFab, AMREX_SPACEDIM > >& w0mac,
const RealVector& r0_old,
const RealVector& r0_edge_old,
const Vector<std::array< MultiFab, AMREX_SPACEDIM > >& r0mac_old,
const RealVector& r0_new,
const RealVector& r0_edge_new,
const Vector<std::array< MultiFab, AMREX_SPACEDIM > >& r0mac_new,
const RealVector& r0_predicted_edge,
int start_comp, int num_comp)
{
// timer for profiling
BL_PROFILE_VAR("Maestro::MakeRhoXFlux()", MakeRhoXFlux);
const int rho_comp = Rho;
const int spec_comp = FirstSpec;
const int nspec = NumSpec;
const int max_lev = max_radial_level;
const int species_pred_type_loc = species_pred_type;
const bool use_exact_base_state_loc = use_exact_base_state;
const bool evolve_base_state_loc = evolve_base_state;
for (int lev=0; lev<=finest_level; ++lev) {
#if (AMREX_SPACEDIM == 3)
MultiFab rho0mac_edgex, rho0mac_edgey, rho0mac_edgez;
if (spherical == 1) {
rho0mac_edgex.define(convert(grids[lev],nodal_flag_x), dmap[lev], 1, 1);
rho0mac_edgey.define(convert(grids[lev],nodal_flag_y), dmap[lev], 1, 1);
rho0mac_edgez.define(convert(grids[lev],nodal_flag_z), dmap[lev], 1, 1);
MultiFab::LinComb(rho0mac_edgex,0.5,r0mac_old[lev][0],0,0.5,r0mac_new[lev][0],0,0,1,1);
MultiFab::LinComb(rho0mac_edgey,0.5,r0mac_old[lev][1],0,0.5,r0mac_new[lev][1],0,0,1,1);
MultiFab::LinComb(rho0mac_edgez,0.5,r0mac_old[lev][2],0,0.5,r0mac_new[lev][2],0,0,1,1);
}
#endif
// loop over boxes (make sure mfi takes a cell-centered multifab as an argument)
#ifdef _OPENMP
#pragma omp parallel
#endif
for ( MFIter mfi(state[lev], TilingIfNotGPU()); mfi.isValid(); ++mfi ) {
// Get the index space of the valid region
const Box& xbx = mfi.nodaltilebox(0);
const Box& ybx = mfi.nodaltilebox(1);
#if (AMREX_SPACEDIM == 3)
const Box& zbx = mfi.nodaltilebox(2);
#endif
const Array4<Real> sedgex = sedge[lev][0].array(mfi);
const Array4<Real> sfluxx = sflux[lev][0].array(mfi);
const Array4<Real> etarhoflux_arr = etarhoflux[lev].array(mfi);
const Array4<const Real> umacx = umac[lev][0].array(mfi);
const Array4<Real> sedgey = sedge[lev][1].array(mfi);
const Array4<Real> sfluxy = sflux[lev][1].array(mfi);
const Array4<const Real> vmac = umac[lev][1].array(mfi);
#if (AMREX_SPACEDIM == 3)
const Array4<Real> sedgez = sedge[lev][2].array(mfi);
const Array4<Real> sfluxz = sflux[lev][2].array(mfi);
const Array4<const Real> wmac = umac[lev][2].array(mfi);
#endif
Real * AMREX_RESTRICT w0_p = w0.dataPtr();
const Real * AMREX_RESTRICT rho0_old_p = r0_old.dataPtr();
const Real * AMREX_RESTRICT rho0_new_p = r0_new.dataPtr();
const Real * AMREX_RESTRICT rho0_edge_old_p = r0_edge_old.dataPtr();
const Real * AMREX_RESTRICT rho0_edge_new_p = r0_edge_new.dataPtr();
const Real * AMREX_RESTRICT rho0_predicted_edge_p = r0_predicted_edge.dataPtr();
#if (AMREX_SPACEDIM == 2)
// x-direction
AMREX_PARALLEL_FOR_4D(xbx, num_comp, i, j, k, n, {
int comp = n+start_comp;
// reset density flux
if (n == 0) {
sfluxx(i,j,k,0) = 0.0;
}
Real rho0_edge = 0.5*(rho0_old_p[lev+j*(max_lev+1)]+rho0_new_p[lev+j*(max_lev+1)]);
if (species_pred_type_loc == pred_rhoprime_and_X) {
// edge states are rho' and X. To make the (rho X) flux,
// we need the edge state of rho0
sfluxx(i,j,k,comp) = umacx(i,j,k)*
(rho0_edge+sedgex(i,j,k,rho_comp))*sedgex(i,j,k,comp);
} else if (species_pred_type_loc == pred_rhoX) {
// edge states are (rho X)
sfluxx(i,j,k,comp) = umacx(i,j,k)*sedgex(i,j,k,comp);
} else if (species_pred_type_loc == pred_rho_and_X) {
// edge states are rho and X
sfluxx(i,j,k,comp) = umacx(i,j,k)*
sedgex(i,j,k,rho_comp)*sedgex(i,j,k,comp);
}
// compute the density fluxes by summing the species fluxes
sfluxx(i,j,k,0) += sfluxx(i,j,k,comp);
});
// y-direction
AMREX_PARALLEL_FOR_4D(ybx, num_comp, i, j, k, n, {
int comp = n+start_comp;
// reset density flux
if (n == 0) {
sfluxy(i,j,k,0) = 0.0;
}
Real rho0_edge = 0.5*(rho0_edge_old_p[lev+j*(max_lev+1)]+rho0_edge_new_p[lev+j*(max_lev+1)]);
if (species_pred_type_loc == pred_rhoprime_and_X) {
// ! edge states are rho' and X. To make the (rho X) flux,
// ! we need the edge state of rho0
sfluxy(i,j,k,comp) =
vmac(i,j,k)*(rho0_edge+sedgey(i,j,k,rho_comp))*sedgey(i,j,k,comp);
} else if (species_pred_type_loc == pred_rhoX) {
// ! edge states are (rho X)
sfluxy(i,j,k,comp) =
vmac(i,j,k)*sedgey(i,j,k,comp);
} else if (species_pred_type_loc == pred_rho_and_X) {
// ! edge state are rho and X
sfluxy(i,j,k,comp) =
vmac(i,j,k)*sedgey(i,j,k,rho_comp)*sedgey(i,j,k,comp);
}
if (evolve_base_state_loc && !use_exact_base_state_loc) {
if (comp >= spec_comp && comp <= spec_comp+nspec-1) {
etarhoflux_arr(i,j,k) += sfluxy(i,j,k,comp);
}
if (comp==spec_comp+nspec-1) {
etarhoflux_arr(i,j,k) -= w0_p[lev+j*(max_lev+1)]*rho0_predicted_edge_p[lev+j*(max_lev+1)];
}
}
// compute the density fluxes by summing the species fluxes
sfluxy(i,j,k,0) += sfluxy(i,j,k,comp);
});
#elif (AMREX_SPACEDIM == 3)
if (spherical == 0) {
// x-direction
AMREX_PARALLEL_FOR_4D(xbx, num_comp, i, j, k, n, {
int comp = n + start_comp;
// reset density flux
if (n == 0) {
sfluxx(i,j,k,0) = 0.0;
}
Real rho0_edge = 0.5*(rho0_old_p[lev+k*(max_lev+1)]+rho0_new_p[lev+k*(max_lev+1)]);
if (species_pred_type_loc == pred_rhoprime_and_X) {
// edge states are rho' and X. To make the (rho X) flux,
// we need the edge state of rho0
sfluxx(i,j,k,comp) = umacx(i,j,k)*
(rho0_edge+sedgex(i,j,k,rho_comp))*sedgex(i,j,k,comp);
} else if (species_pred_type_loc == pred_rhoX) {
// edge states are (rho X)
sfluxx(i,j,k,comp) = umacx(i,j,k)*sedgex(i,j,k,comp);
} else if (species_pred_type_loc == pred_rho_and_X) {
// edge states are rho and X
sfluxx(i,j,k,comp) = umacx(i,j,k)*
sedgex(i,j,k,rho_comp)*sedgex(i,j,k,comp);
}
// compute the density fluxes by summing the species fluxes
sfluxx(i,j,k,0) += sfluxx(i,j,k,comp);
});
// y-direction
AMREX_PARALLEL_FOR_4D(ybx, num_comp, i, j, k, n, {
int comp = n + start_comp;
// reset density flux
if (n == 0) {
sfluxy(i,j,k,0) = 0.0;
}
Real rho0_edge = 0.5*(rho0_old_p[lev+k*(max_lev+1)]+rho0_new_p[lev+k*(max_lev+1)]);
if (species_pred_type_loc == pred_rhoprime_and_X) {
// edge states are rho' and X. To make the (rho X) flux,
// we need the edge state of rho0
sfluxy(i,j,k,comp) = vmac(i,j,k)*
(rho0_edge+sedgey(i,j,k,rho_comp))*sedgey(i,j,k,comp);
} else if (species_pred_type_loc == pred_rhoX) {
// edge states are (rho X)
sfluxy(i,j,k,comp) = vmac(i,j,k)*sedgey(i,j,k,comp);
} else if (species_pred_type_loc == pred_rho_and_X) {
// edge states are rho and X
sfluxy(i,j,k,comp) = vmac(i,j,k)*
sedgey(i,j,k,rho_comp)*sedgey(i,j,k,comp);
}
// compute the density fluxes by summing the species fluxes
sfluxy(i,j,k,0) += sfluxy(i,j,k,comp);
});
// z-direction
AMREX_PARALLEL_FOR_4D(zbx, num_comp, i, j, k, n, {
int comp = n + start_comp;
// reset density flux
if (n == 0) {
sfluxz(i,j,k,0) = 0.0;
}
Real rho0_edge = 0.5*(rho0_edge_old_p[lev+k*(max_lev+1)]+rho0_edge_new_p[lev+k*(max_lev+1)]);
if (species_pred_type_loc == pred_rhoprime_and_X) {
// ! edge states are rho' and X. To make the (rho X) flux,
// ! we need the edge state of rho0
sfluxz(i,j,k,comp) =
wmac(i,j,k)*(rho0_edge+sedgez(i,j,k,rho_comp))*sedgez(i,j,k,comp);
} else if (species_pred_type_loc == pred_rhoX) {
// ! edge states are (rho X)
sfluxz(i,j,k,comp) =
wmac(i,j,k)*sedgez(i,j,k,comp);
} else if (species_pred_type_loc == pred_rho_and_X) {
// ! edge state are rho and X
sfluxz(i,j,k,comp) =
wmac(i,j,k)*sedgez(i,j,k,rho_comp)*sedgez(i,j,k,comp);
}
if (evolve_base_state_loc && !use_exact_base_state_loc) {
if (comp >= spec_comp && comp <= spec_comp+nspec-1) {
etarhoflux_arr(i,j,k) += sfluxz(i,j,k,comp);
}
if (comp == spec_comp+nspec-1) {
etarhoflux_arr(i,j,k) -= w0_p[lev+k*(max_lev+1)]*rho0_predicted_edge_p[lev+k*(max_lev+1)];
}
}
// compute the density fluxes by summing the species fluxes
sfluxz(i,j,k,0) += sfluxz(i,j,k,comp);
});
} else {
const Array4<const Real> rho0_edgex = rho0mac_edgex.array(mfi);
const Array4<const Real> rho0_edgey = rho0mac_edgey.array(mfi);
const Array4<const Real> rho0_edgez = rho0mac_edgez.array(mfi);
// x-direction
AMREX_PARALLEL_FOR_4D(xbx, num_comp, i, j, k, n, {
int comp = n + start_comp;
// reset density flux
if (n == 0) {
sfluxx(i,j,k,0) = 0.0;
}
if (species_pred_type_loc == pred_rhoprime_and_X) {
// edge states are rho' and X. To make the (rho X) flux,
// we need the edge state of rho0
sfluxx(i,j,k,comp) = umacx(i,j,k)*
(rho0_edgex(i,j,k)+sedgex(i,j,k,rho_comp))*sedgex(i,j,k,comp);
} else if (species_pred_type_loc == pred_rhoX) {
// edge states are (rho X)
sfluxx(i,j,k,comp) = umacx(i,j,k)*sedgex(i,j,k,comp);
} else if (species_pred_type_loc == pred_rho_and_X) {
// edge states are rho and X
sfluxx(i,j,k,comp) = umacx(i,j,k)*
sedgex(i,j,k,rho_comp)*sedgex(i,j,k,comp);
}
// compute the density fluxes by summing the species fluxes
sfluxx(i,j,k,0) += sfluxx(i,j,k,comp);
});
// y-direction
AMREX_PARALLEL_FOR_4D(ybx, num_comp, i, j, k, n, {
int comp = n + start_comp;
// reset density flux
if (n == 0) {
sfluxy(i,j,k,0) = 0.0;
}
if (species_pred_type_loc == pred_rhoprime_and_X) {
// edge states are rho' and X. To make the (rho X) flux,
// we need the edge state of rho0
sfluxy(i,j,k,comp) = vmac(i,j,k)*
(rho0_edgey(i,j,k)+sedgey(i,j,k,rho_comp))*sedgey(i,j,k,comp);
} else if (species_pred_type_loc == pred_rhoX) {
// edge states are (rho X)
sfluxy(i,j,k,comp) = vmac(i,j,k)*sedgey(i,j,k,comp);
} else if (species_pred_type_loc == pred_rho_and_X) {
// edge states are rho and X
sfluxy(i,j,k,comp) = vmac(i,j,k)*
sedgey(i,j,k,rho_comp)*sedgey(i,j,k,comp);
}
// compute the density fluxes by summing the species fluxes
sfluxy(i,j,k,0) += sfluxy(i,j,k,comp);
});
// z-direction
AMREX_PARALLEL_FOR_4D(zbx, num_comp, i, j, k, n, {
int comp = n + start_comp;
// reset density flux
if (n == 0) {
sfluxz(i,j,k,0) = 0.0;
}
if (species_pred_type_loc == pred_rhoprime_and_X) {
// edge states are rho' and X. To make the (rho X) flux,
// we need the edge state of rho0
sfluxz(i,j,k,comp) =
wmac(i,j,k)*(rho0_edgez(i,j,k)+sedgez(i,j,k,rho_comp))*sedgez(i,j,k,comp);
} else if (species_pred_type_loc == pred_rhoX) {
// ! edge states are (rho X)
sfluxz(i,j,k,comp) =
wmac(i,j,k)*sedgez(i,j,k,comp);
} else if (species_pred_type_loc == pred_rho_and_X) {
// ! edge state are rho and X
sfluxz(i,j,k,comp) =
wmac(i,j,k)*sedgez(i,j,k,rho_comp)*sedgez(i,j,k,comp);
}
// compute the density fluxes by summing the species fluxes
sfluxz(i,j,k,0) += sfluxz(i,j,k,comp);
});
} // end spherical
#endif
} // end MFIter loop
// increment or decrement the flux registers by area and time-weighted fluxes
// Note that the fluxes need to be scaled by dt and area
// In this example we are solving s_t = -div(+F)
// The fluxes contain, e.g., F_{i+1/2,j} = (s*u)_{i+1/2,j}
// Keep this in mind when considering the different sign convention for updating
// the flux registers from the coarse or fine grid perspective
// NOTE: the flux register associated with flux_reg_s[lev] is associated
// with the lev/lev-1 interface (and has grid spacing associated with lev-1)
if (reflux_type == 2) {
// Get the grid size
const Real* dx = geom[lev].CellSize();
// NOTE: areas are different in DIM=2 and DIM=3
#if (AMREX_SPACEDIM == 3)
const Real area[3] = {dx[1]*dx[2], dx[0]*dx[2], dx[0]*dx[1]};
#else
const Real area[2] = {dx[1], dx[0]};
#endif
if (flux_reg_s[lev+1])
{
for (int i = 0; i < AMREX_SPACEDIM; ++i) {
// update the lev+1/lev flux register (index lev+1)
flux_reg_s[lev+1]->CrseInit(sflux[lev][i],i,start_comp,start_comp,num_comp, -1.0*dt*area[i]);
// also include density flux
flux_reg_s[lev+1]->CrseInit(sflux[lev][i],i,Rho,Rho,1, -1.0*dt*area[i]);
}
}
if (flux_reg_s[lev])
{
for (int i = 0; i < AMREX_SPACEDIM; ++i) {
// update the lev/lev-1 flux register (index lev)
flux_reg_s[lev]->FineAdd(sflux[lev][i],i,start_comp,start_comp,num_comp, 1.0*dt*area[i]);
// also include density flux
flux_reg_s[lev]->FineAdd(sflux[lev][i],i,Rho,Rho,1, 1.0*dt*area[i]);
}
}
if (spherical == 0) {
// need edge_restrict for etarhoflux
}
}
} // end loop over levels
// average down fluxes
if (reflux_type == 1) {
AverageDownFaces(sflux);
}
// Something analogous to edge_restriction is done in UpdateScal()
}
void
Maestro::MakeRhoHFlux (const Vector<MultiFab>& state,
Vector<std::array< MultiFab, AMREX_SPACEDIM > >& sflux,
Vector<std::array< MultiFab, AMREX_SPACEDIM > >& sedge,
const Vector<std::array< MultiFab, AMREX_SPACEDIM > >& umac,
const Vector<std::array< MultiFab, AMREX_SPACEDIM > >& w0mac,
const RealVector& r0_old,
const RealVector& r0_edge_old,
const Vector<std::array< MultiFab, AMREX_SPACEDIM > >& r0mac_old,
const RealVector& r0_new,
const RealVector& r0_edge_new,
const Vector<std::array< MultiFab, AMREX_SPACEDIM > >& r0mac_new,
const RealVector& rh0_old,
const RealVector& rh0_edge_old,
const Vector<std::array< MultiFab, AMREX_SPACEDIM > >& rh0mac_old,
const RealVector& rh0_new,
const RealVector& rh0_edge_new,
const Vector<std::array< MultiFab, AMREX_SPACEDIM > >& rh0mac_new,
const Vector<std::array< MultiFab, AMREX_SPACEDIM > >& h0mac_old,
const Vector<std::array< MultiFab, AMREX_SPACEDIM > >& h0mac_new)
{
// timer for profiling
BL_PROFILE_VAR("Maestro::MakeRhoHFlux()", MakeRhoHFlux);
const bool have_h = enthalpy_pred_type == pred_h ||
enthalpy_pred_type == pred_T_then_h ||
enthalpy_pred_type == pred_Tprime_then_h;
#if (AMREX_SPACEDIM == 3)
const bool have_hprime = enthalpy_pred_type == pred_hprime;
#endif
const bool have_rhoh = enthalpy_pred_type == pred_rhoh;
const int rho_comp = Rho;
const int rhoh_comp = RhoH;
const int max_lev = max_radial_level;
const int species_pred_type_loc = species_pred_type;
const int enthalpy_pred_type_loc = enthalpy_pred_type;
for (int lev=0; lev<=finest_level; ++lev) {
#if (AMREX_SPACEDIM == 3)
MultiFab rho0mac_edgex, rho0mac_edgey, rho0mac_edgez;
MultiFab h0mac_edgex, h0mac_edgey, h0mac_edgez;
MultiFab rhoh0mac_edgex, rhoh0mac_edgey, rhoh0mac_edgez;
rho0mac_edgex.define(convert(grids[lev],nodal_flag_x), dmap[lev], 1, 0);
rho0mac_edgey.define(convert(grids[lev],nodal_flag_y), dmap[lev], 1, 0);
rho0mac_edgez.define(convert(grids[lev],nodal_flag_z), dmap[lev], 1, 0);
h0mac_edgex.define(convert(grids[lev],nodal_flag_x), dmap[lev], 1, 0);
h0mac_edgey.define(convert(grids[lev],nodal_flag_y), dmap[lev], 1, 0);
h0mac_edgez.define(convert(grids[lev],nodal_flag_z), dmap[lev], 1, 0);
rhoh0mac_edgex.define(convert(grids[lev],nodal_flag_x), dmap[lev], 1, 0);
rhoh0mac_edgey.define(convert(grids[lev],nodal_flag_y), dmap[lev], 1, 0);
rhoh0mac_edgez.define(convert(grids[lev],nodal_flag_z), dmap[lev], 1, 0);
rho0mac_edgex.setVal(0.);
rho0mac_edgey.setVal(0.);
rho0mac_edgez.setVal(0.);
h0mac_edgex.setVal(0.);
h0mac_edgey.setVal(0.);
h0mac_edgez.setVal(0.);
rhoh0mac_edgex.setVal(0.);
rhoh0mac_edgey.setVal(0.);
rhoh0mac_edgez.setVal(0.);
if (spherical == 1) {
if (use_exact_base_state) {
MultiFab::LinComb(rhoh0mac_edgex,0.5,rh0mac_old[lev][0],0,0.5,rh0mac_new[lev][0],0,0,1,0);
MultiFab::LinComb(rhoh0mac_edgey,0.5,rh0mac_old[lev][1],0,0.5,rh0mac_new[lev][1],0,0,1,0);
MultiFab::LinComb(rhoh0mac_edgez,0.5,rh0mac_old[lev][2],0,0.5,rh0mac_new[lev][2],0,0,1,0);
} else {
MultiFab::LinComb(rho0mac_edgex,0.5,r0mac_old[lev][0],0,0.5,r0mac_new[lev][0],0,0,1,0);
MultiFab::LinComb(rho0mac_edgey,0.5,r0mac_old[lev][1],0,0.5,r0mac_new[lev][1],0,0,1,0);
MultiFab::LinComb(rho0mac_edgez,0.5,r0mac_old[lev][2],0,0.5,r0mac_new[lev][2],0,0,1,0);
MultiFab::LinComb(h0mac_edgex,0.5,h0mac_old[lev][0],0,0.5,h0mac_new[lev][0],0,0,1,0);
MultiFab::LinComb(h0mac_edgey,0.5,h0mac_old[lev][1],0,0.5,h0mac_new[lev][1],0,0,1,0);
MultiFab::LinComb(h0mac_edgez,0.5,h0mac_old[lev][2],0,0.5,h0mac_new[lev][2],0,0,1,0);
}
}
#endif
// loop over boxes (make sure mfi takes a cell-centered multifab as an argument)
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MFIter mfi(state[lev], TilingIfNotGPU()); mfi.isValid(); ++mfi) {
// Get the index space of the valid region
const Box& xbx = mfi.nodaltilebox(0);
const Box& ybx = mfi.nodaltilebox(1);
#if (AMREX_SPACEDIM == 3)
const Box& zbx = mfi.nodaltilebox(2);
#endif
const Array4<Real> sedgex = sedge[lev][0].array(mfi);
const Array4<Real> sfluxx = sflux[lev][0].array(mfi);
const Array4<const Real> umacx = umac[lev][0].array(mfi);
const Array4<Real> sedgey = sedge[lev][1].array(mfi);
const Array4<Real> sfluxy = sflux[lev][1].array(mfi);
const Array4<const Real> vmac = umac[lev][1].array(mfi);
#if (AMREX_SPACEDIM == 3)
const Array4<Real> sedgez = sedge[lev][2].array(mfi);
const Array4<Real> sfluxz = sflux[lev][2].array(mfi);
const Array4<const Real> wmac = umac[lev][2].array(mfi);
#endif
const Real * AMREX_RESTRICT rho0_old_p = r0_old.dataPtr();
const Real * AMREX_RESTRICT rho0_new_p = r0_new.dataPtr();
const Real * AMREX_RESTRICT rhoh0_old_p = rh0_old.dataPtr();
const Real * AMREX_RESTRICT rhoh0_new_p = rh0_new.dataPtr();
const Real * AMREX_RESTRICT rho0_edge_old_p = r0_edge_old.dataPtr();
const Real * AMREX_RESTRICT rho0_edge_new_p = r0_edge_new.dataPtr();
const Real * AMREX_RESTRICT rhoh0_edge_old_p = rh0_edge_old.dataPtr();
const Real * AMREX_RESTRICT rhoh0_edge_new_p = rh0_edge_new.dataPtr();
#if (AMREX_SPACEDIM == 2)
AMREX_PARALLEL_FOR_3D(xbx, i, j, k, {
// create x-fluxes
if (have_h) {
// enthalpy edge state is h
if (species_pred_type_loc == pred_rhoprime_and_X) {
// density edge state is rho'
Real rho0_edge = 0.5*(rho0_old_p[lev+j*(max_lev+1)]+rho0_new_p[lev+j*(max_lev+1)]);
sfluxx(i,j,k,rhoh_comp) =
umacx(i,j,k)*(rho0_edge+sedgex(i,j,k,rho_comp))*sedgex(i,j,k,rhoh_comp);
} else if (species_pred_type_loc == pred_rho_and_X ||
species_pred_type_loc == pred_rhoX) {
// density edge state is rho
sfluxx(i,j,k,rhoh_comp) =
umacx(i,j,k)*sedgex(i,j,k,rho_comp)*sedgex(i,j,k,rhoh_comp);
}
} else if (have_rhoh) {
sfluxx(i,j,k,rhoh_comp) = umacx(i,j,k)*sedgex(i,j,k,rhoh_comp);
} else if (enthalpy_pred_type_loc == pred_rhohprime ||
enthalpy_pred_type_loc == pred_T_then_rhohprime) {
// ! enthalpy edge state is (rho h)'
Real rhoh0_edge = 0.5*(rhoh0_old_p[lev+j*(max_lev+1)]+rhoh0_new_p[lev+j*(max_lev+1)]);
sfluxx(i,j,k,rhoh_comp) = umacx(i,j,k)*(rhoh0_edge+sedgex(i,j,k,rhoh_comp));
}
});
AMREX_PARALLEL_FOR_3D(ybx, i, j, k, {
// create y-fluxes
if (have_h) {
// enthalpy edge state is h
if (species_pred_type_loc == pred_rhoprime_and_X) {
// density edge state is rho'
Real rho0_edge = 0.5*(rho0_edge_old_p[lev+j*(max_lev+1)]+rho0_edge_new_p[lev+j*(max_lev+1)]);
sfluxy(i,j,k,rhoh_comp) =
vmac(i,j,k)*(rho0_edge+sedgey(i,j,k,rho_comp))*sedgey(i,j,k,rhoh_comp);
} else if (species_pred_type_loc == pred_rho_and_X ||
species_pred_type_loc == pred_rhoX) {
// density edge state is rho
sfluxy(i,j,k,rhoh_comp) =
vmac(i,j,k)*sedgey(i,j,k,rho_comp)*sedgey(i,j,k,rhoh_comp);
}
} else if (have_rhoh) {
sfluxy(i,j,k,rhoh_comp) = vmac(i,j,k)*sedgey(i,j,k,rhoh_comp);
} else if (enthalpy_pred_type_loc == pred_rhohprime ||
enthalpy_pred_type_loc == pred_T_then_rhohprime) {
// enthalpy edge state is (rho h)'
Real rhoh0_edge = 0.5*(rhoh0_edge_old_p[lev+j*(max_lev+1)]+rhoh0_edge_new_p[lev+j*(max_lev+1)]);
sfluxy(i,j,k,rhoh_comp) = vmac(i,j,k)*(sedgey(i,j,k,rhoh_comp)+rhoh0_edge);
}
});
#elif (AMREX_SPACEDIM == 3)
if (spherical == 0) {
AMREX_PARALLEL_FOR_3D(xbx, i, j, k, {
// create x-fluxes
if (have_h) {
// enthalpy edge state is h
if (species_pred_type_loc == pred_rhoprime_and_X) {
// density edge state is rho'
Real rho0_edge = 0.5*(rho0_old_p[lev+k*(max_lev+1)]+rho0_new_p[lev+k*(max_lev+1)]);
sfluxx(i,j,k,rhoh_comp) =
umacx(i,j,k)*(rho0_edge+sedgex(i,j,k,rho_comp))*sedgex(i,j,k,rhoh_comp);
} else if (species_pred_type_loc == pred_rho_and_X ||
species_pred_type_loc == pred_rhoX) {
// density edge state is rho
sfluxx(i,j,k,rhoh_comp) =
umacx(i,j,k)*sedgex(i,j,k,rho_comp)*sedgex(i,j,k,rhoh_comp);
}
} else if (have_rhoh) {
sfluxx(i,j,k,rhoh_comp) = umacx(i,j,k)*sedgex(i,j,k,rhoh_comp);
} else if (enthalpy_pred_type_loc == pred_rhohprime ||
enthalpy_pred_type_loc == pred_T_then_rhohprime) {
// ! enthalpy edge state is (rho h)'
Real rhoh0_edge = 0.5*(rhoh0_old_p[lev+k*(max_lev+1)]+rhoh0_new_p[lev+k*(max_lev+1)]);
sfluxx(i,j,k,rhoh_comp) = umacx(i,j,k)*(rhoh0_edge+sedgex(i,j,k,rhoh_comp));
}
});
AMREX_PARALLEL_FOR_3D(ybx, i, j, k, {
// create y-fluxes
if (have_h) {
// enthalpy edge state is h
if (species_pred_type_loc == pred_rhoprime_and_X) {
// density edge state is rho'
Real rho0_edge = 0.5*(rho0_old_p[lev+k*(max_lev+1)]+rho0_new_p[lev+k*(max_lev+1)]);
sfluxy(i,j,k,rhoh_comp) =
vmac(i,j,k)*(rho0_edge+sedgey(i,j,k,rho_comp))*sedgey(i,j,k,rhoh_comp);
} else if (species_pred_type_loc == pred_rho_and_X ||
species_pred_type_loc == pred_rhoX) {
// density edge state is rho
sfluxy(i,j,k,rhoh_comp) =
vmac(i,j,k)*sedgey(i,j,k,rho_comp)*sedgey(i,j,k,rhoh_comp);
}
} else if (have_rhoh) {
sfluxy(i,j,k,rhoh_comp) = vmac(i,j,k)*sedgey(i,j,k,rhoh_comp);
} else if (enthalpy_pred_type_loc == pred_rhohprime ||
enthalpy_pred_type_loc == pred_T_then_rhohprime) {
// ! enthalpy edge state is (rho h)'
Real rhoh0_edge = 0.5*(rhoh0_old_p[lev+k*(max_lev+1)]+rhoh0_new_p[lev+k*(max_lev+1)]);
sfluxy(i,j,k,rhoh_comp) = vmac(i,j,k)*(rhoh0_edge+sedgey(i,j,k,rhoh_comp));
}
});
AMREX_PARALLEL_FOR_3D(zbx, i, j, k, {
// create z-fluxes
if (have_h) {
// enthalpy edge state is h
if (species_pred_type_loc == pred_rhoprime_and_X) {
// density edge state is rho'
Real rho0_edge = 0.5*(rho0_edge_old_p[lev+k*(max_lev+1)]+rho0_edge_new_p[lev+k*(max_lev+1)]);
sfluxz(i,j,k,rhoh_comp) =
wmac(i,j,k)*(rho0_edge+sedgez(i,j,k,rho_comp))*sedgez(i,j,k,rhoh_comp);
} else if (species_pred_type_loc == pred_rho_and_X ||
species_pred_type_loc == pred_rhoX) {
// density edge state is rho
sfluxz(i,j,k,rhoh_comp) =
wmac(i,j,k)*sedgez(i,j,k,rho_comp)*sedgez(i,j,k,rhoh_comp);
}
} else if (have_rhoh) {
sfluxz(i,j,k,rhoh_comp) = wmac(i,j,k)*sedgez(i,j,k,rhoh_comp);
} else if (enthalpy_pred_type_loc == pred_rhohprime ||
enthalpy_pred_type_loc == pred_T_then_rhohprime) {
// enthalpy edge state is (rho h)'
Real rhoh0_edge = 0.5*(rhoh0_edge_old_p[lev+k*(max_lev+1)]+rhoh0_edge_new_p[lev+k*(max_lev+1)]);
sfluxz(i,j,k,rhoh_comp) = wmac(i,j,k)*(sedgez(i,j,k,rhoh_comp)+rhoh0_edge);
}
});
} else {
if (use_exact_base_state) {
const Array4<const Real> rhoh0_edgex = rhoh0mac_edgex.array(mfi);
const Array4<const Real> rhoh0_edgey = rhoh0mac_edgey.array(mfi);
const Array4<const Real> rhoh0_edgez = rhoh0mac_edgez.array(mfi);
AMREX_PARALLEL_FOR_3D(xbx, i, j, k, {
if (have_h) {
// enthalpy edge state is h
// this is not supported on irregular-spaced base state
} else if (have_hprime) {
// enthalpy edge state is h'
// this is not supported on irregular-spaced base state
} else if (have_rhoh) {
sfluxx(i,j,k,rhoh_comp) = umacx(i,j,k)*sedgex(i,j,k,rhoh_comp);
} else {
// enthalpy edge state is (rho h)'
// Average (rho h) onto edges by averaging rho and h
// separately onto edges.
// (rho h)_edge = (rho h)' + rhoh_0
sfluxx(i,j,k,rhoh_comp) =
umacx(i,j,k)*(rhoh0_edgex(i,j,k)+sedgex(i,j,k,rhoh_comp));
}
});
AMREX_PARALLEL_FOR_3D(ybx, i, j, k, {
if (have_h) {
// enthalpy edge state is h
// this is not supported on irregular-spaced base state
} else if (have_hprime) {
// enthalpy edge state is h'
// this is not supported on irregular-spaced base state
} else if (have_rhoh) {
sfluxy(i,j,k,rhoh_comp) = vmac(i,j,k)*sedgey(i,j,k,rhoh_comp);
} else {
// enthalpy edge state is (rho h)'
// Average (rho h) onto edges by averaging rho and h
// separately onto edges.
// (rho h)_edge = (rho h)' + rhoh_0
sfluxy(i,j,k,rhoh_comp) =
vmac(i,j,k)*(rhoh0_edgey(i,j,k)+sedgey(i,j,k,rhoh_comp));
}
});
AMREX_PARALLEL_FOR_3D(zbx, i, j, k, {
if (have_h) {
// enthalpy edge state is h
// this is not supported on irregular-spaced base state
} else if (have_hprime) {
// enthalpy edge state is h'
// this is not supported on irregular-spaced base state
} else if (have_rhoh) {
sfluxz(i,j,k,rhoh_comp) = wmac(i,j,k)*sedgez(i,j,k,rhoh_comp);
} else {
// enthalpy edge state is (rho h)'
// Average (rho h) onto edges by averaging rho and h
// separately onto edges.
// (rho h)_edge = (rho h)' + rhoh_0
sfluxz(i,j,k,rhoh_comp) =
wmac(i,j,k)*(rhoh0_edgez(i,j,k)+sedgez(i,j,k,rhoh_comp));
}
});
} else {
const Array4<const Real> rho0_edgex = rho0mac_edgex.array(mfi);
const Array4<const Real> rho0_edgey = rho0mac_edgey.array(mfi);
const Array4<const Real> rho0_edgez = rho0mac_edgez.array(mfi);
const Array4<const Real> h0_edgex = h0mac_edgex.array(mfi);
const Array4<const Real> h0_edgey = h0mac_edgey.array(mfi);
const Array4<const Real> h0_edgez = h0mac_edgez.array(mfi);
AMREX_PARALLEL_FOR_3D(xbx, i, j, k, {
if (have_h) {
// enthalpy edge state is h
if (species_pred_type_loc == pred_rhoprime_and_X) {
// density edge state is rho'
sfluxx(i,j,k,rhoh_comp) = umacx(i,j,k) *
(rho0_edgex(i,j,k) + sedgex(i,j,k,rho_comp))*sedgex(i,j,k,rhoh_comp);
} else if (species_pred_type_loc == pred_rho_and_X ||
species_pred_type_loc == pred_rhoX) {
// density edge state is rho
sfluxx(i,j,k,rhoh_comp) = umacx(i,j,k) *
sedgex(i,j,k,rho_comp)*sedgex(i,j,k,rhoh_comp);
}
} else if (have_hprime) {
// enthalpy edge state is h'
if (species_pred_type_loc == pred_rhoprime_and_X) {
// density edge state is rho'
// (rho h)_edge = (h' + h_0) * (rho' + rho_0) where h0 is
// computed from (rho h)_0 / rho_0
// sfluxx = (umac(i,j,k)+w0macx(i,j,k)) * (rho h)_edge
sfluxx(i,j,k,rhoh_comp) = umacx(i,j,k) *
(sedgex(i,j,k,rho_comp)+rho0_edgex(i,j,k)) * (sedgex(i,j,k,rhoh_comp)+h0_edgex(i,j,k));
}
} else if (have_rhoh) {
sfluxx(i,j,k,rhoh_comp) = umacx(i,j,k)*sedgex(i,j,k,rhoh_comp);
} else {
// enthalpy edge state is (rho h)'
// Average (rho h) onto edges by averaging rho and h
// separately onto edges.
// (rho h)_edge = (rho h)' + (rho_0 * h_0)
// where h_0 is computed from (rho h)_0 / rho_0
sfluxx(i,j,k,rhoh_comp) =
umacx(i,j,k)*(rho0_edgex(i,j,k)*h0_edgex(i,j,k)+sedgex(i,j,k,rhoh_comp));
}
});
AMREX_PARALLEL_FOR_3D(ybx, i, j, k, {
if (have_h) {
// enthalpy edge state is h
if (species_pred_type_loc == pred_rhoprime_and_X) {
// density edge state is rho'
sfluxy(i,j,k,rhoh_comp) = vmac(i,j,k) *
(rho0_edgey(i,j,k) + sedgey(i,j,k,rho_comp))*sedgey(i,j,k,rhoh_comp);
} else if (species_pred_type_loc == pred_rho_and_X ||
species_pred_type_loc == pred_rhoX) {
// density edge state is rho
sfluxy(i,j,k,rhoh_comp) = vmac(i,j,k) *
sedgey(i,j,k,rho_comp)*sedgey(i,j,k,rhoh_comp);
}
} else if (have_hprime) {
// enthalpy edge state is h'
if (species_pred_type_loc == pred_rhoprime_and_X) {
// density edge state is rho'
// (rho h)_edge = (h' + h_0) * (rho' + rho_0) where h0 is
// computed from (rho h)_0 / rho_0
// sfluxx = (umac(i,j,k)+w0macx(i,j,k)) * (rho h)_edge
sfluxy(i,j,k,rhoh_comp) = vmac(i,j,k) *
(sedgey(i,j,k,rho_comp)+rho0_edgey(i,j,k)) * (sedgey(i,j,k,rhoh_comp)+h0_edgey(i,j,k));
}
} else if (have_rhoh) {
sfluxy(i,j,k,rhoh_comp) = vmac(i,j,k)*sedgey(i,j,k,rhoh_comp);
} else {
// enthalpy edge state is (rho h)'
// Average (rho h) onto edges by averaging rho and h
// separately onto edges.
// (rho h)_edge = (rho h)' + (rho_0 * h_0)
// where h_0 is computed from (rho h)_0 / rho_0
sfluxy(i,j,k,rhoh_comp) =
vmac(i,j,k)*(rho0_edgey(i,j,k)*h0_edgey(i,j,k)+sedgey(i,j,k,rhoh_comp));
}
});
AMREX_PARALLEL_FOR_3D(zbx, i, j, k, {
if (have_h) {
// enthalpy edge state is h
if (species_pred_type_loc == pred_rhoprime_and_X) {
// density edge state is rho'
sfluxz(i,j,k,rhoh_comp) = wmac(i,j,k) *
(rho0_edgez(i,j,k) + sedgez(i,j,k,rho_comp))*sedgez(i,j,k,rhoh_comp);
} else if (species_pred_type_loc == pred_rho_and_X ||
species_pred_type_loc == pred_rhoX) {
// density edge state is rho
sfluxz(i,j,k,rhoh_comp) = wmac(i,j,k) *
sedgez(i,j,k,rho_comp)*sedgez(i,j,k,rhoh_comp);
}
} else if (have_hprime) {
// enthalpy edge state is h'
if (species_pred_type_loc == pred_rhoprime_and_X) {
// density edge state is rho'
// (rho h)_edge = (h' + h_0) * (rho' + rho_0) where h0 is
// computed from (rho h)_0 / rho_0
// sfluxx = (umac(i,j,k)+w0macx(i,j,k)) * (rho h)_edge
sfluxz(i,j,k,rhoh_comp) = wmac(i,j,k) *
(sedgez(i,j,k,rho_comp)+rho0_edgez(i,j,k)) * (sedgez(i,j,k,rhoh_comp)+h0_edgez(i,j,k));
}
} else if (have_rhoh) {
sfluxz(i,j,k,rhoh_comp) = wmac(i,j,k)*sedgez(i,j,k,rhoh_comp);
} else {
// enthalpy edge state is (rho h)'
// Average (rho h) onto edges by averaging rho and h
// separately onto edges.
// (rho h)_edge = (rho h)' + (rho_0 * h_0)
// where h_0 is computed from (rho h)_0 / rho_0
sfluxz(i,j,k,rhoh_comp) =
wmac(i,j,k)*(rho0_edgez(i,j,k)*h0_edgez(i,j,k)+sedgez(i,j,k,rhoh_comp));
}
});
}
}
#endif
} // end MFIter loop
// increment or decrement the flux registers by area and time-weighted fluxes
// Note that the fluxes need to be scaled by dt and area
// In this example we are solving s_t = -div(+F)
// The fluxes contain, e.g., F_{i+1/2,j} = (s*u)_{i+1/2,j}
// Keep this in mind when considering the different sign convention for updating
// the flux registers from the coarse or fine grid perspective
// NOTE: the flux register associated with flux_reg_s[lev] is associated
// with the lev/lev-1 interface (and has grid spacing associated with lev-1)
if (reflux_type == 2) {
// Get the grid size
const Real* dx = geom[lev].CellSize();
// NOTE: areas are different in DIM=2 and DIM=3
#if (AMREX_SPACEDIM == 3)
const Real area[3] = {dx[1]*dx[2], dx[0]*dx[2], dx[0]*dx[1]};
#else
const Real area[2] = {dx[1], dx[0]};
#endif
if (flux_reg_s[lev+1])
{
for (int i = 0; i < AMREX_SPACEDIM; ++i) {
// update the lev+1/lev flux register (index lev+1)
flux_reg_s[lev+1]->CrseInit(sflux[lev][i],i,RhoH,RhoH,1, -1.0*dt*area[i]);
}
}
if (flux_reg_s[lev])
{
for (int i = 0; i < AMREX_SPACEDIM; ++i) {
// update the lev/lev-1 flux register (index lev)
flux_reg_s[lev]->FineAdd(sflux[lev][i],i,RhoH,RhoH,1, 1.0*dt*area[i]);
}
}
}
} // end loop over levels
if (reflux_type == 1) {
AverageDownFaces(sflux);
}
// Something analogous to edge_restriction is done in UpdateScal()
}
| 47.979787 | 123 | 0.473271 | XinlongSBU |
3ef9c8e4e0b641fdbbcea3006950837a1fd633e2 | 714 | cpp | C++ | codes/c++/101.cpp | YuanweiZHANG/Leetcode | 14a083528431bc65ada8f8265a5ef9d0fae40ecd | [
"MIT"
] | null | null | null | codes/c++/101.cpp | YuanweiZHANG/Leetcode | 14a083528431bc65ada8f8265a5ef9d0fae40ecd | [
"MIT"
] | null | null | null | codes/c++/101.cpp | YuanweiZHANG/Leetcode | 14a083528431bc65ada8f8265a5ef9d0fae40ecd | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <stack>
using namespace std;
/**
* 2020-04-16
* Veronica
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if (!root)
return true;
return isSymmetricCore(root->left, root->right);
}
bool isSymmetricCore(TreeNode* p, TreeNode* q) {
if (!p && !q)
return true;
if (!p || !q || p->val != q->val)
return false;
return isSymmetricCore(p->left, q->right) && isSymmetricCore(p->right, q->left);
}
};
int main() {
Solution solution;
TreeNode* root = NULL;
cout << solution.isSymmetric(root) << endl;
return 0;
} | 17.85 | 82 | 0.644258 | YuanweiZHANG |
41017fb2f376efeecdc4633c5b85a459ea5687d9 | 9,873 | cpp | C++ | 3rdparty/etl/src/ETIndexHandler.cpp | Osumi-Akari/energytycoon | 25d18a0ee4a9f8833e678af297734602918a92e9 | [
"Unlicense"
] | null | null | null | 3rdparty/etl/src/ETIndexHandler.cpp | Osumi-Akari/energytycoon | 25d18a0ee4a9f8833e678af297734602918a92e9 | [
"Unlicense"
] | null | null | null | 3rdparty/etl/src/ETIndexHandler.cpp | Osumi-Akari/energytycoon | 25d18a0ee4a9f8833e678af297734602918a92e9 | [
"Unlicense"
] | null | null | null | /********************************************************************************
EDITABLE TERRAIN LIBRARY v3 for Ogre
Copyright (c) 2008 Holger Frydrych <frydrych@oddbeat.de>
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.
********************************************************************************/
#include "ETCommon.h"
#include "ETIndexHandler.h"
#include <OgreVertexIndexData.h>
#include <OgreHardwareBufferManager.h>
#include <OgreException.h>
#include <cassert>
using namespace Ogre;
using namespace std;
namespace ET
{
IndexHandler::IndexHandler(unsigned int sizeX, unsigned int sizeZ)
: mSizeX(sizeX), mSizeZ(sizeZ), mUse32Bit(false)
{
// determine maximal level of detail possible with the given sizes
findMaxLOD();
// determine whether our data can fit into 16bit index buffers or not
unsigned int numVertices = sizeX*sizeZ;
if (numVertices > 65536)
mUse32Bit = true;
}
IndexHandler::~IndexHandler()
{
for (size_t i = 0; i < mIndexBuffers.size(); ++i)
{
for (IndexMap::iterator it = mIndexBuffers[i].begin(); it != mIndexBuffers[i].end(); ++it)
delete it->second;
}
}
void IndexHandler::findMaxLOD()
{
// determine max LOD in X dimension
unsigned int maxLODX = (mSizeX != 1 ? 32 : 0);
for (unsigned int n = 1; n < 32; ++n)
{
unsigned int size = (1 << n) + 1;
if (size == mSizeX)
{
maxLODX = n;
break;
}
}
// determine max LOD in Z dimension
unsigned int maxLODZ = (mSizeZ != 1 ? 32 : 0);
for (unsigned int n = 1; n < 32; ++n)
{
unsigned int size = (1 << n) + 1;
if (size == mSizeZ)
{
maxLODZ = n;
break;
}
}
if (maxLODX == 32 || maxLODZ == 32)
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Dimensions must satisfy (2^n)+1", "ET::IndexHandler::findMaxLOD");
mMaxLOD = min(maxLODX, maxLODZ);
mIndexBuffers = LODArray(mMaxLOD);
}
IndexData* IndexHandler::getIndexData(unsigned int ownLOD, unsigned int northLOD,
unsigned int eastLOD, unsigned int southLOD, unsigned int westLOD)
{
assert(ownLOD < mIndexBuffers.size() && "Requested unexpected LOD");
// derive map index for the neighbour's LOD constitution
// only LODs higher than the requesting patch's LOD are of interest
if (northLOD <= ownLOD)
northLOD = 0;
if (eastLOD <= ownLOD)
eastLOD = 0;
if (southLOD <= ownLOD)
southLOD = 0;
if (westLOD <= ownLOD)
westLOD = 0;
unsigned int mapIndex = (northLOD<<24) | (eastLOD<<16) | (southLOD<<8) | westLOD;
IndexData* data = 0;
IndexMap::iterator it = mIndexBuffers[ownLOD].find(mapIndex);
if (it != mIndexBuffers[ownLOD].end())
{
// already created index data for this occasion
data = it->second;
}
else
{
if (mUse32Bit)
data = createIndexData<Ogre::uint32>(ownLOD, northLOD, eastLOD, southLOD, westLOD);
else
data = createIndexData<Ogre::uint16>(ownLOD, northLOD, eastLOD, southLOD, westLOD);
mIndexBuffers[ownLOD].insert(IndexMap::value_type(mapIndex, data));
}
return data;
}
template<typename IndexType>
IndexData* IndexHandler::createIndexData(unsigned int ownLOD, unsigned int northLOD,
unsigned int eastLOD, unsigned int southLOD, unsigned int westLOD)
{
// for a chosen LOD n, only the (2^n)th vertices are included in the index buffer
unsigned int step = 1 << ownLOD;
// determine begin and end points in X and Z direction
unsigned int startX = (westLOD ? step : 0);
unsigned int startZ = (northLOD ? step : 0);
unsigned int endX = mSizeX - 1 - (eastLOD ? step : 0);
unsigned int endZ = mSizeZ - 1 - (southLOD ? step : 0);
// determine the necessary precision of the index buffers
HardwareIndexBuffer::IndexType it =
(mUse32Bit ? HardwareIndexBuffer::IT_32BIT : HardwareIndexBuffer::IT_16BIT);
// estimate index buffer length
size_t length = (mSizeX/step) * (mSizeZ/step) * 8;
// create index data
IndexData* indexData = new IndexData;
indexData->indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer(
it, length, HardwareBuffer::HBU_STATIC_WRITE_ONLY);
IndexType* pIdx = static_cast<IndexType*>(indexData->indexBuffer->lock(
0, indexData->indexBuffer->getSizeInBytes(), HardwareBuffer::HBL_DISCARD));
unsigned int numIndexes = 0;
// go over all the vertices and combine them to triangles in trilist format.
// skip the borders if stitching is necessary
for (unsigned int j = startZ; j < endZ; j += step)
{
for (unsigned int i = startX; i < endX; i += step)
{
*pIdx++ = index<IndexType>(i, j);
*pIdx++ = index<IndexType>(i, j+step);
*pIdx++ = index<IndexType>(i+step, j);
*pIdx++ = index<IndexType>(i, j+step);
*pIdx++ = index<IndexType>(i+step, j+step);
*pIdx++ = index<IndexType>(i+step, j);
numIndexes += 6;
}
}
// stitch edges to neighbours with higher lod where needed
if (northLOD > 0)
numIndexes += stitchBorder<IndexType>(DIR_NORTH, ownLOD, northLOD, westLOD > 0, eastLOD > 0, &pIdx);
if (eastLOD > 0)
numIndexes += stitchBorder<IndexType>(DIR_EAST, ownLOD, eastLOD, northLOD > 0, southLOD > 0, &pIdx);
if (southLOD > 0)
numIndexes += stitchBorder<IndexType>(DIR_SOUTH, ownLOD, southLOD, eastLOD > 0, westLOD > 0, &pIdx);
if (westLOD > 0)
numIndexes += stitchBorder<IndexType>(DIR_WEST, ownLOD, westLOD, southLOD > 0, northLOD > 0, &pIdx);
indexData->indexBuffer->unlock();
indexData->indexCount = numIndexes;
indexData->indexStart = 0;
return indexData;
}
template<typename IndexType>
int IndexHandler::stitchBorder(int direction, unsigned int hiLOD, unsigned int loLOD, bool omitFirstTri,
bool omitLastTri, IndexType** ppIdx)
{
assert(loLOD > hiLOD);
// code taken from Ogre's TSM
// TODO: Rewrite this!!
IndexType* pIdx = *ppIdx;
int step = 1 << hiLOD;
int superstep = 1 << loLOD;
int halfsuperstep = superstep >> 1;
int rowstep = 0;
size_t startx = 0, starty = 0, endx = 0;
bool horizontal = false;
switch (direction)
{
case DIR_NORTH:
startx = starty = 0;
endx = mSizeX - 1;
rowstep = step;
horizontal = true;
break;
case DIR_SOUTH:
startx = mSizeX-1;
starty = mSizeZ-1;
endx = 0;
rowstep = -step;
step = -step;
superstep = -superstep;
halfsuperstep = -halfsuperstep;
horizontal = true;
break;
case DIR_EAST:
startx = 0;
endx = mSizeZ-1;
starty = mSizeX-1;
rowstep = -step;
horizontal = false;
break;
case DIR_WEST:
startx = mSizeZ-1;
endx = 0;
starty = 0;
rowstep = step;
step = -step;
superstep = -superstep;
halfsuperstep = -halfsuperstep;
horizontal = false;
break;
}
unsigned int numIndexes = 0;
for (size_t j = startx; j != endx; j += superstep)
{
int k;
for (k = 0; k != halfsuperstep; k += step)
{
size_t jk = j + k;
if (j != startx || k != 0 || !omitFirstTri)
{
if (horizontal)
{
*pIdx++ = index<IndexType>(j, starty);
*pIdx++ = index<IndexType>(jk, starty + rowstep);
*pIdx++ = index<IndexType>(jk + step, starty + rowstep);
}
else
{
*pIdx++ = index<IndexType>(starty, j);
*pIdx++ = index<IndexType>(starty+rowstep, jk);
*pIdx++ = index<IndexType>(starty+rowstep, jk+step);
}
numIndexes += 3;
}
}
if (horizontal)
{
*pIdx++ = index<IndexType>(j, starty);
*pIdx++ = index<IndexType>(j+halfsuperstep, starty+rowstep);
*pIdx++ = index<IndexType>(j+superstep, starty);
}
else
{
*pIdx++ = index<IndexType>(starty, j);
*pIdx++ = index<IndexType>(starty+rowstep, j+halfsuperstep);
*pIdx++ = index<IndexType>(starty, j+superstep);
}
numIndexes += 3;
for (k = halfsuperstep; k != superstep; k += step)
{
size_t jk = j + k;
if (j != endx - superstep || k != superstep - step || !omitLastTri)
{
if (horizontal)
{
*pIdx++ = index<IndexType>(j+superstep, starty);
*pIdx++ = index<IndexType>(jk, starty+rowstep);
*pIdx++ = index<IndexType>(jk+step, starty+rowstep);
}
else
{
*pIdx++ = index<IndexType>(starty, j+superstep);
*pIdx++ = index<IndexType>(starty+rowstep, jk);
*pIdx++ = index<IndexType>(starty+rowstep, jk+step);
}
numIndexes += 3;
}
}
}
*ppIdx = pIdx;
return numIndexes;
}
template <typename IndexType>
IndexType IndexHandler::index(size_t x, size_t z) const
{
return (IndexType) (x + z * mSizeX);
}
}
| 30.472222 | 115 | 0.599514 | Osumi-Akari |
4102fab03bd88530e38bf7a60c1dcace162208ae | 205 | cc | C++ | external/hacked_packages/pytest-cpp-0.4/tests/acceptance/googletest-samples/main.cc | willsheffler/rosette | 199fdbf18e9fceb5324cd7bae9b47c3feb47af73 | [
"Apache-2.0"
] | null | null | null | external/hacked_packages/pytest-cpp-0.4/tests/acceptance/googletest-samples/main.cc | willsheffler/rosette | 199fdbf18e9fceb5324cd7bae9b47c3feb47af73 | [
"Apache-2.0"
] | 1 | 2015-02-24T13:15:29.000Z | 2015-02-26T23:45:19.000Z | external/hacked_packages/pytest-cpp-0.4/tests/acceptance/googletest-samples/main.cc | willsheffler/rosette | 199fdbf18e9fceb5324cd7bae9b47c3feb47af73 | [
"Apache-2.0"
] | null | null | null | // compiled with samples which don't declare their own main() function
#include "gtest/gtest.h"
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | 25.625 | 70 | 0.697561 | willsheffler |
4103417d514d4e5f5245d77094c8b1622d8288fc | 10,508 | cpp | C++ | afj-assignment-04/lib/grammar.cpp | Kyslik/afj-assignment-04 | 026c8408bb1284c535f04bed91fe32d894ca6ef1 | [
"MIT"
] | null | null | null | afj-assignment-04/lib/grammar.cpp | Kyslik/afj-assignment-04 | 026c8408bb1284c535f04bed91fe32d894ca6ef1 | [
"MIT"
] | null | null | null | afj-assignment-04/lib/grammar.cpp | Kyslik/afj-assignment-04 | 026c8408bb1284c535f04bed91fe32d894ca6ef1 | [
"MIT"
] | null | null | null | //
// grammar.cpp
// afj-assignment-04
//
// Created by Martin Kiesel on 08/05/16.
// Copyright © 2016 Martin Kiesel. All rights reserved.
//
#include <iostream>
#include <fstream>
#include <sstream>
#include "grammar.hpp"
namespace afj_4
{
namespace grammar
{
void Grammar::addTerminal(const std::string &terminal)
{
if (terminal.length() == 1 && _nonterminals.find(terminal) == _nonterminals.end())
_terminals.insert(terminal);
if (terminal.empty())
_terminals.insert(EPSILON);
if (terminal.length() != 1)
{
for (uint i = 0; i < terminal.length(); i++)
{
std::string str("");
str += terminal.at(i);
addTerminal(str);
}
}
}
void Grammar::displayFirst()
{
displayTerminalSet(_firsts);
}
bool Grammar::insertInFirst(types::TerminalSet &terminal_set, const types::Terminal &terminal, const std::string &in)
{
if(!insertInTerminalSet(terminal_set, terminal, in)) return false;
std::cout << "inserting in FIRST(" << in << "): " << terminal.value << std::endl;
return true;
}
void Grammar::computeFirst()
{
for (const auto &terminal : _terminals)
{
if (terminal == EPSILON) continue;
_firsts[terminal] = types::TerminalSet({types::Terminal(terminal, false)});
}
for (const auto &rule : _rules)
{
if (_firsts.find(rule.left.value) == _firsts.end())
_firsts[rule.left.value] = types::TerminalSet();
if (rule.right.unionals.size() == 0 ||
rule.right.unionals[0].type == NONTERMINAL) continue;
auto &terminal_set = _firsts[rule.left.value];
insertInFirst(terminal_set, rule.right.unionals[0].terminal, rule.left.value);
}
while (true)
{
bool changed = false;
for (const auto &rule : _rules)
{
if (rule.right.unionals.size() == 0 ||
rule.right.unionals[0].type == TERMINAL) continue;
std::cout << "rule: " << rule.left.value << " -> " << rule.right.representation << std::endl;
auto &terminal_set = _firsts[rule.left.value];
size_t terminal_set_size = terminal_set.size();
{
auto unional = rule.right.unionals[0];
if (unional.type == TERMINAL && !unional.terminal.is_epsilon)
insertInFirst(terminal_set, unional.terminal, rule.left.value);
if (unional.type == NONTERMINAL)
for (const auto &first : _firsts[unional.nonterminal.value])
if (!first.is_epsilon)
insertInFirst(terminal_set, first, rule.left.value);
}
uint i = 0;
while(i < rule.right.unionals.size() - 1 &&
rule.right.unionals[i].type == NONTERMINAL &&
_firsts[rule.right.unionals[i].nonterminal.value].find(types::Terminal(EPSILON, true)) != _firsts[rule.right.unionals[i].nonterminal.value].end())
{
{
auto unional = rule.right.unionals[i+1];
if (unional.type == TERMINAL && !unional.terminal.is_epsilon)
insertInFirst(terminal_set, unional.terminal, rule.left.value);
if (unional.type == NONTERMINAL)
for (const auto &first : _firsts[unional.nonterminal.value])
if (!first.is_epsilon)
insertInFirst(terminal_set, first, rule.left.value);
}
i++;
}
if(i == rule.right.unionals.size() &&
_firsts[rule.right.unionals[i].nonterminal.value].find(EPSILON) != _firsts[rule.right.unionals[i].nonterminal.value].end())
insertInFirst(terminal_set, types::Terminal(EPSILON, true), rule.left.value);
if (!changed && terminal_set_size != terminal_set.size()) changed = true;
}
if (!changed) break;
}
}
void Grammar::displayFollow()
{
displayTerminalSet(_follows);
}
bool Grammar::insertInFollow(types::TerminalSet &terminal_set, const types::Terminal &terminal, const std::string &in)
{
if (!insertInTerminalSet(terminal_set, terminal, in)) return false;
std::cout << "inserting in FOLLOW(" << in << "): " << terminal.value << std::endl;
return true;
}
void Grammar::computeFollow()
{
insertInFollow(_follows[_rules[0].left.value], types::Terminal(EPSILON, true), _rules[0].left.value);
while(true)
{
bool changed = false;
for (const auto &rule : _rules)
{
auto &terminal_set = _follows[rule.left.value];
for (uint i = 0; i < rule.right.unionals.size(); i++)
{
auto unional = rule.right.unionals[i];
if (unional.type == TERMINAL) continue;
std::string nonterminal = unional.nonterminal.value;
size_t nonterminal_set_size = _follows[nonterminal].size();
if (i + 1 < rule.right.unionals.size())
{
std::string next_unional_value = rule.right.unionals[i + 1].getValue();
for (const auto &first : _firsts[next_unional_value])
if (!first.is_epsilon)
insertInFollow(_follows[nonterminal], first, nonterminal);
else
for (const auto &f : _follows[next_unional_value])
insertInFollow(_follows[nonterminal], f, nonterminal);
if (_firsts[next_unional_value].find(types::Terminal(EPSILON, true)) == _firsts[nonterminal].end())
for (const auto &terminal : terminal_set)
insertInFollow(_follows[nonterminal], terminal, nonterminal);
}
else
for (const auto &terminal : terminal_set)
insertInFollow(_follows[nonterminal], terminal, nonterminal);
if (!changed &&
(nonterminal_set_size != _follows[nonterminal].size())) changed = true;
}
}
if (!changed) break;
}
}
bool Grammar::insertInTerminalSet(types::TerminalSet &terminal_set, const types::Terminal &terminal, const std::string &in)
{
if (terminal_set.find(terminal) != terminal_set.end()) return false;
terminal_set.insert(terminal);
return true;
}
void Grammar::displayTerminalSet(const types::StringToTerminalSetMap &terminal_set_map)
{
for (const auto &set : terminal_set_map)
{
std::cout << set.first << ": ";
for (const auto &item : set.second)
std::cout << item.value << " ";
std::cout << std::endl << std::endl;
}
}
bool Grammar::computeDecompositionTable()
{
for (const auto &nonterminal : _nonterminals)
for (const auto &terminal : _terminals)
_decomposition_table[nonterminal][terminal] = -1;
for (uint i = 0; i < _rules.size(); i++)
{
std::string nonterminal = _rules[i].left.value;
bool has_epsilon = false;
for (const auto &unional : _rules[i].right.unionals)
{
if (has_epsilon) break;
has_epsilon = unional.isEpsilon();
}
if (has_epsilon)
{
for (const auto &follow : _follows[nonterminal])
{
if (_decomposition_table[nonterminal][follow.value] == i) continue;
if (_decomposition_table[nonterminal][follow.value] == -1)
_decomposition_table[nonterminal][follow.value] = i;
else
return false;
}
}
else
{
for (const auto &first : _firsts[nonterminal])
{
if (_decomposition_table[nonterminal][first.value] == i) continue;
if (first.is_epsilon) continue;
if (_decomposition_table[nonterminal][first.value] == -1)
_decomposition_table[nonterminal][first.value] = i;
else
return false;
}
}
}
return true;
}
void Grammar::writeToFile(const std::string &output)
{
std::cout << "Writing to file \"" << output << "\"..." << std::endl;
std::ofstream out_file;
out_file.open(output);
out_file << "FIRST:" << std::endl;
for (const auto &set : _firsts)
{
std::string firsts;
firsts += set.first + ": ";
for (const auto &item : set.second)
firsts += item.value + ", ";
firsts.erase(firsts.end() - 2, firsts.end());
out_file << firsts << std::endl;
}
out_file << std::endl;
out_file << "FOLLOW:" << std::endl;
for (const auto &set : _follows)
{
std::string follows;
follows += set.first + ": ";
for (const auto &item : set.second)
follows += item.value + ", ";
follows.erase(follows.end() - 2, follows.end());
out_file << follows << std::endl;
}
out_file << std::endl;
for (const auto &nonterminal_row : _decomposition_table)
{
out_file << nonterminal_row.first << ": ";
for (const auto &rule : nonterminal_row.second)
{
if (rule.second == -1)
out_file << rule.first << " - /, ";
else
out_file << rule.first << " - " << rule.second+1 << ", ";
}
out_file << std::endl;
}
out_file.close();
}
}
} | 36.234483 | 168 | 0.501808 | Kyslik |
41034f208c4e9edf30b1918e51eed0132f53fd42 | 1,275 | cpp | C++ | sdf-net/lib/submodules/libigl/tutorial/604_Triangle/main.cpp | hardikk13/nglod | 6c6c66ce1b39c5a3515cafc290ec903ae90b506e | [
"MIT"
] | null | null | null | sdf-net/lib/submodules/libigl/tutorial/604_Triangle/main.cpp | hardikk13/nglod | 6c6c66ce1b39c5a3515cafc290ec903ae90b506e | [
"MIT"
] | null | null | null | sdf-net/lib/submodules/libigl/tutorial/604_Triangle/main.cpp | hardikk13/nglod | 6c6c66ce1b39c5a3515cafc290ec903ae90b506e | [
"MIT"
] | null | null | null | #include <igl/opengl/glfw/Viewer.h>
#include <igl/triangle/triangulate.h>
// Input polygon
Eigen::MatrixXd V;
Eigen::MatrixXi E;
Eigen::MatrixXd H;
// Triangulated interior
Eigen::MatrixXd V2;
Eigen::MatrixXi F2;
int main(int argc, char *argv[])
{
using namespace Eigen;
using namespace std;
// Create the boundary of a square
V.resize(8,2);
E.resize(8,2);
H.resize(1,2);
// create two squares, one with edge length of 4,
// one with edge length of 2
// both centered at origin
V << -1,-1, 1,-1, 1,1, -1, 1,
-2,-2, 2,-2, 2,2, -2, 2;
// add the edges of the squares
E << 0,1, 1,2, 2,3, 3,0,
4,5, 5,6, 6,7, 7,4;
// specify a point that is inside a closed shape
// where we do not want triangulation to happen
H << 0,0;
// Triangulate the interior
// a0.005 means that the area of each triangle should
// not be greater than 0.005
// q means that no angles will be smaller than 20 degrees
// for a detailed set of commands please refer to:
// https://www.cs.cmu.edu/~quake/triangle.switch.html
igl::triangle::triangulate(V,E,H,"a0.005q",V2,F2);
// Plot the generated mesh
igl::opengl::glfw::Viewer viewer;
viewer.data().set_mesh(V2,F2);
viewer.launch();
}
| 26.020408 | 60 | 0.627451 | hardikk13 |
4105e6b6718b235b9d597ee392f076af3ff10654 | 922 | cpp | C++ | src/ctap/reset.cpp | uru-card/uru-card | 0d20f8dd3bd5db3781ac0c6535744f77af6dfda2 | [
"Apache-2.0"
] | 98 | 2020-06-29T11:01:45.000Z | 2022-02-20T06:50:31.000Z | src/ctap/reset.cpp | uru-card/uru-card | 0d20f8dd3bd5db3781ac0c6535744f77af6dfda2 | [
"Apache-2.0"
] | 9 | 2020-06-29T11:22:19.000Z | 2022-03-16T11:06:12.000Z | src/ctap/reset.cpp | uru-card/uru-card | 0d20f8dd3bd5db3781ac0c6535744f77af6dfda2 | [
"Apache-2.0"
] | 1 | 2021-07-29T16:12:54.000Z | 2021-07-29T16:12:54.000Z | #include <Arduino.h>
#include <YACL.h>
#include "fido2/ctap/ctap.h"
#include "util/util.h"
namespace FIDO2
{
namespace CTAP
{
namespace Request
{
CommandCode Reset::getCommandCode() const
{
return authenticatorReset;
}
Status parseReset(const CBOR &cbor, std::unique_ptr<Command> &request)
{
request = std::unique_ptr<Reset>(new Reset());
return CTAP2_OK;
}
} // namespace Request
namespace Response
{
CommandCode Reset::getCommandCode() const
{
return authenticatorReset;
}
Status encode(const Reset *response, std::unique_ptr<CBOR> &cbor)
{
return CTAP2_OK;
}
} // namespace Response
} // namespace CTAP
} // namespace FIDO2 | 22.487805 | 82 | 0.509761 | uru-card |
4108eb22a65ef908199fdba979c870b54251f16f | 304 | cpp | C++ | 10- Recursion & Backtracking/LinearSearch.cpp | ShreyashRoyzada/C-plus-plus-Algorithms | 9db89faf0a9b9e636aece3e7289f21ab6a1e3748 | [
"MIT"
] | 21 | 2020-10-03T03:57:19.000Z | 2022-03-25T22:41:05.000Z | 10- Recursion & Backtracking/LinearSearch.cpp | ShreyashRoyzada/C-plus-plus-Algorithms | 9db89faf0a9b9e636aece3e7289f21ab6a1e3748 | [
"MIT"
] | 40 | 2020-10-02T07:02:34.000Z | 2021-10-30T16:00:07.000Z | 10- Recursion & Backtracking/LinearSearch.cpp | ShreyashRoyzada/C-plus-plus-Algorithms | 9db89faf0a9b9e636aece3e7289f21ab6a1e3748 | [
"MIT"
] | 90 | 2020-10-02T07:06:22.000Z | 2022-03-25T22:41:17.000Z | #include<iostream>
using namespace std;
int linearSearch(int *a, int i, int key, int n){
if(i==n){
return -1;
}
if(i==key){
return i;
}
return linearSearch(a, i+1, key,n);
}
int main()
{
int a[]= {1,2,3,5,4,8};
int n= sizeof(a)/sizeof(int);
int key;cin>>key;
cout<<linearSearch(a,0,key,n);
} | 16.888889 | 48 | 0.608553 | ShreyashRoyzada |
41098bd3b922147e0b075bba069846dcba4d6dfc | 1,563 | hpp | C++ | src/netspeak/model/SearchResult.hpp | netspeak/netspeak4-application-cpp | b322c19e22c71f39be95b37b14f43daab1cb9024 | [
"MIT"
] | null | null | null | src/netspeak/model/SearchResult.hpp | netspeak/netspeak4-application-cpp | b322c19e22c71f39be95b37b14f43daab1cb9024 | [
"MIT"
] | 7 | 2020-06-02T18:37:02.000Z | 2021-02-17T11:04:22.000Z | src/netspeak/model/SearchResult.hpp | netspeak/netspeak4-application-ngrams | b322c19e22c71f39be95b37b14f43daab1cb9024 | [
"MIT"
] | null | null | null | #ifndef NETSPEAK_MODEL_SEARCH_RESULT_HPP
#define NETSPEAK_MODEL_SEARCH_RESULT_HPP
#include <memory>
#include <vector>
#include "netspeak/model/NormQuery.hpp"
#include "netspeak/model/Phrase.hpp"
namespace netspeak {
namespace model {
class SearchResult {
public:
struct Item {
std::shared_ptr<const NormQuery> query;
Phrase phrase;
Item() = delete;
Item(const std::shared_ptr<const NormQuery>& query, const Phrase& phrase)
: query(query), phrase(phrase) {}
inline bool operator==(const Item& rhs) const {
return phrase == rhs.phrase;
}
inline bool operator!=(const Item& rhs) const {
return phrase != rhs.phrase;
}
inline bool operator<(const Item& rhs) const {
return phrase < rhs.phrase;
}
inline bool operator<=(const Item& rhs) const {
return phrase <= rhs.phrase;
}
inline bool operator>(const Item& rhs) const {
return phrase > rhs.phrase;
}
inline bool operator>=(const Item& rhs) const {
return phrase >= rhs.phrase;
}
};
private:
std::vector<Item> phrases_;
std::vector<std::string> unknown_words_;
public:
SearchResult(){};
SearchResult(const SearchResult&) = delete;
std::vector<Item>& phrases() {
return phrases_;
}
const std::vector<Item>& phrases() const {
return phrases_;
}
std::vector<std::string>& unknown_words() {
return unknown_words_;
}
const std::vector<std::string>& unknown_words() const {
return unknown_words_;
}
};
} // namespace model
} // namespace netspeak
#endif
| 21.121622 | 77 | 0.662828 | netspeak |
410d1fd34142e08ac378f424bfaa92ae24488562 | 10,161 | cpp | C++ | OpenEXR/IlmImfUtil/ImfFlatImageIO.cpp | Lord-Kamina/openexr | cb16232387a8dabf75797ff8d3015594a7a87abe | [
"BSD-3-Clause"
] | 107 | 2015-01-27T22:01:49.000Z | 2021-12-27T07:44:25.000Z | OpenEXR/IlmImfUtil/ImfFlatImageIO.cpp | Lord-Kamina/openexr | cb16232387a8dabf75797ff8d3015594a7a87abe | [
"BSD-3-Clause"
] | 2 | 2015-10-09T19:13:25.000Z | 2018-12-25T17:16:54.000Z | OpenEXR/IlmImfUtil/ImfFlatImageIO.cpp | Lord-Kamina/openexr | cb16232387a8dabf75797ff8d3015594a7a87abe | [
"BSD-3-Clause"
] | 17 | 2015-03-12T19:11:30.000Z | 2020-11-30T15:51:23.000Z | ///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------
//
// OpenEXR file I/O for flat images.
//
//----------------------------------------------------------------------------
#include "ImfFlatImageIO.h"
#include <ImfInputFile.h>
#include <ImfOutputFile.h>
#include <ImfTiledInputFile.h>
#include <ImfTiledOutputFile.h>
#include <ImfHeader.h>
#include <ImfChannelList.h>
#include <ImfTestFile.h>
#include <Iex.h>
#include <cstring>
#include <cassert>
using namespace IMATH_NAMESPACE;
using namespace IEX_NAMESPACE;
using namespace std;
OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER
void
saveFlatImage
(const string &fileName,
const Header &hdr,
const FlatImage &img,
DataWindowSource dws)
{
if (img.levelMode() != ONE_LEVEL || hdr.hasTileDescription())
saveFlatTiledImage (fileName, hdr, img, dws);
else
saveFlatScanLineImage (fileName, hdr, img, dws);
}
void
saveFlatImage
(const string &fileName,
const FlatImage &img)
{
Header hdr;
hdr.displayWindow() = img.dataWindow();
saveFlatImage (fileName, hdr, img);
}
void
loadFlatImage
(const string &fileName,
Header &hdr,
FlatImage &img)
{
bool tiled, deep, multiPart;
if (!isOpenExrFile (fileName.c_str(), tiled, deep, multiPart))
{
THROW (ArgExc, "Cannot load image file " << fileName << ". "
"The file is not an OpenEXR file.");
}
if (multiPart)
{
THROW (ArgExc, "Cannot load image file " << fileName << ". "
"Multi-part file loading is not supported.");
}
if (deep)
{
THROW (ArgExc, "Cannot load deep image file " << fileName << " "
"as a flat image.");
}
if (tiled)
loadFlatTiledImage (fileName, hdr, img);
else
loadFlatScanLineImage (fileName, hdr, img);
}
void
loadFlatImage
(const string &fileName,
FlatImage &img)
{
Header hdr;
loadFlatImage (fileName, hdr, img);
}
void
saveFlatScanLineImage
(const string &fileName,
const Header &hdr,
const FlatImage &img,
DataWindowSource dws)
{
Header newHdr;
for (Header::ConstIterator i = hdr.begin(); i != hdr.end(); ++i)
{
if (strcmp (i.name(), "dataWindow") &&
strcmp (i.name(), "tiles") &&
strcmp (i.name(), "channels"))
{
newHdr.insert (i.name(), i.attribute());
}
}
newHdr.dataWindow() = dataWindowForFile (hdr, img, dws);
const FlatImageLevel &level = img.level();
FrameBuffer fb;
for (FlatImageLevel::ConstIterator i = level.begin(); i != level.end(); ++i)
{
newHdr.channels().insert (i.name(), i.channel().channel());
fb.insert (i.name(), i.channel().slice());
}
OutputFile out (fileName.c_str(), newHdr);
out.setFrameBuffer (fb);
out.writePixels (newHdr.dataWindow().max.y - newHdr.dataWindow().min.y + 1);
}
void
saveFlatScanLineImage
(const string &fileName,
const FlatImage &img)
{
Header hdr;
hdr.displayWindow() = img.dataWindow();
saveFlatScanLineImage (fileName, hdr, img);
}
void
loadFlatScanLineImage
(const string &fileName,
Header &hdr,
FlatImage &img)
{
InputFile in (fileName.c_str());
const ChannelList &cl = in.header().channels();
img.clearChannels();
for (ChannelList::ConstIterator i = cl.begin(); i != cl.end(); ++i)
img.insertChannel (i.name(), i.channel());
img.resize (in.header().dataWindow(), ONE_LEVEL, ROUND_DOWN);
FlatImageLevel &level = img.level();
FrameBuffer fb;
for (FlatImageLevel::ConstIterator i = level.begin(); i != level.end(); ++i)
fb.insert (i.name(), i.channel().slice());
in.setFrameBuffer (fb);
in.readPixels (level.dataWindow().min.y, level.dataWindow().max.y);
for (Header::ConstIterator i = in.header().begin();
i != in.header().end();
++i)
{
if (strcmp (i.name(), "tiles"))
hdr.insert (i.name(), i.attribute());
}
}
void
loadFlatScanLineImage
(const string &fileName,
FlatImage &img)
{
Header hdr;
loadFlatScanLineImage (fileName, hdr, img);
}
namespace {
void
saveLevel (TiledOutputFile &out, const FlatImage &img, int x, int y)
{
const FlatImageLevel &level = img.level (x, y);
FrameBuffer fb;
for (FlatImageLevel::ConstIterator i = level.begin(); i != level.end(); ++i)
fb.insert (i.name(), i.channel().slice());
out.setFrameBuffer (fb);
out.writeTiles (0, out.numXTiles (x) - 1, 0, out.numYTiles (y) - 1, x, y);
}
} // namespace
void
saveFlatTiledImage
(const string &fileName,
const Header &hdr,
const FlatImage &img,
DataWindowSource dws)
{
Header newHdr;
for (Header::ConstIterator i = hdr.begin(); i != hdr.end(); ++i)
{
if (strcmp (i.name(), "dataWindow") &&
strcmp (i.name(), "tiles") &&
strcmp (i.name(), "channels"))
{
newHdr.insert (i.name(), i.attribute());
}
}
if (hdr.hasTileDescription())
{
newHdr.setTileDescription
(TileDescription (hdr.tileDescription().xSize,
hdr.tileDescription().ySize,
img.levelMode(),
img.levelRoundingMode()));
}
else
{
newHdr.setTileDescription
(TileDescription (64, // xSize
64, // ySize
img.levelMode(),
img.levelRoundingMode()));
}
newHdr.dataWindow() = dataWindowForFile (hdr, img, dws);
const FlatImageLevel &level = img.level (0, 0);
for (FlatImageLevel::ConstIterator i = level.begin(); i != level.end(); ++i)
newHdr.channels().insert (i.name(), i.channel().channel());
TiledOutputFile out (fileName.c_str(), newHdr);
switch (img.levelMode())
{
case ONE_LEVEL:
saveLevel (out, img, 0, 0);
break;
case MIPMAP_LEVELS:
for (int x = 0; x < out.numLevels(); ++x)
saveLevel (out, img, x, x);
break;
case RIPMAP_LEVELS:
for (int y = 0; y < out.numYLevels(); ++y)
for (int x = 0; x < out.numXLevels(); ++x)
saveLevel (out, img, x, y);
break;
default:
assert (false);
}
}
void
saveFlatTiledImage
(const string &fileName,
const FlatImage &img)
{
Header hdr;
hdr.displayWindow() = img.dataWindow();
saveFlatTiledImage (fileName, hdr, img);
}
namespace {
void
loadLevel (TiledInputFile &in, FlatImage &img, int x, int y)
{
FlatImageLevel &level = img.level (x, y);
FrameBuffer fb;
for (FlatImageLevel::ConstIterator i = level.begin(); i != level.end(); ++i)
fb.insert (i.name(), i.channel().slice());
in.setFrameBuffer (fb);
in.readTiles (0, in.numXTiles (x) - 1, 0, in.numYTiles (y) - 1, x, y);
}
} // namespace
void
loadFlatTiledImage
(const string &fileName,
Header &hdr,
FlatImage &img)
{
TiledInputFile in (fileName.c_str());
const ChannelList &cl = in.header().channels();
img.clearChannels();
for (ChannelList::ConstIterator i = cl.begin(); i != cl.end(); ++i)
img.insertChannel (i.name(), i.channel());
img.resize (in.header().dataWindow(),
in.header().tileDescription().mode,
in.header().tileDescription().roundingMode);
switch (img.levelMode())
{
case ONE_LEVEL:
loadLevel (in, img, 0, 0);
break;
case MIPMAP_LEVELS:
for (int x = 0; x < img.numLevels(); ++x)
loadLevel (in, img, x, x);
break;
case RIPMAP_LEVELS:
for (int y = 0; y < img.numYLevels(); ++y)
for (int x = 0; x < img.numXLevels(); ++x)
loadLevel (in, img, x, y);
break;
default:
assert (false);
}
for (Header::ConstIterator i = in.header().begin();
i != in.header().end();
++i)
{
hdr.insert (i.name(), i.attribute());
}
}
void
loadFlatTiledImage
(const string &fileName,
FlatImage &img)
{
Header hdr;
loadFlatTiledImage (fileName, hdr, img);
}
OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_EXIT
| 24.782927 | 80 | 0.586655 | Lord-Kamina |
411194daf2146fd369a4aed89fbb7d3044a055d6 | 3,281 | cpp | C++ | src-plugins/undoRedoRegistration/undoRedoRegistration.cpp | ocommowi/medInria-public | 9074e40c886881666e7a52c53309d8d28e35c0e6 | [
"BSD-4-Clause"
] | null | null | null | src-plugins/undoRedoRegistration/undoRedoRegistration.cpp | ocommowi/medInria-public | 9074e40c886881666e7a52c53309d8d28e35c0e6 | [
"BSD-4-Clause"
] | null | null | null | src-plugins/undoRedoRegistration/undoRedoRegistration.cpp | ocommowi/medInria-public | 9074e40c886881666e7a52c53309d8d28e35c0e6 | [
"BSD-4-Clause"
] | null | null | null | // /////////////////////////////////////////////////////////////////
// Generated by medPluginGenerator
// /////////////////////////////////////////////////////////////////
#include "undoRedoRegistration.h"
#include <dtkCore/dtkAbstractData.h>
#include <dtkCore/dtkAbstractDataFactory.h>
#include <dtkCore/dtkAbstractProcessFactory.h>
#include <registrationFactory/registrationFactory.h>
#include "itkImage.h"
// /////////////////////////////////////////////////////////////////
// undoRedoRegistration
// /////////////////////////////////////////////////////////////////
undoRedoRegistration::undoRedoRegistration(void) : itkProcessRegistration(){}
undoRedoRegistration::~undoRedoRegistration(void){}
bool undoRedoRegistration::registered(void)
{
return dtkAbstractProcessFactory::instance()->registerProcessType("undoRedoRegistration",
createUndoRedoRegistration);
}
QString undoRedoRegistration::description(void) const
{
return "undoRedoRegistration";
}
bool undoRedoRegistration::writeTransform(const QString& file){return false;}
itk::Transform<double,3,3>::Pointer undoRedoRegistration::getTransform(){return NULL;}
QStringList * undoRedoRegistration::getTitleAndParameters(){return NULL;}
void undoRedoRegistration::undo(){
itk::ImageRegistrationFactory<RegImageType>::Pointer m_factory = registrationFactory::instance()->getItkRegistrationFactory();
m_factory->Undo();
generateOutput();
}
void undoRedoRegistration::redo(){
itk::ImageRegistrationFactory<RegImageType>::Pointer m_factory = registrationFactory::instance()->getItkRegistrationFactory();
m_factory->Redo();
generateOutput();
}
void undoRedoRegistration::setInput(dtkAbstractData *data, int channel){
itkProcessRegistration::setInput(data,channel);
typedef itk::Image< float, 3 > RegImageType;
itk::ImageRegistrationFactory<RegImageType>::Pointer m_factory = registrationFactory::instance()->getItkRegistrationFactory();
if (channel==0)
m_factory->SetFixedImage((RegImageType*)this->fixedImage().GetPointer());
else if (channel==1)
m_factory->SetMovingImage((RegImageType*)this->movingImages()[0].GetPointer());
registrationFactory::instance()->reset();
}
void undoRedoRegistration::generateOutput(bool algorithm,dtkAbstractProcess * process){
typedef itk::Image< float, 3 > RegImageType;
itk::ImageRegistrationFactory<RegImageType>::Pointer m_factory = registrationFactory::instance()->getItkRegistrationFactory();
if (m_factory->GetFixedImage()!=NULL && m_factory->GetMovingImage()!=NULL){
m_factory->Update();
itk::ImageBase<3>::Pointer result = m_factory->GetOutput();
result->DisconnectPipeline();
if (algorithm && process)
{
if (process->output())
process->output()->setData(result);
}
else
if ((!algorithm) && (this->output()))
this->output()->setData(result);
}
}
// /////////////////////////////////////////////////////////////////
// Type instanciation
// /////////////////////////////////////////////////////////////////
dtkAbstractProcess *createUndoRedoRegistration(void)
{
return new undoRedoRegistration;
}
| 38.6 | 130 | 0.629077 | ocommowi |
4117908e59bd2f5b87794ddf0e858896f13a9532 | 335 | hpp | C++ | common/Stopwatch.hpp | CltKitakami/MyLib | d2dc4fb06ea5c3379a1818b49b0ecf13f8cd2b36 | [
"MIT"
] | null | null | null | common/Stopwatch.hpp | CltKitakami/MyLib | d2dc4fb06ea5c3379a1818b49b0ecf13f8cd2b36 | [
"MIT"
] | null | null | null | common/Stopwatch.hpp | CltKitakami/MyLib | d2dc4fb06ea5c3379a1818b49b0ecf13f8cd2b36 | [
"MIT"
] | null | null | null | #ifndef _STOPWATCH_HPP_
#define _STOPWATCH_HPP_
#include <cstdint>
#ifndef _MSC_VER
#include <sys/time.h>
#else
#include <windows.h>
#endif
class Stopwatch
{
public:
void start();
void stop();
uint32_t getMillis();
uint32_t getMicros();
private:
struct timeval begin, end;
struct timeval getElapsedTime();
};
#endif
| 11.964286 | 36 | 0.716418 | CltKitakami |
4118f9e840af92b4b8c3503526ce307eb9bcd371 | 9,940 | cpp | C++ | carto/CartoImageProc.cpp | mpthomas/Draw-Bot | 83bb7d755f805ae7f1a7b2fa9053c0882bc20b35 | [
"Apache-2.0"
] | null | null | null | carto/CartoImageProc.cpp | mpthomas/Draw-Bot | 83bb7d755f805ae7f1a7b2fa9053c0882bc20b35 | [
"Apache-2.0"
] | null | null | null | carto/CartoImageProc.cpp | mpthomas/Draw-Bot | 83bb7d755f805ae7f1a7b2fa9053c0882bc20b35 | [
"Apache-2.0"
] | null | null | null |
#include "CartoImageProc.hpp"
#include <iostream>
#include <sys/stat.h>
#include "PerlinNoise.hpp"
#include "CartoPath.hpp"
#include "CartoNode.hpp"
#include "CartoSimulator.hpp"
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
#include <cmath>
namespace Carto {
using namespace cv;
using namespace std;
CartoImageProc::CartoImageProc() {
this->image_name.assign("CartoImageProc");
}
CartoImageProc::CartoImageProc(std::string filename, int id) {
struct stat buffer;
if(stat(filename.c_str(), &buffer) == 0) {
this->image_name.assign(filename);
this->mat = imread(filename,1);
}else{
cout << "File not found: " << filename << endl;
exit(1);
}
this->id=id;
}
CartoImageProc::~CartoImageProc() {}
void CartoImageProc::setMat(Mat mat){
this->mat=mat.clone();
}
void CartoImageProc::filterGrayscale(cv::Mat *inmat, int start, int end){
TickMeter tm;
tm.start();
Mat tmp = Mat::zeros(inmat->rows, inmat->cols, CV_8UC3);
tmp=Scalar::all(255);
for(int x=0; x<inmat->cols; x++){
for(int y=0; y<inmat->rows; y++) {
uchar val=inmat->at<uchar>(Point(x,y));
if(val >= (uchar)start && val <= (uchar)end) {
inmat->at<uchar>(Point(x,y))=val;
}else{
inmat->at<uchar>(Point(x,y))=255;
}
}
}
tm.stop();
std::cout << "filterGrayscale: " << tm.getTimeSec() << std::endl;
}
void CartoImageProc::filterPerlin(cv::Mat *inmat, double scale){
TickMeter tm;
tm.start();
Mat perlin = CreatePerlinNoiseImage(Size(inmat->cols,inmat->rows),scale);
uchar inmat_val, perlin_val;
for(int x=0; x<inmat->cols; x++){
for(int y=0; y<inmat->rows; y++) {
inmat_val=inmat->at<uchar>(Point(x,y));
perlin_val=perlin.at<uchar>(Point(x,y));
if(inmat_val < 255 && perlin_val < 125) {
inmat->at<uchar>(Point(x,y))=255;
}else if (inmat_val < 255){
inmat->at<uchar>(Point(x,y))=0;
}
}
}
tm.stop();
std::cout << "filterPerlin: " << tm.getTimeSec() << std::endl;
}
void CartoImageProc::autoFilterPerlin(cv::Mat *inmat, double scale) {
int max_x = inmat->cols;
int max_y = inmat->rows;
int block_x_size=100, block_y_size=100;
Mat tmp_mat = inmat->clone();
vector<Mat> channels;
double mean, s;
uchar inmat_val, perlin_val;
for(int start_x=0; start_x< max_x; start_x+=block_x_size) {
for(int start_y=0; start_y < max_y; start_y+=block_y_size){
if(start_x+block_x_size > max_x) {
start_x = max_x - (start_x - block_x_size);
block_x_size = max_x - start_x;
}
if(start_y+block_y_size > max_y) {
start_y = max_x - (start_y - block_y_size);
block_y_size = max_y - start_y;
}
this->createMask(inmat, &tmp_mat, start_x, block_x_size, start_y, block_y_size);
mean = cv::mean(tmp_mat)[0]/1000*-1; // Average of first and only channel
s = .255 - mean + scale; // create a perlin scale filter relative to the mean. Offset by scale arg
Mat perlin = CreatePerlinNoiseImage(Size(tmp_mat.cols, tmp_mat.rows), s);
std::cout << "Mean: " << mean << " Scale: " << s << std::endl;
for(int x = 0; x < perlin.cols; x++) {
for(int y = 0; y < perlin.rows; y++) {
inmat_val=inmat->at<uchar>(Point(x + start_x,y + start_y));
perlin_val=perlin.at<uchar>(Point(x,y));
if(inmat_val < 255 && perlin_val < 125) {
inmat->at<uchar>(Point(x + start_x,y + start_y))=255;
}else if (inmat_val < 255){
inmat->at<uchar>(Point(x + start_x,y + start_y))=0;
}
}
}
}
}
}
void CartoImageProc::toGrayscale() {
cvtColor(this->mat,this->mat,CV_BGR2GRAY);
}
void CartoImageProc::show() {
TickMeter tm;
tm.start();
string window_name=this->image_name;
window_name.append(std::to_string(this->window_ctr));
this->window_ctr++;
namedWindow(window_name,CV_WINDOW_AUTOSIZE);
imshow(window_name,this->mat);
tm.stop();
std::cout << "show: " << tm.getTimeSec() << std::endl;
}
void CartoImageProc::show(Mat mat, std::string name) {
TickMeter tm;
tm.start();
namedWindow(name,CV_GUI_EXPANDED | WINDOW_NORMAL);
imshow(name,mat);
tm.stop();
std::cout << "show: " << tm.getTimeSec() << std::endl;
}
void CartoImageProc::createMask(Mat *inmat, Mat *mask, int start_x, int len_x, int start_y, int len_y) {
TickMeter tm;
tm.start();
*mask=Scalar::all(0);
Rect roi = Rect(start_x, start_y, len_x, len_y);
Mat crop(*inmat, roi);
crop.copyTo(*mask);
tm.stop();
std::cout << "createMask: " << tm.getTimeSec() << std::endl;
}
void CartoImageProc::buildTSPath(Mat *inmat) {
}
void CartoImageProc::getPath(cv::Mat *inmat, std::vector<Carto::CartoNode> *nodes, cv::Point start_point) {
//int target_x=1634, target_y=729;
int target_x=1736, target_y=2052;
Mat drawingMat = imread("/Users/matt/xcode/track_bmw.jpeg");
CartoPath *path = new CartoPath();
if(drawingMat.empty()) {
std::cout << "Unable to find blank drawing mat";
return;
}
cvtColor(drawingMat,drawingMat,COLOR_BGR2GRAY);
drawingMat=Scalar::all(255);
if(inmat->rows <= drawingMat.rows and inmat->cols <= drawingMat.cols) {
inmat->copyTo(drawingMat(Rect(target_x, target_y,inmat->cols,inmat->rows)));
}else{
std::cout << "Mismatch for source image and drawing mat\n";
return;
}
path->detected_edges = drawingMat.clone();
//*inmat=drawingMat.clone();
//path->buildANNPath(nodes);
path->buildANNPath(nodes,Point(1736,2052));
return;
}
void CartoImageProc::processPath(cv::Mat *inmat, std::vector<Carto::CartoNode> *nodes) {
Mat drawingMat = imread("/Users/matt/xcode/track_bmw.jpeg");
CartoPath *path = new CartoPath();
//int target_x=1634, target_y=729;
int target_x=1736, target_y=2052;
if(drawingMat.empty()) {
std::cout << "Unable to find blank drawing mat";
return;
}
cvtColor(drawingMat,drawingMat,COLOR_BGR2GRAY);
drawingMat=Scalar::all(255);
if(inmat->rows <= drawingMat.rows and inmat->cols <= drawingMat.cols) {
inmat->copyTo(drawingMat(Rect(target_x, target_y,inmat->cols,inmat->rows)));
}else{
std::cout << "Mismatch for source image and drawing mat\n";
return;
}
path->detected_edges = drawingMat.clone();
this->sim=new CartoSimulator(&path->detected_edges);
/* Reset it. No longer need old image */
drawingMat=Scalar::all(255);
this->line_counter=0;
/* Finally Render it */
std::cout << "Start Point is: " << Point(this->sim->prev_point) << std::endl;
std::cout << "First Node is: " << Point(nodes->at(0).point) << std::endl;
this->renderPath(*nodes, &drawingMat, this->sim->prev_point);
/* Reset our inmat so it can be displayed by caller */
*inmat=drawingMat;
this->sim->arduino->close();
}
void CartoImageProc::renderPath(std::vector<CartoNode> annNode, Mat *inmat, Point start_point){
if(annNode.size() == 0) {
return;
}
for(int i=0;i<annNode.size();i++) {
this->sim->MoveToPoint(annNode[i].point,1);
//Point simp=Point(this->sim->prev_point.x/5, this->sim->prev_point.y/5);
Point simp=this->sim->prev_point;
if(this->sim->draw_line) {
line(*inmat,start_point,simp,Scalar(0,0,0),2,8);
//if(this->sim->line1->color[0] < 100) {
// circle(*inmat, simp, 2, Scalar(200,200,200),1);
//}
//std::cout << this->sim->prev_point.x << " " << this->sim->prev_point.y;
//std::cout << " Len1: " << this->sim->line1->length << " Len2: " << this->sim->line2->length << std::endl;
}
if(annNode[i].neighbors.size() > 0) {
//this->renderPath(annNode[i].neighbors,inmat,annNode[i].point);
this->renderPath(annNode[i].neighbors,inmat,simp);
}
//start_point=annNode[i].point;
start_point=simp;
}
}
void CartoImageProc::reloadImage(std::string filename) {
struct stat buffer;
if(stat(filename.c_str(), &buffer) == 0) {
this->mat = imread(filename,1);
}else{
cout << "CartoImageProc::reloadImage(): File not found: " << filename << endl;
}
}
}
| 34.634146 | 123 | 0.512173 | mpthomas |
411e3928579a66b19248021cbaad0d936655f227 | 2,774 | cpp | C++ | QuoteGeneration/qcnl/win/os_version.cpp | dpuzikox/SGXDataCenterAttestationPrimitives | 88c8bb619db0945623256138a980f950139e6013 | [
"BSD-3-Clause"
] | 156 | 2018-09-06T07:19:23.000Z | 2022-03-30T19:01:40.000Z | QuoteGeneration/qcnl/win/os_version.cpp | dpuzikox/SGXDataCenterAttestationPrimitives | 88c8bb619db0945623256138a980f950139e6013 | [
"BSD-3-Clause"
] | 136 | 2018-10-02T00:58:26.000Z | 2022-03-21T08:45:25.000Z | QuoteGeneration/qcnl/win/os_version.cpp | dpuzikox/SGXDataCenterAttestationPrimitives | 88c8bb619db0945623256138a980f950139e6013 | [
"BSD-3-Clause"
] | 109 | 2018-10-01T19:09:58.000Z | 2022-03-29T13:33:51.000Z | /*
* Copyright (C) 2011-2021 Intel Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* File: os_version.cpp
*
* Description: Detect Windows OS version
*
*/
#include <Windows.h>
// Get Windows Version
typedef LONG NTSTATUS, *PNTSTATUS;
typedef NTSTATUS(WINAPI* FpRtlGetVersion)(PRTL_OSVERSIONINFOW);
bool isWin81OrLater() {
HMODULE hMod = ::GetModuleHandleW(L"ntdll.dll");
if (hMod) {
FpRtlGetVersion rtlGetVersion = (FpRtlGetVersion)::GetProcAddress(hMod, "RtlGetVersion");
if (rtlGetVersion != nullptr) {
RTL_OSVERSIONINFOW versionInfo = { 0 };
versionInfo.dwOSVersionInfoSize = sizeof(versionInfo);
if (0 == rtlGetVersion(&versionInfo)) {
// For Windows 10, MajorVersion is 10
// For Windows 8.1, MajorVersion=6 and MinorVersion=3
// For Windows 8, MajorVersion=6 and MinorVersion=2
// For Windows 7, MajorVersion=6 and MinorVersion=1
if (versionInfo.dwMajorVersion < 6 ||
(versionInfo.dwMajorVersion == 6 && versionInfo.dwMinorVersion <= 2))
return false;
}
}
}
// default to true if we failed to get the info
return true;
}
| 43.34375 | 97 | 0.693944 | dpuzikox |
411e477533f25450adf67fe60d3afe2af5c413b7 | 1,313 | hpp | C++ | include/codegen/include/Microsoft/Win32/Win32Native.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/Microsoft/Win32/Win32Native.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/Microsoft/Win32/Win32Native.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:09:38 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.Object
#include "System/Object.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Microsoft::Win32
namespace Microsoft::Win32 {
}
// Completed forward declares
// Type namespace: Microsoft.Win32
namespace Microsoft::Win32 {
// Autogenerated type: Microsoft.Win32.Win32Native
class Win32Native : public ::Il2CppObject {
public:
// Nested type: Microsoft::Win32::Win32Native::WIN32_FIND_DATA
class WIN32_FIND_DATA;
// static public System.String GetMessage(System.Int32 hr)
// Offset: 0x1098620
static ::Il2CppString* GetMessage(int hr);
// static public System.Int32 MakeHRFromErrorCode(System.Int32 errorCode)
// Offset: 0x109869C
static int MakeHRFromErrorCode(int errorCode);
// static System.UInt32 GetCurrentProcessId()
// Offset: 0x10986A8
static uint GetCurrentProcessId();
}; // Microsoft.Win32.Win32Native
}
DEFINE_IL2CPP_ARG_TYPE(Microsoft::Win32::Win32Native*, "Microsoft.Win32", "Win32Native");
#pragma pack(pop)
| 35.486486 | 89 | 0.70297 | Futuremappermydud |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.